Skip to content

3D engine that AI agents drive

Render the poster in crucible pack (#2178)

Nguyen Xuan An9a71597d7a91
diff --git a/bin/crucible.mjs b/bin/crucible.mjs
index e80f1229..28c4d541 100644
--- a/bin/crucible.mjs
+++ b/bin/crucible.mjs
@@ -1,39 +1,60 @@
#!/usr/bin/env node
// The crucible command line. `crucible pack <scene.json> --out <dir>` compiles a recipe into a runtime-only web bundle (docs/pack.md).
import { existsSync } from 'node:fs';
-import { dirname, join, resolve } from 'node:path';
+import { basename, dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
-const USAGE = 'Usage: crucible pack <scene.json> --out <dir> [--poster <picture.webp>] [--runtime <crucible-scene.js>]';
-const PACK_FLAGS = Object.freeze(['--out', '--poster', '--runtime']);
+const USAGE = 'Usage: crucible pack <scene.json> --out <dir> [--poster <picture.webp> | --no-poster] [--poster-size <w>x<h>] [--runtime <crucible-scene.js>]';
+const PACK_FLAGS = Object.freeze(['--out', '--poster', '--poster-size', '--runtime']);
+const PACK_SWITCHES = Object.freeze(['--no-poster']);
export function parsePackArguments(argumentList) {
const options = { recipePath: null };
for (let index = 0; index < argumentList.length; index += 1) {
const argument = argumentList[index];
- if (PACK_FLAGS.includes(argument)) {
+ if (PACK_SWITCHES.includes(argument)) {
+ options.noPoster = true;
+ } else if (PACK_FLAGS.includes(argument)) {
const value = argumentList[index + 1];
if (value === undefined || value.startsWith('--')) throw new TypeError(`${argument}: pass a value, such as ${argument} <path>.`);
- options[argument.slice(2)] = value;
+ options[flagKey(argument)] = value;
index += 1;
} else if (argument.startsWith('--')) {
- throw new TypeError(`${argument}: unknown option; crucible pack takes ${PACK_FLAGS.join(', ')}.`);
+ throw new TypeError(`${argument}: unknown option; crucible pack takes ${[...PACK_FLAGS, ...PACK_SWITCHES].join(', ')}.`);
} else if (options.recipePath === null) {
options.recipePath = argument;
} else {
throw new TypeError(`${argument}: only one scene.json can be packed at a time; pass the others in separate runs.`);
}
}
+ checkPosterOptions(options);
return options;
}
+// --poster-size becomes options.posterSize.
+function flagKey(flag) {
+ return flag.slice(2).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
+}
+
+function checkPosterOptions(options) {
+ if (options.poster && options.noPoster) throw new TypeError('--poster and --no-poster: pass one; --poster uses your picture, --no-poster packs without one.');
+ if (options.posterSize && (options.poster || options.noPoster)) {
+ throw new TypeError('--poster-size: it sizes the poster that pack renders; drop it when you pass --poster or --no-poster.');
+ }
+}
+
// A published package carries build/scene-pack.js; a source checkout runs src/scene-pack.js directly.
async function loadPackModule() {
const built = join(packageRoot, 'build', 'scene-pack.js');
return import(pathToFileURL(existsSync(built) ? built : join(packageRoot, 'src', 'scene-pack.js')).href);
}
+async function loadPosterModule() {
+ const built = join(packageRoot, 'build', 'scene-pack-poster.js');
+ return import(pathToFileURL(existsSync(built) ? built : join(packageRoot, 'src', 'scene-pack-poster.js')).href);
+}
+
async function main(argumentList) {
const [command, ...rest] = argumentList;
if (command !== 'pack') {
@@ -42,6 +63,9 @@ async function main(argumentList) {
}
try {
const options = parsePackArguments(rest);
+ const posterModule = options.poster || options.noPoster ? null : await loadPosterModule();
+ // The size is read before packing, so a bad --poster-size fails before any work.
+ const posterSize = options.posterSize ? posterModule?.parsePosterSize(options.posterSize) : undefined;
const { packRecipeFile } = await loadPackModule();
const result = await packRecipeFile({
recipePath: options.recipePath,
@@ -50,6 +74,10 @@ async function main(argumentList) {
runtimePath: options.runtime,
packageRoot,
});
+ if (posterModule) {
+ const title = basename(options.recipePath, extname(options.recipePath));
+ result.files.push(await posterModule.addGeneratedPoster({ outDir: result.outDir, title, size: posterSize }));
+ }
console.log(`Packed ${result.packBytes} bytes into ${result.outDir}: ${result.files.join(', ')}`);
return 0;
} catch (error) {
diff --git a/changes/2178.md b/changes/2178.md
index d03fe237..23c04571 100644
--- a/changes/2178.md
+++ b/changes/2178.md
@@ -1 +1,2 @@
- `crucible pack <scene.json> --out <dir>` compiles a recipe into a runtime-only web bundle, and `<crucible-scene>` shows its poster at once and swaps in live 3D without the recipe compiler (#2178)
+- `crucible pack` renders the poster itself in headless Chrome (`--poster-size <w>x<h>`, default 1280x720, writes `poster.webp`); `--poster <picture>` uses your own and `--no-poster` skips it (#2178)
diff --git a/config/vite.lib.config.js b/config/vite.lib.config.js
index 957b9106..1441ebc7 100644
--- a/config/vite.lib.config.js
+++ b/config/vite.lib.config.js
@@ -37,7 +37,7 @@ export default defineConfig({
build: {
copyPublicDir: false,
rolldownOptions: {
- external: ['@dimforge/rapier3d-compat', 'jolt-physics', 'manifold-3d', /^node:/],
+ external: ['@dimforge/rapier3d-compat', 'jolt-physics', 'manifold-3d', 'playwright-core', /^node:/],
output: { banner: legalBanner },
},
outDir: 'build',
@@ -74,6 +74,7 @@ export default defineConfig({
clutter: 'src/clutter.js',
'light-bake': 'src/light-bake.js',
'scene-pack': 'src/scene-pack.js',
+ 'scene-pack-poster': 'src/scene-pack-poster.js',
'crucible-scene': 'src/crucible-scene.js',
'light-bake-gpu': 'src/light-bake-gpu.js',
'ground-bounce': 'src/ground-bounce.js',
diff --git a/docs/pack.md b/docs/pack.md
index 1bc96db8..d5855758 100644
--- a/docs/pack.md
+++ b/docs/pack.md
@@ -7,7 +7,7 @@ This is slice 1 of #2178. It packs a still scene. Scroll, hover and click trigge
## Pack a scene
```sh
-npx crucible pack scene.json --out dist/scene --poster shot.webp
+npx crucible pack scene.json --out dist/scene
```
It writes into `dist/scene`:
@@ -16,10 +16,22 @@ It writes into `dist/scene`:
| --- | --- |
| `scene.pack` | the compiled parts (geometry as typed arrays), camera, lighting, effects and the shader modules the scene needs |
| `crucible-scene.js` and its chunks | the runtime: the `<crucible-scene>` element and the renderer |
-| `poster.webp` | the picture you passed with `--poster` (WebP, PNG or JPEG) |
+| `poster.webp` | the poster: rendered from the recipe's camera, or the picture you passed with `--poster` (WebP, PNG or JPEG) |
| `index.html` | a page that uses all of the above |
-`--poster` copies a picture you rendered. Pack does not render one itself yet. Without it the element shows a dark box until the 3D is ready. `--runtime <file>` names a built `crucible-scene.js` when the package has no `build/` folder, such as in a source checkout.
+## The poster
+
+Pack renders the poster itself: it opens the bundle it just wrote in headless Chrome, lets the live element draw the recipe's camera view and saves the canvas as `poster.webp`. The poster is the picture the live 3D settles on, and the element shows it at once, before the renderer has loaded.
+
+| Flag | What it does |
+| --- | --- |
+| `--poster-size <w>x<h>` | the poster size in pixels, default `1280x720`, each side from 64 to 2560 |
+| `--poster <picture>` | use a WebP, PNG or JPEG you rendered instead of rendering one |
+| `--no-poster` | write no poster; the element shows a dark box until the 3D is ready |
+
+Rendering needs Chrome (set `CHROME_PATH` to its executable when it is not installed in the usual place). Without Chrome, pack stops and says to pass `--poster` or `--no-poster`.
+
+`--runtime <file>` names a built `crucible-scene.js` when the package has no `build/` folder, such as in a source checkout.
Packing the same recipe twice writes the same `scene.pack` bytes.
diff --git a/src/scene-pack-poster.js b/src/scene-pack-poster.js
new file mode 100644
index 00000000..7f4243eb
--- /dev/null
+++ b/src/scene-pack-poster.js
@@ -0,0 +1,121 @@
+// Renders the poster of a packed scene (docs/pack.md): the bundle `crucible pack` just wrote is opened in headless Chrome, the
+// live <crucible-scene> draws the recipe's camera view, and the canvas is saved as a WebP. The poster is therefore the same
+// picture the live element shows, drawn by the renderer the page ships (no second renderer).
+import { createServer } from 'node:http';
+import { readFile, writeFile } from 'node:fs/promises';
+import { extname, join, resolve, sep } from 'node:path';
+import { indexHtml } from './scene-pack.js';
+
+export const POSTER_FILE_NAME = 'poster.webp';
+export const POSTER_DEFAULT_SIZE = Object.freeze({ width: 1280, height: 720 });
+export const POSTER_SIZE_LIMITS = Object.freeze({ minimum: 64, maximum: 2560 });
+const POSTER_WEBP_QUALITY = 0.85;
+const RENDER_TIMEOUT_MS = 60000;
+const CONTENT_TYPES = Object.freeze({ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.pack': 'application/octet-stream' });
+
+/** Reads `--poster-size 1280x720`: two integers from 64 to 2560, so a bad value fails before any browser starts. */
+export function parsePosterSize(text) {
+ const match = /^(\d+)x(\d+)$/.exec(String(text).trim());
+ if (!match) throw new TypeError(`--poster-size: got ${JSON.stringify(text)}; pass <width>x<height>, such as 1280x720.`);
+ const [width, height] = [Number(match[1]), Number(match[2])];
+ const { minimum, maximum } = POSTER_SIZE_LIMITS;
+ if (![width, height].every(side => side >= minimum && side <= maximum)) {
+ throw new RangeError(`--poster-size: ${width}x${height} is out of range; each side must be from ${minimum} to ${maximum}.`);
+ }
+ return { width, height };
+}
+
+function chromeUnavailable(error) {
+ return new Error(`poster: headless Chrome did not start (${error.message.split('\n')[0]}). Install Chrome or set CHROME_PATH to its executable; or pass --poster <picture.webp> to use a picture you rendered, or --no-poster to pack without one.`);
+}
+
+// Chrome cannot fetch ES modules from file://, so the bundle is served from a loopback server that reads only its own folder.
+function serveFolder(folder) {
+ const server = createServer(async (request, response) => {
+ const requested = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
+ const path = resolve(folder, requested === '/' ? 'index.html' : `.${requested}`);
+ if (!path.startsWith(folder + sep) || !(extname(path) in CONTENT_TYPES)) {
+ response.writeHead(404).end();
+ return;
+ }
+ try {
+ response.writeHead(200, { 'Content-Type': CONTENT_TYPES[extname(path)] }).end(await readFile(path));
+ } catch {
+ response.writeHead(404).end();
+ }
+ });
+ return new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => resolve(server));
+ });
+}
+
+async function launchChrome() {
+ const { chromium } = await import('playwright-core');
+ const args = ['--enable-webgl', '--ignore-gpu-blocklist'];
+ const launchOptions = process.env.CHROME_PATH ? { headless: true, args, executablePath: process.env.CHROME_PATH } : { headless: true, args, channel: 'chrome' };
+ try {
+ return await chromium.launch(launchOptions);
+ } catch (error) {
+ throw chromeUnavailable(error);
+ }
+}
+
+// The screenshot is PNG; the page re-encodes it as WebP, so the repo needs no encoder.
+const ENCODE_WEBP = async ({ png, quality }) => {
+ const image = new Image();
+ image.src = `data:image/png;base64,${png}`;
+ await image.decode();
+ const canvas = document.createElement('canvas');
+ canvas.width = image.naturalWidth;
+ canvas.height = image.naturalHeight;
+ canvas.getContext('2d').drawImage(image, 0, 0);
+ const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/webp', quality));
+ if (!blob || blob.type !== 'image/webp') throw new Error('this Chrome cannot encode WebP');
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ let binary = '';
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
+ return btoa(binary);
+};
+
+/** Opens `<bundleFolder>/index.html` at the poster size and returns the live scene as WebP bytes. */
+export async function renderPosterWebp(bundleFolder, { width, height } = POSTER_DEFAULT_SIZE) {
+ const folder = resolve(bundleFolder);
+ const server = await serveFolder(folder);
+ let browser;
+ try {
+ browser = await launchChrome();
+ const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 });
+ page.setDefaultTimeout(RENDER_TIMEOUT_MS);
+ await page.goto(`http://127.0.0.1:${server.address().port}/index.html`);
+ const outcome = await page.waitForFunction(() => {
+ const element = document.querySelector('crucible-scene');
+ return element.getAttribute('state') !== 'loading' ? element.getAttribute('state') : false;
+ }).then(handle => handle.jsonValue());
+ if (outcome !== 'live') throw new Error('poster: the packed scene did not draw in Chrome; open the pack in a page and read the console, or pass --poster <picture.webp>.');
+ // The element fades its canvas in (240 ms); a screenshot taken before the fade ends is a darkened picture.
+ await page.evaluate(async () => {
+ const element = document.querySelector('crucible-scene');
+ await Promise.all(element.shadowRoot.getAnimations({ subtree: true }).map(animation => animation.finished));
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ });
+ const png = (await page.screenshot({ type: 'png' })).toString('base64');
+ return Buffer.from(await page.evaluate(ENCODE_WEBP, { png, quality: POSTER_WEBP_QUALITY }), 'base64');
+ } finally {
+ await browser?.close();
+ server.close();
+ }
+}
+
+/** Renders the poster of the bundle in `outDir` and writes `<outDir>/poster.webp`. Returns the file name. */
+export async function writePosterFile(outDir, size) {
+ await writeFile(join(outDir, POSTER_FILE_NAME), await renderPosterWebp(outDir, size));
+ return POSTER_FILE_NAME;
+}
+
+/** After `packRecipeFile` wrote a bundle without a poster: renders one, then rewrites index.html so the element uses it. */
+export async function addGeneratedPoster({ outDir, title, size = POSTER_DEFAULT_SIZE }) {
+ const posterName = await writePosterFile(outDir, size);
+ await writeFile(join(outDir, 'index.html'), indexHtml({ title, posterName }));
+ return posterName;
+}
diff --git a/tests/scene-pack-poster.test.js b/tests/scene-pack-poster.test.js
new file mode 100644
index 00000000..e6deb06b
--- /dev/null
+++ b/tests/scene-pack-poster.test.js
@@ -0,0 +1,66 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { build } from 'esbuild';
+import { packRecipeFile } from '../src/scene-pack.js';
+import { addGeneratedPoster, parsePosterSize, POSTER_DEFAULT_SIZE, POSTER_SIZE_LIMITS } from '../src/scene-pack-poster.js';
+import { parsePackArguments } from '../bin/crucible.mjs';
+
+const RECIPE_PATH = 'public/recipes/view-transform.json';
+const SMOKE_SIZE = Object.freeze({ width: 640, height: 360 });
+
+// Width and height from the first chunk of a WebP file (lossy VP8, lossless VP8L or extended VP8X).
+function webpDimensions(bytes) {
+ assert.equal(bytes.toString('ascii', 0, 4), 'RIFF');
+ assert.equal(bytes.toString('ascii', 8, 12), 'WEBP');
+ const chunk = bytes.toString('ascii', 12, 16);
+ if (chunk === 'VP8 ') return { width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff };
+ if (chunk === 'VP8X') return { width: bytes.readUIntLE(24, 3) + 1, height: bytes.readUIntLE(27, 3) + 1 };
+ const bits = bytes.readUInt32LE(21);
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
+}
+
+test('parsePosterSize reads <width>x<height> and keeps both sides inside the limits', () => {
+ assert.deepEqual(parsePosterSize('1280x720'), POSTER_DEFAULT_SIZE);
+ assert.deepEqual(parsePosterSize(`${POSTER_SIZE_LIMITS.minimum}x${POSTER_SIZE_LIMITS.maximum}`), { width: POSTER_SIZE_LIMITS.minimum, height: POSTER_SIZE_LIMITS.maximum });
+ assert.throws(() => parsePosterSize('1280'), /--poster-size: got "1280"; pass <width>x<height>/);
+ assert.throws(() => parsePosterSize('wide'), /pass <width>x<height>/);
+ assert.throws(() => parsePosterSize('63x720'), /out of range; each side must be from 64 to 2560/);
+ assert.throws(() => parsePosterSize('1280x2561'), /out of range/);
+ assert.throws(() => parsePosterSize('0x0'), /out of range/);
+});
+
+test('crucible pack reads --poster-size and --no-poster, and refuses flags that contradict each other', () => {
+ assert.equal(parsePackArguments(['a.json', '--out', 'dist']).noPoster, undefined);
+ assert.equal(parsePackArguments(['a.json', '--out', 'dist', '--no-poster']).noPoster, true);
+ assert.equal(parsePackArguments(['a.json', '--out', 'dist', '--poster-size', '800x450']).posterSize, '800x450');
+ assert.throws(() => parsePackArguments(['a.json', '--poster', 'p.webp', '--no-poster']), /pass one/);
+ assert.throws(() => parsePackArguments(['a.json', '--no-poster', '--poster-size', '800x450']), /--poster-size: .*drop it when you pass --poster or --no-poster/);
+ assert.throws(() => parsePackArguments(['a.json', '--poster', 'p.webp', '--poster-size', '800x450']), /--poster-size/);
+ assert.throws(() => parsePackArguments(['a.json', '--poster-size']), /--poster-size: pass a value/);
+});
+
+test('a packed scene gets a WebP poster of the requested size, and index.html uses it', async t => {
+ const folder = mkdtempSync(join(tmpdir(), 'crucible-poster-'));
+ try {
+ const runtimeFolder = join(folder, 'runtime');
+ await build({ entryPoints: ['src/crucible-scene.js'], bundle: true, format: 'esm', splitting: true, outdir: runtimeFolder, logLevel: 'error' });
+ const outDir = join(folder, 'out');
+ await packRecipeFile({ recipePath: RECIPE_PATH, outDir, runtimePath: join(runtimeFolder, 'crucible-scene.js'), packageRoot: folder });
+ assert.ok(!existsSync(join(outDir, 'poster.webp')), 'pack alone writes no poster');
+ try {
+ await addGeneratedPoster({ outDir, title: 'view-transform', size: SMOKE_SIZE });
+ } catch (error) {
+ if (/headless Chrome did not start/.test(error.message)) return t.skip('no Chrome to render the poster with');
+ throw error;
+ }
+ const poster = readFileSync(join(outDir, 'poster.webp'));
+ assert.deepEqual(webpDimensions(poster), SMOKE_SIZE);
+ assert.ok(poster.length > 1500, `a drawn scene is more than a flat colour (got ${poster.length} bytes)`);
+ assert.match(readFileSync(join(outDir, 'index.html'), 'utf8'), /<crucible-scene src="\.\/scene\.pack" poster="\.\/poster\.webp">/);
+ } finally {
+ rmSync(folder, { recursive: true, force: true });
+ }
+});