aorecomp

Anarchy Online classic in the browser

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


commit 1f057b83579c53425b15a0e2166eb653fb6813aa
parent 5de1e17c1739ca90e72707092f09ee06e60627f0
Author: anon <anon@example.com>
Date:   Sat, 31 Oct 2026 04:20:20 +0000

Verify ordinary starter combat and reliable harness input

Diffstat:
MDEVELOPERS.md | 19++++++++++++++-----
MTODO.md | 33+++++++++++++++++++++++++++++----
Mclient/tests/game_test.mjs | 104++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mdocs/native-picking.md | 32++++++++++++++++++++++++++++++++
Mdocs/open-questions.md | 6++++++
Mdocs/starter-progression.md | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/browser_game_test.go | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mserver/browser_stream_test.go | 20++++++++++++++++++++
Mtools/client/game_test.mjs | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mtools/client/test_starter_equipment.mjs | 278+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mtools/client/test_starter_mission_targets.mjs | 37++-----------------------------------
11 files changed, 690 insertions(+), 85 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -448,6 +448,12 @@ C snapshots taken after complete game frames. It does not grant items, edit stats, teleport characters, bypass native commands or inject protocol packets. Use it for remaining gameplay work instead of copying local memory-scanning scripts or adding sleeps after each action. +Short key/click helpers release on the fresh consumed SDL event, then read the +next full snapshot. Reading a large snapshot while holding a skill button can +trigger native autorepeat and buy more points than intended. +`GameTest.walk(x, z)` follows observed position and heading with bounded native +steering/final-approach pulses. It rejects stalled routes and waits for actor +readiness when travel changes playfields. Use it for ordinary ground routes. Run its isolated browser regression with Node.js, Playwright and Chromium available (`node` on PATH, `playwright` installed locally or on NODE_PATH, @@ -468,11 +474,14 @@ DISPLAY/XAUTHORITY environment as the other GPU browser checks. `TestBrowserStarterEquipment` creates two Atrox Enforcers through Options with their normal Omni starter loadouts and the production training-ground population. -It checks native equipment ownership against authoritative inventory state, -observer isolation, page reconnect and cold database loading. It does not grant -items or change character stats, cash or enemies. This is the equipment slice -of the larger progression regression; earned combat, purchases and recovery -remain separate checks. +It checks issued-bat equip/remove/re-wear, normal skill purchases, the issued +shirt and nano crystal, a full-health spawned Leet kill, single-award corpse +cash, any generated part, laboratory use/locked retry and quiet recovery. +Native ownership is compared with server state, observer isolation, page +reconnect and cold database loading. Skills and rewards use ordinary native +commands and production random rolls, without grants or edited characters/enemies. +Earned levels, missions, sales, purchases and actual reclaim remain broader +regression work. `TestBrowserStarterMissionTargets` walks a normally created starter through its training exit to Backyard1. It checks the distinct booth56001, entrance56006 and diff --git a/TODO.md b/TODO.md @@ -3023,6 +3023,24 @@ with payloads and known client/server provenance. book; the corrected helper confirms the corpse and real right-click Use collects its two credits with the book still present. See [native picking evidence](docs/native-picking.md). +- [x] [P1] Release short browser-harness inputs before reading a full native + snapshot. Check: each fresh consumed key/button event triggers release without + waiting for a large snapshot, stale/queued events cannot release it early, and + failures still release held input. The fresh starter regression observed + 133..233ms mouse holds and two Treatment clicks purchasing four points. The + correction reduces the median hold from 166.64ms to 24.81ms; exact ordinary + training and the connected normal-roll kill/cash/recovery ledger pass, with + focused stale-event/error-release tests. The wider focus/repeat audit remains + open. See [starter progression](docs/starter-progression.md#maintained-fresh-character-combat-and-recovery). +- [x] [P1] Avoid waiting for world picking at a GUI-covered probe. The precise + mission-booth approach projected its root below the canvas; the first on-canvas + candidate at [275,750] landed on the bottom HUD and produced no native query. + The driver now uses the existing native hotspot lookup to skip GUI-covered + pixels and probes higher portions of nearby models, retaining the completed + world-query guarantee. A fresh Leet also reproduced transparent chat blocking + its origin. Focused driver tests and real native booth Use pass. Fully covered + models can still require ordinary camera/movement input. See + [native picking evidence](docs/native-picking.md#gui-covered-probes). - [x] Include original mission booths and entrances in native frame snapshots. Their shared n3Dynel layout and typed directory identity are recovered from the client. A WASM fixture distinguishes equal numeric IDs, and an ordinary @@ -3117,6 +3135,10 @@ with payloads and known client/server provenance. database is closed`. Include session-writer draining before database cleanup; retained captures are in `local/todo-progression-play/`. Its resumed manual fixture now waits for connected clients to retire before closing SQLite. + The maintained starter regression reproduces the same late nano-duration + write during a failed run. Shared browser-stream cleanup now waits for its + world sessions to retire after closing their streams, while ignoring synthetic + non-browser clients. The broader fixture-handle audit remains open. - [ ] [P3] Reproduce stale shop interaction state after a live control-panel inventory edit. In the restoration smoke run, a nearby original terminal reported "Too far away" after the edit, while a fresh page could use it. @@ -3434,10 +3456,13 @@ and server restarts. Turn every reproduced bug into a focused regression test. instance in slot6, with no page errors or admin edits. Combat, earned loot, leveling and purchases are not yet verified in this normal-play run. Retained evidence: `local/gameplay-loop-smoke/`; owned characters/items were cleaned up. - `TestBrowserStarterEquipment` now repeats normal two-client creation and the - issued bat's equip/remove/re-equip, owner reconnect and cold ownership checks - against production training-ground resources. This is an automated equipment - slice; it does not complete the earned combat, purchases or recovery gate. + `TestBrowserStarterEquipment` now repeats normal two-client creation, issued + bat equip/remove/re-equip, exact skill purchases, the issued buff and shirt, + a full-health spawned Leet kill, corpse cash/item accounting and laboratory + recovery with locked repeats. It compares native ownership with server state, + page reconnect and cold loading, using production rolls and training-ground + resources. Earned levels, missions, sales/purchases and actual reclaim remain + broader regression work. A new two-client harness run now connects seven full-health ordinary kills, an earned Monster Part sale and funded mission request to all five private encounters, exact-book hand-in and earned QL1 Metaplast body armor. Rejected diff --git a/client/tests/game_test.mjs b/client/tests/game_test.mjs @@ -102,6 +102,77 @@ test('a stalled game releases held keys and reports the unmet condition', async assert.deepEqual(keys, [['down', 'KeyW'], ['up', 'KeyW']]); }); +for (const action of ['key', 'click']) test(`${action} releases consumed input before reading a full snapshot`, async () => { + const game = new GameTest(); + const calls = []; + let held = false, consumed = false; + const downType = action === 'key' ? 768 : 1025; + const upType = action === 'key' ? 769 : 1026; + game.record({kind: 'input', stage: 'consumed', type: downType}); + const input = { + down: async () => { + held = true; + calls.push('down'); + game.record({kind: 'input', stage: 'queued', type: downType}); + setImmediate(() => { + consumed = true; + game.record({kind: 'input', stage: 'consumed', type: downType}); + }); + }, + up: async () => { + held = false; + calls.push(['up', consumed]); + game.record({kind: 'input', stage: 'consumed', type: upType}); + }, + }; + game.page = {bringToFront: async () => {}, locator: () => ({focus: async () => {}}), + keyboard: input, mouse: {...input, move: async () => {}}}; + game.point = async (x, y) => ({x, y}); + game.snapshot = async () => { + assert(!held, 'A full snapshot kept the native button held and allowed autorepeat'); + return {frame: 1}; + }; + + if (action === 'key') await game.key('KeyU'); + else await game.click(835, 376); + + assert.deepEqual(calls, ['down', ['up', true]]); +}); + +test('an engine failure still releases a short key press', async () => { + const game = new GameTest(); + const keys = []; + game.page = {bringToFront: async () => {}, locator: () => ({focus: async () => {}}), + keyboard: { + down: async key => { + keys.push(['down', key]); + setImmediate(() => game.record({kind: 'error', message: 'native client aborted'})); + }, + up: async key => keys.push(['up', key]), + }}; + + const action = game.key('KeyU'); + + await assert.rejects(action, /native client aborted/); + assert.deepEqual(keys, [['down', 'KeyU'], ['up', 'KeyU']]); +}); + +test('walking stops for observed zoning before sending another movement pulse', async () => { + const game = new GameTest(); + game.state = {localId: 7, actors: [{type: 50000, id: 7, playfield: 950}]}; + const keys = []; + let ready = 0; + game.page = {bringToFront: async () => {}, locator: () => ({focus: async () => {}}), + keyboard: {press: async key => keys.push(key)}}; + game.snapshot = async () => { game.state.actors[0].playfield = 3000; return game.state; }; + game.ready = async () => { ++ready; }; + + await game.walk(60, 75); + + assert.equal(ready, 1); + assert.deepEqual(keys, []); +}); + test('client errors still fail waits after ordinary traffic fills the trace', async () => { const game = new GameTest(); game.snapshot = async () => ({frame: 1}); @@ -119,7 +190,7 @@ test('client errors still fail waits after ordinary traffic fills the trace', as test('picking follows a moving native projection between probes', async () => { const game = new GameTest(); const moves = []; - game.page = {mouse: {move: async (x, y) => { moves.push([x, y]); }}}; + game.page = {evaluate: async () => true, mouse: {move: async (x, y) => { moves.push([x, y]); }}}; game.point = async (x, y) => ({x, y}); let frame = 0; game.snapshot = async () => { @@ -141,7 +212,7 @@ test('picking waits for the current pixel instead of accepting cached hover', as let pending = 0, frame = 0; let pick = {sequence: 0, position: [42, 42], identity: [50000, 7]}; let hover = pick.identity; - game.page = {mouse: {move: async (x, y) => { moves.push([x, y]); pending = 3; }}}; + game.page = {evaluate: async () => true, mouse: {move: async (x, y) => { moves.push([x, y]); pending = 3; }}}; game.point = async (x, y) => ({x, y}); game.snapshot = async () => { ++frame; @@ -163,7 +234,7 @@ test('picking waits for the current pixel instead of accepting cached hover', as test('picking skips pixels outside the canvas before waiting for native selection', async () => { const game = new GameTest(); const moves = []; - game.page = {mouse: {move: async (x, y) => { + game.page = {evaluate: async () => true, mouse: {move: async (x, y) => { assert(y < 768, 'An offscreen pointer cannot reach the native picker'); moves.push([x, y]); }}}; @@ -177,3 +248,30 @@ test('picking skips pixels outside the canvas before waiting for native selectio assert.deepEqual(point, [100, 762]); assert.deepEqual(moves, [[100, 762]]); }); + +test('picking finds visible mesh above a GUI-covered origin before the model leaves view', async () => { + const game = new GameTest(); + const moves = []; + let observations = 0; + game.page = { + evaluate: async (callback, {y}) => y < 594, + mouse: {move: async (x, y) => { + assert(y < 594, 'Transparent chat consumes this pointer without a world query'); + moves.push([x, y]); + }}, + }; + game.point = async (x, y) => ({x, y}); + game.snapshot = async () => { + ++observations; + const hover = moves.at(-1)?.[1] === 553 ? [50000, 7] : [0, 0]; + return {screen: [1024, 768], hover, + pick: {sequence: moves.length, position: moves.at(-1), identity: hover}, + actors: [{type: 50000, id: 7, screenPosition: observations < 20 ? [100, 673, 0.5] : null}]}; + }; + + const point = await game.pick(50000, 7); + + assert.deepEqual(point, [100, 553]); + assert.deepEqual(moves, [[100, 593], [99, 593], [101, 593], [92, 593], + [108, 593], [80, 593], [120, 593], [100, 553]]); +}); diff --git a/docs/native-picking.md b/docs/native-picking.md @@ -98,3 +98,35 @@ inventory. Captures are in `mission88-third-corpse-open/`. The independent verifier and exact comparison records are `local/picker-timing-research/tmp_verify_overlap.py` and `overlap-verified.json`. + +### GUI-covered probes + +World queries do not run for pointers captured by native UI hotspots, including +the transparent chat history. A fresh starter's roaming Leet projected into +that history and left the query describing an earlier pointer position for the +whole wait. A close booth approach also placed its first on-canvas probe on the +bottom toolbar. Captures are `local/game-tests/starter-20261030-201953/` and +`local/game-tests/mission-targets-20261030-195448/`. In +`local/game-tests/mission-targets-20261030-202715/`, chat covers the booth's +origin at approximately [379,673], while its upper model remains visible. + +The driver now consults `client/browser/index.html:touchRegion`, the existing +lookup over native hotspots in hit order, before moving to each candidate. +GUI-covered candidates are skipped; world candidates still require a fresh +completed query at their exact pixel and matching hover. Probes extend up to +200 pixels above the origin for nearby tall statels. Fully covered targets +can still require ordinary camera or movement input to expose them. The public +driver regression reproduces transparent chat covering an otherwise on-canvas +probe and verifies selection from the next visible world candidate. +Blocked pixels share one snapshot per probe row, avoiding a separate frame +wait for every covered pixel. The focused +test includes a model that leaves view if too many observations are needed; +the stale-hover and moving-projection checks also pass. All 126 JavaScript +tests pass. Native movement, picking and reload pass in 16.84 seconds, with +ordinary backyard booth Use passing in 41.88 seconds. Captures: +`local/game-tests/20261030-205203/` and +`local/game-tests/mission-targets-20261030-205412/`. +The maintained starter uses native Tab targeting for a moving combatant and +observed right-mouse camera input to expose stationary remains on uneven terrain. +Its [item-bearing run](starter-progression.md#maintained-fresh-character-combat-and-recovery) +retains strict mouse picking for the corpse and verifies the generated item transfer. diff --git a/docs/open-questions.md b/docs/open-questions.md @@ -104,6 +104,12 @@ and layouts must be verified against the original binaries before reuse. - [AOCapture](https://github.com/philippelatulippe/AOCapture): capture parsing and proposed spawn/movement inference. The examined extraction/inference work contained TODOs; it did not establish an available spawn archive. +- [Simula's public AO traffic dataset](https://datasets.simula.no/ao/): + Petlund et al., "Network Traffic from Anarchy Online: Analysis, Statistics + and Applications", MMSys 2012, pp. 95-100. The + [paper's section 3](https://web-backend.simula.no/sites/default/files/publications/Simula.simula.1162.pdf) + specifies packet headers without payloads and anonymized addresses. It cannot + establish game-content messages or 14.9.1 loot, token or reclaim rules. ## Limits on historical reconstruction diff --git a/docs/starter-progression.md b/docs/starter-progression.md @@ -1359,3 +1359,66 @@ verifier are retained under `tmp_verify_level4_connected.py` and `earned-level4-connected-verified.json`. Maintained Go/C sources are unchanged. Actual reclaim and the broader P0 progression gate remain open. + +## Maintained fresh-character combat and recovery + +`TestBrowserStarterEquipment` now repeats the first combat slice with two new +Omni Atrox Enforcers in a disposable world. Its `newServer()` initialization +uses the production combat/loot generator. Native skill purchases spend 330 of +the issued 1500 IP, yielding 84 maximum HP. The owner wears its issued shirt, +consumes its crystal to learn Thug's Delight and normally casts it, reaching +attack rating 27. The observer retains its issued items, skills, cash and XP. + +The owner must have full native/server health before the fight. The chosen +ordinary level-1 Leet must have its full provisional 100 server HP; +this check does not establish historical Leet balance. Ordinary attacks and +Fast Attack on received skill unlocks earn 100 XP. Native corpse Use collects +the actual cash; closing/reopening must emit another typed Use request without +another award. Any naturally generated QL1 Monster Part must transfer with its +exact identity and metadata. Empty and item-bearing corpses remain separate +outcomes; the test does not change loot rolls. + +Recovery uses the issued laboratory on real Treatment unlocks, checks each +charge debit and health gain, rejects immediate locked repeats, and waits for +full native/server HP. The exact remaining supply follows those accepted uses. +The final ledger accounts for the consumed crystal, all other issued instances, +cash and any generated part. Page reload checks every native identity, slot, +quantity and quality; a stopped simulation and cold database load independently +check ownership, health, skills and rewards. Screenshots include corpse loot, +both equipment pages and final inventory/Stats; `ledger.json` retains the +authoritative accounting alongside native traces. + +The skill form exposed a harness input problem: full snapshots delayed mouse +release, and two intended Treatment clicks purchased four points. The same 30 +clicks held for a median 166.64ms before the fix and 24.81ms afterward; only +Treatment changed, 9->7, preserving 30 IP. Short presses now release on fresh +consumed input events. Stale/queued events cannot release them early, and an +engine error still releases held input. Bounded walking pulses also avoid +snapshot-dependent turn overshoot. The training route passes through the +observed fence opening via [62,65] and [62,74]. + +The combat approach follows the Leet's current native position and uses the +shipped Tab target cycle, then checks range against its server position before +attacking. After the kill, bounded backward presses keep the corpse within the +five-metre Use range. Native right-mouse camera input frames its observed +projection above chat when terrain hides the model. Corpse selection still +requires a completed native mouse query. The normal-roll capture +`local/game-tests/starter-20261030-205552/` passes this connected path with +100 XP, 1170 IP, four credits, laboratory x21 and full 84 HP. The observer's +seven items and progress remain unchanged across page reload and cold loading. + +The item-bearing run `local/game-tests/starter-20261030-211254/` passes in +221.62 seconds with naturally generated part 15: type51005/template42640, +QL1/count1/ammo0. Native pickup moves it from corpse slot0 to server slot67 +(native inventory slot51). Page reload and cold loading retain all seven owner +items, learned nano43371, three credits, laboratory x21, XP100/IP1170 and full +84 HP; the observer retains all seven issued items and zero progress. The +independent verifier checks full native type/template/slot/quality/count metadata +for this run and seven normal empty-drop runs. Its script and report are +`local/todo-progression-play/tmp_verify_starter_production.py` and +`starter-production-verified.json`. All 126 JavaScript checks pass, and the +focused browser-stream/session Go tests also pass with the race detector. + +This automated slice complements the earned continuation above. Further earned +levels, mission completion, sales/purchases and actual reclaim remain part of +the broader regression gate. diff --git a/server/browser_game_test.go b/server/browser_game_test.go @@ -87,31 +87,68 @@ func TestBrowserStarterEquipment(t *testing.T) { _, source, _, _ := runtime.Caller(0) root := filepath.Dir(filepath.Dir(source)) output := filepath.Join(root, "local", "game-tests", "starter-"+time.Now().Format("20060102-150405")) - world := newTestServer(t) + + // Use production initialization and random rolls in a disposable world. + t.Chdir(t.TempDir()) + world := newServer() + t.Cleanup(func() { world.db.Close() }) 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() player := world.browserCharacter_locked(r) - json.NewEncoder(w).Encode(player.inventory) + enemies := []map[string]any{} + corpses := []map[string]any{} + for _, enemy := range world.characters { + if enemy.corpse != nil && enemy.playfield == player.playfield { + corpses = append(corpses, map[string]any{"id": enemy.id, + "items": enemy.corpse.items, "credits": enemy.corpse.credits}) + } + if enemy.npc && enemy.playfield == player.playfield && enemy.monsterData == 17655 && enemy.level == 1 && enemy.health > 0 { + enemies = append(enemies, map[string]any{"id": enemy.id, "position": enemy.position, + "health": enemy.health, "maximumHealth": enemy.maximumHealth()}) + } + } + json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "health": player.health, + "maximumHealth": player.maximumHealth(), "stats": player.stats, "enemies": enemies, "corpses": corpses}) }) host := httptest.NewServer(mux) t.Cleanup(host.Close) closeTestBrowserStreams(t, world) - // Advance actual equipment delays while keeping the test's simulation stoppable. + // Advance the ordinary world without changing characters, encounters or rolls. ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute) defer cancel() stopped := make(chan struct{}) go func() { defer close(stopped) - ticker := time.NewTicker(250 * time.Millisecond) - defer ticker.Stop() + movement := time.NewTicker(time.Second / 60) + simulation := time.NewTicker(250 * time.Millisecond) + checkpoint := time.NewTicker(time.Second) + defer movement.Stop() + defer simulation.Stop() + defer checkpoint.Stop() for { select { - case now := <-ticker.C: + case now := <-movement.C: + world.advancePlayerMovement(now) + case now := <-simulation.C: + world.advanceCorpseExpiry(now) + world.advanceNPCRespawns(now) + world.advanceNPCs(now) world.advanceEquipment(now) + world.advanceItemEffects(now) + world.advanceNanos(now) + world.advanceCombat(now) + world.advanceRegeneration(now) + case now := <-checkpoint.C: + if err := world.checkpointWorld(now); err != nil { + t.Error(err) + } + if err := world.flushPositions(now); err != nil { + t.Error(err) + } case <-ctx.Done(): return } @@ -123,11 +160,16 @@ func TestBrowserStarterEquipment(t *testing.T) { command.Dir = root command.Stdout, command.Stderr = os.Stdout, os.Stderr err := command.Run() + cancel() + <-stopped t.Logf("Browser artifacts: %s", output) if err != nil { t.Fatal(err) } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } restored := newServer() defer restored.db.Close() world.mutex.Lock() @@ -138,11 +180,26 @@ func TestBrowserStarterEquipment(t *testing.T) { continue } players++ - if len(player.inventory.Items) != 7 || player.inventory.Credits != 0 || player.level != 1 || player.experience != 0 || + if player.level != 1 || player.health != player.maximumHealth() || !reflect.DeepEqual(player.inventory.Items, restored.characters[player.id].inventory.Items) || - !reflect.DeepEqual(player.inventory.references(), restored.characters[player.id].inventory.references()) { + !reflect.DeepEqual(player.inventory.references(), restored.characters[player.id].inventory.references()) || + !reflect.DeepEqual(player.inventory.LearnedNanos, restored.characters[player.id].inventory.LearnedNanos) || + !reflect.DeepEqual(player.stats, restored.characters[player.id].stats) || + player.health != restored.characters[player.id].health || player.experience != restored.characters[player.id].experience || + player.inventory.Credits != restored.characters[player.id].inventory.Credits { t.Fatalf("starter ownership changed across cold loading for %s: %+v", player.name, player.inventory) } + if player.name == "Starterwatch" { + if len(player.inventory.Items) != 7 || player.inventory.Credits != 0 || player.experience != 0 || player.stats.ImprovementPoints != 1500 { + t.Fatalf("observer received another player's progress: %+v", player) + } + continue + } + if player.experience != 100 || player.stats.ImprovementPoints != 1170 || player.maximumHealth() != 84 || player.aggDef != 100 || + player.inventory.Credits < 1 || player.inventory.Credits > 5 || + !reflect.DeepEqual(player.inventory.LearnedNanos, []uint32{43371}) { + t.Fatalf("ordinary starter fight, training or learning was not retained: %+v", player) + } } if players != 2 { t.Fatalf("created %d ordinary characters, want 2", players) diff --git a/server/browser_stream_test.go b/server/browser_stream_test.go @@ -28,6 +28,26 @@ func closeTestBrowserStreams(t *testing.T, world *server) { for _, stream := range streams { stream.close() } + + // World sessions save paused nano durations before removing their client entry. + deadline := time.Now().Add(5 * time.Second) + for { + world.mutex.Lock() + remaining := 0 + for _, client := range world.clients { + if client.stream != nil { + remaining++ + } + } + world.mutex.Unlock() + if remaining == 0 { + return + } + if time.Now().After(deadline) { + t.Fatal("browser world sessions did not finish disconnecting") + } + time.Sleep(time.Millisecond) + } }) } diff --git a/tools/client/game_test.mjs b/tools/client/game_test.mjs @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import {EventEmitter, once} from 'node:events'; import fs from 'node:fs/promises'; // Reassemble protocol packets, independently of WebSocket fragmentation and replay. @@ -30,6 +31,7 @@ export class PacketStream { export class GameTest { events = []; + inputEvents = new EventEmitter(); errors = []; snapshots = []; sequence = 0; @@ -108,6 +110,8 @@ export class GameTest { this.events.push(recorded); if (event.kind === 'error') this.errors.push(recorded); if (this.events.length > 2048) { this.events.shift(); ++this.dropped; } + if (event.kind === 'error' || event.kind === 'input' && event.stage === 'consumed') + this.inputEvents.emit('input', recorded); } async snapshot(timeout = 10000) { @@ -173,6 +177,20 @@ export class GameTest { return state.actors.find(actor => actor.type === 50000 && actor.id === state.localId); } + // Release short presses on the input event, before a large snapshot can delay them. + async waitInput(sequence, type) { + const consumed = event => event.sequence > sequence && event.kind === 'input' && + event.stage === 'consumed' && event.type === type; + assert(!this.errors[0], this.errors[0]?.message); + if (this.events.some(consumed)) return; + const signal = AbortSignal.timeout(10000); + for (;;) { + const [event] = await once(this.inputEvents, 'input', {signal}); + assert(!this.errors[0], this.errors[0]?.message); + if (consumed(event)) return; + } + } + // Separate down/up by consumed game frames, without guessing a click duration. async key(key) { this.record({kind: 'action', action: 'key', key}); @@ -181,8 +199,7 @@ export class GameTest { let sequence = this.sequence; await this.page.keyboard.down(key); try { - await this.wait('key down consumed', () => this.events.some(event => - event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 768)); + await this.waitInput(sequence, 768); } finally { sequence = this.sequence; await this.page.keyboard.up(key); @@ -206,6 +223,50 @@ export class GameTest { event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 769)); } + // Bound steering presses so snapshot delivery cannot extend a turn past its goal. + async walk(x, z) { + await this.page.bringToFront(); + await this.page.locator('#canvas').focus(); + const field = this.local().playfield; + const difference = (a, b) => Math.atan2(Math.sin(a - b), Math.cos(a - b)); + let best = Infinity, progressAt = Date.now(); + for (;;) { + await this.snapshot(); + assert(!this.errors[0], this.errors[0]?.message); + const actor = this.local(); + if (!actor || actor.playfield !== field) { await this.ready(); return; } + const distance = Math.hypot(x - actor.position[0], z - actor.position[2]); + if (distance < 0.35) return; + if (distance < best - 0.05) { best = distance; progressAt = Date.now(); } + assert(Date.now() - progressAt < 8000, 'Route is not approaching its destination'); + const yaw = Math.atan2(x - actor.position[0], z - actor.position[2]); + const angle = difference(yaw, 2 * Math.atan2(actor.rotation[1], actor.rotation[3])); + const key = Math.abs(angle) > 0.06 ? (angle > 0 ? 'KeyD' : 'KeyA') : 'KeyW'; + + // Hold straight travel until steering or the final approach needs another pulse. + if (key === 'KeyW' && distance > 3) { + await this.hold('KeyW', `walk toward ${x},${z}`, state => { + const actor = this.local(state); + if (!actor || actor.playfield !== field) return true; + const distance = Math.hypot(x - actor.position[0], z - actor.position[2]); + if (distance < best - 0.05) { best = distance; progressAt = Date.now(); } + assert(Date.now() - progressAt < 8000, 'Route is not approaching its destination'); + const yaw = Math.atan2(x - actor.position[0], z - actor.position[2]); + return distance < 2 || Math.abs(difference(yaw, 2 * Math.atan2(actor.rotation[1], actor.rotation[3]))) > 0.06; + }, 120000); + continue; + } + + const delay = key === 'KeyW' + ? Math.min(500, Math.max(40, (distance - 0.1) / 4.025 * 1000)) + : Math.min(200, Math.max(20, Math.abs(angle) / 3.5 * 1000)); + this.record({kind: 'action', action: 'walk-pulse', key, delay, x, z}); + const sequence = this.sequence; + await this.page.keyboard.press(key, {delay}); + await this.waitInput(sequence, 769); + } + } + async point(x, y) { const bounds = await this.page.locator('#canvas').boundingBox(); assert(bounds, 'Canvas has no bounds'); @@ -221,8 +282,7 @@ export class GameTest { let sequence = this.sequence; await this.page.mouse.down({button}); try { - await this.wait('mouse down consumed', () => this.events.some(event => - event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 1025)); + await this.waitInput(sequence, 1025); } finally { sequence = this.sequence; await this.page.mouse.up({button}); @@ -234,27 +294,29 @@ export class GameTest { async pick(type, id) { this.record({kind: 'action', action: 'pick', type, id}); let state = await this.snapshot(); - // Distant models can be only a few pixels wide around their projected origin. - for (const dy of [0, -8, -20, -40, 8, 20]) for (const dx of [0, -1, 1, -8, 8, -20, 20]) { - // Follow native movement while probing, including an entity entering the view. - const actor = state.actors.find(actor => actor.type === type && actor.id === id); - assert(actor?.screenPosition, `Entity ${type}:${id} is not projected`); - const [x, y, depth] = actor.screenPosition; - assert(depth >= 0 && depth <= 1, `Entity ${type}:${id} is outside the camera depth range`); - const pixel = [Math.round(x + dx), Math.round(y + dy)]; - if (pixel[0] < 0 || pixel[0] >= state.screen[0] || pixel[1] < 0 || pixel[1] >= state.screen[1]) { - state = await this.snapshot(); - continue; + // Probe narrow distant models and visible upper portions of nearby statels. + for (const dy of [0, -8, -20, -40, -80, -120, -160, -200, 8, 20]) { + for (const dx of [0, -1, 1, -8, 8, -20, 20]) { + const actor = state.actors.find(actor => actor.type === type && actor.id === id); + assert(actor?.screenPosition, `Entity ${type}:${id} is not projected`); + const [x, y, depth] = actor.screenPosition; + assert(depth >= 0 && depth <= 1, `Entity ${type}:${id} is outside the camera depth range`); + const pixel = [Math.round(x + dx), Math.round(y + dy)]; + if (pixel[0] < 0 || pixel[0] >= state.screen[0] || pixel[1] < 0 || pixel[1] >= state.screen[1]) continue; + const point = await this.point(x + dx, y + dy); + // Native hotspot order blocks world queries even through transparent UI. + if (!await this.page.evaluate(({x, y}) => touchRegion(x, y)?.world === true, point)) continue; + const sequence = state.pick?.sequence ?? 0; + await this.page.mouse.move(point.x, point.y); + // Native selection runs separately from pointer delivery and cached hover. + state = await this.wait('native pick at the current pointer pixel', state => + state.pick && state.pick.sequence > sequence && + state.pick.position[0] === pixel[0] && state.pick.position[1] === pixel[1] && + state.hover[0] === state.pick.identity[0] && state.hover[1] === state.pick.identity[1]); + if (state.hover[0] === type && state.hover[1] === id) return [x + dx, y + dy]; } - const point = await this.point(x + dx, y + dy); - const sequence = state.pick?.sequence ?? 0; - await this.page.mouse.move(point.x, point.y); - // Native selection runs separately from pointer delivery and cached hover. - state = await this.wait('native pick at the current pointer pixel', state => - state.pick && state.pick.sequence > sequence && - state.pick.position[0] === pixel[0] && state.pick.position[1] === pixel[1] && - state.hover[0] === state.pick.identity[0] && state.hover[1] === state.pick.identity[1]); - if (state.hover[0] === type && state.hover[1] === id) return [x + dx, y + dy]; + // Follow movement between rows without spending a frame on every blocked pixel. + state = await this.snapshot(); } throw new Error(`Native picker did not hit ${type}:${id} near its screen position`); } diff --git a/tools/client/test_starter_equipment.mjs b/tools/client/test_starter_equipment.mjs @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; import {createRequire} from 'node:module'; import {GameTest} from './game_test.mjs'; @@ -6,8 +7,46 @@ const {chromium} = createRequire(import.meta.url)('playwright'); const [url, output] = process.argv.slice(2); assert(url && output, 'Run through TestBrowserStarterEquipment'); const browser = await chromium.launch({executablePath: '/usr/bin/chromium', - args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage']}); + args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); const games = []; + +// Use the issued laboratory on its real unlocks and retain every charge debit. +async function recover(game, label) { + const count = game.local().inventory.find(item => item.templates[0] === 116628).count; + await game.key('F1'); + await game.key('KeyX'); + await game.wait('seated for laboratory use', state => game.local(state).stats[430] === 2); + let uses = 0, sequence = game.sequence; + const deadline = Date.now() + 180000; + for (;;) { + await game.snapshot(); + const server = await (await game.page.request.get(url + '/test-state')).json(); + if (game.local().stats[27] === 84 && server.health === 84) break; + assert(Date.now() < deadline, 'Starter health did not recover in both client and server'); + const unlocked = game.events.some(event => { + if (event.sequence <= sequence || event.direction !== 'framereceived' || event.opcode !== '5e477770') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(packet.length - 20) === 164 && packet.readUInt32BE(packet.length - 4) === 124; + }); + if (uses && (!unlocked || server.maximumHealth - server.health < 15)) continue; + sequence = game.sequence; + await game.click(681, 45, 'right'); + ++uses; + await game.wait('one laboratory charge consumed', state => + game.local(state).inventory.find(item => item.templates[0] === 116628).count === count - uses); + await game.click(681, 45, 'right'); + const locked = await (await game.page.request.get(url + '/test-state')).json(); + assert.equal(locked.inventory.Items.find(item => item.Template === 116628).Count, count - uses); + assert(locked.health >= Math.min(84, server.health + 15)); + } + assert(uses > 0); + assert.equal(game.local().inventory.find(item => item.templates[0] === 116628).count, count - uses); + await game.key('KeyX'); + await game.save(output + '/' + label); + return uses; +} + try { // Create both characters through the same Options form used during ordinary play. for (const name of ['Starterowner', 'Starterwatch']) { @@ -40,14 +79,14 @@ try { const watched = observer.local().inventory; const bat = issued.find(item => item.templates[0] === 121564); assert(bat); - const before = await (await owner.page.request.get(url + '/test-state')).json(); + const before = (await (await owner.page.request.get(url + '/test-state')).json()).inventory; // The native inventory's initial three-column layout puts the issued bat fourth. await owner.key('i'); await owner.save(output + '/inventory'); await owner.click(681, 99, 'right'); await owner.wait('issued bat equipped', state => owner.local(state).inventory.some(item => item.id === bat.id && item.slot === 6)); - const equipped = await (await owner.page.request.get(url + '/test-state')).json(); + const equipped = (await (await owner.page.request.get(url + '/test-state')).json()).inventory; assert.deepEqual(equipped.Items, before.Items.map(item => item.ID === bat.id ? {...item, Slot: 6} : item)); assert.deepEqual(owner.local().inventory.map(item => item.id).sort(), issued.map(item => item.id).sort()); await observer.snapshot(); @@ -65,7 +104,7 @@ try { // Remove through Wear, then equip the same instance from its original inventory cell. await owner.click(867, 206, 'right'); await owner.wait('issued bat returned to inventory', state => owner.local(state).inventory.some(item => item.id === bat.id && item.slot === 51)); - const removed = await (await owner.page.request.get(url + '/test-state')).json(); + const removed = (await (await owner.page.request.get(url + '/test-state')).json()).inventory; assert.deepEqual(removed.Items, before.Items); assert.deepEqual(owner.local().inventory, issued); await owner.page.keyboard.press('Control+1'); @@ -73,12 +112,239 @@ try { await owner.save(output + '/removed'); await owner.click(681, 99, 'right'); await owner.wait('same issued bat equipped again', state => owner.local(state).inventory.some(item => item.id === bat.id && item.slot === 6)); - const reworn = await (await owner.page.request.get(url + '/test-state')).json(); + const reworn = (await (await owner.page.request.get(url + '/test-state')).json()).inventory; assert.deepEqual(reworn.Items, equipped.Items); await observer.snapshot(); assert.deepEqual(observer.local().inventory, watched); - for (const game of games) assert.deepEqual(game.errors, []); console.log('PASS: native remove/rewear preserves both starter loadouts and charges'); + + // Train the health, weapon and nano requirements through the native skill form. + await owner.key('KeyI'); + await owner.key('KeyU'); + for (const [y, points] of [[226, 3], [256, 3], [346, 5]]) + for (let point = 0; point < points; ++point) await owner.click(835, y); + await owner.click(445, 622); + await owner.key('KeyU'); + await owner.click(302, 272); + for (const [y, points] of [[166, 5], [436, 4]]) + for (let point = 0; point < points; ++point) await owner.click(835, y); + await owner.click(288, 504); + for (const [y, points] of [[226, 4], [316, 4], [376, 2]]) + for (let point = 0; point < points; ++point) await owner.click(835, y); + await owner.click(445, 622); + await owner.wait('ordinary skill purchase', state => owner.local(state).stats[53] === 1170); + const trained = await (await owner.page.request.get(url + '/test-state')).json(); + assert.equal(trained.stats.ImprovementPoints, 1170); + assert.equal(trained.stats.Abilities.Stamina, 13); + assert.equal(trained.stats.Abilities.Intelligence, 6); + assert.equal(trained.stats.Body.BodyDevelopment, 10); + assert.equal(trained.stats.Melee.OneHandBlunt, 10); + assert.equal(trained.stats.Melee.FastAttack, 9); + assert.equal(trained.stats.NanoAiding.PsychologicalModification, 9); + assert.equal(trained.stats.NanoAiding.SensoryImprovement, 9); + assert.equal(trained.stats.NanoAiding.Treatment, 7); + assert.equal(trained.stats.NanoAiding.FirstAid, 5); + assert.equal(trained.maximumHealth, 84); + await owner.key('KeyI'); + const trainingUses = await recover(owner, 'trained-recovery'); + + // Wear the issued shirt and learn/cast the issued Thug's Delight crystal. + const crystal = issued.find(item => item.templates[0] === 43379); + const shirt = issued.find(item => item.templates[0] === 29426); + await owner.click(681, 154, 'right'); + await owner.wait('issued shirt worn', state => owner.local(state).inventory.some(item => item.id === shirt.id && item.slot === 21)); + await owner.click(740, 99, 'right'); + await owner.wait('issued crystal consumed', state => !owner.local(state).inventory.some(item => item.id === crystal.id)); + await owner.page.keyboard.press('Control+8'); + await owner.click(927, 96); + await owner.key('F1'); + await owner.click(857, 128, 'right'); + await owner.wait('Thug\'s Delight active', state => owner.local(state).stats[22] === 27); + await owner.page.keyboard.press('Control+8'); + + // Drag the native aggression thumb, then approach a full-health spawned Leet. + await owner.page.keyboard.press('Control+9'); + const thumb = await owner.point(927, 190), aggressive = await owner.point(1006, 190); + await owner.page.mouse.move(thumb.x, thumb.y); + await owner.snapshot(); + await owner.page.mouse.down(); + try { + await owner.snapshot(); + await owner.page.mouse.move(aggressive.x, aggressive.y, {steps: 12}); + } finally { await owner.page.mouse.up(); } + await owner.wait('full aggression', state => owner.local(state).stats[51] === 100); + await owner.page.keyboard.press('Control+9'); + const population = await (await owner.page.request.get(url + '/test-state')).json(); + const position = owner.local().position; + const distance = enemy => Math.hypot(enemy.position[0] - position[0], enemy.position[2] - position[2]); + const enemy = population.enemies.sort((a, b) => distance(a) - distance(b))[0]; + assert(enemy && distance(enemy) < 40); + assert.equal(enemy.health, enemy.maximumHealth); + // Cross the authored opening before approaching the selected roaming Leet. + for (const [x, z] of [[62, 65], [62, 74]]) + await owner.walk(x, z); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + + let beforeFight, healthyEnemy; + const approachDeadline = Date.now() + 30000; + for (;;) { + await owner.snapshot(); + assert(Date.now() < approachDeadline, 'Starter did not approach the moving Leet'); + const target = owner.state.actors.find(actor => actor.type === 50000 && actor.id === enemy.id); + const position = owner.local().position; + if (Math.hypot(target.position[0] - position[0], target.position[1] - position[1], + target.position[2] - position[2]) > 2.5) { + await owner.walk(target.position[0], target.position[2] - 2); + continue; + } + // Cycle native combat targets without requiring a moving ground model above chat. + if (owner.state.selected[0] !== 50000 || owner.state.selected[1] !== enemy.id) { + await owner.key('Tab'); + continue; + } + beforeFight = await (await owner.page.request.get(url + '/test-state')).json(); + healthyEnemy = beforeFight.enemies.find(actor => actor.id === enemy.id); + if (Math.hypot(healthyEnemy.position[0] - owner.local().position[0], + healthyEnemy.position[1] - owner.local().position[1], healthyEnemy.position[2] - owner.local().position[2]) <= 3) break; + } + assert.equal(beforeFight.health, 84); + assert.equal(owner.local().stats[27], 84); + assert.equal(healthyEnemy.health, 100); + assert.equal(healthyEnemy.maximumHealth, 100); + await owner.key('KeyQ'); + let special = owner.sequence; + await owner.key('KeyN'); + const deadline = Date.now() + 120000; + for (;;) { + await owner.snapshot(); + assert(owner.local().stats[27] > 0, 'Ordinary starter died during its first fight'); + if (owner.state.actors.some(actor => actor.type === 51050 && actor.id === enemy.id)) break; + assert(Date.now() < deadline, 'Ordinary Leet fight did not finish'); + const unlocked = owner.events.some(event => { + if (event.sequence <= special || event.direction !== 'framereceived' || event.opcode !== '5e477770') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(packet.length - 20) === 164 && packet.readUInt32BE(packet.length - 4) === 147; + }); + if (unlocked) { + special = owner.sequence; + await owner.key('KeyN'); + } + } + await owner.wait('earned kill XP', state => owner.local(state).stats[52] === 100); + await owner.save(output + '/earned-kill'); + + // Use the actual remains twice, then take any generated part exactly once. + const killed = await (await owner.page.request.get(url + '/test-state')).json(); + const corpse = killed.corpses.find(corpse => corpse.id === enemy.id); + assert(corpse && corpse.credits >= 1 && corpse.credits <= 5); + const corpseDistance = state => { + const position = owner.local(state).position; + const remains = state.actors.find(actor => actor.type === 51050 && actor.id === enemy.id); + return Math.hypot(position[0] - remains.position[0], position[1] - remains.position[1], + position[2] - remains.position[2]); + }; + // Expose the small corpse above chat while staying within the five-metre Use range. + const viewingDeadline = Date.now() + 20000; + while (corpseDistance(owner.state) < 4.3) { + assert(Date.now() < viewingDeadline, 'Starter did not clear its corpse view'); + const sequence = owner.sequence; + await owner.page.keyboard.press('KeyS', {delay: 200}); + await owner.waitInput(sequence, 769); + await owner.snapshot(); + } + assert(corpseDistance(owner.state) < 5); + + // Frame the stationary remains through native camera input when terrain puts them behind UI. + const remains = () => owner.state.actors.find(actor => actor.type === 51050 && actor.id === enemy.id); + if (remains().screenPosition[1] < 350 || remains().screenPosition[1] > 540) { + const cameraPoint = await owner.point(512, 300); + let mouseY = cameraPoint.y, sequence = owner.sequence; + const framingDeadline = Date.now() + 10000; + await owner.page.mouse.move(cameraPoint.x, mouseY); + await owner.page.mouse.down({button: 'right'}); + try { + await owner.waitInput(sequence, 1025); + for (;;) { + await owner.snapshot(); + const screenY = remains().screenPosition[1]; + if (screenY >= 350 && screenY <= 540) break; + assert(Date.now() < framingDeadline, 'Starter did not frame its corpse above chat'); + mouseY += screenY > 540 ? 20 : -20; + await owner.page.mouse.move(cameraPoint.x, mouseY, {steps: 2}); + } + } finally { + sequence = owner.sequence; + await owner.page.mouse.up({button: 'right'}); + } + await owner.waitInput(sequence, 1026); + } + let [x, y] = await owner.pick(51050, enemy.id); + await owner.click(x, y, 'right'); + await owner.wait('earned corpse cash', state => owner.local(state).stats[61] === corpse.credits); + await owner.wait('corpse window open', state => state.regions.some( + ([left, top, right, bottom]) => left === 0 && top === 0 && right === 178 && bottom === 128)); + await owner.click(170, 8); + const reopen = owner.sequence; + [x, y] = await owner.pick(51050, enemy.id); + await owner.click(x, y, 'right'); + await owner.wait('native corpse reopen request', () => owner.events.some(event => { + if (event.sequence <= reopen || event.direction !== 'framesent' || event.opcode !== '52526858') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(packet.length - 8) === 51050 && packet.readUInt32BE(packet.length - 4) === enemy.id; + })); + await owner.wait('corpse window reopened', state => state.regions.some( + ([left, top, right, bottom]) => left === 0 && top === 0 && right === 178 && bottom === 128)); + await owner.save(output + '/corpse-loot'); + if (corpse.items?.length) { + assert.deepEqual(corpse.items, [{ID: corpse.items[0].ID, Type: 51005, + Template: 42640, Quality: 1, Slot: 0, Count: 1, Ammo: 0}]); + await owner.click(30, 45); + await owner.wait('generated part in native inventory', state => + owner.local(state).inventory.some(item => item.templates[0] === 42640)); + } + await owner.click(170, 8); + const combatUses = await recover(owner, 'post-combat-recovery'); + + // Account for every issued identity, consumed crystal, charge and generated item. + const expected = before.Items.filter(item => item.ID !== crystal.id).map(item => { + if (item.ID === bat.id) return {...item, Slot: 6}; + if (item.ID === shirt.id) return {...item, Slot: 21}; + if (item.Template === 116628) return {...item, Count: 25 - trainingUses - combatUses}; + return item; + }); + for (const item of corpse.items ?? []) expected.push({...item, Slot: 67}); + expected.sort((a, b) => a.ID - b.ID); + const final = await (await owner.page.request.get(url + '/test-state')).json(); + assert.deepEqual(final.inventory.Items, expected); + assert.equal(final.inventory.Credits, corpse.credits); + assert.deepEqual(final.inventory.LearnedNanos, [43371]); + await fs.writeFile(output + '/ledger.json', JSON.stringify({issued: before, trained: trained.stats, + fightStart: {health: beforeFight.health, enemy: healthyEnemy}, corpse, trainingUses, combatUses, + inventory: final.inventory, health: final.health}, null, 2) + '\n'); + await owner.page.reload(); + await owner.ready(); + assert.deepEqual(owner.local().inventory.map(item => item.id).sort(), expected.map(item => item.ID).sort()); + for (const item of expected) { + const actual = owner.local().inventory.find(actual => actual.id === item.ID); + assert.equal(actual.slot, item.Slot >= 64 ? item.Slot - 16 : item.Slot); + assert.equal(actual.count, item.Count); + assert.equal(actual.quality, item.Quality); + assert.equal(actual.templates[0], item.Template); + } + await owner.key('KeyI'); + await owner.page.keyboard.press('Control+1'); + await owner.snapshot(); + await owner.save(output + '/final-weapon'); + await owner.click(953, 53); + await owner.page.keyboard.press('Control+9'); + await owner.snapshot(); + await observer.snapshot(); + assert.deepEqual(observer.local().inventory, watched); + assert.equal(observer.local().stats[52], 0); + assert.equal(observer.local().stats[53], 1500); + assert.equal(observer.local().stats[61], 0); + for (const game of games) assert.deepEqual(game.errors, []); + console.log('PASS: normal training, issued buff, spawned kill, corpse ledger, laboratory recovery and page ownership'); } finally { try { for (const [index, game] of games.entries()) await game.save(output + '/client-' + index); diff --git a/tools/client/test_starter_mission_targets.mjs b/tools/client/test_starter_mission_targets.mjs @@ -9,39 +9,6 @@ const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage']}); let game; -// Follow ordinary movement feedback, stopping when a route no longer approaches its goal. -function difference(a, b) { return Math.atan2(Math.sin(a - b), Math.cos(a - b)); } -async function walk(x, z) { - const field = game.local().playfield; - let best = Infinity, progressAt = Date.now(); - for (;;) { - await game.snapshot(); - const actor = game.local(); - if (!actor || actor.playfield !== field) return; - const distance = Math.hypot(x - actor.position[0], z - actor.position[2]); - if (distance < 1.2) return; - if (distance < best - 0.2) { best = distance; progressAt = Date.now(); } - assert(Date.now() - progressAt < 8000, 'Route is not approaching its destination'); - const yaw = Math.atan2(x - actor.position[0], z - actor.position[2]); - const angle = difference(yaw, 2 * Math.atan2(actor.rotation[1], actor.rotation[3])); - if (Math.abs(angle) > 0.05) { - await game.hold(angle > 0 ? 'KeyD' : 'KeyA', 'face route', state => { - const actor = game.local(state); - if (!actor || actor.playfield !== field) return true; - const remaining = difference(yaw, 2 * Math.atan2(actor.rotation[1], actor.rotation[3])); - return Math.abs(remaining) < 0.05 || Math.sign(remaining) !== Math.sign(angle); - }); - } - const start = game.local().position; - await game.hold('KeyW', 'walk toward ' + x + ',' + z, state => { - const actor = game.local(state); - return !actor || actor.playfield !== field || - Math.hypot(actor.position[0] - start[0], actor.position[2] - start[2]) >= Math.min(3, distance - 1) || - Math.hypot(x - actor.position[0], z - actor.position[2]) < 1.2; - }, 5000); - } -} - try { const context = await browser.newContext({viewport: {width: 1024, height: 768}}); const page = await context.newPage(); @@ -81,8 +48,8 @@ try { assert(Math.hypot(door.position[0] - 102.95067, door.position[2] - 130.01703) < 0.01); await game.save(output + '/backyard'); - for (const [x, z] of [[102.5, 102], [102.5, 143], [104, 150], [102, 149.5]]) - await walk(x, z); + for (const [x, z] of [[102.5, 102], [102.5, 143], [104, 149.5], [103, 149.1]]) + await game.walk(x, z); assert.equal(game.local().playfield, 3000); if (!game.state.camera.firstPerson) await game.key('F8'); await game.save(output + '/booth-approach');