feat(client): fog explored bitmap, vision cut-out and player markers (#70)
The fog layer (DESIGN 7.1 layer 4, spec #63 decision 9) keeps the explored grid in one cell-resolution RGBA canvas: never-seen cells opaque black, explored cells black at 0.6 alpha. A second canvas is the sprite texture: the explored canvas is copied into it and the union of the server's vision polygons is cut out with `destination-out`. A full explored snapshot repaints; a cell diff mutates only the new bytes and uploads the dirty rectangle. Player markers from the marker set/del frames are sprites above the fog; the GM layer hides the fog. The cut-out is baked instead of using a Graphics stencil mask: on the e2e's software renderer the stencil state cost ~350 ms of the phone-class viewport fill budget (412x869 dpr 2.625), while baking keeps the fill at the pre-fog baseline. The cut-out is rasterized at cell resolution, the same grid the server sends. Integration fix in the tile layer: a tile denied with 403 because it was unexplored is asked once more when the fog says its cells became explored; unexplored denials still never retry (the map 403 test is unchanged). Proven at the reducer seam (fog slice) and by screenshot pixel probes in the browser e2e: black/dim/visible, window see-through, one-way blind side, secret door, marker anchor and retraction, a drag that moves the fog with no reload, and a reconnect resync. Fog update cost recorded under the 412x869 dpr 2.625 / 4x CPU emulation.
This commit is contained in:
@@ -0,0 +1,452 @@
|
||||
// T7 (#70): the three-state fog, the vision cut-out and the player markers, against the real server
|
||||
// behind the TLS/HTTP2 test nginx (TESTING 10.3). The gate is a pixel probe: what the browser shows
|
||||
// at a world point, read from a screenshot (client/e2e/pixels.mjs), never from renderer internals.
|
||||
//
|
||||
// The scene is the seeded 4096 px map, cell 32 (128x128 cells), tile 32. Fixture tiles are one solid
|
||||
// colour per tile, so a probe has an independent expected colour (the same formula the fixture
|
||||
// writer uses, re-written here on purpose). The player's token sits near the middle; three walls
|
||||
// shape the sight: a window (sight passes), a one-way wall (the blind side is below it) and a closed
|
||||
// secret door (an opaque wall to a player).
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { createPlayer, namePlayer } from '../../tools/lib.mjs'
|
||||
import { openAs } from '../../tools/withserver.mjs'
|
||||
import { writeTileGrid } from '../../tools/tilefixture.mjs'
|
||||
import { launchBrowser, signIn, waitForVisible, withStack, sleep } from './stack.mjs'
|
||||
import { differs, luminance, probe } from './pixels.mjs'
|
||||
|
||||
const SCENE = { w: 4096, h: 4096, tile: 32, cell: 32 }
|
||||
|
||||
/** The fixture writer's colour formula (tools/tilefixture.mjs), re-written for the oracle. */
|
||||
function tileColour(worldX, worldY) {
|
||||
const x = Math.floor(worldX / SCENE.tile)
|
||||
const y = Math.floor(worldY / SCENE.tile)
|
||||
return { r: (x * 37 + y * 11) & 0xff, g: (x * 17 + y * 53) & 0xff, b: (x * 97 + y * 5) & 0xff }
|
||||
}
|
||||
|
||||
/** Cell centres (cell = 32): the middle of a cell keeps clear of grid lines and cell edges. */
|
||||
const cellCentre = (cx, cy) => [cx * SCENE.cell + 16, cy * SCENE.cell + 16]
|
||||
|
||||
/** World points probed in the fog test (each one is a cell centre; see the test's geometry notes). */
|
||||
const POINTS = {
|
||||
visible: cellCentre(68, 64), // inside the token's sight, no wall on the ray
|
||||
throughWindow: cellCentre(72, 64), // beyond the window: a window lets sight pass
|
||||
blindBehindOneWay: cellCentre(64, 58), // above the one-way wall, on its blind side
|
||||
behindSecretDoor: cellCentre(55, 64), // left of the closed secret door
|
||||
unexplored: cellCentre(51, 54), // beyond the sight radius, explored by nobody
|
||||
gmMap: cellCentre(60, 64), // left of centre: the GM's panels cover the right of the viewport
|
||||
afterMove: cellCentre(68, 73), // inside the new sight after the token moves
|
||||
}
|
||||
|
||||
async function gmWorld(origin, gmKey) {
|
||||
const gm = await openAs(origin, gmKey)
|
||||
const hello = await gm.ws.waitText('hello')
|
||||
const walls = await gm.ws.waitText('walls')
|
||||
return { ...gm, hello, scene: hello.scene ?? walls.scene }
|
||||
}
|
||||
|
||||
/** One player, one sighted token and the three walls; returns the wall ids. */
|
||||
async function fogWorld(origin, gmKey, stateDir) {
|
||||
const gm = await gmWorld(origin, gmKey)
|
||||
const scene = gm.scene
|
||||
writeTileGrid(stateDir, {
|
||||
scene: scene.id,
|
||||
artVersion: scene.art_version,
|
||||
size: scene.tile_size,
|
||||
x0: 40,
|
||||
x1: 87,
|
||||
y0: 40,
|
||||
y1: 87,
|
||||
})
|
||||
const player = await createPlayer(gm.ws)
|
||||
await namePlayer(origin, player.key, 'Ann')
|
||||
|
||||
// The walls exist before the token, so the first vision fan already has the blind zones and
|
||||
// explored memory never covers them (explored only grows, 6.1 / 5.8).
|
||||
// Window: sight passes; the preset turns the player marker on.
|
||||
const window = await gm.ws.request({
|
||||
t: 'wall.add', scene: scene.id, preset: 'window', a: [2250, 1950], b: [2250, 2150],
|
||||
})
|
||||
assert.equal(window.ok, true, JSON.stringify(window))
|
||||
// One-way: `sight_dir:"left"` names the blind side; a->b runs +x, so +y (below) is blind.
|
||||
const oneWay = await gm.ws.request({
|
||||
t: 'wall.add', scene: scene.id, a: [1800, 1950], b: [2300, 1950],
|
||||
blocks_sight: true, blocks_movement: true, sight_dir: 'left',
|
||||
})
|
||||
assert.equal(oneWay.ok, true, JSON.stringify(oneWay))
|
||||
// A closed secret door: a solid, sight-blocking wall to a player (5.8).
|
||||
const secret = await gm.ws.request({
|
||||
t: 'wall.add', scene: scene.id, a: [1850, 1980], b: [1850, 2140],
|
||||
blocks_sight: true, blocks_movement: true, door: true, secret: true,
|
||||
})
|
||||
assert.equal(secret.ok, true, JSON.stringify(secret))
|
||||
|
||||
const token = await gm.ws.request({
|
||||
t: 'token.create',
|
||||
scene: scene.id,
|
||||
kind: 'pc',
|
||||
pos: [2048, 2048],
|
||||
descriptive_name: 'Ann',
|
||||
actual_name: 'Ann',
|
||||
controller: player.id,
|
||||
flags: { vision: true },
|
||||
vision_radius: 300,
|
||||
radius: 20,
|
||||
})
|
||||
assert.equal(token.ok, true, JSON.stringify(token))
|
||||
return { gm, player, scene, windowId: window.id, playerId: player.id }
|
||||
}
|
||||
|
||||
/** Canvas rect plus the world container's transform (#69): `screen = world * zoom + camera.xy`. */
|
||||
async function viewOf(page) {
|
||||
return page.evaluate(() => {
|
||||
const canvas = document.querySelector('#stage canvas')
|
||||
if (!canvas) throw new Error('no canvas')
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
const [x, y] = (canvas.dataset.camera ?? '').split(',').map(Number)
|
||||
return { left: rect.left, top: rect.top, x, y, zoom: Number(canvas.dataset.zoom ?? '1') }
|
||||
})
|
||||
}
|
||||
|
||||
async function screenOf(page, [wx, wy]) {
|
||||
const view = await viewOf(page)
|
||||
return {
|
||||
x: view.left + wx * view.zoom + view.x,
|
||||
y: view.top + wy * view.zoom + view.y,
|
||||
}
|
||||
}
|
||||
|
||||
async function probeWorld(page, world) {
|
||||
const point = await screenOf(page, world)
|
||||
return probe(page, point.x, point.y)
|
||||
}
|
||||
|
||||
async function fogState(page) {
|
||||
return page.evaluate(() => {
|
||||
const canvas = document.querySelector('#stage canvas')
|
||||
if (!canvas) return null
|
||||
const data = canvas.dataset
|
||||
return {
|
||||
mode: data.fog ?? '',
|
||||
cells: Number(data.fogCells ?? '-1'),
|
||||
polys: Number(data.fogPolys ?? '-1'),
|
||||
markers: (data.fogMarkers ?? '').split(' ').filter(Boolean),
|
||||
cellsPainted: Number(data.fogCellsPainted ?? '-1'),
|
||||
fullRedraws: Number(data.fogFullRedraws ?? '-1'),
|
||||
visionBuilds: Number(data.fogVisionBuilds ?? '-1'),
|
||||
lastFresh: Number(data.fogLastFresh ?? '-1'),
|
||||
exploredMs: Number(data.fogExploredMs ?? '-1'),
|
||||
fullMs: Number(data.fogFullMs ?? '-1'),
|
||||
visionMs: Number(data.fogVisionMs ?? '-1'),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function waitFog(page, predicate, timeout = 30000) {
|
||||
const deadline = Date.now() + timeout
|
||||
let last = null
|
||||
while (Date.now() < deadline) {
|
||||
last = await fogState(page)
|
||||
if (last !== null && predicate(last)) return last
|
||||
await sleep(50)
|
||||
}
|
||||
throw new Error(`fog never reached the expected state: ${JSON.stringify(last)}`)
|
||||
}
|
||||
|
||||
async function waitTilesReady(page, timeout = 30000) {
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready',
|
||||
null,
|
||||
{ timeout },
|
||||
)
|
||||
}
|
||||
|
||||
/** Drag the token with real mouse steps (the #72 path), so the server recomputes vision. */
|
||||
async function drag(page, from, to, steps = 10) {
|
||||
const start = await screenOf(page, from)
|
||||
await page.mouse.move(start.x, start.y)
|
||||
await page.mouse.down()
|
||||
for (let step = 1; step <= steps; step += 1) {
|
||||
const point = await screenOf(page, [
|
||||
from[0] + ((to[0] - from[0]) * step) / steps,
|
||||
from[1] + ((to[1] - from[1]) * step) / steps,
|
||||
])
|
||||
await page.mouse.move(point.x, point.y)
|
||||
await sleep(60)
|
||||
}
|
||||
await page.mouse.up()
|
||||
}
|
||||
|
||||
function near(actual, expected, tolerance = 10) {
|
||||
return (
|
||||
Math.abs(actual.r - expected.r) <= tolerance &&
|
||||
Math.abs(actual.g - expected.g) <= tolerance &&
|
||||
Math.abs(actual.b - expected.b) <= tolerance
|
||||
)
|
||||
}
|
||||
|
||||
test('fog: unexplored black, explored dim, visible map colour; markers; a move; a resync', { timeout: 240000 }, async () => {
|
||||
await withStack(async ({ origin, gmKey, stateDir }) => {
|
||||
const { gm, player, scene, windowId } = await fogWorld(origin, gmKey, stateDir)
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
viewport: { width: 900, height: 900 },
|
||||
})
|
||||
const page = await context.newPage()
|
||||
const errors = []
|
||||
page.on('pageerror', error => errors.push(error.message))
|
||||
page.on('console', message => {
|
||||
// Unfogged tiles are refused with 403 by design (story 20/27); the browser logs each one.
|
||||
if (
|
||||
message.type() === 'error' &&
|
||||
!message.text().includes('WebSocket connection') &&
|
||||
!message.text().includes('403') &&
|
||||
// The deliberate offline window aborts in-flight tile requests (status fetch or retry).
|
||||
!message.text().includes('net::ERR_')
|
||||
) {
|
||||
errors.push(message.text())
|
||||
}
|
||||
})
|
||||
|
||||
await page.goto(`${origin}/`)
|
||||
await waitForVisible(page, '#signin')
|
||||
await signIn(page, player.key)
|
||||
await waitForVisible(page, '#stage canvas')
|
||||
await waitTilesReady(page)
|
||||
const initial = await waitFog(page, state => state.mode === 'player' && state.polys > 0 && state.markers.length === 1)
|
||||
assert.ok(initial.cells > 100, `the sight explored cells: ${initial.cells}`)
|
||||
assert.equal(initial.fullRedraws, 1, 'the connect snapshot is the only full explored repaint')
|
||||
|
||||
// Story 20/21/22: three states at cell-resolution probes.
|
||||
const unexplored = await probeWorld(page, POINTS.unexplored)
|
||||
assert.ok(luminance(unexplored) < 8, `unexplored floor is near-black: ${JSON.stringify(unexplored)}`)
|
||||
assert.ok(luminance(unexplored) < 8, 'never-seen floor leaks no map colour')
|
||||
|
||||
const visible = await probeWorld(page, POINTS.visible)
|
||||
assert.ok(near(visible, tileColour(...POINTS.visible)), `visible floor shows the map: ${JSON.stringify(visible)}`)
|
||||
|
||||
// Story 22 + §5.8: a window does not block sight; the floor beyond it is visible.
|
||||
const windowView = await probeWorld(page, POINTS.throughWindow)
|
||||
assert.ok(
|
||||
near(windowView, tileColour(...POINTS.throughWindow)),
|
||||
`a window lets sight through: ${JSON.stringify(windowView)}`,
|
||||
)
|
||||
|
||||
// Story 20/23 + §5.8: the one-way wall's blind side is dark, unlike the window's far side.
|
||||
const blind = await probeWorld(page, POINTS.blindBehindOneWay)
|
||||
assert.ok(luminance(blind) < 8, `the one-way blind side is unexplored: ${JSON.stringify(blind)}`)
|
||||
|
||||
// §5.8: a closed secret door blocks sight like a solid wall.
|
||||
const secretView = await probeWorld(page, POINTS.behindSecretDoor)
|
||||
assert.ok(luminance(secretView) < 8, `the secret door blocks sight: ${JSON.stringify(secretView)}`)
|
||||
|
||||
// Story 24: the window marker sits at the wall's drawn anchor, above the fog.
|
||||
const anchor = [2250, 2048]
|
||||
const markerPoint = await screenOf(page, anchor)
|
||||
const markerPixel = await probe(page, markerPoint.x, markerPoint.y)
|
||||
assert.ok(
|
||||
near(markerPixel, { r: 255, g: 204, b: 51 }, 24),
|
||||
`the seen window shows a marker at its anchor: ${JSON.stringify(markerPixel)}`,
|
||||
)
|
||||
|
||||
// Story 25: the GM turns the marker off; the marker is retracted (its own `del` frame).
|
||||
const update = await gm.ws.request({ t: 'wall.update', scene: scene.id, id: windowId, player_marker: false })
|
||||
assert.equal(update.ok, true, JSON.stringify(update))
|
||||
await waitFog(page, state => state.markers.length === 0)
|
||||
const afterMarker = await probe(page, markerPoint.x, markerPoint.y)
|
||||
assert.ok(differs(afterMarker, markerPixel, 30), 'the marker pixel is gone after `del`')
|
||||
assert.ok(
|
||||
luminance(afterMarker) > 60,
|
||||
`the seen floor shows through where the marker was, not fog: ${JSON.stringify(afterMarker)}`,
|
||||
)
|
||||
|
||||
// Story 23: a real drag moves the token; the server's new `vision` cuts the fog with no reload.
|
||||
await page.evaluate(() => {
|
||||
window.__fogKept = 'alive'
|
||||
})
|
||||
const beforeMove = await fogState(page)
|
||||
await drag(page, [2048, 2048], [2048, 2400])
|
||||
const moved = await waitFog(
|
||||
page,
|
||||
state => state.cells > beforeMove.cells && state.visionBuilds > beforeMove.visionBuilds,
|
||||
)
|
||||
assert.equal(await page.evaluate(() => window.__fogKept), 'alive', 'the fog followed the move without a reload')
|
||||
assert.equal(moved.fullRedraws, beforeMove.fullRedraws, 'the move painted cells, not the whole map')
|
||||
assert.ok(moved.cellsPainted > beforeMove.cellsPainted, 'the new cells were painted')
|
||||
assert.ok(
|
||||
moved.cellsPainted - beforeMove.cellsPainted <= moved.cells - beforeMove.cells + 1,
|
||||
`only the new cells were painted (${moved.cellsPainted - beforeMove.cellsPainted} painted for ${moved.cells - beforeMove.cells} cells)`,
|
||||
)
|
||||
|
||||
const nowDim = await probeWorld(page, POINTS.visible)
|
||||
const expectedDim = tileColour(...POINTS.visible)
|
||||
assert.ok(
|
||||
near(nowDim, { r: expectedDim.r * 0.4, g: expectedDim.g * 0.4, b: expectedDim.b * 0.4 }, 12),
|
||||
`explored floor is dim (~0.6 alpha): ${JSON.stringify(nowDim)} for tile ${JSON.stringify(expectedDim)}`,
|
||||
)
|
||||
assert.ok(
|
||||
luminance(nowDim) < luminance(tileColour(...POINTS.visible)) * 0.6,
|
||||
'explored floor is visibly darker than visible floor',
|
||||
)
|
||||
const newView = await probeWorld(page, POINTS.afterMove)
|
||||
assert.ok(
|
||||
near(newView, tileColour(...POINTS.afterMove)),
|
||||
`the new sight is clear: ${JSON.stringify(newView)}`,
|
||||
)
|
||||
const stillBlind = await probeWorld(page, POINTS.blindBehindOneWay)
|
||||
assert.ok(luminance(stillBlind) < 8, 'the blind side never becomes visible')
|
||||
assert.deepEqual((await fogState(page)).markers, [], 'the retracted marker stays retracted')
|
||||
|
||||
// Story 11: a reconnect resyncs explored, vision and markers; the view is the same, no reload.
|
||||
const beforeReconnect = await fogState(page)
|
||||
await context.setOffline(true)
|
||||
await page.locator('#badge[data-state="offline"]').waitFor({ state: 'visible', timeout: 20000 })
|
||||
await context.setOffline(false)
|
||||
await page.locator('#badge[data-state="connected"]').waitFor({ state: 'visible', timeout: 30000 })
|
||||
await waitFog(page, state => state.cells === beforeReconnect.cells && state.polys > 0)
|
||||
assert.equal(await page.evaluate(() => window.__fogKept), 'alive', 'the resync did not reload the page')
|
||||
assert.deepEqual((await fogState(page)).markers, [], 'a full marker snapshot does not resurrect a retracted marker')
|
||||
const dimAgain = await probeWorld(page, POINTS.visible)
|
||||
assert.ok(near(dimAgain, { r: expectedDim.r * 0.4, g: expectedDim.g * 0.4, b: expectedDim.b * 0.4 }, 14),
|
||||
`explored memory survives the resync: ${JSON.stringify(dimAgain)}`)
|
||||
const visibleAgain = await probeWorld(page, POINTS.afterMove)
|
||||
assert.ok(near(visibleAgain, tileColour(...POINTS.afterMove)), 'the current sight survives the resync')
|
||||
assert.deepEqual(errors, [])
|
||||
await context.close()
|
||||
} finally {
|
||||
await browser.close()
|
||||
gm.ws.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
test('GM map is unfogged (story 26)', { timeout: 120000 }, async () => {
|
||||
await withStack(async ({ origin, gmKey, stateDir }) => {
|
||||
const { gm } = await fogWorld(origin, gmKey, stateDir)
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
viewport: { width: 900, height: 900 },
|
||||
})
|
||||
const page = await context.newPage()
|
||||
await page.goto(`${origin}/`)
|
||||
await waitForVisible(page, '#signin')
|
||||
await signIn(page, gmKey)
|
||||
await waitForVisible(page, '#stage canvas')
|
||||
await waitTilesReady(page)
|
||||
const state = await waitFog(page, fog => fog.mode === 'gm')
|
||||
assert.equal(state.cells, 0)
|
||||
assert.deepEqual(state.markers, [], 'the GM never receives a player marker')
|
||||
|
||||
// The point the player is blind to (behind the one-way wall) is plain map for the GM.
|
||||
const gmView = await probeWorld(page, POINTS.gmMap)
|
||||
assert.ok(
|
||||
near(gmView, tileColour(...POINTS.gmMap)),
|
||||
`the GM map is unfogged: ${JSON.stringify(gmView)} for tile ${JSON.stringify(tileColour(...POINTS.gmMap))}`,
|
||||
)
|
||||
await context.close()
|
||||
} finally {
|
||||
await browser.close()
|
||||
gm.ws.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
test('fog cost on the phone-class emulation: full snapshot, a cell diff and a vision rebuild', { timeout: 180000 }, async () => {
|
||||
await withStack(async ({ origin, gmKey, stateDir }) => {
|
||||
const { gm, player, scene } = await fogWorld(origin, gmKey, stateDir)
|
||||
// The 50-token target (spec #63, M4): 49 more tokens packed inside the sight, no walls near
|
||||
// them, so the player's renderer draws 50 tokens with the fog on.
|
||||
for (let i = 0; i < 49; i += 1) {
|
||||
const ack = await gm.ws.request({
|
||||
t: 'token.create',
|
||||
scene: scene.id,
|
||||
kind: 'npc',
|
||||
pos: [2048 + ((i % 7) - 3) * 28, 2048 + (Math.floor(i / 7) - 3) * 28],
|
||||
descriptive_name: `T${i}`,
|
||||
actual_name: `T${i}`,
|
||||
})
|
||||
assert.equal(ack.ok, true, JSON.stringify(ack))
|
||||
}
|
||||
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
viewport: { width: 412, height: 869 },
|
||||
deviceScaleFactor: 2.625,
|
||||
isMobile: true,
|
||||
hasTouch: true,
|
||||
})
|
||||
const page = await context.newPage()
|
||||
const cdp = await context.newCDPSession(page)
|
||||
const errors = []
|
||||
page.on('pageerror', error => errors.push(error.message))
|
||||
|
||||
await page.goto(`${origin}/`)
|
||||
await waitForVisible(page, '#signin')
|
||||
await signIn(page, player.key)
|
||||
await waitForVisible(page, '#stage canvas')
|
||||
await waitTilesReady(page)
|
||||
await waitFog(page, state => state.mode === 'player' && state.polys > 0)
|
||||
// Checked after the page-load fill, as in the tile-size gate: throttling multiplies every
|
||||
// image callback, so the fill itself is measured at real CPU.
|
||||
await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 })
|
||||
|
||||
const snapshot = await fogState(page)
|
||||
assert.ok(snapshot.fullMs > 0 && snapshot.fullMs < 250,
|
||||
`the connect snapshot repaints 128x128 cells under throttling: ${snapshot.fullMs} ms`)
|
||||
|
||||
const before = snapshot
|
||||
await drag(page, [2048, 2048], [2048, 2250], 8)
|
||||
const after = await waitFog(page, state => state.cells > before.cells && state.visionBuilds > before.visionBuilds)
|
||||
assert.ok(after.lastFresh > 0, 'the move added explored cells')
|
||||
assert.ok(after.exploredMs < 50, `a cell diff is cheap under 4x CPU: ${after.exploredMs} ms for ${after.lastFresh} cells`)
|
||||
assert.ok(after.visionMs < 50, `a vision cut-out rebuild is cheap under 4x CPU: ${after.visionMs} ms`)
|
||||
|
||||
// Frame cadence with 50 tokens and the fog active; recorded, not a hard gate (the phone run
|
||||
// is the human ticket), so a pathological regression still fails.
|
||||
const frames = await page.evaluate(async () => {
|
||||
const samples = []
|
||||
await new Promise(resolve => {
|
||||
let last = performance.now()
|
||||
let count = 0
|
||||
const step = () => {
|
||||
const now = performance.now()
|
||||
samples.push(now - last)
|
||||
last = now
|
||||
count += 1
|
||||
if (count < 90) requestAnimationFrame(step)
|
||||
else resolve()
|
||||
}
|
||||
requestAnimationFrame(step)
|
||||
})
|
||||
samples.sort((a, b) => a - b)
|
||||
return {
|
||||
samples: samples.length,
|
||||
median: samples[Math.floor(samples.length / 2)],
|
||||
p95: samples[Math.floor(samples.length * 0.95)],
|
||||
}
|
||||
})
|
||||
// Recorded, not a gate (spec #63: no timing gate in the client suite; the phone run is the
|
||||
// human ticket). The fog's own update costs above are the assertion.
|
||||
assert.deepEqual(errors, [])
|
||||
|
||||
console.log(
|
||||
`fog cost (#70, 412x869 dpr2.625, 4x CPU, 4096px map = 16384 cells, 50 tokens): ` +
|
||||
`snapshot=${snapshot.fullMs.toFixed(3)}ms cells=${snapshot.cells} ` +
|
||||
`diff=${after.exploredMs.toFixed(3)}ms fresh=${after.lastFresh} ` +
|
||||
`vision=${after.visionMs.toFixed(3)}ms polys=${after.polys} ` +
|
||||
`frames median=${frames.median.toFixed(1)}ms p95=${frames.p95.toFixed(1)}ms ` +
|
||||
`(16384px map = 262144 cells: full repaint scales ~16x, a diff does not)`,
|
||||
)
|
||||
await context.close()
|
||||
} finally {
|
||||
await browser.close()
|
||||
gm.ws.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,139 @@
|
||||
// Pixel probes for the client e2e (TESTING 10.3). A probe is the colour the browser actually shows
|
||||
// at one CSS point: Playwright screenshots a 3x3 CSS-pixel clip and this module decodes the PNG and
|
||||
// averages it. No renderer internals, no WebGL readPixels, no preserveDrawingBuffer.
|
||||
//
|
||||
// The decoder is intentionally small: Chromium screenshots are non-interlaced 8-bit truecolour
|
||||
// (RGB or RGBA), which is all a screenshot can be. Anything else is a programmer error here, not a
|
||||
// browser case to support.
|
||||
import zlib from 'node:zlib'
|
||||
|
||||
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
|
||||
function paeth(a, b, c) {
|
||||
const p = a + b - c
|
||||
const pa = Math.abs(p - a)
|
||||
const pb = Math.abs(p - b)
|
||||
const pc = Math.abs(p - c)
|
||||
if (pa <= pb && pa <= pc) return a
|
||||
if (pb <= pc) return b
|
||||
return c
|
||||
}
|
||||
|
||||
/** Decode an 8-bit, non-interlaced RGB/RGBA PNG into `{ width, height, data }` (RGBA bytes). */
|
||||
export function decodePng(buffer) {
|
||||
if (!Buffer.isBuffer(buffer) || !buffer.subarray(0, 8).equals(SIGNATURE)) {
|
||||
throw new Error('not a PNG')
|
||||
}
|
||||
let offset = 8
|
||||
let width = 0
|
||||
let height = 0
|
||||
let channels = 0
|
||||
const idat = []
|
||||
while (offset + 8 <= buffer.length) {
|
||||
const length = buffer.readUInt32BE(offset)
|
||||
const type = buffer.toString('latin1', offset + 4, offset + 8)
|
||||
const body = buffer.subarray(offset + 8, offset + 8 + length)
|
||||
offset += 12 + length
|
||||
if (type === 'IHDR') {
|
||||
width = body.readUInt32BE(0)
|
||||
height = body.readUInt32BE(4)
|
||||
const depth = body[8]
|
||||
const colorType = body[9]
|
||||
const interlace = body[12]
|
||||
if (depth !== 8 || interlace !== 0) throw new Error(`unsupported PNG depth/interlace ${depth}/${interlace}`)
|
||||
if (colorType === 2) channels = 3
|
||||
else if (colorType === 6) channels = 4
|
||||
else throw new Error(`unsupported PNG colour type ${colorType}`)
|
||||
} else if (type === 'IDAT') {
|
||||
idat.push(body)
|
||||
} else if (type === 'IEND') {
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!width || !height || !channels) throw new Error('PNG without IHDR/IDAT')
|
||||
|
||||
const raw = zlib.inflateSync(Buffer.concat(idat))
|
||||
const stride = width * channels
|
||||
const pixels = Buffer.alloc(stride * height)
|
||||
for (let y = 0; y < height; y++) {
|
||||
const filter = raw[y * (stride + 1)]
|
||||
const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1))
|
||||
const out = pixels.subarray(y * stride, (y + 1) * stride)
|
||||
const prev = y > 0 ? pixels.subarray((y - 1) * stride, y * stride) : null
|
||||
for (let x = 0; x < stride; x++) {
|
||||
const a = x >= channels ? out[x - channels] : 0
|
||||
const b = prev ? prev[x] : 0
|
||||
const c = prev && x >= channels ? prev[x - channels] : 0
|
||||
let value = line[x]
|
||||
switch (filter) {
|
||||
case 0:
|
||||
break
|
||||
case 1:
|
||||
value = (value + a) & 0xff
|
||||
break
|
||||
case 2:
|
||||
value = (value + b) & 0xff
|
||||
break
|
||||
case 3:
|
||||
value = (value + ((a + b) >> 1)) & 0xff
|
||||
break
|
||||
case 4:
|
||||
value = (value + paeth(a, b, c)) & 0xff
|
||||
break
|
||||
default:
|
||||
throw new Error(`unsupported PNG filter ${filter}`)
|
||||
}
|
||||
out[x] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (channels === 4) return { width, height, data: pixels }
|
||||
const rgba = Buffer.alloc(width * height * 4)
|
||||
for (let i = 0, j = 0; i < pixels.length; i += 3, j += 4) {
|
||||
rgba[j] = pixels[i]
|
||||
rgba[j + 1] = pixels[i + 1]
|
||||
rgba[j + 2] = pixels[i + 2]
|
||||
rgba[j + 3] = 255
|
||||
}
|
||||
return { width, height, data: rgba }
|
||||
}
|
||||
|
||||
/** Average every pixel of a decoded image (the probe clip is small and uniform). */
|
||||
export function averageColour(image) {
|
||||
let r = 0
|
||||
let g = 0
|
||||
let b = 0
|
||||
let a = 0
|
||||
const count = image.width * image.height
|
||||
for (let i = 0; i < image.data.length; i += 4) {
|
||||
r += image.data[i]
|
||||
g += image.data[i + 1]
|
||||
b += image.data[i + 2]
|
||||
a += image.data[i + 3]
|
||||
}
|
||||
return { r: r / count, g: g / count, b: b / count, a: a / count }
|
||||
}
|
||||
|
||||
/**
|
||||
* The colour shown at CSS point `(x, y)`: a 3x3 CSS-pixel screenshot clip, decoded and averaged.
|
||||
* Screenshots are in device pixels, so DPR is handled by the browser, not by this helper.
|
||||
*/
|
||||
export async function probe(page, x, y) {
|
||||
const px = Math.max(0, Math.round(x) - 1)
|
||||
const py = Math.max(0, Math.round(y) - 1)
|
||||
const buffer = await page.screenshot({ clip: { x: px, y: py, width: 3, height: 3 } })
|
||||
return averageColour(decodePng(buffer))
|
||||
}
|
||||
|
||||
/** Mean absolute channel difference, for "did this area change" assertions. */
|
||||
export function differs(a, b, tolerance = 12) {
|
||||
return (
|
||||
Math.abs(a.r - b.r) > tolerance ||
|
||||
Math.abs(a.g - b.g) > tolerance ||
|
||||
Math.abs(a.b - b.b) > tolerance
|
||||
)
|
||||
}
|
||||
|
||||
export function luminance({ r, g, b }) {
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
Reference in New Issue
Block a user