aorecomp

Anarchy Online classic in the browser

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


tests/e2e/cursor.test.mjs (16735B)


      1 import assert from 'node:assert/strict';
      2 import fs from 'node:fs/promises';
      3 import {before, test} from 'node:test';
      4 import {buildServer, withFixture} from './fixture.mjs';
      5 
      6 before(buildServer);
      7 
      8 test('a session takeover restores the OS cursor on the reconnect screen', {timeout: 150_000}, async () => {
      9   await withFixture('cursor-takeover', async fixture => {
     10     const context = await fixture.visitor();
     11     const game = await fixture.game(context);
     12     const page = game.page;
     13     try {
     14       // Leave the first tab in a game-controlled cursor state.
     15       await page.mouse.move(500, 300);
     16       await page.keyboard.down('Shift');
     17       await page.mouse.down({button: 'right'});
     18       await game.wait('game hides the cursor', state => !state.cursor.visible);
     19 
     20       const replacement = await fixture.game(context);
     21       await page.locator('#reconnect').waitFor({state: 'visible'});
     22       await page.bringToFront();
     23       await page.mouse.up({button: 'right'});
     24       await page.keyboard.up('Shift');
     25       assert.equal(await page.locator('#loading').textContent(), 'This character connected elsewhere.');
     26       assert.equal(await page.locator('canvas').evaluate(canvas => getComputedStyle(canvas).cursor), 'default');
     27 
     28       // A live admin kick should leave the replacement tab usable as well.
     29       const login = await context.request.post(fixture.url + '/admin/login', {
     30         form: {username: 'Operator', password: 'admin', password_confirm: 'admin'}, maxRedirects: 0,
     31       });
     32       assert.equal(login.status(), 303);
     33       const admin = await context.newPage();
     34       const player = await fixture.state(context);
     35       await admin.goto(fixture.url + '/admin/players/' + player.id);
     36       await admin.getByRole('button', {name: 'Kick player'}).click();
     37       await replacement.page.locator('#reconnect').waitFor({state: 'visible'});
     38       assert.equal(await replacement.page.locator('#loading').textContent(), 'An administrator ended this session.');
     39       assert.equal(await replacement.page.locator('canvas').evaluate(canvas => getComputedStyle(canvas).cursor), 'default');
     40     } finally {
     41       await context.close();
     42     }
     43   });
     44 });
     45 
     46 test('Shift right-drag releases camera control in either release order', {timeout: 120_000}, async () => {
     47   await withFixture('cursor-shift', async fixture => {
     48     const context = await fixture.visitor();
     49     await fixture.setup(context, 'position', {playfield: 705, position: [960, 16.5, 510], rotation: [0, 0, 0, 1]});
     50     const game = await fixture.game(context);
     51     const page = game.page;
     52     if (!game.state.camera.firstPerson) await game.key('F8');
     53 
     54     for (const shiftFirst of [true, false]) {
     55       await page.mouse.move(500, 300);
     56       await page.keyboard.down('Shift');
     57       await page.mouse.down({button: 'right'});
     58       await game.wait('camera control active', state => !state.cursor.visible);
     59       await page.mouse.move(560, 350, {steps: 8});
     60       await game.snapshot();
     61       if (shiftFirst) await page.keyboard.up('Shift');
     62       await page.mouse.up({button: 'right'});
     63       if (!shiftFirst) await page.keyboard.up('Shift');
     64 
     65       await game.wait('pointer restored after Shift right-drag', state => state.cursor.visible);
     66       const rotation = game.local().rotation;
     67       const angles = game.state.camera.angles;
     68       // Movement packets quantize quaternion components to 1/16384.
     69       await game.waitFor('server facing after camera release', async () =>
     70         (await fixture.state(context)).rotation.every((value, index) => Math.abs(value - rotation[index]) < 0.0001));
     71       const serverRotation = (await fixture.state(context)).rotation;
     72       await page.mouse.move(400, 250, {steps: 8});
     73       await game.snapshot();
     74       assert.deepEqual(game.local().rotation, rotation);
     75       assert.deepEqual(game.state.camera.angles, angles);
     76       assert.deepEqual((await fixture.state(context)).rotation, serverRotation);
     77       assert.equal(game.state.cursor.visible, true);
     78       assert.notEqual(await page.locator('canvas').evaluate(canvas => getComputedStyle(canvas).cursor), 'none');
     79     }
     80     assert.deepEqual(game.errors, []);
     81   });
     82 });
     83 
     84 test('browser cursor preserves native shapes, camera controls and item dragging', {timeout: 180_000}, async () => {
     85   await withFixture('cursor', async fixture => {
     86     const context = await fixture.browser.newContext({viewport: {width: 1024, height: 768}, deviceScaleFactor: 2});
     87     const response = await context.request.post(fixture.url + '/browser-launch');
     88     assert.equal(response.status(), 200);
     89     assert.equal((await context.request.post(fixture.url + '/_test/visitor')).status(), 204);
     90     await fixture.setup(context, 'position', {playfield: 705, position: [960, 16.5, 510], rotation: [0, 0, 0, 1]});
     91     const items = (await fixture.state(context)).items;
     92     const target = await fixture.setup(context, 'leet', {position: [960, 16.5, 498]});
     93     const game = await fixture.game(context);
     94     const page = game.page;
     95     const style = () => page.locator('canvas').evaluate(canvas => getComputedStyle(canvas).cursor);
     96     const records = [];
     97     const inspect = async name => {
     98       await game.snapshot();
     99       const css = await style();
    100       records.push({name, cursor: game.state.cursor, css, camera: game.state.camera});
    101       await fs.writeFile(fixture.output + '/cursor.json', JSON.stringify(records, null, 2));
    102       if (!game.state.cursor.visible) {
    103         assert.equal(css, 'none');
    104         return;
    105       }
    106       assert.match(css, /^url\("data:image\/png;base64,/);
    107       await fs.writeFile(fixture.output + '/' + name + '.png', Buffer.from(css.match(/base64,([^\"]+)/)[1], 'base64'));
    108       const bounds = await page.locator('canvas').boundingBox();
    109       const [hotX, hotY] = game.state.cursor.hotspot;
    110       const hotspot = css.match(/\)(?: (\d+) (\d+))?, auto$/);
    111       assert(hotspot);
    112       assert.deepEqual([Number(hotspot[1] || 0), Number(hotspot[2] || 0)],
    113         [Math.round(hotX * bounds.width / game.state.screen[0]), Math.round(hotY * bounds.height / game.state.screen[1])]);
    114     };
    115 
    116     await page.mouse.move(500, 300);
    117     await inspect('world');
    118     const restingCursor = await style();
    119     await page.evaluate(() => {
    120       window.cursorExits = 0;
    121       document.querySelector('canvas').addEventListener('mouseleave', () => ++window.cursorExits);
    122     });
    123     await page.mouse.move(-20, 300);
    124     await game.snapshot();
    125     assert.equal(await page.evaluate(() => window.cursorExits), 1);
    126     await page.mouse.move(500, 300);
    127     await game.snapshot();
    128     assert.equal(game.state.cursor.shape, 0);
    129     assert.equal(await style(), restingCursor, 'Re-entry must restore the game arrow without a shape change');
    130     await inspect('reentered');
    131     await game.key('i');
    132     const source = game.state.grids.flatMap(grid => grid.cells).find(cell =>
    133       cell.identity[0] === 104 && cell.identity[1] === 48);
    134     assert(source && !source.dummy);
    135     await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2);
    136     await game.wait('native item pickup', state => state.dragged[0] !== 0);
    137     await page.mouse.move(450, 300);
    138     await inspect('dragged');
    139     await game.save(fixture.output + '/dragged');
    140 
    141     // Throttle only the game worker; browser pointer delivery keeps running.
    142     const running = await Promise.all(page.workers().map(async candidate => {
    143       const active = await Promise.race([
    144         candidate.evaluate(() => typeof AOTest !== 'undefined' && AOTest.frame > 0).catch(() => false),
    145         new Promise(resolve => setTimeout(() => resolve(false), 2000)),
    146       ]);
    147       return active ? candidate : null;
    148     }));
    149     const worker = running.find(candidate => candidate);
    150     assert(worker, 'The running game worker must be observable');
    151     await worker.evaluate(() => {
    152       self.cursorTestRAF = requestAnimationFrame;
    153       self.requestAnimationFrame = callback => setTimeout(() => callback(performance.now()), 1000);
    154     });
    155     try {
    156       await game.snapshot();
    157       const frame = await worker.evaluate(() => AOTest.frame);
    158       const css = await style();
    159       await page.evaluate(() => {
    160         window.cursorTestMoves = [];
    161         window.cursorTestListener = event => window.cursorTestMoves.push([event.clientX, event.clientY]);
    162         document.querySelector('canvas').addEventListener('mousemove', window.cursorTestListener);
    163       });
    164       await page.mouse.move(600, 300, {steps: 8});
    165       assert.equal(await worker.evaluate(() => AOTest.frame), frame, 'Pointer input must arrive between game frames');
    166       assert.equal(await page.evaluate(() => window.cursorTestMoves.length), 8);
    167       assert.equal(await style(), css, 'The browser retains its native cursor between game frames');
    168       await page.evaluate(() => document.querySelector('canvas').removeEventListener('mousemove', window.cursorTestListener));
    169     } finally {
    170       await worker.evaluate(() => { self.requestAnimationFrame = self.cursorTestRAF; });
    171     }
    172 
    173     const destination = game.state.grids[0].cells.find(cell => cell.index === 8);
    174     assert(destination);
    175     await game.click((destination.bounds[0] + destination.bounds[2]) / 2, (destination.bounds[1] + destination.bounds[3]) / 2);
    176     await game.wait('native item drop', state => state.dragged[0] === 0 && state.grids[0].cells.some(cell =>
    177       cell.index === 8 && cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy));
    178     assert.deepEqual((await fixture.state(context)).items, items);
    179     await game.key('i');
    180 
    181     // The visible target cursor and click must agree on the same native pixel.
    182     if (!game.state.camera.firstPerson) await game.key('F8');
    183     await game.hold('KeyD', 'facing the target', state => Math.abs(game.local(state).rotation[3]) < 0.05);
    184     const [x, y] = await game.pick(50000, target.id);
    185     await game.wait('context-sensitive target cursor', state => state.cursor.shape !== 0);
    186     await inspect('target');
    187     await game.click(x, y);
    188     await game.wait('aligned target selection', state => state.selected[0] === 50000 && state.selected[1] === target.id);
    189 
    190     await page.mouse.move(500, 300);
    191     await game.snapshot();
    192     const projected = state => state.actors.find(actor => actor.type === 50000 && actor.id === target.id).screenPosition;
    193     const before = projected(game.state);
    194     let sequence = game.sequence;
    195     await page.mouse.down({button: 'right'});
    196     try {
    197       await game.waitInput(sequence, 1025);
    198       await game.wait('camera control active', state => !state.cursor.visible);
    199       await page.mouse.move(560, 450, {steps: 12});
    200       await game.wait('camera rotation', state =>
    201         projected(state)?.some((value, index) => index < 2 && Math.abs(value - before[index]) > 5));
    202       assert.equal(game.state.cursor.visible, false);
    203       await inspect('camera-held');
    204     } finally {
    205       sequence = game.sequence;
    206       await page.mouse.up({button: 'right'});
    207       await game.waitInput(sequence, 1026);
    208     }
    209     await game.wait('pointer restored after camera control', state => state.cursor.visible);
    210     await inspect('camera-released');
    211     await page.setViewportSize({width: 800, height: 600});
    212     await game.wait('resized render surface', state => state.screen[0] === 800 && state.screen[1] === 600);
    213     await inspect('resized');
    214     await page.keyboard.press('Control+Alt+m');
    215     await page.locator('#pixel-mode').selectOption('retina');
    216     await page.locator('#player-menu').getByRole('button', {name: 'Close', exact: true}).click();
    217     await game.wait('retina render surface', state => state.screen[0] === 1600 && state.screen[1] === 1200);
    218     await inspect('retina');
    219     assert.deepEqual(game.errors, []);
    220   });
    221 });
    222 
    223 test('mobile inventory taps open native actions and holds move items', {timeout: 120_000}, async () => {
    224   await withFixture('cursor-touch', async fixture => {
    225     const context = await fixture.browser.newContext({viewport: {width: 1024, height: 768},
    226       userAgent: 'Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/130.0.0.0 Mobile Safari/537.36',
    227       hasTouch: true, isMobile: true});
    228     const response = await context.request.post(fixture.url + '/browser-launch');
    229     assert.equal(response.status(), 200);
    230     assert.equal((await context.request.post(fixture.url + '/_test/visitor')).status(), 204);
    231     const items = (await fixture.state(context)).items;
    232     const game = await fixture.game(context);
    233     await game.key('i');
    234     await game.key('F1');
    235     const point = async index => {
    236       const cell = game.state.grids.flatMap(grid => grid.cells).find(cell =>
    237         cell.index === index);
    238       assert(cell);
    239       return game.point((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2);
    240     };
    241     const tap = async index => {
    242       const {x, y} = await point(index);
    243       await game.page.touchscreen.tap(x, y);
    244     };
    245     const input = await context.newCDPSession(game.page);
    246 
    247     await tap(0);
    248     await game.wait('native item menu after a short tap', state => state.itemMenu);
    249     assert.deepEqual(game.state.itemMenu.identity, [104, 48]);
    250     assert.deepEqual(game.state.dragged, [0, 0]);
    251     await game.save(fixture.output + '/item-menu');
    252     await game.page.touchscreen.tap(450, 300);
    253     await game.wait('outside tap dismisses menu', state => !state.itemMenu);
    254     assert.deepEqual((await fixture.state(context)).items, items);
    255 
    256     // Opening settings during the native hold delay must cancel without using the item.
    257     await tap(0);
    258     await game.page.locator('#menu-button').click();
    259     assert.equal(await game.page.locator('#desktop-controls').isVisible(), false);
    260     assert.match(await game.page.locator('#mobile-options').innerText(), /double-tap to use\/equip/);
    261     await game.page.locator('#player-menu').getByRole('button', {name: 'Close', exact: true}).click();
    262 
    263     await input.send('Input.dispatchTouchEvent', {type: 'touchStart', touchPoints: [await point(0)]});
    264     try {
    265       await game.wait('long hold picks up item', state => state.dragged[0] === 104 && state.dragged[1] === 48);
    266     } finally {
    267       await input.send('Input.dispatchTouchEvent', {type: 'touchEnd', touchPoints: []});
    268     }
    269     await tap(1);
    270     await game.wait('occupied destination displaces its item', state => state.dragged[0] === 104 &&
    271       state.dragged[1] === 49 && state.grids[0].cells.some(cell =>
    272         cell.index === 1 && cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy));
    273     await tap(8);
    274     await game.wait('touch drop', state => state.dragged[0] === 0 && state.grids[0].cells.some(cell =>
    275       cell.index === 8 && cell.identity[0] === 104 && cell.identity[1] === 49 && !cell.dummy));
    276 
    277     await input.send('Input.dispatchTouchEvent', {type: 'touchStart', touchPoints: [await point(8)]});
    278     try {
    279       await game.wait('hold before dragging', state => state.dragged[0] === 104 && state.dragged[1] === 49);
    280       await input.send('Input.dispatchTouchEvent', {type: 'touchMove', touchPoints: [await point(0)]});
    281     } finally {
    282       await input.send('Input.dispatchTouchEvent', {type: 'touchEnd', touchPoints: []});
    283     }
    284     await game.wait('hold then drag places the item on release', state => state.dragged[0] === 0 &&
    285       state.grids[0].cells.some(cell => cell.index === 0 && cell.identity[1] === 49 && !cell.dummy));
    286     assert.deepEqual((await fixture.state(context)).items, items);
    287 
    288     await tap(0);
    289     await game.wait('first aid opens its native menu', state => state.itemMenu);
    290     const use = game.state.itemMenu.actions.find(action => action.command === 5);
    291     assert(use, 'First aid offers the native Use action');
    292     const target = await game.point((use.bounds[0] + use.bounds[2]) / 2, (use.bounds[1] + use.bounds[3]) / 2);
    293     await game.page.touchscreen.tap(target.x, target.y);
    294     await game.wait('menu use consumes one first aid charge', state => !state.itemMenu &&
    295       game.local(state).inventory.some(item => item.id === items[1].id && item.count === 2));
    296 
    297     assert.equal(await game.page.locator('canvas').evaluate(canvas => getComputedStyle(canvas).cursor), 'none');
    298     assert.deepEqual((await fixture.state(context)).items, items.map((item, index) => index === 1 ? {...item, count: 2} : item));
    299 
    300     // The weapon's native menu has no Use action; a double tap must perform its default right click.
    301     await tap(3);
    302     await tap(3);
    303     await game.wait('double tap equips the starter weapon', state => !state.itemMenu &&
    304       game.local(state).inventory.some(item => item.id === items[3].id && item.slot === 6));
    305     assert.deepEqual((await fixture.state(context)).items, items.map((item, index) =>
    306       index === 1 ? {...item, count: 2} : index === 3 ? {...item, slot: 6} : item));
    307     assert.deepEqual(game.errors, []);
    308   });
    309 });