commit efedefe5ffce46d0971b081f3270975fca698122
parent f9f283a91e79c063db1ff1a97e7bee188c721a1a
Author: anon <anon@example.com>
Date: Thu, 22 Oct 2026 03:30:53 +0000
Persist owned inventory items and handle native deletion
Diffstat:
12 files changed, 882 insertions(+), 7 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -27,6 +27,8 @@ Back up `data/` when moving servers. Paths are relative to the working directory
Each `data/players/<id>/` directory contains `player.yaml` for identity,
credentials and character properties, `position.yaml` for the current playfield,
coordinates, rotation and return-door context, and the player's chat files.
+Owned items are saved separately in `inventory.yaml`; see
+[inventory behavior](docs/inventory.md) for the current scope and wire evidence.
Movement updates memory immediately. Changed positions are saved to
`position.yaml` every 20 seconds on a fixed schedule with a random offset per
player. The scheduler checks once per second; stationary players cause no writes.
diff --git a/TODO.md b/TODO.md
@@ -0,0 +1,366 @@
+# Game feature TODO
+
+Target: classic Anarchy Online 14.9.1. Keep verified historical rules separate
+from provisional balance values.
+
+Each checkbox is a milestone with a concrete completion check. Sections group
+related work; they are not batches that must be finished together. If one change
+naturally completes several milestones, verify and check off all of them rather
+than artificially limiting the implementation.
+
+Suggested early route: one inventory item -> one equipped melee weapon -> one
+lootable corpse -> kill XP -> creature respawn -> player resurrection.
+Backpacks, implants and advanced weapons are not prerequisites for this loop.
+Test fixtures can supply items and encounters before shops and rewards exist;
+no extra player-facing provisioning system is needed just for testing.
+
+## Inventory basics
+
+- [x] Show one owned item in the native inventory. Check: a fixture grants one
+ nonstacking item with the correct template, QL and slot; it remains after
+ reconnect and server restart.
+- [ ] Move an item to an empty inventory slot. Check: the native drag/drop move
+ survives reconnect without changing its identity or creating another copy.
+- [x] Delete an inventory item. Check: it disappears permanently and another
+ character cannot delete it by supplying its identity.
+- [x] Handle a full inventory. Check: a grant or pickup fails without losing
+ the source item or overwriting an occupied slot.
+
+Inventory persistence, protocol evidence and the remaining visual-order gap are
+recorded in [inventory behavior](docs/inventory.md).
+
+## Stacks and backpacks
+
+- [ ] Merge one stackable item type. Check: compatible stacks combine up to the
+ applicable limit without changing the total item count.
+- [ ] Split a stack. Check: splitting a known quantity produces two persistent
+ stacks with the same combined count; invalid quantities change nothing.
+- [ ] Open one empty backpack. Check: an owned backpack opens its native
+ container window with the correct capacity.
+- [ ] Put one item into a backpack and take it out. Check: its location and the
+ backpack contents survive reconnect and restart, with no duplicate item.
+- [ ] Enforce container placement rules. Check: full bags and prohibited nesting
+ are rejected without losing items; permitted moves match recovered rules.
+
+## Equipment, one kind at a time
+
+- [ ] Equip and unequip one melee weapon. Check: its appearance and base attack
+ data replace fists; unequipping restores fists, including for another observer.
+- [ ] Enforce that weapon's requirements. Check: a character below one required
+ skill cannot equip it, while a qualifying character can.
+- [ ] Equip one armor piece. Check: the correct native slot and appearance
+ update, and its armor stats appear and disappear with equip/unequip.
+- [ ] Apply one equipment stat bonus. Check: a known bonus affects derived stats
+ exactly once and unequipping restores the baseline.
+- [ ] Combine two equipment bonuses to the same stat. Check: removing either
+ item leaves precisely the other item's contribution.
+- [ ] Equip one implant. Check: its slot, treatment/ability requirements and
+ bonuses work independently of armor and weapon slots.
+- [ ] Equip one belt. Check: the corresponding deck slots become available and
+ invalid belt removal cannot strand installed equipment.
+- [ ] Install one NCU memory. Check: available NCU changes by the item's amount
+ and remains correct after reconnect and removal.
+- [ ] Apply overequipping rules to one weapon. Check: dropping below a verified
+ requirement threshold changes effectiveness at the correct boundary.
+
+## Combat calculations
+
+- [ ] Resolve hit versus miss. Check: controlled test rolls produce the matching
+ native outcomes; a miss does not reduce health.
+- [ ] Resolve a critical hit. Check: a known weapon and controlled roll produce
+ the expected critical damage and client feedback.
+- [ ] Apply armor to one damage type. Check: known armor/damage inputs produce
+ sourced results, including the minimum-damage boundary.
+- [ ] Select armor by damage type. Check: changing only the attack's damage type
+ selects the corresponding protection rather than a universal armor value.
+- [ ] Scale one weapon's damage with attack rating. Check: fixed stats and rolls
+ match documented expected amounts at representative boundaries.
+- [ ] Select Martial Arts fist QL from skill. Check: known MA values select the
+ evidenced template/QL and change damage without equipping a weapon.
+- [ ] Replace the approximate melee range check. Check: two actors at known
+ positions and sizes are accepted or rejected at the recovered range boundary.
+- [ ] Reject attacks through one solid obstruction. Check: the same stationary
+ encounter works in the open and fails with a wall between the actors.
+
+## Additional weapon actions
+
+- [ ] Fire one ranged weapon with a loaded magazine. Check: it attacks outside
+ melee range, uses its own timing and consumes one round per applicable shot.
+- [ ] Stop firing when the magazine is empty. Check: an empty weapon cannot
+ continue dealing damage or create ammunition on reconnect.
+- [ ] Reload that weapon. Check: compatible inventory ammunition fills the
+ magazine after the correct delay and the total round count is conserved.
+- [ ] Implement one melee special. Check: a suitable weapon/character can use
+ the action once, with native feedback and an enforced skill lock.
+- [ ] Implement one ranged special. Check: its damage, ammunition use and lock
+ match the chosen action; repeated requests cannot bypass the lock.
+- [ ] Dual wield one verified weapon pair. Check: the actor's shared scheduling
+ matches expected attack/recharge ordering without independent timer exploits.
+- [ ] Swap a weapon during combat. Check: swapping cannot bypass an existing
+ recharge or leave results queued for a removed weapon.
+
+## NPC profiles and behavior
+
+- [ ] Give one creature at one level an explicit combat profile. Check: its
+ health, weapon and timing come from that profile rather than universal values;
+ each value is identified as verified or provisional.
+- [ ] Give that species a second level. Check: the two levels have independently
+ checked resources and combat values rather than an assumed scaling formula.
+- [ ] Add a second species with different behavior or equipment. Check: changing
+ one species' profile does not change the other species.
+- [ ] Pursue a target across open ground. Check: an engaged creature follows a
+ moving player and resumes attacks only when in range.
+- [ ] Return a creature home after pursuit ends. Check: it disengages, returns
+ to its home area and can participate in a new encounter.
+- [ ] Give one hostile creature proximity aggression. Check: an eligible nearby
+ player is attacked while an ineligible or out-of-range player is not.
+- [ ] Switch targets using damage threat. Check: a controlled two-player fight
+ selects the expected target and removes disconnected targets.
+- [ ] Navigate around one simple obstacle. Check: a pursuing creature takes a
+ valid route around a wall rather than walking through it.
+- [ ] Recover NPC resources outside combat. Check: one profile follows an
+ evidenced recovery/reset policy without healing twice on disengagement.
+
+## Death and recovery
+
+- [ ] Respawn one creature. Check: after the profile's respawn interval, exactly
+ one living replacement appears with fresh resources and no old fight state.
+- [ ] Resurrect a player through the native flow. Check: death leads to a valid
+ resurrection location and usable character without reloading the browser.
+- [ ] Save a resurrection location. Check: using one save terminal persists the
+ location and a later death returns the character there.
+- [ ] Reclaim items after death. Check: the applicable items move to reclaim and
+ can be recovered once, including after reconnect.
+- [ ] Apply the classic insurance/XP-loss policy. Check: recorded before/after
+ XP and save-point cases match the documented 14.9.1 rule.
+
+## Loot and credits
+
+- [ ] Open a corpse containing one fixed item. Check: the native loot window
+ shows that item's identity and QL.
+- [ ] Take that corpse item. Check: it moves into inventory, disappears from the
+ corpse and remains owned after restart.
+- [ ] Resolve simultaneous pickup attempts. Check: two clients requesting the
+ same item produce one owner and no duplicate or lost item.
+- [ ] Enforce individual loot rights. Check: the entitled player can loot and
+ an unrelated player cannot; expiry follows an explicit policy.
+- [ ] Award and retain credits. Check: taking a known corpse credit amount
+ changes the balance once and survives reconnect and restart.
+- [ ] Roll loot for one creature profile. Check: controlled rolls select the
+ documented entries and quantities, including an empty result where allowed.
+- [ ] Remove an expired corpse. Check: observers lose the corpse and stale loot
+ requests cannot recover or duplicate its contents.
+
+## Character progression
+
+- [ ] Award XP for one creature kill. Check: the eligible killer gains one known
+ reward exactly once; the total survives restart.
+- [ ] Advance through one level threshold. Check: crossing it updates the native
+ level display and the correct derived resources without a second level-up.
+- [ ] Award IP for that level. Check: the expected amount is granted once and
+ the native unspent-IP value survives reconnect.
+- [ ] Raise one trained skill with IP. Check: the native request spends the
+ correct amount, updates effective skill and persists the base value.
+- [ ] Raise one ability with IP. Check: cost and ability trickle update together
+ without treating the ability as a trained skill.
+- [ ] Enforce one skill/title cap boundary. Check: the final permitted increase
+ succeeds and the next is rejected without spending IP.
+
+## Usable items
+
+- [ ] Use one First Aid item. Check: it restores the expected health, consumes
+ the applicable quantity/charge and cannot be reused during its skill lock.
+- [ ] Use one nano-restoring item. Check: nano recovery, consumption and its lock
+ match that item rather than inheriting the health item's behavior.
+- [ ] Use one sitting treatment kit. Check: it works in the permitted posture
+ and combat state and is rejected outside those conditions without consumption.
+
+## Character creation
+
+- [ ] Choose a breed at creation. Check: the choice persists and the native
+ appearance and derived resource coefficients agree with it.
+- [ ] Choose a profession at creation. Check: profession-dependent starting
+ values and progression use the selected data rather than always Soldier.
+- [ ] Choose a faction at creation. Check: the faction persists and is correctly
+ represented to other clients.
+- [ ] Choose appearance at creation. Check: supported appearance choices survive
+ reconnect and are rendered consistently to another player.
+- [ ] Grant one profession's starter loadout. Check: a new character receives
+ the expected items once; reconnecting does not grant another set.
+
+## Shops
+
+- [ ] Browse one vendor's fixed stock. Check: the native shop window displays
+ the expected items, QLs and prices without transferring ownership.
+- [ ] Buy one item. Check: credits and inventory change together; insufficient
+ credits or space leaves both unchanged.
+- [ ] Sell one inventory item. Check: ownership and credits change once and
+ repeating the request cannot sell the same item twice.
+- [ ] Refresh one vendor's stock. Check: the intended stock policy updates the
+ list without changing an already purchased item's identity or properties.
+
+## Nanos and effects
+
+- [ ] Learn one nano program. Check: consuming its crystal adds a persistent
+ native program entry and cannot learn or consume it twice accidentally.
+- [ ] Cast one self-heal. Check: cast time, nano cost, health gain and recharge
+ agree with the chosen program and appear correctly in the native client.
+- [ ] Cancel an in-progress cast. Check: the applicable cancellation/refund rule
+ is followed and no delayed heal or duplicate result occurs.
+- [ ] Cast one direct-damage program on a creature. Check: target validation,
+ damage and death handling work without starting an unintended weapon attack.
+- [ ] Apply one temporary stat buff. Check: the native effect appears, the stat
+ changes once, and expiration removes exactly that contribution.
+- [ ] Enforce NCU capacity. Check: a buff fitting the available NCU succeeds and
+ one exceeding it is rejected without charging resources incorrectly.
+- [ ] Replace or reject a conflicting buff. Check: one known nano-line pair
+ follows its evidenced stacking rule without retaining both bonuses.
+- [ ] Cancel one active buff manually. Check: its effect, stat contribution and
+ NCU use disappear together.
+- [ ] Apply one damage-over-time effect. Check: the expected number of ticks
+ occurs and stopping/removing the effect prevents further ticks.
+- [ ] Apply one heal-over-time effect. Check: recovery ticks stop at expiration
+ and clamp resources correctly.
+- [ ] Apply one root or snare. Check: movement changes and recovery/break rules
+ agree between the server and native client.
+- [ ] Coordinate a nano with weapon combat. Check: casting, interruption and
+ recharge follow shared action rules without accelerating either action.
+
+## Quests
+
+- [ ] Accept one quest through an existing NPC conversation. Check: the choice
+ creates persistent quest state and a native journal entry.
+- [ ] Complete one kill objective. Check: only the relevant creature advances
+ the objective, including after reconnect.
+- [ ] Hand in one required item. Check: the correct item is consumed only when
+ the quest state permits it; wrong items and repeated requests change nothing.
+- [ ] Claim one quest reward. Check: the reward and completion state persist
+ together and cannot be claimed twice.
+- [ ] Advance one quest to a second stage. Check: dialogue and available actions
+ change with the saved stage rather than resetting on a new conversation.
+
+## Missions
+
+- [ ] Browse one mission terminal offer. Check: its native details and location
+ render correctly without accepting it automatically.
+- [ ] Accept that mission. Check: its journal entry and assigned destination
+ survive reconnect.
+- [ ] Enter and leave one fixed mission interior. Check: the assigned door
+ selects the right instance and returns the player to the right entrance.
+- [ ] Complete one mission objective. Check: a chosen target or object completes
+ the mission once, with the expected reward.
+- [ ] Abandon that mission. Check: its journal entry and private assignment are
+ removed without affecting another character's mission.
+- [ ] Generate one two-room mission layout. Check: a fixed test seed produces
+ connected rooms with a reachable entrance, objective and exit.
+
+## Teams
+
+- [ ] Form a two-player team. Check: invitation and acceptance update both native
+ team windows; declining does not add a member.
+- [ ] Leave a team voluntarily. Check: both native team windows reflect the
+ departure and leadership transfers correctly if the leader leaves.
+- [ ] Remove a team member as leader. Check: a leader can remove a member and
+ an ordinary member cannot remove another player.
+- [ ] Handle a team member disconnecting. Check: the documented membership and
+ leadership policy is applied without stale UI entries or duplicate membership.
+- [ ] Replicate team resources. Check: a teammate's health/nano display updates
+ correctly without spawning unrelated actors or exposing private inventory.
+- [ ] Share XP from one team kill. Check: a controlled encounter awards the
+ expected shares once and excludes ineligible members.
+- [ ] Apply one team loot policy. Check: a known two-player loot sequence follows
+ that policy while unrelated players remain excluded.
+
+## Travel
+
+- [ ] Enable one verified whom-pah route. Check: its trigger reaches the intended
+ destination and cannot immediately bounce the player back unintentionally.
+- [ ] Enter the Grid through one access point. Check: eligibility is enforced
+ and the native client arrives in the correct playfield.
+- [ ] Leave the Grid through one exit. Check: the exit's requirements and
+ destination are correct and the character remains usable after reconnect.
+- [ ] Use one ground vehicle. Check: equipping/using it changes movement speed
+ under the applicable requirements and ending use restores ordinary movement.
+- [ ] Use one flying vehicle. Check: altitude and movement modes replicate to an
+ observer and zoning does not leave the character stuck in the wrong mode.
+- [ ] Resolve one currently unmapped door. Check: source evidence identifies its
+ eligibility and destination, and a real client can make the round trip.
+
+## Pets
+
+- [ ] Summon one pet. Check: one owned entity appears to its owner and an
+ observer; repeated requests follow the applicable pet-count limit.
+- [ ] Make the pet follow. Check: it follows its owner across a simple route
+ without changing another player's pet.
+- [ ] Make the pet wait. Check: it stays at the commanded position while its
+ owner moves, until another valid command changes its behavior.
+- [ ] Order the pet to attack. Check: it validates the target and begins combat
+ on its own action schedule.
+- [ ] Stop a pet's attack. Check: the stop command clears combat and queued
+ actions according to the recovered behavior.
+- [ ] Handle pet death. Check: death removes the applicable ownership state and
+ stale commands cannot act on a replacement pet.
+- [ ] Dismiss a pet. Check: only its owner can dismiss it and observers lose
+ the entity exactly once.
+- [ ] Expire a timed pet. Check: its lifetime ends at the expected point without
+ removing a newer pet or allowing another queued attack.
+- [ ] Handle the pet owner's disconnect. Check: the documented pet lifecycle
+ policy runs without leaving an active attack on an unavailable owner/target.
+- [ ] Give one healing pet a heal command. Check: it heals an eligible target
+ on its own action schedule rather than behaving as a combat pet.
+
+## Player trading and tradeskills
+
+- [ ] Open a two-player trade. Check: both native windows refer to the correct
+ participants and offered items remain unavailable for conflicting transfers.
+- [ ] Complete an item-for-item trade. Check: both confirmations transfer items
+ together; cancellation leaves original ownership unchanged.
+- [ ] Include credits in a trade. Check: credit and item transfers commit
+ together, with no negative balance or repeated transfer.
+- [ ] Combine one tradeskill recipe. Check: valid ingredients and skills produce
+ the expected result QL; failure preserves the applicable inputs.
+- [ ] Add one implant-building recipe. Check: the chosen cluster/implant pair
+ produces the evidenced requirements, bonuses and QL result.
+
+## Faction and PvP
+
+- [ ] Replicate suppression-gas rules for one area. Check: the native area state
+ and attack eligibility agree inside, outside and across its boundary.
+- [ ] Resolve one permitted player-versus-player attack. Check: the applicable
+ damage rule is used and protected targets remain unharmed.
+- [ ] Apply one faction guard's hostility rules. Check: an eligible enemy is
+ attacked while a friendly player is not.
+- [ ] Apply one evidenced PvP reward or penalty. Check: a controlled encounter
+ changes the relevant state once and leaves PvE progression unchanged.
+
+## Organizations and social features
+
+- [ ] Persist a friend-list entry. Check: adding/removing a friend survives
+ reconnect and the appropriate online-status updates reach the owner.
+- [ ] Ignore one player. Check: the supported chat channels honor the saved
+ ignore entry and removing it restores delivery.
+- [ ] Create one organization. Check: its name, identity and founder membership
+ survive restart.
+- [ ] Invite an organization member. Check: accepting a valid invitation creates
+ persistent membership; declining does not add the player.
+- [ ] Remove an organization member. Check: an authorized member can remove the
+ target, an unauthorized member cannot, and the change survives reconnect.
+- [ ] Change one organization's member rank. Check: the rank persists and the
+ affected permission changes without granting unrelated privileges.
+- [ ] Deliver organization chat. Check: members receive it, nonmembers do not,
+ and a slow member cannot stall other recipients.
+
+## Checks that apply to each milestone
+
+- Exercise the native client path, not only a server helper or admin edit.
+- Persist durable state as part of the feature; verify reconnect and restart.
+- Reject invalid, stale and repeated requests without unintended state changes.
+- Use two clients for shared ownership, visibility or encounter behavior.
+- Keep socket writes and transport shutdown outside shared server work.
+- Record the source and expected cases for historical rules. A bounded research
+ milestone can precede a behavior change when its formula or protocol is unknown.
+
+Current implementation coverage and research gaps are recorded in the
+[combat reconstruction](docs/combat-client-reconstruction.md),
+[NPC conversation notes](docs/npc-scripts.md), and
+[developer guide](DEVELOPERS.md).
diff --git a/docs/inventory.md b/docs/inventory.md
@@ -0,0 +1,88 @@
+# Inventory behavior and 14.9.1 evidence
+
+The server persists individual owned items in
+`data/players/<owner>/inventory.yaml`, separately from the editable character
+profile. Each item has an instance ID, native identity type, exact template,
+quality and logical inventory slot. The first fixture uses QL 1 Solar-Powered
+Pistol, template 121567, identity type 51018. Players do not receive a fixture
+item automatically.
+
+The ordinary inventory has 30 logical slots, 64 through 93. Grants choose an
+empty slot and return failure when all are occupied. Inventory changes use the
+existing atomic file replacement and become visible in memory after the save
+succeeds. A persisted last-issued ID preserves the allocation high-water mark,
+including after deleting the last item. Startup takes the maximum across owners.
+Profile edits and zoning preserve inventory independently of profile fields.
+
+Only individual items at an exact catalog quality are supported. Template
+endpoints are identical; arbitrary-quality interpolation, stacks, backpacks,
+equipment, loot and starter loadouts remain separate milestones.
+
+## Native messages
+
+`FullCharacter` (`0x29304349`, version 16) begins with the owned-item list. Its
+encoded length is `(items + 1) * 1009`. Each entry has these network-order fields:
+
+| Field | Size | Initial individual-item value |
+| --- | --- | --- |
+| Logical slot | 4 | 64 through 93 |
+| Entry flags | 2 | 2 |
+| Count | 2 | 1 |
+| Instance type and ID | 8 | Template type and persistent server ID |
+| Low and high template | 8 | Same exact template ID |
+| Quality | 4 | Catalog quality |
+| Auxiliary value | 4 | 0 |
+
+The maintained client source establishes the 32-byte wire entry:
+`client/game/kkr.dll/lifted-0037.c`, `sub_3607F5B0` reads the first list through
+`sub_3602DBA0`; `client/game/kkr.dll/lifted-0017.c`, `sub_3602DC40` reads the
+two shorts, identity and template information. `sub_360011B0` in
+`client/game/kkr.dll/lifted-0000.c` reads the final four integers.
+The 14.9.1 conversion inserts its seventh list after the variable-length
+inventory, rather than at an offset valid only for an empty list. Flag 2 was
+verified with the native WASM icon, tooltip and QL 1 details window.
+
+`ContainerAddItem` (`0x47537a24`) carries source page/slot, target owner identity
+and destination slot. The server accepts only an authenticated current session's
+own ordinary inventory and an empty destination. It saves before acknowledging
+the move. Equipment and cross-owner/container transfers are rejected. This
+layout is corroborated by the local AOtomation `ContainerAddItemMessage` and
+CellAO `ContainerAddItemMessageHandler` reference sources; it is not the message
+used by the native same-window visual rearrangement described below.
+
+The captured 14.9.1 `CharacterAction` (`0x5e477770`) delete payload is exactly
+five integers: action 112, page 104, logical slot, low template and high template.
+It has no intervening unknown field or trailing short from the newer AOtomation
+`CharacterActionMessage` schema. The native held-right-click menu, delete icon
+and confirmation emit this packet. The server checks the session, owner, page,
+occupied slot and both templates, saves the deletion, then echoes the action.
+Repeated requests for the now-empty slot do nothing.
+
+## Visual order remains a separate client concern
+
+The shipped `cd_image/text/help/The Inventory Window.txt` documents left-click
+pickup/place, Shift-left-click inspection and held-right-click deletion. Manual
+WASM testing confirms that picking up an item and placing it elsewhere in the
+same window rearranges its visual cell without sending a server move request.
+Its logical server slot remains unchanged. `browser_initialize` in
+`client/runtime/browser_host.c` currently copies native preferences into a
+private in-memory filesystem on every startup. Visual ordering therefore resets
+on browser reload. The TODO's native move/reconnect milestone remains open until
+that client preference persistence is implemented and verified.
+
+## Verification
+
+`server/inventory_test.go` exercises native initialization and a captured native
+delete request through the world connection, plus restart persistence, explicit
+logical moves, ID allocation across owners, profile edits, invalid/foreign/stale
+requests, full inventory and disk-write failure. Foreign owner requests are
+rejected even when the caller has an item at the same slot. No live socket write
+is performed by the inventory handler; acknowledgements use the connection's
+existing FIFO output queue.
+
+Manual WASM evidence is retained locally under `local/inventory-smoke/`: QL 1
+details, native rearrangement, held menu, confirmation, deletion and packet logs.
+The isolated fixture grants one pistol before native world initialization.
+Deletion was checked after reload, and a second simultaneous WASM visitor showed
+only its own pistol while the first visitor's inventory stayed empty. The
+browser driver closes its contexts and temporary server in `finally`.
diff --git a/docs/items.md b/docs/items.md
@@ -105,10 +105,11 @@ silently omitting a definition.
## Definitions versus owned items
-A definition is not an owned item. A future inventory needs persistent instance
-identity, owner/container, slot, quantity and quality, plus the definition IDs
-used to derive its properties. CellAO's `Item` constructor takes **quality,
-low template ID and high template ID**, and its item implementation interpolates
+A definition is not an owned item. The [initial inventory](inventory.md) persists
+instance identity, owner, slot and exact-template quality for individual items.
+Stacks, containers and interpolated qualities remain separate milestones.
+CellAO's `Item` constructor takes **quality, low template ID and high template
+ID**, and its item implementation interpolates
properties between the templates. Consequently, one row per extracted ID is
not sufficient to represent every possible quality level.
diff --git a/server/control.go b/server/control.go
@@ -234,6 +234,7 @@ func (server *server) updateUser_locked(destination userData) error {
}
previousPlayfield := character.playfield
updated := destination.character()
+ updated.inventory = character.inventory
updated.browserTokenHash = character.browserTokenHash
updated.savedProfile = character.savedProfile
updated.savedPosition = character.savedPosition
diff --git a/server/inventory.go b/server/inventory.go
@@ -0,0 +1,130 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "fmt"
+ "slices"
+
+ "go.yaml.in/yaml/v3"
+)
+
+type ownedItem struct {
+ ID uint32 `yaml:"id"`
+ Type uint32 `yaml:"type"`
+ Template uint32 `yaml:"template"`
+ Quality uint32 `yaml:"quality"`
+ Slot uint32 `yaml:"slot"`
+}
+
+type playerInventory struct {
+ LastID uint32 `yaml:"last_id"`
+ Items []ownedItem `yaml:"items"`
+}
+
+func (inventory playerInventory) validate() error {
+ ids := make(map[uint32]bool)
+ slots := make(map[uint32]bool)
+ for _, item := range inventory.Items {
+ if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] ||
+ item.Slot < 64 || item.Slot >= 94 || slots[item.Slot] {
+ return fmt.Errorf("invalid inventory item identity or slot")
+ }
+ ids[item.ID], slots[item.Slot] = true, true
+ }
+ return nil
+}
+
+func (server *server) saveInventory_locked(character *character, inventory playerInventory) error {
+ contents, err := yaml.Marshal(inventory)
+ if err != nil {
+ return err
+ }
+ if err := writeFileAtomic(fmt.Sprintf("data/players/%d/inventory.yaml", character.id), contents, 0600); err != nil {
+ return err
+ }
+ character.inventory = inventory
+ return nil
+}
+
+func (server *server) grantItem_locked(character *character, template uint32) (bool, error) {
+ // Start with exact catalog qualities; arbitrary QL interpolation is separate.
+ var definition *gamedata.Item
+ for index := range gamedata.Items.Items {
+ if gamedata.Items.Items[index].ID == template {
+ definition = &gamedata.Items.Items[index]
+ break
+ }
+ }
+ if definition == nil || definition.RecordType != 1000020 || definition.Quality == nil {
+ return false, fmt.Errorf("unknown item template %d", template)
+ }
+ var slot uint32
+ for slot = 64; slot < 94; slot++ {
+ if !slices.ContainsFunc(character.inventory.Items, func(item ownedItem) bool { return item.Slot == slot }) {
+ break
+ }
+ }
+ if slot == 94 {
+ return false, nil
+ }
+ if server.nextItem == ^uint32(0) {
+ return false, fmt.Errorf("item identities exhausted")
+ }
+
+ // Publish the new identity only after the complete inventory reaches disk.
+ inventory := playerInventory{LastID: server.nextItem + 1, Items: slices.Clone(character.inventory.Items)}
+ inventory.Items = append(inventory.Items, ownedItem{inventory.LastID, definition.HeaderWords[0], template, *definition.Quality, slot})
+ if err := server.saveInventory_locked(character, inventory); err != nil {
+ return false, err
+ }
+ server.nextItem = inventory.LastID
+ return true, nil
+}
+
+func (server *server) handleInventory(client *worldClient, body []byte) error {
+ key := binary.BigEndian.Uint32(body)
+ if len(body) != 36 {
+ return fmt.Errorf("invalid inventory message length")
+ }
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ character := server.characters[client.id]
+ if server.clients[client.id] != client || !client.ready || client.loading || character.health == 0 ||
+ binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id {
+ return nil
+ }
+
+ // Only this character's ordinary inventory page is supported here.
+ sourceType, sourceSlot := binary.BigEndian.Uint32(body[16:20]), binary.BigEndian.Uint32(body[20:24])
+ if key == 0x5e477770 {
+ sourceType, sourceSlot = binary.BigEndian.Uint32(body[20:24]), binary.BigEndian.Uint32(body[24:28])
+ }
+ index := slices.IndexFunc(character.inventory.Items, func(item ownedItem) bool { return item.Slot == sourceSlot })
+ if sourceType != 104 || index < 0 {
+ return nil
+ }
+ inventory := playerInventory{LastID: character.inventory.LastID, Items: slices.Clone(character.inventory.Items)}
+ if key == 0x47537a24 {
+ destination := binary.BigEndian.Uint32(body[32:36])
+ if binary.BigEndian.Uint32(body[24:28]) != 50000 || binary.BigEndian.Uint32(body[28:32]) != client.id ||
+ destination < 64 || destination >= 94 ||
+ slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.Slot == destination }) {
+ return nil
+ }
+ inventory.Items[index].Slot = destination
+ } else {
+ if binary.BigEndian.Uint32(body[28:32]) != inventory.Items[index].Template ||
+ binary.BigEndian.Uint32(body[32:36]) != inventory.Items[index].Template {
+ return nil
+ }
+ inventory.Items = slices.Delete(inventory.Items, index, index+1)
+ }
+ if err := server.saveInventory_locked(character, inventory); err != nil {
+ return err
+ }
+ // send only enqueues owned packet bytes, never waits for the transport.
+ return client.send(n3Packet(key, 50000, client.id, body[16:]))
+}
diff --git a/server/inventory_test.go b/server/inventory_test.go
@@ -0,0 +1,255 @@
+package main
+
+import (
+ "encoding/binary"
+ "encoding/hex"
+ "net"
+ "os"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func inventoryMovePacket(owner, source, destination uint32) []byte {
+ body := make([]byte, 0, 20)
+ for _, value := range []uint32{104, source, 50000, owner, destination} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x47537a24, 50000, owner, body)
+}
+
+func inventoryDeletePacket(owner, slot uint32) []byte {
+ body := make([]byte, 0, 20)
+ for _, value := range []uint32{112, 104, slot, 121567, 121567} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x5e477770, 50000, owner, body)
+}
+
+func TestInventoryNativeMoveDeleteAndRestart(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world := newTestServer(t)
+ world.newCharacter()
+ if err := world.saveUser_locked(world.characters[1]); err != nil {
+ t.Fatal(err)
+ }
+ granted, err := world.grantItem_locked(world.characters[1], 121567)
+ if err != nil || !granted {
+ t.Fatalf("grant: %v %v", granted, err)
+ }
+ expected := ownedItem{ID: 1, Type: 51018, Template: 121567, Quality: 1, Slot: 64}
+ if !reflect.DeepEqual(world.characters[1].inventory.Items, []ownedItem{expected}) {
+ t.Fatalf("granted item: %+v", world.characters[1].inventory)
+ }
+ world = newTestInventoryServer(t)
+ connect := func() (net.Conn, chan error) {
+ t.Helper()
+ client, connection := net.Pipe()
+ t.Cleanup(func() { client.Close() })
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ done := make(chan error, 1)
+ go func() { defer connection.Close(); done <- world.serveWorldConnection(connection) }()
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
+ binary.BigEndian.PutUint16(cookie, 0xdfdf)
+ client.Write(cookie)
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x29304349 {
+ if hex.EncodeToString(packet[33:69]) != "000007e200000040000200010000c74a000000010001dadf0001dadf0000000100000000" {
+ t.Fatalf("native inventory list: %x", packet[33:69])
+ }
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5f52412e {
+ break
+ }
+ }
+ client.Write(targetPacket(n3Packet(0x570c2039, 50000, 1, nil)))
+ readPacket(client)
+ return client, done
+ }
+ client, done := connect()
+
+ client.Write(targetPacket(inventoryMovePacket(1, 64, 72)))
+ move, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ client.Close()
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ world = newTestInventoryServer(t)
+ expected.Slot = 72
+ if !reflect.DeepEqual(world.characters[1].inventory.Items, []ownedItem{expected}) ||
+ binary.BigEndian.Uint32(move[16:20]) != 0x47537a24 || binary.BigEndian.Uint32(move[45:49]) != 72 {
+ t.Fatalf("move lost item identity or slot: %+v %x", world.characters[1].inventory, move)
+ }
+ // The next connection must initialize using the saved slot.
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ done = make(chan error, 1)
+ go func() { defer connection.Close(); done <- world.serveWorldConnection(connection) }()
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
+ binary.BigEndian.PutUint16(cookie, 0xdfdf)
+ client.Write(cookie)
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x29304349 && binary.BigEndian.Uint32(packet[37:41]) != 72 {
+ t.Fatal("reconnect did not send the moved slot")
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5f52412e {
+ break
+ }
+ }
+ client.Write(targetPacket(n3Packet(0x570c2039, 50000, 1, nil)))
+ readPacket(client)
+ // Captured 14.9.1 delete layout, with the test owner and moved slot.
+ request, err := hex.DecodeString("dfdf000a0001003100000001000000025e4777700000c35000000001000000007000000068000000480001dadf0001dadf000000")
+ if err != nil {
+ t.Fatal(err)
+ }
+ client.Write(request)
+ deleted, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ client.Close()
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ world = newTestInventoryServer(t)
+
+ if len(world.characters[1].inventory.Items) != 0 || world.nextItem != 1 ||
+ binary.BigEndian.Uint32(deleted[29:33]) != 112 {
+ t.Fatalf("deletion did not persist: %+v %x", world.characters[1].inventory, deleted)
+ }
+ if granted, err := world.grantItem_locked(world.characters[1], 121567); err != nil || !granted ||
+ world.characters[1].inventory.Items[0].ID != 2 {
+ t.Fatalf("deleted identity was reused: %+v %v", world.characters[1].inventory, err)
+ }
+}
+
+func newTestInventoryServer(t *testing.T) *server {
+ t.Helper()
+ world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character)}
+ if err := world.loadUsers(); err != nil {
+ t.Fatal(err)
+ }
+ return world
+}
+
+func TestInventoryRejectsForeignOccupiedAndStaleRequests(t *testing.T) {
+ for _, scenario := range []string{"foreign move", "foreign target", "foreign delete", "wrong template", "occupied", "outside", "empty", "replaced", "loading", "repeat move", "repeat delete"} {
+ t.Run(scenario, func(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, conn := newCombatWorld()
+ os.MkdirAll("data/players/1", 0700)
+ world.characters[1].inventory = playerInventory{LastID: 2, Items: []ownedItem{
+ {1, 51018, 121567, 1, 64}, {2, 51018, 121567, 1, 65},
+ }}
+ client := world.clients[1]
+ packet := inventoryMovePacket(1, 64, 72)
+ switch scenario {
+ case "foreign move":
+ packet = inventoryMovePacket(2, 64, 72)
+ case "foreign target":
+ binary.BigEndian.PutUint32(packet[48:52], 2)
+ case "foreign delete":
+ packet = inventoryDeletePacket(2, 64)
+ case "wrong template":
+ packet = inventoryDeletePacket(1, 64)
+ binary.BigEndian.PutUint32(packet[48:52], 121568)
+ case "occupied":
+ packet = inventoryMovePacket(1, 64, 65)
+ case "outside":
+ packet = inventoryMovePacket(1, 64, 94)
+ case "empty":
+ packet = inventoryDeletePacket(1, 72)
+ case "replaced":
+ world.clients[1] = &worldClient{id: 1}
+ case "loading":
+ client.loading = true
+ case "repeat move", "repeat delete":
+ if scenario == "repeat delete" {
+ packet = inventoryDeletePacket(1, 64)
+ }
+ if err := world.handleInventory(client, packet[20:]); err != nil {
+ t.Fatal(err)
+ }
+ conn.packets = nil
+ }
+ before := append([]ownedItem(nil), world.characters[1].inventory.Items...)
+
+ err := world.handleInventory(client, packet[20:])
+
+ if err != nil || !reflect.DeepEqual(before, world.characters[1].inventory.Items) || len(conn.packets) != 0 {
+ t.Fatalf("invalid request changed inventory: %+v %v", world.characters[1].inventory, err)
+ }
+ })
+ }
+}
+
+func TestInventoryFullGrantAndFailedSavePreserveItems(t *testing.T) {
+ t.Chdir(t.TempDir())
+ os.MkdirAll("data/players/1", 0700)
+ world, _ := newCombatWorld()
+ for range 30 {
+ if granted, err := world.grantItem_locked(world.characters[1], 121567); err != nil || !granted {
+ t.Fatalf("grant: %v %v", granted, err)
+ }
+ }
+ before, err := os.ReadFile("data/players/1/inventory.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ granted, err := world.grantItem_locked(world.characters[1], 121567)
+ after, readErr := os.ReadFile("data/players/1/inventory.yaml")
+ os.Remove("data/players/1/inventory.yaml")
+ os.Mkdir("data/players/1/inventory.yaml", 0700)
+ saveErr := world.handleInventory(world.clients[1], inventoryDeletePacket(1, 64)[20:])
+
+ if granted || err != nil || readErr != nil || string(before) != string(after) || saveErr == nil ||
+ len(world.characters[1].inventory.Items) != 30 || world.nextItem != 30 {
+ t.Fatalf("full inventory or failed save lost items: granted=%v err=%v save=%v", granted, err, saveErr)
+ }
+}
+
+func TestInventorySurvivesProfileEditAndKeepsGlobalIdentities(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world := newTestServer(t)
+ for range 2 {
+ player := world.newCharacter()
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted {
+ t.Fatalf("grant: %v %v", granted, err)
+ }
+ }
+ destination := world.characters[1].userData()
+ destination.Name = "Inventory Owner"
+ destination.Playfield = 800
+
+ if err := world.updateUser(destination); err != nil {
+ t.Fatal(err)
+ }
+ live := world.characters[1].inventory.Items
+ world = newTestInventoryServer(t)
+ if granted, err := world.grantItem_locked(world.characters[1], 121567); err != nil || !granted {
+ t.Fatalf("grant after restart: %v %v", granted, err)
+ }
+
+ if len(live) != 1 || live[0].ID != 1 || len(world.characters[1].inventory.Items) != 2 ||
+ world.characters[1].inventory.Items[0].ID != 1 || world.characters[1].inventory.Items[1].ID != 3 ||
+ world.characters[2].inventory.Items[0].ID != 2 || world.characters[1].name != "Inventory Owner" {
+ t.Fatalf("profile edit or restart changed inventory: %+v %+v", world.characters[1].inventory, world.characters[2].inventory)
+ }
+}
diff --git a/server/main.go b/server/main.go
@@ -395,6 +395,10 @@ func (server *server) serveWorldClient(client *worldClient) error {
return fmt.Errorf("N3 message before character initialization")
}
switch binary.BigEndian.Uint32(body[0:4]) {
+ case 0x47537a24:
+ if err := server.handleInventory(client, body); err != nil {
+ return err
+ }
case 0x28494070, 0x4a41203e, 0x76793f0d:
if err := server.handleCombat(client, body); err != nil {
return err
@@ -409,6 +413,10 @@ func (server *server) serveWorldClient(client *worldClient) error {
}
// Acknowledge sitting and standing so the client updates its posture.
switch binary.BigEndian.Uint32(body[16:20]) {
+ case 112:
+ if err := server.handleInventory(client, body); err != nil {
+ return err
+ }
case 86, 87:
if binary.BigEndian.Uint32(body[16:20]) == 87 {
loggingOut = false
diff --git a/server/state.go b/server/state.go
@@ -20,6 +20,7 @@ type character struct {
monsterData uint32
level uint16
stats characterStats
+ inventory playerInventory
health uint32
nano uint32
sitting bool
@@ -76,6 +77,7 @@ type server struct {
// Order entity-state packet batches; acquire before mutex.
updateMutex sync.Mutex
nextCharacter uint32
+ nextItem uint32
characters map[uint32]*character
roamingNPCs map[uint32][]*character
clients map[uint32]*worldClient
diff --git a/server/target_protocol.go b/server/target_protocol.go
@@ -70,8 +70,9 @@ func targetPacket(packet []byte) []byte {
}
case 0x29304349:
// FullCharacter has seven encoded lists before its stats.
- tail := append([]byte(nil), packet[64:]...)
- packet = binary.BigEndian.AppendUint32(packet[:64], 1009)
+ inventoryEnd := 64 + int(binary.BigEndian.Uint32(packet[40:44])/1009-1)*32
+ tail := append([]byte(nil), packet[inventoryEnd:]...)
+ packet = binary.BigEndian.AppendUint32(packet[:inventoryEnd], 1009)
packet = append(packet, tail...)
// kkr.dll FullChar 0x1007f5b0: empty stat map, lists and auxiliary identity.
packet = packet[:len(packet)-20]
diff --git a/server/users.go b/server/users.go
@@ -166,6 +166,20 @@ func (server *server) loadUsers() error {
return fmt.Errorf("duplicate user ID %d", user.ID)
}
server.characters[user.ID] = user.character()
+ inventoryPath := filepath.Join("data/players", file.Name(), "inventory.yaml")
+ contents, err = os.ReadFile(inventoryPath)
+ if err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ if err == nil {
+ if err := decodeUsers(bytes.NewReader(contents), &server.characters[user.ID].inventory); err != nil {
+ return fmt.Errorf("%s: %w", inventoryPath, err)
+ }
+ if err := server.characters[user.ID].inventory.validate(); err != nil {
+ return fmt.Errorf("%s: %w", inventoryPath, err)
+ }
+ server.nextItem = max(server.nextItem, server.characters[user.ID].inventory.LastID)
+ }
server.characters[user.ID].savedProfile = profile
server.characters[user.ID].savedPosition = position
server.characters[user.ID].nextPositionSave = time.Now().Add(time.Duration(rand.Int64N(int64(20 * time.Second))))
diff --git a/server/world.go b/server/world.go
@@ -143,7 +143,14 @@ func characterPacket(character *character) []byte {
func fullCharacterPacket(character *character) []byte {
// Version 16 begins with six encoded lists, followed by four stat lists.
body := binary.BigEndian.AppendUint32(nil, 16)
- for range 6 {
+ // Individual exact-template entries carry flags 2 and count 1.
+ body = binary.BigEndian.AppendUint32(body, uint32(len(character.inventory.Items)+1)*1009)
+ for _, item := range character.inventory.Items {
+ for _, value := range []uint32{item.Slot, 0x00020001, item.Type, item.ID, item.Template, item.Template, item.Quality, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ }
+ for range 5 {
body = binary.BigEndian.AppendUint32(body, 1009)
}
base := character.baseStats()