aorecomp

Anarchy Online classic in the browser

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


commit e85edcdd37aca5828488134d3c8c1c2896eb8764
parent 57cd81362be9a18a498e95b7662f3772ac4a9896
Author: anon <anon@example.com>
Date:   Thu, 22 Oct 2026 14:12:53 +0000

Persist native inventory stacks and restore Ctrl-click splitting

Diffstat:
MDEVELOPERS.md | 5+++--
MTODO.md | 8+++++++-
Mclient/runtime/linux_window.c | 10++--------
Mclient/tests/browser_camera.c | 11++++++-----
Adocs/inventory-stacks.md | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/inventory.md | 10++++++----
Mserver/armor_test.go | 4++--
Mserver/attack_rating_test.go | 2+-
Mserver/corpse_expiry_test.go | 6+++---
Mserver/equipment_test.go | 6+++---
Mserver/inventory.go | 28++++++++++++++++++++++++----
Mserver/inventory_test.go | 4++--
Mserver/loot.go | 2+-
Mserver/loot_test.go | 8++++----
Mserver/main.go | 2+-
Mserver/overequipping_test.go | 2+-
Mserver/reclaim.go | 2+-
Mserver/reclaim_test.go | 26+++++++++++++-------------
Mserver/respawn_test.go | 2+-
Mserver/resurrection_test.go | 2+-
Aserver/stacks.go | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/stacks_test.go | 334+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/target_protocol.go | 12++++++++++--
Mserver/users.go | 11+++++++++++
Mserver/world.go | 8++++++--
25 files changed, 711 insertions(+), 62 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -86,8 +86,9 @@ Opening the same character in another tab disconnects the earlier tab. That tab shows a Reconnect button; clicking it takes the character back. Temporary network interruptions still reconnect automatically. Click the game or press a key to enable sound. -Two-finger scrolling (or a mouse wheel) rotates the browser camera. Right-button -drag and Ctrl-drag also work; the game canvas suppresses the browser context menu. +Two-finger scrolling (or a mouse wheel) and right-button dragging rotate the +browser camera. Ctrl-left-click retains the native inventory split gesture; +the game canvas suppresses the browser context menu. Press Ctrl+Alt+M (Control+Option+M on Mac), or tap Opt on mobile, for player settings. Switch between CSS pixels and Retina pixels while playing; the choice is remembered. Retina uses the screen's pixel density, making the original interface smaller diff --git a/TODO.md b/TODO.md @@ -36,7 +36,7 @@ recorded in [inventory behavior](docs/inventory.md). - [ ] 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 +- [x] 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. @@ -45,6 +45,12 @@ recorded in [inventory behavior](docs/inventory.md). - [ ] Enforce container placement rules. Check: full bags and prohibited nesting are rejected without losing items; permitted moves match recovered rules. +Essence of Pure Jealousy now supports persistent native splitting and merging. +The historical merge cap remains unresolved, so the merge item stays open; +65535 is only the native quantity representation ceiling. Protocol evidence, +rejected-split recovery and verification are in +[inventory stacks](docs/inventory-stacks.md). + ## Equipment, one kind at a time - [x] Equip and unequip one melee weapon. Check: its appearance and base attack diff --git a/client/runtime/linux_window.c b/client/runtime/linux_window.c @@ -44,7 +44,7 @@ static uint8_t keyboard_state[256]; static uint32_t queued_mouse_buttons; #ifdef __EMSCRIPTEN__ /* Browsers cannot warp the physical pointer; camera recentering is virtual. */ -static int cursor_x, cursor_y, cursor_warped, control_drag; +static int cursor_x, cursor_y, cursor_warped; static int browser_mouse, browser_mouse_x, browser_mouse_y; static int wheel_drag; static uint32_t wheel_deadline; @@ -1039,7 +1039,7 @@ static void process_event(const SDL_Event *event) queued_mouse_buttons &= ~releases[i][0]; queue_message(client.handle, releases[i][1], queued_mouse_buttons, 0, 2, 0); } - control_drag = cursor_warped = 0; + cursor_warped = 0; #endif if (client.capture) change_capture(0); if (client.active) { @@ -1095,12 +1095,6 @@ static void process_event(const SDL_Event *event) uint32_t button = event->button.button, message, mask; #ifdef __EMSCRIPTEN__ end_wheel_drag(); - if (button == SDL_BUTTON_LEFT) { - if (event->type == SDL_MOUSEBUTTONDOWN) - control_drag = !!(SDL_GetModState() & KMOD_CTRL); - if (control_drag) button = SDL_BUTTON_RIGHT; - if (event->type == SDL_MOUSEBUTTONUP) control_drag = 0; - } #endif if (button == SDL_BUTTON_LEFT) { message = 0x201; mask = 1; } else if (button == SDL_BUTTON_RIGHT) { message = 0x204; mask = 2; } diff --git a/client/tests/browser_camera.c b/client/tests/browser_camera.c @@ -68,19 +68,20 @@ static void recentering_preserves_relative_motion(void) assert(!(MEM32(0x50003008) & 2)); } -static void control_drag_releases_after_modifier_release(void) +static void control_left_click_keeps_its_native_button(void) { SDL_SetModState(KMOD_CTRL); SDL_Event event = {.type = SDL_MOUSEBUTTONDOWN}; event.button.button = SDL_BUTTON_LEFT; assert(SDL_PushEvent(&event) == 1); - assert(mouse_message() == 0x204); + assert(mouse_message() == 0x201); + assert(MEM32(0x50003008) == 9); SDL_SetModState(KMOD_NONE); event.type = SDL_MOUSEBUTTONUP; assert(SDL_PushEvent(&event) == 1); - assert(mouse_message() == 0x205); + assert(mouse_message() == 0x202); assert(!MEM32(0x50003008)); assert(!mouse_message()); } @@ -246,13 +247,13 @@ int main(void) assert(window); SDL_FlushEvents(SDL_FIRSTEVENT, SDL_LASTEVENT); recentering_preserves_relative_motion(); - control_drag_releases_after_modifier_release(); + control_left_click_keeps_its_native_button(); wheel_rotation_keeps_fractional_motion_and_ends(); focus_loss_releases_camera_button(); browser_controls_preserve_key_and_text_order(); touch_drag_preserves_the_press_position(); touch_camera_accumulates_motion_after_recentering(); touch_camera_release_preserves_recentered_position(); - puts("camera: recentering, Ctrl-drag, wheel motion, focus loss and browser key/text/touch input passed"); + puts("camera: recentering, Ctrl-left-click, wheel motion, focus loss and browser key/text/touch input passed"); return 0; } diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md @@ -0,0 +1,149 @@ +# Inventory stacks in 14.9.1 + +The supported stack is Essence of Pure Jealousy, template 152030, exact QL 42, +identity type 51005. Its original record is in +`server/gamedata/items/items_078.yaml`, with Can stat 30 = 513, flags +`0x00400821`, Energy 26 = 3 and Clip 212 = 3. Its description explicitly +instructs Ctrl-clicking to separate a charge. It has no action/effect sections. +New fixture grants use its three-charge catalog quantity. Production drops +and tradeskill use remain separate features. + +[Auno's historical 12.8 record](https://auno.org/ao/db.php?id=152030&patch=12080000) +already includes the splitting instruction. Its +[current record and dated comments](https://auno.org/ao/db.php?id=152030) +include a December 23, 2002 player report placing it in Steps of Madness. +These corroborate the shipped item; they do not establish a historical stack +maximum or drop rule. The shipped `The Inventory Window.txt` independently +documents Ctrl-left-click splitting. + +## Native protocol + +Evidence comes from original 14.9.1 `kkr.dll`, SHA-256 +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +The retained bundles are `local/reports/stack-protocol-1491-evidence.json` +(56 records) and `local/reports/stack-resync-1491-evidence.json` (44 records). + +Both operations use CharacterAction `0x5e477770`, with five network-order +DWORDs after the message header: + +| Action | Fields | +| --- | --- | +| 52, split | `52, sourcePage, sourceSlot, 0, retainedSourceCount` | +| 53, join | `53, keptPage, keptSlot, removedPage, removedSlot` | + +`N3Msg_SplitItem` at `0x10022d50` checks the original count and available +space, applies the split locally through `0x1005edb0`, then sends action 52. +The final field is the count retained in the source. The first free ordinary +slot receives the difference. The native search starts at 48 and ends at 77; +server saved slots remain 64..93. An unchanged response does not split again, +because the current source count already equals the retained count. Evidence: +`ev_602e0a0586dda4b99775a519b2ed33d5bc615ab035fad5777711bd513ed19b98` +and `ev_e501da0bcfc60b0bd90c7bc5fd33a29ad54cef983996514cc598828682277fb8`. + +`N3Msg_JoinItems` at `0x10022ba0` waits for its response. Both identities must +be different slots in the same page, both item Can values must contain +`0x200`, and low/high template and QL must match. Response helper `0x1005ec30` +keeps the first slot and adds the second slot's count before removing it. +The generated-source helper is in `client/game/kkr.dll/lifted-0029.c`. +Direction and checks are supported by +`ev_22f06fb27128af42a5babde5a290d6fd9f24bcd92d075f86a813261a0a2e60ae` +and `ev_d87a842dd8417af8e91dcb61a97596d71ff6fce8b6bca2b6110cdabd783afcc6`. + +Stack mutations require inventory entry flag `0x1`. Initial Essence rows +therefore use flag 1; individual items retain flag 2. Local split clones use +`0x21` and a zero instance identity. The row stores a ushort quantity at offset +6 and its QL/low/high triple at offsets 16/20/24. Persistent server IDs remain +owned state, while stack requests address page/slot and carry no new instance +ID or operation nonce. + +The join helper performs a literal 16-bit addition and can wrap. The server +rejects sums above 65535 to preserve quantity. This is the representation +ceiling, **not a recovered classic server stack cap**. Neither catalog Clip 3 +nor price stat 74 = 50000 establishes a merge maximum. The historical server +cap remains unresolved. Overflow assembly evidence: +`ev_e650f59cb6fa2ba4d648045ef820df9906bafaacc81b90e200adaede6597eec4`. + +## Persistence and rejection + +Each owned item now has a ushort Count in `inventory.yaml`; pre-quantity saved +items and reclaim entries with an absent/zero count load as one individual. +Only the supported Essence can currently have a count above one. FullCharacter, +corpse and reclaim entries serialize the quantity rather than a constant one. +The existing atomic inventory replacement publishes both changed counts and +any newly allocated ID together, after saving successfully. + +A split requires `1 <= retained < currentCount` and an empty ordinary slot. +The server gives the new stack the first free slot and a fresh global ID. +An immediate repeated retained count is a no-op. A repeated join finds the +removed slot empty. The wire cannot distinguish every replay after subsequent +slot reuse or a later merge; it has no previous-count or operation token. +Every accepted operation still conserves the total quantity. + +The original client does not roll back a rejected optimistic split. A plain +FullCharacter overlays only non-null rows and reapplies equipment, so it cannot +remove a provisional clone safely. That behavior is supported by +`ev_331fd15acd45f210966ad41148a5960706f3a66f90d7daa3d710e0e9e5d29ba1`. +The server instead rebuilds only the supported ordinary stacks: + +1. Preserve all occupied individual-item slots and all equipment. +2. Delete the other ordinary slots using native action 112, removing any + provisional Essence clones. The Essence has no deletion event functions. +3. Add each authoritative stack in slot order using AddTemplate `0x052e2f0c`, + body `{low, high, QL, count}`. It chooses the first free ordinary slot. +4. Move it to its saved slot with the existing own-player ContainerAddItem + response when needed. + +This correction policy uses recovered native operations; it is not proof of +how the original server rejected splits. It preserves individual live-item +identities and avoids reapplying worn effects. AddTemplate creates template +proxies without transmitting a persistent ID; reconnect supplies the saved IDs. +Native proof: +`ev_51546b34f37c502e64f97b7f8d254e9cb41cf83c71b676217ffd69bc1ff2761a`, +`ev_7b4afe19deabc80973ba1b2ac210a5f9b66e9ac793f6521ed89d7b5eec615066`, +and `ev_78e48f17a73e495dccf184968e44268af825c92b3d9bd79d86ccd44c30c86806`. +Apparent ATR activation calls on these paths resolve to original `0x1010def0`, +a `RET 4` stub, and must not be filled in as a missing adapter method. + +## Verification + +`server/stacks_test.go` exercises grant quantities, merge direction, source +retention and first-free allocation, repeat/concurrent requests, restart, +unsigned-short overflow, full inventory, disk-write failures, invalid and foreign +requests, corpse/reclaim encoding and migration of pre-quantity saves. A real +world connection verifies actions 52/53 and that retained count 65 is not +translated as an inventory slot. Rejected-split tests verify hole restoration +and preservation of individual items and equipped armor. + +The browser input adapter now preserves native Ctrl-left-click. Its previous +global conversion to a right-click prevented the shipped inventory split gesture. +`client/tests/browser_camera.c` reproduces that regression against the old +adapter and verifies the corrected button/modifier state alongside right-button +camera, wheel, focus-loss, key/text and touch behavior. Other camera controls +retain their existing native input paths. + +The matching rebuilt WASM bundle was exercised with two Chromium clients in +`local/stack-smoke/`. Actual inventory gestures joined two three-charge stacks +to six, Ctrl-clicked them into one plus five, and joined them again. A fixture +rejected the next optimistic split through the production correction path: +the native inventory returned to six without changing the pistol, worn item +identities, displayed AC 6 or attack rating 400. After placing the selected +item, the restored stack could be split again. This does not claim that the +native cursor selection is cleared by the correction. + +The second owner independently split three into one plus two. Both clients +reconnected after a server restart with unchanged saved slots, counts and IDs; +a subsequent split allocated ID 114 after the previous global high-water mark +113. Ten read-only native heap snapshots matched the authoritative quantities. +There were no client exceptions; sixteen connection refusals were expected +during the intentional restart. The clients and fixture server were closed +afterward. `tmp_verify.py` retains these checks beside screenshots and packet +captures. The served Brotli executable was decompressed and matched against +the tested build, and every published manifest digest was checked. + +The focused C input fixture failed against the old Ctrl-click mapping and +passed with the correction in both Chromium and Firefox. The browser control +JavaScript tests and all three WASM publishing tests also passed. +The complete maintained server suite, `go test ./server/... -count=1`, passed +with `ao/server` completing in 84.361 seconds. +The focused race run over stacks, inventory, equipment, armor, attack rating, +overequipping, character stats, reclaim and combat passed in 136.415 seconds. diff --git a/docs/inventory.md b/docs/inventory.md @@ -3,7 +3,7 @@ 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 +quality, quantity 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. @@ -15,9 +15,11 @@ 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 -and starter loadouts remain separate milestones. Native corpse pickup is +Items use exact catalog qualities with identical template endpoints. Essence +of Pure Jealousy now supports persistent [native stacks](inventory-stacks.md), +including merge, split and rejected-split correction. Its historical server +merge cap remains unresolved. Arbitrary-quality interpolation, backpacks and +starter loadouts remain separate milestones. Native corpse pickup is described in [the corpse and loot protocol](corpse-loot.md). QL 1 Kinetic Axe equipment is described below. Exact QL 1/200 Metaplast chest armor and QL 1 boots use the [native armor path](armor.md). Other equipment remains unsupported. diff --git a/server/armor_test.go b/server/armor_test.go @@ -51,7 +51,7 @@ func TestArmorNativeMoveDelayAndRestart(t *testing.T) { world.advanceEquipment(finish) restarted := newTestInventoryServer(t) - if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64}, {2, 51022, 85686, 1, 21}, {3, 51022, 85638, 1, 66}}) { + if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64, 1}, {2, 51022, 85686, 1, 21, 1}, {3, 51022, 85638, 1, 66, 1}}) { t.Fatalf("armor identity or slot did not persist: %+v", restarted.characters[1].inventory) } if len(conn.packets) != 2 || len(observer.packets) != 1 || @@ -127,7 +127,7 @@ func TestArmorRejectsRequirementsAndInterruptedWear(t *testing.T) { case "unsupported identity": player.inventory.Items[1].Type = 51018 case "occupied": - player.inventory.Items = append(player.inventory.Items, ownedItem{4, 51022, 85686, 1, 21}) + player.inventory.Items = append(player.inventory.Items, ownedItem{4, 51022, 85686, 1, 21, 1}) } before := append([]ownedItem(nil), player.inventory.Items...) diff --git a/server/attack_rating_test.go b/server/attack_rating_test.go @@ -84,7 +84,7 @@ func TestAttackRatingFistEndpointsIncludeZeroSkill(t *testing.T) { func TestAttackRatingScaledMinimumPrecedesArmor(t *testing.T) { world, _ := newArmorDamageWorld(t) attacker := &character{stats: defaultCharacterStats(), inventory: playerInventory{ - Items: []ownedItem{{1, 51018, 209283, 1, 6}}, + Items: []ownedItem{{1, 51018, 209283, 1, 6, 1}}, }} attacker.stats.OneHandEdged = 398 var hits []uint32 diff --git a/server/corpse_expiry_test.go b/server/corpse_expiry_test.go @@ -18,7 +18,7 @@ func newExpiringCorpseWorld(t *testing.T) (*server, *combatTestConn, time.Time) world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) killed := world.characters[1].nextAttack world.advanceCombat(killed) - world.characters[1000000].corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1}} + world.characters[1000000].corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}} return world, conn, killed } @@ -98,7 +98,7 @@ func TestCorpseExpiryPreservesAlreadyTakenInventoryAfterRestart(t *testing.T) { world.handleInventory(world.clients[1], lootTakeRequest()) restarted := newTestInventoryServer(t) - expected := []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64}} + expected := []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}} if world.characters[1000000] != nil || !slices.Equal(world.characters[1].inventory.Items, expected) || !slices.Equal(restarted.characters[1].inventory.Items, expected) { t.Fatal("expiry lost or duplicated the item that had already changed owners") @@ -158,7 +158,7 @@ func TestCorpseExpiryConcurrentPickupHasAtMostOneDurableOwner(t *testing.T) { items := world.characters[1].inventory.Items if world.characters[1000000] != nil || len(items) > 1 || !slices.Equal(items, restarted.characters[1].inventory.Items) || - (len(items) == 1 && items[0] != (ownedItem{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64})) { + (len(items) == 1 && items[0] != (ownedItem{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1})) { t.Fatal("a pickup racing expiry duplicated or lost durable ownership") } } diff --git a/server/equipment_test.go b/server/equipment_test.go @@ -62,8 +62,8 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) { world.advanceEquipment(world.clients[1].equipment.readyAt) unequipped := newTestInventoryServer(t) - if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 6}}) || - !reflect.DeepEqual(unequipped.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64}}) { + if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 6, 1}}) || + !reflect.DeepEqual(unequipped.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64, 1}}) { t.Fatal("equipment move changed identity or did not survive restart") } if len(conn.packets) != 4 || len(observer.packets) != 3 { @@ -146,7 +146,7 @@ func TestEquipmentCompletionRechecksStateAndPreservesFailedSave(t *testing.T) { world.advanceEquipment(finish) - if !reflect.DeepEqual(world.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64}}) { + if !reflect.DeepEqual(world.characters[1].inventory.Items, []ownedItem{{1, 51018, 209283, 1, 64, 1}}) { t.Fatalf("interrupted equip changed inventory: %+v", world.characters[1].inventory) } }) diff --git a/server/inventory.go b/server/inventory.go @@ -16,6 +16,7 @@ type ownedItem struct { Template uint32 `yaml:"template"` Quality uint32 `yaml:"quality"` Slot uint32 `yaml:"slot"` + Count uint16 `yaml:"count"` } type reclaimItem struct { @@ -33,7 +34,8 @@ 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] || + if item.ID == 0 || item.ID > inventory.LastID || ids[item.ID] || item.Count == 0 || + (item.Count != 1 && !item.isEssenceStack()) || (item.Slot < 64 && (item.equipmentSlot() == 0 || item.Slot != item.equipmentSlot())) || item.Slot >= 94 || slots[item.Slot] { return fmt.Errorf("invalid inventory item identity or slot") @@ -41,7 +43,8 @@ func (inventory playerInventory) validate() error { ids[item.ID], slots[item.Slot] = true, true } for _, entry := range inventory.Reclaim { - if entry.Item.ID == 0 || entry.Item.ID > inventory.LastID || ids[entry.Item.ID] || entry.Item.Slot < 64 || entry.Item.Slot >= 94 { + if entry.Item.ID == 0 || entry.Item.ID > inventory.LastID || ids[entry.Item.ID] || entry.Item.Count == 0 || + (entry.Item.Count != 1 && !entry.Item.isEssenceStack()) || entry.Item.Slot < 64 || entry.Item.Slot >= 94 { return fmt.Errorf("invalid reclaim item identity or slot") } ids[entry.Item.ID] = true @@ -84,7 +87,11 @@ func (server *server) grantItem_locked(character *character, template uint32) (b inventory := character.inventory inventory.LastID = server.nextItem + 1 inventory.Items = slices.Clone(character.inventory.Items) - inventory.Items = append(inventory.Items, ownedItem{inventory.LastID, definition.HeaderWords[0], template, *definition.Quality, slot}) + item := ownedItem{inventory.LastID, definition.HeaderWords[0], template, *definition.Quality, slot, 1} + if item.isEssenceStack() { + item.Count = uint16(itemStat(definition, 212)) + } + inventory.Items = append(inventory.Items, item) if err := server.saveInventory_locked(character, inventory); err != nil { return false, err } @@ -105,10 +112,16 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { 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 || client.equipment != nil || + 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 } + if client.equipment != nil { + if key == 0x5e477770 && binary.BigEndian.Uint32(body[16:20]) == 52 { + return server.syncStacks_locked(client) + } + return nil + } // Page identities must agree with this owner's actual logical slot. sourceType, sourceSlot := binary.BigEndian.Uint32(body[16:20]), binary.BigEndian.Uint32(body[20:24]) @@ -119,6 +132,10 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { return server.takeLoot_locked(client, body) } index := slices.IndexFunc(character.inventory.Items, func(item ownedItem) bool { return item.Slot == sourceSlot }) + if key == 0x5e477770 && binary.BigEndian.Uint32(body[16:20]) == 52 && sourceType == 104 && + sourceSlot >= 64 && sourceSlot < 94 && index < 0 { + return server.syncStacks_locked(client) + } if index < 0 || (sourceSlot >= 64 && sourceType != 104) || (sourceSlot == 6 && sourceType != 101) || ((sourceSlot == 21 || sourceSlot == 30) && sourceType != 102) { @@ -134,6 +151,9 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { if sourceSlot < 64 { return nil } + if key == 0x5e477770 && (binary.BigEndian.Uint32(body[16:20]) == 52 || binary.BigEndian.Uint32(body[16:20]) == 53) { + return server.changeStack_locked(client, index, body) + } inventory := character.inventory inventory.Items = slices.Clone(character.inventory.Items) if key == 0x47537a24 { diff --git a/server/inventory_test.go b/server/inventory_test.go @@ -37,7 +37,7 @@ func TestInventoryNativeMoveDeleteAndRestart(t *testing.T) { if err != nil || !granted { t.Fatalf("grant: %v %v", granted, err) } - expected := ownedItem{ID: 1, Type: 51018, Template: 121567, Quality: 1, Slot: 64} + expected := ownedItem{ID: 1, Type: 51018, Template: 121567, Quality: 1, Slot: 64, Count: 1} if !reflect.DeepEqual(world.characters[1].inventory.Items, []ownedItem{expected}) { t.Fatalf("granted item: %+v", world.characters[1].inventory) } @@ -152,7 +152,7 @@ func TestInventoryRejectsForeignOccupiedAndStaleRequests(t *testing.T) { 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}, + {1, 51018, 121567, 1, 64, 1}, {2, 51018, 121567, 1, 65, 1}, }} client := world.clients[1] packet := inventoryMovePacket(1, 64, 72) diff --git a/server/loot.go b/server/loot.go @@ -58,7 +58,7 @@ func lootInventoryPacket(owner uint32, corpse *character, open bool) []byte { body := binary.BigEndian.AppendUint32(nil, uint32(len(corpse.corpse.items)+1)*1009) for _, item := range corpse.corpse.items { // Bit 0 selects the native template-proxy transfer path. - for _, value := range []uint32{item.Slot, 0x00030001, item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { + for _, value := range []uint32{item.Slot, 0x00030000 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { body = binary.BigEndian.AppendUint32(body, value) } } diff --git a/server/loot_test.go b/server/loot_test.go @@ -30,7 +30,7 @@ func newLootWorld(t *testing.T) (*server, *combatTestConn) { t.Fatal(err) } world.advanceCombat(player.nextAttack) - world.characters[1000000].corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1}} + world.characters[1000000].corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}} return world, conn } @@ -73,7 +73,7 @@ func TestLootNativeCorpseTakeAndRestart(t *testing.T) { } restarted := newTestInventoryServer(t) - expected := []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64}} + expected := []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}} if !slices.Equal(restarted.characters[1].inventory.Items, expected) || restarted.nextItem != 17 || len(world.characters[1000000].corpse.items) != 0 { t.Fatalf("loot ownership after restart: %+v", restarted.characters[1].inventory) } @@ -116,7 +116,7 @@ func TestLootFillsTheLastNativeInventorySlot(t *testing.T) { world, conn := newLootWorld(t) for slot := uint32(64); slot < 93; slot++ { world.characters[1].inventory.Items = append(world.characters[1].inventory.Items, - ownedItem{ID: slot + 100, Type: 51018, Template: 121567, Quality: 1, Slot: slot}) + ownedItem{ID: slot + 100, Type: 51018, Template: 121567, Quality: 1, Slot: slot, Count: 1}) } world.characters[1].inventory.LastID = 192 world.handleLootUse(world.clients[1], lootUseRequest(1)) @@ -157,7 +157,7 @@ func TestLootRejectsUnavailableItemsWithoutChangingOwnership(t *testing.T) { binary.BigEndian.PutUint32(request[20:24], 1) case "full inventory": for slot := uint32(64); slot < 94; slot++ { - world.characters[1].inventory.Items = append(world.characters[1].inventory.Items, ownedItem{ID: slot, Slot: slot}) + world.characters[1].inventory.Items = append(world.characters[1].inventory.Items, ownedItem{ID: slot, Slot: slot, Count: 1}) } case "save failure": if err := os.Mkdir("data/players/1/inventory.yaml", 0700); err != nil { diff --git a/server/main.go b/server/main.go @@ -440,7 +440,7 @@ func (server *server) serveWorldClient(client *worldClient) error { if err := server.handleResurrection(client, body); err != nil { return err } - case 112: + case 52, 53, 112: if err := server.handleInventory(client, body); err != nil { return err } diff --git a/server/overequipping_test.go b/server/overequipping_test.go @@ -75,7 +75,7 @@ func TestOverequippingIncludesTrickleAndRecoversAfterRestart(t *testing.T) { func TestOverequippingAdjustedMinimumPrecedesArmor(t *testing.T) { world, _ := newArmorDamageWorld(t) attacker := &character{stats: defaultCharacterStats(), inventory: playerInventory{ - Items: []ownedItem{{1, 51018, 209283, 1, 6}}, + Items: []ownedItem{{1, 51018, 209283, 1, 6, 1}}, }} attacker.stats.OneHandEdged, attacker.stats.Brawling = 398, 1 diff --git a/server/reclaim.go b/server/reclaim.go @@ -42,7 +42,7 @@ func reclaimInventoryPacket(player *character, slots []uint32) []byte { for slot, id := range slots { index := slices.IndexFunc(player.inventory.Reclaim, func(entry reclaimItem) bool { return entry.Item.ID == id }) item := player.inventory.Reclaim[index].Item - for _, value := range []uint32{uint32(slot), 0x00030001, item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { + for _, value := range []uint32{uint32(slot), 0x00030000 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { body = binary.BigEndian.AppendUint32(body, value) } } diff --git a/server/reclaim_test.go b/server/reclaim_test.go @@ -38,7 +38,7 @@ func newReclaimWorld(t *testing.T) (*server, *combatTestConn) { t.Fatal(err) } player.inventory = playerInventory{LastID: 3, Items: []ownedItem{ - {1, 51018, 209283, 1, 6}, {2, 51018, 121567, 1, 64}, {3, 51005, 42640, 1, 65}, + {1, 51018, 209283, 1, 6, 1}, {2, 51018, 121567, 1, 64, 1}, {3, 51005, 42640, 1, 65, 1}, }} world.nextItem = 3 if err := world.saveInventory_locked(player, player.inventory); err != nil { @@ -145,7 +145,7 @@ func TestReclaimPendingThenPrivatePickupPersistsOnce(t *testing.T) { if binary.BigEndian.Uint32(moved[16:20]) != 0x47537a24 || binary.BigEndian.Uint32(moved[29:33]) != 106 || binary.BigEndian.Uint32(moved[45:49]) != 49 { t.Fatalf("incorrect native pickup: %x", moved) } - expected := ownedItem{3, 51005, 42640, 1, 65} + expected := ownedItem{3, 51005, 42640, 1, 65, 1} if len(player.inventory.Items) != 3 || player.inventory.Items[2] != expected || len(player.inventory.Reclaim) != 0 || len(conn.packets) != count || !reflect.DeepEqual(player.inventory, restarted.characters[1].inventory) { t.Fatal("pickup lost or duplicated an item") @@ -157,7 +157,7 @@ func TestReclaimRejectsInvalidOpenAndPickup(t *testing.T) { t.Run(scenario, func(t *testing.T) { world, conn := newReclaimWorld(t) player, client := world.characters[1], world.clients[1] - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}} player.inventory.LastID = 4 world.handleReclaim(client, reclaimRequest(109)) request := reclaimTakeRequest(0) @@ -214,7 +214,7 @@ func TestReclaimFullInventoryAndFailedPickupSaveRetainSource(t *testing.T) { t.Run(scenario, func(t *testing.T) { world, conn := newReclaimWorld(t) player, client := world.characters[1], world.clients[1] - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}} player.inventory.LastID = 4 world.nextItem = 4 if scenario == "full" { @@ -243,8 +243,8 @@ func TestReclaimConcurrentPickupKeepsOtherWindowSlotsStable(t *testing.T) { player, client := world.characters[1], world.clients[1] player.inventory.LastID = 5 player.inventory.Reclaim = []reclaimItem{ - {ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}, - {ownedItem{5, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}, + {ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}, + {ownedItem{5, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}, } world.handleReclaim(client, reclaimRequest(109)) var group sync.WaitGroup @@ -273,7 +273,7 @@ func TestReclaimSurvivesOtherInventoryTransactions(t *testing.T) { world, _ := newReclaimWorld(t) player, client := world.characters[1], world.clients[1] player.inventory.LastID = 4 - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(time.Minute).UTC()}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(time.Minute).UTC()}} world.nextItem = 4 expected := slices.Clone(player.inventory.Reclaim) @@ -301,7 +301,7 @@ func TestReclaimSurvivesOtherInventoryTransactions(t *testing.T) { case "loot": npc := world.characters[1000000] npc.health, npc.playfield, npc.position = 0, player.playfield, player.position - npc.corpse = &npcCorpse{looter: 1, items: []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1}}} + npc.corpse = &npcCorpse{looter: 1, items: []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}}} client.lootCorpse = npc.id if err := world.handleInventory(client, lootTakeRequest()); err != nil { t.Fatal(err) @@ -321,7 +321,7 @@ func TestReclaimLargePoolRemainsAvailableAcrossWindows(t *testing.T) { player, client := world.characters[1], world.clients[1] player.inventory.LastID = 104 for id := uint32(4); id <= 104; id++ { - player.inventory.Reclaim = append(player.inventory.Reclaim, reclaimItem{ownedItem{id, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}) + player.inventory.Reclaim = append(player.inventory.Reclaim, reclaimItem{ownedItem{id, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}) } world.handleReclaim(client, reclaimRequest(109)) @@ -340,7 +340,7 @@ func TestReclaimLargePoolRemainsAvailableAcrossWindows(t *testing.T) { func TestReclaimPreventsInsuranceUntilEmptied(t *testing.T) { world, conn := newReclaimWorld(t) player := world.characters[1] - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().Add(-time.Second)}} err := world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:]) @@ -357,7 +357,7 @@ func TestReclaimNativeWireRoundTripAndRestart(t *testing.T) { if err := world.saveUser_locked(player); err != nil { t.Fatal(err) } - player.inventory = playerInventory{LastID: 17, Reclaim: []reclaimItem{{ownedItem{17, 51005, 42640, 1, 64}, time.Now().Add(-time.Second).UTC()}}} + player.inventory = playerInventory{LastID: 17, Reclaim: []reclaimItem{{ownedItem{17, 51005, 42640, 1, 64, 1}, time.Now().Add(-time.Second).UTC()}}} if err := world.saveInventory_locked(player, player.inventory); err != nil { t.Fatal(err) } @@ -395,7 +395,7 @@ func TestReclaimNativeWireRoundTripAndRestart(t *testing.T) { binary.BigEndian.Uint32(closed[29:33]) != 110 { t.Fatalf("incorrect native reclaim round trip: %x %x %x %x", acknowledged, contents, moved, closed) } - if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{17, 51005, 42640, 1, 64}}) || len(restarted.characters[1].inventory.Reclaim) != 0 { + if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{17, 51005, 42640, 1, 64, 1}}) || len(restarted.characters[1].inventory.Reclaim) != 0 { t.Fatal("native pickup did not persist its sole owner") } } @@ -406,7 +406,7 @@ func TestReclaimLoadRejectsDuplicateAndInvalidIdentities(t *testing.T) { world, _ := newReclaimWorld(t) player := world.characters[1] player.inventory.LastID = 4 - player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().UTC()}} + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65, 1}, time.Now().UTC()}} switch scenario { case "owned duplicate": player.inventory.Reclaim[0].Item.ID = 3 diff --git a/server/respawn_test.go b/server/respawn_test.go @@ -152,7 +152,7 @@ func TestNPCRespawnKeepsOldLootSeparateAcrossTwoKills(t *testing.T) { world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) killed := world.characters[1].nextAttack world.advanceCombat(killed) - world.characters[1000000].corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1}} + world.characters[1000000].corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}} world.handleLootUse(world.clients[1], lootUseRequest(1)) world.advanceNPCRespawns(killed.Add(100 * time.Second)) diff --git a/server/resurrection_test.go b/server/resurrection_test.go @@ -22,7 +22,7 @@ func TestResurrectionNativeRequestRedirectsAndPersistsBeforeReconnect(t *testing if err := world.saveUser_locked(player); err != nil { t.Fatal(err) } - item := ownedItem{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64} + item := ownedItem{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1} if err := world.saveInventory_locked(player, playerInventory{LastID: 17, Items: []ownedItem{item}}); err != nil { t.Fatal(err) } diff --git a/server/stacks.go b/server/stacks.go @@ -0,0 +1,119 @@ +package main + +import ( + "encoding/binary" + "fmt" + "slices" +) + +func (item ownedItem) isEssenceStack() bool { + return item.Type == 51005 && item.Template == 152030 && item.Quality == 42 +} + +func (server *server) changeStack_locked(client *worldClient, index int, body []byte) error { + player := server.characters[client.id] + if !player.inventory.Items[index].isEssenceStack() { + return nil + } + inventory := player.inventory + inventory.Items = slices.Clone(player.inventory.Items) + if binary.BigEndian.Uint32(body[16:20]) == 52 { + // Action 52 carries the count retained in the original, already split locally. + retained := binary.BigEndian.Uint32(body[32:36]) + if retained == uint32(inventory.Items[index].Count) && binary.BigEndian.Uint32(body[28:32]) == 0 { + return nil + } + if binary.BigEndian.Uint32(body[28:32]) != 0 || retained == 0 || retained > uint32(inventory.Items[index].Count) { + return server.syncStacks_locked(client) + } + var slot uint32 + for slot = 64; slot < 94; slot++ { + if !slices.ContainsFunc(inventory.Items, func(item ownedItem) bool { return item.Slot == slot }) { + break + } + } + if slot == 94 { + return server.syncStacks_locked(client) + } + if server.nextItem == ^uint32(0) { + return fmt.Errorf("item identities exhausted") + } + item := inventory.Items[index] + inventory.LastID = server.nextItem + 1 + item.ID, item.Slot, item.Count = inventory.LastID, slot, item.Count-uint16(retained) + inventory.Items[index].Count = uint16(retained) + inventory.Items = append(inventory.Items, item) + } else { + // The native join response keeps the first slot and removes the second. + other := slices.IndexFunc(inventory.Items, func(item ownedItem) bool { return item.Slot == binary.BigEndian.Uint32(body[32:36]) }) + if binary.BigEndian.Uint32(body[28:32]) != 104 || other < 0 || other == index || !inventory.Items[other].isEssenceStack() { + return nil + } + count := uint32(inventory.Items[index].Count) + uint32(inventory.Items[other].Count) + // Native ushort addition wraps; prevent loss at its representation ceiling. + // This is not evidence of the original server's maximum permitted stack. + if count > 65535 { + return nil + } + inventory.Items[index].Count = uint16(count) + inventory.Items = slices.Delete(inventory.Items, other, other+1) + } + + // Publish quantities and any new identity only after one atomic inventory save. + if err := server.saveInventory_locked(player, inventory); err != nil { + return err + } + server.nextItem = max(server.nextItem, inventory.LastID) + return client.send(n3Packet(0x5e477770, 50000, client.id, body[16:])) +} + +func (server *server) syncStacks_locked(client *worldClient) error { + // Preserve live individual items and equipped modifiers. Only Essence has + // optimistic clones here, and its catalog has no deletion event functions. + player := server.characters[client.id] + var occupied [30]bool + for _, item := range player.inventory.Items { + if item.Slot >= 64 && !item.isEssenceStack() { + occupied[item.Slot-64] = true + } + } + for slot := uint32(64); slot < 94; slot++ { + if occupied[slot-64] { + continue + } + var body []byte + for _, value := range []uint32{112, 104, slot, 0, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + if err := client.send(n3Packet(0x5e477770, 50000, client.id, body)); err != nil { + return err + } + } + + // AddTemplate chooses first-free; move each restored stack to its saved slot. + items := slices.Clone(player.inventory.Items) + slices.SortFunc(items, func(first, second ownedItem) int { return int(first.Slot) - int(second.Slot) }) + for _, item := range items { + if !item.isEssenceStack() { + continue + } + var body []byte + for _, value := range []uint32{item.Template, item.Template, item.Quality, uint32(item.Count)} { + body = binary.BigEndian.AppendUint32(body, value) + } + if err := client.send(n3Packet(0x052e2f0c, 50000, client.id, body)); err != nil { + return err + } + slot := uint32(64) + for occupied[slot-64] { + slot++ + } + if slot != item.Slot { + if err := client.send(itemMovePacket(client.id, slot, item.Slot)); err != nil { + return err + } + } + occupied[item.Slot-64] = true + } + return nil +} diff --git a/server/stacks_test.go b/server/stacks_test.go @@ -0,0 +1,334 @@ +package main + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "net" + "os" + "reflect" + "slices" + "sync" + "testing" + "time" +) + +func stackActionPacket(owner, action, slot, argument uint32) []byte { + otherPage := uint32(0) + if action == 53 { + otherPage = 104 + } + var body []byte + for _, value := range []uint32{action, 104, slot, otherPage, argument} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x5e477770, 50000, owner, body) +} + +func newStackWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + t.Chdir(t.TempDir()) + world, conn := newCombatWorld() + player := world.characters[1] + player.name, player.level, player.appearance = "Stack Owner", 1, 277 + player.rotation[3], player.stats = 1, defaultCharacterStats() + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for range 2 { + if granted, err := world.grantItem_locked(player, 152030); err != nil || !granted { + t.Fatalf("grant Essence: %v %v", granted, err) + } + } + return world, conn +} + +func TestStackJoinSplitRepeatAndRestartPreserveQuantities(t *testing.T) { + world, conn := newStackWorld(t) + player := world.characters[1] + + if err := world.handleInventory(world.clients[1], stackActionPacket(1, 53, 65, 64)[20:]); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(player.inventory.Items, []ownedItem{{2, 51005, 152030, 42, 65, 6}}) { + t.Fatalf("join did not retain the first identity: %+v", player.inventory) + } + request := stackActionPacket(1, 52, 65, 2)[20:] + world.handleInventory(world.clients[1], request) + world.handleInventory(world.clients[1], request) + restarted := newTestInventoryServer(t).characters[1] + packet := targetPacket(fullCharacterPacket(restarted)) + + expected := []ownedItem{{2, 51005, 152030, 42, 65, 2}, {3, 51005, 152030, 42, 64, 4}} + if !reflect.DeepEqual(player.inventory.Items, expected) || !reflect.DeepEqual(restarted.inventory, player.inventory) || + player.inventory.LastID != 3 || world.nextItem != 3 || len(conn.packets) != 2 { + t.Fatalf("split lost quantities or repeated allocation: %+v restart %+v packets %d", player.inventory, restarted.inventory, len(conn.packets)) + } + if binary.BigEndian.Uint16(packet[41:43]) != 1 || binary.BigEndian.Uint16(packet[43:45]) != 2 || + binary.BigEndian.Uint16(packet[73:75]) != 1 || binary.BigEndian.Uint16(packet[75:77]) != 4 { + t.Fatalf("native template-stack flags/counts: %x", packet[33:101]) + } +} + +func TestStackNativeWireDoesNotTranslateRetainedCountAsASlot(t *testing.T) { + fixture, _ := newStackWorld(t) + fixture.characters[1].inventory.Items[0].Count = 100 + if err := fixture.saveInventory_locked(fixture.characters[1], fixture.characters[1].inventory); err != nil { + t.Fatal(err) + } + world := newTestInventoryServer(t) + client, connection := net.Pipe() + client.SetDeadline(time.Now().Add(5 * time.Second)) + done := make(chan error, 1) + go func() { defer connection.Close(); done <- world.serveWorldConnection(connection) }() + defer func() { + client.Close() + if err := <-done; err != nil { + t.Error(err) + } + }() + cookie, _ := hex.DecodeString("dfdf00010001002000000001000000020000001b000000010000000000000000") + client.Write(cookie) + for { + packet, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + if binary.BigEndian.Uint32(packet[16:20]) == 0x5f52412e { + break + } + } + client.Write(targetPacket(n3Packet(0x570c2039, 50000, 1, nil))) + if _, err := readPacket(client); err != nil { + t.Fatal(err) + } + + client.Write(targetPacket(stackActionPacket(1, 52, 64, 65))) + split, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + client.Write(targetPacket(stackActionPacket(1, 53, 64, 66))) + join, err := readPacket(client) + if err != nil { + t.Fatal(err) + } + + if binary.BigEndian.Uint32(split[29:33]) != 52 || binary.BigEndian.Uint32(split[37:41]) != 48 || binary.BigEndian.Uint32(split[45:49]) != 65 || + binary.BigEndian.Uint32(join[29:33]) != 53 || binary.BigEndian.Uint32(join[37:41]) != 48 || binary.BigEndian.Uint32(join[45:49]) != 50 { + t.Fatalf("native split count or join slots were mistranslated: %x %x", split, join) + } + expected := []ownedItem{{1, 51005, 152030, 42, 64, 100}, {2, 51005, 152030, 42, 65, 3}} + if !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory.Items, expected) { + t.Fatal("native round trip changed the combined quantity") + } +} + +func TestStackRejectsInvalidQuantitiesAndOwnership(t *testing.T) { + for _, scenario := range []string{"zero", "same count", "too many", "negative", "empty", "same slot", "other quality", "other item", "foreign owner", "foreign source page", "foreign destination page", "loading", "dead", "stale session", "pending equipment"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newStackWorld(t) + player, client := world.characters[1], world.clients[1] + request := stackActionPacket(1, 52, 64, 1)[20:] + switch scenario { + case "zero": + request = stackActionPacket(1, 52, 64, 0)[20:] + case "same count": + request = stackActionPacket(1, 52, 64, 3)[20:] + case "too many": + request = stackActionPacket(1, 52, 64, 4)[20:] + case "negative": + request = stackActionPacket(1, 52, 64, 0xffffffff)[20:] + case "empty": + request = stackActionPacket(1, 52, 66, 1)[20:] + case "same slot": + request = stackActionPacket(1, 53, 64, 64)[20:] + case "other quality": + request = stackActionPacket(1, 53, 64, 65)[20:] + player.inventory.Items[1].Quality, player.inventory.Items[1].Count = 41, 1 + case "other item": + request = stackActionPacket(1, 53, 64, 65)[20:] + player.inventory.Items[1] = ownedItem{2, 51018, 121567, 1, 65, 1} + case "foreign owner": + request = stackActionPacket(2, 52, 64, 1)[20:] + case "foreign source page": + binary.BigEndian.PutUint32(request[20:24], 106) + case "foreign destination page": + request = stackActionPacket(1, 53, 64, 65)[20:] + binary.BigEndian.PutUint32(request[28:32], 106) + case "loading": + client.loading = true + case "dead": + player.health = 0 + case "stale session": + world.clients[1] = &worldClient{id: 1} + case "pending equipment": + client.equipment = &equipmentMove{} + } + before := slices.Clone(player.inventory.Items) + persisted, err := os.ReadFile("data/players/1/inventory.yaml") + if err != nil { + t.Fatal(err) + } + + err = world.handleInventory(client, request) + after, readErr := os.ReadFile("data/players/1/inventory.yaml") + + if err != nil || readErr != nil || !bytes.Equal(persisted, after) || !reflect.DeepEqual(player.inventory.Items, before) || world.nextItem != 2 { + t.Fatalf("rejected stack request changed ownership/quantity: %+v %v %v", player.inventory, err, readErr) + } + }) + } +} + +func TestStackJoinPreventsUnsignedShortOverflow(t *testing.T) { + for _, scenario := range []struct { + second uint16 + expected []ownedItem + }{ + {25535, []ownedItem{{1, 51005, 152030, 42, 64, 65535}}}, + {25536, []ownedItem{{1, 51005, 152030, 42, 64, 40000}, {2, 51005, 152030, 42, 65, 25536}}}, + } { + world, _ := newStackWorld(t) + player := world.characters[1] + player.inventory.Items[0].Count, player.inventory.Items[1].Count = 40000, scenario.second + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + err := world.handleInventory(world.clients[1], stackActionPacket(1, 53, 64, 65)[20:]) + restarted := newTestInventoryServer(t).characters[1] + + if err != nil || !reflect.DeepEqual(restarted.inventory.Items, scenario.expected) || world.nextItem != 2 { + t.Fatalf("join overflowed or lost quantity: %+v %v", restarted.inventory, err) + } + } +} + +func TestStackFullInventoryAndFailedSaveKeepQuantities(t *testing.T) { + for _, scenario := range []string{"full", "split save failure", "join save failure"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newStackWorld(t) + player := world.characters[1] + request := stackActionPacket(1, 52, 64, 1)[20:] + if scenario == "full" { + for slot := uint32(66); slot < 94; slot++ { + if granted, err := world.grantItem_locked(player, 121567); err != nil || !granted { + t.Fatal(granted, err) + } + } + } else { + if scenario == "join save failure" { + request = stackActionPacket(1, 53, 64, 65)[20:] + } + if err := os.Remove("data/players/1/inventory.yaml"); err != nil { + t.Fatal(err) + } + if err := os.Mkdir("data/players/1/inventory.yaml", 0700); err != nil { + t.Fatal(err) + } + } + before, next := slices.Clone(player.inventory.Items), world.nextItem + + err := world.handleInventory(world.clients[1], request) + + if (err != nil) != (scenario != "full") || !reflect.DeepEqual(player.inventory.Items, before) || world.nextItem != next { + t.Fatalf("failed stack transaction changed state: %+v %v", player.inventory, err) + } + }) + } +} + +func TestStackConcurrentRepeatDoesNotDuplicateQuantity(t *testing.T) { + for _, scenario := range []struct { + action, argument uint32 + expected []ownedItem + }{ + {52, 1, []ownedItem{{1, 51005, 152030, 42, 64, 1}, {2, 51005, 152030, 42, 65, 3}, {3, 51005, 152030, 42, 66, 2}}}, + {53, 65, []ownedItem{{1, 51005, 152030, 42, 64, 6}}}, + } { + world, conn := newStackWorld(t) + request := stackActionPacket(1, scenario.action, 64, scenario.argument)[20:] + errors := make(chan error, 2) + var workers sync.WaitGroup + + for range 2 { + workers.Go(func() { errors <- world.handleInventory(world.clients[1], request) }) + } + workers.Wait() + close(errors) + + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + if !reflect.DeepEqual(world.characters[1].inventory.Items, scenario.expected) || len(conn.packets) != 1 { + t.Fatalf("repeated stack request duplicated quantity: %+v packets%d", world.characters[1].inventory, len(conn.packets)) + } + } +} + +func TestStackRejectedSplitRebuildsOnlySupportedStacks(t *testing.T) { + world, conn := newStackWorld(t) + player := world.characters[1] + for _, template := range []uint32{121567, 85686} { + if granted, err := world.grantItem_locked(player, template); err != nil || !granted { + t.Fatal(granted, err) + } + } + world.handleInventory(world.clients[1], inventoryMovePacket(1, 67, 21)[20:]) + world.advanceEquipment(world.clients[1].equipment.readyAt) + world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 70)[20:]) + before := slices.Clone(player.inventory.Items) + conn.packets = nil + + err := world.handleInventory(world.clients[1], stackActionPacket(1, 52, 70, 0)[20:]) + var deleted []uint32 + var moved [][2]uint32 + var added []uint32 + for _, packet := range conn.packets { + switch binary.BigEndian.Uint32(packet[16:20]) { + case 0x5e477770: + deleted = append(deleted, binary.BigEndian.Uint32(packet[37:41])) + case 0x47537a24: + moved = append(moved, [2]uint32{binary.BigEndian.Uint32(packet[33:37]), binary.BigEndian.Uint32(packet[45:49])}) + case 0x052e2f0c: + added = append(added, binary.BigEndian.Uint32(packet[41:45])) + default: + t.Fatalf("unexpected correction packet: %x", packet) + } + } + + if err != nil || len(deleted) != 29 || slices.Contains(deleted, 50) || + !reflect.DeepEqual(moved, [][2]uint32{{48, 49}, {48, 54}}) || !reflect.DeepEqual(added, []uint32{3, 3}) || + !reflect.DeepEqual(player.inventory.Items, before) || player.armorClass(90) != 5 { + t.Fatalf("correction changed non-stack items/equipment or restored wrong slots: delete%v move%v count%v %v", deleted, moved, added, err) + } +} + +func TestStackCountsSurviveCorpseAndReclaimEncoding(t *testing.T) { + corpse := &character{id: 1000000, corpse: &npcCorpse{items: []ownedItem{{1, 51005, 152030, 42, 0, 9}}}} + player := &character{id: 1, inventory: playerInventory{Reclaim: []reclaimItem{{Item: ownedItem{2, 51005, 152030, 42, 64, 7}}}}} + + loot := targetPacket(lootInventoryPacket(1, corpse, true)) + reclaim := targetPacket(reclaimInventoryPacket(player, []uint32{2})) + + if binary.BigEndian.Uint16(loot[39:41]) != 9 || binary.BigEndian.Uint16(reclaim[39:41]) != 7 { + t.Fatalf("container packets lost stack quantities: %x %x", loot, reclaim) + } +} + +func TestStackLegacyIndividualInventoriesDefaultToOne(t *testing.T) { + newStackWorld(t) + legacy := "last_id: 2\nitems:\n- id: 1\n type: 51018\n template: 121567\n quality: 1\n slot: 64\nreclaim:\n- item:\n id: 2\n type: 51018\n template: 121567\n quality: 1\n slot: 65\n available_at: 2020-01-01T00:00:00Z\n" + if err := os.WriteFile("data/players/1/inventory.yaml", []byte(legacy), 0600); err != nil { + t.Fatal(err) + } + + player := newTestInventoryServer(t).characters[1] + + if player.inventory.Items[0].Count != 1 || player.inventory.Reclaim[0].Item.Count != 1 { + t.Fatalf("legacy individuals lost their quantity: %+v", player.inventory) + } +} diff --git a/server/target_protocol.go b/server/target_protocol.go @@ -109,9 +109,13 @@ func targetPacket(packet []byte) []byte { binary.BigEndian.PutUint32(packet[52:56], destination-16) } case 0x5e477770: - if binary.BigEndian.Uint32(packet[36:40]) == 112 && binary.BigEndian.Uint32(packet[40:44]) == 104 { + action := binary.BigEndian.Uint32(packet[36:40]) + 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 { + binary.BigEndian.PutUint32(packet[52:56], binary.BigEndian.Uint32(packet[52:56])-16) + } case 0x54111123: packet = append(packet[:36:36], encodeMovement1491(packet[36:])...) case 0x5f52412e: @@ -148,9 +152,13 @@ func decodeInventory1491(body []byte) { binary.BigEndian.PutUint32(body[32:36], decodeInventorySlot1491(destination)) } case 0x5e477770: - if binary.BigEndian.Uint32(body[16:20]) == 112 && binary.BigEndian.Uint32(body[20:24]) == 104 { + action := binary.BigEndian.Uint32(body[16:20]) + if (action == 52 || action == 53 || action == 112) && binary.BigEndian.Uint32(body[20:24]) == 104 { binary.BigEndian.PutUint32(body[24:28], decodeInventorySlot1491(binary.BigEndian.Uint32(body[24:28]))) } + if action == 53 && binary.BigEndian.Uint32(body[28:32]) == 104 { + binary.BigEndian.PutUint32(body[32:36], decodeInventorySlot1491(binary.BigEndian.Uint32(body[32:36]))) + } } } diff --git a/server/users.go b/server/users.go @@ -181,6 +181,17 @@ func (server *server) loadUsers() error { if err := decodeUsers(bytes.NewReader(contents), &server.characters[user.ID].inventory); err != nil { return fmt.Errorf("%s: %w", inventoryPath, err) } + // Inventories saved before quantities existed contain individual items. + for index := range server.characters[user.ID].inventory.Items { + if server.characters[user.ID].inventory.Items[index].Count == 0 { + server.characters[user.ID].inventory.Items[index].Count = 1 + } + } + for index := range server.characters[user.ID].inventory.Reclaim { + if server.characters[user.ID].inventory.Reclaim[index].Item.Count == 0 { + server.characters[user.ID].inventory.Reclaim[index].Item.Count = 1 + } + } if err := server.characters[user.ID].inventory.validate(); err != nil { return fmt.Errorf("%s: %w", inventoryPath, err) } diff --git a/server/world.go b/server/world.go @@ -147,10 +147,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) - // Individual exact-template entries carry flags 2 and count 1. + // Template-stack rows need flag 1; individual live-item rows retain flag 2. 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} { + flags := uint32(2) + if item.isEssenceStack() { + flags = 1 + } + for _, value := range []uint32{item.Slot, flags<<16 | uint32(item.Count), item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { body = binary.BigEndian.AppendUint32(body, value) } }