aorecomp

Anarchy Online classic in the browser

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


commit 352917afef9d899be4c161adf4d6bbd1fa28d9cf
parent 1710165a4ffd93e0323a42b21598bbdd912865e7
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 17:50:57 +0000

Enable trading with starter NPC vendors

Diffstat:
MTODO.md | 17+++++++++--------
Adocs/npc-shops.md | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_npc_shops_test.go | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/gamedata/npc_shops.go | 11+++++++++++
Mserver/gamedata/shop_stock.yaml | 5+++++
Mserver/main.go | 2+-
Aserver/npc_shops_test.go | 166+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/shop_purchases_test.go | 2+-
Mserver/shops.go | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mserver/world_actions.go | 10++++++++++
Atools/client/test_npc_shops.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 562 insertions(+), 20 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -48,14 +48,15 @@ research separately. More screenshots and test cases do not count as new gamepla The specific Trade report remains unreproduced; its actor/location or a new failing capture is needed before repeating the passing Trade scenarios. -- [ ] **A2: NPC vendors respond and trade.** Start with the two OT Food Providers - in Omni Trade (`710/district/0/fixed/18` and `19`). The current machine-only - purchase handler and dialogue registry do not implement these vendors. - Implement reusable NPC shop admission using the existing quote/transaction - rules, then bind the starter vendors on each faction's chosen early route. - Completion: ordinary E/right-click opens a usable stock window; buy, sell, - cancel, range rejection and reconnect preserve credits and item identity. - Record the exact route/vendor set before expanding beyond it. +- [x] **A2: NPC vendors respond and trade.** The two Omni Trade Food Providers + (`710/district/0/fixed/18` and `19`) and each faction's training-ground + Secondhand Peddler share shop admission and atomic quote/transaction rules. + November 5: all five original placements passed real E/right-click, buy/sell, + cancel, range cancellation and reconnect checks, preserving credits and exact + item identities. Catalog objects are removed when the shop closes, allowing + repeated NPC interaction. Stock selection is provisional; a temporary pickup + box at the seller's feet remains a visual limitation while the window is open. + See [the finite vendor set, verification and evidence limits](docs/npc-shops.md). - [ ] **A3: Recognizable NPC appearances on early routes.** Start with Omni-Tek Elite Guards in Omni Trade. Their provisional body mappings do not establish diff --git a/docs/npc-shops.md b/docs/npc-shops.md @@ -0,0 +1,116 @@ +# Starter NPC vendors + +A2 covers exactly these five original population placements. It does not add +vendors by name or promote every human NPC to a merchant. + +| NPC | Stable group | Original position | Catalog/price template | +| --- | --- | --- | --- | +| OT Food Provider | `710/district/0/fixed/18` | 514.2, 11.0001, 365.3 | OT Food 120973 | +| OT Food Provider | `710/district/0/fixed/19` | 412.7, 17.000101, 352.09998 | OT Food 120973 | +| Secondhand Peddler, Omni training | `950/district/1/fixed/0` | 189.06712, 15.541694, 52.672432 | Startup Shop 27054 | +| Secondhand Peddler, Clan training | `952/district/3/fixed/0` | 189.9154, 15.833457, 48.40023 | Startup Shop 27054 | +| Secondhand Peddler, Neutral training | `954/district/1/fixed/0` | 194.15007, 3.6784623, 153.59198 | Startup Shop 27054 | + +The early route for this gate is each faction's training ground and these two +reported Trade providers. Existing population YAML supplies placement and body; +this change does not establish historical outfits or expand the appearance gate. + +## Stock policy and evidence limits + +Food Providers offer QL1 Chocolate Chip Muffin 130581 and Bottle of Fresh Water +130593. Peddlers offer QL1 Treatment Laboratory 25812, Simple Nano Kit 85366, +Basic Nano Recharger 25820, and the four original 100-round ammunition packages +21605, 21609, 21613 and 21601. The existing catalog and transaction mechanisms +supply original item identities, charges and prices. + +This finite stock selection and its assignment to NPCs are reconstruction +policy. Original NPC stock lists, refresh rules and NPC-specific price modifiers +have not been recovered. Original vending templates supply modifiers 426/427: +OT Food uses 6/100 and Startup Shop uses 4/105. The OT Food template's ordinary +faction-use criterion is retained. Stock belongs to the shared original template, +so the existing OT Food machine using 120973 receives the same two food entries. +The food's original use action is head text; this is not a claim of healing. + +Sources are the maintained original item records (120973 in `items_036.yaml`, +27054 in `items_000.yaml`, food in `items_051.yaml`) and population records in +`zones/zone_710.yaml`, `zone_950.yaml`, `zone_952.yaml`, `zone_954.yaml`. +The maintained OFPO name/body identification uses a later observation at the +matching placement. SOPD identification uses later Neutral training observations. +Neither proves the 14.9.1 stock. Reopen historical stock research only with an +original server stock source or a recorded NPC transaction, not another broad +search for these names. + +## Native interaction and shared transactions + +The shipped 14.9.1 `kkr.dll` SHA-256 is +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +REA/Ghidra 12.1.2 observations are retained in +`local/npc-vendors/native-evidence.json`: + +- `0x1002c350`, `N3Msg_DefaultActionOnDynel`, chooses TradeStart for a live + non-dialogue SimpleChar. Evidence `ev_a7c19a7ab89247d290564d7b4a8a50386b784d615766760e5dde01aadf6d9302`. +- `0x1001f840`, `N3Msg_TradeStart`, enforces five-meter distance and sends + Trade action 0 with the target character as A and zero B. Evidence + `ev_3713f64b56c7dcbfbaf17bbb427614f27cdddc700c98dcefd838430491917fc9`. +- `0x100262c0`, `N3Msg_ShopGetItemCost`, and `0x10027060`, + `N3Msg_GetShopItemStat`, require a `VendingMachine_t` dynamic cast. + Evidence `ev_a3b8934cc052fbedafd95e83132e81abd2155182071537f4827cb1a31ba805ab` + and `ev_a19611d663074f066e888118d20acdedcd3f75f204e9c62fdaaf91db1c9e8304`. + +The server answers the character's TradeStart, or E-key Use (kind 0), with a +connection-local vending catalog, typed `(51035, NPC instance)`, at the NPC's +position. The NPC remains the interaction target; this auxiliary object supplies the native shop +catalog and pricing interface. This proxy arrangement is an implementation +inferred from the observed client requirements, not a recovered server packet +capture. Existing machine-side and player-side trade initialization, catalog +page 111 and quote/transaction handling are shared without a second economy. + +The catalog uses Mesh12=0, which selects the original pickup-box fallback. +It exists only while the shop is open: completion, cancellation and range +cleanup close the trade and remove the auxiliary object. The temporary box at +the seller's feet is a provisional visual limitation, not an original NPC-shop +presentation claim. It must not remain and block the next NPC interaction. + +Bounded rendering research found that full-update attachment `0x100b25c0` +explicitly enables world visibility, overriding an initial cleared flag. +Parenting and model-free variants failed to open the native catalog. Initial +and immediate post-creation scale updates left the model full-sized; static +mesh loading can discard a scale update before resource readiness. No supported +visibility-only message was established. Reopen this question with an original +NPC-shop packet capture or evidence of a message that hides a registered item +without changing its catalog lifetime. Attachment evidence is retained in +`local/npc-vendors/attachment-evidence.json`, evidence +`ev_9295844f53cfb301b5bcd2ccb11e6a28bd022289e57dd1dcf8b8e6156f3b7211`. + +Admission checks the current NPC, maintained binding, visibility, life, zone +and five-meter player distance at start and on every subsequent trade action. +Existing player session/equipment/trade admission and item-use requirements +also apply. Missing/despawned/dead/out-of-range sellers cannot commit a basket. +Movement outside range also aborts the server draft: the native movement path +can close the window without sending TradeAbort. This cleanup is shared with +ordinary vending machines, so a hidden stale draft cannot retain offered items. +Purchased items, sold ownership and credits use the existing atomic SQLite +transaction, and cancellation restores the same offered identities. + +## Verification + +Handler regressions cover all five bindings through purchase, sale and cold +reload, plus rejection at start and Accept for unseen, dead, removed, unbound, +non-NPC, other-zone and out-of-range sellers. The browser regression uses the +original placements, controlled funds and one sale item; it is not evidence of +earned progression. Run it with +`AO_GAME_TEST=1 go test ./server -run '^TestBrowserNPCShops$' -count=1 -timeout=12m -v`. +November 5 native checks passed all five original placements: right-click and E +open stock with displayed prices, sale plus purchase commits once, cancellation +retains ownership, reconnect replays the exact purchased identity, and ordinary +movement outside range cancels the server draft. Each close also removes the +auxiliary catalog from the client; subsequent NPC picking succeeds. The Go +fixture verifies the same inventory and credits after a cold database reload. +Retained artifacts are `local/npc-vendors/20261105-094512` (Omni training) and +`local/npc-vendors/20261105-094608` (the other four routes). + +All 104 focused server tests passed with selection +`^Test(NPCShop|Shop|PlayerTrade|StaticItemUseDoesNotAliasCollidingShop|Held)`. +This includes rejected-write/retry, item packing, original machine admission, +player-trade isolation and the new seller/range checks. Output is retained in +`local/npc-vendors/regressions-final.log`. diff --git a/server/browser_npc_shops_test.go b/server/browser_npc_shops_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" +) + +func TestBrowserNPCShops(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the five starter NPC vendors") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/npc-vendors", time.Now().Format("20060102-150405")) + for _, route := range []string{"710/district/0/fixed/18", "710/district/0/fixed/19", "950/district/1/fixed/0", "952/district/3/fixed/0", "954/district/1/fixed/0"} { + t.Run(route, func(t *testing.T) { + world := newTestServer(t) + var npc *character + for _, actor := range world.characters { + if actor.npcDefinitionID == route { + npc = actor + break + } + } + if npc == nil { + t.Fatal("starter vendor is absent from the original population") + } + player := world.newCharacter() + player.playfield, player.position, player.appearance = npc.playfield, npc.position, 0x515 + if npc.playfield == 952 { + player.appearance = 0x315 + } else if npc.playfield == 954 { + player.appearance = 0x115 + } + player.position[1] += .75 + player.position[2] -= 3 + player.rotation = [4]float32{0, 0, 0, 1} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("npc-shops"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{Credits: 1000, LastID: 1, Items: []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + open, sales, purchases := false, 0, uint16(0) + if client := world.clients[1]; client != nil && client.shop != nil { + open, sales, purchases = true, len(client.shop.items), client.shop.purchases[0] + } + json.NewEncoder(w).Encode(map[string]any{"npc": npc.id, "route": route, "position": npc.position, + "open": open, "sales": sales, "purchases": purchases, "inventory": player.inventory}) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_npc_shops.mjs"), host.URL, filepath.Join(output, route)) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + t.Logf("Browser artifacts: %s", filepath.Join(output, route)) + if err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t).characters[1].inventory + if !reflect.DeepEqual(cold, player.inventory) || len(cold.Items) != 1 || cold.Items[0].ID != 2 || cold.Credits == 1000 { + t.Fatal("NPC purchase/sale did not persist exactly once", cold) + } + }) + } +} diff --git a/server/gamedata/npc_shops.go b/server/gamedata/npc_shops.go @@ -0,0 +1,11 @@ +package gamedata + +// NPCShops binds the finite starter route to original vending templates. +// Stock and price-template selection are reconstruction policy; see docs/npc-shops.md. +var NPCShops = map[string]uint32{ + "710/district/0/fixed/18": 120973, + "710/district/0/fixed/19": 120973, + "950/district/1/fixed/0": 27054, + "952/district/3/fixed/0": 27054, + "954/district/1/fixed/0": 27054, +} diff --git a/server/gamedata/shop_stock.yaml b/server/gamedata/shop_stock.yaml @@ -95,3 +95,8 @@ - {template: 70565, quality: 2} 99502: *basic_armor 99570: *basic_armor + +# NPC starter route: fixed QL1 food and medical/ammunition subsets. +# These are provisional catalogs, not recovered NPC stock; docs/npc-shops.md. +120973: [{template: 130581, quality: 1}, {template: 130593, quality: 1}] +27054: [{template: 25812, quality: 1}, {template: 85366, quality: 1}, {template: 25820, quality: 1}, {template: 21605, quality: 1}, {template: 21609, quality: 1}, {template: 21613, quality: 1}, {template: 21601, quality: 1}] diff --git a/server/main.go b/server/main.go @@ -575,7 +575,7 @@ func (server *server) serveWorldClient(client *worldClient) error { err = server.handleReload(client, body) } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 101 || binary.BigEndian.Uint32(body[40:44]) == 102 || binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 107 || binary.BigEndian.Uint32(body[40:44]) == 51017) { err = server.handleOwnedItemUse(client, body) - } else if len(body) == 48 && binary.BigEndian.Uint32(body[40:44]) == 51035 { + } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 51035 || binary.BigEndian.Uint32(body[40:44]) == 50000) { err = server.handleShopUse(client, body) } else if len(body) == 48 && binary.BigEndian.Uint32(body[40:44]) == 56001 { err = server.handleMissionBoothUse(client, body) diff --git a/server/npc_shops_test.go b/server/npc_shops_test.go @@ -0,0 +1,166 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "reflect" + "testing" +) + +func TestNPCShopRoutesBuySellAndReload(t *testing.T) { + for _, route := range []string{"710/district/0/fixed/18", "710/district/0/fixed/19", "950/district/1/fixed/0", "952/district/3/fixed/0", "954/district/1/fixed/0"} { + t.Run(route, func(t *testing.T) { + world, conn := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.appearance = 0x515 + npc := &character{id: 1000001, npc: true, health: 100, npcDefinitionID: route, playfield: player.playfield, position: player.position} + world.characters[npc.id] = npc + client.npcs = map[uint32]bool{npc.id: true} + player.inventory.Credits = 1000 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + for _, request := range [][]byte{ + shopTradePacket([2]uint32{50000, 1}, 0, [2]uint32{50000, npc.id}, [2]uint32{}), + shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64}), + shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, npc.id}, [2]uint32{111, 0}), + shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{}), + } { + if err := world.handleTrade(client, request[20:]); err != nil { + t.Fatal(err) + } + } + + want := ownedItem{ID: 2, Type: 51005, Template: 25812, Quality: 1, Slot: 64, Count: 50} + credits := uint32(1327) + if gamedata.NPCShops[route] == 120973 { + want.Type, want.Template, want.Count = 51018, 130581, 1 + credits = 1702 + } + cold := newTestInventoryServer(t).characters[1].inventory + if client.shop != nil || !reflect.DeepEqual(player.inventory.Items, []ownedItem{want}) || player.inventory.Credits != credits || !reflect.DeepEqual(cold, player.inventory) { + t.Fatalf("NPC transaction or cold reload differs: live=%+v cold=%+v", player.inventory, cold) + } + if len(conn.packets) < 4 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x7f544905 || + binary.BigEndian.Uint32(conn.packets[0][20:24]) != 51035 || binary.BigEndian.Uint32(conn.packets[0][24:28]) != npc.id || + binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x58362220 || binary.BigEndian.Uint32(conn.packets[1][24:28]) != npc.id { + t.Fatal("NPC trade did not create its private vending catalog") + } + }) + } +} + +func TestNPCShopRevalidatesSellerOnStartAndAccept(t *testing.T) { + for _, stage := range []string{"start", "accept"} { + for _, invalid := range []string{"unseen", "dead", "other zone", "outside range", "unbound", "removed", "player"} { + t.Run(stage+"/"+invalid, func(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + npc := &character{id: 1000001, npc: true, health: 100, npcDefinitionID: "950/district/1/fixed/0", playfield: player.playfield, position: player.position} + world.characters[npc.id] = npc + client.npcs = map[uint32]bool{npc.id: true} + before := player.inventory + request := shopTradePacket([2]uint32{50000, 1}, 0, [2]uint32{50000, npc.id}, [2]uint32{}) + if stage == "accept" { + if err := world.handleTrade(client, request[20:]); err != nil || client.shop == nil { + t.Fatalf("open NPC shop: %v", err) + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil { + t.Fatal(err) + } + request = shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{}) + } + switch invalid { + case "unseen": + delete(client.npcs, npc.id) + case "dead": + npc.health = 0 + case "other zone": + npc.playfield++ + case "outside range": + npc.position[0] += 6 + case "unbound": + npc.npcDefinitionID = "950/district/2/group/0/authored_point" + case "removed": + delete(world.characters, npc.id) + case "player": + npc.npc = false + } + + if err := world.handleTrade(client, request[20:]); err != nil { + t.Fatal(err) + } + + if client.shop != nil || client.trade != nil || !reflect.DeepEqual(player.inventory, before) || + !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory, before) { + t.Fatal("unavailable NPC accepted a trade or changed ownership") + } + }) + } + } +} + +func TestNPCShopKeyboardUseAndCancellation(t *testing.T) { + world, conn := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + npc := &character{id: 1000001, npc: true, health: 100, npcDefinitionID: "950/district/1/fixed/0", playfield: player.playfield, position: player.position} + world.characters[npc.id] = npc + client.npcs = map[uint32]bool{npc.id: true} + before := player.inventory + request := shopUseRequest(1) + binary.BigEndian.PutUint32(request[28:32], 0) + binary.BigEndian.PutUint32(request[40:44], 50000) + binary.BigEndian.PutUint32(request[44:48], npc.id) + + if err := world.handleShopUse(client, request); err != nil || client.shop == nil { + t.Fatalf("native E Use did not open NPC catalog: %v", err) + } + if binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 { + t.Fatal("NPC Use was not acknowledged") + } + for _, packet := range [][]byte{ + shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64}), + shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{}), + } { + if err := world.handleTrade(client, packet[20:]); err != nil { + t.Fatal(err) + } + } + + if client.shop != nil || !reflect.DeepEqual(player.inventory, before) || + !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory, before) { + t.Fatal("NPC shop cancellation changed the offered item's identity or credits") + } +} + +func TestNPCShopMovementCancelsOutsideRange(t *testing.T) { + world, _ := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + world.characters[1000001] = &character{id: 1000001, npc: true, health: 100, npcDefinitionID: "950/district/1/fixed/0", playfield: player.playfield} + client.npcs = map[uint32]bool{1000001: true} + before := player.inventory + for _, packet := range [][]byte{ + shopTradePacket([2]uint32{50000, 1}, 0, [2]uint32{50000, 1000001}, [2]uint32{}), + shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64}), + } { + if err := world.handleTrade(client, packet[20:]); err != nil { + t.Fatal(err) + } + } + if client.shop == nil || len(client.shop.items) != 1 { + t.Fatal("NPC sale draft was not prepared") + } + + if err := world.handleMovement(client, playerMovementRequest(&character{id: 1, position: [3]float32{4, 0, 0}, rotation: [4]float32{0, 0, 0, 1}}, 4)); err != nil || client.shop == nil { + t.Fatalf("movement within range cancelled the shop: %v", err) + } + if err := world.handleMovement(client, playerMovementRequest(&character{id: 1, position: [3]float32{6, 0, 0}, rotation: [4]float32{0, 0, 0, 1}}, 4)); err != nil { + t.Fatal(err) + } + + if client.shop != nil || !reflect.DeepEqual(player.inventory, before) || + !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory, before) { + t.Fatal("movement retained an unreachable draft or lost its offered item") + } +} diff --git a/server/shop_purchases_test.go b/server/shop_purchases_test.go @@ -67,7 +67,7 @@ func TestShopKnownStockOnlyAdmitsSupportedItemQualities(t *testing.T) { for _, entry := range templates { template := entry.Template definition := gamedata.ItemTemplates[template] - if !gamedata.ItemQualitySupported(template, entry.Quality) || (definition.HeaderWords[0] != 51005 && definition.HeaderWords[0] != 51022 && definition.HeaderWords[0] != 51054) { + if !gamedata.ItemQualitySupported(template, entry.Quality) || (definition.HeaderWords[0] != 51005 && definition.HeaderWords[0] != 51018 && definition.HeaderWords[0] != 51022 && definition.HeaderWords[0] != 51054) { t.Fatalf("stock %d needs a separately verified delivery/packing path", template) } item := ownedItem{Type: definition.HeaderWords[0], Template: template, Quality: entry.Quality} diff --git a/server/shops.go b/server/shops.go @@ -17,6 +17,24 @@ type shopTrade struct { purchases map[uint32]uint16 } +func (server *server) shopMachine_locked(client *worldClient, id uint32) (gamedata.ShopMachine, bool) { + if machine, exists := gamedata.ShopMachines[id]; exists { + return machine, true + } + npc := server.characters[id] + if npc == nil || !npc.npc || npc.health == 0 || !client.npcs[id] { + return gamedata.ShopMachine{}, false + } + template, exists := gamedata.NPCShops[npc.npcDefinitionID] + if !exists { + return gamedata.ShopMachine{}, false + } + // Native catalog/quote APIs require VendingMachine_t. Keep admission on the + // NPC; Mesh12=0 uses the pickup box only for the lifetime of its private catalog. + return gamedata.ShopMachine{Template: template, Playfield: npc.playfield, Position: npc.position, + Rotation: npc.rotation, Stats: [][2]uint32{{12, 0}}}, true +} + func (server *server) canUseShop_locked(client *worldClient, machine gamedata.ShopMachine) bool { player := server.characters[client.id] if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || @@ -58,11 +76,13 @@ func (server *server) handleShopUse(client *worldClient, body []byte) error { if len(body) != 48 { return fmt.Errorf("invalid shop use length") } + // E sends character Use with kind 0; a vending machine uses kind 1. + targetType, kind := binary.BigEndian.Uint32(body[40:44]), binary.BigEndian.Uint32(body[28:32]) if binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 3 || - binary.BigEndian.Uint32(body[28:32]) != 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 || + binary.BigEndian.Uint32(body[32:36]) != 50000 || binary.BigEndian.Uint32(body[36:40]) != client.id || - binary.BigEndian.Uint32(body[40:44]) != 51035 || + !(targetType == 51035 && kind == 1 || targetType == 50000 && kind == 0) || !client.target || server.clients[client.id] != client || !client.ready || client.loading { return nil } @@ -72,8 +92,12 @@ func (server *server) handleShopUse(client *worldClient, body []byte) error { } client.useSequence = sequence machineID := binary.BigEndian.Uint32(body[44:48]) - machine, exists := gamedata.ShopMachines[machineID] + machine, exists := server.shopMachine_locked(client, machineID) accepted := exists && server.canUseShop_locked(client, machine) + if targetType == 50000 { + npc := server.characters[machineID] + accepted = accepted && npc != nil && npc.npc + } reply := append([]byte(nil), body[16:]...) binary.BigEndian.PutUint32(reply, 2) if accepted { @@ -82,6 +106,10 @@ func (server *server) handleShopUse(client *worldClient, body []byte) error { if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil || !accepted { return err } + return server.startShop_locked(client, machineID, machine) +} + +func (server *server) startShop_locked(client *worldClient, machineID uint32, machine gamedata.ShopMachine) error { if client.shop != nil { if err := server.abortShop_locked(client); err != nil { return err @@ -126,8 +154,22 @@ func (server *server) abortShop_locked(client *worldClient) error { return err } } + return server.finishShop_locked(client, 2) +} + +func (server *server) finishShop_locked(client *worldClient, action uint32) error { + shop := client.shop client.shop = nil - return client.send(shopTradePacket([2]uint32{50000, client.id}, 2, [2]uint32{}, [2]uint32{})) + if err := client.send(shopTradePacket([2]uint32{50000, client.id}, action, [2]uint32{}, [2]uint32{})); err != nil { + return err + } + // NPC catalogs are connection-local and must not obstruct the next interaction. + if shop != nil { + if _, machine := gamedata.ShopMachines[shop.machine]; !machine { + return client.send(n3Packet(0x36510078, 51035, shop.machine, nil)) + } + } + return nil } func restoredTradeInventory(inventory playerInventory, offers map[uint32]ownedItem, returned []uint32) (playerInventory, map[uint32]ownedItem) { @@ -237,19 +279,28 @@ func (server *server) handleTrade(client *worldClient, body []byte) error { return nil } action := binary.BigEndian.Uint32(body[20:24]) + first := [2]uint32{binary.BigEndian.Uint32(body[24:28]), binary.BigEndian.Uint32(body[28:32])} + second := [2]uint32{binary.BigEndian.Uint32(body[32:36]), binary.BigEndian.Uint32(body[36:40])} + if action == 0 && first[0] == 50000 && second == [2]uint32{} { + if npc := server.characters[first[1]]; npc != nil && npc.npc { + machine, exists := server.shopMachine_locked(client, npc.id) + if exists && server.canUseShop_locked(client, machine) { + return server.startShop_locked(client, npc.id, machine) + } + return nil + } + } if action == 0 || client.trade != nil { return server.handlePlayerTrade_locked(client, body) } if client.shop == nil { return nil } - machine := gamedata.ShopMachines[client.shop.machine] - if action == 2 || !server.canUseShop_locked(client, machine) { + machine, exists := server.shopMachine_locked(client, client.shop.machine) + if action == 2 || !exists || !server.canUseShop_locked(client, machine) { return server.abortShop_locked(client) } player := server.characters[client.id] - first := [2]uint32{binary.BigEndian.Uint32(body[24:28]), binary.BigEndian.Uint32(body[28:32])} - second := [2]uint32{binary.BigEndian.Uint32(body[32:36]), binary.BigEndian.Uint32(body[36:40])} if (action == 4 || action == 5) && first == [2]uint32{51035, client.shop.machine} { if second[0] != 111 || second[1] >= uint32(len(client.shop.stock)) { return server.abortShop_locked(client) @@ -406,8 +457,7 @@ func (server *server) handleTrade(client *worldClient, body []byte) error { } server.nextItem = nextItem } - client.shop = nil - if err := client.send(shopTradePacket([2]uint32{50000, client.id}, 3, [2]uint32{}, [2]uint32{})); err != nil { + if err := server.finishShop_locked(client, 3); err != nil { return err } // Deliver first-free rows in the same order as the durable allocation. diff --git a/server/world_actions.go b/server/world_actions.go @@ -199,6 +199,16 @@ func (server *server) handleMovement(client *worldClient, body []byte) error { if client.trade != nil && !server.playerTradeAvailable_locked(client.trade.clients[0], client.trade.clients[1]) { server.cancelPlayerTrade_locked(client) } + // Native movement may close the shop locally without sending TradeAbort. + if client.shop != nil { + machine, exists := server.shopMachine_locked(client, client.shop.machine) + if !exists || !server.canUseShop_locked(client, machine) { + if err := server.abortShop_locked(client); err != nil { + server.mutex.Unlock() + return err + } + } + } // Locomotion interrupts an admitted cast; rotation-only updates do not. updates := make(map[*worldClient][][]byte) if client.bank != nil && !server.bankAvailable_locked(client) { diff --git a/tools/client/test_npc_shops.mjs b/tools/client/test_npc_shops.mjs @@ -0,0 +1,97 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +let game; +const evidence = {}; +try { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'npc-shops', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const cell = (state, page, slot) => state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === page && cell.identity[1] === slot && !cell.dummy); + const clickCell = async source => game.click( + (source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); + const waitServer = async (description, predicate) => { + const deadline = Date.now() + 5000; + while (!predicate(await server())) { + assert(Date.now() < deadline, description); + await game.snapshot(); + } + }; + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + evidence.before = await server(); + if (!game.state.camera.firstPerson) await game.key('F8'); + await game.key('KeyI'); + const open = async keyboard => { + await game.click(...await game.pick(50000, evidence.before.npc), keyboard ? 'left' : 'right'); + if (keyboard) await game.key('KeyE'); + await game.wait('NPC catalog opens', state => cell(state, 111, 0)); + assert((await server()).open); + }; + await open(false); + await game.save(output + '/catalog'); + await clickCell(cell(game.state, 111, 0)); + await waitServer('catalog purchase selected', state => state.purchases === 1); + await clickCell(cell(game.state, 104, 48)); + await game.wait('sale item picked', state => state.dragged[0] === 104); + await game.click(860, 412); + await waitServer('axe offered', state => state.sales === 1); + await game.save(output + '/basket'); + await game.click(873, 475); + await waitServer('NPC sale and purchase committed', state => !state.open && state.inventory.Items.length === 1 && state.inventory.Items[0].ID === 2); + await game.wait('completed catalog removed', state => !state.actors.some(actor => actor.type === 51035 && actor.id === evidence.before.npc)); + evidence.purchased = await server(); + const food = evidence.before.route.startsWith('710/'); + assert.equal(evidence.purchased.inventory.Credits, food ? 1702 : 1327); + assert.deepEqual(evidence.purchased.inventory.Items, [{ID: 2, Type: food ? 51018 : 51005, + Template: food ? 130581 : 25812, Quality: 1, Slot: 64, Count: food ? 1 : 50, Ammo: 0}]); + + // E uses the selected living NPC; cancellation retains the same owned item. + await open(true); + console.log('Verified E-key catalog', evidence.before.route); + await clickCell(cell(game.state, 111, 0)); + await waitServer('second selection', state => state.purchases === 1); + await game.click(945, 475); + await waitServer('cancelled', state => !state.open); + await game.wait('cancelled catalog removed', state => !state.actors.some(actor => actor.type === 51035 && actor.id === evidence.before.npc)); + assert.deepEqual((await server()).inventory, evidence.purchased.inventory); + await page.reload({waitUntil: 'domcontentloaded'}); + await page.waitForFunction(() => typeof Module !== 'undefined' && typeof Module._browser_test_request === 'function', null, {timeout: 30000}); + await game.ready(); + console.log('Reload ready', evidence.before.route); + evidence.reloaded = await server(); + assert.deepEqual(evidence.reloaded.inventory, evidence.purchased.inventory); + await game.wait('durable purchased identity replayed', state => game.local(state).inventory.some(item => item.id === 2)); + + // Keep a draft open while ordinary backward movement leaves the seller's range. + if (!game.state.camera.firstPerson) await game.key('F8'); + await open(false); + await clickCell(cell(game.state, 111, 0)); + await waitServer('range draft selected', state => state.purchases === 1); + await game.hold('KeyS', 'walk out of NPC range', state => Math.hypot( + game.local(state).position[0] - evidence.before.position[0], + game.local(state).position[2] - evidence.before.position[2]) > 6); + await waitServer('leaving NPC range cancels the draft', state => !state.open); + await game.wait('out-of-range catalog removed', state => !state.actors.some(actor => actor.type === 51035 && actor.id === evidence.before.npc)); + evidence.outside = await server(); + assert.deepEqual(evidence.outside.inventory, evidence.purchased.inventory); + assert.deepEqual(game.errors, []); + console.log('PASS:', evidence.before.route, 'right-click/E, purchase/sale, cancel, reconnect and range rejection'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + if (game) await game.save(output + '/final'); + } finally { await browser.close(); } +}