server/state.go (9465B)
1 package main 2 3 import ( 4 "ao/server/gamedata" 5 "encoding/binary" 6 "fmt" 7 "log" 8 "net" 9 "sync" 10 "sync/atomic" 11 "time" 12 ) 13 14 type character struct { 15 id uint32 16 name string 17 title string 18 playfield uint32 19 position [3]float32 20 rotation [4]float32 21 appearance uint16 22 headMesh uint32 23 height uint16 24 monsterData uint32 25 level uint16 26 experience uint32 27 insuredExperience uint32 28 profession uint16 29 stats characterStats 30 inventory playerInventory 31 corpse *npcCorpse 32 combatProfile *gamedata.NPCCombatProfile 33 team *playerTeam 34 teamRevision uint64 35 missions []acceptedMission 36 health uint32 37 nano uint32 38 nanoReserved uint32 39 sitting bool 40 aggDef int32 41 fighting uint32 42 nextAttack time.Time 43 rechargeUntil time.Time 44 running bool 45 followTarget uint32 46 movement playerMovement 47 geometry *sceneGeometry 48 body playerCollisionBody 49 roomState playerRoomState 50 returnDoor *doorOrigin 51 npc bool 52 npcDefinitionID string 53 npcActiveUntil time.Time 54 motion *npcMotion 55 pet *ownedPet 56 pets map[uint32]bool 57 58 damageContributors map[damageContributor]uint32 59 leadingContributor damageContributor 60 threat map[uint32]int64 61 62 browserTokenHash string 63 resurrectionTerminal uint32 64 resurrectionShock uint32 65 implantChangesUntil time.Time 66 nanoRechargeUntil time.Time 67 skillLocks map[uint32]time.Time 68 activeNanos []activeNano 69 regenerationAt time.Time 70 regenerationSeconds uint32 71 savedProfile playerProfile 72 savedPosition playerPosition 73 savedVitals playerVitals 74 nextPositionSave time.Time 75 76 connectedAt time.Time 77 connectedSeconds int64 78 savedConnectedSeconds int64 79 } 80 81 type worldClient struct { 82 clientOutput 83 conn net.Conn 84 stream *browserStream 85 browserTokenHash string 86 ready bool 87 loading bool 88 id uint32 89 target bool 90 regenerationAt time.Time 91 regenerationSeconds uint32 92 npcs map[uint32]bool 93 players map[uint32]bool 94 dialogue *npcDialogue 95 equipment *equipmentMove 96 wornRemoval [46][]byte 97 nanoCast *nanoCast 98 reloadUntil time.Time 99 lootCorpse uint32 100 reclaimItems []uint32 101 backpacks map[uint32]backpackHandle 102 shop *shopTrade 103 trade *playerTrade 104 bank *bankSession 105 useSequence uint32 106 selectedTarget [2]uint32 107 enteredDoor doorOrigin 108 doorMessages []string 109 teamInvitation *teamInvitation 110 missionOffer *missionOffer 111 absorbedBonuses map[uint32]resourceBonuses 112 } 113 114 func (client *worldClient) send(packet []byte) error { 115 if client.target && binary.BigEndian.Uint16(packet[2:4]) == 10 { 116 packet = targetPacket(append([]byte(nil), packet...)) 117 } 118 return client.sendEncoded(packet) 119 } 120 121 func (client *worldClient) sendEncoded(packet []byte) error { 122 // Copy before stamping the recipient; a broadcast shares its encoded bytes. 123 client.mutex.Lock() 124 defer client.mutex.Unlock() 125 if client.writeWake == nil { 126 packet = append([]byte(nil), packet...) 127 binary.BigEndian.PutUint32(packet[12:16], client.id) 128 return writeClientPacket(client.conn, packet) 129 } 130 start := len(client.outgoing) 131 if err := client.enqueue_locked(client.conn, packet); err != nil { 132 return err 133 } 134 binary.BigEndian.PutUint32(client.outgoing[start+12:start+16], client.id) 135 return nil 136 } 137 138 // Startup constructs the world before admitting requests. Partitioning transfers 139 // mutable game state to zone goroutines and leaves only services on the root. 140 // Game operations run on their owning zone; cross-zone work exchanges commands 141 // and detached values through the directory and lifecycle coordinator. 142 type server struct { 143 populationLoaded bool 144 npcOwners map[uint32]uint32 145 worldServices 146 catalogOnce sync.Once 147 catalog itemCatalogIndex 148 browserStreamsOnce sync.Once 149 browserStreamService *browserStreamRegistry 150 151 tasks *serviceTasks 152 world *worldRuntime 153 zone *zoneRuntime 154 playfield uint32 155 retiredMission *acceptedMission 156 databaseQueries atomic.Uint64 157 profileWriter *profileWriter 158 savedNPCs map[uint32]savedNPC 159 activeNPCs map[uint32]bool 160 itemPlacements map[uint32]itemPlacement 161 nextCharacter uint32 162 nextNPC uint32 163 nextItem uint32 164 items map[uint32]itemRecord 165 worldItems map[uint32]worldItem 166 depletedResources map[uint32]bool 167 characters map[uint32]*character 168 mobileNPCs map[uint32][]*character 169 npcCells map[npcCell]map[uint32]*character 170 npcLocations map[uint32]npcCell 171 simulatedNPCs map[uint32]*character 172 navigation map[uint32]*zoneNavigator 173 navigationWorkers sync.WaitGroup 174 navigationStopped bool 175 npcRespawns []npcRespawn 176 petExpiry []*character 177 corpseExpiry []*character 178 missionExpiry []acceptedMission 179 clients map[uint32]*worldClient 180 movementFrames []playerMovementFrame 181 fighting map[uint32]*character 182 browserCreations map[string]*browserCreationCredentials 183 weather int 184 weatherUntil time.Time 185 nextWeather time.Time 186 gameSeconds float64 187 clockStarted time.Time 188 lastNPCUpdate time.Time 189 } 190 191 func newServer() *server { 192 state := newServerBase() 193 if err := state.loadInitialState(); err != nil { 194 panic(err) 195 } 196 return state 197 } 198 199 func (state *server) loadInitialState() error { 200 if err := state.preparePopulations(); err != nil { 201 return err 202 } 203 if err := state.loadUsers(); err != nil { 204 return err 205 } 206 return state.loadPets() 207 } 208 209 func newServerBase() *server { 210 server := &server{ 211 worldServices: worldServices{loginPort: 7500, worldPort: 7501, httpPort: 8080, baseURL: "/"}, 212 gameSeconds: 48600, clockStarted: time.Now(), 213 characters: make(map[uint32]*character), 214 mobileNPCs: make(map[uint32][]*character), 215 clients: make(map[uint32]*worldClient), 216 fighting: make(map[uint32]*character), 217 } 218 ground, err := readTerrain() 219 if err != nil { 220 panic(err) 221 } 222 server.terrain = ground 223 geometry, err := readSceneGeometry(resources) 224 if err != nil { 225 panic(err) 226 } 227 geometry.terrain = ground 228 server.geometry = geometry 229 links, err := readZoneLinks() 230 if err != nil { 231 panic(err) 232 } 233 server.zoneLinks = links 234 // Audited unlocked entrances on the early city/shop routes. 235 server.cityDoors = map[doorOrigin]bool{ 236 {705, 0xc01102c1}: false, {1183, 0xc000049f}: false, 237 {705, 0xc03902c1}: false, {1191, 0xc00004a7}: false, 238 {540, 0xc01d021c}: false, {1180, 0xc000049c}: false, 239 {800, 0xc0170320}: false, {1186, 0xc00004a2}: false, 240 } 241 for playfield, zone := range links["target"] { 242 for _, door := range zone.Doors { 243 if door.WhomPah { 244 server.cityDoors[doorOrigin{playfield, door.ID}] = false 245 } 246 } 247 } 248 server.worldResources, err = readWorldResources() 249 if err != nil { 250 panic(err) 251 } 252 if _, err := server.openDatabase(); err != nil { 253 panic(err) 254 } 255 return server 256 } 257 258 func (server *server) newCharacter() *character { 259 server.nextCharacter++ 260 player := newPlayerCharacter(server.nextCharacter) 261 player.geometry = server.geometry 262 server.characters[player.id] = player 263 return player 264 } 265 266 func newPlayerCharacter(id uint32) *character { 267 player := &character{ 268 id: id, name: fmt.Sprintf("Local Explorer %d", id), 269 playfield: 950, position: [3]float32{52.625, 14.75, 56.875 + float32((id-1)%4)*3}, 270 rotation: [4]float32{0, 0, 0, 1}, appearance: 0x315, level: 1, profession: 1, 271 } 272 player.stats = defaultCharacterStats(player.appearance >> 4 & 7) 273 player.health = player.maximumHealth() 274 return player 275 } 276 277 func (server *server) broadcast(playfield, exclude uint32, packet []byte) { 278 // The zone owns the recipients; sending only enqueues bytes for their writers. 279 key := binary.BigEndian.Uint32(packet[20:24]) 280 var native []byte 281 for id, client := range server.clients { 282 if id != exclude && client.ready && server.characters[id].playfield == playfield { 283 actor := binary.BigEndian.Uint32(packet[28:32]) 284 if binary.BigEndian.Uint32(packet[24:28]) == 50000 && !client.seesPlayer(actor) && !client.npcs[actor] { 285 continue 286 } 287 if key == 0x36510078 && binary.BigEndian.Uint32(packet[24:28]) == 50000 && client.players[actor] { 288 for _, removal := range server.forgetPlayer(client, actor) { 289 if err := client.send(removal); err != nil { 290 client.ready = false 291 client.disconnect(client.conn) 292 break 293 } 294 } 295 continue 296 } 297 // A new or removed actor no longer has its previous resource snapshot basis. 298 if (key == 0x271b3a6b || key == 0x36510078) && binary.BigEndian.Uint32(packet[24:28]) == 50000 { 299 delete(client.absorbedBonuses, binary.BigEndian.Uint32(packet[28:32])) 300 } 301 encoded := packet 302 if client.target { 303 if native == nil { 304 native = targetPacket(append([]byte(nil), packet...)) 305 } 306 encoded = native 307 } 308 if err := client.sendEncoded(encoded); err != nil { 309 log.Printf("World broadcast: %v", err) 310 client.ready = false 311 client.disconnect(client.conn) 312 } 313 } 314 } 315 }