aorecomp

Anarchy Online classic in the browser

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


tools/client/game_test.mjs (16622B)


      1 import assert from 'node:assert/strict';
      2 import {EventEmitter, once} from 'node:events';
      3 import fs from 'node:fs/promises';
      4 
      5 // Reassemble protocol packets, independently of WebSocket fragmentation and replay.
      6 export class PacketStream {
      7   offset = 0;
      8   pending = Buffer.alloc(0);
      9 
     10   receive(payload) {
     11     if (!Buffer.isBuffer(payload)) return [];
     12     assert(payload.length >= 8, 'Missing stream offset');
     13     const offset = Number(payload.readBigUInt64BE());
     14     assert(offset <= this.offset, 'Gap in browser stream');
     15     const skip = this.offset - offset;
     16     const bytes = payload.subarray(8 + skip);
     17     this.offset += bytes.length;
     18     this.pending = Buffer.concat([this.pending, bytes]);
     19     const packets = [];
     20     while (this.pending.length >= 8) {
     21       const length = this.pending.readUInt16BE(6);
     22       assert(length >= 20, 'Invalid game packet length');
     23       const aligned = (length + 3) & ~3;
     24       if (this.pending.length < aligned) break;
     25       packets.push(this.pending.subarray(0, length));
     26       this.pending = this.pending.subarray(aligned);
     27     }
     28     return packets;
     29   }
     30 }
     31 
     32 export class GameTest {
     33   events = [];
     34   lifecycle = [];
     35   lifecycleDropped = 0;
     36   inputEvents = new EventEmitter();
     37   errors = [];
     38   snapshots = [];
     39   sequence = 0;
     40   dropped = 0;
     41   state = null;
     42   streams = new Map();
     43   navigation = 0;
     44   worldStream = null;
     45   readyActors = new Set();
     46 
     47   static async attach(page) {
     48     const game = new GameTest();
     49     game.page = page;
     50     await page.exposeFunction('aoTestEvent', event => game.record(event));
     51     await page.addInitScript(() => {
     52       // Capture browser delivery separately from the game's SDL consumption.
     53       for (const type of ['keydown', 'keyup', 'mousedown', 'mouseup'])
     54         window.addEventListener(type, event => window.aoTestEvent({kind: 'browser-input',
     55           type, code: event.code, button: event.button, x: event.clientX, y: event.clientY,
     56           time: performance.timeOrigin + performance.now()}), true);
     57     });
     58     page.on('framenavigated', frame => {
     59       if (frame === page.mainFrame()) {
     60         ++game.navigation;
     61         game.worldStream = null;
     62         game.readyActors.clear();
     63         game.record({kind: 'navigation', url: frame.url()});
     64       }
     65     });
     66     // Playwright's pageerror loses the stack when WASM throws a string such as unwind.
     67     const runtime = await page.context().newCDPSession(page);
     68     runtime.on('Runtime.exceptionThrown', ({exceptionDetails}) => game.record({kind: 'error',
     69       message: exceptionDetails.exception?.description?.split('\n')[0] ??
     70         String(exceptionDetails.exception?.value ?? exceptionDetails.text),
     71       details: exceptionDetails}));
     72     await runtime.send('Runtime.enable');
     73     page.on('console', message => {
     74       if (message.type() === 'error' || message.type() === 'warning')
     75         game.record({kind: 'console', level: message.type(), message: message.text()});
     76     });
     77     page.on('websocket', socket => {
     78       if (!socket.url().endsWith('/browser-world')) return;
     79       const navigation = game.navigation;
     80       let streams, stream;
     81       for (const direction of ['framesent', 'framereceived']) socket.on(direction, ({payload}) => {
     82         try {
     83           if (typeof payload === 'string') {
     84             const handshake = JSON.parse(payload);
     85             if (direction === 'framesent' && handshake.stream) {
     86               stream = handshake.stream;
     87               if (game.worldStream !== stream) game.readyActors.clear();
     88               game.worldStream = stream;
     89               streams = game.streams.get(handshake.stream);
     90               if (!streams) {
     91                 streams = {framesent: new PacketStream(), framereceived: new PacketStream()};
     92                 game.streams.set(handshake.stream, streams);
     93               }
     94             }
     95             return;
     96           }
     97           assert(streams, 'Game bytes arrived before stream handshake');
     98           for (const packet of streams[direction].receive(payload)) {
     99             const kind = packet.readUInt32BE(16).toString(16).padStart(8, '0');
    100             const actor = packet.readUInt16BE(2) === 10 && packet.length >= 28 ?
    101               [packet.readUInt32BE(20), packet.readUInt32BE(24)] : null;
    102             game.record({kind: 'packet', direction, navigation, stream, actor, opcode: kind, hex: packet.toString('hex')});
    103           }
    104         } catch (error) {
    105           game.record({kind: 'error', message: String(error)});
    106         }
    107       });
    108     });
    109     return game;
    110   }
    111 
    112   record(event) {
    113     // Transport reconnects retain readiness; a new game stream must acknowledge again.
    114     if (event.kind === 'packet' && event.direction === 'framereceived' && event.opcode === '570c2039' &&
    115         event.navigation === this.navigation && event.stream === this.worldStream && event.actor?.[0] === 50000)
    116       this.readyActors.add(event.actor[1]);
    117     const recorded = {time: Date.now(), navigation: this.navigation, ...event, sequence: ++this.sequence};
    118     this.events.push(recorded);
    119     // Preserve death, return requests and resurrection across large world replays.
    120     if (event.kind === 'packet') {
    121       const action = event.opcode === '5e477770' && event.hex.length >= 66 ?
    122         Buffer.from(event.hex, 'hex').readUInt32BE(29) : 0;
    123       if (event.opcode === '445f2a0b' || action === 99 || action === 152) {
    124         this.lifecycle.push(recorded);
    125         if (this.lifecycle.length > 64) { this.lifecycle.shift(); ++this.lifecycleDropped; }
    126       }
    127     }
    128     if (event.kind === 'error') this.errors.push(recorded);
    129     if (this.events.length > 2048) { this.events.shift(); ++this.dropped; }
    130     if (event.kind === 'error' || event.kind === 'input' && event.stage === 'consumed')
    131       this.inputEvents.emit('input', recorded);
    132   }
    133 
    134   async snapshot(timeout = 10000) {
    135     const frame = await this.page.evaluate(() => {
    136       if (!Module.onTestSnapshot) {
    137         Module.onTestSnapshot = snapshot => {
    138           window.aoTestSnapshot = {...snapshot, browser: {focused: document.hasFocus(),
    139             visibility: document.visibilityState, activeElement: document.activeElement?.id}};
    140         };
    141         Module.onTestEvent = event => window.aoTestEvent(event);
    142       }
    143       const frame = window.aoTestSnapshot?.frame ?? -1;
    144       Module._browser_test_request();
    145       return frame;
    146     });
    147     await this.page.waitForFunction(frame => window.aoTestSnapshot?.frame > frame, frame,
    148       {timeout});
    149     const previous = this.state;
    150     this.state = await this.page.evaluate(() => window.aoTestSnapshot);
    151     this.state.navigation = this.navigation;
    152     const before = previous && this.local(previous), after = this.local();
    153     if (before && after) {
    154       const stats = after.stats.map((value, id) => [id, before.stats[id], value])
    155         .filter(([, before, after]) => before !== after);
    156       if (stats.length) this.record({kind: 'stats', frame: this.state.frame, changes: stats});
    157       if (JSON.stringify(before.inventory) !== JSON.stringify(after.inventory))
    158         this.record({kind: 'inventory', frame: this.state.frame, items: after.inventory});
    159       if (JSON.stringify(before.position) !== JSON.stringify(after.position))
    160         this.record({kind: 'position', frame: this.state.frame, position: after.position});
    161     }
    162     this.snapshots.push(this.state);
    163     if (this.snapshots.length > 32) this.snapshots.shift();
    164     return this.state;
    165   }
    166 
    167   // Controller/storage conditions can outlive the current native page instance.
    168   async waitFor(label, predicate) {
    169     const deadline = Date.now() + 10000;
    170     do {
    171       const error = this.errors[0];
    172       assert(!error, error?.message);
    173       const result = await predicate();
    174       if (result) return result;
    175       await new Promise(resolve => setTimeout(resolve, 25));
    176     } while (Date.now() < deadline);
    177     throw new Error(`Timed out waiting for ${label}`);
    178   }
    179 
    180   async wait(label, predicate, timeout = 10000) {
    181     const deadline = Date.now() + timeout;
    182     do {
    183       let state;
    184       try { state = await this.snapshot(Math.max(1, deadline - Date.now())); }
    185       catch (error) {
    186         if (error.name !== 'TimeoutError') throw error;
    187         break;
    188       }
    189       const error = this.errors[0];
    190       assert(!error, error?.message);
    191       if (predicate(state)) return state;
    192     } while (Date.now() < deadline);
    193     throw new Error(`Timed out waiting for ${label}; client frame ${this.state?.frame ?? 'none'}`);
    194   }
    195 
    196   async ready() {
    197     await this.page.waitForFunction(() => typeof Module !== 'undefined' &&
    198       typeof Module._browser_test_request === 'function', null, {timeout: 180000});
    199     return this.wait('local actor and inventory', state => {
    200       const actor = state.actors.find(actor => actor.type === 50000 && actor.id === state.localId);
    201       return actor && !actor.deleting && actor.inventory && state.screen[0] > 0 &&
    202         this.worldStream !== null && this.readyActors.has(state.localId);
    203     }, 180000);
    204   }
    205 
    206   local(state = this.state) {
    207     return state.actors.find(actor => actor.type === 50000 && actor.id === state.localId);
    208   }
    209 
    210   // Release short presses on the input event, before a large snapshot can delay them.
    211   async waitInput(sequence, type) {
    212     const consumed = event => event.sequence > sequence && event.kind === 'input' &&
    213       event.stage === 'consumed' && event.type === type;
    214     assert(!this.errors[0], this.errors[0]?.message);
    215     if (this.events.some(consumed)) return;
    216     const signal = AbortSignal.timeout(10000);
    217     for (;;) {
    218       const [event] = await once(this.inputEvents, 'input', {signal});
    219       assert(!this.errors[0], this.errors[0]?.message);
    220       if (consumed(event)) return;
    221     }
    222   }
    223 
    224   // Separate down/up by consumed game frames, without guessing a click duration.
    225   async key(key) {
    226     this.record({kind: 'action', action: 'key', key});
    227     await this.page.bringToFront();
    228     await this.page.locator('#canvas').focus();
    229     let sequence = this.sequence;
    230     await this.page.keyboard.down(key);
    231     try {
    232       await this.waitInput(sequence, 768);
    233     } finally {
    234       sequence = this.sequence;
    235       await this.page.keyboard.up(key);
    236     }
    237     await this.wait('key up consumed', () => this.events.some(event =>
    238       event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 769));
    239   }
    240 
    241   async hold(key, label, predicate, timeout = 10000) {
    242     this.record({kind: 'action', action: 'hold', key, label});
    243     await this.page.bringToFront();
    244     await this.page.locator('#canvas').focus();
    245     await this.page.keyboard.down(key);
    246     let sequence;
    247     try { await this.wait(label, predicate, timeout); }
    248     finally {
    249       sequence = this.sequence;
    250       await this.page.keyboard.up(key);
    251     }
    252     return this.wait('held key released', () => this.events.some(event =>
    253       event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 769));
    254   }
    255 
    256   // Bound steering presses so snapshot delivery cannot extend a turn past its goal.
    257   async walk(x, z) {
    258     await this.page.bringToFront();
    259     await this.page.locator('#canvas').focus();
    260     if (!this.local()) await this.ready();
    261     const field = this.local().playfield;
    262     const difference = (a, b) => Math.atan2(Math.sin(a - b), Math.cos(a - b));
    263     let best = Infinity, progressAt = Date.now();
    264     for (;;) {
    265       await this.snapshot();
    266       assert(!this.errors[0], this.errors[0]?.message);
    267       const actor = this.local();
    268       if (!actor || actor.playfield !== field) { await this.ready(); return; }
    269       const distance = Math.hypot(x - actor.position[0], z - actor.position[2]);
    270       if (distance < 0.35) return;
    271       if (distance < best - 0.05) { best = distance; progressAt = Date.now(); }
    272       assert(Date.now() - progressAt < 8000, 'Route is not approaching its destination');
    273       const yaw = Math.atan2(x - actor.position[0], z - actor.position[2]);
    274       const angle = difference(yaw, 2 * Math.atan2(actor.rotation[1], actor.rotation[3]));
    275       const key = Math.abs(angle) > 0.06 ? (angle > 0 ? 'KeyD' : 'KeyA') : 'KeyW';
    276 
    277       // Hold longer moves until the final approach or an observed steering change.
    278       if (key === 'KeyW' && distance >= 1) {
    279         await this.hold('KeyW', `walk toward ${x},${z}`, state => {
    280           const actor = this.local(state);
    281           if (!actor || actor.playfield !== field) return true;
    282           const distance = Math.hypot(x - actor.position[0], z - actor.position[2]);
    283           if (distance < best - 0.05) { best = distance; progressAt = Date.now(); }
    284           assert(Date.now() - progressAt < 8000, 'Route is not approaching its destination');
    285           const yaw = Math.atan2(x - actor.position[0], z - actor.position[2]);
    286           return distance < 1 || Math.abs(difference(yaw, 2 * Math.atan2(actor.rotation[1], actor.rotation[3]))) > 0.06;
    287         }, 120000);
    288         continue;
    289       }
    290 
    291       const delay = key === 'KeyW' ? 200 : Math.min(200, Math.max(20, Math.abs(angle) / 3.5 * 1000));
    292       this.record({kind: 'action', action: 'walk-pulse', key, delay, x, z});
    293       const sequence = this.sequence;
    294       await this.page.keyboard.press(key, {delay});
    295       await this.waitInput(sequence, 769);
    296     }
    297   }
    298 
    299   async point(x, y) {
    300     const bounds = await this.page.locator('#canvas').boundingBox();
    301     assert(bounds, 'Canvas has no bounds');
    302     return {x: bounds.x + Math.round(x) * bounds.width / this.state.screen[0],
    303       y: bounds.y + Math.round(y) * bounds.height / this.state.screen[1]};
    304   }
    305 
    306   async click(x, y, button = 'left') {
    307     const point = await this.point(x, y);
    308     this.record({kind: 'action', action: 'click', x, y, button});
    309     await this.page.mouse.move(point.x, point.y);
    310     await this.snapshot();
    311     let sequence = this.sequence;
    312     await this.page.mouse.down({button});
    313     try {
    314       await this.waitInput(sequence, 1025);
    315     } finally {
    316       sequence = this.sequence;
    317       await this.page.mouse.up({button});
    318     }
    319     await this.wait('mouse up consumed', () => this.events.some(event =>
    320       event.sequence > sequence && event.kind === 'input' && event.stage === 'consumed' && event.type === 1026));
    321   }
    322 
    323   async pick(type, id) {
    324     this.record({kind: 'action', action: 'pick', type, id});
    325     let state = await this.snapshot();
    326     // Corpses can lie below or sideways from their root; living models extend above it.
    327     for (const dy of type === 51050 ? [0, -8, 8, -20, 20, -40, 40, -80, 80, -120, 120, -160, 160, -200, 200] : [0, -8, -20, -40, -80, -120, -160, -200, 8, 20]) {
    328       for (const dx of type === 51050 ? [0, -8, 8, -20, 20, -40, 40, -80, 80, -120, 120, -180, 180] : [0, -1, 1, -8, 8, -20, 20]) {
    329         const actor = state.actors.find(actor => actor.type === type && actor.id === id);
    330         assert(actor?.screenPosition, `Entity ${type}:${id} is not projected`);
    331         const [x, y, depth] = actor.screenPosition;
    332         assert(depth >= 0 && depth <= 1, `Entity ${type}:${id} is outside the camera depth range`);
    333         const pixel = [Math.round(x + dx), Math.round(y + dy)];
    334         if (pixel[0] < 0 || pixel[0] >= state.screen[0] || pixel[1] < 0 || pixel[1] >= state.screen[1]) continue;
    335         const point = await this.point(x + dx, y + dy);
    336         // Native hotspot order blocks world queries even through transparent UI.
    337         if (!await this.page.evaluate(({x, y}) => touchRegion(x, y)?.world === true, point)) continue;
    338         const sequence = state.pick?.sequence ?? 0;
    339         await this.page.mouse.move(point.x, point.y);
    340         // Native selection runs separately from pointer delivery and cached hover.
    341         state = await this.wait('native pick at the current pointer pixel', state =>
    342           state.pick && state.pick.sequence > sequence &&
    343           state.pick.position[0] === pixel[0] && state.pick.position[1] === pixel[1] &&
    344           state.hover[0] === state.pick.identity[0] && state.hover[1] === state.pick.identity[1]);
    345         if (state.hover[0] === type && state.hover[1] === id) return [x + dx, y + dy];
    346       }
    347       // Follow movement between rows without spending a frame on every blocked pixel.
    348       state = await this.snapshot();
    349     }
    350     throw new Error(`Native picker did not hit ${type}:${id} near its screen position`);
    351   }
    352 
    353   async save(directory) {
    354     await fs.mkdir(directory, {recursive: true});
    355     await fs.writeFile(`${directory}/trace.json`, JSON.stringify({url: this.page.url(),
    356       dropped: this.dropped, lifecycleDropped: this.lifecycleDropped, lifecycle: this.lifecycle,
    357       errors: this.errors, events: this.events, snapshots: this.snapshots}, null, 2) + '\n');
    358     await this.page.screenshot({path: `${directory}/screen.png`});
    359   }
    360 }