Skip to content

3D engine that AI agents drive

Fail a benchmark scene whose default camera renders a flat frame (#2158)

Nguyen Xuan Ande0f023a6dfc
diff --git a/bench/scene-frames/check-default-cameras.mjs b/bench/scene-frames/check-default-cameras.mjs
new file mode 100644
index 00000000..96cb147d
--- /dev/null
+++ b/bench/scene-frames/check-default-cameras.mjs
@@ -0,0 +1,50 @@
+// Renders each scene file's own camera small and fails when a frame is nearly one colour:
+// node bench/scene-frames/check-default-cameras.mjs <scene-directory>[,<scene-directory>...] [--width 320] [--height 180]
+// A scene directory holds scene.json, scene.glb and sky.hdr (see bench/glaze-passes/run.mjs). Exit code 1 lists the flat scenes.
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { decodePng } from '../agent-modeling/png-check.mjs';
+import { MINIMUM_MEAN_LUMINANCE_STEP, meanLuminanceStep } from './uniform-frame.mjs';
+
+const RENDER_MEDIA = fileURLToPath(new URL('../../scripts/render-media.mjs', import.meta.url));
+
+function renderDefaultCamera(directory, width, height) {
+ const work = mkdtempSync(join(tmpdir(), 'scene-frame-'));
+ try {
+ const output = join(work, 'frame.png');
+ const result = spawnSync(process.execPath, [RENDER_MEDIA, '--kind', 'image', '--scene', 'file', '--config', `${directory}/scene.json`, '--width', String(width), '--height', String(height), '--output', output], { encoding: 'utf8' });
+ if (result.status !== 0) throw new Error(`render-media failed for ${directory}: ${(result.stderr || result.stdout).split('\n').slice(-5).join(' ')}`);
+ const png = decodePng(readFileSync(output));
+ return meanLuminanceStep(png.pixels, png.channels, png.width);
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
+
+function main(argv) {
+ const positional = [];
+ let width = 320;
+ let height = 180;
+ for (let index = 0; index < argv.length; index++) {
+ if (argv[index] === '--width') width = Number(argv[++index]);
+ else if (argv[index] === '--height') height = Number(argv[++index]);
+ else positional.push(argv[index]);
+ }
+ if (positional.length === 0) throw new Error('Pass a comma separated list of scene directories, each holding scene.json.');
+ const flat = [];
+ for (const directory of positional.join(',').split(',').filter(Boolean).map(entry => resolve(entry))) {
+ const deviation = renderDefaultCamera(directory, width, height);
+ const verdict = deviation < MINIMUM_MEAN_LUMINANCE_STEP ? 'FLAT' : 'ok';
+ console.log(`${verdict}\t${basename(directory)}\tmean luminance step ${deviation.toFixed(3)} of 255 (minimum ${MINIMUM_MEAN_LUMINANCE_STEP})`);
+ if (verdict === 'FLAT') flat.push(basename(directory));
+ }
+ if (flat.length > 0) {
+ console.error(`Default camera renders a near-uniform frame: ${flat.join(', ')}. Move eye and target in scene.json to a view that shows the scene.`);
+ process.exitCode = 1;
+ }
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) main(process.argv.slice(2));
diff --git a/bench/scene-frames/uniform-frame.mjs b/bench/scene-frames/uniform-frame.mjs
new file mode 100644
index 00000000..37515da6
--- /dev/null
+++ b/bench/scene-frames/uniform-frame.mjs
@@ -0,0 +1,35 @@
+// Tells a flat frame from a picture: the mean luminance step between neighbouring pixels of a small render.
+// A scene whose default camera sits behind a wall renders one colour, so every still and frame time from it measures nothing (#2158).
+// Steps, not the spread around the mean, because a flat white frame with a vignette still spreads widely (standard deviation 16 of 255)
+// while its neighbouring pixels differ by almost nothing.
+
+/** Frames with a mean step below this (of 255) count as flat. Calibrated on Lone Monk behind its wall against the other benchmark scenes (0.32 flat, 2.4 and up for the rest). */
+export const MINIMUM_MEAN_LUMINANCE_STEP = 1;
+
+function luminanceAt(pixels, offset) {
+ return 0.2126 * pixels[offset] + 0.7152 * pixels[offset + 1] + 0.0722 * pixels[offset + 2];
+}
+
+/** Mean absolute Rec. 709 luma difference to the right and lower neighbour of 8-bit RGB or RGBA pixels, on a 0 to 255 scale. */
+export function meanLuminanceStep(pixels, channels, width) {
+ if (channels !== 3 && channels !== 4) throw new Error(`Pass pixels with 3 or 4 channels, got ${channels}.`);
+ if (!Number.isInteger(width) || width < 2) throw new Error(`Pass the frame width in pixels (at least 2), got ${width}.`);
+ const height = Math.floor(pixels.length / channels / width);
+ if (height < 2) throw new Error('Pass at least two rows of pixels to measure.');
+ let totalStep = 0;
+ let stepCount = 0;
+ for (let row = 0; row < height - 1; row++) {
+ for (let column = 0; column < width - 1; column++) {
+ const offset = (row * width + column) * channels;
+ const luma = luminanceAt(pixels, offset);
+ totalStep += Math.abs(luma - luminanceAt(pixels, offset + channels));
+ totalStep += Math.abs(luma - luminanceAt(pixels, offset + width * channels));
+ stepCount += 2;
+ }
+ }
+ return totalStep / stepCount;
+}
+
+export function isNearUniformFrame(pixels, channels, width, minimum = MINIMUM_MEAN_LUMINANCE_STEP) {
+ return meanLuminanceStep(pixels, channels, width) < minimum;
+}
diff --git a/docs/culling-lod.md b/docs/culling-lod.md
index 825c810e..8f2015a9 100644
--- a/docs/culling-lod.md
+++ b/docs/culling-lod.md
@@ -61,3 +61,5 @@ A scan with about one triangle per pixel or more is shaded once per sample at ne
`addLodsToDenseParts(parts, { pixels })` from `src/dense-lods.js` gives levels to the parts of a scene that has more than one triangle per pixel (`pixels` is the canvas width times its height times the pixel ratio squared). A part gets levels when it has at least `minimumTriangles` (default 20000) triangles and can take them; parts with the same geometry share one set. It returns `parts` itself for a scene under the density. It is not applied by itself, and it takes seconds on a million triangles, so call it once while loading. On the Monster scene (1.6 million triangles, 1280 by 720, 4 samples) called with the canvas size, the frame went from 5.8 to 1.9 ms, and Lone Monk (5.6 million) from 15.4 to 9.5 ms (measured before the error metric was changed to a distance); the picture changes slightly (root mean square 2.0 of 255), because far parts draw from coarser levels (#1163).
A scene file (`scene.json`, rendered by `scripts/render-media.mjs --scene file`) gets the same levels by default; `"renderer": { "denseLods": false }` keeps every triangle of a dense scan. With the option on, `partsForRendererOptions` in `src/dense-lods.js` calls `addLodsToDenseParts` at the canvas size and pixel ratio before the renderer is built (#1163).
+
+`npm run bench:scene-frames -- <scene directory> [<scene directory>...]` renders each scene file's own camera at 320 by 180 and exits 1 when the frame is nearly one colour (mean luminance step between neighbouring pixels under 1 of 255). A camera behind a wall gave Lone Monk a white frame that no timing or RMSE could use (0.32 flat; the other benchmark scenes measure 2.4 to 7.8), and the same check flags the Barbershop scene (#2158). The detector is `bench/scene-frames/uniform-frame.mjs`.
diff --git a/package.json b/package.json
index e45f3a17..202fbaa4 100644
--- a/package.json
+++ b/package.json
@@ -239,6 +239,7 @@
"smoke:agent-branches": "node scripts/smoke-agent-branches.mjs",
"parity": "node scripts/parity-report.mjs",
"bench:agent": "node bench/agent-modeling/bench.mjs",
+ "bench:scene-frames": "node bench/scene-frames/check-default-cameras.mjs",
"reference": "node bench/reference/run.mjs",
"reference:line-art": "node bench/reference/line-art.mjs",
"size": "node scripts/measure-size.mjs",
diff --git a/tests/uniform-frame.test.js b/tests/uniform-frame.test.js
new file mode 100644
index 00000000..eef3e323
--- /dev/null
+++ b/tests/uniform-frame.test.js
@@ -0,0 +1,46 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { isNearUniformFrame, meanLuminanceStep } from '../bench/scene-frames/uniform-frame.mjs';
+
+const WIDTH = 8;
+const HEIGHT = 8;
+
+function filled(channels, value) {
+ return new Uint8Array(WIDTH * HEIGHT * channels).fill(value);
+}
+
+test('a flat white frame has no luminance steps and counts as uniform', () => {
+ const white = filled(4, 255);
+ assert.ok(meanLuminanceStep(white, 4, WIDTH) < 1e-3);
+ assert.equal(isNearUniformFrame(white, 4, WIDTH), true);
+});
+
+test('a smooth gradient counts as uniform: its steps are tiny although its values differ across the frame', () => {
+ const pixels = new Uint8Array(WIDTH * HEIGHT * 3);
+ for (let pixel = 0; pixel < WIDTH * HEIGHT; pixel++) {
+ const column = pixel % WIDTH;
+ pixels.fill(255 - Math.abs(column - 3.5) * 2, pixel * 3, pixel * 3 + 3);
+ }
+ assert.equal(isNearUniformFrame(pixels, 3, WIDTH), true);
+});
+
+test('a frame with a dark and a bright half has detail', () => {
+ const pixels = filled(3, 30);
+ pixels.fill(220, (WIDTH * HEIGHT * 3) / 2);
+ assert.ok(meanLuminanceStep(pixels, 3, WIDTH) > 1);
+ assert.equal(isNearUniformFrame(pixels, 3, WIDTH), false);
+});
+
+test('a checkerboard has detail', () => {
+ const pixels = new Uint8Array(WIDTH * HEIGHT * 3);
+ for (let pixel = 0; pixel < WIDTH * HEIGHT; pixel++) {
+ pixels.fill((pixel + Math.floor(pixel / WIDTH)) % 2 === 0 ? 20 : 230, pixel * 3, pixel * 3 + 3);
+ }
+ assert.equal(isNearUniformFrame(pixels, 3, WIDTH), false);
+});
+
+test('bad input says what to pass', () => {
+ assert.throws(() => meanLuminanceStep(new Uint8Array(64), 2, WIDTH), /3 or 4 channels/);
+ assert.throws(() => meanLuminanceStep(new Uint8Array(64), 4, 1), /frame width/);
+ assert.throws(() => meanLuminanceStep(new Uint8Array(8), 4, WIDTH), /two rows/);
+});