server/zone_runtime.go (7722B)
1 package main 2 3 import ( 4 "errors" 5 "log" 6 "net" 7 "time" 8 ) 9 10 // A zone receives commands and advances its own state on one goroutine. The 11 // caller transfers the state at construction and must subsequently use commands. 12 type zoneRuntime struct { 13 lastOccupied time.Time 14 commands chan zoneRequest 15 quiescing chan struct{} 16 quiesced chan struct{} 17 stopping chan struct{} 18 done chan struct{} 19 players map[uint32]*character 20 presence map[uint32]playerPresence 21 presenceDirty []uint32 22 incomingAttacks map[uint32]uint32 23 checkpoint *simulationCheckpoint 24 checkpointDone <-chan error 25 stopError error 26 } 27 28 type zoneCommand interface { 29 execute(*server) error 30 } 31 32 type zoneRequest struct { 33 observe bool 34 command zoneCommand 35 done chan error 36 } 37 38 type zonePacket struct { 39 client *worldClient 40 body []byte 41 } 42 43 func (packet zonePacket) execute(state *server) error { 44 if state.clients[packet.client.id] != packet.client { 45 return nil 46 } 47 return state.handleWorldMessage(packet.client, packet.body) 48 } 49 50 func newZoneRuntime(state *server) *zoneRuntime { 51 zone := &zoneRuntime{commands: make(chan zoneRequest), quiescing: make(chan struct{}), quiesced: make(chan struct{}), stopping: make(chan struct{}), done: make(chan struct{})} 52 zone.players = make(map[uint32]*character) 53 zone.presence = make(map[uint32]playerPresence) 54 zone.incomingAttacks = make(map[uint32]uint32) 55 for id, player := range state.characters { 56 if !player.npc { 57 zone.players[id] = player 58 zone.presenceDirty = append(zone.presenceDirty, id) 59 } 60 } 61 for _, attacker := range state.fighting { 62 if attacker.fighting != 0 && attacker.fighting < 1000000 { 63 zone.incomingAttacks[attacker.fighting]++ 64 } 65 } 66 state.zone = zone 67 go zone.run(state) 68 return zone 69 } 70 71 func (zone *zoneRuntime) run(state *server) { 72 defer close(zone.done) 73 var movement, actions, crossings, checkpoints *time.Ticker 74 var movementTicks, actionTicks, crossingTicks, checkpointTicks <-chan time.Time 75 startTicks := func() { 76 movement = time.NewTicker(time.Second / 60) 77 actions = time.NewTicker(250 * time.Millisecond) 78 crossings = time.NewTicker(100 * time.Millisecond) 79 checkpoints = time.NewTicker(time.Second) 80 movementTicks, actionTicks, crossingTicks, checkpointTicks = movement.C, actions.C, crossings.C, checkpoints.C 81 zone.lastOccupied = time.Now() 82 } 83 pauseTicks := func() { 84 if movement != nil { 85 movement.Stop() 86 actions.Stop() 87 crossings.Stop() 88 checkpoints.Stop() 89 } 90 movementTicks, actionTicks, crossingTicks, checkpointTicks = nil, nil, nil, nil 91 state.movementFrames = nil 92 } 93 defer pauseTicks() 94 if !state.populationDormant() { 95 startTicks() 96 } 97 quiescing := zone.quiescing 98 stopTicks := func() { 99 pauseTicks() 100 quiescing = nil 101 close(zone.quiesced) 102 } 103 zone.publishPresence(state) 104 for { 105 select { 106 case request := <-zone.commands: 107 if !request.observe && state.populationDormant() { 108 if err := state.activatePopulation(); err != nil { 109 request.done <- err 110 continue 111 } 112 if quiescing != nil { 113 startTicks() 114 } 115 state.expirePets(time.Now(), nil) 116 state.advanceCorpseExpiry(time.Now()) 117 state.advanceNPCRespawns(time.Now()) 118 } 119 if packet, ok := request.command.(zonePacket); ok && state.world != nil && missionLifecyclePacket(packet.body) { 120 state.world.missionOperations <- missionOperation{zone: zone, packet: packet, done: request.done} 121 continue 122 } 123 occupied := len(state.clients) != 0 124 err := request.command.execute(state) 125 if occupied || len(state.clients) != 0 { 126 zone.lastOccupied = time.Now() 127 } 128 if state.populationDormant() { 129 pauseTicks() 130 } 131 if state.retiredMission != nil && quiescing != nil { 132 stopTicks() 133 } 134 zone.publishPresence(state) 135 request.done <- err 136 case now := <-movementTicks: 137 started := time.Now() 138 state.advancePlayerMovement(now) 139 reportSimulationTick(state.playfield, "player movement", now, started) 140 case now := <-actionTicks: 141 started := time.Now() 142 state.advanceActions(now) 143 reportSimulationTick(state.playfield, "NPC and actions", now, started) 144 zone.publishPresence(state) 145 case now := <-crossingTicks: 146 started := time.Now() 147 state.advanceZoneCrossings(now) 148 reportSimulationTick(state.playfield, "zone crossings", now, started) 149 zone.publishPresence(state) 150 case now := <-checkpointTicks: 151 started := time.Now() 152 asleep, err := zone.hibernate(state, now) 153 if err != nil { 154 log.Printf("Zone %d hibernation: %v", state.playfield, err) 155 } 156 if asleep { 157 pauseTicks() 158 } else if !state.populationDormant() { 159 zone.startCheckpoint(state, now) 160 } 161 reportSimulationTick(state.playfield, "checkpoint", now, started) 162 case err := <-zone.checkpointDone: 163 zone.finishCheckpoint(state, err) 164 case <-quiescing: 165 stopTicks() 166 case <-zone.stopping: 167 if zone.checkpointDone != nil { 168 zone.finishCheckpoint(state, <-zone.checkpointDone) 169 } 170 zone.stopError = zone.finalCheckpoint(state, time.Now()) 171 state.stopNavigation() 172 return 173 } 174 } 175 } 176 177 // External producers must stop before quiescing. Keep processing arrivals until 178 // every source has finished its last command or tick, then stop the owners. 179 func (zone *zoneRuntime) quiesce() { 180 close(zone.quiescing) 181 <-zone.quiesced 182 } 183 184 func (zone *zoneRuntime) call(command zoneCommand) error { 185 return zone.request(zoneRequest{command: command}) 186 } 187 188 // Observations and environment defaults do not wake a dormant population. 189 func (zone *zoneRuntime) observe(command zoneCommand) error { 190 return zone.request(zoneRequest{command: command, observe: true}) 191 } 192 193 func (zone *zoneRuntime) request(request zoneRequest) error { 194 request.done = make(chan error, 1) 195 select { 196 case zone.commands <- request: 197 return <-request.done 198 case <-zone.done: 199 return net.ErrClosed 200 } 201 } 202 203 func (zone *zoneRuntime) stop() error { 204 close(zone.stopping) 205 <-zone.done 206 return zone.stopError 207 } 208 209 // A connection stays with its source zone until the protocol redirects it. Its 210 // new connection joins the destination after ownership has been transferred. 211 type zoneJoin struct { 212 client *worldClient 213 player uint32 214 } 215 216 var errZoneOwnerChanged = errors.New("character changed zone before admission") 217 218 func (command zoneJoin) execute(state *server) error { 219 if state.world != nil && state.characters[command.player] == nil { 220 return errZoneOwnerChanged 221 } 222 return state.joinWorldClient(command.client, command.player) 223 } 224 225 type zoneLeave struct{ client *worldClient } 226 227 func (command zoneLeave) execute(state *server) error { 228 state.leaveWorldClient(command.client) 229 return nil 230 } 231 232 type zoneVicinity struct { 233 client *worldClient 234 kind uint32 235 message string 236 metadata []byte 237 runtime *chatRuntime 238 delivery *chatVicinity 239 } 240 241 func (command *zoneVicinity) execute(state *server) error { 242 var err error 243 command.runtime, command.delivery, err = state.prepareVicinity(command.client, command.kind, command.message, command.metadata) 244 return err 245 } 246 247 func (zone *zoneRuntime) joinWorldClient(client *worldClient, player uint32) error { 248 return zone.call(zoneJoin{client, player}) 249 } 250 251 func (zone *zoneRuntime) leaveWorldClient(client *worldClient) { 252 zone.call(zoneLeave{client}) 253 } 254 255 func (zone *zoneRuntime) handleWorldMessage(client *worldClient, body []byte) error { 256 return zone.call(zonePacket{client, body}) 257 } 258 259 func (zone *zoneRuntime) sendVicinity(client *worldClient, kind uint32, message string, metadata []byte) { 260 command := &zoneVicinity{client: client, kind: kind, message: message, metadata: metadata} 261 err := zone.call(command) 262 if err == nil && command.delivery != nil { 263 err = command.runtime.call(*command.delivery) 264 } 265 if err != nil { 266 log.Printf("Vicinity chat: %v", err) 267 } 268 }