aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit f0b2fe9ac1b10397798354a1cb9663a128edf911
parent 776bb5403e7ae7de4e0f1696b53080b0e87534f5
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 13:13:00 +0000

Add native 102-slot bank storage

Diffstat:
MTODO.md | 19++++++++++++++++---
Adocs/bank-storage.md | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/ranged-weapons.md | 17++++++++---------
Mserver/backpack_quality_test.go | 2+-
Mserver/backpacks.go | 79++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Aserver/bank.go | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/bank_storage_test.go | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/bank_test.go | 569+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/character_editor.go | 3++-
Mserver/combat.go | 1+
Mserver/control.go | 2+-
Mserver/control_inventory.go | 2++
Mserver/control_inventory_test.go | 5+++--
Mserver/control_items.go | 3++-
Aserver/gamedata/banks.yaml | 604++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/gamedata/banks_test.go | 19+++++++++++++++++++
Mserver/gamedata/load.go | 7++++++-
Mserver/insurance.go | 4++++
Mserver/inventory.go | 20+++++++++++++++++++-
Mserver/item_database.go | 28+++++++++++++++++++---------
Mserver/item_pages.go | 3+++
Mserver/item_store.go | 15++++++++++++---
Mserver/main.go | 3++-
Mserver/ranged.go | 55+++++++++++++++++++------------------------------------
Mserver/ranged_test.go | 14+++++++-------
Mserver/stacks.go | 18+++++++++++++-----
Mserver/state.go | 1+
Mserver/target_protocol.go | 2+-
Mserver/world.sql | 5++++-
Mserver/world_actions.go | 3+++
Atools/data/extract_banks.py | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
31 files changed, 1919 insertions(+), 100 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -851,9 +851,22 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah populations/levels, shops, loot tables, quests, missions and travel links have explicit coverage and missing-content work items; normal play obtains the resources needed to progress without admin-created items or encounters. -- [ ] Recover and implement native bank storage. Check: a bank terminal opens - the owner's storage, item/container transfers preserve identities and counts, - capacity and ownership are enforced, and contents survive reconnect/restart. +- [x] Recover native bank storage: 201 original terminals open the owner's + 102-slot bank; atomic item/filled-backpack transfers, capacity, ownership, + Unique scope, stack operations and reconnect/restart are covered. See + [bank storage](docs/bank-storage.md) for native evidence and reconstruction + policies. +- [ ] Extend bank runtime failure coverage: exercise CharacterAction 46 icon + restoration and rejected optimistic splits in the WASM UI, full ordinary + inventory, Unique/NoDrop combinations, deletion and merging, and bank layout + persistence. Verify item identity/count conservation after each case; packet + tests alone do not establish native UI recovery. +- [ ] Implement Briefcase of Holding remote bank access using its authored + profession, skill, title-level and combat conditions; research bank CASH/XP + semantics and historical filled-bag deletion policy. +- [ ] Recover the original global reload hotkey producer. CharacterAction 106 + closes a bank; the verified reload request is GenericCmd command 5 with the + ammunition and weapon identities. Keep bank-close ammunition regression tests. - [ ] Complete organization finances and permissions. Check: the shipped organization commands, including bank deposits/withdrawals and taxes, have researched rules, enforced ranks and atomic accounting; repeated or forbidden diff --git a/docs/bank-storage.md b/docs/bank-storage.md @@ -0,0 +1,149 @@ +# Bank storage + +The 14.9.1 bank uses 102 logical slots, numbered 0..101. The owner's bank is +available through the 201 Rubi-Ka Banking Service Terminals authored in the +original statel resources. Opening uses the normal GenericCmd Use request; +CharacterAction 106 closes the bank. + +## Original evidence + +The original DLLs, rather than a modern server emulator's storage limit, define +this contract. Original addresses below use image base 0x10000000. + +- KKR SHA-256 `a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`: + BankEntry constructor `0x10150b30` allocates 102 inventory positions. + `0x1007d350` reads BankIIR; `0x10151110` reads CASH, XP, PLAYERID and the ordinary + inventory list. `0x10150dc0` names those fields in the database descriptor. +- LLR SHA-256 `ebb09047f6ead192388f7ddfb4795da5013a60f7c2d1c3933ec02eef58a10132`: + Register/MapToKey `0x10023db0`/`0x10023f20` derives wire key `0x343c287f` from + `BankIIR_t`. KKR registration `0x1000d3e0` binds its constructor and reader. +- KKR activation `0x1007d3a0` installs proxy `(57005, ownerID)`, saves the player's + opening position, and opens the bank. Container inventory page is 105. + `N3Msg_UseItem`, `0x1002acd0`, closes that proxy and emits + `{106,0,0,0,0}`. It explicitly prohibits using page-105 items directly. +- KKR generic action validator `0x1004d350` permits world-terminal Use at a + three-dimensional distance <=5 metres. Locality check `0x100567b0` closes the + bank when the player moves more than 5 metres from their opening position. +- ContainerAddItem reader/writer `0x100426d0`/`0x10042710` encodes source identity, + destination identity and destination slot. Receiver `0x100614e0` dispatches + bank deposit `0x1005d700` and withdrawal `0x1005d890`. Both select first-free + slots, irrespective of the packet's destination-slot value. +- Move validator `0x10060510` and Unique lookup `0x10062a20` compare low template + IDs against carried/equipped items and carried Chest contents on withdrawal. + Bank contents are excluded; the bank may contain duplicate Unique items. + NoDrop has no bank-specific prohibition. Filled owned backpacks are permitted. +- CharacterAction reader/activation `0x1007d5c0`/`0x1007d640`, handler + `0x1006fa30` case 46 and correction `0x100624b0` establish rejection payload + `{46,0,0,sourcePage,sourceSlot}`. The source is the second identity. +- Split API `0x10022d50` and optimistic split `0x1005edb0` accept bank page 105, + retain the requested count in the source, and allocate the first free slot. + Delete API `0x10027670` and receiver `0x1005f270` also support page 105. +- DDR SHA-256 `3c937161de8f690351c3c08e158431417cee9ced77a41b677e7123b61a8c9883`: + bank window `0x10044c60` independently sets 102 slots and IconPositionSystem + map 3. Same-grid drops in `0x10045110` only change the local visual layout; + they send no server reorder request. UpdateContainer `0x100441e0` rebuilds + the grid through `0x10045320`, restoring optimistic dummy icons on rejection. + +The complete local evidence bundle is `local/bank-research/native/`: 284 KKR, +21 LLR and 145 DDR records, five exact reused records, retained snapshots, +`ledger.md` and `citations.json` validating 65 citations. Static client evidence +establishes packet and client behavior; it does not observe an original server. + +`tools/data/extract_banks.py` extracts template 116807 from every original +14.9.1 type-1000026 resource. It validates identities, record boundaries and the +exact per-instance script descriptor, then generates `server/gamedata/banks.yaml`. +The retained `local/bank-research/placements.json` includes original record bytes, +resource hashes and the resource index hash. Independent extraction and authored +OnUse effect 53092 are recorded in `local/bank-research/content/`. For example, +terminal `51005:0xc00502c1` is in Omni1 Entertainment, playfield 705, at +`[985,20.2001,580]`. Its template has no faction, level, skill or combat requirement. + +## Wire representation + +BankIIR has the owner SimpleChar envelope and these big-endian fields: + +| Field | Encoding | +| --- | --- | +| CASH, XP, PLAYERID | Three u32 values | +| Inventory count | `(entryCount + 1) * 1009`, u32 | +| Each entry | u32 slot, u16 flags, u16 count, u32 type, u32 instance, u32 low template, u32 high template, u32 quality, u32 auxiliary | + +Template entries use flags 3; owned live Chests use flags 2 and a ChestFullUpdate. +There is no trailing proxy identity. Bank slots never pass through the ordinary +inventory conversion from internal 64..93 to native 48..77. + +ContainerAddItem (`0x47537a24`) uses these identities: + +| Transfer | Source | Destination | +| --- | --- | --- | +| Ordinary inventory to bank | `(104,nativeSlot)` | `(57005,ownerID)` | +| Bag contents to bank | `(107,(handle<<16)&#124;slot)` | `(57005,ownerID)` | +| Bank to ordinary inventory | `(105,bankSlot)` | `(50000,ownerID)` | +| Bank to carried bag | `(105,bankSlot)` | `(51017,bagID)` | + +The native producer normally sends destination slot 111. The acknowledgement +uses the authoritative first-free logical slot. Action 46 translates ordinary +source slots only, preserving bank and packed bag source positions. + +## Server policy and persistence + +`item_locations.bank_player_id` is a distinct root placement. Its constraints +allow exactly one owner/location per instance and one item per bank slot. +Character-editor YAML exposes a top-level `bank` map with `slot_1` through +`slot_102`, alongside the equipment and inventory maps. The control panel shows +item names and instance links. Banked backpacks retain their child placements. + +Every accepted transfer, split, merge or deletion commits item identities, +counts and both placements atomically before acknowledging success. Bank items +are excluded from carried equipment modifiers and reclaim. Session gates reject +stale clients, invalid owners, dead/loading players, overlapping equipment work, +closed banks and movement beyond the opening locality. A banked bag's previously +open handle is closed; direct/stale access requires the bag to be carried again. +That security gate is a reconstruction policy; original client static evidence +only establishes the normal UI prohibition on using bank items. + +CASH and XP are sent as zero: their original server semantics remain unresolved. +Filled-bag deletion follows the current inventory policy of atomically deleting +children; historical server policy is not established. Stack representation is +limited to 65535 units without wrapping; the original server's permitted maximum +is not established. A rejected optimistic bank split replaces the bank snapshot; +the server retains the original opening anchor even though native BankIIR +activation refreshes its local anchor. The server locality remains authoritative. + +Briefcase of Holding (205736) invokes the same bank effect with separate authored +profession, skill, title-level and combat conditions. Remote bank opening is not +implemented by ordinary terminal support. + +## Verification + +Automated coverage exercises all 201 terminal identities, three-dimensional range +boundaries, ownership/session/life-state gates, all 102 storage slots, filled bags, +stack quantities and identities, full-bank/full-inventory rejection, repeated and +concurrent transfers, Unique low-template scope across quality endpoints, loaded +weapon ammunition, deletion, death/reclaim exclusion, failed writes and failed +COMMIT. A real world connection verifies that closing the bank cannot reload. +Bank, backpack, inventory, reload and item-store tests also run twice under the +Go race detector. + +The hardware WASM run used two Chromium clients on the GPU with OpenGL 4.5. +Native controls opened private banks, deposited/withdrew a filled bag and its +child, split ammunition into 1+99 units, and displayed `Bank is full` with 102 +entries. A heap read verified capacity 102 and occupied slot 101. After a real +server restart, every stored item/count/placement matched the prior snapshot; +the client bank matched all 101 remaining stored entries, and withdrawing the +bag restored its child. Moving away cleared the native bank proxy. Browser +errors were empty. Evidence is retained in `local/bank-smoke/verification.json`, +wire captures, native heap snapshots, screenshots and SQLite snapshots. + +Native UI recovery for action-46 rejections and invalid split snapshots, plus +additional merge/delete/layout checks, remains explicit follow-up work in TODO. +The full-bank rejection above was performed locally by the native client; it +does not prove receipt of the server rejection packet. Owned test players, +items, clients and browser contexts were removed after verification, with other +database rows checked unchanged. The single shared preview remains available. + +Regression logs are retained in `local/bank-research/`: the full Go suite passed +(server 412.712 seconds, game data 9.155 seconds), repeated race coverage passed +(193.522 seconds), and vet passed with the existing `-stdversion=false` workaround. +The final reload simplification and loaded-weapon transfer have additional focused +passing runs. The terminal extractor was rerun to verify reproducibility. diff --git a/docs/ranged-weapons.md b/docs/ranged-weapons.md @@ -36,15 +36,12 @@ The original 14.9.1 `kkr.dll` (SHA-256 `a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`) provides the reload contract: -- `N3Msg_UseItem`, address `0x1002acd0`: synthetic identity type `0xdead` - sends CharacterAction `0x5e477770` with `{106,0,0,0,0}`. - `N3Msg_UseItemOnItem`, `0x1002a8b0`: GenericCmd `0x52526858`, command 5, supplies the source ammunition and target weapon. Actual WASM controls send source `(104, inventorySlot)` and target `(101,6)` for the right hand. The persistent weapon identity is accepted as well. - GenericCmd receives its ordinary success/rejection ACK with the original - sequence. A repeated sequence cannot consume ammunition again. The global - CharacterAction request has no GenericCmd ACK. + sequence. A repeated sequence cannot consume ammunition again. - Reload `0x26515e61` carries seven DWORDs: source page, source slot, weapon type, weapon instance ID, remaining stack count, loaded count and remove-stack boolean. The source slot is translated from internal 64..93 to native 48..77; @@ -65,13 +62,15 @@ then `[container+4]`, and read signed DWORD index 26. Constructor `sub_360ABA20` in `client/game/kkr.dll/lifted-0051.c` establishes the subobject offset; getter `sub_36003000` in `lifted-0000.c` establishes the array access. +CharacterAction 106 closes the bank proxy `(57005, owner)`. It does not reload. +The original global reload hotkey producer remains unverified; only the native +ammo-on-weapon request above is implemented. + ## Server policy and durability -The original server's stack selection and transfer policy were not recovered. -This implementation chooses the lowest compatible ordinary inventory slot -for a global reload, and transfers as many available rounds as fit from that -one stack. Explicit use consumes only the named stack. Reloading a full weapon, -missing/wrong ammunition, a foreign item, an invalid session, or overlapping +The original server's transfer policy was not recovered. This implementation +transfers as many available rounds as fit from the named ammunition stack. +Reloading a full weapon, missing/wrong ammunition, a foreign item, an invalid session, or overlapping equipment/nano/reload work cannot transfer rounds. Loaded ammunition is an `items.ammo` scalar. Each shot commits its one-round diff --git a/server/backpack_quality_test.go b/server/backpack_quality_test.go @@ -36,7 +36,7 @@ func TestBackpackOfSurvivalInterpolatesEffectsAndNativeEndpoints(t *testing.T) { world.advanceEquipment(client.equipment.readyAt) restarted := newTestInventoryServer(t).characters[1] snapshot := targetPacket(fullCharacterPacket(restarted)) - chest := backpackPacket(1, player.playfield, player.inventory.Items[1]) + chest := backpackPacket(1, player.playfield, player.inventory.Items[1], 104) expected := [8]uint32{scenario.armor, scenario.armor, scenario.energy, scenario.armor, scenario.energy, scenario.cold, scenario.armor, scenario.cold} for index, amount := range expected { diff --git a/server/backpacks.go b/server/backpacks.go @@ -19,17 +19,13 @@ func (item ownedItem) isPortableContainer() bool { itemStat(definition, 30)&9 == 9 } -func backpackPacket(owner, playfield uint32, item ownedItem) []byte { +func backpackPacket(owner, playfield uint32, item ownedItem, page uint32) []byte { // ChestFullUpdate inherits SimpleItem 11 and Lockable 2, ending in Chest 3. var body []byte for _, value := range []uint32{11, 50000, owner, playfield, 0, 0} { body = binary.BigEndian.AppendUint32(body, value) } - page := byte(104) - if item.Slot < 64 { - page = 102 - } - body = append(body, page, byte(item.Slot)) + body = append(body, byte(page), byte(item.Slot)) body = binary.BigEndian.AppendUint32(body, 5*1009) low, high := item.templateIDs() for _, value := range []uint32{23, item.Template, 701, item.Quality, 702, low, 703, high, 0, 2, 0, 1009, 3} { @@ -139,13 +135,17 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error index++ } client.backpacks[index] = backpackHandle{bag.ID, true} - if err := client.send(backpackPacket(client.id, player.playfield, bag)); err != nil { + parentPage := uint32(104) + if bag.Slot < 64 { + parentPage = 102 + } + if err := client.send(backpackPacket(client.id, player.playfield, bag, parentPage)); err != nil { return err } return client.send(backpackInventoryPacket(client.id, bag.ID, index, player.inventory.Containers[bag.ID])) } -func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) error { +func (server *server) moveContainerItem_locked(client *worldClient, body []byte) error { if !client.target { return nil } @@ -154,7 +154,13 @@ func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) sourcePage, sourceSlot := binary.BigEndian.Uint32(body[16:20]), binary.BigEndian.Uint32(body[20:24]) sourceBag := uint32(0) items := inventory.Items - if sourcePage == 107 { + bank := sourcePage == 105 || binary.BigEndian.Uint32(body[24:28]) == 57005 + if bank && (!server.bankAvailable_locked(client) || client.equipment != nil) { + return client.send(characterActionPacket(client.id, [5]uint32{46, 0, 0, sourcePage, sourceSlot})) + } + if sourcePage == 105 { + items = inventory.Bank + } else if sourcePage == 107 { sourceBag = client.backpacks[sourceSlot>>16].id if sourceBag == 0 || !client.backpacks[sourceSlot>>16].open || !slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.ID == sourceBag && item.isPortableContainer() }) { return nil @@ -169,14 +175,26 @@ func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) return nil } item := items[index] + if bank && itemStat(item.templateDefinition(), 8) > 0 || + sourcePage == 105 && itemStat(item.templateDefinition(), 0)&0x08000000 != 0 && inventory.carriesUnique(item) { + return client.send(characterActionPacket(client.id, [5]uint32{46, 0, 0, sourcePage, binary.BigEndian.Uint32(body[20:24])})) + } // Validate the owner and placement before changing either side of the transfer. targetType, targetID, slot := binary.BigEndian.Uint32(body[24:28]), binary.BigEndian.Uint32(body[28:32]), binary.BigEndian.Uint32(body[32:36]) targetBag := uint32(0) targetItems := inventory.Items first, end := uint32(64), uint32(94) - if targetType == 51017 { + if targetType == 57005 { + if targetID != client.id || sourcePage == 105 { + return nil + } + targetItems, first, end, slot = inventory.Bank, 0, bankCapacity, 111 + } else if targetType == 51017 { if targetID == sourceBag || !slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.ID == targetID && item.isPortableContainer() }) { + if bank { + return client.send(characterActionPacket(client.id, [5]uint32{46, 0, 0, sourcePage, binary.BigEndian.Uint32(body[20:24])})) + } return nil } known := false @@ -184,6 +202,9 @@ func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) known = known || handle.id == targetID } if !known || item.Type == 51017 || itemStat(gamedata.ItemTemplates[item.Template], 0)&0x00200000 != 0 || itemStat(gamedata.ItemTemplates[item.Template], 8) > 0 { + if bank { + return client.send(characterActionPacket(client.id, [5]uint32{46, 0, 0, sourcePage, binary.BigEndian.Uint32(body[20:24])})) + } return nil } targetBag, targetItems, first, end = targetID, inventory.Containers[targetID], 0, 21 @@ -193,9 +214,13 @@ func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) } // The native Chest receiver always chooses its first free contents slot. slot = 111 - } else if targetType != 50000 || targetID != client.id || sourceBag == 0 { + } else if targetType != 50000 || targetID != client.id || sourceBag == 0 && sourcePage != 105 { return nil } + if sourcePage == 105 && targetType == 50000 { + // The native bank withdrawal receiver ignores the requested slot. + slot = 111 + } if slot == 111 { for slot = first; slot < end; slot++ { if !slices.ContainsFunc(targetItems, func(item ownedItem) bool { return item.Slot == slot }) { @@ -204,16 +229,21 @@ func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) } } if slot < first || slot >= end || slices.ContainsFunc(targetItems, func(item ownedItem) bool { return item.Slot == slot }) { + if bank { + return client.send(characterActionPacket(client.id, [5]uint32{46, 0, 0, sourcePage, binary.BigEndian.Uint32(body[20:24])})) + } return nil } - // One inventory file commits ownership, quantity and both container locations. + // Commit ownership, quantity and both container locations atomically. inventory.Containers = maps.Clone(inventory.Containers) if inventory.Containers == nil { inventory.Containers = make(map[uint32][]ownedItem) } remaining := slices.Delete(slices.Clone(items), index, index+1) - if sourceBag == 0 { + if sourcePage == 105 { + inventory.Bank = remaining + } else if sourceBag == 0 { inventory.Items = remaining } else if len(remaining) == 0 { delete(inventory.Containers, sourceBag) @@ -222,7 +252,9 @@ func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) } item.Slot = slot targetItems = append(slices.Clone(targetItems), item) - if targetBag == 0 { + if targetType == 57005 { + inventory.Bank = targetItems + } else if targetBag == 0 { inventory.Items = targetItems } else { inventory.Containers[targetBag] = targetItems @@ -235,7 +267,20 @@ func (server *server) moveBackpackItem_locked(client *worldClient, body []byte) } reply := append([]byte(nil), body[16:]...) binary.BigEndian.PutUint32(reply[16:20], slot) - return client.send(n3Packet(0x47537a24, 50000, client.id, reply)) + if err := client.send(n3Packet(0x47537a24, 50000, client.id, reply)); err != nil { + return err + } + if targetType == 57005 && item.isPortableContainer() { + for handle, bag := range client.backpacks { + if bag.id == item.ID && bag.open { + client.backpacks[handle] = backpackHandle{bag.id, false} + if err := client.send(backpackClosePacket(client.id, bag.id)); err != nil { + return err + } + } + } + } + return nil } func (server *server) handleBackpackAction_locked(client *worldClient, body []byte) error { @@ -248,7 +293,7 @@ func (server *server) handleBackpackAction_locked(client *worldClient, body []by action := binary.BigEndian.Uint32(body[16:20]) if client.equipment != nil { if action == 52 { - return server.syncStackPage_locked(client, handle.id) + return server.syncStackPage_locked(client, 107, handle.id) } return nil } @@ -256,7 +301,7 @@ func (server *server) handleBackpackAction_locked(client *worldClient, body []by index := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == position&65535 }) if index < 0 { if action == 52 { - return server.syncStackPage_locked(client, handle.id) + return server.syncStackPage_locked(client, 107, handle.id) } return nil } diff --git a/server/bank.go b/server/bank.go @@ -0,0 +1,182 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "maps" + "slices" + "time" +) + +// kkr.dll BankEntry constructor 0x10150b30 allocates 102 inventory positions. +const bankCapacity = 102 + +type bankSession struct { + playfield uint32 + position [3]float32 +} + +func (inventory playerInventory) carriesUnique(item ownedItem) bool { + low, _ := item.templateIDs() + for _, carried := range inventory.Items { + other, _ := carried.templateIDs() + if other == low { + return true + } + if carried.isPortableContainer() && slices.ContainsFunc(inventory.Containers[carried.ID], func(child ownedItem) bool { + other, _ := child.templateIDs() + return other == low + }) { + return true + } + } + return false +} + +func bankInventoryPacket(player *character) []byte { + // BankEntry serializes CASH, XP, PLAYERID, then its normal inventory list. + body := binary.BigEndian.AppendUint32(nil, 0) + body = binary.BigEndian.AppendUint32(body, 0) + body = binary.BigEndian.AppendUint32(body, player.id) + body = binary.BigEndian.AppendUint32(body, uint32(len(player.inventory.Bank)+1)*1009) + for _, item := range player.inventory.Bank { + flags := uint32(3) + if item.isPortableContainer() { + flags = 2 + } + low, high := item.templateIDs() + for _, value := range []uint32{item.Slot, flags<<16 | uint32(item.Count), item.Type, item.ID, low, high, item.Quality, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + } + return n3Packet(0x343c287f, 50000, player.id, body) +} + +func (server *server) bankAvailable_locked(client *worldClient) bool { + if client.bank == nil { + return false + } + player := server.characters[client.id] + position := predictedPosition_locked(player, client, time.Now()) + x, y, z := position[0]-client.bank.position[0], position[1]-client.bank.position[1], position[2]-client.bank.position[2] + if player.playfield != client.bank.playfield || x*x+y*y+z*z > 25 { + client.bank = nil + return false + } + return true +} + +func (server *server) handleBankUse(client *worldClient, body []byte) error { + if len(body) != 48 { + return fmt.Errorf("invalid bank use length") + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + defer server.mutex.Unlock() + player := server.characters[client.id] + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || + binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 3 || + binary.BigEndian.Uint32(body[28:32]) != 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 || + binary.BigEndian.Uint32(body[36:40]) != client.id || binary.BigEndian.Uint32(body[40:44]) != 51005 { + return nil + } + sequence := binary.BigEndian.Uint32(body[20:24]) + if sequence <= client.useSequence { + return nil + } + client.useSequence = sequence + terminal, exists := gamedata.BankTerminals[binary.BigEndian.Uint32(body[44:48])] + position := predictedPosition_locked(player, client, time.Now()) + x, y, z := position[0]-terminal.Position[0], position[1]-terminal.Position[1], position[2]-terminal.Position[2] + accepted := exists && player.playfield == terminal.Playfield && x*x+y*y+z*z <= 25 && client.equipment == nil + reply := append([]byte(nil), body[16:]...) + binary.BigEndian.PutUint32(reply, 2) + if accepted { + binary.BigEndian.PutUint32(reply, 1) + } + if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil || !accepted { + return err + } + if client.shop != nil { + if err := server.abortShop_locked(client); err != nil { + return err + } + } + client.bank = &bankSession{player.playfield, position} + for _, item := range player.inventory.Bank { + if item.isPortableContainer() { + if err := client.send(backpackPacket(client.id, player.playfield, item, 105)); err != nil { + return err + } + } + } + return client.send(bankInventoryPacket(player)) +} + +func (server *server) handleBankClose(client *worldClient, body []byte) error { + if len(body) != 36 { + return fmt.Errorf("invalid bank close length") + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + defer server.mutex.Unlock() + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || + binary.BigEndian.Uint32(body[16:20]) != 106 || binary.BigEndian.Uint64(body[20:28]) != 0 || binary.BigEndian.Uint64(body[28:36]) != 0 { + return nil + } + client.bank = nil + return nil +} + +func (server *server) handleBankAction_locked(client *worldClient, body []byte) error { + if !client.target { + return nil + } + if !server.bankAvailable_locked(client) { + client.bank = nil + return client.send(characterActionPacket(client.id, [5]uint32{106})) + } + player := server.characters[client.id] + action := binary.BigEndian.Uint32(body[16:20]) + slot := binary.BigEndian.Uint32(body[24:28]) + index := slices.IndexFunc(player.inventory.Bank, func(item ownedItem) bool { return item.Slot == slot }) + if client.equipment != nil || index < 0 { + if action == 52 { + return server.syncStackPage_locked(client, 105, 0) + } + return nil + } + if action == 52 || action == 53 { + return server.changeStack_locked(client, index, body) + } + item := player.inventory.Bank[index] + low, high := item.templateIDs() + if action != 112 || binary.BigEndian.Uint32(body[28:32]) != low || binary.BigEndian.Uint32(body[32:36]) != high { + return nil + } + + // Deleting a bag destroys its children in the same transaction as its root. + inventory := player.inventory + inventory.Bank = slices.Delete(slices.Clone(inventory.Bank), index, index+1) + if item.isPortableContainer() { + inventory.Containers = maps.Clone(inventory.Containers) + delete(inventory.Containers, item.ID) + if len(inventory.Containers) == 0 { + inventory.Containers = nil + } + } + if err := server.saveInventory_locked(player, inventory); err != nil { + return err + } + for handle, bag := range client.backpacks { + if bag.id == item.ID { + delete(client.backpacks, handle) + } + } + return client.send(n3Packet(0x5e477770, 50000, client.id, body[16:])) +} diff --git a/server/bank_storage_test.go b/server/bank_storage_test.go @@ -0,0 +1,129 @@ +package main + +import ( + "bytes" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strconv" + "strings" + "testing" +) + +func TestBankStoragePreservesFilledBackpack(t *testing.T) { + world := newControlInventoryWorld(t) + + response := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_102: 3}\n"}}) + restarted := newServer() + defer restarted.db.Close() + page, bag := httptest.NewRecorder(), httptest.NewRecorder() + restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) + restarted.httpHandler().ServeHTTP(bag, httptest.NewRequest("GET", "/control/items/3", nil)) + + if response.Code != http.StatusSeeOther { + t.Fatalf("bank placement: %d %s", response.Code, response.Body.String()) + } + if !reflect.DeepEqual(restarted.characters[1].inventory.Bank, []ownedItem{{ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 101, Count: 1}}) || + !reflect.DeepEqual(restarted.characters[1].inventory.Containers[3], []ownedItem{{ID: 4, Type: 51018, Template: 121567, Quality: 1, Count: 1}}) { + t.Fatal("banked backpack or its contents changed across restart") + } + if len(restarted.characters[1].inventory.Items) != 2 || len(restarted.items) != 4 || len(restarted.characters[1].inventory.allItems()) != 4 || + restarted.itemPlacements[3] != (itemPlacement{Bank: 1, Slot: 101}) || restarted.itemPlacements[4] != (itemPlacement{Backpack: 3, Slot: 0}) { + t.Fatal("bank storage lost ownership or duplicated an item") + } + if !strings.Contains(page.Body.String(), "<h2>Bank</h2>") || + !strings.Contains(page.Body.String(), "<tr><td>slot_102</td><td><a href='control/items/3'>Small Backpack (ID 3)</a></td></tr>") || + !strings.Contains(bag.Body.String(), "Bank, slot_102") { + t.Fatal("control panel omitted bank ownership or its final slot") + } +} + +func TestBankStorageRejectsInvalidOwnershipGraphs(t *testing.T) { + for _, document := range []string{ + "bank: {slot_1: 1}", + "bank: {slot_1: 4}", + "bank: {slot_1: 99}", + "bank: {slot_103: 1}", + "bank: {slot_0: 1}", + "bank: {slot_01: 1}", + "inventory: {slots: {inventory_slot_1: null}}\nbank: {slot_1: 1, slot_2: 1}", + } { + t.Run(document, func(t *testing.T) { + world := newControlInventoryWorld(t) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + response := postControlForm(world, "/control/users/1", url.Values{"data": {document}}) + after, err := readTestItemStore(world) + + if response.Code != http.StatusBadRequest || err != nil || !bytes.Equal(before, after) { + t.Fatalf("invalid bank changed storage: %d %s %v", response.Code, response.Body.String(), err) + } + }) + } +} + +func TestBankStorageRejectsAnotherPlayersInstance(t *testing.T) { + world := newControlInventoryWorld(t) + postControlForm(world, "/control/users", url.Values{"name": {"Other"}}) + placed := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_1: null}}\nbank: {slot_1: 1}\n"}}) + if placed.Code != http.StatusSeeOther { + t.Fatal(placed.Body.String()) + } + + response := postControlForm(world, "/control/users/2", url.Values{"data": {"bank: {slot_1: 1}\n"}}) + restarted := newServer() + defer restarted.db.Close() + + if response.Code != http.StatusBadRequest || len(restarted.characters[2].inventory.Bank) != 0 || + len(restarted.characters[1].inventory.Bank) != 1 || restarted.characters[1].inventory.Bank[0].ID != 1 || len(restarted.items) != 4 { + t.Fatal("an item banked by another player changed owner or was duplicated") + } +} + +func TestBankStorageFailurePreservesPlacement(t *testing.T) { + world := newControlInventoryWorld(t) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec(`CREATE TRIGGER reject_bank BEFORE INSERT ON item_locations + WHEN NEW.bank_player_id IS NOT NULL BEGIN SELECT RAISE(FAIL, 'bank write failed'); END`); err != nil { + t.Fatal(err) + } + + response := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_1: 3}\n"}}) + after, err := readTestItemStore(world) + + if response.Code != http.StatusInternalServerError || err != nil || !bytes.Equal(before, after) || + len(world.characters[1].inventory.Bank) != 0 || len(world.characters[1].inventory.Items) != 3 || len(world.characters[1].inventory.Containers[3]) != 1 { + t.Fatalf("failed bank write changed live or stored ownership: %d %v", response.Code, err) + } +} + +func TestBankStorageSupportsEveryNativeSlot(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) + var document strings.Builder + document.WriteString("bank:\n") + for id := 1; id <= 102; id++ { + response := postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) + if response.Code != http.StatusSeeOther { + t.Fatal(response.Body.String()) + } + document.WriteString(" slot_" + strconv.Itoa(id) + ": " + strconv.Itoa(id) + "\n") + } + + response := postControlForm(world, "/control/users/1", url.Values{"data": {document.String()}}) + restarted := newServer() + defer restarted.db.Close() + + if response.Code != http.StatusSeeOther || len(restarted.characters[1].inventory.Bank) != 102 || len(restarted.items) != 102 || + len(restarted.characters[1].inventory.Items) != 0 || restarted.characters[1].inventory.Bank[101].Slot != 101 || restarted.characters[1].inventory.Bank[101].ID != 102 { + t.Fatalf("full native bank did not persist: %d %s", response.Code, response.Body.String()) + } +} diff --git a/server/bank_test.go b/server/bank_test.go @@ -0,0 +1,569 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "reflect" + "slices" + "sync" + "testing" +) + +func bankUseRequest(sequence uint32) []byte { + request := insuranceUseRequest(sequence) + binary.BigEndian.PutUint32(request[64:68], 0xc00502c1) + return request +} + +func newBankWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, conn := newBackpackWorld(t) + t.Cleanup(func() { world.db.Close() }) + player := world.characters[1] + player.playfield, player.position = 705, [3]float32{985, 20.2001, 580} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleTerminalUse(world.clients[1], bankUseRequest(1)[20:]); err != nil { + t.Fatal(err) + } + conn.packets = nil + return world, conn +} + +func TestBankNativeOpeningUsesOwnerProxyAndAllOriginalTerminals(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + sequence := uint32(1) + + for id, terminal := range gamedata.BankTerminals { + player.playfield, player.position = terminal.Playfield, terminal.Position + request := bankUseRequest(sequence + 1) + sequence++ + binary.BigEndian.PutUint32(request[64:68], id) + if err := world.handleTerminalUse(client, request[20:]); err != nil { + t.Fatal(err) + } + } + + if len(conn.packets) != 402 || client.bank == nil { + t.Fatal("not every terminal opens the bank", len(conn.packets)) + } + for i := 0; i < len(conn.packets); i += 2 { + ack, bank := conn.packets[i], conn.packets[i+1] + if binary.BigEndian.Uint32(ack[29:33]) != 1 || binary.BigEndian.Uint32(bank[16:20]) != 0x343c287f || + !bytes.Equal(bank[29:45], []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 3, 241}) { + t.Fatalf("bank header: %x", bank) + } + } +} + +func TestBankOpeningRejectsInvalidUse(t *testing.T) { + for _, scenario := range []string{"far", "vertical", "wrong zone", "owner", "actor", "type", "object", "action", "reply", "mode", "sequence", "dead", "loading", "unready", "stale", "equipment", "old client"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + client.bank = nil + request := bankUseRequest(2)[20:] + switch scenario { + case "far": + player.position[0] += 5.01 + case "vertical": + player.position[1] += 5.01 + case "wrong zone": + player.playfield = 950 + case "owner": + binary.BigEndian.PutUint32(request[8:12], 2) + case "actor": + binary.BigEndian.PutUint32(request[36:40], 2) + case "type": + binary.BigEndian.PutUint32(request[40:44], 51017) + case "object": + binary.BigEndian.PutUint32(request[44:48], 999) + case "action": + binary.BigEndian.PutUint32(request[24:28], 5) + case "reply": + binary.BigEndian.PutUint32(request[16:20], 1) + case "mode": + binary.BigEndian.PutUint32(request[28:32], 0) + case "sequence": + client.useSequence = 2 + case "dead": + player.health = 0 + case "loading": + client.loading = true + case "unready": + client.ready = false + case "stale": + world.clients[1] = &worldClient{id: 1} + case "equipment": + client.equipment = &equipmentMove{} + case "old client": + client.target = false + } + + err := world.handleBankUse(client, request) + + if err != nil || client.bank != nil { + t.Fatal("invalid bank use opened storage", err) + } + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x343c287f || binary.BigEndian.Uint32(packet[29:33]) != 2 { + t.Fatalf("invalid use sent success: %x", packet) + } + } + }) + } +} + +func TestBankTransfersPreserveFilledBagsAndFirstFreeSlots(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 111)[20:]); err != nil { + t.Fatal(err) + } + conn.packets = nil + + for _, request := range [][]byte{ + backpackMoveRequest(107, 1<<16, 57005, 1, 101), + backpackMoveRequest(105, 0, 51017, 3, 111), + backpackMoveRequest(104, 66, 57005, 1, 101), + backpackMoveRequest(104, 64, 57005, 1, 101), + backpackMoveRequest(105, 0, 50000, 1, 93), + } { + if err := world.handleInventory(client, request[20:]); err != nil { + t.Fatal(err) + } + } + restarted := newTestInventoryServer(t).characters[1] + + expected := []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 1, Count: 3}} + if !reflect.DeepEqual(player.inventory.Bank, expected) || !reflect.DeepEqual(restarted.inventory.Bank, expected) || + !slices.Contains(restarted.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}) || + !reflect.DeepEqual(restarted.inventory.Containers, map[uint32][]ownedItem{3: {{ID: 5, Type: 51018, Template: 121567, Quality: 1, Count: 1}}}) || len(world.items) != 5 { + t.Fatalf("bank transfer lost ownership or contents: %+v", restarted.inventory) + } + if len(conn.packets) != 6 || client.backpacks[1].open || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 0 || + binary.BigEndian.Uint32(conn.packets[5][45:49]) != 48 { + t.Fatalf("native first-free or close response: %x", conn.packets) + } +} + +func TestBankTransfersRequireLiveNearbyOwnerSession(t *testing.T) { + for _, scenario := range []string{"closed", "too far", "vertical", "other zone", "foreign bank", "foreign owner", "equipment", "dead", "loading", "unready", "stale", "equipped source", "missing source", "bank reorder", "stale bag"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + request := backpackMoveRequest(104, 64, 57005, 1, 111)[20:] + switch scenario { + case "closed": + world.handleBankClose(client, characterActionPacket(1, [5]uint32{106})[20:]) + case "too far": + player.position[0] += 5.01 + case "vertical": + player.position[1] += 5.01 + case "other zone": + player.playfield = 950 + case "foreign bank": + binary.BigEndian.PutUint32(request[28:32], 2) + case "foreign owner": + binary.BigEndian.PutUint32(request[8:12], 2) + case "equipment": + client.equipment = &equipmentMove{} + case "dead": + player.health = 0 + case "loading": + client.loading = true + case "unready": + client.ready = false + case "stale": + world.clients[1] = &worldClient{id: 1} + case "equipped source": + binary.BigEndian.PutUint32(request[16:20], 101) + case "missing source": + binary.BigEndian.PutUint32(request[20:24], 93) + case "bank reorder": + request = backpackMoveRequest(105, 0, 57005, 1, 111)[20:] + case "stale bag": + request = backpackMoveRequest(107, 1<<16, 57005, 1, 111)[20:] + } + before, _ := readTestItemStore(world) + + err := world.handleInventory(client, request) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(player.inventory.Bank) != 0 { + t.Fatal("invalid bank transfer changed ownership", err) + } + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x47537a24 { + t.Fatalf("invalid move acknowledged: %x", packet) + } + } + }) + } +} + +func TestBankRangeUsesOpeningPositionAndAcceptsFiveMetres(t *testing.T) { + world, _ := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + player.position[0] += 5 + if err := world.handleBankUse(client, bankUseRequest(2)[20:]); err != nil { + t.Fatal(err) + } + player.position[0] += 5 + + err := world.handleInventory(client, backpackMoveRequest(104, 64, 57005, 1, 111)[20:]) + + if err != nil || len(player.inventory.Bank) != 1 || player.inventory.Bank[0].ID != 1 { + t.Fatal("bank locality used terminal instead of opening position", err) + } +} + +func TestBankConcurrentDuplicateMoveCommitsOnlyOnce(t *testing.T) { + world, conn := newBankWorld(t) + client := world.clients[1] + var workers sync.WaitGroup + errors := make(chan error, 8) + + for range 8 { + workers.Go(func() { errors <- world.handleInventory(client, backpackMoveRequest(104, 64, 57005, 1, 111)[20:]) }) + } + workers.Wait() + close(errors) + restarted := newTestInventoryServer(t) + + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + if len(restarted.characters[1].inventory.Bank) != 1 || len(restarted.items) != 5 || len(conn.packets) != 1 { + t.Fatal("duplicate bank move changed quantity or published twice") + } +} + +func TestBankTransferSaveFailurePublishesNothing(t *testing.T) { + world, conn := newBankWorld(t) + if _, err := world.db.Exec("CREATE TRIGGER fail_bank BEFORE INSERT ON item_locations WHEN NEW.bank_player_id IS NOT NULL BEGIN SELECT RAISE(FAIL,'test bank failure'); END"); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + + err := world.handleInventory(world.clients[1], backpackMoveRequest(104, 64, 57005, 1, 111)[20:]) + after, _ := readTestItemStore(world) + + if err == nil || !bytes.Equal(before, after) || len(world.characters[1].inventory.Bank) != 0 || len(conn.packets) != 0 { + t.Fatal("failed bank move partially committed") + } +} + +func TestBankStacksSplitJoinDeleteAndRestart(t *testing.T) { + world, conn := newBankWorld(t) + client := world.clients[1] + for _, slot := range []uint32{64, 65} { + if err := world.handleInventory(client, backpackMoveRequest(104, slot, 57005, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + } + conn.packets = nil + + for _, fields := range [][5]uint32{{53, 105, 0, 105, 1}, {52, 105, 0, 0, 2}, {52, 105, 0, 0, 2}, {112, 105, 1, 152030, 152030}} { + if err := world.handleInventory(client, characterActionPacket(1, fields)[20:]); err != nil { + t.Fatal(err) + } + } + restarted := newTestInventoryServer(t) + + if !reflect.DeepEqual(restarted.characters[1].inventory.Bank, []ownedItem{{ID: 1, Type: 51005, Template: 152030, Quality: 42, Slot: 0, Count: 2}}) || + len(restarted.items) != 4 || restarted.nextItem != 6 || len(conn.packets) != 3 { + t.Fatalf("bank stack operation lost counts or repeated allocation: %+v packets%d", restarted.characters[1].inventory, len(conn.packets)) + } + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[33:37]) != 105 || binary.BigEndian.Uint32(packet[37:41]) > 1 { + t.Fatalf("bank page passed through ordinary slot conversion: %x", packet) + } + } +} + +func TestBankInvalidSplitRestoresAuthoritativeSnapshot(t *testing.T) { + for _, retained := range []uint32{0, 4} { + t.Run(string(rune('0'+retained)), func(t *testing.T) { + world, conn := newBankWorld(t) + client := world.clients[1] + world.handleInventory(client, backpackMoveRequest(104, 64, 57005, 1, 111)[20:]) + before, _ := readTestItemStore(world) + conn.packets = nil + anchor := *client.bank + + err := world.handleInventory(client, characterActionPacket(1, [5]uint32{52, 105, 0, 0, retained})[20:]) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x343c287f || *client.bank != anchor { + t.Fatal("invalid split changed bank contents or server locality", err) + } + }) + } +} + +func TestBankDeletingFilledBagRemovesChildrenAtomically(t *testing.T) { + world, conn := newBankWorld(t) + client := world.clients[1] + world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]) + world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 111)[20:]) + world.handleInventory(client, backpackMoveRequest(104, 66, 57005, 1, 111)[20:]) + conn.packets = nil + + err := world.handleInventory(client, characterActionPacket(1, [5]uint32{112, 105, 0, 99228, 99228})[20:]) + restarted := newTestInventoryServer(t) + + if err != nil || len(restarted.items) != 3 || len(restarted.characters[1].inventory.Bank) != 0 || len(restarted.characters[1].inventory.Containers) != 0 || + len(client.backpacks) != 0 || len(conn.packets) != 1 { + t.Fatal("deleted bank bag retained children or stale handles", err) + } +} + +func TestBankCapacityRejectionPreservesItemAndCorrectsItsSource(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + for range 102 { + if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted { + t.Fatal(granted, err) + } + if err := world.handleInventory(client, backpackMoveRequest(104, 69, 57005, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + } + before, _ := readTestItemStore(world) + conn.packets = nil + + err := world.handleInventory(client, backpackMoveRequest(104, 64, 57005, 1, 111)[20:]) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(player.inventory.Bank) != 102 || len(conn.packets) != 1 || + !bytes.Equal(conn.packets[0][29:49], []byte{0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 104, 0, 0, 0, 48}) { + t.Fatalf("full bank lost an item or used wrong source correction: %v %x", err, conn.packets) + } +} + +func TestBankFullInventoryRejectsWithdrawal(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + world.handleInventory(client, backpackMoveRequest(104, 64, 57005, 1, 111)[20:]) + for len(player.inventory.Items) < 30 { + if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted { + t.Fatal(granted, err) + } + } + before, _ := readTestItemStore(world) + conn.packets = nil + + err := world.handleInventory(client, backpackMoveRequest(105, 0, 50000, 1, 111)[20:]) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(conn.packets) != 1 || !bytes.Equal(conn.packets[0][29:49], []byte{0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 105, 0, 0, 0, 0}) { + t.Fatal("full inventory changed bank item or omitted rejection", err) + } +} + +func TestBankUniqueChecksCarriedLowTemplateAndExcludesBank(t *testing.T) { + for _, placement := range []string{"inventory", "equipped", "carried bag", "bank", "banked bag"} { + t.Run(placement, func(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.Items[4].Template = 123742 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + original := gamedata.ItemTemplates[123742] + unique := *original + unique.Stats = slices.Clone(original.Stats) + for index, stat := range unique.Stats { + if stat[0] == 0 { + unique.Stats[index][1] |= 0x08000000 | 0x40 + } + } + gamedata.ItemTemplates[123742] = &unique + t.Cleanup(func() { gamedata.ItemTemplates[123742] = original }) + world.handleInventory(client, backpackMoveRequest(104, 68, 57005, 1, 111)[20:]) + if granted, err := world.grantItem_locked(player, 123742); err != nil || !granted { + t.Fatal(granted, err) + } + switch placement { + case "equipped": + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[len(inventory.Items)-1].Slot = 6 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + case "carried bag", "banked bag": + world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]) + world.handleInventory(client, backpackMoveRequest(104, 68, 51017, 3, 111)[20:]) + if placement == "banked bag" { + world.handleInventory(client, backpackMoveRequest(104, 66, 57005, 1, 111)[20:]) + } + case "bank": + world.handleInventory(client, backpackMoveRequest(104, 68, 57005, 1, 111)[20:]) + } + before, _ := readTestItemStore(world) + conn.packets = nil + + err := world.handleInventory(client, backpackMoveRequest(105, 0, 50000, 1, 111)[20:]) + after, _ := readTestItemStore(world) + + accepted := placement == "bank" || placement == "banked bag" + if err != nil || len(conn.packets) != 1 || bytes.Equal(before, after) == accepted { + t.Fatal("Unique used the wrong ownership scope", err) + } + expected := uint32(0x5e477770) + if accepted { + expected = 0x47537a24 + } + if binary.BigEndian.Uint32(conn.packets[0][16:20]) != expected { + t.Fatalf("Unique result: %x", conn.packets) + } + }) + } +} + +func TestBankCloseNativeWireDoesNotReload(t *testing.T) { + newRangedWorld(t) + world := newTestInventoryServer(t) + player := world.characters[1] + player.playfield, player.position = 705, [3]float32{985, 20.2001, 580} + peer := connectZoningClient(t, world, true) + peer.Write(targetPacket(bankUseRequest(1))) + for range 2 { + if _, err := readPacket(peer); err != nil { + t.Fatal(err) + } + } + + peer.Write(targetPacket(characterActionPacket(1, [5]uint32{106}))) + ping := systemPacket(1, nil) + binary.BigEndian.PutUint16(ping[2:4], 11) + peer.Write(ping) + packet, err := readPacket(peer) + + world.mutex.Lock() + defer world.mutex.Unlock() + if err != nil || len(packet) != 20 || world.clients[1].bank != nil || player.inventory.Items[0].Ammo != 3 || player.inventory.Items[1].Count != 100 || !world.clients[1].reloadUntil.IsZero() { + t.Fatalf("closing bank reloaded or left storage open: %v %x", err, packet) + } +} + +func TestBankUniqueUsesLowTemplateAcrossQualityEndpoints(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + original := gamedata.ItemTemplates[85511] + unique := *original + unique.Stats = slices.Clone(original.Stats) + for index, stat := range unique.Stats { + if stat[0] == 0 { + unique.Stats[index][1] |= 0x08000000 + } + } + gamedata.ItemTemplates[85511] = &unique + t.Cleanup(func() { gamedata.ItemTemplates[85511] = original }) + inventory := player.inventory + inventory.LastID = 7 + inventory.Items = append(slices.Clone(inventory.Items), ownedItem{ID: 6, Type: 51022, Template: 85512, Quality: 1, Slot: 69, Count: 1}) + inventory.Bank = []ownedItem{{ID: 7, Type: 51022, Template: 85511, Quality: 150, Slot: 0, Count: 1}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + + err := world.handleInventory(client, backpackMoveRequest(105, 0, 50000, 1, 111)[20:]) + after, _ := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 46 { + t.Fatal("Unique compared endpoint template IDs instead of low template", err) + } +} + +func TestBankCommitFailureRollsBackBothPlacements(t *testing.T) { + world, conn := newBankWorld(t) + if _, err := world.db.Exec("CREATE TABLE pending_bank (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_bank_commit AFTER INSERT ON item_locations WHEN NEW.bank_player_id IS NOT NULL BEGIN INSERT INTO pending_bank VALUES (999999); END"); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + + err := world.handleInventory(world.clients[1], backpackMoveRequest(104, 64, 57005, 1, 111)[20:]) + after, _ := readTestItemStore(world) + restarted := newTestInventoryServer(t) + + if err == nil || !bytes.Equal(before, after) || len(world.characters[1].inventory.Bank) != 0 || len(restarted.characters[1].inventory.Bank) != 0 || len(restarted.items) != 5 || len(conn.packets) != 0 { + t.Fatal("failed COMMIT published or partially persisted a bank transfer") + } +} + +func TestBankItemsSurviveDeathAndLeaveSessionClosed(t *testing.T) { + world, _ := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + player.level = 10 + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil { + t.Fatal(err) + } + for _, request := range [][]byte{backpackMoveRequest(104, 68, 51017, 3, 111), backpackMoveRequest(104, 66, 57005, 1, 111)} { + if err := world.handleInventory(client, request[20:]); err != nil { + t.Fatal(err) + } + } + + defeatReclaimPlayer(t, world) + restarted := newTestInventoryServer(t).characters[1] + + if player.health != 0 || client.bank != nil || len(restarted.inventory.Bank) != 1 || restarted.inventory.Bank[0].ID != 3 || + !reflect.DeepEqual(restarted.inventory.Containers[3], []ownedItem{{ID: 5, Type: 51018, Template: 121567, Quality: 1, Count: 1}}) || len(world.items) != 5 { + t.Fatalf("death reclaimed bank items or lost a banked bag's child: %+v", restarted.inventory) + } +} + +func TestBankMovementClosesStorageBeforePlayerReturns(t *testing.T) { + world, conn := newBankWorld(t) + client, player := world.clients[1], world.characters[1] + moved := *player + moved.position[0] += 6 + request := npcMovementPacket(&moved, 2)[20:] + request = append(request[:16:16], encodeMovement1491(request[16:])...) + + err := world.handleMovement(client, request) + world.handleInventory(client, backpackMoveRequest(104, 64, 57005, 1, 111)[20:]) + + if err != nil || client.bank != nil || len(player.inventory.Bank) != 0 || len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 106 || binary.BigEndian.Uint32(conn.packets[1][29:33]) != 46 { + t.Fatalf("movement left bank access active: %v %x", err, conn.packets) + } +} + +func TestBankLoadedWeaponRoundTripPreservesAmmunition(t *testing.T) { + world, _ := newRangedWorld(t) + player, client := world.characters[1], world.clients[1] + player.playfield, player.position = 705, [3]float32{985, 20.2001, 580} + if err := world.handleInventory(client, itemMovePacket(1, 6, 111)[20:]); err != nil { + t.Fatal(err) + } + world.advanceEquipment(client.equipment.readyAt) + if err := world.handleBankUse(client, bankUseRequest(1)[20:]); err != nil { + t.Fatal(err) + } + + if err := world.handleInventory(client, backpackMoveRequest(104, 65, 57005, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + deposited := newTestInventoryServer(t).characters[1].inventory + if err := world.handleInventory(client, backpackMoveRequest(105, 0, 50000, 1, 111)[20:]); err != nil { + t.Fatal(err) + } + withdrawn := newTestInventoryServer(t).characters[1].inventory + + if !reflect.DeepEqual(deposited.Bank, []ownedItem{{ID: 1, Type: 51018, Template: 123742, Quality: 1, Slot: 0, Count: 1, Ammo: 3}}) || + !slices.Contains(withdrawn.Items, ownedItem{ID: 1, Type: 51018, Template: 123742, Quality: 1, Slot: 65, Count: 1, Ammo: 3}) || len(withdrawn.Bank) != 0 || len(world.items) != 2 { + t.Fatal("bank transfer changed loaded rounds or weapon identity") + } +} diff --git a/server/character_editor.go b/server/character_editor.go @@ -7,12 +7,13 @@ type characterEditor struct { Vitals playerVitals `yaml:"vitals"` Inventory inventoryReferences `yaml:"inventory"` Equipment map[string]*uint32 `yaml:"equipment"` + Bank map[string]*uint32 `yaml:"bank"` } func (character *character) editor() characterEditor { record := character.record() items := character.inventory.references() - return characterEditor{record.Profile, record.Position.editor(), record.Vitals, items.inventoryReferences, items.Equipment} + return characterEditor{record.Profile, record.Position.editor(), record.Vitals, items.inventoryReferences, items.Equipment, items.Bank} } func (data characterEditor) character() *character { diff --git a/server/combat.go b/server/combat.go @@ -426,6 +426,7 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr target.position = predictedPosition_locked(&previous, client, now) client.forward = 0 client.reclaimItems = nil + client.bank = nil client.backpacks = nil } server.cancelCombat_locked(target.id, updates) diff --git a/server/control.go b/server/control.go @@ -139,7 +139,7 @@ func (server *server) editUser(w http.ResponseWriter, r *http.Request) { err = fmt.Errorf("unknown resurrection terminal") } if err == nil { - updated.inventory, err = (characterItemReferences{data.Inventory, data.Equipment}).inventory(server.items, server.nextItem) + updated.inventory, err = (characterItemReferences{data.Inventory, data.Equipment, data.Bank}).inventory(server.items, server.nextItem) } var store itemStore if err == nil { diff --git a/server/control_inventory.go b/server/control_inventory.go @@ -46,6 +46,8 @@ func (server *server) inventoryTables_locked(w io.Writer, inventory playerInvent server.itemTableRow_locked(w, equipmentSlots[number], references.Equipment[equipmentSlots[number]]) } fmt.Fprint(w, "</table>") + fmt.Fprint(w, "<h2>Bank</h2>") + server.backpackTable_locked(w, itemRecord{Slots: references.Bank}) if len(inventory.Reclaim) != 0 { fmt.Fprint(w, "<h2>Reclaim</h2><table><tr><th>Original slot</th><th>Item</th></tr>") diff --git a/server/control_inventory_test.go b/server/control_inventory_test.go @@ -73,18 +73,19 @@ func TestControlInventoryTablesShowInstancesContainersAndEmptySlots(t *testing.T body := page.Body.String() for _, expected := range []string{ - "<base href='/share/test/'>", "<textarea name='data'", "<h2>Inventory</h2>", "<h2>Equipment</h2>", + "<base href='/share/test/'>", "<textarea name='data'", "<h2>Inventory</h2>", "<h2>Equipment</h2>", "<h2>Bank</h2>", "<tr><td>inventory_slot_1</td><td><a href='control/items/1'>Solar-Powered Pistol (ID 1)</a></td></tr>", "<tr><td>clothes_head</td><td><a href='control/items/2'>Worn Metaplast Armor Helmet (ID 2)</a></td></tr>", "<h2>Container <a href='control/items/3'>Small Backpack (ID 3)</a></h2>", "<tr><td>slot_1</td><td><a href='control/items/4'>Solar-Powered Pistol (ID 4)</a></td></tr>", "<tr><td>slot_21</td><td>Empty</td></tr>", + "<tr><td>slot_102</td><td>Empty</td></tr>", } { if !strings.Contains(body, expected) { t.Errorf("missing %s", expected) } } - if strings.Count(body, "<td>Empty</td>") != 90 || strings.Index(body, "<td>inventory_slot_2</td>") > strings.Index(body, "<td>inventory_slot_10</td>") { + if strings.Count(body, "<td>Empty</td>") != 192 || strings.Index(body, "<td>inventory_slot_2</td>") > strings.Index(body, "<td>inventory_slot_10</td>") { t.Fatal("slot tables omit empty slots or use lexical slot order") } } diff --git a/server/control_items.go b/server/control_items.go @@ -18,7 +18,7 @@ func controlItemSlots(inventory playerInventory, item ownedItem) []controlItemSl } } if item.Type != 51017 { - for _, bag := range inventory.Items { + for _, bag := range append(slices.Clone(inventory.Items), inventory.Bank...) { if !bag.isPortableContainer() { continue } @@ -34,6 +34,7 @@ func controlItemSlots(inventory playerInventory, item ownedItem) []controlItemSl func (inventory playerInventory) allItems() []ownedItem { items := slices.Clone(inventory.Items) + items = append(items, inventory.Bank...) for _, entry := range inventory.Reclaim { items = append(items, entry.Item) } diff --git a/server/gamedata/banks.yaml b/server/gamedata/banks.yaml @@ -0,0 +1,604 @@ +# Generated from original 14.9.1 statels by extract_banks.py. +3221226037: + playfield: 565 + position: [3336.699951171875, 37.0, 1969.699951171875] +3221226042: + playfield: 570 + position: [1010.2000732421875, 37.209999084472656, 2416.5] +3221226057: + playfield: 585 + position: [605.8148803710938, 69.9000015258789, 1128.076416015625] +3221226142: + playfield: 670 + position: [1107.1998291015625, 15.400100708007812, 4077.354248046875] +3221226167: + playfield: 695 + position: [1461.0, 37.600074768066406, 689.0] +3221291618: + playfield: 610 + position: [1263.911376953125, 21.599979400634766, 2327.477783203125] +3221291628: + playfield: 620 + position: [2727.199951171875, 0.009999999776482582, 2848.30712890625] +3221291633: + playfield: 625 + position: [1306.000244140625, 24.910001754760742, 699.800048828125] +3221291643: + playfield: 635 + position: [749.2985229492188, 46.19999694824219, 1605.7989501953125] +3221291655: + playfield: 647 + position: [985.5214233398438, 14.5, 1964.06005859375] +3221291658: + playfield: 650 + position: [1784.28759765625, 20.500009536743164, 2183.1630859375] +3221291693: + playfield: 685 + position: [2435.146484375, 1.4000999927520752, 1175.0853271484375] +3221291695: + playfield: 687 + position: [405.8482971191406, 15.400041580200195, 846.5928955078125] +3221291799: + playfield: 791 + position: [381.20001220703125, 0.20424674451351166, 756.4000244140625] +3221292189: + playfield: 1181 + position: [196.8507843017578, 5.010024547576904, 169.51109313964844] +3221292190: + playfield: 1182 + position: [196.9766845703125, 6.109987258911133, 160.5486602783203] +3221292192: + playfield: 1184 + position: [219.88705444335938, 5.0101399421691895, 120.78600311279297] +3221292193: + playfield: 1185 + position: [194.8415069580078, 5.010071754455566, 120.99242401123047] +3221292195: + playfield: 1187 + position: [206.7883758544922, 5.010037422180176, 139.08387756347656] +3221357095: + playfield: 551 + position: [2414.60009765625, 22.810001373291016, 3378.89990234375] +3221357104: + playfield: 560 + position: [1853.37646484375, 43.40010070800781, 1141.152099609375] +3221357111: + playfield: 567 + position: [1172.604736328125, 33.41007995605469, 485.59783935546875] +3221357130: + playfield: 586 + position: [432.2027587890625, 6.754937648773193, 758.033203125] +3221357149: + playfield: 605 + position: [2213.39990234375, 30.40999984741211, 2214.558349609375] +3221357190: + playfield: 646 + position: [1892.3380126953125, 15.599997520446777, 1412.7867431640625] +3221357229: + playfield: 685 + position: [1485.4405517578125, 15.400147438049316, 2350.2783203125] +3221357231: + playfield: 687 + position: [654.0945434570312, 17.800071716308594, 1420.1492919921875] +3221357334: + playfield: 790 + position: [1225.4000244140625, 14.610000610351562, 882.0000610351562] +3221357724: + playfield: 1180 + position: [209.4330291748047, 5.009995937347412, 182.97979736328125] +3221357727: + playfield: 1183 + position: [196.7982635498047, 5.009963035583496, 136.83982849121094] +3221357730: + playfield: 1186 + position: [167.6501007080078, 5.009984970092773, 132.35562133789062] +3221422631: + playfield: 551 + position: [1314.0, 32.29999923706055, 1758.0] +3221422640: + playfield: 560 + position: [2868.0, 36.600101470947266, 1899.5] +3221422645: + playfield: 565 + position: [1530.0, 31.21000099182129, 2737.119140625] +3221422665: + playfield: 585 + position: [1326.4000244140625, 9.610000610351562, 2049.37060546875] +3221422726: + playfield: 646 + position: [2800.96826171875, 18.900123596191406, 682.2060546875] +3221422727: + playfield: 647 + position: [1911.80029296875, 24.5, 2261.835205078125] +3221422765: + playfield: 685 + position: [456.987060546875, 15.400041580200195, 2374.7265625] +3221422775: + playfield: 695 + position: [3278.76953125, 20.00010108947754, 794.1599731445312] +3221422870: + playfield: 790 + position: [1226.5, 0.0, 2884.199951171875] +3221422875: + playfield: 795 + position: [3648.300048828125, 30.610000610351562, 586.2999877929688] +3221488281: + playfield: 665 + position: [751.177978515625, 19.010009765625, 1530.6673583984375] +3221488321: + playfield: 705 + position: [681.0, 16.40009880065918, 569.0] +3221488332: + playfield: 716 + position: [638.7999877929688, 39.999996185302734, 1668.699951171875] +3221488411: + playfield: 795 + position: [2030.83056640625, 33.40010070800781, 815.4705200195312] +3221553782: + playfield: 630 + position: [2301.3056640625, 3.0000998973846436, 1842.982177734375] +3221553799: + playfield: 647 + position: [2622.68896484375, 21.200000762939453, 2723.176025390625] +3221553817: + playfield: 665 + position: [934.7742309570312, 49.40009689331055, 3738.637451171875] +3221553857: + playfield: 705 + position: [985.0, 20.20009994506836, 580.0] +3221553868: + playfield: 716 + position: [301.0111389160156, 10.000100135803223, 1840.379638671875] +3221553947: + playfield: 795 + position: [3744.91455078125, 48.39999771118164, 1555.6666259765625] +3221619318: + playfield: 630 + position: [2825.97607421875, 33.000099182128906, 2510.526611328125] +3221619353: + playfield: 665 + position: [2323.241455078125, 7.200099945068359, 2226.078125] +3221619404: + playfield: 716 + position: [308.9516296386719, 10.000100135803223, 2078.57568359375] +3221687284: + playfield: 3060 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687285: + playfield: 3061 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687286: + playfield: 3062 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687287: + playfield: 3063 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687288: + playfield: 3064 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687289: + playfield: 3065 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687290: + playfield: 3066 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687291: + playfield: 3067 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687292: + playfield: 3068 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687293: + playfield: 3069 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687294: + playfield: 3070 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687295: + playfield: 3071 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687304: + playfield: 3080 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687305: + playfield: 3081 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687306: + playfield: 3082 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687307: + playfield: 3083 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687308: + playfield: 3084 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687309: + playfield: 3085 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687310: + playfield: 3086 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687311: + playfield: 3087 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687312: + playfield: 3088 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221687313: + playfield: 3089 + position: [93.47972869873047, 39.999916076660156, 138.3720703125] +3221750425: + playfield: 665 + position: [587.0, 18.099952697753906, 1533.01220703125] +3221752760: + playfield: 3000 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752761: + playfield: 3001 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752762: + playfield: 3002 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752763: + playfield: 3003 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752764: + playfield: 3004 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752765: + playfield: 3005 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752766: + playfield: 3006 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752767: + playfield: 3007 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752768: + playfield: 3008 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752769: + playfield: 3009 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752770: + playfield: 3010 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752771: + playfield: 3011 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752772: + playfield: 3012 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752773: + playfield: 3013 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752774: + playfield: 3014 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752775: + playfield: 3015 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752776: + playfield: 3016 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752777: + playfield: 3017 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752778: + playfield: 3018 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752779: + playfield: 3019 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752780: + playfield: 3020 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752781: + playfield: 3021 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752782: + playfield: 3022 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752783: + playfield: 3023 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752784: + playfield: 3024 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752785: + playfield: 3025 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752786: + playfield: 3026 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752787: + playfield: 3027 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752788: + playfield: 3028 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752789: + playfield: 3029 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752790: + playfield: 3030 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752791: + playfield: 3031 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752792: + playfield: 3032 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752793: + playfield: 3033 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752794: + playfield: 3034 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752795: + playfield: 3035 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752796: + playfield: 3036 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752797: + playfield: 3037 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752798: + playfield: 3038 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752799: + playfield: 3039 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752800: + playfield: 3040 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752801: + playfield: 3041 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752802: + playfield: 3042 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752803: + playfield: 3043 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752804: + playfield: 3044 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752805: + playfield: 3045 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752806: + playfield: 3046 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752807: + playfield: 3047 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752808: + playfield: 3048 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752809: + playfield: 3049 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752810: + playfield: 3050 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752811: + playfield: 3051 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752812: + playfield: 3052 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752813: + playfield: 3053 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752814: + playfield: 3054 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752815: + playfield: 3055 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752816: + playfield: 3056 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752817: + playfield: 3057 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752818: + playfield: 3058 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752819: + playfield: 3059 + position: [109.20470428466797, 115.00012969970703, 152.970703125] +3221752860: + playfield: 3100 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752861: + playfield: 3101 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752862: + playfield: 3102 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752863: + playfield: 3103 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752864: + playfield: 3104 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752865: + playfield: 3105 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752866: + playfield: 3106 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752867: + playfield: 3107 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752868: + playfield: 3108 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752869: + playfield: 3109 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752870: + playfield: 3110 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752871: + playfield: 3111 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752872: + playfield: 3112 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752873: + playfield: 3113 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752874: + playfield: 3114 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752875: + playfield: 3115 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752876: + playfield: 3116 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752877: + playfield: 3117 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752880: + playfield: 3120 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752881: + playfield: 3121 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752882: + playfield: 3122 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752883: + playfield: 3123 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752884: + playfield: 3124 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752885: + playfield: 3125 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752886: + playfield: 3126 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752887: + playfield: 3127 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752888: + playfield: 3128 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752889: + playfield: 3129 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752890: + playfield: 3130 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752891: + playfield: 3131 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752892: + playfield: 3132 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752893: + playfield: 3133 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752894: + playfield: 3134 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752895: + playfield: 3135 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752896: + playfield: 3136 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752897: + playfield: 3137 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752898: + playfield: 3138 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752899: + playfield: 3139 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752900: + playfield: 3140 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752901: + playfield: 3141 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752902: + playfield: 3142 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752903: + playfield: 3143 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752904: + playfield: 3144 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752905: + playfield: 3145 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752906: + playfield: 3146 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752907: + playfield: 3147 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752908: + playfield: 3148 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221752909: + playfield: 3149 + position: [61.597476959228516, 25.000070571899414, 115.31089782714844] +3221815926: + playfield: 630 + position: [2979.3818359375, 35.000099182128906, 663.398193359375] +3221815942: + playfield: 646 + position: [1812.6756591796875, 27.399999618530273, 696.37744140625] +3221815961: + playfield: 665 + position: [663.412841796875, 13.028939247131348, 1412.3787841796875] +3221881462: + playfield: 630 + position: [400.97625732421875, 20.00010108947754, 1498.61865234375] +3221946998: + playfield: 630 + position: [1242.828125, 8.410000801086426, 2388.565185546875] +3221947014: + playfield: 646 + position: [734.0, 16.100000381469727, 1241.0] +3222012599: + playfield: 695 + position: [2812.398193359375, 10.000100135803223, 2800.225830078125] +3222143671: + playfield: 695 + position: [1466.0, 7.400100231170654, 2431.0] +3222209207: + playfield: 695 + position: [3277.000244140625, 7.000100135803223, 2906.000244140625] +3222274743: + playfield: 695 + position: [1578.500244140625, 45.00009536743164, 533.4000244140625] +3222340134: + playfield: 550 + position: [1722.0, 30.00010108947754, 1931.0] +3222340279: + playfield: 695 + position: [1530.0, 7.400100231170654, 2454.0] +3222405670: + playfield: 550 + position: [1550.0, 37.000099182128906, 324.0] +3222602423: + playfield: 695 + position: [2901.0, 10.000100135803223, 2930.0] +3223454201: + playfield: 505 + position: [2001.8685302734375, 41.999996185302734, 3738.334716796875] +3223585273: + playfield: 505 + position: [1868.0819091796875, 25.00010108947754, 1196.0528564453125] diff --git a/server/gamedata/banks_test.go b/server/gamedata/banks_test.go @@ -0,0 +1,19 @@ +package gamedata + +import "testing" + +func TestBankTerminalsMatchOriginalPlacements(t *testing.T) { + terminal, exists := BankTerminals[0xc00502c1] + + if len(BankTerminals) != 201 || !exists || terminal.Playfield != 705 || terminal.Position != [3]float32{985, 20.2001, 580} { + t.Fatal("original bank-terminal placement changed") + } + for id, terminal := range BankTerminals { + if id&65535 != terminal.Playfield { + t.Fatalf("terminal %08x belongs to playfield %d", id, terminal.Playfield) + } + if _, exists := Playfields[terminal.Playfield]; !exists { + t.Fatalf("bank terminal references unknown playfield %d", terminal.Playfield) + } + } +} diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -28,7 +28,11 @@ var ( MapCoordinates MapCoordinateData TerrainEvidence TerrainExtractionEvidence Playfields map[uint32]Playfield - ProfessionTitles map[uint16]struct { + BankTerminals map[uint32]struct { + Playfield uint32 `yaml:"playfield"` + Position [3]float32 `yaml:"position"` + } + ProfessionTitles map[uint16]struct { Health [6]uint32 `yaml:"health"` Nano [6]uint32 `yaml:"nano"` } @@ -65,6 +69,7 @@ func init() { loadYAML("map_coordinates.yaml", &MapCoordinates) loadYAML("terrain_evidence.yaml", &TerrainEvidence) loadYAML("playfields.yaml", &Playfields) + loadYAML("banks.yaml", &BankTerminals) loadYAML("profession_resources.yaml", &ProfessionTitles) loadYAML("ip_training.yaml", &IPTraining) diff --git a/server/insurance.go b/server/insurance.go @@ -1,11 +1,15 @@ package main import ( + "ao/server/gamedata" "encoding/binary" "time" ) func (server *server) handleTerminalUse(client *worldClient, body []byte) error { + if _, bank := gamedata.BankTerminals[binary.BigEndian.Uint32(body[44:48])]; bank && binary.BigEndian.Uint32(body[40:44]) == 51005 { + return server.handleBankUse(client, body) + } if _, shop := starterShop(binary.BigEndian.Uint32(body[44:48])); shop && binary.BigEndian.Uint32(body[40:44]) == 51005 { return server.handleShopUse(client, body) } diff --git a/server/inventory.go b/server/inventory.go @@ -28,6 +28,7 @@ type playerInventory struct { LastID uint32 Credits uint32 Items []ownedItem + Bank []ownedItem Reclaim []reclaimItem Containers map[uint32][]ownedItem FirstAidLockedUntil time.Time @@ -67,6 +68,17 @@ func (inventory playerInventory) validate() error { return fmt.Errorf("equipment in a disabled deck slot") } } + bankSlots := make(map[uint32]bool) + for _, item := range inventory.Bank { + if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Count == 0 || !item.validAmmo() || + (item.Count != 1 && !item.isStackable()) || item.Slot >= bankCapacity || bankSlots[item.Slot] { + return fmt.Errorf("invalid bank item identity or slot") + } + ids[item.ID], bankSlots[item.Slot] = true, true + if item.isPortableContainer() { + bags[item.ID] = true + } + } for _, entry := range inventory.Reclaim { if entry.Item.ID == 0 || entry.Item.ID > inventory.LastID || ids[entry.Item.ID] || entry.Item.Count == 0 || !entry.Item.validAmmo() || (entry.Item.Count != 1 && !entry.Item.isStackable()) || entry.Item.Slot < 64 || entry.Item.Slot >= 94 { @@ -195,6 +207,12 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { if key == 0x5e477770 && binary.BigEndian.Uint32(body[20:24]) == 107 && binary.BigEndian.Uint32(body[24:28])>>16 != 0 { return server.handleBackpackAction_locked(client, body) } + if key == 0x5e477770 && binary.BigEndian.Uint32(body[20:24]) == 105 { + return server.handleBankAction_locked(client, body) + } + if key == 0x47537a24 && (binary.BigEndian.Uint32(body[16:20]) == 105 || binary.BigEndian.Uint32(body[24:28]) == 57005) { + return server.moveContainerItem_locked(client, body) + } if client.equipment != nil { if key == 0x5e477770 && binary.BigEndian.Uint32(body[16:20]) == 52 { return server.syncStacks_locked(client) @@ -203,7 +221,7 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { } if key == 0x47537a24 && (binary.BigEndian.Uint32(body[24:28]) == 51017 || binary.BigEndian.Uint32(body[16:20]) == 107 && binary.BigEndian.Uint32(body[20:24])>>16 != 0) { - return server.moveBackpackItem_locked(client, body) + return server.moveContainerItem_locked(client, body) } // Page identities must agree with this owner's actual logical slot. diff --git a/server/item_database.go b/server/item_database.go @@ -8,8 +8,8 @@ import ( ) type itemPlacement struct { - Player, Backpack, Corpse, Slot uint32 - ReclaimAt string + Player, Bank, Backpack, Corpse, Slot uint32 + ReclaimAt string } func (server *server) persistItems_locked(store itemStore) error { @@ -33,6 +33,9 @@ func (server *server) persistItems_locked(store itemStore) error { for _, item := range inventory.Items { placements[item.ID] = itemPlacement{Player: id, Slot: item.Slot} } + for _, item := range inventory.Bank { + placements[item.ID] = itemPlacement{Bank: id, Slot: item.Slot} + } for _, entry := range inventory.Reclaim { placements[entry.Item.ID] = itemPlacement{Player: id, Slot: entry.Item.Slot, ReclaimAt: entry.AvailableAt.UTC().Format(time.RFC3339Nano)} } @@ -154,10 +157,13 @@ func (server *server) persistItems_locked(store itemStore) error { if previous, exists := server.itemPlacements[id]; exists && previous == placement { continue } - var player, backpack, corpse, reclaim any + var player, bank, backpack, corpse, reclaim any if placement.Player != 0 { player = placement.Player } + if placement.Bank != 0 { + bank = placement.Bank + } if placement.Backpack != 0 { backpack = placement.Backpack } @@ -167,7 +173,7 @@ func (server *server) persistItems_locked(store itemStore) error { if placement.ReclaimAt != "" { reclaim = placement.ReclaimAt } - if _, err := tx.Exec("INSERT INTO item_locations (item_id, player_id, backpack_id, corpse_id, slot, reclaim_at) VALUES (?, ?, ?, ?, ?, ?)", id, player, backpack, corpse, placement.Slot, reclaim); err != nil { + if _, err := tx.Exec("INSERT INTO item_locations (item_id, player_id, bank_player_id, backpack_id, corpse_id, slot, reclaim_at) VALUES (?, ?, ?, ?, ?, ?, ?)", id, player, bank, backpack, corpse, placement.Slot, reclaim); err != nil { return err } } @@ -246,7 +252,7 @@ func (server *server) readItems() (itemStore, error) { } for rows.Next() { var id uint32 - references := characterItemReferences{inventoryReferences: inventoryReferences{Slots: emptyInventorySlots()}, Equipment: emptyEquipmentSlots()} + references := characterItemReferences{inventoryReferences: inventoryReferences{Slots: emptyInventorySlots()}, Equipment: emptyEquipmentSlots(), Bank: emptyItemSlots(bankCapacity)} if err := rows.Scan(&id, &references.Credits, &references.FirstAidLockedUntil); err != nil { rows.Close() return store, err @@ -300,7 +306,7 @@ func (server *server) readItems() (itemStore, error) { return store, err } rows.Close() - rows, err = db.Query("SELECT item_id, player_id, backpack_id, corpse_id, slot, reclaim_at FROM item_locations") + rows, err = db.Query("SELECT item_id, player_id, bank_player_id, backpack_id, corpse_id, slot, reclaim_at FROM item_locations") if err != nil { return store, err } @@ -308,13 +314,17 @@ func (server *server) readItems() (itemStore, error) { server.itemPlacements = make(map[uint32]itemPlacement) for rows.Next() { var id, slot uint32 - var player, backpack, corpse sql.NullInt64 + var player, bank, backpack, corpse sql.NullInt64 var reclaim sql.NullString - if err := rows.Scan(&id, &player, &backpack, &corpse, &slot, &reclaim); err != nil { + if err := rows.Scan(&id, &player, &bank, &backpack, &corpse, &slot, &reclaim); err != nil { return store, err } - server.itemPlacements[id] = itemPlacement{uint32(player.Int64), uint32(backpack.Int64), uint32(corpse.Int64), slot, reclaim.String} + server.itemPlacements[id] = itemPlacement{Player: uint32(player.Int64), Bank: uint32(bank.Int64), Backpack: uint32(backpack.Int64), Corpse: uint32(corpse.Int64), Slot: slot, ReclaimAt: reclaim.String} switch { + case bank.Valid: + references := store.Players[uint32(bank.Int64)] + references.Bank[fmt.Sprintf("slot_%d", slot+1)] = &id + store.Players[uint32(bank.Int64)] = references case player.Valid: references := store.Players[uint32(player.Int64)] if reclaim.Valid { diff --git a/server/item_pages.go b/server/item_pages.go @@ -60,6 +60,9 @@ func (server *server) itemLocations_locked() map[uint32]itemLocation { for _, entry := range player.inventory.Reclaim { locations[entry.Item.ID] = itemLocation{owner: player.id, label: "Reclaim"} } + for _, item := range player.inventory.Bank { + locations[item.ID] = itemLocation{owner: player.id, label: fmt.Sprintf("Bank, slot_%d", item.Slot+1)} + } } for id, record := range server.items { for slot, contained := range record.Slots { diff --git a/server/item_store.go b/server/item_store.go @@ -37,6 +37,7 @@ type inventoryReferences struct { type characterItemReferences struct { inventoryReferences `yaml:",inline"` Equipment map[string]*uint32 `yaml:"equipment"` + Bank map[string]*uint32 `yaml:"bank"` } type playerVitalUpdate struct { @@ -66,7 +67,7 @@ func emptyItemSlots(count uint32) map[string]*uint32 { func (inventory playerInventory) references() characterItemReferences { result := characterItemReferences{inventoryReferences: inventoryReferences{Credits: inventory.Credits, Slots: emptyInventorySlots(), - FirstAidLockedUntil: inventory.FirstAidLockedUntil, TreatmentLocks: maps.Clone(inventory.TreatmentLocks), LearnedNanos: slices.Clone(inventory.LearnedNanos)}, Equipment: emptyEquipmentSlots()} + FirstAidLockedUntil: inventory.FirstAidLockedUntil, TreatmentLocks: maps.Clone(inventory.TreatmentLocks), LearnedNanos: slices.Clone(inventory.LearnedNanos)}, Equipment: emptyEquipmentSlots(), Bank: emptyItemSlots(bankCapacity)} for _, item := range inventory.Items { if item.Slot >= 64 { result.Slots[fmt.Sprintf("inventory_slot_%d", item.Slot-63)] = &item.ID @@ -77,6 +78,9 @@ func (inventory playerInventory) references() characterItemReferences { for _, entry := range inventory.Reclaim { result.Reclaim = append(result.Reclaim, reclaimReference{entry.Item.ID, fmt.Sprintf("inventory_slot_%d", entry.Item.Slot-63), entry.AvailableAt}) } + for _, item := range inventory.Bank { + result.Bank[fmt.Sprintf("slot_%d", item.Slot+1)] = &item.ID + } return result } @@ -141,6 +145,11 @@ func (references characterItemReferences) inventory(records map[uint32]itemRecor } } slices.SortFunc(inventory.Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) }) + var err error + inventory.Bank, err = referencedItems(references.Bank, 0, bankCapacity, records) + if err != nil { + return inventory, err + } for _, entry := range references.Reclaim { record, exists := records[entry.ID] if !exists { @@ -152,7 +161,7 @@ func (references characterItemReferences) inventory(records map[uint32]itemRecor } inventory.Reclaim = append(inventory.Reclaim, reclaimItem{ownedItem{ID: entry.ID, Type: record.Type, Template: record.Template, Quality: record.Quality, Slot: slot, Count: record.Count, Ammo: record.Ammo}, entry.AvailableAt}) } - for _, item := range append(slices.Clone(inventory.Items), reclaimItems(inventory.Reclaim)...) { + for _, item := range append(append(slices.Clone(inventory.Items), inventory.Bank...), reclaimItems(inventory.Reclaim)...) { if !item.isPortableContainer() { continue } @@ -306,7 +315,7 @@ func (store itemStore) validate() error { if err != nil { return fmt.Errorf("player %d: %w", id, err) } - for _, item := range append(slices.Clone(inventory.Items), reclaimItems(inventory.Reclaim)...) { + for _, item := range append(append(slices.Clone(inventory.Items), inventory.Bank...), reclaimItems(inventory.Reclaim)...) { if claimed[item.ID] { return fmt.Errorf("item %d is assigned more than once", item.ID) } diff --git a/server/main.go b/server/main.go @@ -360,6 +360,7 @@ func (server *server) serveWorldClient(client *worldClient) error { client.npcs = make(map[uint32]bool) client.lootCorpse = 0 client.shop = nil + client.bank = nil updates := [][]byte{playfieldPacket(character), characterPacket(character)} for id, other := range server.characters { if id != character.id && other.playfield == character.playfield && server.clients[id] != nil { @@ -550,7 +551,7 @@ func (server *server) serveWorldClient(client *worldClient) error { return err } case 106: - if err := server.handleReload(client, body); err != nil { + if err := server.handleBankClose(client, body); err != nil { return err } case 105: diff --git a/server/ranged.go b/server/ranged.go @@ -41,18 +41,12 @@ func (server *server) applyWeaponDamage_locked(attacker, target *character, dama } func (server *server) handleReload(client *worldClient, body []byte) error { - if len(body) != 36 && len(body) != 56 { + if len(body) != 56 { return fmt.Errorf("invalid reload request length") } - explicit := binary.BigEndian.Uint32(body) == 0x52526858 - if explicit { - if len(body) != 56 || binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 5 || - binary.BigEndian.Uint32(body[28:32]) > 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 || - binary.BigEndian.Uint32(body[36:40]) != client.id { - return nil - } - } else if len(body) != 36 || binary.BigEndian.Uint32(body) != 0x5e477770 || binary.BigEndian.Uint32(body[16:20]) != 106 || - binary.BigEndian.Uint64(body[20:28]) != 0 || binary.BigEndian.Uint64(body[28:36]) != 0 { + if binary.BigEndian.Uint32(body) != 0x52526858 || binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 5 || + binary.BigEndian.Uint32(body[28:32]) > 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 || + binary.BigEndian.Uint32(body[36:40]) != client.id { return nil } @@ -66,32 +60,25 @@ func (server *server) handleReload(client *worldClient, body []byte) error { return nil } var packets [][]byte - var acknowledgement []byte - if explicit { - sequence := binary.BigEndian.Uint32(body[20:24]) - if sequence <= client.useSequence { - server.mutex.Unlock() - return nil - } - client.useSequence = sequence - acknowledgement = append([]byte(nil), body[16:]...) - binary.BigEndian.PutUint32(acknowledgement, 2) + sequence := binary.BigEndian.Uint32(body[20:24]) + if sequence <= client.useSequence { + server.mutex.Unlock() + return nil } + client.useSequence = sequence + acknowledgement := append([]byte(nil), body[16:]...) + binary.BigEndian.PutUint32(acknowledgement, 2) - // A global request names no items; select the lowest compatible ordinary slot. + // Native ammo-on-weapon use names both sides of the transfer. weapon := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == 6 && item.isFlechettePistol() }) - ammo := -1 - for index, item := range player.inventory.Items { - if item.Type == 51005 && item.Template == 21605 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && - (!explicit || binary.BigEndian.Uint32(body[40:44]) == 104 && binary.BigEndian.Uint32(body[44:48]) == item.Slot) && - (ammo < 0 || item.Slot < player.inventory.Items[ammo].Slot) { - ammo = index - } - } + ammo := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { + return item.Type == 51005 && item.Template == 21605 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && + binary.BigEndian.Uint32(body[40:44]) == 104 && binary.BigEndian.Uint32(body[44:48]) == item.Slot + }) now := time.Now() accepted := weapon >= 0 && ammo >= 0 && client.equipment == nil && client.nanoCast == nil && !now.Before(client.reloadUntil) && !player.driving() - if accepted && explicit { + if accepted { targetType, targetID := binary.BigEndian.Uint32(body[48:52]), binary.BigEndian.Uint32(body[52:56]) accepted = targetType == 101 && targetID == 6 || targetType == 51018 && targetID == player.inventory.Items[weapon].ID } @@ -136,9 +123,7 @@ func (server *server) handleReload(client *worldClient, body []byte) error { } *player = candidate client.reloadUntil = readyAt - if explicit { - binary.BigEndian.PutUint32(acknowledgement, 1) - } + binary.BigEndian.PutUint32(acknowledgement, 1) remaining, remove := uint32(source.Count)-loaded, uint32(0) if remaining == 0 { remove = 1 @@ -149,9 +134,7 @@ func (server *server) handleReload(client *worldClient, body []byte) error { } packets = append(packets, n3Packet(0x26515e61, 50000, player.id, response)) } - if explicit { - packets = append([][]byte{n3Packet(0x52526858, 50000, player.id, acknowledgement)}, packets...) - } + packets = append([][]byte{n3Packet(0x52526858, 50000, player.id, acknowledgement)}, packets...) server.mutex.Unlock() for _, packet := range packets { if err := client.send(packet); err != nil { diff --git a/server/ranged_test.go b/server/ranged_test.go @@ -111,7 +111,7 @@ func TestRangedFailedShotSaveLeavesDamageAndAmmoUnchanged(t *testing.T) { func TestReloadTransfersRoundsAtomicallyAndRestoresItsDeadline(t *testing.T) { world, conn := newRangedWorld(t) - request := characterActionPacket(1, [5]uint32{106})[20:] + request := explicitReloadRequest(1, 64, 1) before := time.Now() err := world.handleReload(world.clients[1], request) @@ -124,7 +124,7 @@ func TestReloadTransfersRoundsAtomicallyAndRestoresItsDeadline(t *testing.T) { if restarted.characters[1].rechargeUntil.Before(before.Add(1250*time.Millisecond)) || restarted.characters[1].rechargeUntil.After(time.Now().Add(1250*time.Millisecond)) { t.Fatal("reload deadline did not survive restart") } - if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x26515e61 || !bytes.Equal(conn.packets[0][29:57], []byte{0, 0, 0, 104, 0, 0, 0, 48, 0, 0, 0xc7, 0x4a, 0, 0, 0, 1, 0, 0, 0, 83, 0, 0, 0, 20, 0, 0, 0, 0}) { + if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x26515e61 || !bytes.Equal(conn.packets[1][29:57], []byte{0, 0, 0, 104, 0, 0, 0, 48, 0, 0, 0xc7, 0x4a, 0, 0, 0, 1, 0, 0, 0, 83, 0, 0, 0, 20, 0, 0, 0, 0}) { t.Fatalf("reload wire fields: %x", conn.packets) } } @@ -136,7 +136,7 @@ func TestReloadPausesRemainingRechargeBeforeAnotherAttack(t *testing.T) { next, recharge := world.characters[1].nextAttack, world.characters[1].rechargeUntil health := world.characters[1000000].health - err := world.handleReload(world.clients[1], characterActionPacket(1, [5]uint32{106})[20:]) + err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)) world.advanceCombat(next) world.advanceCombat(next.Add(1250*time.Millisecond - time.Nanosecond)) @@ -152,13 +152,13 @@ func TestReloadUsesOnlyAvailableRoundsAndRemovesAnEmptyStack(t *testing.T) { t.Fatal(err) } - err := world.handleReload(world.clients[1], characterActionPacket(1, [5]uint32{106})[20:]) + err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)) restarted := newTestInventoryServer(t) if err != nil || len(restarted.characters[1].inventory.Items) != 1 || restarted.characters[1].inventory.Items[0].Ammo != 8 || len(restarted.items) != 1 { t.Fatal("partial reload lost or created ammunition", err) } - if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 0 || binary.BigEndian.Uint32(conn.packets[0][49:53]) != 8 || binary.BigEndian.Uint32(conn.packets[0][53:57]) != 1 { + if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[1][45:49]) != 0 || binary.BigEndian.Uint32(conn.packets[1][49:53]) != 8 || binary.BigEndian.Uint32(conn.packets[1][53:57]) != 1 { t.Fatalf("empty-stack reply: %x", conn.packets) } } @@ -210,7 +210,7 @@ func TestReloadRestartsAnInterruptedAttackAfterItsDelay(t *testing.T) { attack, _ := world.characters[1].attackDelays() health := world.characters[1000000].health - err := world.handleReload(world.clients[1], characterActionPacket(1, [5]uint32{106})[20:]) + err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)) ready := world.clients[1].reloadUntil world.advanceCombat(ready.Add(attack - time.Nanosecond)) before := world.characters[1000000].health @@ -279,7 +279,7 @@ func TestReloadFailedTransactionKeepsBothSidesAndDeadline(t *testing.T) { t.Fatal(err) } - err := world.handleReload(world.clients[1], characterActionPacket(1, [5]uint32{106})[20:]) + err := world.handleReload(world.clients[1], explicitReloadRequest(1, 64, 1)) restarted := newTestInventoryServer(t) if err == nil || len(conn.packets) != 0 || world.characters[1].inventory.Items[0].Ammo != 3 || world.characters[1].inventory.Items[1].Count != 100 || !world.characters[1].rechargeUntil.IsZero() || !world.clients[1].reloadUntil.IsZero() { diff --git a/server/stacks.go b/server/stacks.go @@ -17,7 +17,10 @@ func (server *server) changeStack_locked(client *worldClient, index int, body [] items := inventory.Items bag := uint32(0) first, end := uint32(64), uint32(94) - if binary.BigEndian.Uint32(body[20:24]) == 107 { + page := binary.BigEndian.Uint32(body[20:24]) + if page == 105 { + items, first, end = inventory.Bank, 0, bankCapacity + } else if page == 107 { bag = client.backpacks[binary.BigEndian.Uint32(body[24:28])>>16].id items, first, end = inventory.Containers[bag], 0, 21 } @@ -32,7 +35,7 @@ func (server *server) changeStack_locked(client *worldClient, index int, body [] return nil } if binary.BigEndian.Uint32(body[28:32]) != 0 || retained == 0 || retained > uint32(items[index].Count) { - return server.syncStackPage_locked(client, bag) + return server.syncStackPage_locked(client, page, bag) } var slot uint32 for slot = first; slot < end; slot++ { @@ -41,7 +44,7 @@ func (server *server) changeStack_locked(client *worldClient, index int, body [] } } if slot == end { - return server.syncStackPage_locked(client, bag) + return server.syncStackPage_locked(client, page, bag) } if server.nextItem == ^uint32(0) { return fmt.Errorf("item identities exhausted") @@ -76,7 +79,9 @@ func (server *server) changeStack_locked(client *worldClient, index int, body [] } // Publish quantities and any new identity only after one atomic inventory save. - if bag == 0 { + if page == 105 { + inventory.Bank = items + } else if bag == 0 { inventory.Items = items } else { inventory.Containers = maps.Clone(inventory.Containers) @@ -89,7 +94,10 @@ func (server *server) changeStack_locked(client *worldClient, index int, body [] return client.send(n3Packet(0x5e477770, 50000, client.id, body[16:])) } -func (server *server) syncStackPage_locked(client *worldClient, bag uint32) error { +func (server *server) syncStackPage_locked(client *worldClient, page, bag uint32) error { + if page == 105 { + return client.send(bankInventoryPacket(server.characters[client.id])) + } if bag == 0 { return server.syncStacks_locked(client) } diff --git a/server/state.go b/server/state.go @@ -83,6 +83,7 @@ type worldClient struct { reclaimItems []uint32 backpacks map[uint32]backpackHandle shop *shopTrade + bank *bankSession useSequence uint32 selectedTarget [2]uint32 teamInvitation *teamInvitation diff --git a/server/target_protocol.go b/server/target_protocol.go @@ -135,7 +135,7 @@ func targetPacket(packet []byte) []byte { if (action == 52 || action == 53 || action == 112) && binary.BigEndian.Uint32(packet[40:44]) == 104 { binary.BigEndian.PutUint32(packet[44:48], binary.BigEndian.Uint32(packet[44:48])-16) } - if action == 53 && binary.BigEndian.Uint32(packet[48:52]) == 104 { + if (action == 46 || action == 53) && binary.BigEndian.Uint32(packet[48:52]) == 104 { binary.BigEndian.PutUint32(packet[52:56], binary.BigEndian.Uint32(packet[52:56])-16) } case 0x54111123: diff --git a/server/world.sql b/server/world.sql @@ -194,17 +194,20 @@ CREATE TABLE IF NOT EXISTS items ( CREATE TABLE IF NOT EXISTS item_locations ( item_id INTEGER PRIMARY KEY REFERENCES items(id), player_id INTEGER REFERENCES players(id), + bank_player_id INTEGER REFERENCES players(id), backpack_id INTEGER REFERENCES items(id), corpse_id INTEGER REFERENCES npcs(id), slot INTEGER NOT NULL, reclaim_at TEXT, - CHECK ((player_id IS NOT NULL) + (backpack_id IS NOT NULL) + (corpse_id IS NOT NULL) = 1), + CHECK ((player_id IS NOT NULL) + (bank_player_id IS NOT NULL) + (backpack_id IS NOT NULL) + (corpse_id IS NOT NULL) = 1), CHECK ((player_id IS NOT NULL AND slot BETWEEN 1 AND 93) OR + (bank_player_id IS NOT NULL AND slot BETWEEN 0 AND 101) OR (backpack_id IS NOT NULL AND slot BETWEEN 0 AND 20) OR (corpse_id IS NOT NULL AND slot >= 0)), CHECK (reclaim_at IS NULL OR (player_id IS NOT NULL AND slot BETWEEN 64 AND 93)) ); CREATE UNIQUE INDEX IF NOT EXISTS player_slots ON item_locations(player_id, slot) WHERE reclaim_at IS NULL; +CREATE UNIQUE INDEX IF NOT EXISTS bank_slots ON item_locations(bank_player_id, slot); CREATE UNIQUE INDEX IF NOT EXISTS backpack_slots ON item_locations(backpack_id, slot); CREATE UNIQUE INDEX IF NOT EXISTS corpse_slots ON item_locations(corpse_id, slot); CREATE TABLE IF NOT EXISTS chat_history ( diff --git a/server/world_actions.go b/server/world_actions.go @@ -137,6 +137,9 @@ func (server *server) handleMovement(client *worldClient, body []byte) error { } // Locomotion interrupts an admitted cast; rotation-only updates do not. updates := make(map[*worldClient][][]byte) + if client.bank != nil && !server.bankAvailable_locked(client) { + updates[client] = append(updates[client], characterActionPacket(client.id, [5]uint32{106})) + } action := binary.BigEndian.Uint32(body[16:20]) if character.position != previousPosition || action == 1 || action == 3 || action == 5 || action == 7 || action == 13 { server.abortNano_locked(client, client.movementStarted, updates) diff --git a/tools/data/extract_banks.py b/tools/data/extract_banks.py @@ -0,0 +1,56 @@ +import hashlib +import json +import pathlib +import struct + +import ao_database + + +def main(): + client = pathlib.Path('anarchy-vanilla-14.9.1') + assert (client / 'version.id').read_text().strip() == '14.9.1' + database = ao_database.Database(client) + terminals = {} + records = [] + + # Original statels carry identity, transform, template and counted scripts. + for kind, playfield in sorted(database.records): + if kind != 1000026: + continue + payload = database.read(kind, playfield) + offset = 4 + for ordinal in range(struct.unpack_from('<I', payload)[0]): + size = struct.unpack_from('<I', payload, offset)[0] + offset += 4 + raw = payload[offset:offset + size] + offset += size + assert len(raw) == size + if size < 64 or struct.unpack_from('<I', raw, 56)[0] != 116807: + continue + identity_type, identity = struct.unpack_from('<II', raw) + assert identity_type == 51005 and identity not in terminals + assert struct.unpack_from('<I', raw, 60)[0] == size - 64 + assert raw[64:] == struct.pack('>5I', 102, 103, 1009, 0, 0) + terminals[identity] = dict(playfield=playfield, position=list(struct.unpack_from('<3f', raw, 24))) + records.append(dict(playfield=playfield, ordinal=ordinal, identity=identity, + raw_hex=raw.hex(), sha256=hashlib.sha256(raw).hexdigest(), + resource_sha256=hashlib.sha256(payload).hexdigest())) + assert offset == len(payload) + database.close() + + # Retain only the location needed to authorize an actual terminal use. + lines = ['# Generated from original 14.9.1 statels by extract_banks.py.'] + for identity, terminal in sorted(terminals.items()): + lines.extend([f'{identity}:', f' playfield: {terminal["playfield"]}', + f' position: {json.dumps(terminal["position"])}']) + output = pathlib.Path('server/gamedata/banks.yaml') + output.write_text('\n'.join(lines) + '\n') + report = pathlib.Path('local/bank-research/placements.json') + report.parent.mkdir(parents=True, exist_ok=True) + report.write_text(json.dumps(dict(index_sha256=hashlib.sha256(database.index).hexdigest(), + records=records), indent=2) + '\n') + print(f'{output}: {len(terminals)} terminals') + + +if __name__ == '__main__': + main()