fuzzyworld

tower / cascadia / files / tools / screenshots.mjs

Branch cascadia · default branch · all branches

screenshots.mjs

27.1 KB · history · blame

1/**
2 * Screenshot tour. `npm run screenshots`
3 *
4 * Drives the real application in a headless browser and photographs it:
5 * docs/screenshots/<profile>-<shot>.png one file per view, desktop and mobile
6 * docs/screenshots/overview.png all of them on one contact sheet
7 *
8 * Every shot is taken by *using* the map — clicking the view buttons, picking
9 * places out of the list, dragging to orbit and to look up — never by posing a
10 * renderer directly. That is the whole point: a screenshot taken through the UI
11 * fails when the UI fails, so a black canvas, or a sidebar that has eaten the
12 * window, ends up in the picture instead of hiding behind a passing unit test.
13 *
14 * The contact sheet exists to be looked at, once, before committing: one image that
15 * answers "is the application still there?". `--check` puts a number on that (see
16 * `divergence`), but the number is a smoke alarm, not a verdict. Look at the sheet.
17 *
18 * Determinism is deliberate and shallow — a fixed viewport, a seeded Math.random
19 * (nothing in Tower is stochastic since D-049) and the exterior spin switched
20 * off. Anything else that moves between runs is a real change worth seeing.
21 *
22 * Flags:
23 * --check exit non-zero if any shot diverged past the threshold
24 * --threshold <pct> how far a shot may move first (default 3, and calibrated)
25 * --url <origin> photograph a server already running instead of starting one
26 */
27import { mkdir, readFile } from 'node:fs/promises'
28import path from 'node:path'
29import { fileURLToPath } from 'node:url'
30import { createServer } from 'vite'
31import { chromium } from 'playwright'
32
33const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
34const OUT = path.join(ROOT, 'docs', 'screenshots')
35const OVERVIEW = path.join(OUT, 'overview.png')
36
37/**
38 * Above this per-shot mean pixel difference, `--check` stops and asks for human eyes.
39 *
40 * Measured, not guessed, at both ends:
41 *
42 * noise Seven of the ten shots are byte-identical run to run. The two
43 * exterior shots are not: OrbitControls damps toward its target
44 * asymptotically, so the camera lands a hair short of the same place
45 * each time and the labels and markers shift by a pixel. Observed up
46 * to 0.98% on mobile-exterior, where the canvas is narrow enough for
47 * a pixel to count for more.
48 * failure Hiding both 3D canvases scored 7% (desktop-exterior, mostly black
49 * sky already) to 31% (desktop-interior). A shot going entirely black
50 * scores 12% to 39%.
51 *
52 * 3% is three times the worst observed noise and less than half the mildest real
53 * failure. Re-measure both ends before moving it — and note that a view already
54 * broken scores 0% when it breaks further, which is how mobile-exterior behaved
55 * before D-043: this catches regressions, not things that never worked.
56 */
57const DEFAULT_THRESHOLD = 3
58
59/** How many shots to photograph at once. See the pool in main() for why four. */
60const CONCURRENCY = 4
61
62/**
63 * Two shapes, because the second one is currently the interesting one: at 390 px
64 * the fixed 340 px sidebar leaves the world about fifty pixels of window. The
65 * mobile shots are in here to keep that visible until it is fixed.
66 */
67const PROFILES = [
68 { id: 'desktop', label: 'Desktop — 1440×900', viewport: { width: 1440, height: 900 }, scale: 1, mobile: false },
69 { id: 'mobile', label: 'Mobile — 390×844', viewport: { width: 390, height: 844 }, scale: 2, mobile: true },
70]
71
72// --------------------------------------------------------------------- helpers
73
74/** Flush a few animation frames, then hold still, so a settling view has settled. */
75async function settle(page, ms = 900) {
76 await page.evaluate(async () => {
77 for (let i = 0; i < 20; i++) await new Promise((r) => requestAnimationFrame(() => r(null)))
78 })
79 await page.waitForTimeout(ms)
80}
81
82/** The canvas box, for aiming clicks and drags at the world rather than the panel. */
83async function stage(page) {
84 const box = await page.locator('main').boundingBox()
85 if (!box) throw new Error('no <main> to aim at')
86 return { x: box.x, y: box.y, w: box.width, h: box.height }
87}
88
89/** A slow drag, so pointermove handlers read it as a gesture and not as a jump. */
90async function drag(page, [fx, fy], [tx, ty]) {
91 await page.mouse.move(fx, fy)
92 await page.mouse.down()
93 const steps = 24
94 for (let i = 1; i <= steps; i++) {
95 await page.mouse.move(fx + ((tx - fx) * i) / steps, fy + ((ty - fy) * i) / steps)
96 await page.waitForTimeout(8)
97 }
98 await page.mouse.up()
99}
100
101/**
102 * Open one of the three views by clicking its button, as a reader would.
103 *
104 * Waits for the view to exist rather than for a guess at how long it takes. Three
105 * is a deferred import, so both 3D views appear some hundreds of milliseconds
106 * after the click — and a drag begun before the renderer has attached its pointer
107 * handlers is silently half-swallowed. That is not hypothetical: it is how
108 * interior-overhead came out pitched +13° when its drag is sized for +45°, and it
109 * had been doing so quietly for several runs behind a 2.5 s timeout that was
110 * usually but not always long enough.
111 *
112 * Both readouts are rendered only once their view is live, so a non-empty one is
113 * the signal — no app change needed to expose it.
114 */
115async function openView(page, view) {
116 await page.click(`#views button[data-view="${view}"]`)
117 if (view !== 'map') {
118 await page.waitForFunction(
119 (sel) => (document.querySelector(sel)?.textContent ?? '').length > 0,
120 view === 'exterior' ? '#spin' : '#standing',
121 { timeout: 30_000 })
122 }
123 await page.waitForTimeout(view === 'map' ? 400 : 700)
124 await settle(page)
125}
126
127/**
128 * Reach the sidebar, whatever shape it is in.
129 *
130 * On a wide screen it is a column and always there. Below 720 px it is a drawer
131 * that starts closed, so anything in it has to be opened for first — and closed
132 * again afterwards, or every mobile shot would be a picture of the panel.
133 */
134async function withPanel(page, fn) {
135 /**
136 * Ask the same media query the CSS and the app ask, rather than looking at the
137 * buttons. A closed drawer is only translated off-screen, so `isVisible()` on
138 * anything inside it still answers true and then the click times out against
139 * "element is outside of the viewport".
140 */
141 const drawer = await page.evaluate(() => matchMedia('(max-width: 720px)').matches)
142 const isOpen = () =>
143 page.evaluate(() => document.getElementById('app').classList.contains('panel-open'))
144
145 if (drawer && !(await isOpen())) {
146 await page.click('#panel-toggle')
147 await page.waitForTimeout(300)
148 }
149 await fn()
150 // The app closes the drawer itself when a place is picked, so this is only for
151 // the cases where it did not — flipping a checkbox, say.
152 if (drawer && (await isOpen())) {
153 await page.click('#panel-close')
154 await page.waitForTimeout(300)
155 }
156 await settle(page)
157}
158
159/** Click a place in the World list. In every view this is also how you travel. */
160async function pick(page, name) {
161 await withPanel(page, () => page.locator('#list li', { hasText: name }).first().click())
162}
163
164// ----------------------------------------------------------------------- shots
165
166/**
167 * The tour. `on` names the profiles a shot is taken in — the sightline probe and
168 * the overhead look are desktop-only because they are gestures, and the reader
169 * card is desktop-only because it is the same layout with fewer controls.
170 */
171const SHOTS = [
172 {
173 id: 'map',
174 caption: 'Map — the unrolled inner surface, with a place selected',
175 on: ['desktop', 'mobile'],
176 run: async (page) => {
177 await openView(page, 'map')
178 await pick(page, 'The Capital')
179 },
180 },
181 {
182 id: 'map-sightline',
183 caption: 'Map — shift-click two points to measure a sightline through the air',
184 on: ['desktop'],
185 run: async (page) => {
186 await openView(page, 'map')
187 const s = await stage(page)
188 // Two points well apart in z, so the readout has a long line of sight and a
189 // transmission worth reading. Shift is held down across both clicks, because
190 // the probe is a two-click gesture and the map reads the modifier on each.
191 await page.keyboard.down('Shift')
192 await page.mouse.click(s.x + s.w * 0.22, s.y + s.h * 0.45)
193 await page.mouse.click(s.x + s.w * 0.68, s.y + s.h * 0.58)
194 await page.keyboard.up('Shift')
195 await settle(page)
196 },
197 },
198 {
199 id: 'exterior',
200 caption: 'Exterior, x-ray hull — the inner surface projected out, with the caps and the collector',
201 on: ['desktop', 'mobile'],
202 run: async (page) => {
203 await openView(page, 'exterior')
204 // Spin off: a turning Tower photographs differently every run, and the value
205 // of these images is that a difference means something.
206 await withPanel(page, () => page.uncheck('#f-spin'))
207 await withPanel(page, () => page.selectOption('#f-ext-view', 'xray'))
208 const s = await stage(page)
209 await drag(page, [s.x + s.w * 0.5, s.y + s.h * 0.5], [s.x + s.w * 0.5 - 150, s.y + s.h * 0.5 + 70])
210 // The default view sits about 1,200 km out, where Tower is a sliver. Close in
211 // until the caps and the collector are worth looking at.
212 for (let i = 0; i < 6; i++) {
213 await page.mouse.wheel(0, -400)
214 await page.waitForTimeout(120)
215 }
216 // OrbitControls damps at 0.08 per frame, so the camera coasts after a drag.
217 // Wait it out: a shot taken mid-coast is a different image every run.
218 await settle(page, 3000)
219 },
220 },
221 {
222 id: 'exterior-true',
223 caption: 'Exterior, true hull — bare skin, and the land visible in through the far cap window',
224 on: ['desktop'],
225 run: async (page) => {
226 await openView(page, 'exterior')
227 await withPanel(page, () => page.uncheck('#f-spin'))
228 await withPanel(page, () => page.selectOption('#f-ext-view', 'true'))
229 // Swing round to the far cap: the window is the whole point of this mode and
230 // it is at one specific end of a 540 km object.
231 await pick(page, 'The Far Cap')
232 const s = await stage(page)
233 await page.mouse.move(s.x + s.w * 0.5, s.y + s.h * 0.5)
234 for (let i = 0; i < 3; i++) {
235 await page.mouse.wheel(0, -400)
236 await page.waitForTimeout(120)
237 }
238 await settle(page, 3000)
239 },
240 },
241 {
242 id: 'interior',
243 caption: 'Interior — standing at The Narrows, the ground curving up on both sides',
244 on: ['desktop', 'mobile'],
245 run: async (page) => {
246 await openView(page, 'interior')
247 await pick(page, 'The Narrows')
248 await settle(page, 1400)
249 },
250 },
251 {
252 id: 'interior-overhead',
253 caption: 'Interior — looking up: the far side 100 km overhead is clearer than ground 100 km away',
254 on: ['desktop'],
255 run: async (page) => {
256 await openView(page, 'interior')
257 await pick(page, 'Greatwood')
258 const s = await stage(page)
259 /**
260 * Dragging down pitches the view up. The interior turns at 0.0032 rad per
261 * pixel at the default 60° field, so 164 px is 30°.
262 *
263 * It was 245 px / 45° until the far cap became a window. At 45° the frame is
264 * almost all haze — which is honest, and a poor picture of the claim in the
265 * caption. 30° keeps the ground's edge curving up on one side and the cap on
266 * the other, which is what the shot is actually for.
267 */
268 await drag(page, [s.x + s.w * 0.5, s.y + s.h * 0.32], [s.x + s.w * 0.5, s.y + s.h * 0.32 + 164])
269 await settle(page, 1600)
270 },
271 },
272 {
273 id: 'panel',
274 caption: 'Mobile — the sidebar as a drawer, opened over the world and one tap from gone',
275 on: ['mobile'],
276 run: async (page) => {
277 await openView(page, 'interior')
278 await pick(page, 'The Narrows')
279 await page.click('#panel-toggle')
280 await page.waitForTimeout(400)
281 await settle(page)
282 },
283 },
284 {
285 id: 'interior-night',
286 caption: 'Interior — the far cap window at night: stars, and the beam banked to a thousandth',
287 on: ['desktop'],
288 run: async (page) => {
289 await openView(page, 'interior')
290 // The Capital is 270 km from the far cap, which is far enough to see the
291 // whole 100 km window and near enough that some of the sky survives the air.
292 await pick(page, 'The Capital')
293 await withPanel(page, () => page.selectOption('#f-light', 'night'))
294 await settle(page, 1600)
295 },
296 },
297 {
298 id: 'interior-suncap',
299 caption: 'Interior — the sun cap window: the collector\'s black disc, and stars round the edge of it',
300 on: ['desktop'],
301 run: async (page) => {
302 await openView(page, 'interior')
303 await pick(page, 'The Capital')
304 await withPanel(page, () => page.selectOption('#f-light', 'night'))
305 // Turn to face sunward. 246 px is 45° at the default field, and the drag has
306 // to stay inside the viewport, so it goes round in four passes rather than
307 // one 982 px sweep that would run off the edge and drop the pointer capture.
308 const s = await stage(page)
309 for (let i = 0; i < 4; i++) {
310 await drag(page, [s.x + s.w * 0.8, s.y + s.h * 0.5], [s.x + s.w * 0.8 - 246, s.y + s.h * 0.5])
311 await page.waitForTimeout(150)
312 }
313 await settle(page, 1600)
314 },
315 },
316 {
317 id: 'interior-dawn',
318 caption: 'Interior — dawn: a lit sky over dark ground, and the light still 27 km away',
319 on: ['desktop'],
320 run: async (page) => {
321 await openView(page, 'interior')
322 await pick(page, 'The Capital')
323 await withPanel(page, async () => {
324 // 06:17. The dawn front leaves the sun cap at 06:00 and takes 40 minutes to
325 // cross the world, so at The Capital's z 270 km it is 27 km short and still
326 // coming — which is the whole point of the shot.
327 await page.locator('#f-time').fill('378')
328 await page.locator('#f-time').dispatchEvent('input')
329 })
330 const s = await stage(page)
331 for (let i = 0; i < 4; i++) {
332 await drag(page, [s.x + s.w * 0.8, s.y + s.h * 0.5], [s.x + s.w * 0.8 - 246, s.y + s.h * 0.5])
333 await page.waitForTimeout(150)
334 }
335 await settle(page, 1600)
336 },
337 },
338 {
339 id: 'reader',
340 caption: 'Reader mode (?reader=1) — terrain, places, a detail card and the probe, no editing',
341 on: ['desktop'],
342 run: async (page) => {
343 await openView(page, 'map')
344 await pick(page, 'The Spindle')
345 await settle(page)
346 },
347 },
348]
349
350/** Reader mode is a query parameter, so it has to be chosen before the page loads. */
351const searchFor = (shot) => (shot.id === 'reader' ? '?reader=1' : '')
352
353const fileFor = (profile, shot) => path.join(OUT, `${profile}-${shot}.png`)
354
355// ------------------------------------------------------------------- the tour
356
357/**
358 * Launch the browser that will do the drawing.
359 *
360 * `channel: 'chromium'` is the full Chrome for Testing build, which reaches the
361 * real GPU; the default headless shell falls back to SwiftShader and renders the
362 * interior's haze integral on the CPU. That is not a small difference — one
363 * interior shot measured **87.3 s on SwiftShader against 6.4 s on the GPU**, and
364 * the 180° turn inside it went from 77.7 s to 2.6 s, because every mouse move
365 * during a drag waits on a frame.
366 *
367 * The cost is that the baseline is now tied to this machine's GPU rather than to a
368 * software renderer that would give the same pixels anywhere. Nothing runs this in
369 * CI, so that is a fair trade — but it is why `--check` compares against images a
370 * particular machine produced, and why a different one will show a large one-off
371 * divergence rather than a regression.
372 */
373async function launch() {
374 try {
375 return await chromium.launch({ channel: 'chromium' })
376 } catch {
377 console.log(' (no Chrome for Testing build; falling back to the software renderer)')
378 return await chromium.launch()
379 }
380}
381
382async function capture(browser, base, profile, shot) {
383 const t0 = Date.now()
384 /**
385 * A fresh context per shot. The app autosaves the view, the eye height and the
386 * heading to localStorage, so a shared context would let each shot inherit the
387 * previous one's camera and quietly stop being reproducible.
388 */
389 const context = await browser.newContext({
390 viewport: profile.viewport,
391 deviceScaleFactor: profile.scale,
392 isMobile: profile.mobile,
393 hasTouch: profile.mobile,
394 })
395 /**
396 * Insurance rather than a live need: the rain that used to be the world's one
397 * randomised thing is gone (D-049), and the star field is hashed in GLSL rather
398 * than sampled. If anything stochastic comes back, the contact sheet stays
399 * comparable between runs without anyone having to remember why.
400 */
401 await context.addInitScript(() => {
402 let seed = 0x2f6e2b1
403 Math.random = () => {
404 seed = (seed * 1664525 + 1013904223) >>> 0
405 return seed / 0x100000000
406 }
407 })
408 const page = await context.newPage()
409 const problems = []
410 page.on('pageerror', (e) => problems.push(String(e)))
411 page.on('console', (m) => { if (m.type() === 'error') problems.push(m.text()) })
412
413 await page.goto(`${base}/${searchFor(shot)}`, { waitUntil: 'networkidle' })
414 await settle(page)
415 await shot.run(page)
416
417 const file = fileFor(profile.id, shot.id)
418 await page.screenshot({ path: file, scale: 'css' })
419 await context.close()
420
421 const note = problems.length ? ` ⚠ ${problems.length} console error(s): ${problems[0]}` : ''
422 console.log(` ${path.relative(ROOT, file)} ${((Date.now() - t0) / 1000).toFixed(1)}s${note}`)
423}
424
425// -------------------------------------------------------------- contact sheet
426
427const dataUri = async (file) => `data:image/png;base64,${(await readFile(file)).toString('base64')}`
428
429/**
430 * Build the overview: every shot on one page, photographed as one image.
431 *
432 * Deliberately undated. Eight of the ten files this tool writes come out
433 * byte-identical run to run, so regenerating usually costs git nothing at all;
434 * the exterior shot is the exception, carrying a pixel or two of renderer noise
435 * that measures 0.00% and still changes the bytes, and the sheet inherits it.
436 * A date stamp would guarantee a fresh 600 kB blob every day regardless, which
437 * is a bad trade for a fact git already records.
438 *
439 * The browser is already running and already knows how to lay images out, so the
440 * contact sheet is an HTML page rather than a compositing routine and a PNG decoder
441 * this project would otherwise have no use for (tools/png.mjs only encodes).
442 */
443async function buildOverview(browser, cells) {
444 const context = await browser.newContext({ viewport: { width: 1600, height: 1000 } })
445 const page = await context.newPage()
446 // The doctype is load-bearing: without it the sheet lays out in quirks mode, the
447 // frames stop clamping their images, and the page grows tall enough that
448 // Page.captureScreenshot gives up with "Unable to capture screenshot".
449 await page.setContent(`<!doctype html>
450<style>
451 :root { color-scheme: dark; }
452 body { margin: 0; padding: 28px; background: #0b0d12; color: #dde3ee;
453 font: 13px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
454 h1 { font-size: 16px; letter-spacing: 0.08em; text-transform: uppercase; margin: 0 0 4px; }
455 p.sub { color: #8892a6; margin: 0 0 22px; font-size: 12px; }
456 .grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
457 figure { margin: 0; background: #131722; border: 1px solid #232a3a; border-radius: 8px;
458 padding: 10px; display: flex; flex-direction: column; }
459 .frame { height: 300px; display: flex; align-items: center; justify-content: center;
460 background: #05070d; border-radius: 4px; overflow: hidden; }
461 img { max-width: 100%; max-height: 100%; display: block; }
462 figcaption { margin-top: 8px; font-size: 11px; color: #8892a6; }
463 figcaption b { display: block; color: #7fd4ff; font-weight: 500; letter-spacing: 0.04em;
464 text-transform: uppercase; font-size: 10px; margin-bottom: 2px; }
465</style>
466<h1>Tower — screenshot overview</h1>
467<p class="sub">${cells.length} views · one glance before committing</p>
468<div class="grid">
469${cells.map((c) => ` <figure><div class="frame"><img src="${c.src}" /></div>
470 <figcaption><b>${c.label.replace('-', ' · ')}</b>${c.caption}</figcaption></figure>`).join('\n')}
471</div>`)
472 await page.waitForTimeout(400)
473 /**
474 * Size the window to the sheet and take an ordinary screenshot. `fullPage` is the
475 * obvious call and it fails outright here: the page carries every shot inline as
476 * a data URI, and capturing beyond the viewport on that much content returns
477 * "Unable to capture screenshot" from the protocol rather than an image.
478 */
479 const height = await page.evaluate(() => document.documentElement.scrollHeight)
480 await page.setViewportSize({ width: 1600, height })
481 await page.waitForTimeout(200)
482 await page.screenshot({ path: OVERVIEW, scale: 'css' })
483 await context.close()
484 console.log(` ${path.relative(ROOT, OVERVIEW)} ${1600}×${height}`)
485}
486
487/**
488 * Mean absolute difference between two PNGs, as a percentage of full scale.
489 *
490 * A crude metric on purpose. It is not trying to be a visual-diff tool; it is
491 * trying to notice that the interior went black, or that the sidebar swallowed the
492 * window. Returns null when the two are different sizes — the viewport changed, or
493 * a shot is new, which is a change the author already knows about.
494 *
495 * It is measured per shot rather than on the contact sheet, because the sheet
496 * dilutes: nine panels on a dark page, and rewriting two of them outright moved
497 * the whole-sheet mean by 0.6%. Per shot the same change reads in tens of percent,
498 * which is a number a threshold can actually be set against.
499 */
500async function divergence(browser, before, after) {
501 const context = await browser.newContext({ viewport: { width: 400, height: 300 } })
502 const page = await context.newPage()
503 const result = await page.evaluate(async ([a, b]) => {
504 const load = (src) => new Promise((res, rej) => {
505 const img = new Image()
506 img.onload = () => res(img)
507 img.onerror = () => rej(new Error('bad image'))
508 img.src = src
509 })
510 const [ia, ib] = await Promise.all([load(a), load(b)])
511 if (ia.width !== ib.width || ia.height !== ib.height) return null
512 const pixels = (img) => {
513 const c = document.createElement('canvas')
514 c.width = img.width
515 c.height = img.height
516 const ctx = c.getContext('2d')
517 ctx.drawImage(img, 0, 0)
518 return ctx.getImageData(0, 0, img.width, img.height).data
519 }
520 const pa = pixels(ia)
521 const pb = pixels(ib)
522 let sum = 0
523 // RGB only: both sheets are fully opaque, and alpha would only dilute the mean.
524 for (let i = 0; i < pa.length; i += 4) {
525 sum += Math.abs(pa[i] - pb[i]) + Math.abs(pa[i + 1] - pb[i + 1]) + Math.abs(pa[i + 2] - pb[i + 2])
526 }
527 return ((sum / ((pa.length / 4) * 3)) / 255) * 100
528 }, [before, after])
529 await context.close()
530 return result
531}
532
533// ------------------------------------------------------------------------ main
534
535const argv = process.argv.slice(2)
536const check = argv.includes('--check')
537const flag = (name) => {
538 const i = argv.indexOf(name)
539 return i >= 0 ? argv[i + 1] : undefined
540}
541const threshold = Number(flag('--threshold') ?? DEFAULT_THRESHOLD)
542const givenUrl = flag('--url')
543
544await mkdir(OUT, { recursive: true })
545/**
546 * Read every existing shot before anything overwrites it. These are the only
547 * baseline there is — the run is about to replace them in place.
548 */
549const previous = new Map()
550for (const profile of PROFILES) {
551 for (const shot of SHOTS) {
552 if (!shot.on.includes(profile.id)) continue
553 const file = fileFor(profile.id, shot.id)
554 const buf = await readFile(file).catch(() => null)
555 if (buf) previous.set(`${profile.id}-${shot.id}`, `data:image/png;base64,${buf.toString('base64')}`)
556 }
557}
558
559// Serve the app ourselves unless pointed at one already running. Vite's own API
560// means no port guessing and no orphaned child process to reap.
561const server = givenUrl ? null : await createServer({ root: ROOT, server: { port: 0 } })
562if (server) await server.listen()
563const base = givenUrl ?? server.resolvedUrls.local[0].replace(/\/$/, '')
564console.log(`\nTower screenshots — ${base}\n`)
565
566const cells = []
567try {
568 const tour = await launch()
569 try {
570 /**
571 * Every shot is independent — its own context, its own page, its own copy of
572 * the world — so they run several at a time. On the GPU a shot is mostly
573 * waiting: for the module graph, for a shader compile, for a view to settle.
574 * Serial, that idle time is the whole run; four at once fills it.
575 *
576 * Four rather than more because each shot holds a WebGL context and its own
577 * copy of the terrain rasters, and because past that the machine starts
578 * competing with itself for the GPU and the settle timings get noisier — which
579 * matters here more than speed does, since a shot that settles differently
580 * between runs shows up as divergence rather than as a slow run.
581 */
582 const jobs = []
583 for (const profile of PROFILES) {
584 for (const shot of SHOTS) {
585 if (shot.on.includes(profile.id)) jobs.push({ profile, shot })
586 }
587 }
588 const results = new Array(jobs.length)
589 let next = 0
590 const worker = async () => {
591 for (let i = next++; i < jobs.length; i = next++) {
592 const { profile, shot } = jobs[i]
593 await capture(tour, base, profile, shot)
594 results[i] = {
595 src: await dataUri(fileFor(profile.id, shot.id)),
596 caption: shot.caption,
597 label: `${profile.id}-${shot.id}`,
598 }
599 }
600 }
601 await Promise.all(Array.from({ length: CONCURRENCY }, worker))
602 // The sheet reads in profile order, not in whatever order the pool finished.
603 cells.push(...results)
604 } finally {
605 await tour.close()
606 }
607
608 /**
609 * A second browser for the paperwork. The tour leaves nine WebGL contexts and
610 * two Three.js scenes behind it, and in that browser Page.captureScreenshot on
611 * the sheet fails outright with "Unable to capture screenshot" — the sheet is
612 * plain HTML and images, so the only thing wrong with it is its neighbours.
613 */
614 const sheet = await launch()
615 try {
616 console.log('Overview')
617 await buildOverview(sheet, cells)
618
619 if (!previous.size) {
620 console.log('\nNothing to compare against — this run is the baseline.')
621 } else {
622 console.log('\nDivergence from the committed shots')
623 let worst = 0
624 let worstName = ''
625 for (const cell of cells) {
626 const before = previous.get(cell.label)
627 if (!before) {
628 console.log(` ${cell.label.padEnd(26)} new`)
629 continue
630 }
631 const moved = await divergence(sheet, before, cell.src)
632 if (moved === null) {
633 console.log(` ${cell.label.padEnd(26)} resized`)
634 continue
635 }
636 if (moved > worst) { worst = moved; worstName = cell.label }
637 console.log(` ${cell.label.padEnd(26)} ${moved.toFixed(2)}%${moved > threshold ? ' ←' : ''}`)
638 }
639 if (worst > threshold) {
640 console.log(`\n${worstName} moved ${worst.toFixed(2)}%, over the ${threshold}% threshold.`)
641 console.log('Open docs/screenshots/overview.png and make sure the UI is still there.')
642 if (check) process.exitCode = 1
643 } else {
644 console.log(`\nWorst: ${worstName} at ${worst.toFixed(2)}%, under the ${threshold}% threshold.`)
645 }
646 }
647 } finally {
648 await sheet.close()
649 }
650} finally {
651 await server?.close()
652}
653console.log('\nDone. Look at docs/screenshots/overview.png.\n')