aorecomp

Anarchy Online classic in the browser

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


commit ae241d4e5c56f072b2f69c4717baf705fefd37dd
parent dd406a93bf95fc52a007d3698de23b761b4d438c
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 21:42:04 +0000

Collect reviewed world resources with durable independent depletion

Diffstat:
MTODO.md | 26+++++++++++++++++++++++---
Mdocs/npc-mapping-integration.md | 17++++++++++-------
Mdocs/npc-profile-eligibility.md | 4++--
Adocs/resource-pickup.md | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_resource_pickup_test.go | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/item_families.yaml | 2++
Mserver/gamedata/item_quality_test.go | 1+
Mserver/item_database.go | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mserver/item_store.go | 43++++++++++++++++++++++++++-----------------
Mserver/state.go | 49+++++++++++++++++++++++++------------------------
Mserver/world.sql | 3+++
Mserver/world_items.go | 31++++++++++++++++++++++++++-----
Aserver/world_resource_pickup_test.go | 241+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/world_resources.go | 9++++++++-
Mserver/world_resources_test.go | 9++++-----
Atools/client/test_resource_pickup.mjs | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_resource_pickup_cold.mjs | 41+++++++++++++++++++++++++++++++++++++++++
17 files changed, 835 insertions(+), 66 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -918,13 +918,26 @@ for exact records, protocol, tests and remaining reconstruction assumptions. resources. Carbonrich Rocks render through original item template150274 and mesh55669, with durable item identities and atomic zone allocation. Explicit template-bound profiles can admit reviewed best-effort identities; generic - species profiles still require species evidence. Harvesting, replenishment, - summon/pet behavior and stronger historical identity evidence remain open. + species profiles still require species evidence. Raw rock pickup now preserves + the same instance and atomically records source depletion; extraction-tool + processing, replenishment, summon/pet behavior and stronger historical identity + evidence remain open. See [mapping integration](docs/npc-mapping-integration.md). - [x] Import the complete NPC mapping catalog and per-group evidence, preserve authored population structure, and render Carbonrich Rocks as world resources. - Test zone allocation, replay, cold loading, forbidden pickup/combat, item-ID + Test zone allocation, replay, cold loading, refused creature combat, item-ID exhaustion and database failure rollback through the shared item store. +- [x] Collect a reviewed carry-only Carbonrich Rock through ordinary world pickup. + Reproduction: select an original type51005 rock within five metres and press R; + the former mission-only path refused it. Completion: the same item ID, QL and + template reach native inventory, both native views remove only that source, and + independent depletion survives page/cold replay and collected-item deletion. + Required-write failures publish nothing and retry once; competing collectors + yield one durable owner. World packets now include the original pickup + template fields, fixing the observed fresh native row with template IDs0/0. + Controlled fixtures establish these checks, not earned progression. Refill + timing and original quality distribution remain evidence gaps, and Jensen + processing remains separate. See [resource pickup](docs/resource-pickup.md). - [x] Give one creature at one level an explicit combat profile. Check: its health, weapon and timing come from that profile rather than universal values; each value is identified as verified or provisional. @@ -2464,6 +2477,13 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). GPU WASM verifies the visible floor model, immediate native pickup icon, page reconnect, exit/reentry and cold-server recovery with no respawn. See [mission floor items](docs/mission-objectives.md). +- [ ] [P0] Remove the collector's mission-floor model after successful pickup. + Reproduction: native R creates the Blue Book inventory proxy, but the collected + snapshot still contains type51005:3 and its selected floor label until reload; + see `local/mission-generation/20261103-103107/collected/`. Completion: a fixture + beside the book verifies immediate collector removal after the move reply, + usable inventory metadata, unchanged physical ownership and page/cold replay. + Preserve failure rollback, duplicate-request refusal and observer isolation. - [x] [P1] Preserve native template metadata when collecting mission-floor items. World stat23 supplies the visible resource, while the original pickup descriptor independently reads stat702/703. Supply the authored low endpoint in stat702 diff --git a/docs/npc-mapping-integration.md b/docs/npc-mapping-integration.md @@ -56,10 +56,11 @@ Allocation failure publishes neither partial items nor a new item counter. The original source level range currently selects resource quality using the existing inclusive placement cycle. That policy is provisional. Rocks are -inspectable world objects; harvesting, extraction-tool eligibility, depletion, -replenishment and resulting tradeskill items still require implementation. -They cannot be collected through the mission-objective pickup path or attacked -as characters. Summon mappings likewise still need pet ownership and lifecycle +inspectable world objects. Reviewed carry-only rocks can now be collected through +the shared world pickup path, with independent durable depletion and native +pickup-template delivery; see [resource pickup](resource-pickup.md). Replenishment, +extraction-tool eligibility and resulting tradeskill items remain open. Rocks +cannot be attacked as characters. Summon mappings likewise still need pet ownership and lifecycle integration before they constitute playable summons. ## Evidence and checks @@ -72,7 +73,8 @@ Go checks pass. Rebuilding the catalog reproduces the retained JSON exactly. New regressions cover static-item packets and zone scope, stable other-NPC identities, replay/cold load, unknown or mixed asset contracts, eight database -failure modes, counter exhaustion, forbidden pickup/combat and explicit versus +failure modes, counter exhaustion, the former pickup refusal, refused creature +combat and explicit versus generic profile admission. The complete Go run plus the corrected unresolved name fixture retest cover 1,691 roots / 16,603 passing results. The original full invocation retains one failure: its Acolyte Seleen test assumed the newly @@ -95,5 +97,6 @@ Parnassos rocks render and show the original Carbonrich Rock item description, remain world objects across page reconnect and cold server restart, reuse the same five item IDs, and have no corresponding character instances. The fixture's nine owned items and credits remain intact. Controlled character warps establish these initialization/rendering -claims, not ordinary travel or earned progression. Harvesting and playable -summons are not covered by these checks. +claims, not ordinary travel or earned progression. Extraction-tool processing +and playable summons are not covered by these checks. Later raw pickup checks +are recorded separately in [resource pickup](resource-pickup.md). diff --git a/docs/npc-profile-eligibility.md b/docs/npc-profile-eligibility.md @@ -18,8 +18,8 @@ stand-ins retain the existing prototype 43712/43713 weapon initialization. This removes unintended Leet-specific health, combat, XP, Monster Parts, cash, respawn delay and corpse lifetime from unresolved groups. It does not implement their proper behavior: prototype combat and ordinary corpse handling still -apply. Carbonrich Rocks now render as static world items; harvesting remains -open. Previously committed rewards, contents and lifecycle deadlines are +apply. Carbonrich Rocks render as static world items with reviewed raw pickup; +extraction-tool processing and replenishment remain open. Previously committed rewards, contents and lifecycle deadlines are not reversed when loading a changed definition; replacement profile eligibility is checked again for the new life. diff --git a/docs/resource-pickup.md b/docs/resource-pickup.md @@ -0,0 +1,109 @@ +# Carbonrich Rock pickup + +Ordinary world pickup now transfers a reviewed Carbonrich Rock to the collector +without allocating another item. The previous mission-only gate refused every +static resource. An initial WASM retry also exposed missing pickup-template +fields: the server had the correct owned item, but the fresh native inventory +row contained template IDs0/0. Resource SimpleItem packets now supply selected +QL701 and endpoint templates702/703 as required by the original client. + +The completion check is a short controlled scenario at an original placement: +select the rock within five metres, press R, verify the same physical instance +in native and server inventory, observe the other client's source removal, and +repeat page and cold loading without recreating the source. A deliberately +failed depletion write must leave the source and inventory unchanged, then +permit collection exactly once after the failure is removed. + +## Original evidence + +Fresh parsing of original 14.9.1 records1000020:150274 and1000020:150273 matches +every maintained catalog field, including payload hashes and record offsets. +Both descriptors have header `[51005, 2, 15, 23]`, Can30=1 (Carry only), +flags0=0xa0000401, mesh12=55669 and no sections or undecoded data. There is no +authored pickup skill, tool or companion event to execute. Normalized records +are identical except for identity/provenance, QL54, value74 and icon79: + +| Template | QL | Value74 | Icon79 | +| --- | --- | --- | --- | +| 150274 | 1 | 1 | 72772 | +| 150273 | 255 | 510 | 72774 | + +The shared quality system admits this pair at QL1..255, preserving the native +endpoint selection, value interpolation and icon selection. No new item-specific +interpolation code is needed. The source index SHA256 is +`46e5dc54af9358cc9bff05f4358e86af630e497bc677f361c133c88073b84d71`; +payload hashes are +`e465b7970ce96f3b6fb5ac786fe3403bc9c55ae1645040d4b2b2e4119725bb6e` and +`cd953c3f16e41029ea5fd901f36f60b2e2af0d329676f44d9009458cd776cbb4`. + +The original pickup proxy constructor is +`client/game/kkr.dll/lifted-0042.c::sub_36090EB0`: it reads stats701,703,702, +substitutes702 when703 is absent, and returns QL/low/high. Visible world +template23 alone does not initialize the collected item. + +The period [Arcanum Carbonrich Rock guide](https://www.paradisesgarage.com/arcanum/crafting_carbonrichrocks.html), +dated December10,2002, describes picking rocks from the ground. Its +[nanocrystal guide](https://www.paradisesgarage.com/arcanum/crafting_nanodiscs.html) +separately describes using a Jensen extractor on an already collected rock. +These support raw pickup without inventing an extraction-tool gate. They do not +establish a refill timer or an exact quality distribution for these placements. + +## Ownership and depletion + +The existing public inventory handler supplies actor authentication and typed +item routing. The resource branch requires a known original placement in the +collector's playfield, matching position/template/QL, a complete reviewed +carry-only contract, five-metre three-dimensional range and a free inventory +slot. Existing shop, bank, trade, pending-equipment and Unique restrictions +still apply. Unsupported qualities or descriptor companions refuse the whole +pickup. Resource actors remain type51005, never combatants. + +One item-store transaction removes the world location, assigns its physical +item to the first free carried slot and inserts its source ordinal into +`resource_depletions`. Required writes and final owner/item/depletion state are +checked before COMMIT. Only then does memory publish, the collector receive +the normal move reply followed by typed resource removal, and ready observers +receive the typed source removal. The collector's resource shape otherwise +remained visible until reload, despite a correct inventory row; the move must +precede shape retirement so the pickup proxy can still read its templates. +SQL failure, ignored writes, rewrites and COMMIT failure preserve the old state. + +Depletion belongs to the original placement, independently of the collected +item. Destroying or transferring the item cannot reactivate the source. +Reconnect, zone initialization and cold loading skip depleted source ordinals; +replayed pickup requests neither allocate another item nor write checkpoints. +The marker has no foreign key to the physical item. It is not rewritten on +ordinary simulation ticks or unrelated inventory transactions. + +This implements collection and its durable unreplenished state. It does not +claim that original rocks were permanently absent. Refill timing remains an +evidence gap; no timer has been guessed. Jensen processing and its resulting +tradeskill chain remain open. The existing inclusive source-level placement +cycle is still provisional quality selection. Original population IDs, counts, +positions and level ranges are unchanged. + +## Verification + +Evidence is retained under `local/resource-pickup/`. The pre-change public +handler regression fails on the former pickup refusal. Focused Go checks cover +same-instance ownership, independent depletion after deletion, duplicate and +competing requests, range/zone/full-inventory/descriptor refusals, nine database +failure modes and exact retry. Adjacent mission-objective pickup remains on the +same transaction path. + +The two-client WASM fixture uses original Parnassos placement1000668 in +playfield500 at `[318.12518, .0011, 196.0258]`, template150274QL1. Characters +are positioned beside it as a controlled fixture with no issued inventory or +credits. This verifies protocol and ownership behavior, not earned progression. +The five zone rocks keep their original global item identities; collecting the +selected rock does not advance the item counter or change HP, nano, XP or cash. + +The accepted run is `local/resource-pickup/20261103-133745/`: warm32.10seconds, +cold15.20seconds, nine clean traces with no dropped events or page exceptions. +Visual review confirms the collected icon and immediate ground-shape removal. +The cold SQL snapshot has five total physical items, four remaining resource +locations, item5 owned by player1 at slot64, and only source1000668 depleted. +The final Go run passes32 roots/291 results across server and gamedata; the +focused race run passes5 roots/14 results. Vet and both Node syntax checks pass. +`local/resource-pickup/verification.json` records the original payload audit, +accepted traces, ownership checks and excluded earlier reproductions. diff --git a/server/browser_resource_pickup_test.go b/server/browser_resource_pickup_test.go @@ -0,0 +1,120 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "math" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserWorldResourcePickup(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for original world-resource pickup") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/resource-pickup", time.Now().Format("20060102-150405")) + t.Chdir(t.TempDir()) + world := newServerForTest(t) + resource := world.worldResources[1000668] + if resource.template != 150274 || resource.quality != 1 || resource.position != [3]float32{318.12518, .0011, 196.0258} { + t.Fatal("retained original Carbonrich checkpoint changed", resource) + } + for index := range 2 { + player := world.newCharacter() + player.name, player.playfield = []string{"Rockowner", "Rockwatch"}[index], resource.playfield + player.position = [3]float32{resource.position[0] + 2, resource.position[1] + .75, resource.position[2] - float32(index)*3} + angle := math.Atan2(float64(resource.position[0]-player.position[0]), float64(resource.position[2]-player.position[2])) / 2 + player.rotation = [4]float32{0, float32(math.Sin(angle)), 0, float32(math.Cos(angle))} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("resource-pickup-", index)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + } + if err := world.ensureWorldResources_locked(resource.playfield); err != nil { + t.Fatal(err) + } + var itemID uint32 + for id, placement := range world.worldItems { + if placement.resource == 1000668 { + itemID = id + } + } + if itemID == 0 { + t.Fatal("original resource did not allocate its world instance") + } + lastID := world.nextItem + run := func(t *testing.T, world *server, script, phaseOutput string) { + t.Helper() + 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() + _, onGround := world.worldItems[itemID] + json.NewEncoder(w).Encode(map[string]any{"item": itemID, "definition": 1000668, "playfield": resource.playfield, + "inventory": world.characters[1].inventory, "observer": world.characters[2].inventory, + "onGround": onGround, "depleted": world.depletedResources[1000668], "lastID": world.nextItem, + "health": world.characters[1].health, "nano": world.characters[1].nano}) + }) + mux.HandleFunc("POST /test-clear-failure", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + if _, err := world.db.Exec("DROP TRIGGER fail_collection"); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/"+script), host.URL, phaseOutput) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } + expected := []ownedItem{{ID: itemID, Type: 51005, Template: 150274, Quality: 1, Slot: 64, Count: 1}} + if !slices.Equal(world.characters[1].inventory.Items, expected) || len(world.characters[2].inventory.Items) != 0 || + !world.depletedResources[1000668] || world.nextItem != lastID { + t.Fatal("native collection or replay changed identity, counter, depletion or another owner") + } + } + t.Run("warm", func(t *testing.T) { + registerTestDatabaseCleanup(t, world) + if _, err := world.db.Exec("CREATE TRIGGER fail_collection BEFORE INSERT ON resource_depletions BEGIN SELECT RAISE(ABORT,'collection'); END"); err != nil { + t.Fatal(err) + } + run(t, world, "test_resource_pickup.mjs", filepath.Join(output, "warm")) + }) + if t.Failed() { + return + } + t.Run("cold", func(t *testing.T) { + cold := newServerForTest(t) + run(t, cold, "test_resource_pickup_cold.mjs", filepath.Join(output, "cold")) + cold.updateMutex.Lock() + cold.mutex.Lock() + _, err := cold.db.Exec("VACUUM INTO ?", filepath.Join(output, "world.sqlite")) + cold.mutex.Unlock() + cold.updateMutex.Unlock() + if err != nil { + t.Fatal(err) + } + }) +} diff --git a/server/gamedata/item_families.yaml b/server/gamedata/item_families.yaml @@ -123,3 +123,5 @@ - [85631, 22142] - [85679, 22064] - [85735, 21955] +# Carry-only Carbonrich Rock: complete original descriptors; docs/resource-pickup.md. +- [150274, 150273] diff --git a/server/gamedata/item_quality_test.go b/server/gamedata/item_quality_test.go @@ -45,6 +45,7 @@ func TestReviewedItemFamilyQualityRanges(t *testing.T) { {120588, 142686, 1, 200}, {120589, 142688, 1, 200}, {120590, 142690, 1, 200}, {85505, 22331, 1, 200}, {85552, 22246, 1, 200}, {85591, 22196, 1, 200}, {85631, 22142, 1, 200}, {85679, 22064, 1, 200}, {85735, 21955, 1, 200}, + {150274, 150273, 1, 255}, } { for _, template := range [2]uint32{family.lowTemplate, family.highTemplate} { t.Run(fmt.Sprint(template), func(t *testing.T) { diff --git a/server/item_database.go b/server/item_database.go @@ -15,6 +15,11 @@ type itemPlacement struct { } func (server *server) persistItems_locked(store itemStore) error { + for resource := range server.depletedResources { + if !store.DepletedResources[resource] { + return fmt.Errorf("cannot remove resource depletion %d", resource) + } + } db, err := server.database() if err != nil { return err @@ -196,6 +201,25 @@ func (server *server) persistItems_locked(store itemStore) error { } } } + // Depletion belongs to the original placement, independently of the collected item. + collectedResources := make(map[uint32]uint32) + for resource := range store.DepletedResources { + if server.depletedResources[resource] { + continue + } + for id, source := range server.worldItems { + if source.resource == resource && placements[id].Player != 0 { + collectedResources[resource] = id + } + } + if collectedResources[resource] == 0 { + return fmt.Errorf("resource %d has no collected instance", resource) + } + var savedID uint32 + if err := tx.QueryRow("INSERT INTO resource_depletions(resource_id) VALUES (?) RETURNING resource_id", resource).Scan(&savedID); err != nil { + return fmt.Errorf("deplete resource %d: %w", resource, err) + } + } for _, edited := range store.edited { record := edited.record() if err := updateRecord(tx, "characters", edited.id, characterColumns, record.fields()); err != nil { @@ -364,6 +388,31 @@ func (server *server) persistItems_locked(store itemStore) error { return fmt.Errorf("retired mission %d retains its assignment, NPCs or doors", store.removedMission.id) } } + if len(collectedResources) != 0 { + var count int + if err := tx.QueryRow("SELECT count(*) FROM resource_depletions").Scan(&count); err != nil { + return err + } + if count != len(store.DepletedResources) { + return fmt.Errorf("resource depletion count changed before commit") + } + var savedID uint32 + for resource := range store.DepletedResources { + if err := tx.QueryRow("SELECT resource_id FROM resource_depletions WHERE resource_id=?", resource).Scan(&savedID); err != nil { + return fmt.Errorf("resource %d depletion was not saved: %w", resource, err) + } + } + for resource, id := range collectedResources { + item, destination := store.Items[id], placements[id] + if err := tx.QueryRow(`SELECT items.id FROM items JOIN item_locations ON item_id=items.id + WHERE items.id=? AND (type, template, quality, count, ammo) IS (?, ?, ?, 1, 0) + AND player_id=? AND slot=? AND reclaim_at IS NULL + AND NOT EXISTS (SELECT 1 FROM item_locations WHERE resource_id=?)`, id, item.Type, item.Template, item.Quality, + destination.Player, destination.Slot, resource).Scan(&savedID); err != nil { + return fmt.Errorf("collected resource %d ownership was not saved: %w", resource, err) + } + } + } if err := tx.Commit(); err != nil { return err } @@ -372,7 +421,7 @@ func (server *server) persistItems_locked(store itemStore) error { } func (server *server) readItems() (itemStore, error) { - store := itemStore{Items: make(map[uint32]itemRecord), Players: make(map[uint32]characterItemReferences), Corpses: make(map[uint32][]ownedItem), WorldItems: make(map[uint32]worldItem)} + store := itemStore{Items: make(map[uint32]itemRecord), Players: make(map[uint32]characterItemReferences), Corpses: make(map[uint32][]ownedItem), WorldItems: make(map[uint32]worldItem), DepletedResources: make(map[uint32]bool)} db, err := server.database() if err != nil { return store, err @@ -380,7 +429,28 @@ func (server *server) readItems() (itemStore, error) { if err := db.QueryRow("SELECT last_item_id FROM world WHERE id=1").Scan(&store.LastID); err != nil { return store, err } - rows, err := db.Query("SELECT id, type, template, quality, count, ammo FROM items") + rows, err := db.Query("SELECT resource_id FROM resource_depletions") + if err != nil { + return store, err + } + for rows.Next() { + var resource uint32 + if err := rows.Scan(&resource); err != nil { + rows.Close() + return store, err + } + if _, known := server.worldResources[resource]; !known { + rows.Close() + return store, fmt.Errorf("unknown depleted resource %d", resource) + } + store.DepletedResources[resource] = true + } + if err := rows.Err(); err != nil { + rows.Close() + return store, err + } + rows.Close() + rows, err = db.Query("SELECT id, type, template, quality, count, ammo FROM items") if err != nil { return store, err } diff --git a/server/item_store.go b/server/item_store.go @@ -48,21 +48,22 @@ type playerVitalUpdate struct { } type itemStore struct { - LastID uint32 `yaml:"last_id"` - Items map[uint32]itemRecord `yaml:"items"` - Players map[uint32]characterItemReferences `yaml:"players"` - Corpses map[uint32][]ownedItem - WorldItems map[uint32]worldItem - edited []*character - vitalUpdate *playerVitalUpdate - skillLock *skillLockUpdate - mission *acceptedMission - updatedMission *acceptedMission - removedMission *acceptedMission - spawnedNPCs []*character - inventoryPlayers []uint32 - checkpointAt time.Time - flush bool + LastID uint32 `yaml:"last_id"` + Items map[uint32]itemRecord `yaml:"items"` + Players map[uint32]characterItemReferences `yaml:"players"` + Corpses map[uint32][]ownedItem + WorldItems map[uint32]worldItem + DepletedResources map[uint32]bool + edited []*character + vitalUpdate *playerVitalUpdate + skillLock *skillLockUpdate + mission *acceptedMission + updatedMission *acceptedMission + removedMission *acceptedMission + spawnedNPCs []*character + inventoryPlayers []uint32 + checkpointAt time.Time + flush bool } func emptyItemSlots(count uint32) map[string]*uint32 { @@ -196,7 +197,8 @@ func reclaimItems(entries []reclaimItem) []ownedItem { func (server *server) itemStore_locked(character *character, inventory playerInventory) (itemStore, error) { store := itemStore{LastID: max(server.nextItem, inventory.LastID), Items: maps.Clone(server.items), - Players: make(map[uint32]characterItemReferences), Corpses: make(map[uint32][]ownedItem), WorldItems: maps.Clone(server.worldItems), inventoryPlayers: []uint32{character.id}} + Players: make(map[uint32]characterItemReferences), Corpses: make(map[uint32][]ownedItem), WorldItems: maps.Clone(server.worldItems), + DepletedResources: maps.Clone(server.depletedResources), inventoryPlayers: []uint32{character.id}} if store.Items == nil { store.Items = make(map[uint32]itemRecord) } @@ -269,6 +271,7 @@ func (server *server) writeItemStore_locked(store itemStore) error { } server.items = store.Items server.worldItems = store.WorldItems + server.depletedResources = store.DepletedResources server.nextItem = store.LastID for _, npc := range store.spawnedNPCs { server.characters[npc.id] = npc @@ -323,6 +326,7 @@ func (server *server) loadItems() error { } server.items, server.nextItem = store.Items, store.LastID server.worldItems = store.WorldItems + server.depletedResources = store.DepletedResources for id, items := range store.Corpses { server.characters[id].corpse.items = items } @@ -331,8 +335,13 @@ func (server *server) loadItems() error { func (store itemStore) validate() error { claimed := make(map[uint32]bool) + for resource, depleted := range store.DepletedResources { + if resource == 0 || !depleted { + return fmt.Errorf("invalid resource depletion %d", resource) + } + } for id, placement := range store.WorldItems { - if _, exists := store.Items[id]; !exists || (placement.mission == 0) == (placement.resource == 0) { + if _, exists := store.Items[id]; !exists || (placement.mission == 0) == (placement.resource == 0) || store.DepletedResources[placement.resource] { return fmt.Errorf("invalid world item %d placement", id) } for _, coordinate := range placement.position { diff --git a/server/state.go b/server/state.go @@ -127,30 +127,31 @@ type server struct { baseURL string mutex sync.Mutex // Order entity-state packet batches; acquire before mutex. - updateMutex sync.Mutex - nextCharacter uint32 - nextNPC uint32 - nextItem uint32 - items map[uint32]itemRecord - worldItems map[uint32]worldItem - worldResources map[uint32]worldResource - characters map[uint32]*character - mobileNPCs map[uint32][]*character - npcRespawns []npcRespawn - corpseExpiry []*character - missionExpiry []acceptedMission - clients map[uint32]*worldClient - fighting map[uint32]*character - combatRoll func(uint32) uint32 - chats map[uint32]*chatClient - chatLogMutex sync.Mutex - browserStreams map[string]*browserStream - gameSeconds float64 - clockStarted time.Time - lastNPCUpdate time.Time - terrain map[uint32]*terrain - geometry *sceneGeometry - zoneLinks map[string]map[uint32]zoneLinks + updateMutex sync.Mutex + nextCharacter uint32 + nextNPC uint32 + nextItem uint32 + items map[uint32]itemRecord + worldItems map[uint32]worldItem + worldResources map[uint32]worldResource + depletedResources map[uint32]bool + characters map[uint32]*character + mobileNPCs map[uint32][]*character + npcRespawns []npcRespawn + corpseExpiry []*character + missionExpiry []acceptedMission + clients map[uint32]*worldClient + fighting map[uint32]*character + combatRoll func(uint32) uint32 + chats map[uint32]*chatClient + chatLogMutex sync.Mutex + browserStreams map[string]*browserStream + gameSeconds float64 + clockStarted time.Time + lastNPCUpdate time.Time + terrain map[uint32]*terrain + geometry *sceneGeometry + zoneLinks map[string]map[uint32]zoneLinks } func newServer() *server { diff --git a/server/world.sql b/server/world.sql @@ -223,6 +223,9 @@ CREATE UNIQUE INDEX IF NOT EXISTS bank_slots ON item_locations(bank_player_id, s CREATE UNIQUE INDEX IF NOT EXISTS backpack_slots ON item_locations(backpack_id, slot); CREATE UNIQUE INDEX IF NOT EXISTS corpse_slots ON item_locations(corpse_id, slot); CREATE UNIQUE INDEX IF NOT EXISTS resource_locations ON item_locations(resource_id); +CREATE TABLE IF NOT EXISTS resource_depletions ( + resource_id INTEGER PRIMARY KEY CHECK (resource_id BETWEEN 1 AND 4294967295) +); CREATE TABLE IF NOT EXISTS missions ( id INTEGER PRIMARY KEY CHECK (id BETWEEN 1 AND 4294967295), owner_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE, diff --git a/server/world_items.go b/server/world_items.go @@ -130,8 +130,11 @@ func (server *server) worldItemPackets_locked(player *character) [][]byte { resource := server.worldResources[placement.resource] if resource.playfield == player.playfield { item := server.items[id] + low, high := (ownedItem{Type: item.Type, Template: item.Template, Quality: item.Quality}).templateIDs() + // client/game/kkr.dll/lifted-0042.c::sub_36090EB0 uses + // stats701/702/703 to construct the collected inventory item. packets = append(packets, n3Packet(0x3b11256f, item.Type, id, - simpleItemBody(item.Template, player.playfield, resource.position, [4]float32{0, 0, 0, 1}, [][2]uint32{{701, item.Quality}}))) + simpleItemBody(item.Template, player.playfield, resource.position, [4]float32{0, 0, 0, 1}, [][2]uint32{{701, item.Quality}, {702, low}, {703, high}}))) } } else if mission != nil && placement.mission == mission.id { item := server.items[id] @@ -149,16 +152,21 @@ func (server *server) takeWorldItem_locked(client *worldClient, body []byte) err player := server.characters[client.id] placement, exists := server.worldItems[id] mission := server.missionWorld_locked(player.playfield) + record := server.items[id] + item := ownedItem{ID: id, Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count, Ammo: record.Ammo} + resource, knownResource := server.worldResources[placement.resource] + resourcePickup := placement.resource != 0 && knownResource && resource.playfield == player.playfield && + resource.position == placement.position && resource.template == record.Template && resource.quality == record.Quality && + !server.depletedResources[placement.resource] && supportedWorldResourcePickup(item) + missionPickup := placement.resource == 0 && mission != nil && placement.mission == mission.id && time.Now().Before(mission.expiresAt) denied := characterActionPacket(client.id, [5]uint32{146, 51005, id}) - if !client.target || !exists || mission == nil || placement.mission != mission.id || !time.Now().Before(mission.expiresAt) || + if !client.target || !exists || (!resourcePickup && !missionPickup) || client.trade != nil || client.shop != nil || client.bank != nil || client.equipment != nil || binary.BigEndian.Uint32(body[24:28]) != 0 || binary.BigEndian.Uint32(body[28:32]) != 0 || binary.BigEndian.Uint32(body[32:36]) != 111 { return client.send(denied) } position := predictedPosition_locked(player, time.Now()) x, y, z := position[0]-placement.position[0], position[1]-placement.position[1], position[2]-placement.position[2] - record := server.items[id] - item := ownedItem{ID: id, Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count, Ammo: record.Ammo} if x*x+y*y+z*z > 25 || item.Type != 51005 || itemStat(item.templateDefinition(), 30)&1 == 0 || itemStat(item.templateDefinition(), 0)&0x08000000 != 0 && player.inventory.carriesUnique(item) { return client.send(denied) @@ -181,6 +189,12 @@ func (server *server) takeWorldItem_locked(client *worldClient, body []byte) err return err } delete(store.WorldItems, id) + if resourcePickup { + if store.DepletedResources == nil { + store.DepletedResources = make(map[uint32]bool) + } + store.DepletedResources[placement.resource] = true + } if err := server.writeItemStore_locked(store); err != nil { return err } @@ -194,7 +208,14 @@ func (server *server) takeWorldItem_locked(client *worldClient, body []byte) err } // client/game/kkr.dll/lifted-0029.c, sub_360614E0/sub_3605F7C0: // Destination 0/0 selects world pickup and the same first-free slot locally. - return client.send(n3Packet(0x47537a24, 50000, client.id, slices.Clone(body[16:]))) + if err := client.send(n3Packet(0x47537a24, 50000, client.id, slices.Clone(body[16:]))); err != nil { + return err + } + // Retire the resource shape after its proxy has constructed the carried item. + if resourcePickup { + return client.send(n3Packet(0x36510078, item.Type, id, nil)) + } + return nil } func simpleItemBody(template, playfield uint32, position [3]float32, rotation [4]float32, stats [][2]uint32) []byte { diff --git a/server/world_resource_pickup_test.go b/server/world_resource_pickup_test.go @@ -0,0 +1,241 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "maps" + "reflect" + "slices" + "sync" + "testing" +) + +func newResourcePickupWorld(t *testing.T) (*server, *combatTestConn, *combatTestConn) { + t.Helper() + world := newWorldResourceWorld(t) + owner, observer := &combatTestConn{}, &combatTestConn{} + for _, output := range []*combatTestConn{owner, observer} { + player := world.newCharacter() + player.playfield, player.position = 950, [3]float32{53, 14, 56} + world.clients[player.id] = &worldClient{id: player.id, target: true, ready: true, conn: output} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + } + if err := world.ensureWorldResources_locked(950); err != nil { + t.Fatal(err) + } + return world, owner, observer +} + +func TestWorldResourcePickupTransfersItsExactInstance(t *testing.T) { + world, owner, observer := newResourcePickupWorld(t) + player, client := world.characters[1], world.clients[1] + before := *player + + err := world.handleInventory(client, worldPickupRequest(player.id, 1)) + cold := newTestInventoryServer(t) + + expected := []ownedItem{{ID: 1, Type: 51005, Template: 150274, Quality: 3, Slot: 64, Count: 1}} + if err != nil || !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + len(world.worldItems) != 0 || len(cold.worldItems) != 0 || world.nextItem != 1 || cold.nextItem != 1 || + !world.depletedResources[1000001] || !cold.depletedResources[1000001] || len(world.characters[2].inventory.Items) != 0 { + t.Fatal("original carry-only resource did not transfer its exact physical instance", err) + } + if player.health != before.health || player.nano != before.nano || player.experience != before.experience || player.stats != before.stats || + player.inventory.Credits != 0 || len(owner.packets) != 2 || binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x47537a24 || + !bytes.Equal(owner.packets[1], targetPacket(n3Packet(0x36510078, 51005, 1, nil))) || + len(observer.packets) != 1 || binary.BigEndian.Uint32(observer.packets[0][16:20]) != 0x36510078 { + t.Fatal("resource pickup changed player resources or did not publish the committed move/removal") + } +} + +func TestWorldResourceDepletionSurvivesReplayAndItemDeletion(t *testing.T) { + world, _, _ := newResourcePickupWorld(t) + if err := world.handleInventory(world.clients[1], worldPickupRequest(1, 1)); err != nil { + t.Fatal(err) + } + auditCheckpointWrites(t, world) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + for _, client := range []*worldClient{world.clients[1], world.clients[2]} { + if err := world.handleInventory(client, worldPickupRequest(client.id, 1)); err != nil { + t.Fatal(err) + } + } + if err := world.ensureWorldResources_locked(950); err != nil { + t.Fatal(err) + } + after, err := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || len(world.worldItems) != 0 { + t.Fatal("repeat pickup or zone entry changed ownership or recreated a collected resource", err) + } + + request := inventoryDeletePacket(1, 64)[20:] + binary.BigEndian.PutUint32(request[28:32], 150274) + binary.BigEndian.PutUint32(request[32:36], 150273) + if err := world.handleInventory(world.clients[1], request); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + if err := cold.ensureWorldResources_locked(950); err != nil { + t.Fatal(err) + } + + if len(cold.items) != 0 || len(cold.worldItems) != 0 || len(cold.characters[1].inventory.Items) != 0 || + !cold.depletedResources[1000001] || cold.nextItem != 1 { + t.Fatal("destroying the collected item reactivated its independent original placement") + } +} + +func TestWorldResourcePickupFailuresRollBackAndRetry(t *testing.T) { + for _, failure := range []struct{ name, sql string }{ + {"marker failure", "CREATE TRIGGER fail_pickup BEFORE INSERT ON resource_depletions BEGIN SELECT RAISE(ABORT,'depletion'); END"}, + {"ignored marker", "CREATE TRIGGER fail_pickup BEFORE INSERT ON resource_depletions BEGIN SELECT RAISE(IGNORE); END"}, + {"deleted marker", "CREATE TRIGGER fail_pickup AFTER INSERT ON resource_depletions BEGIN DELETE FROM resource_depletions WHERE resource_id=NEW.resource_id; END"}, + {"rewritten marker", "CREATE TRIGGER fail_pickup AFTER INSERT ON resource_depletions BEGIN UPDATE resource_depletions SET resource_id=42 WHERE resource_id=NEW.resource_id; END"}, + {"ignored source removal", "CREATE TRIGGER fail_pickup BEFORE DELETE ON item_locations WHEN OLD.resource_id IS NOT NULL BEGIN SELECT RAISE(IGNORE); END"}, + {"ignored owner placement", "CREATE TRIGGER fail_pickup BEFORE INSERT ON item_locations WHEN NEW.player_id=1 BEGIN SELECT RAISE(IGNORE); END"}, + {"rewritten owner", "CREATE TRIGGER fail_pickup AFTER INSERT ON item_locations WHEN NEW.player_id=1 BEGIN UPDATE item_locations SET player_id=2 WHERE item_id=NEW.item_id; END"}, + {"rewritten item", "CREATE TRIGGER fail_pickup AFTER INSERT ON resource_depletions BEGIN UPDATE items SET quality=99 WHERE id=1; END"}, + {"commit", "CREATE TABLE pickup_commit_failure(value INTEGER REFERENCES items(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_pickup AFTER INSERT ON resource_depletions BEGIN INSERT INTO pickup_commit_failure VALUES(0); END"}, + } { + t.Run(failure.name, func(t *testing.T) { + world, owner, observer := newResourcePickupWorld(t) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec(failure.sql); err != nil { + t.Fatal(err) + } + + err = world.handleInventory(world.clients[1], worldPickupRequest(1, 1)) + after, readErr := readTestItemStore(world) + cold := newTestInventoryServer(t) + + if err == nil || readErr != nil || !bytes.Equal(before, after) || len(world.worldItems) != 1 || len(cold.worldItems) != 1 || + len(world.depletedResources) != 0 || len(cold.depletedResources) != 0 || len(world.characters[1].inventory.Items) != 0 || + len(cold.characters[1].inventory.Items) != 0 || len(owner.packets) != 0 || len(observer.packets) != 0 { + t.Fatal("failed pickup changed a source, owner, depletion, counter or observer", err, readErr) + } + + if _, err := world.db.Exec("DROP TRIGGER fail_pickup"); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(world.clients[1], worldPickupRequest(1, 1)); err != nil { + t.Fatal(err) + } + cold = newTestInventoryServer(t) + + if len(cold.worldItems) != 0 || !cold.depletedResources[1000001] || len(cold.characters[1].inventory.Items) != 1 || + cold.characters[1].inventory.Items[0].ID != 1 || cold.nextItem != 1 { + t.Fatal("retry did not collect the same physical resource exactly once") + } + }) + } +} + +func TestWorldResourcePickupRefusesUnavailableSources(t *testing.T) { + for _, scenario := range []string{"range", "vertical range", "wrong playfield", "unknown binding", "moved binding", "wrong quality", "unsupported quality", "multiple count", "companion event", "undecoded", "full inventory"} { + t.Run(scenario, func(t *testing.T) { + world, owner, observer := newResourcePickupWorld(t) + player := world.characters[1] + switch scenario { + case "range": + player.position[0] += 5.01 + case "vertical range": + player.position[1] += 5.01 + case "wrong playfield": + player.playfield = 952 + case "unknown binding", "moved binding": + placement := world.worldItems[1] + if scenario == "unknown binding" { + placement.resource = 123 + } else { + placement.position[0]++ + } + world.worldItems[1] = placement + case "wrong quality", "unsupported quality", "multiple count": + record := world.items[1] + record.Quality = 4 + if scenario == "unsupported quality" { + record.Quality = 256 + resource := world.worldResources[1000001] + resource.quality = 256 + world.worldResources[1000001] = resource + } else if scenario == "multiple count" { + record.Quality, record.Count = 3, 2 + } + world.items[1] = record + case "companion event", "undecoded": + original := gamedata.ItemTemplates[150274] + definition := *original + if scenario == "companion event" { + definition.Sections = []gamedata.ItemSection{{Type: 2, Subtype: 4}} + } else { + definition.Undecoded = &gamedata.UndecodedItemData{Reason: "unknown contract"} + } + gamedata.ItemTemplates[150274] = &definition + t.Cleanup(func() { gamedata.ItemTemplates[150274] = original }) + case "full inventory": + for range 30 { + if granted, err := world.grantItem_locked(player, 99719); err != nil || !granted { + t.Fatal(granted, err) + } + } + } + before := player.inventory + placements, records := maps.Clone(world.worldItems), maps.Clone(world.items) + owner.packets, observer.packets = nil, nil + + err := world.handleInventory(world.clients[1], worldPickupRequest(1, 1)) + + if err != nil || !reflect.DeepEqual(player.inventory, before) || !reflect.DeepEqual(placements, world.worldItems) || + !reflect.DeepEqual(records, world.items) || len(world.depletedResources) != 0 || len(observer.packets) != 0 || + len(owner.packets) != 1 || binary.BigEndian.Uint32(owner.packets[0][29:33]) != 146 { + t.Fatal("refused resource changed ownership, depletion or observers", err) + } + }) + } +} + +func TestWorldResourceCompetingPickupsHaveOneDurableOwner(t *testing.T) { + world, _, _ := newResourcePickupWorld(t) + var workers sync.WaitGroup + errors := make(chan error, 2) + + for _, client := range []*worldClient{world.clients[1], world.clients[2]} { + workers.Add(1) + go func() { + defer workers.Done() + errors <- world.handleInventory(client, worldPickupRequest(client.id, 1)) + }() + } + workers.Wait() + close(errors) + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + cold := newTestInventoryServer(t) + + if len(cold.characters[1].inventory.Items)+len(cold.characters[2].inventory.Items) != 1 || len(cold.items) != 1 || + len(cold.worldItems) != 0 || len(cold.depletedResources) != 1 || !cold.depletedResources[1000001] || cold.nextItem != 1 { + t.Fatal("competing pickups did not retain one owner and one independent depletion") + } + for _, id := range []uint32{1, 2} { + if !slices.Equal(world.characters[id].inventory.Items, cold.characters[id].inventory.Items) { + t.Fatal("pickup owner differs after cold load", id) + } + } +} diff --git a/server/world_resources.go b/server/world_resources.go @@ -49,7 +49,7 @@ func (server *server) ensureWorldResources_locked(playfield uint32) error { } var missing []uint32 for identity, resource := range server.worldResources { - if resource.playfield == playfield && !present[identity] { + if resource.playfield == playfield && !present[identity] && !server.depletedResources[identity] { missing = append(missing, identity) } } @@ -78,3 +78,10 @@ func (server *server) ensureWorldResources_locked(playfield uint32) error { } return server.writeItemStore_locked(store) } + +func supportedWorldResourcePickup(item ownedItem) bool { + definition := gamedata.ItemTemplates[item.Template] + return item.Type == 51005 && item.Count == 1 && item.Ammo == 0 && definition != nil && definition.RecordType == 1000020 && + definition.HeaderWords[0] == 51005 && definition.Undecoded == nil && len(definition.Sections) == 0 && + itemStat(definition, 30) == 1 && itemStat(definition, 0) == 0xa0000401 && gamedata.ItemQualitySupported(item.Template, item.Quality) +} diff --git a/server/world_resources_test.go b/server/world_resources_test.go @@ -52,7 +52,9 @@ func TestWorldResourceUsesAnItemIdentityAndSurvivesColdReplay(t *testing.T) { packet = packet[:binary.BigEndian.Uint16(packet[6:8])] if binary.BigEndian.Uint32(packet[16:20]) != 0x3b11256f || binary.BigEndian.Uint32(packet[20:24]) != 51005 || binary.BigEndian.Uint32(packet[24:28]) != 2 || binary.BigEndian.Uint32(packet[91:95]) != 150274 || - binary.BigEndian.Uint32(packet[len(packet)-12:len(packet)-8]) != 701 || binary.BigEndian.Uint32(packet[len(packet)-8:len(packet)-4]) != 3 { + binary.BigEndian.Uint32(packet[len(packet)-28:len(packet)-24]) != 701 || binary.BigEndian.Uint32(packet[len(packet)-24:len(packet)-20]) != 3 || + binary.BigEndian.Uint32(packet[len(packet)-20:len(packet)-16]) != 702 || binary.BigEndian.Uint32(packet[len(packet)-16:len(packet)-12]) != 150274 || + binary.BigEndian.Uint32(packet[len(packet)-12:len(packet)-8]) != 703 || binary.BigEndian.Uint32(packet[len(packet)-8:len(packet)-4]) != 150273 { t.Fatalf("resource did not use the original SimpleItem/template/quality contract: %x", packet) } } @@ -102,7 +104,7 @@ func TestWorldResourceAllocationFailuresRetainStateAndRetry(t *testing.T) { } } -func TestWorldResourceCannotBePickedUpOrAttackedAsACreature(t *testing.T) { +func TestWorldResourceCannotBeAttackedAsACreature(t *testing.T) { world := newWorldResourceWorld(t) player := world.newCharacter() player.playfield, player.position = 950, [3]float32{53, 14, 56} @@ -116,9 +118,6 @@ func TestWorldResourceCannotBePickedUpOrAttackedAsACreature(t *testing.T) { t.Fatal(err) } - if err := world.handleInventory(client, worldPickupRequest(player.id, 1)); err != nil { - t.Fatal(err) - } attack := attackPacket(player.id, 1)[20:] binary.BigEndian.PutUint32(attack[16:20], 51005) if err := world.handleCombat(client, attack); err != nil { diff --git a/tools/client/test_resource_pickup.mjs b/tools/client/test_resource_pickup.mjs @@ -0,0 +1,122 @@ +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']}); +const games = [], sockets = [], evidence = {}; +try { + for (const index of [0, 1]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'resource-pickup-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + page.on('websocket', socket => { if (socket.url().endsWith('/browser-world')) sockets[index] = socket; }); + games.push(game); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + if (!game.state.camera.firstPerson) await game.key('F8'); + } + const [owner, observer] = games; + const server = async () => (await owner.page.request.get(url + '/test-state')).json(); + const reload = async game => { + await game.page.reload(); await game.ready(); + await game.page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + if (!game.state.camera.firstPerson) await game.key('F8'); + }; + evidence.before = await server(); + assert.equal(evidence.before.onGround, true); + assert.equal(evidence.before.depleted, false); + assert.equal(evidence.before.inventory.Items, null); + const pickup = async () => { + const point = await owner.point(500, 400); + let cursorY = point.y; + await owner.page.mouse.move(point.x, cursorY); + await owner.page.mouse.down({button: 'right'}); + try { + const deadline = Date.now() + 10000; + while (true) { + const state = await owner.snapshot(); + const actor = state.actors.find(actor => actor.type === 51005 && actor.id === evidence.before.item); + assert(actor?.screenPosition); + const screenY = actor.screenPosition[1]; + if (screenY >= 350 && screenY <= 540) break; + assert(Date.now() < deadline, 'Original ground resource did not enter the camera view'); + cursorY += screenY > 540 ? 20 : -20; + await owner.page.mouse.move(point.x, cursorY, {steps: 2}); + } + } finally { await owner.page.mouse.up({button: 'right'}); } + await owner.click(...await owner.pick(51005, evidence.before.item)); + const sequence = owner.sequence; + await owner.key('KeyR'); + await owner.wait('real original world pickup request', () => owner.events.some(event => { + if (event.sequence <= sequence || event.direction !== 'framesent' || event.opcode !== '47537a24') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(29) === 51005 && packet.readUInt32BE(33) === evidence.before.item; + })); + }; + await owner.save(output + '/original-ground'); + + // A failed depletion write must preserve the source and both inventory views. + const closed = sockets[0].waitForEvent('close', {timeout: 15000}); + await Promise.all([closed, pickup()]); + assert((await owner.page.request.post(url + '/test-clear-failure')).ok()); + await reload(owner); + evidence.failed = await server(); + assert.equal(evidence.failed.onGround, true); + assert.equal(evidence.failed.depleted, false); + assert.equal(evidence.failed.inventory.Items, null); + assert.equal(evidence.failed.lastID, evidence.before.lastID); + assert.equal(evidence.failed.inventory.Credits, evidence.before.inventory.Credits); + await owner.save(output + '/failed-recovered'); + await observer.save(output + '/observer-failed'); + + // Retry collects the original instance; the observer retires its world copy. + await pickup(); + await owner.wait('collected resource has a usable native inventory row', state => owner.local(state).inventory.length === 1); + const fresh = owner.local().inventory[0]; + assert.deepEqual(fresh.templates, [150274, 150274]); + assert.equal(fresh.quality, 1); + assert.equal(fresh.count, 1); + evidence.fresh = fresh; + await owner.wait('collector loses the original world shape', state => !state.actors.some(actor => + actor.type === 51005 && actor.id === evidence.before.item)); + assert.deepEqual(owner.local().inventory[0].templates, [150274, 150274]); + evidence.collected = await server(); + assert.deepEqual(evidence.collected.inventory.Items, [{ID: evidence.before.item, Type: 51005, Template: 150274, + Quality: 1, Slot: 64, Count: 1, Ammo: 0}]); + assert.equal(evidence.collected.depleted, true); + assert.equal(evidence.collected.onGround, false); + assert.equal(evidence.collected.lastID, evidence.before.lastID); + assert.equal(evidence.collected.health, evidence.before.health); + assert.equal(evidence.collected.nano, evidence.before.nano); + await observer.wait('observer loses only the collected source', state => !state.actors.some(actor => + actor.type === 51005 && actor.id === evidence.before.item)); + await owner.key('KeyI'); + await owner.save(output + '/collected'); + await observer.save(output + '/observer-collected'); + + for (const game of games) await reload(game); + assert.deepEqual(owner.local().inventory, [{slot: 48, type: 51005, id: evidence.before.item, quality: 1, + templates: [150274, 150274], count: 1}]); + assert(!observer.state.actors.some(actor => actor.type === 51005 && actor.id === evidence.before.item)); + evidence.reloaded = await server(); + assert.deepEqual(evidence.reloaded.inventory, evidence.collected.inventory); + assert.equal(evidence.reloaded.onGround, false); + assert.equal(evidence.reloaded.depleted, true); + assert.equal(evidence.reloaded.lastID, evidence.before.lastID); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: original resource pickup rollback/retry, visible inventory, observer removal and page conservation'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); + } finally { await browser.close(); } +} diff --git a/tools/client/test_resource_pickup_cold.mjs b/tools/client/test_resource_pickup_cold.mjs @@ -0,0 +1,41 @@ +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']}); +const games = []; +try { + for (const index of [0, 1]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'resource-pickup-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + } + const [owner, observer] = games; + const state = await (await owner.page.request.get(url + '/test-state')).json(); + assert.deepEqual(owner.local().inventory, [{slot: 48, type: 51005, id: state.item, quality: 1, + templates: [150274, 150274], count: 1}]); + assert.deepEqual(observer.local().inventory, []); + assert.equal(state.onGround, false); + assert.equal(state.depleted, true); + assert.equal(state.inventory.Credits, 0); + assert.equal(state.inventory.Items[0].ID, state.item); + for (const game of games) assert(!game.state.actors.some(actor => actor.type === 51005 && actor.id === state.item)); + await owner.key('KeyI'); + assert(games.every(game => game.errors.length === 0)); + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(state, null, 2) + '\n'); + console.log('PASS: cold resource identity, selected quality, inventory and independent depletion remain exact'); +} finally { + try { await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); } + finally { await browser.close(); } +}