Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Warn on empty frame, subject out of frame, clipped exposure and stale bake (#652)

Nguyen Xuan An27385df27cde
diff --git a/changes/652.md b/changes/652.md
new file mode 100644
index 00000000..a8a12554
--- /dev/null
+++ b/changes/652.md
@@ -0,0 +1 @@
+- scene_review, scene_look and the render result warn, with a field and a value to try, on an empty frame (`empty-frame`), a subject out of frame or too small (`subject-out-of-frame`, `subject-too-small`), a black or clipped frame (`exposure-black`, `exposure-clipped`) and a bake that no longer matches the lights or parts drawn (`bake-stale`, after a motion seek moves a light or a part). They arrive in the frame's `diagnostics`, and a render job keeps one entry per warning in its result metrics (#652, #603)
diff --git a/changes/652.size.md b/changes/652.size.md
new file mode 100644
index 00000000..db544436
--- /dev/null
+++ b/changes/652.size.md
@@ -0,0 +1,3 @@
+- scene:agent-scene: worldBounds and bakeStaleness (277 bytes gzip) let the preview tell an agent that a frame is empty, framed wrong or lit by a stale bake, which it otherwise finds only by reading the image.
+- scene:agent-scene+lazy: the checks, the fingerprint and the stale-bake comparison (742 bytes gzip in all, most of it in the lazy bake module) are the same agent-facing diagnostics.
+- goal:agent-scene: 277 bytes for two small scene reads that frame, stale-bake and empty-frame warnings need; the sphere and luminance math sits outside the scene bundle.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 7b759791..db16404b 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -28,6 +28,7 @@ import { parseCube } from '../src/view-transform.js';
import { weightTracksFromGltfAnimation } from '../src/export-skeleton.js';
import { clipFromGltfAnimation } from '../src/skeleton-pose.js';
import { sessionProblem } from '../src/agent-errors.js';
+import { framingProblems, exposureProblems, lumaShares } from '../src/frame-checks.js';
import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../src/agent-branches.js';
import { agentAssetDecodeOptions, withCatalogLimitAdvice } from '../src/agent-asset-limits.js';
import { sceneQueryFor, summarizeWalkMap, walkOptionsFor, createQueryOnlyCache } from './agent-walkmap.js';
@@ -83,7 +84,32 @@ function candidateCamera(record, operations) {
return createAgentScene({ format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [], camera }).camera;
}
-function renderInfo(renderer) {
+const EXPOSURE_PROBE_SIZE = 64;
+let exposureProbe;
+
+/** Luma shares of a 64 by 64 copy of the frame just drawn; the copy is a read of the drawing buffer, so call it in the draw's task. */
+function sampleFrameShares() {
+ exposureProbe ??= Object.assign(document.createElement('canvas'), { width: EXPOSURE_PROBE_SIZE, height: EXPOSURE_PROBE_SIZE });
+ const context = exposureProbe.getContext('2d', { willReadFrequently: true });
+ context.drawImage(canvas, 0, 0, EXPOSURE_PROBE_SIZE, EXPOSURE_PROBE_SIZE);
+ return lumaShares(context.getImageData(0, 0, EXPOSURE_PROBE_SIZE, EXPOSURE_PROBE_SIZE).data);
+}
+
+/**
+ * Warnings about the frame just drawn from `camera`: framing, a stale bake and exposure (when `exposure` is given, the
+ * effects.exposure drawn with). Imported assets have no part bounds or bake, so they get the exposure check only.
+ */
+function viewProblems(record, camera, exposure) {
+ const problems = [];
+ const boxes = record.scene.worldBounds?.();
+ if (boxes) problems.push(...framingProblems({ camera, aspect: canvas.width / canvas.height, boxes }));
+ if (record.scene.bakeStaleness) problems.push(...record.scene.bakeStaleness());
+ if (exposure !== undefined) problems.push(...exposureProblems({ shares: sampleFrameShares(), exposure }));
+ return problems;
+}
+
+function renderInfo(renderer, viewWarnings = []) {
+ const diagnostics = [...(renderer.diagnostics ?? []), ...viewWarnings];
const context = renderer.context;
const debug = context.getExtension('WEBGL_debug_renderer_info');
return {
@@ -100,7 +126,7 @@ function renderInfo(renderer) {
morphTextures: renderer.morphTextures?.size ?? 0,
gpuBuffers: renderer.buffers?.length ?? 0,
drawBatches: renderer.batches?.length ?? 0,
- ...(renderer.diagnostics?.length ? { diagnostics: renderer.diagnostics } : {}),
+ ...(diagnostics.length ? { diagnostics } : {}),
};
}
@@ -711,7 +737,7 @@ window.__agentPreview = {
geometries: [], materials: [], nodes: [], camera: { ...record.scene.camera, ...shot.camera } }).camera;
validatePreviewCamera(camera);
draw(record, shot.rendererTime, camera);
- const render = renderInfo(record.renderer);
+ const render = renderInfo(record.renderer, viewProblems(record, camera, record.scene.effects.exposure));
if (render.width < 64 || render.height < 64) throw new Error('Render budget reduced review below its minimum output size.');
const context = reviewGrid.getContext('2d');
const x = index % columns * width;
@@ -763,7 +789,7 @@ window.__agentPreview = {
},
// `pass` draws one render pass instead of the lit image. Object ID frames also list the part behind each ID.
// `camera` overrides camera fields and `depthOfField` the blur and focus distance (a timeline shot); `brightness` scales exposure for a dip through black.
- frame({ sessionId, animation, motionTime, rendererTime = 0, pass, passDepthRange, passFloat = false, floatOutput = false, camera: cameraOverrides, depthOfField: depthOfFieldOverrides, brightness = 1 }) {
+ frame({ sessionId, animation, motionTime, rendererTime = 0, pass, passDepthRange, passFloat = false, floatOutput = false, camera: cameraOverrides, depthOfField: depthOfFieldOverrides, brightness = 1, diagnose = false }) {
const record = requireSession(sessionId);
if (!Number.isFinite(brightness) || brightness < 0 || brightness > 1) throw new RangeError('Invalid frame brightness.');
if (!Number.isFinite(rendererTime) || rendererTime < 0 || rendererTime > 3600) throw new RangeError('Invalid render time.');
@@ -784,7 +810,9 @@ window.__agentPreview = {
const outputFramebuffer = floatOutput && !pass ? record.floatModule.outputFor(record, canvas).framebuffer : undefined;
draw(record, rendererTime, shotCamera, { pass, passDepthRange, passFloat, previousCamera, outputFramebuffer, ...(objectMotion ? { objectMotion } : {}),
...(brightness === 1 ? {} : { exposure }), ...(shotEffects ? { effects: shotEffects } : {}) });
- const info = renderInfo(record.renderer);
+ // The first lit frame of a job is checked; a pass or a fade has no exposure to judge.
+ const checkLitFrame = diagnose && !pass && !floatOutput && brightness === 1;
+ const info = renderInfo(record.renderer, pass ? [] : viewProblems(record, shotCamera ?? record.scene.camera, checkLitFrame ? record.scene.effects.exposure : undefined));
return pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() } : info;
},
// Reads the last frame as RGBA float32, rows bottom to top, cropped to `region` (pixels from the top left): the lit image
@@ -1012,7 +1040,7 @@ window.__agentPreview = {
record.scene.sampleMotion(motionTime);
}
draw(record);
- const render = renderInfo(record.renderer);
+ const render = renderInfo(record.renderer, viewProblems(record, record.scene.camera, record.scene.effects.exposure));
record.lastRender = render;
const labels = withLabels ? collectLabels(record, record.scene.camera, canvas.width, canvas.height) : undefined;
return {
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 04c421d0..ce189280 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -30,6 +30,7 @@ import { audioInputArguments, createAudioLibrary, measureStreamSeconds } from '.
import { filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline } from '../src/film-timeline.js';
import { isPreviewHost } from './preview-host.mjs';
import { normalizeReview, REVIEW_LIMITS } from './agent-review.mjs';
+import { mergeFrameDiagnostics } from '../src/frame-checks.js';
import { BRANCH_LIMITS, validateBranchName } from '../src/agent-branches.js';
import { sessionProblem } from '../src/agent-errors.js';
@@ -554,7 +555,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
window.__finishDraw();
const drawMilliseconds = performance.now() - drawStarted;
return { ...result, drawMilliseconds, pageEncoded: await window.__encodeFrame(encodeIndex) };
- }, { input: frameInput, encodeIndex: pageEncodes ? frame : null });
+ }, { input: { ...frameInput, diagnose: frame === 0 }, encodeIndex: pageEncodes ? frame : null });
const roundTripSeconds = (performance.now() - renderStarted) / 1000;
const drawSeconds = rendered.pageEncoded ? rendered.drawMilliseconds / 1000 : roundTripSeconds;
metrics.renderSeconds += drawSeconds;
@@ -564,6 +565,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
metrics.width = width;
metrics.height = height;
metrics.estimatedBytes = rendered.estimatedBytes;
+ mergeFrameDiagnostics(metrics, rendered.diagnostics);
async function captureFrameBytes() {
if (rendered.pageEncoded) {
signal.throwIfAborted();
diff --git a/src/agent-bake.js b/src/agent-bake.js
index 82581504..47c7e1d8 100644
--- a/src/agent-bake.js
+++ b/src/agent-bake.js
@@ -15,6 +15,43 @@ const PRESET_SAMPLES_FLOOR = 16;
const BAKE_FIELDS = ['preset', 'samples', 'bounces', 'texelsPerUnit', 'probes', 'irradianceGrid', 'gridFog'];
const BAKED_MATERIAL_FIELDS = ['emission', 'emissiveColor', 'emissiveMap', 'lightMap', 'lightMapScale', 'occlusionMap', 'occlusionStrength'];
+const MATRIX_TOLERANCE = 1e-4;
+const MAXIMUM_NAMED_PARTS = 3;
+
+function staleWarning(message, fix) {
+ return { kind: 'bake-stale', severity: 'warning', target: 'bake', message, fix };
+}
+
+/** A string that changes when a light, the sun or the key color changes: the lights a bake lit the scene with. */
+export function lightsFingerprint(environment) {
+ const { pointLights, spotLights, areaLights, keyColor, keyIntensity, lightDirection, keyAffects } = environment;
+ return JSON.stringify([pointLights, spotLights, areaLights, keyColor, keyIntensity, lightDirection, keyAffects]);
+}
+
+/**
+ * Warnings when what is drawn is no longer what the bake lit: `baked` holds the lights fingerprint and part matrices from
+ * the bake, `current` the sampled environment and the matrices of the parts now (a motion seek moves both).
+ */
+export function staleBakeProblems({ baked, current }) {
+ const problems = [];
+ if (lightsFingerprint(current.environment) !== baked.lightsFingerprint) {
+ problems.push(staleWarning('A light or the sun has moved or changed since the bake, but baked light does not follow it.',
+ 'Set motionTime to null to draw the rest pose the bake lit, or remove the light motion tracks, or remove bake and use live lights.'));
+ }
+ const moved = [];
+ for (const [name, matrix] of current.matrices) {
+ const bakedMatrix = baked.matrices.get(name);
+ if (bakedMatrix && matrix.some((value, index) => Math.abs(value - bakedMatrix[index]) > MATRIX_TOLERANCE)) moved.push(name);
+ }
+ if (moved.length) {
+ const named = moved.slice(0, MAXIMUM_NAMED_PARTS).join(', ');
+ const rest = moved.length > MAXIMUM_NAMED_PARTS ? ` and ${moved.length - MAXIMUM_NAMED_PARTS} more` : '';
+ problems.push(staleWarning(`${named}${rest} moved since the bake, so their baked light and shadows stay where they were.`,
+ 'Set motionTime to null for the rest pose, remove the motion tracks that move them, or remove bake and use live lights.'));
+ }
+ return problems;
+}
+
/** Validates a recipe bake section and returns the plain, resolved form stored in the recipe (null clears it). */
export function normalizeAgentBake(input) {
if (input === null || input === undefined) {
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 65ecb327..b6884c4c 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1296,6 +1296,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
sourceRestParts,
parts: restParts, restParts,
bakeReport: lightBakeResult ? { ...lightBakeResult.report, reused: lightBakeResult.reused } : null,
+ bakeInputs: lightBakeResult ? lightBakeResult.inputs : null,
reflectionReport: reflected ? reflected.report : null,
// A renderer holding the deformed cloth parts of the old state needs the rest parts back as a topology change.
topologyChanged: Boolean(state && (restParts !== state.restParts || state.parts !== state.restParts)),
@@ -1357,8 +1358,10 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
if (lightBake?.key === key && lightBake.sourceRestParts === sourceRestParts) {
return { ...lightBake, reused: true };
}
- const baked = agentSceneModule('bake').bakeAgentParts(sourceRestParts, worldMatrices, recipe.environment, recipe.bake, generatedGeometryGenerators);
- lightBake = { key, sourceRestParts, parts: baked.parts, report: baked.report };
+ const bakeModule = agentSceneModule('bake');
+ const baked = bakeModule.bakeAgentParts(sourceRestParts, worldMatrices, recipe.environment, recipe.bake, generatedGeometryGenerators);
+ lightBake = { key, sourceRestParts, parts: baked.parts, report: baked.report,
+ inputs: { lightsFingerprint: bakeModule.lightsFingerprint(recipe.environment), matrices: worldMatrices } };
return { ...lightBake, reused: false };
}
@@ -1528,6 +1531,29 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
const environment = structuredClone(state.recipe.environment);
return state.movedLook ?agentSceneModule('motion').motionEnvironment(environment, state.movedLook) : environment;
},
+ /** World bounds ({ name, min, max }) of the visible mesh parts in the current pose; parts with no known bounds are left out. */
+ worldBounds() {
+ const bounds = [];
+ // A bake or a skin replaces a drawn part's geometry, so the bounds come from the part as built, in the drawn pose.
+ const drawnParts = new Map(state.restParts.map(part => [part.name, part]));
+ for (const sourcePart of state.sourceRestParts) {
+ const part = drawnParts.get(sourcePart.name);
+ const local = state.localBounds.get(sourcePart.geometry);
+ if (!part || !local || part.visibility?.visible === false) continue;
+ const positions = [];
+ for (let corner = 0; corner < 8; corner++) {
+ positions.push(corner & 1 ? local.max[0] : local.min[0], corner & 2 ? local.max[1] : local.min[1], corner & 4 ? local.max[2] : local.min[2]);
+ }
+ bounds.push({ name: part.name, ...boundsFor({ positions }, part.matrix) });
+ }
+ return bounds;
+ },
+ /** Warnings when the sampled lights or part poses no longer match what the last bake lit; empty without a bake. */
+ bakeStaleness() {
+ if (!state.bakeInputs) return [];
+ const matrices = new Map(state.restParts.map(part => [part.name, part.matrix]));
+ return agentSceneModule('bake').staleBakeProblems({ baked: state.bakeInputs, current: { environment: this.environment, matrices } });
+ },
get postPasses() {
return structuredClone(state.recipe.postPasses ?? []);
},
diff --git a/src/frame-checks.js b/src/frame-checks.js
new file mode 100644
index 00000000..cfe0ec20
--- /dev/null
+++ b/src/frame-checks.js
@@ -0,0 +1,149 @@
+/**
+ * Cheap checks on a frame that renders without error but shows nothing useful: an empty frame, a subject out of frame
+ * or too small, and clipped or black exposure. They use the shape of `agent-diagnostics.js` (kind, severity, target,
+ * message, fix); each fix names a field and a value to try. Framing is sphere-against-frustum math on part bounds and
+ * exposure reads a 64 by 64 copy of the frame. The stale bake check lives in `agent-bake.js`, which loads with a bake.
+ */
+const TINY_SUBJECT_RATIO = 0.05;
+const BLACK_LUMA = 5 / 255;
+const WHITE_LUMA = 250 / 255;
+const BLACK_FRAME_SHARE = 0.98;
+const CLIPPED_FRAME_SHARE = 0.35;
+
+function warning(kind, target, message, fix) {
+ return { kind, severity: 'warning', target, message, fix };
+}
+
+function subtract(first, second) {
+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];
+}
+
+function dot(first, second) {
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
+}
+
+function cross(first, second) {
+ return [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];
+}
+
+function normalize(vector) {
+ const length = Math.hypot(...vector) || 1;
+ return vector.map(component => component / length);
+}
+
+function round(value) {
+ return Math.round(value * 100) / 100;
+}
+
+/** Half the vertical field of view as a tangent, or null for a camera these checks do not model. */
+function halfHeightTangent(camera, aspect) {
+ if (camera.projection === 'orthographic' || camera.shift) return null;
+ if (Number.isFinite(camera.fov)) return Math.tan(camera.fov * Math.PI / 360);
+ if (Number.isFinite(camera.focalLength)) return (camera.sensorWidth ?? 36) / aspect / 2 / camera.focalLength;
+ return null;
+}
+
+function sphereOf(box) {
+ const center = [0, 1, 2].map(axis => (box.min[axis] + box.max[axis]) / 2);
+ return { center, radius: Math.hypot(...subtract(box.max, center)) };
+}
+
+function unionOf(boxes) {
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (const box of boxes) {
+ for (let axis = 0; axis < 3; axis++) {
+ min[axis] = Math.min(min[axis], box.min[axis]);
+ max[axis] = Math.max(max[axis], box.max[axis]);
+ }
+ }
+ return { min, max };
+}
+
+/** A camera that keeps the viewing direction, aims at the middle of the boxes and backs off until they fit. */
+function framingSuggestion(camera, boxes, tangent) {
+ const { center, radius } = sphereOf(unionOf(boxes));
+ const direction = normalize(subtract(camera.eye, camera.target));
+ const distance = Math.max(radius / tangent * 1.15, camera.near * 2);
+ const eye = center.map((value, axis) => value + direction[axis] * distance);
+ return `Set camera.target to [${center.map(round)}] and camera.eye to [${eye.map(round)}]`;
+}
+
+/**
+ * Warnings for where the camera points. `boxes` are world bounds ({ min, max }) of the visible parts; a camera that is
+ * orthographic or shifted gets none, because the frustum test below assumes a centered perspective view.
+ */
+export function framingProblems({ camera, aspect, boxes }) {
+ const tangent = halfHeightTangent(camera, aspect);
+ if (!tangent) return [];
+ if (boxes.length === 0) {
+ return [warning('empty-frame', 'nodes', 'The scene has no visible parts, so the frame shows only the background.',
+ 'Add a mesh node with scene_apply add-node (and add-geometry, add-material), or set visible: true on a hidden node.')];
+ }
+ const tangentWide = tangent * aspect;
+ const forward = normalize(subtract(camera.target, camera.eye));
+ const right = normalize(cross(forward, camera.up));
+ const upward = cross(right, forward);
+ const sideScale = Math.sqrt(1 + tangent * tangent);
+ const wideScale = Math.sqrt(1 + tangentWide * tangentWide);
+ const visibleBoxes = boxes.filter(box => {
+ const { center, radius } = sphereOf(box);
+ const offset = subtract(center, camera.eye);
+ const depth = dot(offset, forward);
+ if (depth + radius < camera.near || depth - radius > camera.far) return false;
+ const sideways = (Math.abs(dot(offset, right)) - tangentWide * depth) / wideScale;
+ const vertical = (Math.abs(dot(offset, upward)) - tangent * depth) / sideScale;
+ return sideways <= radius && vertical <= radius;
+ });
+ if (visibleBoxes.length * 2 < boxes.length) {
+ return [warning('subject-out-of-frame', 'camera',
+ `${boxes.length - visibleBoxes.length} of ${boxes.length} parts are outside the camera frustum.`,
+ `${framingSuggestion(camera, boxes, tangent)} to put every part in view.`)];
+ }
+ const { center, radius } = sphereOf(unionOf(visibleBoxes));
+ const depth = dot(subtract(center, camera.eye), forward);
+ if (depth > 0 && radius / (depth * tangent) < TINY_SUBJECT_RATIO) {
+ return [warning('subject-too-small', 'camera',
+ `The visible parts fill under ${Math.round(TINY_SUBJECT_RATIO * 100)} percent of the frame height.`,
+ `${framingSuggestion(camera, visibleBoxes, tangent)} to fill the frame, or lower camera.fov.`)];
+ }
+ return [];
+}
+
+/** The share of pixels near black and near white in RGBA bytes, by Rec. 709 luma. */
+export function lumaShares(rgba) {
+ let black = 0;
+ let white = 0;
+ const pixels = rgba.length / 4;
+ for (let offset = 0; offset < rgba.length; offset += 4) {
+ const luma = (0.2126 * rgba[offset] + 0.7152 * rgba[offset + 1] + 0.0722 * rgba[offset + 2]) / 255;
+ if (luma <= BLACK_LUMA) black++;
+ else if (luma >= WHITE_LUMA) white++;
+ }
+ return { black: black / pixels, white: white / pixels };
+}
+
+/** Warnings for a frame that is nearly all black or has a large clipped area; `exposure` is the current effects.exposure. */
+export function exposureProblems({ shares, exposure }) {
+ if (shares.black >= BLACK_FRAME_SHARE) {
+ return [warning('exposure-black', 'effects.exposure',
+ `${Math.round(shares.black * 100)} percent of the frame is black after tone mapping.`,
+ `Raise effects.exposure from ${exposure} to ${round(Math.max(exposure, 0.25) * 4)}, raise environment.keyIntensity, or aim a light at the subject.`)];
+ }
+ if (shares.white >= CLIPPED_FRAME_SHARE) {
+ return [warning('exposure-clipped', 'effects.exposure',
+ `${Math.round(shares.white * 100)} percent of the frame is clipped to white after tone mapping.`,
+ `Lower effects.exposure from ${exposure} to ${round(exposure / 2)}, or lower environment.keyIntensity.`)];
+ }
+ return [];
+}
+
+/** Adds a frame's diagnostics to `metrics.diagnostics`, keeping one entry per kind, target and message across a job's frames. */
+export function mergeFrameDiagnostics(metrics, frameDiagnostics) {
+ if (!frameDiagnostics?.length) return;
+ metrics.diagnostics ??= [];
+ for (const problem of frameDiagnostics) {
+ const known = metrics.diagnostics.some(entry => entry.kind === problem.kind && entry.target === problem.target && entry.message === problem.message);
+ if (!known) metrics.diagnostics.push(problem);
+ }
+}
diff --git a/tests/frame-checks.test.js b/tests/frame-checks.test.js
new file mode 100644
index 00000000..c240d329
--- /dev/null
+++ b/tests/frame-checks.test.js
@@ -0,0 +1,114 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createAgentScene } from '../src/agent-scene.js';
+import { exposureProblems, framingProblems, lumaShares, mergeFrameDiagnostics } from '../src/frame-checks.js';
+import { closedRoom, closedRoomWithoutBake } from './support/agent-bake-rooms.mjs';
+
+function sceneWithCamera(camera) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }],
+ materials: [{ id: 'red', color: [0.8, 0.2, 0.2] }],
+ nodes: [{ id: 'cube', geometry: 'box', material: 'red' }],
+ camera,
+ };
+}
+
+function framingOf(recipe) {
+ const scene = createAgentScene(recipe);
+ return framingProblems({ camera: scene.camera, aspect: 1, boxes: scene.worldBounds() });
+}
+
+function kinds(problems) {
+ return problems.map(problem => problem.kind);
+}
+
+test('a subject in view gives no framing warning', () => {
+ assert.deepEqual(framingOf(sceneWithCamera({ eye: [3, 2, 4], target: [0, 0, 0], fov: 45 })), []);
+ assert.deepEqual(framingOf(closedRoom()), []);
+});
+
+test('a scene with no parts is an empty frame and says what to add', () => {
+ const problems = framingOf({ ...sceneWithCamera({}), nodes: [] });
+ assert.deepEqual(kinds(problems), ['empty-frame']);
+ assert.match(problems[0].fix, /add-node/);
+});
+
+test('a camera that looks away from the subject names a camera.target and camera.eye that frame it', () => {
+ const problems = framingOf(sceneWithCamera({ eye: [3, 2, 4], target: [30, 2, -40], fov: 45 }));
+ assert.deepEqual(kinds(problems), ['subject-out-of-frame']);
+ assert.match(problems[0].fix, /camera\.target to \[0,0,0\].*camera\.eye to \[/);
+});
+
+test('a subject far away fills so little of the frame that it is called too small', () => {
+ const problems = framingOf(sceneWithCamera({ eye: [0, 0, 400], target: [0, 0, 0], fov: 45, far: 2000 }));
+ assert.deepEqual(kinds(problems), ['subject-too-small']);
+});
+
+test('hidden parts do not count and orthographic cameras are not judged', () => {
+ const hidden = sceneWithCamera({ eye: [3, 2, 4], target: [0, 0, 0] });
+ hidden.nodes[0].visible = false;
+ assert.deepEqual(kinds(framingOf(hidden)), ['empty-frame']);
+ assert.deepEqual(framingOf(sceneWithCamera({ eye: [3, 2, 4], target: [30, 2, -40], projection: 'orthographic' })), []);
+});
+
+function frameOf(luma, count = 100) {
+ return new Uint8Array(count * 4).fill(luma);
+}
+
+test('exposure warns on a black or clipped frame and not on a normal one', () => {
+ const black = exposureProblems({ shares: lumaShares(frameOf(0)), exposure: 1 });
+ assert.deepEqual(kinds(black), ['exposure-black']);
+ assert.match(black[0].fix, /effects\.exposure from 1 to 4/);
+ const white = exposureProblems({ shares: lumaShares(frameOf(255)), exposure: 1 });
+ assert.deepEqual(kinds(white), ['exposure-clipped']);
+ assert.match(white[0].fix, /effects\.exposure from 1 to 0\.5/);
+ assert.deepEqual(exposureProblems({ shares: lumaShares(frameOf(120)), exposure: 1 }), []);
+ const mostlyMid = frameOf(120);
+ mostlyMid.fill(255, 0, 40);
+ assert.deepEqual(exposureProblems({ shares: lumaShares(mostlyMid), exposure: 1 }), []);
+});
+
+function lightMoves() {
+ return closedRoom({ motion: { duration: 2, loop: false, tracks: [
+ { kind: 'light', id: 'point:0', property: 'position', keyframes: [{ time: 0, value: [0, 2.7, 0] }, { time: 2, value: [1, 2.7, 0] }] },
+ ] } });
+}
+
+test('an unchanged baked scene gives no stale warning at the rest pose', () => {
+ assert.deepEqual(createAgentScene(closedRoom()).bakeStaleness(), []);
+ const scene = createAgentScene(lightMoves());
+ scene.sampleMotion(0);
+ assert.deepEqual(scene.bakeStaleness(), []);
+ assert.deepEqual(createAgentScene(closedRoomWithoutBake()).bakeStaleness(), []);
+});
+
+test('moving a light after a bake gives bake-stale with the fix', () => {
+ const scene = createAgentScene(lightMoves());
+ scene.sampleMotion(2);
+ const problems = scene.bakeStaleness();
+ assert.deepEqual(kinds(problems), ['bake-stale']);
+ assert.match(problems[0].fix, /motionTime to null/);
+ scene.sampleMotion(null);
+ assert.deepEqual(scene.bakeStaleness(), []);
+});
+
+test('moving a part after a bake names the part', () => {
+ const scene = createAgentScene(closedRoom({ motion: { duration: 2, loop: false, tracks: [
+ { kind: 'node', id: 'block', property: 'translation', keyframes: [{ time: 0, value: [-0.7, 0.6, -0.4] }, { time: 2, value: [0.5, 0.6, -0.4] }] },
+ ] } }));
+ scene.sampleMotion(2);
+ const problems = scene.bakeStaleness();
+ assert.deepEqual(kinds(problems), ['bake-stale']);
+ assert.match(problems[0].message, /block moved/);
+});
+
+test('job metrics keep one entry per warning across frames', () => {
+ const metrics = {};
+ const warning = { kind: 'exposure-black', target: 'effects.exposure', message: 'm', fix: 'f' };
+ mergeFrameDiagnostics(metrics, [warning]);
+ mergeFrameDiagnostics(metrics, [{ ...warning }]);
+ mergeFrameDiagnostics(metrics, undefined);
+ assert.equal(metrics.diagnostics.length, 1);
+});
diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjs
index 20d1228c..cf640d81 100644
--- a/tests/support/preview-harness.mjs
+++ b/tests/support/preview-harness.mjs
@@ -13,6 +13,7 @@ import { hasPatternTextures } from '../../scripts/agent-preview-textures.js';
import { assetCopyKey, recipeAssetNeeds } from '../../src/agent-scene-assets.js';
import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../../src/agent-branches.js';
import { sessionProblem } from '../../src/agent-errors.js';
+import { framingProblems, exposureProblems, lumaShares } from '../../src/frame-checks.js';
import { agentAssetDecodeOptions, withCatalogLimitAdvice } from '../../src/agent-asset-limits.js';
import { sceneQueryFor, summarizeWalkMap, walkOptionsFor, createQueryOnlyCache } from '../../scripts/agent-walkmap.js';
@@ -30,8 +31,9 @@ export function previewHarness() {
const tiles = [];
const makeCanvas = () => ({ width: 768, height: 512,
replaceWith() {}, toDataURL: () => 'data:image/png;base64,cG5n',
- getContext: kind => kind === '2d' ? { fillRect() {}, fillText() {}, strokeText() {},
- drawImage: () => tiles.push(renders.at(-1)) } : { getExtension: () => null } });
+ getContext(kind) { const target = this; return kind === '2d' ? { fillRect() {}, fillText() {}, strokeText() {},
+ drawImage: () => { if (target.width !== 64) tiles.push(renders.at(-1)); },
+ getImageData: (x, y, width, height) => ({ data: new Uint8ClampedArray(width * height * 4).fill(128) }) } : { getExtension: () => null }; } });
const canvas = makeCanvas();
class FaultInjectedRenderer {
memoryPlan = { estimatedBytes: 1024 };
@@ -79,7 +81,7 @@ export function previewHarness() {
// The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.
setManifoldModuleLoader: () => {},
needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},
- sceneQueryFor, summarizeWalkMap, walkOptionsFor, createQueryOnlyCache, parseGltf, hasPatternTextures, Uint8Array, atob, sessionProblem, assetCopyKey, recipeAssetNeeds, agentAssetDecodeOptions, withCatalogLimitAdvice,
+ sceneQueryFor, summarizeWalkMap, walkOptionsFor, createQueryOnlyCache, parseGltf, hasPatternTextures, Uint8Array, atob, sessionProblem, framingProblems, exposureProblems, lumaShares, assetCopyKey, recipeAssetNeeds, agentAssetDecodeOptions, withCatalogLimitAdvice,
applyProjection, applyCameraFields, mat4, resolveAgentShadow, agentEnvironmentMap, BRANCH_LIMITS,
// Line art needs a real renderer with render passes, so the fault-injected one gets a no-op install.
agentSceneModule: name => (name === 'lineArt' ? { installLineArt: renderer => renderer } : name === 'userPass' ? { ...agentSceneModule(name), installUserPasses: renderer => renderer } : agentSceneModule(name)), agentSceneModuleLoaded, createBranchStore, printableLabel,