Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

feat(site): settle Holodeck shots on readiness, and capture headed (#276) (#301)

Matthew Kissingerbb5a9b0705c7
diff --git a/packs/holodeck/README.md b/packs/holodeck/README.md
index ea3864ff..101cad71 100644
--- a/packs/holodeck/README.md
+++ b/packs/holodeck/README.md
@@ -153,3 +153,47 @@ and a different commit, refuses source-revision rollback, and still verifies tha
changed assets descend from the selected revisions. Shared assets used by other
packs cannot change through this path. This preserves the original authoring-world
revision rather than inventing one for a repository maintenance change.
+
+## Scene shots
+
+Each pack page shows two shots of its walkable world, declared in `HOLODECK_SHOTS`
+(`holodeck-spec.mjs`) with the Holodeck benchmark camera each one uses. From `site/`:
+
+```sh
+node scripts/capture-holodeck-shots.mjs --out .localdata/holodeck-shots [--only view,view]
+node scripts/stage-holodeck.mjs --shots --captures .localdata/holodeck-shots --mirror .localdata/holodeck-delivery
+```
+
+The capture loads each world in benchmark mode, hides the interface and screenshots it at the
+shot size. `receipt.json` records the world, the SHA-256 of its `manifest.json` before and after
+(so a deploy mid-capture is refused), the camera, the backend, the browser, whether Chrome ran
+headless or headed, how the shot settled and how far the frame still moved. Staging accepts only
+a WebGPU capture of the declared camera from that pack's world.
+
+### Settling
+
+A world that publishes readiness of its own (`holodeckPrototype.renderReady`, and any sky-light
+or probe-grid state beside it) is waited on, and the receipt names the signals. Holodeck
+publishes none yet, so `--settle MS` stands in, at 45 s by default: Meridian Sanctuary's sky
+light and probe grid were still resolving at 8 s, which put black mirror cubes and sky-only orbs
+in shots the receipt recorded as valid.
+
+The kept frame is the second of two taken `--drift MS` apart (2 s by default), and a frame that
+moved more than `--max-drift` between them is refused: a converged frame differs only by
+dithering, so anything more means the scene is still resolving. The default, 0.01 mean absolute
+luminance difference, has not been calibrated against the live worlds — the receipt records the
+measured drift for every shot, so the first headed run says what these scenes actually settle
+to. A world that animates can capture with `--max-drift off`.
+
+### Linux hybrid GPUs
+
+Headless Chrome gets no GPU through PRIME offload: the world reports no drawn frame and the wait
+times out, which the error says rather than blaming the world. Capture headed instead, with the
+offload variables exported — Chrome inherits this process's environment:
+
+```sh
+__NV_PRIME_RENDER_OFFLOAD=1 __VK_LAYER_NV_optimus=NVIDIA_only __GLX_VENDOR_LIBRARY_NAME=nvidia \
+ node scripts/capture-holodeck-shots.mjs --out .localdata/holodeck-shots --headed
+```
+
+On the hub (CachyOS, GTX 1660 Ti) that renders WebGPU in about 30 s per world.
diff --git a/site/scripts/capture-holodeck-shots.mjs b/site/scripts/capture-holodeck-shots.mjs
index a6af92a7..8ceb88cd 100644
--- a/site/scripts/capture-holodeck-shots.mjs
+++ b/site/scripts/capture-holodeck-shots.mjs
@@ -2,6 +2,7 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import puppeteer from 'puppeteer-core';
+import sharp from 'sharp';
import { chromeExecutable } from './build-site-media.mjs';
import { HOLODECK_PACKS, HOLODECK_SHOT_SIZE, HOLODECK_SHOTS } from './holodeck-spec.mjs';
import { readJson } from './media-pins.mjs';
@@ -9,18 +10,95 @@ import { hashBytes } from './mirror-core.mjs';
import { HOLODECK_WORLDS, holodeckWorld } from './stage-holodeck.mjs';
/**
- * Capture each pack's declared scene shots from its live Holodeck world with headless Chrome on WebGPU, interface
- * hidden, at the shot size. Each world loads in benchmark mode with the declared camera and settles before the
- * screenshot. The folder gets `<view>.png` and `receipt.json`, which names the world, the SHA-256 of its
- * `manifest.json` (read before and after the capture, so a deploy in between is refused), the camera, the backend
- * and browser; `stage-holodeck.mjs --shots --captures DIR` stages them. Needs a WebGPU-capable GPU.
+ * Capture each pack's declared scene shots from its live Holodeck world with Chrome on WebGPU, interface hidden, at
+ * the shot size. Each world loads in benchmark mode with the declared camera and settles before the screenshot. The
+ * folder gets `<view>.png` and `receipt.json`, which names the world, the SHA-256 of its `manifest.json` (read
+ * before and after the capture, so a deploy in between is refused), the camera, the backend and browser, whether
+ * Chrome ran headless or headed, how the shot settled and how far the frame still moved;
+ * `stage-holodeck.mjs --shots --captures DIR` stages them. Needs a WebGPU-capable GPU.
*
* node scripts/capture-holodeck-shots.mjs --out .localdata/holodeck-shots [--only view,view]
+ * [--headed] [--settle MS] [--drift MS] [--max-drift VALUE|off]
+ *
+ * On a Linux hybrid-GPU host, headless Chrome gets no GPU through PRIME offload: the world never reports a drawn
+ * frame and the wait times out. Capture headed, with the offload variables exported -- Chrome inherits this
+ * process's environment, so nothing here needs to pass them:
+ *
+ * __NV_PRIME_RENDER_OFFLOAD=1 __VK_LAYER_NV_optimus=NVIDIA_only __GLX_VENDOR_LIBRARY_NAME=nvidia \
+ * node scripts/capture-holodeck-shots.mjs --out .localdata/holodeck-shots --headed
*/
export const CAPTURE_TOOL = 'scripts/capture-holodeck-shots.mjs';
-const SETTLE_MS = 8000;
+/**
+ * How long to let a world settle when it publishes no readiness of its own. Meridian Sanctuary's sky light and
+ * probe grid were still resolving at 8 s -- its mirror cubes came out black and its orbs showed only sky -- and
+ * were right at 45 s.
+ */
+const SETTLE_MS = 45_000;
+/** How far apart the two frames of the drift check are taken, and how long the hidden interface has to repaint. */
+const DRIFT_MS = 2_000;
+/** A converged frame differs between two captures only by dithering and tone-mapping noise. */
+const MAX_DRIFT = 0.01;
+const READY_MS = 180_000;
const HIDE_INTERFACE = 'aside.viewer-diagnostics, .diagnostics-toggle { display: none !important; }';
+const pause = (ms) => new Promise((done) => setTimeout(done, ms));
+
+const SIGNALS = "['renderReady', 'skyLightReady', 'probeGridReady']";
+/** The world has drawn at least one frame. */
+export const WORLD_READY = 'window.holodeckPrototype?.ready && window.holodeckPrototype.drawCalls > 0';
+/** Which readiness signals of its own the world publishes, if any. */
+export const RENDER_SIGNALS = `${SIGNALS}.filter((name) => window.holodeckPrototype?.[name] !== undefined)`;
+/** Every readiness signal the world publishes is true. Holodeck publishes none yet, so a settle stands in. */
+export const RENDER_READY = `${SIGNALS}.map((name) => window.holodeckPrototype?.[name]).filter((signal) => signal !== undefined).every(Boolean)`;
+
+/**
+ * How far two captures of the same frame differ: the mean absolute difference of their luminance, 0..1. A converged
+ * frame differs only by dithering and tone-mapping noise; a probe grid still filling in or a sky light still
+ * resolving moves much further, which is exactly what a fixed wait photographed half-finished.
+ */
+export async function captureDrift(first, second) {
+ const [a, b] = await Promise.all([first, second].map((png) => sharp(png).greyscale().raw().toBuffer()));
+ if (a.length !== b.length) throw new Error(`The two captures are different sizes: ${a.length} and ${b.length} samples`);
+ let total = 0;
+ for (let index = 0; index < a.length; index++) total += Math.abs(a[index] - b[index]);
+ return total / a.length / 255;
+}
+
+/**
+ * Settle one open world and keep its frame. The world's own readiness decides when it publishes any; otherwise a
+ * settle stands in, and either way the kept frame is the second of two taken `driftMs` apart, so a scene still
+ * resolving is refused rather than photographed. A world that never reports a drawn frame says what to try, because
+ * on a Linux hybrid-GPU host that is headless Chrome missing the GPU rather than a broken world.
+ */
+export async function settleAndShoot(page, { view, headless = true, settleMs = SETTLE_MS, driftMs = DRIFT_MS, maxDrift = MAX_DRIFT, readyMs = READY_MS }) {
+ try { await page.waitForFunction(WORLD_READY, { timeout: readyMs }); }
+ catch (error) {
+ const advice = headless
+ ? ' Headless Chrome gets no GPU through PRIME offload on a Linux hybrid-GPU host: capture with --headed and __NV_PRIME_RENDER_OFFLOAD=1, __VK_LAYER_NV_optimus=NVIDIA_only, __GLX_VENDOR_LIBRARY_NAME=nvidia exported.'
+ : '';
+ throw new Error(`${view}: the world reported no drawn frame within ${readyMs} ms.${advice}`, { cause: error });
+ }
+ const published = (await page.evaluate(RENDER_SIGNALS)) ?? [];
+ let settled;
+ if (published.length) {
+ try { await page.waitForFunction(RENDER_READY, { timeout: readyMs }); }
+ catch (error) { throw new Error(`${view}: the world did not become render-ready within ${readyMs} ms (${published.join(', ')})`, { cause: error }); }
+ settled = published.join('+');
+ } else {
+ await pause(settleMs);
+ settled = `settle:${settleMs}ms`;
+ }
+ await page.addStyleTag({ content: HIDE_INTERFACE });
+ await pause(driftMs);
+ const first = Buffer.from(await page.screenshot({ type: 'png' }));
+ await pause(driftMs);
+ const png = Buffer.from(await page.screenshot({ type: 'png' }));
+ const drift = await captureDrift(first, png);
+ if (maxDrift !== false && drift > maxDrift) {
+ throw new Error(`${view}: the frame still moved ${drift.toFixed(4)} between captures ${driftMs} ms apart, over ${maxDrift}. Give it a longer --settle, or --max-drift off for a scene that animates.`);
+ }
+ return { png, settled, drift };
+}
const manifestSha256 = async (world) => {
const response = await fetch(new URL('manifest.json', world), { cache: 'no-store' });
@@ -28,7 +106,7 @@ const manifestSha256 = async (world) => {
return hashBytes(Buffer.from(await response.arrayBuffer()));
};
-export async function captureHolodeckShots({ out, only, size = HOLODECK_SHOT_SIZE, shots = HOLODECK_SHOTS, packs = HOLODECK_PACKS }) {
+export async function captureHolodeckShots({ out, only, headed = false, settleMs, driftMs, maxDrift, size = HOLODECK_SHOT_SIZE, shots = HOLODECK_SHOTS, packs = HOLODECK_PACKS }) {
if (!out) throw new Error('An explicit output folder is required');
const worlds = await readJson(HOLODECK_WORLDS);
const jobs = packs.flatMap((pack) => (shots[pack.id] ?? []).map((shot) => ({ ...shot, world: holodeckWorld(worlds, pack.id) })))
@@ -41,7 +119,7 @@ export async function captureHolodeckShots({ out, only, size = HOLODECK_SHOT_SIZ
const prior = JSON.parse(await readFile(join(out, 'receipt.json'), 'utf8'));
if (prior.tool === CAPTURE_TOOL && prior.size?.width === size.width && prior.size?.height === size.height) receipt = prior;
} catch (error) { if (error.code !== 'ENOENT') throw error; }
- const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: true, args: ['--enable-unsafe-webgpu', '--enable-features=Vulkan', '--ignore-gpu-blocklist'] });
+ const browser = await puppeteer.launch({ executablePath: chromeExecutable(), headless: !headed, args: ['--enable-unsafe-webgpu', '--enable-features=Vulkan', '--ignore-gpu-blocklist'] });
try {
const version = await browser.version();
for (const { view, camera, world } of jobs) {
@@ -53,18 +131,14 @@ export async function captureHolodeckShots({ out, only, size = HOLODECK_SHOT_SIZ
await page.evaluateOnNewDocument((scenario) => { window.holodeckBenchmarkScenario = scenario; }, { id: view, ...camera });
const url = new URL(world); url.searchParams.set('benchmark', '1');
await page.goto(url.href, { waitUntil: 'load', timeout: 120_000 });
- await page.waitForFunction(() => window.holodeckPrototype?.ready && window.holodeckPrototype.drawCalls > 0, { timeout: 180_000 });
- await new Promise((done) => setTimeout(done, SETTLE_MS));
- await page.addStyleTag({ content: HIDE_INTERFACE });
- await new Promise((done) => setTimeout(done, 500));
- const png = Buffer.from(await page.screenshot({ type: 'png' }));
+ const { png, settled, drift } = await settleAndShoot(page, { view, headless: !headed, settleMs, driftMs, maxDrift });
const probe = await page.evaluate(() => { const p = window.holodeckPrototype; return { backend: p.backend, drawCalls: p.drawCalls, errors: p.errors ?? [] }; });
await page.close();
if (errors.length || probe.errors.length) throw new Error(`${view}: the world reported errors: ${[...errors, ...probe.errors].join('; ')}`);
if (probe.backend !== 'WebGPU') throw new Error(`${view}: rendered on ${probe.backend}, not WebGPU`);
if ((await manifestSha256(world)) !== before) throw new Error(`${view}: ${world} changed during the capture`);
await writeFile(join(out, `${view}.png`), png);
- receipt.shots[view] = { world, manifestSha256: before, camera, backend: probe.backend, drawCalls: probe.drawCalls, browser: version, capturedAt: new Date().toISOString() };
+ receipt.shots[view] = { world, manifestSha256: before, camera, backend: probe.backend, drawCalls: probe.drawCalls, browser: version, chrome: headed ? 'headed' : 'headless', settled, drift, capturedAt: new Date().toISOString() };
await writeFile(join(out, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n');
console.log(JSON.stringify({ view, ...receipt.shots[view] }));
}
@@ -75,13 +149,20 @@ export async function captureHolodeckShots({ out, only, size = HOLODECK_SHOT_SIZ
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
- const args = process.argv.slice(2), options = {};
- for (let i = 0; i < args.length; i += 2) {
- const [flag, value] = [args[i], args[i + 1]];
+ const args = process.argv.slice(2), options = { headed: args.includes('--headed') };
+ const rest = args.filter((arg) => arg !== '--headed');
+ for (let i = 0; i < rest.length; i += 2) {
+ const [flag, value] = [rest[i], rest[i + 1]];
if (!value || value.startsWith('--')) throw new Error(`Missing value for ${flag}`);
if (flag === '--out') options.out = resolve(value);
else if (flag === '--only') options.only = value.split(',');
+ else if (flag === '--settle') options.settleMs = Number(value);
+ else if (flag === '--drift') options.driftMs = Number(value);
+ else if (flag === '--max-drift') options.maxDrift = value === 'off' ? false : Number(value);
else throw new Error(`Unknown option ${flag}`);
}
+ for (const [flag, value] of [['--settle', options.settleMs], ['--drift', options.driftMs], ['--max-drift', options.maxDrift]]) {
+ if (value !== undefined && value !== false && !(Number.isFinite(value) && value >= 0)) throw new Error(`${flag} takes a number of at least 0`);
+ }
await captureHolodeckShots(options);
}
diff --git a/site/scripts/capture-holodeck-shots.test.ts b/site/scripts/capture-holodeck-shots.test.ts
new file mode 100644
index 00000000..9ea9e421
--- /dev/null
+++ b/site/scripts/capture-holodeck-shots.test.ts
@@ -0,0 +1,76 @@
+import { expect, test } from 'bun:test';
+import sharp from 'sharp';
+import { RENDER_READY, RENDER_SIGNALS, WORLD_READY, captureDrift, settleAndShoot } from './capture-holodeck-shots.mjs';
+
+const frame = (grey: number) => sharp({ create: { width: 4, height: 4, channels: 3, background: { r: grey, g: grey, b: grey } } }).png().toBuffer();
+
+/** An open world page: which readiness signals it publishes, whether each wait resolves, and the frames it shows. */
+function fakeWorld({ published = [] as string[], draws = true, renderReady = true, frames = [] as Buffer[] }) {
+ const waited: string[] = [];
+ let shown = 0;
+ return {
+ waited,
+ styles: [] as string[],
+ async waitForFunction(expression: string) {
+ waited.push(expression);
+ if (expression === WORLD_READY && !draws) throw new Error('Waiting failed: 180000ms exceeded');
+ if (expression === RENDER_READY && !renderReady) throw new Error('Waiting failed: 180000ms exceeded');
+ },
+ async evaluate(expression: string) {
+ expect(expression).toBe(RENDER_SIGNALS);
+ return published;
+ },
+ async addStyleTag({ content }: { content: string }) { this.styles.push(content); },
+ async screenshot() { return frames[Math.min(shown++, frames.length - 1)]; },
+ };
+}
+
+const settle = { view: 'meridian-sanctuary-overview', settleMs: 0, driftMs: 0 };
+
+test('drift is the mean absolute luminance difference between two captures of the same frame', async () => {
+ const [dark, lighter] = await Promise.all([frame(0), frame(51)]);
+ expect(await captureDrift(dark, dark)).toBe(0);
+ expect(await captureDrift(dark, lighter)).toBeCloseTo(51 / 255, 6);
+ expect(await captureDrift(lighter, dark)).toBeCloseTo(51 / 255, 6);
+ const wide = await sharp({ create: { width: 8, height: 4, channels: 3, background: { r: 0, g: 0, b: 0 } } }).png().toBuffer();
+ await expect(captureDrift(dark, wide)).rejects.toThrow('different sizes');
+});
+
+test('a world that publishes its own readiness is waited on, and the shot names it', async () => {
+ const still = await frame(120);
+ const page = fakeWorld({ published: ['renderReady', 'skyLightReady'], frames: [still] });
+ const shot = await settleAndShoot(page, settle);
+ expect(shot.settled).toBe('renderReady+skyLightReady');
+ expect(shot.drift).toBe(0);
+ expect(page.waited).toEqual([WORLD_READY, RENDER_READY]);
+ expect(page.styles).toEqual([expect.stringContaining('viewer-diagnostics')]);
+});
+
+test('a world that publishes none settles for the given time, and the shot names that instead', async () => {
+ const page = fakeWorld({ frames: [await frame(120)] });
+ const shot = await settleAndShoot(page, { ...settle, settleMs: 1 });
+ expect(shot.settled).toBe('settle:1ms');
+ expect(page.waited).toEqual([WORLD_READY]);
+});
+
+test('readiness the world publishes but has not reached is a timeout naming the signals', async () => {
+ const page = fakeWorld({ published: ['probeGridReady'], renderReady: false, frames: [await frame(120)] });
+ await expect(settleAndShoot(page, settle)).rejects.toThrow('did not become render-ready within 180000 ms (probeGridReady)');
+});
+
+test('a frame still moving between two captures is refused rather than kept', async () => {
+ // The Meridian mirrors at 8 s: the frame was still resolving, and the receipt recorded the shot as valid anyway.
+ const frames = await Promise.all([frame(0), frame(80)]);
+ const page = fakeWorld({ frames });
+ await expect(settleAndShoot(page, settle)).rejects.toThrow(/still moved 0\.3137 between captures 0 ms apart, over 0\.01.*--settle/s);
+ // A scene that animates can say so, and the measured drift is still reported.
+ const animated = await settleAndShoot(fakeWorld({ frames }), { ...settle, maxDrift: false });
+ expect(animated.drift).toBeCloseTo(80 / 255, 6);
+ expect(animated.png).toEqual(frames[1]);
+});
+
+test('a world that never draws a frame blames headless Chrome on a hybrid GPU, not the world', async () => {
+ const page = fakeWorld({ draws: false, frames: [await frame(0)] });
+ await expect(settleAndShoot(page, settle)).rejects.toThrow(/no drawn frame within 180000 ms.*--headed.*__NV_PRIME_RENDER_OFFLOAD=1/s);
+ await expect(settleAndShoot(page, { ...settle, headless: false })).rejects.toThrow(/no drawn frame within 180000 ms\.$/);
+});