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.

Make kiln_render shots fast on large assets (#339)

Matthew Kissinger8b9e62804f50
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7285677e..cb934d0e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,26 @@ does not publish a package.
## Unreleased
+- `kiln_render` and `kiln_edit` draw `shots` that change only the camera from the artifact itself, in one
+ request per projection and service limit, after asking the capture cache. On a 2.6M-triangle cathedral on
+ Node 22.23.4, nine shots at 1000 px on a built program went from 301 s to 7.1 s, all nine cached from
+ 260 s to 4.2 s, and one shot from 42 s to 3.6 s. Same-camera images differ by at most one level per
+ channel. A shot that changes what draws (`visibility: 'isolate'`, `hide`, or a subject in a lower level
+ of detail) keeps a derivative for that shot, which now skips the QA, validator, metrics and manifest
+ work that derivative discarded (9.1 s to 2.5 s for one isolated shot). `kiln_inspect` shots stay on the
+ derivative route. Results change where they report this: `derivativeReceipts[].inputGlbSha256` of a
+ camera-only shot is the artifact's hash, its compact receipt can omit the hash when `viewFidelity` already
+ states it, a receipt on a host with no retained artifact reads `reasonCodes: ['IN_LOOP_BUILD_NOT_PERSISTED']`,
+ and on a host with one `viewFidelity.exactArtifact` is true when every shot was exact. `./render` exports
+ `renderReviewDerivativeGlb`.
+- Camera bounds, GLB accessor decode and the integration manifest allocate and read less on large
+ assets: bounds no longer build a record per triangle, unnormalized accessors copy directly, and
+ `drawnSceneBounds` visits each referenced vertex once per placement. Cameras, review geometry, bounds and
+ the manifest are byte-identical on the cathedral.
+- `output: 'separate'` is no longer charged for a grid sheet it never builds, and a refused capture states the
+ shots, the size and the largest size that fits as a grid and as separate images.
+- A missing evaluator worker file now names the rebuild instead of `Evaluator worker pipe failed.`, and
+ Windows' `EOF` on the worker pipe waits for the worker to close like `EPIPE`.
- GPU instancing now draws what the copies drew as separate nodes, in both `KILN_BAKE_INSTANCE` and the
three runtime target's `repeatInstances`. A mirrored copy no longer shares a batch with unmirrored ones,
where it drew inside out: single-sided surfaces vanished. Mirrored copies form their own batch on a node
diff --git a/docs/cameras.md b/docs/cameras.md
index 25a73781..79a6b9da 100644
--- a/docs/cameras.md
+++ b/docs/cameras.md
@@ -77,7 +77,9 @@ Without `near`, an explicit perspective camera sets its near plane to half the d
An unknown camera key fails with the accepted keys, for example `fov` names `fovDeg`. `kiln_discover` with `capabilities:true` lists the lens and clip fields under `camera`. A subject name that matches several nodes fails with every matching path. A name that matches none suggests similar names before listing paths.
-The versioned format uses `shots`, not legacy `preset/cells`. Unknown or conflicting controls fail instead of being silently ignored. Cell size is an integer from 128 to 2048; the capture pixel budget (24M pixels by default) bounds the whole sheet, so nine 2048 px shots are refused. Set `output:"separate"` to return one image per shot; omit it for a grid. Both deliveries preserve shot order and camera metadata.
+The versioned format uses `shots`, not legacy `preset/cells`. Unknown or conflicting controls fail instead of being silently ignored. Cell size is an integer from 128 to 2048; the capture pixel budget (24M pixels by default) bounds the whole sheet, so nine 2048 px shots are refused, and the refusal names the largest size that fits. Set `output:"separate"` to return one image per shot; no sheet is built or charged to the budget then. Omit it for a grid. Both deliveries preserve shot order and camera metadata.
+
+Shots that change only the camera are drawn from the artifact itself, together for each projection, so a capture of many shots costs little more than one and each view already drawn answers from the capture cache. A shot that changes what draws (`visibility:"isolate"`, `hide`, or a subject in a lower level of detail) is drawn from a review GLB built for that shot and takes longer on a large asset.
`size` is the square pixel size of each shot. There are no capture request fields named `width` or `height`; those names occur only in returned grid/image dimensions. Orbit cameras likewise have no `target` or `distance` fields: they derive both from the selected subject's bounds. Select the subject and use `padding` to pull back or crop in. When an exact position or look target matters, use an explicit camera with `position` and `target`.
diff --git a/src/__tests__/drawn-scene-bounds.test.ts b/src/__tests__/drawn-scene-bounds.test.ts
new file mode 100644
index 00000000..de72f06e
--- /dev/null
+++ b/src/__tests__/drawn-scene-bounds.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, spyOn, test } from 'bun:test';
+import { Accessor, Document } from '@gltf-transform/core';
+import { EXTMeshGPUInstancing, KHRNodeVisibility } from '@gltf-transform/extensions';
+import { drawnSceneBounds } from '../node-visibility';
+
+const POSITIONS = [0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 100, 100, 100];
+
+function part(doc: Document, positions: Accessor, indices?: number[]) {
+ const buffer = doc.getRoot().listBuffers()[0]!;
+ const primitive = doc.createPrimitive().setAttribute('POSITION', positions);
+ if (indices)
+ primitive.setIndices(
+ doc.createAccessor().setType('SCALAR').setArray(new Uint16Array(indices)).setBuffer(buffer),
+ );
+ return doc.createMesh().addPrimitive(primitive);
+}
+
+function fixture() {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const positions = doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array(POSITIONS))
+ .setBuffer(buffer);
+ const scene = doc.createScene();
+ doc.getRoot().setDefaultScene(scene);
+ return { doc, buffer, positions, scene };
+}
+
+describe('drawnSceneBounds', () => {
+ test('counts referenced vertices only and reads the stored array directly', () => {
+ const { doc, positions, scene } = fixture();
+ // Vertex 4 sits at (100,100,100) and no triangle uses it; repeats add nothing.
+ scene.addChild(doc.createNode().setMesh(part(doc, positions, [0, 1, 2, 2, 1, 3, 0, 1, 2])));
+ const spy = spyOn(Accessor.prototype, 'getElement');
+ try {
+ expect(drawnSceneBounds(scene)).toEqual({ min: [0, 0, 0], max: [1, 2, 3] });
+ expect(spy).not.toHaveBeenCalled();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ test('an unindexed primitive counts every vertex', () => {
+ const { doc, positions, scene } = fixture();
+ scene.addChild(doc.createNode().setMesh(part(doc, positions)));
+ expect(drawnSceneBounds(scene)).toEqual({ min: [0, 0, 0], max: [100, 100, 100] });
+ });
+
+ test('rotation stays tight, hidden subtrees are left out, every instance is placed', () => {
+ const { doc, buffer, positions, scene } = fixture();
+ const quarterTurnZ = [0, 0, Math.SQRT1_2, Math.SQRT1_2] as [number, number, number, number];
+ const parent = doc.createNode().setRotation(quarterTurnZ).setTranslation([10, 0, 0]);
+ parent.addChild(doc.createNode().setMesh(part(doc, positions, [0, 1, 2])));
+ scene.addChild(parent);
+
+ const visibility = doc.createExtension(KHRNodeVisibility);
+ const hidden = doc.createNode().setMesh(part(doc, positions, [4, 0, 1]));
+ hidden.setExtension('KHR_node_visibility', visibility.createVisibility().setVisible(false));
+ scene.addChild(hidden);
+
+ const instancing = doc.createExtension(EXTMeshGPUInstancing);
+ const placed = doc.createNode().setMesh(part(doc, positions, [0, 1, 2]));
+ placed.setExtension(
+ 'EXT_mesh_gpu_instancing',
+ instancing.createInstancedMesh().setAttribute(
+ 'TRANSLATION',
+ doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 50, 0, 0, -50]))
+ .setBuffer(buffer),
+ ),
+ );
+ scene.addChild(placed);
+
+ const { min, max } = drawnSceneBounds(scene);
+ // The rotated part runs from x 8 to 10 and y 0 to 1; instances span z -50 to 50.
+ expect(min[0]!).toBeCloseTo(0, 5);
+ expect(max[0]!).toBeCloseTo(10, 5);
+ expect(min[1]!).toBeCloseTo(0, 5);
+ expect(max[1]!).toBeCloseTo(2, 5);
+ expect(min[2]!).toBeCloseTo(-50, 5);
+ expect(max[2]!).toBeCloseTo(50, 5);
+ });
+
+ test('normalized positions decode through the accessor', () => {
+ const { doc, buffer, scene } = fixture();
+ const quantized = doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Int16Array([0, 0, 0, 32767, 0, 0, 0, 16384, 0]))
+ .setNormalized(true)
+ .setBuffer(buffer);
+ scene.addChild(doc.createNode().setMesh(part(doc, quantized, [0, 1, 2])));
+ const { min, max } = drawnSceneBounds(scene);
+ expect(min).toEqual([0, 0, 0]);
+ expect(max[0]!).toBeCloseTo(1, 5);
+ expect(max[1]!).toBeCloseTo(0.5, 3);
+ expect(max[2]!).toBe(0);
+ });
+
+ test('an index past the last vertex is ignored, and nothing drawn stays unbounded', () => {
+ const { doc, positions, scene } = fixture();
+ scene.addChild(doc.createNode().setMesh(part(doc, positions, [0, 1, 2, 2, 1, 900])));
+ expect(drawnSceneBounds(scene)).toEqual({ min: [0, 0, 0], max: [1, 2, 0] });
+ const empty = fixture();
+ expect(drawnSceneBounds(empty.scene)).toEqual({
+ min: [Infinity, Infinity, Infinity],
+ max: [-Infinity, -Infinity, -Infinity],
+ });
+ });
+});
diff --git a/src/__tests__/lod-review.test.ts b/src/__tests__/lod-review.test.ts
index 5cfa6a24..2f03d58e 100644
--- a/src/__tests__/lod-review.test.ts
+++ b/src/__tests__/lod-review.test.ts
@@ -4,8 +4,9 @@
* A default sheet draws what a loader without the extension draws: LOD0 and the parts outside
* every set. A shot whose subject names a lower level, by path or by name, draws that level in
* LOD0's place, and every result says which level each chain drew in each view. The CPU and GPU
- * producers draw the same scene: a default sheet sends both the artifact bytes, and a shot
- * sends both the same derivative bytes.
+ * producers draw the same scene: a default sheet sends both the artifact bytes, a shot of a lower
+ * level sends both the same derivative bytes, and a shot that only moves the camera draws LOD0
+ * from the artifact on the GPU.
*/
import { describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
@@ -166,7 +167,8 @@ describe('a shot draws the level its subject names', () => {
expect(result.levelsOfDetail![0]!.drawn).toEqual([1, 2]);
});
- test('the CPU and the GPU draw the same derivative bytes for every shot', async () => {
+ test('the CPU and the GPU draw the same scene for every shot', async () => {
+ const artifact = (await renderGLBInProcess(TIERED_CAR)).glb;
// Whole receipts (renderer and input bytes per view) are full detail; compact and lean
// keep only what differs from the viewFidelity summary.
const cpu = await tool('kiln_render')({ code: TIERED_CAR, capture: SHOTS, detail: 'full' });
@@ -182,16 +184,21 @@ describe('a shot draws the level its subject names', () => {
'gpu:lod-test',
'gpu:lod-test',
]);
- expect(gpu.derivativeReceipts!.map((receipt) => receipt.inputGlbSha256)).toEqual(
- cpu.derivativeReceipts!.map((receipt) => receipt.inputGlbSha256),
+ // The shots of a lower level share their derivative with the CPU; the shot of LOD0 only moves
+ // the camera, so the GPU draws it first, from the artifact.
+ const gpuInputs = gpu.derivativeReceipts!.map((receipt) => receipt.inputGlbSha256);
+ expect(gpuInputs.slice(0, 2)).toEqual(
+ cpu.derivativeReceipts!.slice(0, 2).map((receipt) => receipt.inputGlbSha256),
);
+ expect(gpuInputs[2]).toBe(sha(artifact));
expect(drawnByChain(gpu)).toEqual(drawnByChain(cpu));
const tyres = ['Wheel_FL', 'Wheel_FR', 'Wheel_RL', 'Wheel_RR'].map((w) => `Mesh_Tyre_${w}`);
- expect(await drawnMeshes(requests[0]!.glb)).toEqual(['Mesh_Shell2']);
- expect(await drawnMeshes(requests[1]!.glb)).toEqual(['Mesh_Shell1', ...tyres].sort());
- expect(await drawnMeshes(requests[2]!.glb)).toEqual(
+ expect(sha(requests[0]!.glb)).toBe(sha(artifact));
+ expect(await drawnMeshes(requests[0]!.glb)).toEqual(
['Mesh_Mirror', 'Mesh_Shell0', ...tyres].sort(),
);
+ expect(await drawnMeshes(requests[1]!.glb)).toEqual(['Mesh_Shell2']);
+ expect(await drawnMeshes(requests[2]!.glb)).toEqual(['Mesh_Shell1', ...tyres].sort());
});
test('a name two lower levels share is ambiguous; a path picks one', async () => {
diff --git a/src/__tests__/review-derivative-bytes.test.ts b/src/__tests__/review-derivative-bytes.test.ts
new file mode 100644
index 00000000..ac14f8ca
--- /dev/null
+++ b/src/__tests__/review-derivative-bytes.test.ts
@@ -0,0 +1,128 @@
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import {
+ BoxGeometry,
+ DataTexture,
+ Group,
+ Mesh,
+ MeshStandardMaterial,
+ RepeatWrapping,
+ SRGBColorSpace,
+} from 'three';
+import type { PbrRenderRequest } from '../composer/render-port';
+import * as renderModule from '../render';
+import { renderReviewDerivativeGlb, renderSceneToGLB } from '../render';
+import { createKilnProgramToolRegistry } from '../tools/registry';
+import { loadGlbReviewScene } from '../views';
+import { encodePng } from '../views/png';
+
+const sha = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
+
+/** Textures, tangents, a second UV set, a hidden part and a repeated mesh in one artifact. */
+function authored(): Group {
+ const root = new Group();
+ root.name = 'Root';
+ const pixels = new Uint8Array(16 * 16 * 4);
+ for (let i = 0; i < 16 * 16; i++) {
+ pixels[i * 4] = (i * 7) % 256;
+ pixels[i * 4 + 1] = (i * 13) % 256;
+ pixels[i * 4 + 2] = (i * 29) % 256;
+ pixels[i * 4 + 3] = 255;
+ }
+ const color = new DataTexture(pixels, 16, 16);
+ color.colorSpace = SRGBColorSpace;
+ color.wrapS = color.wrapT = RepeatWrapping;
+ color.needsUpdate = true;
+ const normal = new DataTexture(pixels.slice(), 16, 16);
+ normal.needsUpdate = true;
+ const geometry = new BoxGeometry(1, 2, 3);
+ geometry.setAttribute('uv1', geometry.getAttribute('uv')!.clone());
+ const material = new MeshStandardMaterial({ map: color, normalMap: normal, roughness: 0.4 });
+ for (const [name, x] of [
+ ['Left', -2],
+ ['Right', 2],
+ ] as const) {
+ const part = new Mesh(geometry, material);
+ part.name = name;
+ part.position.x = x;
+ root.add(part);
+ }
+ const hidden = new Mesh(new BoxGeometry(), new MeshStandardMaterial({ color: '#ff0000' }));
+ hidden.name = 'Hidden';
+ hidden.visible = false;
+ root.add(hidden);
+ return root;
+}
+
+afterEach(() => {
+ // Spies must not outlive the test that installed them.
+ for (const spy of spies.splice(0)) spy.mockRestore();
+});
+const spies: { mockRestore(): void }[] = [];
+
+describe('renderReviewDerivativeGlb', () => {
+ for (const gltfExporter of ['three', 'legacy'] as const)
+ test(`writes the bytes a derivative export writes (${gltfExporter})`, async () => {
+ const artifact = (await renderSceneToGLB(authored(), { optimize: 'off' })).bytes;
+ const evidence = await loadGlbReviewScene(artifact);
+ const bytesOnly = await loadGlbReviewScene(artifact);
+ const full = await renderSceneToGLB(evidence.root as never, {
+ derivative: true,
+ gltfExporter,
+ });
+ const reviewed = await renderReviewDerivativeGlb(bytesOnly.root as never, { gltfExporter });
+ expect(sha(reviewed)).toBe(sha(full.bytes));
+ });
+
+ test('refuses a scene with nothing to draw, as the evidence path does', async () => {
+ const empty = new Group();
+ await expect(renderSceneToGLB(empty, { derivative: true })).rejects.toThrow(
+ 'no measurable scene',
+ );
+ await expect(renderReviewDerivativeGlb(empty)).rejects.toThrow('no measurable scene');
+ const allHidden = new Group();
+ const mesh = new Mesh(new BoxGeometry(), new MeshStandardMaterial());
+ mesh.visible = false;
+ allHidden.add(mesh);
+ await expect(renderReviewDerivativeGlb(allHidden)).rejects.toThrow('every triangle is hidden');
+ });
+});
+
+describe('view cells', () => {
+ const code =
+ "const meta={name:'pair',category:'prop'};function build(){const r=createRoot('Root');" +
+ "createPart('Near',boxGeo(1,1,1),gameMaterial('#888888'),{parent:r});" +
+ "createPart('Far',boxGeo(1,1,1),gameMaterial('#333333'),{parent:r,position:[3,0,0]});return r;}";
+ const port = async (req: PbrRenderRequest) => ({
+ ok: true,
+ rendererId: 'gpu:test',
+ cameras: req.cameras,
+ width: req.width,
+ height: req.height,
+ viewsPng: (req.cameras ?? []).map(() => encodePng(new Uint8Array(128 * 128 * 3), 128, 128)),
+ derivativeFidelity: {
+ materialFaithful: true as const,
+ inputGlbSha256: `sha256:${sha(req.glb)}` as const,
+ },
+ });
+
+ test('a shot that needs a derivative pays for its bytes only', async () => {
+ const evidence = spyOn(renderModule, 'renderSceneToGLB');
+ spies.push(evidence);
+ const render = createKilnProgramToolRegistry({ viewRenderPort: port }).find(
+ (def) => def.name === 'kiln_render',
+ )!;
+ const out = (await render.run({
+ code,
+ capture: {
+ version: 'kiln.capture.v1',
+ size: 128,
+ shots: [{ subject: { name: 'Mesh_Near' }, visibility: 'isolate' }],
+ },
+ })) as { ok: boolean };
+ expect(out.ok).toBe(true);
+ // The build itself may run in this process; only a derivative export would be waste.
+ const derivatives = evidence.mock.calls.filter(([, options]) => options?.derivative === true);
+ expect(derivatives).toHaveLength(0);
+ });
+});
diff --git a/src/composer/render-port.ts b/src/composer/render-port.ts
index beb53d9a..a416c1d8 100644
--- a/src/composer/render-port.ts
+++ b/src/composer/render-port.ts
@@ -183,15 +183,17 @@ export interface ViewFidelityV1 {
reasonCodes?: ViewFidelityReasonCode[];
}
-/** One purpose-built review GLB and the pixels derived from those exact bytes. */
+/**
+ * One view cell and the GLB its pixels were drawn from. Most cells draw a purpose-built review
+ * derivative. A shot that changes only the camera draws the artifact bytes themselves, and then
+ * `exactArtifact` is true under the same rule as a full-asset grid.
+ */
export interface DerivativeViewReceiptV1 extends ViewFidelityV1 {
captureCache?: { hit: boolean; reused: number; total: number };
camera?: ResolvedAssetCameraV1;
cameraFidelity?: 'echo-validated' | 'engine-resolved';
/** Stable cell/frame identity within the review surface. */
derivativeLabel: string;
- /** Derivative bytes are never the persisted/final artifact. */
- exactArtifact: false;
}
/** Aggregate material-fidelity truth for a derivative review surface. */
@@ -482,6 +484,8 @@ export type { Backdrop, BackdropId } from '../views/background';
export interface PbrRenderResult {
captureCache?: { hit: boolean; reused: number; total: number };
+ /** Per view, whether a capture cache supplied it, in request order. */
+ captureCacheHits?: boolean[];
ok: boolean;
/** Honest producer identity, e.g. "dawn-vulkan:nvidia-rtx-a4500:NVIDIA: 550.100"
* or the CPU fallback's deterministic "cpu-raster:<engine-version>". */
diff --git a/src/evaluator/subprocess-pipe-close.test.ts b/src/evaluator/subprocess-pipe-close.test.ts
index 97e5be82..e4513729 100644
--- a/src/evaluator/subprocess-pipe-close.test.ts
+++ b/src/evaluator/subprocess-pipe-close.test.ts
@@ -1,4 +1,6 @@
import { test, expect } from 'bun:test';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { renderGLBViaProcessLaunch, sanitizedEvaluatorEnv } from './subprocess';
const result = JSON.stringify({
version: 'kiln.evaluator.result.v2',
@@ -59,3 +61,41 @@ test('input-close errors retain deadline and cancellation authority', async () =
clearTimeout(timer);
}
}, 10000);
+
+test('a missing worker file names the rebuild, whatever size the request was', async () => {
+ const missing = join(tmpdir(), 'kiln-missing-worker', 'evaluator-worker.mjs');
+ for (const source of ['small', UNFLUSHABLE_SOURCE]) {
+ const failure = await renderGLBViaProcessLaunch(
+ source,
+ {},
+ { deadlineMs: 15000 },
+ {
+ command: process.execPath,
+ args: ['-e', 'process.exit(1)'],
+ env: sanitizedEvaluatorEnv(),
+ workerFile: missing,
+ },
+ ).catch((error) => error);
+ expect(failure.code).toBe('WORKER_FAILED');
+ expect(failure.message).toContain('evaluator-worker.mjs is missing');
+ expect(failure.message).toContain('bun run build:runtime');
+ expect(failure.message).toContain('restart');
+ expect(failure.message).not.toContain(tmpdir());
+ }
+}, 30000); // Two process launches.
+
+test('a worker that exists keeps the plain failure', async () => {
+ const failure = await renderGLBViaProcessLaunch(
+ 'small',
+ {},
+ { deadlineMs: 15000 },
+ {
+ command: process.execPath,
+ args: ['-e', 'process.exit(1)'],
+ env: sanitizedEvaluatorEnv(),
+ workerFile: process.execPath,
+ },
+ ).catch((error) => error);
+ expect(failure.code).toBe('WORKER_FAILED');
+ expect(failure.message).toBe('Evaluator worker failed.');
+}, 20000);
diff --git a/src/evaluator/subprocess-pipe-order.test.ts b/src/evaluator/subprocess-pipe-order.test.ts
index d7dbbfc0..a520347e 100644
--- a/src/evaluator/subprocess-pipe-order.test.ts
+++ b/src/evaluator/subprocess-pipe-order.test.ts
@@ -107,3 +107,14 @@ test('stdin, stderr, unknown errors and non-Windows-Bun runtimes keep failing cl
expect(String(result)).not.toContain('private pipe detail');
}
});
+
+test('Windows Node reports a dead worker stdin as EOF, which waits for the worker close like EPIPE', async () => {
+ for (const stream of ['stdin', 'stderr', 'fd3'] as const) {
+ const { result, killed } = await exercise({ stream, errno: 'EOF', bun: false });
+ expect(result).toMatchObject({ code: 'EXECUTION_REJECTED' });
+ expect(killed).toBe(false);
+ }
+ expect((await exercise({ stream: 'stdin', errno: 'EOF', exit: 1 })).result).toMatchObject({
+ code: 'WORKER_FAILED',
+ });
+});
diff --git a/src/evaluator/subprocess.ts b/src/evaluator/subprocess.ts
index 4ab2850c..beabeba5 100644
--- a/src/evaluator/subprocess.ts
+++ b/src/evaluator/subprocess.ts
@@ -4,6 +4,8 @@ import {
type AuthoringDiagnostic,
} from './authoring-diagnostic';
import { spawn, type SpawnOptions } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { basename } from 'node:path';
import { solidFailureAdvice, type SolidFailureDetails } from './solid-diagnostic';
import { fileURLToPath } from 'node:url';
import type { RenderGlbOptions, RenderResult } from '../render';
@@ -47,6 +49,8 @@ export interface EvaluatorProcessLaunch {
args: string[];
env: NodeJS.ProcessEnv;
detached?: boolean;
+ /** The worker the launch runs, checked when it fails so the error can name the rebuild. */
+ workerFile?: string;
}
export class EvaluatorSubprocessError extends Error {
@@ -178,8 +182,18 @@ export async function renderGLBViaProcessLaunch(
command: process.execPath,
args: process.versions.bun ? [workerPath] : [`--max-old-space-size=${maxHeapMb}`, workerPath],
env: sanitizedEvaluatorEnv(),
+ workerFile: workerPath,
};
const resolvedLaunch = launch ?? defaultLaunch;
+ // A worker that dies at once fails differently by request size and platform; a missing file is
+ // the one cause with a known next step, so every failure path asks about it.
+ const workerFailure = (message: string) =>
+ new EvaluatorSubprocessError(
+ 'WORKER_FAILED',
+ resolvedLaunch.workerFile && !existsSync(resolvedLaunch.workerFile)
+ ? `Evaluator worker failed: ${basename(resolvedLaunch.workerFile)} is missing beside the engine. Reinstall Kiln (bun install, then bun run build:runtime), run kiln-init . --repair in the workspace, and restart the MCP session.`
+ : message,
+ );
const detached = resolvedLaunch.detached === true;
return await new Promise<RenderResult>((resolve, reject) => {
@@ -193,7 +207,7 @@ export async function renderGLBViaProcessLaunch(
const protocol = child.stdio[3];
if (!protocol) {
terminateProcess(child, detached);
- reject(new EvaluatorSubprocessError('WORKER_FAILED', 'Evaluator worker did not start.'));
+ reject(workerFailure('Evaluator worker did not start.'));
return;
}
const chunks: Buffer[] = [];
@@ -223,15 +237,20 @@ export async function renderGLBViaProcessLaunch(
// Always consume pipe errors; only an active request becomes a worker error.
if (settled) return;
// Windows/Bun can report a closed input/stderr/protocol pipe before the
- // process close event drains its complete fd3 envelope. Keep the host
+ // process close event drains its complete fd3 envelope, and Windows/Node
+ // reports writing to a worker that already exited as EOF. Keep the host
// deadline and cancellation armed, then require exit 0 plus strict decode.
if (
- ['EPIPE', 'ECONNRESET', 'ERR_STREAM_DESTROYED', 'ERR_STREAM_PREMATURE_CLOSE'].includes(
- error.code ?? '',
- )
+ [
+ 'EOF',
+ 'EPIPE',
+ 'ECONNRESET',
+ 'ERR_STREAM_DESTROYED',
+ 'ERR_STREAM_PREMATURE_CLOSE',
+ ].includes(error.code ?? '')
)
return;
- finish(new EvaluatorSubprocessError('WORKER_FAILED', 'Evaluator worker pipe failed.'));
+ finish(workerFailure('Evaluator worker pipe failed.'));
terminateProcess(child, detached);
};
child.stdin?.on('error', pipeFailed);
@@ -272,12 +291,12 @@ export async function renderGLBViaProcessLaunch(
stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk.byteLength);
});
child.on('error', () => {
- finish(new EvaluatorSubprocessError('WORKER_FAILED', 'Evaluator worker failed to start.'));
+ finish(workerFailure('Evaluator worker failed to start.'));
});
child.on('close', (exitCode) => {
if (settled) return;
if (exitCode !== 0 || chunks.length === 0) {
- finish(new EvaluatorSubprocessError('WORKER_FAILED', 'Evaluator worker failed.'));
+ finish(workerFailure('Evaluator worker failed.'));
return;
}
try {
diff --git a/src/node-visibility.ts b/src/node-visibility.ts
index 5037c969..cf98356a 100644
--- a/src/node-visibility.ts
+++ b/src/node-visibility.ts
@@ -7,7 +7,7 @@
* counts (triangles, draw calls, bounds) is what draws; each hidden subtree is listed apart
* with its own triangles, so hidden state costs no variant program.
*/
-import type { Document, Node as GltfNode, Scene } from '@gltf-transform/core';
+import type { Accessor, Document, Node as GltfNode, Scene } from '@gltf-transform/core';
import { KHRNodeVisibility, type InstancedMesh } from '@gltf-transform/extensions';
import * as THREE from 'three';
import type { HiddenNodeV1 } from './contracts/integration';
@@ -57,9 +57,28 @@ export function summarizeHiddenNodes(doc: Document): HiddenNodeV1[] {
return found;
}
+/** Each vertex a primitive's indices reach, once, in first-use order; every vertex without them. */
+function referencedVertices(indices: Accessor | null, position: Accessor): Uint32Array {
+ const vertexCount = position.getCount();
+ if (!indices) return Uint32Array.from({ length: vertexCount }, (_, vertex) => vertex);
+ const count = indices.getCount();
+ const stored = indices.getNormalized() ? null : indices.getArray();
+ const seen = new Uint8Array(vertexCount);
+ const vertices = new Uint32Array(count);
+ let unique = 0;
+ for (let i = 0; i < count; i++) {
+ const vertex = stored ? stored[i]! : indices.getScalar(i);
+ if (seen[vertex]) continue;
+ seen[vertex] = 1;
+ vertices[unique++] = vertex;
+ }
+ return vertices.subarray(0, unique);
+}
+
/**
- * World bounds of the geometry a loader draws: `getBounds` without hidden subtrees, vertex by
- * vertex so rotated geometry stays tight, including every GPU instance placement.
+ * World bounds of the geometry a loader draws: `getBounds` without hidden subtrees, each vertex a
+ * triangle reaches once per placement so rotated geometry stays tight, including every GPU
+ * instance placement.
*/
export function drawnSceneBounds(scene: Scene): { min: number[]; max: number[] } {
const min = [Infinity, Infinity, Infinity];
@@ -91,21 +110,24 @@ export function drawnSceneBounds(scene: Scene): { min: number[]; max: number[] }
for (const primitive of mesh.listPrimitives()) {
const position = primitive.getAttribute('POSITION');
if (!position) continue;
- const indices = primitive.getIndices();
- const count = indices ? indices.getCount() : position.getCount();
+ const vertices = referencedVertices(primitive.getIndices(), position);
+ const stored = position.getNormalized() ? null : position.getArray();
for (const m of matrices)
- for (let i = 0; i < count; i++) {
- position.getElement(indices ? indices.getScalar(i) : i, local);
- const [x, y, z] = local as [number, number, number];
- const world = [
- m[0]! * x + m[4]! * y + m[8]! * z + m[12]!,
- m[1]! * x + m[5]! * y + m[9]! * z + m[13]!,
- m[2]! * x + m[6]! * y + m[10]! * z + m[14]!,
- ];
- for (let k = 0; k < 3; k++) {
- if (world[k]! < min[k]!) min[k] = world[k]!;
- if (world[k]! > max[k]!) max[k] = world[k]!;
- }
+ for (let i = 0; i < vertices.length; i++) {
+ const vertex = vertices[i]!;
+ if (!stored) position.getElement(vertex, local);
+ const x = stored ? stored[vertex * 3]! : local[0]!;
+ const y = stored ? stored[vertex * 3 + 1]! : local[1]!;
+ const z = stored ? stored[vertex * 3 + 2]! : local[2]!;
+ const wx = m[0]! * x + m[4]! * y + m[8]! * z + m[12]!;
+ const wy = m[1]! * x + m[5]! * y + m[9]! * z + m[13]!;
+ const wz = m[2]! * x + m[6]! * y + m[10]! * z + m[14]!;
+ if (wx < min[0]!) min[0] = wx;
+ if (wy < min[1]!) min[1] = wy;
+ if (wz < min[2]!) min[2] = wz;
+ if (wx > max[0]!) max[0] = wx;
+ if (wy > max[1]!) max[1] = wy;
+ if (wz > max[2]!) max[2] = wz;
}
}
}
diff --git a/src/render.ts b/src/render.ts
index 4abbd959..9cc0a3e7 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -1699,36 +1699,15 @@ function optimizeWarnings(summary: OptimizeSummary): string[] {
}
/**
- * Serialize a pre-built Three.js scene graph to a GLB byte stream.
- *
- * This is the shared bridge used by both `renderGLB(code)` (headless, re-
- * executes code) and the in-editor `exportGLB()` (uses the live scene).
- *
- * Works in both Node and browser - uses WebIO, which only touches network
- * APIs on the read side. The write side is pure bytes-in/bytes-out, so the
- * same function serializes identically on either platform. That unifies
- * the two historical paths (Three.js GLTFExporter in the editor vs.
- * gltf-transform bridge headlessly) into one canonical pipeline.
- *
- * Pure function: no file I/O, no globals, no WebGL.
+ * Source-data invariants that precede any operation dereferencing bindings. Reuses the structured
+ * QA transport without claiming that the full QA rules ran. Like invalid geometry buffers,
+ * malformed skin data cannot be made safe by QA-warn or derivative mode. No automatic weight
+ * normalization or rest-pose repair occurs.
*/
-export async function renderSceneToGLB(
+function assertSceneSourceIntegrity(
root: THREE.Object3D,
- opts: RenderSceneOptions = {},
-): Promise<RenderSceneResult> {
- assertNoLegacyRuntimePolicy(opts);
- const requirements = resolveRequirementsContext(opts.requirements);
- const clips = opts.clips ?? [];
- const indexPolicy = resolveIndexPolicy(opts.indexPolicy);
- if (indexPolicy === 'asBuilt' && resolveOptimize(opts.optimize) !== 'off')
- throw new Error('asBuilt indexPolicy requires optimize off to preserve authored buffers');
- if (opts.geometryPolicy !== undefined && !['warn', 'strict'].includes(opts.geometryPolicy))
- throw new Error('geometryPolicy must be warn or strict');
- const exporter = resolveGltfExporter(opts.gltfExporter);
- // Mandatory source-data invariants precede any operation that dereferences bindings.
- // Reuse the structured QA transport without claiming that the full QA rules ran.
- // Like invalid geometry buffers, malformed skin data cannot be made safe by QA-warn
- // or derivative mode. No automatic weight normalization or rest-pose repair occurs.
+ requirements: ReturnType<typeof resolveRequirementsContext>,
+): void {
const skinIntegrity = inspectSkinIntegrity(root);
if (skinIntegrity.findings.length) {
throw new AssetQaBlockedError(
@@ -1748,13 +1727,13 @@ export async function renderSceneToGLB(
);
}
assertPortableMaterialSides(root);
- // A set of LOD tiers needs its declared thresholds before anything is written. A
- // derivative re-serializes a review scene that has no declarations, so it is not judged.
- const lodSets = opts.derivative === true ? [] : collectLodSets(root);
- // An opt-in solid assertion is the author's, so a derivative re-serialization is not judged.
- if (opts.derivative !== true) assertRequiredSolids(root);
- const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);
- // The headline counts what a plain loader draws: LOD0 and the parts outside every set.
+}
+
+/** The headline counts what a plain loader draws: LOD0 and the parts outside every set. */
+function drawnTriangleCount(
+ root: THREE.Object3D,
+ lodSets: ReturnType<typeof collectLodSets>,
+): number {
let tris = countTriangles(root);
for (const set of lodSets) for (const level of set.levels.slice(1)) tris -= countTriangles(level);
const hiddenTris = hiddenTriangles(root, new Set(lodSets.flatMap((set) => set.levels.slice(1))));
@@ -1762,50 +1741,24 @@ export async function renderSceneToGLB(
throw new Error(
'renderSceneToGLB: every triangle is hidden (visible = false on the root or on every part), so nothing draws. Hide parts inside the asset, not all of it.',
);
- tris -= hiddenTris;
- const materialRecipeApplications = collectMaterialRecipeApplications(root);
- const materialResourceProvenance = collectMaterialResourceProvenance(root);
-
- // Runtime-aware joint-name validation (follow-up #6 from the W1.1 spike
- // report). Walk the scene graph + animation tracks and surface any track
- // whose target name doesn't resolve to a scene node. Non-fatal - the GLB
- // still renders; agents iterating on code use these warnings to fix the
- // next iteration. Runs before the bridge so the descriptive "rename the
- // pivot" hint is first; the bridge also emits a briefer "target not
- // found - skipped" for each unresolved track (kept for compatibility).
- for (const w of inspectGeneratedAnimation(root, clips)) warnings.push(w);
- const externalSupport = requirements.requirements.requirements.externalSupport;
- for (const w of inspectSceneStructure(root, {
- ...(externalSupport?.state === 'requested'
- ? { externalSupport: externalSupport.value.supports }
- : {}),
- }))
- warnings.push(w);
-
- // T2.2 — encode in-memory textures to PNG BEFORE QA, so QA judges the file
- // that will actually be written. A procedural DataTexture used to reach the
- // bridge with no encoded bytes and be dropped without a word; now it is
- // either baked into the GLB or warned about by name.
- const atlas = collectAtlasProvenance(root);
- const bakedTextures = await bakeSceneTextures(root, warnings);
- // A normal-mapped mesh without tangents makes every runtime invent its own
- // tangent basis, so the same asset lights differently in different engines.
- // Only touches meshes that actually carry a normal map — the attribute
- // changes the exported bytes.
- ensureNormalMapTangents(root, warnings);
-
- const qaPolicy = qaPolicyFromEnv();
- const sceneEvidence = await collectRequirementsSceneEvidence(requirements, root, qaPolicy);
- const sceneQaReport = runRequirementsSceneQa(requirements, root, clips, qaPolicy, sceneEvidence);
- // A derivative export withholds the throw without hiding the finding.
- const qaBlocks = qaBlockingEnabled() && opts.derivative !== true;
- const qaSuppressedBy = opts.derivative === true ? 'derivative re-serialization' : 'KILN_QA_MODE';
- if (sceneQaReport.disposition === 'block') {
- const blocked = new AssetQaBlockedError(sceneQaReport, 'scene');
- if (qaBlocks) throw blocked;
- warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
- }
+ return tris - hiddenTris;
+}
+/** Write the scene into a transformed glTF document: everything that decides the bytes. */
+async function buildSceneDocument(
+ root: THREE.Object3D,
+ opts: RenderSceneOptions,
+ scene: {
+ clips: NonNullable<RenderSceneOptions['clips']>;
+ exporter: ReturnType<typeof resolveGltfExporter>;
+ indexPolicy: ReturnType<typeof resolveIndexPolicy>;
+ lodSets: ReturnType<typeof collectLodSets>;
+ tris: number;
+ atlas: ReturnType<typeof collectAtlasProvenance>;
+ warnings: string[];
+ },
+) {
+ const { clips, exporter, indexPolicy, lodSets, tris, atlas, warnings } = scene;
const nativeClips = clipsWithDurationSamples(clips);
// Author userData decided once, so both exporters write the same extras.
const authorExtras = collectAuthorExtras(root);
@@ -1940,6 +1893,102 @@ export async function renderSceneToGLB(
}
}
+ return {
+ doc,
+ indexBuffers,
+ ...(instancing ? { instancing } : {}),
+ ...(optimize ? { optimize } : {}),
+ };
+}
+
+/**
+ * Serialize a pre-built Three.js scene graph to a GLB byte stream.
+ *
+ * This is the shared bridge used by both `renderGLB(code)` (headless, re-
+ * executes code) and the in-editor `exportGLB()` (uses the live scene).
+ *
+ * Works in both Node and browser - uses WebIO, which only touches network
+ * APIs on the read side. The write side is pure bytes-in/bytes-out, so the
+ * same function serializes identically on either platform. That unifies
+ * the two historical paths (Three.js GLTFExporter in the editor vs.
+ * gltf-transform bridge headlessly) into one canonical pipeline.
+ *
+ * Pure function: no file I/O, no globals, no WebGL.
+ */
+export async function renderSceneToGLB(
+ root: THREE.Object3D,
+ opts: RenderSceneOptions = {},
+): Promise<RenderSceneResult> {
+ assertNoLegacyRuntimePolicy(opts);
+ const requirements = resolveRequirementsContext(opts.requirements);
+ const clips = opts.clips ?? [];
+ const indexPolicy = resolveIndexPolicy(opts.indexPolicy);
+ if (indexPolicy === 'asBuilt' && resolveOptimize(opts.optimize) !== 'off')
+ throw new Error('asBuilt indexPolicy requires optimize off to preserve authored buffers');
+ if (opts.geometryPolicy !== undefined && !['warn', 'strict'].includes(opts.geometryPolicy))
+ throw new Error('geometryPolicy must be warn or strict');
+ const exporter = resolveGltfExporter(opts.gltfExporter);
+ assertSceneSourceIntegrity(root, requirements);
+ // A set of LOD tiers needs its declared thresholds before anything is written. A
+ // derivative re-serializes a review scene that has no declarations, so it is not judged.
+ const lodSets = opts.derivative === true ? [] : collectLodSets(root);
+ // An opt-in solid assertion is the author's, so a derivative re-serialization is not judged.
+ if (opts.derivative !== true) assertRequiredSolids(root);
+ const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);
+ const tris = drawnTriangleCount(root, lodSets);
+ const materialRecipeApplications = collectMaterialRecipeApplications(root);
+ const materialResourceProvenance = collectMaterialResourceProvenance(root);
+
+ // Runtime-aware joint-name validation (follow-up #6 from the W1.1 spike
+ // report). Walk the scene graph + animation tracks and surface any track
+ // whose target name doesn't resolve to a scene node. Non-fatal - the GLB
+ // still renders; agents iterating on code use these warnings to fix the
+ // next iteration. Runs before the bridge so the descriptive "rename the
+ // pivot" hint is first; the bridge also emits a briefer "target not
+ // found - skipped" for each unresolved track (kept for compatibility).
+ for (const w of inspectGeneratedAnimation(root, clips)) warnings.push(w);
+ const externalSupport = requirements.requirements.requirements.externalSupport;
+ for (const w of inspectSceneStructure(root, {
+ ...(externalSupport?.state === 'requested'
+ ? { externalSupport: externalSupport.value.supports }
+ : {}),
+ }))
+ warnings.push(w);
+
+ // T2.2 — encode in-memory textures to PNG BEFORE QA, so QA judges the file
+ // that will actually be written. A procedural DataTexture used to reach the
+ // bridge with no encoded bytes and be dropped without a word; now it is
+ // either baked into the GLB or warned about by name.
+ const atlas = collectAtlasProvenance(root);
+ const bakedTextures = await bakeSceneTextures(root, warnings);
+ // A normal-mapped mesh without tangents makes every runtime invent its own
+ // tangent basis, so the same asset lights differently in different engines.
+ // Only touches meshes that actually carry a normal map — the attribute
+ // changes the exported bytes.
+ ensureNormalMapTangents(root, warnings);
+
+ const qaPolicy = qaPolicyFromEnv();
+ const sceneEvidence = await collectRequirementsSceneEvidence(requirements, root, qaPolicy);
+ const sceneQaReport = runRequirementsSceneQa(requirements, root, clips, qaPolicy, sceneEvidence);
+ // A derivative export withholds the throw without hiding the finding.
+ const qaBlocks = qaBlockingEnabled() && opts.derivative !== true;
+ const qaSuppressedBy = opts.derivative === true ? 'derivative re-serialization' : 'KILN_QA_MODE';
+ if (sceneQaReport.disposition === 'block') {
+ const blocked = new AssetQaBlockedError(sceneQaReport, 'scene');
+ if (qaBlocks) throw blocked;
+ warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
+ }
+
+ const { doc, indexBuffers, instancing, optimize } = await buildSceneDocument(root, opts, {
+ clips,
+ exporter,
+ indexPolicy,
+ lodSets,
+ tris,
+ atlas,
+ warnings,
+ });
+
// Instanceability metrics, measured against the post-dedup() (and post-optimize,
// when enabled) Document so the counts reflect the GLB the runtime actually
// loads. Informational only — never a gate. Failure is swallowed: the GLB is
@@ -2080,6 +2129,43 @@ export async function renderSceneToGLB(
};
}
+/**
+ * The bytes of a review derivative and nothing else: the same bytes `renderSceneToGLB` writes with
+ * `derivative: true`, without the QA, validator, metrics and manifest evidence a view cell would
+ * discard. The scene was already adjudicated when its artifact was built; the source invariants
+ * that make a scene unsafe to serialize still throw.
+ */
+export async function renderReviewDerivativeGlb(
+ root: THREE.Object3D,
+ opts: Pick<RenderSceneOptions, 'gltfExporter'> = {},
+): Promise<Uint8Array> {
+ assertSceneSourceIntegrity(root, resolveRequirementsContext(undefined));
+ const tris = drawnTriangleCount(root, []);
+ if (tris <= 0) throw new Error('renderSceneToGLB: final GLB has no measurable scene');
+ // Warnings are evidence about the source, reported when the artifact was built.
+ const warnings: string[] = [];
+ const atlas = collectAtlasProvenance(root);
+ await bakeSceneTextures(root, warnings);
+ ensureNormalMapTangents(root, warnings);
+ const { doc } = await buildSceneDocument(
+ root,
+ { ...opts, derivative: true },
+ {
+ clips: [],
+ exporter: resolveGltfExporter(opts.gltfExporter),
+ indexPolicy: resolveIndexPolicy(undefined),
+ lodSets: [],
+ tris,
+ atlas,
+ warnings,
+ },
+ );
+ ensureDefaultScene(doc);
+ await refreshAtlasDocumentProvenance(doc);
+ await validateAtlasDocumentProvenance(doc);
+ return engineIO().writeBinary(doc);
+}
+
/**
* Execute Kiln code and serialize to a GLB Buffer.
*
diff --git a/src/tools/__tests__/camera-integration.test.ts b/src/tools/__tests__/camera-integration.test.ts
index 822acbba..341b278d 100644
--- a/src/tools/__tests__/camera-integration.test.ts
+++ b/src/tools/__tests__/camera-integration.test.ts
@@ -308,7 +308,8 @@ test('isolate hides surrounding geometry on the GPU path, not only the CPU raste
},
})) as Record<string, unknown>;
expect(mixed.ok).toBe(true);
- expect(requests.map((r) => glbMeshCount(r.glb))).toEqual([1, 2]);
+ // The context shot draws the artifact, in a request made before any derivative cell.
+ expect(requests.map((r) => glbMeshCount(r.glb))).toEqual([2, 1]);
expect(await run('context')).toBe(2);
// The CPU rasterizer culls on `mesh.visible` (views/raster.ts), but a GLB has no
// per-mesh visibility, so an unfiltered serialization makes isolate a silent
diff --git a/src/tools/__tests__/exact-artifact-shots.test.ts b/src/tools/__tests__/exact-artifact-shots.test.ts
new file mode 100644
index 00000000..c1c92d6d
--- /dev/null
+++ b/src/tools/__tests__/exact-artifact-shots.test.ts
@@ -0,0 +1,397 @@
+import { describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import type { PbrRenderRequest, PbrRenderResult } from '../../composer/render-port';
+import { createKilnNativeToolRegistry, createKilnProgramToolRegistry } from '../registry';
+import { encodePng } from '../../views/png';
+
+const code =
+ "const meta={name:'pair',category:'prop'};function build(){const r=createRoot('Root');" +
+ "createPart('Near',boxGeo(1,1,1),gameMaterial('#888888'),{parent:r});" +
+ "createPart('Far',boxGeo(1,1,1),gameMaterial('#333333'),{parent:r,position:[3,0,0]});" +
+ "const hidden=createPart('Cover',boxGeo(9,9,9),gameMaterial('#ff0000'),{parent:r});hidden.visible=false;return r;}";
+
+const sha = (bytes: Uint8Array) =>
+ `sha256:${createHash('sha256').update(bytes).digest('hex')}` as const;
+
+/** A GPU port that answers every camera, and remembers what it was asked. */
+function fixture(
+ options: { identity?: string; answer?: (req: PbrRenderRequest) => PbrRenderResult | null } = {},
+) {
+ const requests: PbrRenderRequest[] = [];
+ const telemetry: unknown[] = [];
+ const defs = createKilnProgramToolRegistry({
+ ...(options.identity ? { captureCacheIdentity: options.identity } : {}),
+ onViewsRendered: (drawn: unknown) => telemetry.push(drawn),
+ viewRenderPort: async (req: PbrRenderRequest): Promise<PbrRenderResult> => {
+ requests.push(req);
+ const answered = options.answer?.(req);
+ if (answered) return answered;
+ const size = req.width ?? 128;
+ return {
+ ok: true,
+ rendererId: 'gpu:test',
+ cameras: req.cameras,
+ width: req.width,
+ height: req.height,
+ viewsPng: (req.cameras ?? []).map((_, index) =>
+ encodePng(new Uint8Array(size * size * 3).fill(10 + index * 20), size, size),
+ ),
+ derivativeFidelity: { materialFaithful: true, inputGlbSha256: sha(req.glb) },
+ };
+ },
+ } as never);
+ const render = defs.find((def) => def.name === 'kiln_render')!;
+ return { render, requests, telemetry };
+}
+
+const orbit = (azimuthDeg: number, extra: Record<string, unknown> = {}) => ({
+ name: `A${azimuthDeg}`,
+ camera: { type: 'orbit', azimuthDeg, elevationDeg: 20 },
+ ...extra,
+});
+interface Rendered {
+ ok: boolean;
+ error?: string;
+ programRef: string;
+ captureCache?: { hit: boolean; reused: number; total: number };
+ views: string[];
+ viewFidelity: {
+ exactArtifact: boolean;
+ inputGlbSha256: string;
+ reasonCodes?: string[];
+ materialFaithful: boolean;
+ degraded: boolean;
+ delivered: string;
+ };
+ framesBase64?: string[];
+ pngBase64?: string;
+ derivativeReceipts: {
+ exactArtifact: boolean;
+ inputGlbSha256: string;
+ derivativeLabel: string;
+ materialFaithful: boolean;
+ degradeReason?: string;
+ delivered: string;
+ captureCache?: { hit: boolean; reused: number; total: number };
+ camera: unknown;
+ cameraFidelity: string;
+ }[];
+ cameraShots: { name: string; camera: unknown }[];
+}
+const run = async (
+ render: ReturnType<typeof fixture>['render'],
+ args: Record<string, unknown>,
+): Promise<Rendered> => {
+ const out = (await render.run({ detail: 'full', ...args })) as Rendered;
+ expect(out.error).toBeUndefined();
+ return out;
+};
+const capture = (shots: unknown[], extra: Record<string, unknown> = {}) => ({
+ version: 'kiln.capture.v1',
+ shots,
+ size: 128,
+ ...extra,
+});
+
+describe('camera-only shots', () => {
+ test('go in one request over the exact artifact, and say so', async () => {
+ const { render, requests, telemetry } = fixture();
+ const shots = [0, 40, 80, 120, 160, 200, 240, 280, 320].map((azimuth) => orbit(azimuth));
+ const out = await run(render, { code, capture: capture(shots) });
+
+ expect(requests).toHaveLength(1);
+ expect(requests[0]!.cameras).toHaveLength(9);
+ expect(sha(requests[0]!.glb)).toBe(out.viewFidelity.inputGlbSha256 as `sha256:${string}`);
+ // The same claim as a full-asset grid on a host that keeps no retained artifact.
+ expect(out.viewFidelity).toMatchObject({
+ exactArtifact: false,
+ materialFaithful: true,
+ degraded: false,
+ delivered: 'full-material',
+ reasonCodes: ['IN_LOOP_BUILD_NOT_PERSISTED'],
+ });
+ expect(out.views).toEqual(shots.map((shot) => shot.name));
+ expect(out.derivativeReceipts.map((r) => r.derivativeLabel)).toEqual(out.views);
+ for (const [index, receipt] of out.derivativeReceipts.entries()) {
+ expect(receipt.exactArtifact).toBe(false);
+ expect(receipt.inputGlbSha256).toBe(out.viewFidelity.inputGlbSha256);
+ expect(receipt.cameraFidelity).toBe('echo-validated');
+ expect(receipt.camera).toEqual(out.cameraShots[index]!.camera);
+ expect(receipt.camera).toEqual(requests[0]!.cameras![index]);
+ }
+ expect(telemetry).toHaveLength(9);
+ expect(telemetry[0]).toEqual({ renderer: 'gpu:test', degraded: false, neededPbr: true });
+ });
+
+ test('a host that retains the artifact gets the exact claim, as its grids do', async () => {
+ const requests: PbrRenderRequest[] = [];
+ const defs = createKilnNativeToolRegistry(
+ {
+ viewRenderPort: async (req: PbrRenderRequest): Promise<PbrRenderResult> => {
+ requests.push(req);
+ return {
+ ok: true,
+ rendererId: 'gpu:test',
+ cameras: req.cameras,
+ width: req.width,
+ height: req.height,
+ viewsPng: (req.cameras ?? []).map(() =>
+ encodePng(new Uint8Array(128 * 128 * 3), 128, 128),
+ ),
+ derivativeFidelity: { materialFaithful: true, inputGlbSha256: sha(req.glb) },
+ };
+ },
+ } as never,
+ {},
+ );
+ const render = defs.find((def) => def.name === 'kiln_render')!;
+ const out = await run(render, { code, capture: capture([orbit(0), orbit(90)]) });
+ expect(requests).toHaveLength(1);
+ expect(out.viewFidelity.exactArtifact).toBe(true);
+ expect(out.viewFidelity.reasonCodes).toEqual([]);
+ expect(out.derivativeReceipts.map((r) => r.exactArtifact)).toEqual([true, true]);
+ // One isolated shot among them: the sheet as a whole is not the exact artifact.
+ const mixed = await run(render, {
+ code,
+ capture: capture([orbit(0), orbit(90, { visibility: 'isolate' })]),
+ });
+ expect(mixed.viewFidelity.exactArtifact).toBe(false);
+ expect(mixed.viewFidelity.reasonCodes).toEqual(['IN_LOOP_BUILD_NOT_PERSISTED']);
+ expect(mixed.derivativeReceipts.map((r) => r.exactArtifact)).toEqual([true, false]);
+ });
+
+ test('shots past the service limit split, and the images stay in shot order', async () => {
+ const { render, requests } = fixture();
+ const shots = [0, 72, 144, 216, 288].map((azimuth) => orbit(azimuth));
+ const out = await run(render, {
+ code,
+ capture: capture(shots, { size: 2048, output: 'separate' }),
+ });
+ expect(requests.map((req) => req.cameras!.length)).toEqual([4, 1]);
+ expect(out.framesBase64).toHaveLength(5);
+ expect(out.derivativeReceipts.map((r) => r.derivativeLabel)).toEqual(out.views);
+ expect(out.derivativeReceipts[4]!.camera).toEqual(requests[1]!.cameras![0]);
+ }, 60_000); // Five 2048 px PNG encodes and decodes.
+
+ test('a subject framed in context is still camera-only', async () => {
+ const { render, requests } = fixture();
+ const out = await run(render, {
+ code,
+ capture: capture([orbit(0, { subject: { name: 'Mesh_Near' } }), orbit(90)]),
+ });
+ expect(requests).toHaveLength(1);
+ expect(out.derivativeReceipts[0]!.inputGlbSha256).toBe(out.viewFidelity.inputGlbSha256);
+ });
+
+ test('every view in the cache means no request at all, and the counters say which', async () => {
+ const { render, requests } = fixture({ identity: 'gpu-fixture' });
+ const shots = [orbit(0), orbit(90), orbit(180)];
+ const first = await run(render, { code, capture: capture(shots) });
+ expect(requests).toHaveLength(1);
+ expect(first.captureCache).toEqual({ hit: false, reused: 0, total: 3 });
+
+ const repeat = await run(render, {
+ programRef: first.programRef,
+ capture: capture(shots),
+ });
+ expect(requests).toHaveLength(1);
+ expect(repeat.captureCache).toEqual({ hit: true, reused: 3, total: 3 });
+ for (const receipt of repeat.derivativeReceipts)
+ expect(receipt.captureCache).toEqual({ hit: true, reused: 1, total: 1 });
+ expect(repeat.pngBase64).toBe(first.pngBase64);
+
+ const partial = await run(render, {
+ programRef: first.programRef,
+ capture: capture([orbit(0), orbit(45), orbit(180)]),
+ });
+ expect(requests).toHaveLength(2);
+ expect(requests[1]!.cameras).toHaveLength(1);
+ expect(partial.captureCache).toEqual({ hit: false, reused: 2, total: 3 });
+ expect(partial.derivativeReceipts.map((r) => r.captureCache?.hit)).toEqual([true, false, true]);
+ });
+
+ test('a changed size or backdrop never returns a stale image', async () => {
+ const { render, requests } = fixture({ identity: 'gpu-fixture' });
+ const shots = [orbit(30)];
+ const first = await run(render, { code, capture: capture(shots) });
+ const larger = await run(render, {
+ programRef: first.programRef,
+ capture: capture(shots, { size: 256 }),
+ });
+ expect(requests).toHaveLength(2);
+ expect(requests[1]).toMatchObject({ width: 256, height: 256 });
+ expect(larger.captureCache?.hit).toBe(false);
+
+ const dark = await run(render, {
+ programRef: first.programRef,
+ capture: capture(shots, { backdrop: 'dark' }),
+ });
+ expect(requests).toHaveLength(3);
+ expect(requests[2]!.backdrop).toBe('dark');
+ expect(dark.captureCache?.hit).toBe(false);
+
+ const again = await run(render, {
+ programRef: first.programRef,
+ capture: capture(shots, { backdrop: 'dark' }),
+ });
+ expect(requests).toHaveLength(3);
+ expect(again.captureCache?.hit).toBe(true);
+ expect(again.pngBase64).toBe(dark.pngBase64);
+ });
+
+ test('a rebuilt asset never returns the old asset image', async () => {
+ const { render, requests } = fixture({ identity: 'gpu-fixture' });
+ await run(render, { code, capture: capture([orbit(30)]) });
+ const changed = code.replace('#888888', '#884444');
+ const out = await run(render, { code: changed, capture: capture([orbit(30)]) });
+ expect(requests).toHaveLength(2);
+ expect(sha(requests[0]!.glb)).not.toBe(sha(requests[1]!.glb));
+ expect(out.captureCache?.hit).toBe(false);
+ });
+
+ test('separate frames follow the same route', async () => {
+ const { render, requests } = fixture();
+ const out = await run(render, {
+ code,
+ capture: capture([orbit(0), orbit(90)], { output: 'separate' }),
+ });
+ expect(requests).toHaveLength(1);
+ expect(out.framesBase64).toHaveLength(2);
+ expect(out.pngBase64).toBeUndefined();
+ });
+});
+
+describe('shots that change what draws', () => {
+ test('isolate and hide keep a derivative; the rest still share the exact request', async () => {
+ const { render, requests } = fixture();
+ const out = await run(render, {
+ code,
+ capture: capture(
+ [
+ orbit(0),
+ orbit(90, { subject: { name: 'Mesh_Near' }, visibility: 'isolate' }),
+ orbit(180),
+ orbit(270, { hide: ['Mesh_Far'] }),
+ ],
+ { version: 'kiln.capture.v2' },
+ ),
+ });
+ expect(out.views).toEqual(['A0', 'A90', 'A180', 'A270']);
+ expect(requests).toHaveLength(3);
+ expect(requests[0]!.cameras).toHaveLength(2);
+ expect(requests[1]!.cameras).toHaveLength(1);
+ expect(requests[2]!.cameras).toHaveLength(1);
+ const artifact = out.viewFidelity.inputGlbSha256;
+ expect(sha(requests[0]!.glb) as string).toBe(artifact);
+ expect(sha(requests[1]!.glb) as string).not.toBe(artifact);
+ expect(sha(requests[2]!.glb) as string).not.toBe(artifact);
+ expect(out.derivativeReceipts.map((r) => r.inputGlbSha256 === artifact)).toEqual([
+ true,
+ false,
+ true,
+ false,
+ ]);
+ expect(out.derivativeReceipts[1]!.camera).toEqual(requests[1]!.cameras![0]);
+ expect(out.derivativeReceipts[2]!.camera).toEqual(requests[0]!.cameras![1]);
+ });
+
+ test('a lower level of detail keeps a derivative', async () => {
+ const lod =
+ "const meta={name:'lod',category:'prop'};function build(){const r=createRoot('Root');" +
+ "const tiers=['Body_LOD0','Body_LOD1'].map((name)=>{const g=new THREE.Group();g.name=name;r.add(g);return g;});" +
+ "createPart('Near',boxGeo(2,2,2),gameMaterial('#888888'),{parent:tiers[0]});" +
+ "createPart('Far',boxGeo(1,1,1),gameMaterial('#333333'),{parent:tiers[1]});" +
+ 'defineLod(tiers,{screenCoverage:[0.2,0]});return r;}';
+ const { render, requests } = fixture();
+ const out = await run(render, {
+ code: lod,
+ capture: capture([orbit(0), orbit(90, { subject: { name: 'Body_LOD1' } })]),
+ });
+ expect(requests).toHaveLength(2);
+ const artifact = out.viewFidelity.inputGlbSha256;
+ expect(sha(requests[0]!.glb) as string).toBe(artifact);
+ expect(sha(requests[1]!.glb) as string).not.toBe(artifact);
+ expect(out.derivativeReceipts.map((r) => r.inputGlbSha256 === artifact)).toEqual([true, false]);
+ });
+});
+
+describe('the batch stays inside the degrade policy', () => {
+ test('a failed batch falls back to a cell per shot, which may still succeed', async () => {
+ const { render, requests } = fixture({
+ answer: (req) =>
+ (req.cameras?.length ?? 0) > 1
+ ? { ok: false, rendererId: 'gpu:test', error: 'too much at once' }
+ : null,
+ });
+ const out = await run(render, { code, capture: capture([orbit(0), orbit(90)]) });
+ expect(requests).toHaveLength(3);
+ expect(out.viewFidelity).toMatchObject({ materialFaithful: true, exactArtifact: false });
+ const artifact = out.viewFidelity.inputGlbSha256;
+ expect(out.derivativeReceipts.map((r) => r.inputGlbSha256 === artifact)).toEqual([
+ false,
+ false,
+ ]);
+ });
+
+ test('a port that never answers ends in the CPU degrade with the deadline as its reason', async () => {
+ const requests: PbrRenderRequest[] = [];
+ const defs = createKilnProgramToolRegistry({
+ viewRenderTimeoutMs: 30,
+ viewRenderPort: async (req: PbrRenderRequest) => {
+ requests.push(req);
+ return new Promise<PbrRenderResult>(() => {});
+ },
+ } as never);
+ const out = await run(defs.find((def) => def.name === 'kiln_render')!, {
+ code,
+ capture: capture([orbit(0), orbit(90)]),
+ });
+ expect(requests).toHaveLength(3);
+ expect(out.viewFidelity).toMatchObject({
+ materialFaithful: false,
+ delivered: 'geometry-flat',
+ degraded: true,
+ exactArtifact: false,
+ });
+ expect(out.derivativeReceipts[0]!.degradeReason).toBe('view render port timed out after 30ms');
+ });
+
+ test('required GPU still refuses when batch and cells fail', async () => {
+ const defs = createKilnProgramToolRegistry({
+ viewRenderRequired: true,
+ viewRenderPort: async () => ({ ok: false, rendererId: 'gpu:test', error: 'offline' }),
+ } as never);
+ const out = (await defs
+ .find((def) => def.name === 'kiln_render')!
+ .run({ code, capture: capture([orbit(0)]) })) as { ok: boolean; error: string };
+ expect(out.ok).toBe(false);
+ expect(out.error).toContain('Required GPU render failed: offline');
+ });
+
+ test('without a port the CPU route is unchanged', async () => {
+ const render = createKilnProgramToolRegistry().find((def) => def.name === 'kiln_render')!;
+ const out = await run(render, { code, capture: capture([orbit(0), orbit(90)]) });
+ expect(out.viewFidelity).toMatchObject({
+ delivered: 'geometry-flat',
+ exactArtifact: false,
+ reasonCodes: ['IN_LOOP_BUILD_NOT_PERSISTED'],
+ });
+ expect(out.derivativeReceipts.every((r) => r.exactArtifact === false)).toBe(true);
+ });
+
+ test('cancellation during a batch ends the call', async () => {
+ const controller = new AbortController();
+ const defs = createKilnProgramToolRegistry({
+ evaluationControls: () => ({ signal: controller.signal }),
+ viewRenderPort: async () => {
+ controller.abort(new Error('cancelled by the host'));
+ return new Promise<PbrRenderResult>(() => {});
+ },
+ } as never);
+ const out = (await defs
+ .find((def) => def.name === 'kiln_render')!
+ .run({ code, capture: capture([orbit(0), orbit(90)]) })) as { ok: boolean; error: string };
+ expect(out.ok).toBe(false);
+ expect(out.error).toContain('cancelled by the host');
+ });
+});
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 7605e5c7..8b05a473 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -49,7 +49,7 @@ import * as THREE from 'three';
import { validate, type ValidationIssue } from '../validation';
import { appendSourceCheck } from '../evaluator/source-check';
-import { inspectSceneStructure, renderSceneToGLB, type RenderResult } from '../render';
+import { inspectSceneStructure, renderReviewDerivativeGlb, type RenderResult } from '../render';
import type {
AssetCategory,
AssetIntentV1,
@@ -515,16 +515,11 @@ async function renderDerivativeCell(
// joint ancestors survive as transform-only nodes in the derivative.
const { withoutHiddenMeshes } = await import('../views/camera');
derivativeRoot = withoutHiddenMeshes(derivativeRoot);
- const rendered = await renderSceneToGLB(derivativeRoot, {
- // The scene here was loaded back from a GLB this engine already produced
- // and adjudicated. Submitting it for judgement a second time fails on the
- // round trip rather than on the asset: see `derivative` in render.ts.
- derivative: true,
- // Review reconstruction preserves UV2 and UV3; the legacy authored exporter
- // does not carry them into the GPU derivative.
- gltfExporter: 'three',
- requirements: toolRequirements(context).binding,
- });
+ // The scene here was loaded back from a GLB this engine already produced and
+ // adjudicated, so a cell needs its bytes and none of the build's evidence.
+ // Review reconstruction preserves UV2 and UV3; the legacy authored exporter
+ // does not carry them into the GPU derivative.
+ const reviewBytes = await renderReviewDerivativeGlb(derivativeRoot, { gltfExporter: 'three' });
const { cameraFromBounds, measureBounds } = await import('../views');
const camera =
input.camera ??
@@ -535,7 +530,7 @@ async function renderDerivativeCell(
undefined,
measureBounds(input.root),
);
- const derivativeGlb = Uint8Array.from(rendered.bytes);
+ const derivativeGlb = Uint8Array.from(reviewBytes);
const inputGlbSha256 = await sha256Glb(derivativeGlb);
let degradeReason: string | undefined;
const derivativeReasonCodes: ViewFidelityReasonCode[] = [];
@@ -674,6 +669,50 @@ async function renderDerivativeCell(
return { png: flat.png, receipt };
}
+/**
+ * Shots that change only the camera, drawn from the build's own bytes. Host telemetry counts each
+ * one, as it does a derivative cell; a shot left undrawn renders as a derivative cell and reports there.
+ */
+async function renderExactArtifactShots(
+ input: {
+ shots: import('../views').ResolvedCameraShotV1[];
+ size: number;
+ backdrop: import('../views/background').BackdropId;
+ },
+ glb: Uint8Array,
+ context: KilnToolContext,
+): Promise<readonly (import('../views').DerivativeCellRenderResult | undefined)[] | undefined> {
+ if (!context.viewRenderPort) return undefined;
+ const { captureExactArtifactShotsViaPort } = await import('../views/port');
+ const cells = await captureExactArtifactShotsViaPort(
+ context.viewRenderPort,
+ glb,
+ resolveInLoopViewRenderTimeoutMs(context, 'derivative-cell'),
+ input.shots,
+ input.size,
+ {
+ exactArtifact: context.programArtifacts !== undefined,
+ ...(context.captureLimits ? { limits: context.captureLimits } : {}),
+ backdrop: input.backdrop,
+ ...(context.evaluationControls ? { execution: context.evaluationControls() } : {}),
+ },
+ );
+ context.evaluationControls?.().signal?.throwIfAborted();
+ for (const cell of cells) {
+ if (!cell) continue;
+ try {
+ context.onViewsRendered?.({
+ renderer: cell.receipt.rendererId,
+ degraded: false,
+ neededPbr: true,
+ });
+ } catch {
+ /* best effort */
+ }
+ }
+ return cells;
+}
+
function derivativeReviewFidelity(
receipts: DerivativeViewReceiptV1[] | undefined,
): DerivativeReviewFidelityV1 | undefined {
@@ -1190,8 +1229,9 @@ async function retainReviewedArtifact(
): Promise<KilnRenderViewsResult> {
context.evaluationControls?.().signal?.throwIfAborted();
if (!context.programArtifacts) return reviewed;
- // Full-asset grids depict the exact retained bytes. Derivative shots remain
- // derivative evidence even though their source artifact is retained as well.
+ // Full-asset grids depict the exact retained bytes. A capture with shots has
+ // already said so per receipt: a derivative among them stays derivative
+ // evidence even though its source artifact is retained as well.
if (reviewed.viewFidelity && !reviewed.derivativeReceipts) {
reviewed.viewFidelity = {
...reviewed.viewFidelity,
@@ -1239,11 +1279,19 @@ async function runRenderViews(
const metrics = collectSceneMetrics(root);
if ('shots' in (input.capture ?? {})) {
const { renderCaptureGrid } = await import('../views');
- const grid = await renderCaptureGrid(root, input.capture!, (cell) =>
- renderDerivativeCell(cell, context),
+ const grid = await renderCaptureGrid(
+ root,
+ input.capture!,
+ (cell) => renderDerivativeCell(cell, context),
+ context.captureLimits,
+ {
+ framesOnly: true,
+ renderExactShots: (shots) => renderExactArtifactShots(shots, rendered.glb, context),
+ },
);
const receipts = grid.derivativeReceipts;
const materialFaithful = receipts.every((r) => r.materialFaithful);
+ const exactArtifact = receipts.every((r) => r.exactArtifact);
context.evaluationControls?.().signal?.throwIfAborted();
const reviewed: KilnRenderViewsResult = {
ok: true,
@@ -1279,11 +1327,11 @@ async function runRenderViews(
requested: 'full-preferred',
delivered: materialFaithful ? 'full-material' : 'geometry-flat',
materialFaithful,
- exactArtifact: false,
+ exactArtifact,
rendererId: [...new Set(receipts.map((r) => r.rendererId))].join(', '),
inputGlbSha256: await sha256Glb(Uint8Array.from(rendered.glb)),
degraded: !materialFaithful,
- reasonCodes: ['IN_LOOP_BUILD_NOT_PERSISTED'],
+ reasonCodes: exactArtifact ? [] : ['IN_LOOP_BUILD_NOT_PERSISTED'],
},
warnings: [...rendered.warnings],
};
@@ -2443,7 +2491,8 @@ async function guardCaptureBudget(
let cells = 6,
size = 384,
cols = 3,
- compose = true;
+ compose = true,
+ nameFit = false;
if (name === 'kiln_inspect') {
cells = 1;
size = 512;
@@ -2461,6 +2510,10 @@ async function guardCaptureBudget(
cells = args.capture.shots.length;
size = args.capture.size ?? 384;
cols = args.capture.cols ?? Math.min(3, cells);
+ // Only these tools deliver separate frames without a sheet.
+ if (['kiln_render', 'kiln_edit'].includes(name) && args.capture.output === 'separate')
+ compose = false;
+ nameFit = true;
} else {
const { resolveGridCapture } = await import('../views/capture');
const resolved = resolveGridCapture(args.capture);
@@ -2468,7 +2521,7 @@ async function guardCaptureBudget(
cols = resolved.cols;
}
}
- enforceCapturePixels(cells, size, cols, context.captureLimits, compose);
+ enforceCapturePixels(cells, size, cols, context.captureLimits, compose, nameFit);
const out = await run();
if (out && typeof out === 'object') {
const media = out as { pngBase64?: string; framesBase64?: string[] };
diff --git a/src/views/__tests__/camera-sdk.test.ts b/src/views/__tests__/camera-sdk.test.ts
index 91c608c3..72596d36 100644
--- a/src/views/__tests__/camera-sdk.test.ts
+++ b/src/views/__tests__/camera-sdk.test.ts
@@ -34,7 +34,7 @@ test('advanced capture preserves vertex colors in the exact derivative sent to t
},
rendered.bytes,
5000,
- { version: 'kiln.capture.v1', shots: [{}], size: 128 },
+ { version: 'kiln.capture.v1', shots: [{ visibility: 'isolate' }], size: 128 },
);
expect(out.ok).toBe(true);
expect(received).toBeDefined();
diff --git a/src/views/__tests__/capture-limits.test.ts b/src/views/__tests__/capture-limits.test.ts
index 912d6c06..96da20b2 100644
--- a/src/views/__tests__/capture-limits.test.ts
+++ b/src/views/__tests__/capture-limits.test.ts
@@ -1,5 +1,8 @@
-import { test, expect } from 'bun:test';
+import { test, expect, spyOn } from 'bun:test';
import { createKilnProgramToolRegistry } from '../../tools/registry';
+import { enforceCapturePixels } from '../capture-limits';
+import * as gridModule from '../grid';
+import { PAD } from '../grid';
const code =
"const meta={name:'limit',category:'prop'};function build(){const r=createRoot('Root');createPart('Body',boxGeo(1,1,1),gameMaterial('#e24433'),{parent:r});return r;}";
test('host pixel limits reject CPU and GPU requests before evaluation or rendering', async () => {
@@ -79,3 +82,59 @@ test('GPU image headers are bounded before decompression', async () => {
);
expect(out).toMatchObject({ ok: false, reason: expect.stringMatching(/pixel budget/) });
});
+
+test('the pixel budget names what to change', () => {
+ const charged = () => enforceCapturePixels(6, 1800, 3, undefined, true, true);
+ expect(charged).toThrow(
+ 'capture pixel budget exceeded: 39002592 pixels against a limit of 24000000 (6 shots at size 1800, plus their grid sheet). Largest size that fits: 1411 as a grid, 2000 with output: "separate".',
+ );
+ expect(() => enforceCapturePixels(9, 2048, 3, undefined, false, true)).toThrow(
+ 'capture pixel budget exceeded: 37748736 pixels against a limit of 24000000 (9 shots at size 2048). Largest size that fits: 1632.',
+ );
+ // Nothing at the smallest capture size fits: the only change left is fewer shots.
+ expect(() => enforceCapturePixels(9, 128, 3, { maxTotalPixels: 1000 }, true, true)).toThrow(
+ /Use fewer shots\.$/,
+ );
+ // Tools without a size to change keep the plain statement.
+ expect(() => enforceCapturePixels(6, 384, 3, { maxTotalPixels: 100 })).toThrow(
+ /^capture pixel budget exceeded: \d+ pixels against a limit of 100\.$/,
+ );
+});
+
+test('separate images are not charged for a sheet nobody receives', async () => {
+ const separateOnly = 6 * 128 * 128;
+ const defs = createKilnProgramToolRegistry({ captureLimits: { maxTotalPixels: separateOnly } });
+ const render = defs.find((d) => d.name === 'kiln_render')!;
+ const shots = Array.from({ length: 6 }, (_, index) => ({
+ camera: { type: 'orbit', azimuthDeg: index * 60 },
+ }));
+ const out = (await render.run({
+ code,
+ capture: { version: 'kiln.capture.v1', shots, size: 128, output: 'separate' },
+ })) as { ok: boolean; error?: string; framesBase64?: string[]; gridWidth?: number };
+ expect(out.error).toBeUndefined();
+ expect(out.ok).toBe(true);
+ expect(out.framesBase64).toHaveLength(6);
+ expect(out.gridWidth).toBe(3 * 128 + 4 * PAD);
+ const grid = (await render.run({
+ code,
+ capture: { version: 'kiln.capture.v1', shots, size: 128 },
+ })) as { ok: boolean; error: string };
+ expect(grid.ok).toBe(false);
+ expect(grid.error).toContain('capture pixel budget exceeded');
+ expect(grid.error).toContain('with output: "separate"');
+});
+
+test('a separate capture never composes its sheet', async () => {
+ const grids = spyOn(gridModule, 'compositeCellGrid');
+ try {
+ const render = createKilnProgramToolRegistry().find((d) => d.name === 'kiln_render')!;
+ const capture = { version: 'kiln.capture.v1', shots: [{}], size: 128 };
+ await render.run({ code, capture: { ...capture, output: 'separate' } });
+ expect(grids).not.toHaveBeenCalled();
+ await render.run({ code, capture });
+ expect(grids).toHaveBeenCalledTimes(1);
+ } finally {
+ grids.mockRestore();
+ }
+});
diff --git a/src/views/__tests__/drawn-geometry.test.ts b/src/views/__tests__/drawn-geometry.test.ts
new file mode 100644
index 00000000..39860d67
--- /dev/null
+++ b/src/views/__tests__/drawn-geometry.test.ts
@@ -0,0 +1,143 @@
+import { expect, test } from 'bun:test';
+import {
+ BoxGeometry,
+ BufferAttribute,
+ BufferGeometry,
+ Float32BufferAttribute,
+ Group,
+ Mesh,
+ MeshStandardMaterial,
+} from 'three';
+import { defaultPerspectiveNear, resolveAssetCamera } from '../camera';
+import {
+ collectTriangles,
+ measureBounds,
+ measureDrawnGeometry,
+ measurePartBounds,
+ nearestDrawnTriangleDistance,
+} from '../raster';
+
+/** Reading the index array means a walk over triangles, which camera framing has no need for. */
+function forbidIndexRead(mesh: Mesh): Mesh {
+ const index = mesh.geometry.index!;
+ Object.defineProperty(index, 'array', {
+ get() {
+ throw new Error('bounds read the index array');
+ },
+ });
+ return mesh;
+}
+
+/** A visible part, a hidden part far away, an instanced transform and an unreferenced vertex. */
+function scene(): Group {
+ const root = new Group();
+ root.name = 'Root';
+ root.position.set(1, 2, 3);
+ root.rotation.set(0.3, 0.7, 0.1);
+ const body = new Mesh(new BoxGeometry(1, 2, 3), new MeshStandardMaterial());
+ body.name = 'Body';
+ body.position.set(-2, 0, 0);
+ root.add(body);
+ const hidden = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial());
+ hidden.name = 'Hidden';
+ hidden.position.set(50, 0, 0);
+ hidden.visible = false;
+ root.add(hidden);
+ const loose = new BufferGeometry();
+ // The fourth vertex is in no triangle; the rasterizer's box has always counted every position.
+ loose.setAttribute(
+ 'position',
+ new Float32BufferAttribute([0, 0, 0, 1, 0, 0, 0, 1, 0, 9, 9, 9], 3),
+ );
+ loose.setIndex(new BufferAttribute(new Uint16Array([0, 1, 2]), 1));
+ const part = new Mesh(loose, new MeshStandardMaterial());
+ part.name = 'Loose';
+ root.add(part);
+ return root;
+}
+
+test('the drawn box and triangle count equal what the rasterizer collects', () => {
+ for (const node of [scene(), scene().children[0]!, scene().children[2]!]) {
+ const collected = collectTriangles(node as never);
+ const measured = measureDrawnGeometry(node);
+ expect({ min: measured.min, max: measured.max }).toEqual(collected.bbox);
+ expect(measured.triangles).toBe(collected.tris.length);
+ expect(measureBounds(node)).toEqual(collected.bbox);
+ expect(measurePartBounds(node)).toEqual(collected.bbox);
+ }
+});
+
+test('an empty subtree measures as the zero box, and vertices without a triangle still count', () => {
+ const empty = new Group();
+ expect(measureDrawnGeometry(empty)).toEqual({ min: [0, 0, 0], max: [0, 0, 0], triangles: 0 });
+ expect(measurePartBounds(empty)).toBeNull();
+
+ const line = new BufferGeometry();
+ line.setAttribute('position', new Float32BufferAttribute([1, 2, 3, 4, 5, 6], 3));
+ const mesh = new Mesh(line, new MeshStandardMaterial());
+ expect(collectTriangles(mesh as never).bbox).toEqual({ min: [1, 2, 3], max: [4, 5, 6] });
+ expect(measureDrawnGeometry(mesh)).toEqual({ min: [1, 2, 3], max: [4, 5, 6], triangles: 0 });
+ expect(measurePartBounds(mesh)).toBeNull();
+});
+
+test('measuring a scene walks positions and never triangle records', () => {
+ const mesh = forbidIndexRead(new Mesh(new BoxGeometry(), new MeshStandardMaterial()));
+ expect(measureBounds(mesh)).toEqual({ min: [-0.5, -0.5, -0.5], max: [0.5, 0.5, 0.5] });
+ expect(measureDrawnGeometry(mesh).triangles).toBe(12);
+});
+
+test('resolving an orbit or bounds-framed camera walks positions and never triangle records', () => {
+ const root = new Group();
+ root.add(forbidIndexRead(new Mesh(new BoxGeometry(), new MeshStandardMaterial())));
+ const orbit = resolveAssetCamera(root, { camera: { type: 'orbit', azimuthDeg: 30 } });
+ expect(orbit.subject.bounds).toEqual({ min: [-0.5, -0.5, -0.5], max: [0.5, 0.5, 0.5] });
+ resolveAssetCamera(root, {
+ camera: {
+ type: 'explicit',
+ projection: 'orthographic',
+ position: [4, 4, 4],
+ framing: 'bounds',
+ },
+ });
+});
+
+test('a subject with vertices but no triangle is still refused', () => {
+ const root = new Group();
+ const line = new BufferGeometry();
+ line.setAttribute('position', new Float32BufferAttribute([1, 2, 3, 4, 5, 6], 3));
+ root.add(new Mesh(line, new MeshStandardMaterial()));
+ expect(() => resolveAssetCamera(root)).toThrow(/has no visible geometry/);
+});
+
+test('the nearest triangle distance matches the per-triangle reading', () => {
+ const position: [number, number, number] = [5, -3, 7];
+ const root = scene();
+ let nearest = Number.POSITIVE_INFINITY;
+ for (const { v } of collectTriangles(root as never).tris) {
+ const dx = Math.max(
+ Math.min(v[0]!, v[3]!, v[6]!) - position[0],
+ 0,
+ position[0] - Math.max(v[0]!, v[3]!, v[6]!),
+ );
+ const dy = Math.max(
+ Math.min(v[1]!, v[4]!, v[7]!) - position[1],
+ 0,
+ position[1] - Math.max(v[1]!, v[4]!, v[7]!),
+ );
+ const dz = Math.max(
+ Math.min(v[2]!, v[5]!, v[8]!) - position[2],
+ 0,
+ position[2] - Math.max(v[2]!, v[5]!, v[8]!),
+ );
+ nearest = Math.min(nearest, Math.sqrt(dx * dx + dy * dy + dz * dz));
+ }
+ expect(nearestDrawnTriangleDistance(root, position)).toBe(nearest);
+ expect(defaultPerspectiveNear(root, position, 1000)).toBe(Math.max(0.001, nearest / 2));
+ expect(nearestDrawnTriangleDistance(new Group(), position)).toBe(Number.POSITIVE_INFINITY);
+ // Unindexed geometry reads its triangles in position order.
+ const flat = new BufferGeometry();
+ flat.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 1, 0, 0, 0, 1, 0], 3));
+ const single = new Mesh(flat, new MeshStandardMaterial());
+ expect(nearestDrawnTriangleDistance(single, [0.5, 0.25, 2])).toBe(2);
+ expect(nearestDrawnTriangleDistance(single, [0.5, 0.25, 0])).toBe(0);
+});
diff --git a/src/views/__tests__/exact-shots.test.ts b/src/views/__tests__/exact-shots.test.ts
new file mode 100644
index 00000000..dcd84199
--- /dev/null
+++ b/src/views/__tests__/exact-shots.test.ts
@@ -0,0 +1,276 @@
+import { describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { BoxGeometry, DataTexture, Group, Mesh, MeshStandardMaterial, SRGBColorSpace } from 'three';
+import { MAX_CAMERAS, MAX_CAMERA_TOTAL_PIXELS } from '../../../render-service/src/contract.mjs';
+import type { PbrRenderRequest } from '../../composer/render-port';
+import { createGltfIO } from '../../gltf-io';
+import { renderSceneToGLB } from '../../render';
+import { MemoryCaptureCache, createCachedRenderPort } from '../capture-cache';
+import { encodePng } from '../png';
+import {
+ MAX_CAMERAS_PER_REQUEST,
+ MAX_PIXELS_PER_REQUEST,
+ captureExactArtifactShotsViaPort,
+ captureViewsViaPort,
+ exactShotRequestSizes,
+} from '../port';
+import { loadGlbReviewScene } from '..';
+import { resolveAssetCamera } from '../camera';
+
+const sha = (bytes: Uint8Array) =>
+ `sha256:${createHash('sha256').update(bytes).digest('hex')}` as const;
+
+const gpu = (requests: PbrRenderRequest[]) => async (req: PbrRenderRequest) => {
+ requests.push(req);
+ const size = req.width!;
+ return {
+ ok: true,
+ rendererId: 'gpu:test',
+ cameras: req.cameras,
+ width: req.width,
+ height: req.height,
+ viewsPng: req.cameras!.map(() => encodePng(new Uint8Array(size * size * 3), size, size)),
+ derivativeFidelity: { materialFaithful: true as const, inputGlbSha256: sha(req.glb) },
+ };
+};
+
+/** A box whose only texture samples the given UV set, every set holding different coordinates. */
+async function channelAsset(channel: number): Promise<Uint8Array> {
+ const root = new Group();
+ root.name = 'Root';
+ const geometry = new BoxGeometry();
+ const uv = geometry.getAttribute('uv')!;
+ for (const [index, name] of ['uv1', 'uv2', 'uv3'].entries()) {
+ const set = uv.clone();
+ for (let i = 0; i < set.count; i++) set.setXY(i, uv.getX(i) * (index + 2) * 0.25, uv.getY(i));
+ geometry.setAttribute(name, set);
+ }
+ const map = new DataTexture(new Uint8Array(4 * 4 * 4).fill(200), 4, 4);
+ map.colorSpace = SRGBColorSpace;
+ map.channel = channel;
+ map.needsUpdate = true;
+ const part = new Mesh(geometry, new MeshStandardMaterial({ map }));
+ part.name = 'Body';
+ root.add(part);
+ return (await renderSceneToGLB(root, { gltfExporter: 'three', optimize: 'off' })).bytes;
+}
+
+describe('request sizes', () => {
+ test('the engine split mirrors what the render service admits', () => {
+ expect(MAX_PIXELS_PER_REQUEST).toBe(MAX_CAMERA_TOTAL_PIXELS);
+ expect(MAX_CAMERAS_PER_REQUEST).toBe(MAX_CAMERAS);
+ });
+
+ test('shots split at the pixel limit, in order, and one shot always goes alone', () => {
+ expect(exactShotRequestSizes(9, 1000)).toEqual([9]);
+ // 9 * 1366^2 passes the limit by a little.
+ expect(exactShotRequestSizes(9, 1365)).toEqual([9]);
+ expect(exactShotRequestSizes(9, 1366)).toEqual([8, 1]);
+ expect(exactShotRequestSizes(9, 2048)).toEqual([4, 4, 1]);
+ expect(exactShotRequestSizes(1, 4096)).toEqual([1]);
+ expect(exactShotRequestSizes(1, 8192)).toEqual([1]);
+ });
+});
+
+describe('captureViewsViaPort with shots', () => {
+ test('sends the exact bytes for camera-only shots, in one request', async () => {
+ const artifact = await channelAsset(0);
+ const requests: PbrRenderRequest[] = [];
+ const out = await captureViewsViaPort(gpu(requests), artifact, 5000, {
+ version: 'kiln.capture.v1',
+ shots: [{}, { camera: { type: 'orbit', azimuthDeg: 200 } }],
+ size: 128,
+ });
+ expect(out.ok).toBe(true);
+ expect(requests).toHaveLength(1);
+ expect(sha(requests[0]!.glb)).toBe(sha(artifact));
+ if (out.ok) {
+ expect(out.rendererId).toBe('gpu:test');
+ expect(out.derivativeReceipts?.map((r) => r.exactArtifact)).toEqual([true, true]);
+ expect(out.derivativeReceipts?.[0]?.inputGlbSha256).toBe(sha(artifact));
+ }
+ });
+
+ test('orthographic and perspective shots never share a request, and keep their order', async () => {
+ const artifact = await channelAsset(0);
+ const requests: PbrRenderRequest[] = [];
+ const perspective = (x: number) => ({
+ camera: {
+ type: 'explicit' as const,
+ projection: 'perspective' as const,
+ position: [x, 2, 4] as [number, number, number],
+ target: [0, 0, 0] as [number, number, number],
+ fovDeg: 40,
+ },
+ });
+ const out = await captureViewsViaPort(gpu(requests), artifact, 5000, {
+ version: 'kiln.capture.v1',
+ shots: [
+ { camera: { type: 'orbit', azimuthDeg: 10 } },
+ perspective(1),
+ { camera: { type: 'orbit', azimuthDeg: 200 } },
+ perspective(2),
+ ],
+ size: 128,
+ });
+ expect(out.ok).toBe(true);
+ expect(requests).toHaveLength(2);
+ for (const request of requests)
+ expect(
+ new Set(request.cameras!.map((camera) => (camera as { projection?: string }).projection))
+ .size,
+ ).toBe(1);
+ expect(requests.map((request) => request.cameras!.length)).toEqual([2, 2]);
+ if (out.ok)
+ expect(
+ out.derivativeReceipts?.map(
+ (receipt) => (receipt.camera as { projection?: string } | undefined)?.projection,
+ ),
+ ).toEqual(['orthographic', 'perspective', 'orthographic', 'perspective']);
+ });
+
+ test('a batch gets one shot deadline per camera, as separate requests had', async () => {
+ const artifact = await channelAsset(0);
+ const { root } = await loadGlbReviewScene(artifact);
+ const shots = [0, 90, 180, 270].map((azimuthDeg) =>
+ resolveAssetCamera(root, { camera: { type: 'orbit', azimuthDeg } }),
+ );
+ const requests: PbrRenderRequest[] = [];
+ const answer = gpu(requests);
+ // A renderer that takes 150 ms per view: four views need 600 ms, more than one shot's 400.
+ const slow = async (req: PbrRenderRequest) => {
+ await new Promise((resolve) => setTimeout(resolve, 150 * req.cameras!.length));
+ return answer(req);
+ };
+ const cells = await captureExactArtifactShotsViaPort(slow, artifact, 400, shots, 128, {
+ exactArtifact: true,
+ });
+ expect(requests).toHaveLength(1);
+ expect(cells.every((cell) => cell?.receipt.rendererId === 'gpu:test')).toBe(true);
+ });
+
+ test('a renderer that changes between requests does not reach one sheet', async () => {
+ const artifact = await channelAsset(0);
+ const { root } = await loadGlbReviewScene(artifact);
+ const shots = [0, 72, 144, 216, 288].map((azimuthDeg) =>
+ resolveAssetCamera(root, { camera: { type: 'orbit', azimuthDeg } }),
+ );
+ let call = 0;
+ const cells = await captureExactArtifactShotsViaPort(
+ async (req) => {
+ call++;
+ const size = req.width!;
+ return {
+ ok: true,
+ rendererId: `gpu:${call}`,
+ cameras: req.cameras,
+ width: req.width,
+ height: req.height,
+ viewsPng: req.cameras!.map(() => encodePng(new Uint8Array(size * size * 3), size, size)),
+ derivativeFidelity: { materialFaithful: true as const, inputGlbSha256: sha(req.glb) },
+ };
+ },
+ artifact,
+ 5000,
+ shots,
+ 2048,
+ { exactArtifact: true },
+ );
+ expect(call).toBe(2);
+ expect(cells.map((cell) => cell?.receipt.rendererId)).toEqual([
+ 'gpu:1',
+ 'gpu:1',
+ 'gpu:1',
+ 'gpu:1',
+ undefined,
+ ]);
+ }, 60_000); // Five 2048 px PNG encodes and decodes.
+});
+
+describe('UV sets', () => {
+ for (const channel of [2, 3])
+ test(`an asset sampling TEXCOORD_${channel} reaches the renderer with that set intact`, async () => {
+ const artifact = await channelAsset(channel);
+ const requests: PbrRenderRequest[] = [];
+ const out = await captureViewsViaPort(gpu(requests), artifact, 5000, {
+ version: 'kiln.capture.v1',
+ shots: [{}],
+ size: 128,
+ });
+ expect(out.ok).toBe(true);
+ expect(sha(requests[0]!.glb)).toBe(sha(artifact));
+ const sent = await createGltfIO().readBinary(requests[0]!.glb);
+ const primitive = sent.getRoot().listMeshes()[0]!.listPrimitives()[0]!;
+ for (const set of [1, 2, 3]) expect(primitive.getAttribute(`TEXCOORD_${set}`)).not.toBeNull();
+ expect(primitive.getMaterial()!.getBaseColorTextureInfo()!.getTexCoord()).toBe(channel);
+ // Each set still holds its own coordinates.
+ const u = (set: number) => primitive.getAttribute(`TEXCOORD_${set}`)!.getElement(1, [])[0]!;
+ expect(u(2)).not.toBe(u(3));
+ });
+
+ test('a derivative keeps the set too, so an isolated shot of the same asset still samples it', async () => {
+ const artifact = await channelAsset(3);
+ const requests: PbrRenderRequest[] = [];
+ await captureViewsViaPort(gpu(requests), artifact, 5000, {
+ version: 'kiln.capture.v1',
+ shots: [{ subject: { name: 'Body' }, visibility: 'isolate' }],
+ size: 128,
+ });
+ expect(sha(requests[0]!.glb)).not.toBe(sha(artifact));
+ const sent = await createGltfIO().readBinary(requests[0]!.glb);
+ const primitive = sent.getRoot().listMeshes()[0]!.listPrimitives()[0]!;
+ expect(primitive.getAttribute('TEXCOORD_3')).not.toBeNull();
+ expect(primitive.getMaterial()!.getBaseColorTextureInfo()!.getTexCoord()).toBe(3);
+ });
+});
+
+describe('capture cache keys', () => {
+ test('backdrop, lighting, size and bytes each key their own cell; hits name their cells', async () => {
+ const cache = new MemoryCaptureCache();
+ const requests: PbrRenderRequest[] = [];
+ const inner = gpu(requests);
+ const port = createCachedRenderPort(inner, { cache, identity: () => 'renderer' });
+ const glb = new Uint8Array([1, 2, 3, 4]);
+ const camera = (x: number) => ({
+ version: 'kiln.camera.v1' as const,
+ projection: 'perspective' as const,
+ position: [x, 1, 5] as [number, number, number],
+ target: [0, 0, 0] as [number, number, number],
+ up: [0, 1, 0] as [number, number, number],
+ aspect: 1,
+ near: 0.1,
+ far: 100,
+ fovDeg: 50,
+ });
+ const request = (over: Partial<PbrRenderRequest> = {}): PbrRenderRequest => ({
+ glb,
+ cameras: [camera(1), camera(2)],
+ width: 64,
+ height: 64,
+ ...over,
+ });
+ await port(request());
+ expect(requests).toHaveLength(1);
+ const repeat = await port(request());
+ expect(requests).toHaveLength(1);
+ expect(repeat.captureCache).toEqual({ hit: true, reused: 2, total: 2 });
+ expect(repeat.captureCacheHits).toEqual([true, true]);
+
+ for (const changed of [
+ { backdrop: 'dark' as const },
+ { lightingPresetId: 'other-rig' },
+ { width: 96, height: 96 },
+ { glb: new Uint8Array([9, 9, 9, 9]) },
+ ]) {
+ const before = requests.length;
+ const out = await port(request(changed));
+ expect(requests.length).toBe(before + 1);
+ expect(out.captureCache).toEqual({ hit: false, reused: 0, total: 2 });
+ expect(out.captureCacheHits).toEqual([false, false]);
+ }
+
+ const mixed = await port(request({ cameras: [camera(1), camera(3)] }));
+ expect(mixed.captureCache).toEqual({ hit: false, reused: 1, total: 2 });
+ expect(mixed.captureCacheHits).toEqual([true, false]);
+ });
+});
diff --git a/src/views/__tests__/glb-decode.test.ts b/src/views/__tests__/glb-decode.test.ts
new file mode 100644
index 00000000..7fb2f0c5
--- /dev/null
+++ b/src/views/__tests__/glb-decode.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, spyOn, test } from 'bun:test';
+import { Accessor, Document, Primitive, WebIO } from '@gltf-transform/core';
+import type { Mesh } from 'three';
+import { loadGlbReviewScene } from '..';
+
+/** One triangle-list primitive per requested mode, every attribute kind the review scene reads. */
+async function glb(options: {
+ mode?: number;
+ indices?: number[] | null;
+ positions?: number[];
+ normalizedUv?: boolean;
+}): Promise<Uint8Array> {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const positions = options.positions ?? [0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0];
+ const count = positions.length / 3;
+ const primitive = doc
+ .createPrimitive()
+ .setMode((options.mode ?? Primitive.Mode.TRIANGLES) as never)
+ .setAttribute(
+ 'POSITION',
+ doc.createAccessor().setType('VEC3').setArray(new Float32Array(positions)).setBuffer(buffer),
+ )
+ .setAttribute(
+ 'NORMAL',
+ doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array(Array.from({ length: count }, () => [0, 0, 1]).flat()))
+ .setBuffer(buffer),
+ )
+ .setAttribute(
+ 'COLOR_0',
+ doc
+ .createAccessor()
+ .setType('VEC4')
+ .setArray(new Uint8Array(Array.from({ length: count }, () => [255, 128, 0, 51]).flat()))
+ .setNormalized(true)
+ .setBuffer(buffer),
+ );
+ for (const channel of [0, 2, 3]) {
+ const uv = Array.from({ length: count }, (_, i) => [i / count, channel / 4]).flat();
+ primitive.setAttribute(
+ `TEXCOORD_${channel}`,
+ options.normalizedUv
+ ? doc
+ .createAccessor()
+ .setType('VEC2')
+ .setArray(new Uint16Array(uv.map((value) => Math.round(value * 65535))))
+ .setNormalized(true)
+ .setBuffer(buffer)
+ : doc.createAccessor().setType('VEC2').setArray(new Float32Array(uv)).setBuffer(buffer),
+ );
+ }
+ if (options.indices !== null)
+ primitive.setIndices(
+ doc
+ .createAccessor()
+ .setType('SCALAR')
+ .setArray(new Uint16Array(options.indices ?? [0, 1, 2, 2, 1, 3]))
+ .setBuffer(buffer),
+ );
+ const scene = doc.createScene('Scene');
+ scene.addChild(doc.createNode('Part').setMesh(doc.createMesh('Part').addPrimitive(primitive)));
+ doc.getRoot().setDefaultScene(scene);
+ return new WebIO().writeBinary(doc);
+}
+
+const firstMesh = async (bytes: Uint8Array): Promise<Mesh> => {
+ const { root } = await loadGlbReviewScene(bytes);
+ let mesh: Mesh | undefined;
+ root.traverse((node) => {
+ if ((node as Mesh).isMesh && !mesh) mesh = node as Mesh;
+ });
+ return mesh!;
+};
+const values = (mesh: Mesh, name: string) => Array.from(mesh.geometry.getAttribute(name)!.array);
+const indices = (mesh: Mesh) => Array.from(mesh.geometry.index!.array);
+
+describe('review scene accessor decode', () => {
+ test('unnormalized geometry is copied without an element-by-element read', async () => {
+ const bytes = await glb({});
+ const spy = spyOn(Accessor.prototype, 'getElement');
+ try {
+ const mesh = await firstMesh(bytes);
+ const elementReads = spy.mock.calls.length;
+ expect(mesh.geometry.getAttribute('position')!.count).toBe(4);
+ // Only the normalized COLOR_0 accessor (4 vertices) goes through the element path.
+ expect(elementReads).toBe(4);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ test('values and array types match what the element read produces', async () => {
+ const mesh = await firstMesh(await glb({}));
+ expect(values(mesh, 'position')).toEqual([0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0]);
+ expect(mesh.geometry.getAttribute('position')!.array).toBeInstanceOf(Float32Array);
+ expect(values(mesh, 'normal')).toEqual(Array.from({ length: 4 }, () => [0, 0, 1]).flat());
+ expect(values(mesh, 'uv2')).toEqual(
+ Array.from(new Float32Array([0, 0.5, 0.25, 0.5, 0.5, 0.5, 0.75, 0.5])),
+ );
+ expect(values(mesh, 'uv3')).toEqual(
+ Array.from(new Float32Array([0, 0.75, 0.25, 0.75, 0.5, 0.75, 0.75, 0.75])),
+ );
+ expect(mesh.geometry.index!.array).toBeInstanceOf(Uint32Array);
+ expect(indices(mesh)).toEqual([0, 1, 2, 2, 1, 3]);
+ });
+
+ test('normalized data decodes to floats, as a loader reads it', async () => {
+ const mesh = await firstMesh(await glb({ normalizedUv: true }));
+ const color = mesh.geometry.getAttribute('color')!;
+ expect(color.itemSize).toBe(4);
+ expect(color.getX(0)).toBeCloseTo(1, 6);
+ expect(color.getY(0)).toBeCloseTo(128 / 255, 6);
+ expect(color.getZ(0)).toBe(0);
+ expect(color.getW(0)).toBeCloseTo(51 / 255, 6);
+ const uv2 = mesh.geometry.getAttribute('uv2')!;
+ expect(uv2.getX(1)).toBeCloseTo(0.25, 4);
+ expect(uv2.getY(1)).toBeCloseTo(0.5, 4);
+ });
+
+ test('unindexed, strip and fan primitives keep their triangle lists', async () => {
+ const unindexed = await firstMesh(
+ await glb({ indices: null, positions: [0, 0, 0, 1, 0, 0, 0, 1, 0] }),
+ );
+ expect(indices(unindexed)).toEqual([0, 1, 2]);
+ const strip = await firstMesh(
+ await glb({ mode: Primitive.Mode.TRIANGLE_STRIP, indices: [0, 1, 2, 3] }),
+ );
+ expect(indices(strip)).toEqual([0, 1, 2, 1, 3, 2]);
+ const fan = await firstMesh(
+ await glb({ mode: Primitive.Mode.TRIANGLE_FAN, indices: [0, 1, 2, 3] }),
+ );
+ expect(indices(fan)).toEqual([1, 2, 0, 2, 3, 0]);
+ });
+});
diff --git a/src/views/camera-capture.ts b/src/views/camera-capture.ts
index 477b07bf..d5f7a220 100644
--- a/src/views/camera-capture.ts
+++ b/src/views/camera-capture.ts
@@ -2,6 +2,7 @@ import {
enforceCapturePixels,
enforceCaptureBytes,
MAX_CAPTURE_SHOT_SIZE,
+ MIN_CAPTURE_SHOT_SIZE,
type CaptureLimits,
} from './capture-limits';
import {
@@ -12,9 +13,10 @@ import {
type ResolvedCameraShotV1,
} from './camera';
import { resolveCaptureBackdrop, type CaptureConfig } from './capture';
-import type { DerivativeCellRenderer, ViewGridResult } from './index';
+import type { BackdropId } from './background';
+import type { DerivativeCellRenderer, DerivativeCellRenderResult, ViewGridResult } from './index';
import { encodePng, decodePng } from './png';
-import { compositeCellGrid } from './grid';
+import { compositeCellGrid, PAD } from './grid';
import { annotateViewCell } from './annotate';
import type { DerivativeViewReceiptV1 } from '../composer/render-port';
import { reviewLodChains, withSubjectLevel } from './lod';
@@ -26,6 +28,22 @@ export interface CameraCaptureGridResult extends ViewGridResult {
* Present when the scene has chains. */
viewLevels?: number[][];
}
+export interface CaptureGridOptions {
+ /**
+ * The caller delivers `perFramePngs` for `output: 'separate'` and never reads the sheet, so it
+ * is neither built nor charged to the pixel budget; `png` is then empty.
+ */
+ framesOnly?: boolean;
+ /**
+ * Draws shots that change only the camera, all at once, from the artifact the scene was loaded
+ * from. A shot it leaves undefined, or every shot when it returns undefined, takes `render`.
+ */
+ renderExactShots?: (input: {
+ shots: ResolvedCameraShotV1[];
+ size: number;
+ backdrop: BackdropId;
+ }) => Promise<readonly (DerivativeCellRenderResult | undefined)[] | undefined>;
+}
export function validateAdvancedCapture(config: CaptureConfig): void {
for (const key of Object.keys(config))
if (!['version', 'shots', 'cols', 'size', 'output', 'backdrop'].includes(key))
@@ -43,9 +61,11 @@ export function validateAdvancedCapture(config: CaptureConfig): void {
throw new Error('capture.cols must be 1..3');
if (
config.size !== undefined &&
- (!Number.isInteger(config.size) || config.size < 128 || config.size > MAX_CAPTURE_SHOT_SIZE)
+ (!Number.isInteger(config.size) ||
+ config.size < MIN_CAPTURE_SHOT_SIZE ||
+ config.size > MAX_CAPTURE_SHOT_SIZE)
)
- throw new Error(`capture.size must be 128..${MAX_CAPTURE_SHOT_SIZE}`);
+ throw new Error(`capture.size must be ${MIN_CAPTURE_SHOT_SIZE}..${MAX_CAPTURE_SHOT_SIZE}`);
if (config.output !== undefined && !['grid', 'separate'].includes(config.output))
throw new Error('capture.output must be grid or separate');
resolveCaptureBackdrop(config.backdrop);
@@ -55,6 +75,7 @@ export async function renderCaptureGrid(
config: CaptureConfig,
render?: DerivativeCellRenderer,
limits?: CaptureLimits,
+ options: CaptureGridOptions = {},
): Promise<CameraCaptureGridResult> {
validateAdvancedCapture(config);
// A shot whose subject names a lower level of detail resolves and draws with that level in
@@ -76,34 +97,58 @@ export async function renderCaptureGrid(
const size = config.size ?? 384;
const cols = config.cols ?? Math.min(3, shots.length);
const backdrop = resolveCaptureBackdrop(config.backdrop);
- enforceCapturePixels(shots.length, size, cols, limits);
+ const framesOnly = options.framesOnly === true && config.output === 'separate';
+ enforceCapturePixels(shots.length, size, cols, limits, !framesOnly, true);
const cells: Uint8Array[] = [];
const perFramePngs: Buffer[] = [];
const derivativeReceipts: DerivativeViewReceiptV1[] = [];
- for (const { subject, shot } of plans) {
+ // Isolation, hidden parts and a lower level all change what draws, which the artifact cannot show.
+ const cameraOnly = plans.flatMap((plan, index) =>
+ plan.shot.visibility === 'context' &&
+ !plan.shot.hide?.length &&
+ plan.levels.every((level) => level === 0)
+ ? [index]
+ : [],
+ );
+ const drawn = new Map<number, DerivativeCellRenderResult>();
+ if (options.renderExactShots && cameraOnly.length) {
+ const results = await options.renderExactShots({
+ shots: cameraOnly.map((index) => plans[index]!.shot),
+ size,
+ backdrop,
+ });
+ results?.forEach((result, position) => {
+ if (result) drawn.set(cameraOnly[position]!, result);
+ });
+ }
+ for (const [index, { subject, shot }] of plans.entries()) {
const dir = shot.camera.position.map((n, i) => n - shot.camera.target[i]!) as [
number,
number,
number,
];
const view = { name: shot.name, dir };
- const png = await withSubjectLevel(root, subject, () =>
- withCameraVisibility(root, shot, async () => {
- if (render) {
- const result = await render({
- root,
- label: shot.name,
- view,
- size,
- camera: shot.camera,
- backdrop,
- });
- derivativeReceipts.push(result.receipt);
- return result.png;
- }
- return encodePng(rasterizeCamera(root, shot.camera, size, true, backdrop), size, size);
- }),
- );
+ const exact = drawn.get(index);
+ if (exact) derivativeReceipts.push(exact.receipt);
+ const png =
+ exact?.png ??
+ (await withSubjectLevel(root, subject, () =>
+ withCameraVisibility(root, shot, async () => {
+ if (render) {
+ const result = await render({
+ root,
+ label: shot.name,
+ view,
+ size,
+ camera: shot.camera,
+ backdrop,
+ });
+ derivativeReceipts.push(result.receipt);
+ return result.png;
+ }
+ return encodePng(rasterizeCamera(root, shot.camera, size, true, backdrop), size, size);
+ }),
+ ));
const decoded = decodePng(png);
if (decoded.width !== size || decoded.height !== size)
throw new Error('capture cell dimensions do not match request');
@@ -111,13 +156,14 @@ export async function renderCaptureGrid(
cells.push(decoded.rgb);
perFramePngs.push(encodePng(decoded.rgb, size, size));
}
- const { rgb, width, height } = compositeCellGrid(cells, size, cols);
- const png = encodePng(rgb, width, height);
+ const rows = Math.ceil(shots.length / cols);
+ const sheet = framesOnly ? undefined : compositeCellGrid(cells, size, cols);
+ const png = sheet ? encodePng(sheet.rgb, sheet.width, sheet.height) : Buffer.alloc(0);
enforceCaptureBytes(config.output === 'separate' ? perFramePngs : [png], limits);
return {
png,
- width,
- height,
+ width: sheet?.width ?? cols * size + (cols + 1) * PAD,
+ height: sheet?.height ?? rows * size + (rows + 1) * PAD,
views: shots.map((s) => s.name),
capture: {
preset: `${cols}x${Math.ceil(shots.length / cols)}`,
diff --git a/src/views/camera.ts b/src/views/camera.ts
index b6d46768..bc58e98e 100644
--- a/src/views/camera.ts
+++ b/src/views/camera.ts
@@ -1,5 +1,12 @@
import { Vector3, Matrix4, Euler, Group, type Object3D } from 'three';
-import { collectTriangles, compositingOrder, measureBounds, orbitDir } from './raster';
+import {
+ collectTriangles,
+ compositingOrder,
+ measureBounds,
+ measureDrawnGeometry,
+ nearestDrawnTriangleDistance,
+ orbitDir,
+} from './raster';
import { resolveBackdrop, type BackdropId } from './background';
import { cloneReviewScene } from './scene-copy';
import { visibleNormalSign } from './face-policy';
@@ -180,15 +187,7 @@ export function defaultPerspectiveNear(root: unknown, position: CameraVec3, far:
deforms = true;
});
if (deforms) return FLOOR;
- const [px, py, pz] = position;
- let nearest = Number.POSITIVE_INFINITY;
- for (const { v } of collectTriangles(root as Object3D).tris) {
- const dx = Math.max(Math.min(v[0]!, v[3]!, v[6]!) - px, 0, px - Math.max(v[0]!, v[3]!, v[6]!));
- const dy = Math.max(Math.min(v[1]!, v[4]!, v[7]!) - py, 0, py - Math.max(v[1]!, v[4]!, v[7]!));
- const dz = Math.max(Math.min(v[2]!, v[5]!, v[8]!) - pz, 0, pz - Math.max(v[2]!, v[5]!, v[8]!));
- nearest = Math.min(nearest, Math.sqrt(dx * dx + dy * dy + dz * dz));
- if (nearest === 0) break;
- }
+ const nearest = nearestDrawnTriangleDistance(root, position);
if (!Number.isFinite(nearest)) return FLOOR;
return Math.max(FLOOR, Math.min(nearest / 2, far / 2));
}
@@ -305,9 +304,8 @@ export function resolveAssetCamera(root: unknown, shot: CameraShotV1 = {}): Reso
const rootNode = root as Object3D;
rootNode.updateMatrixWorld(true);
const selected = selectCameraSubject(root, shot.subject);
- const bounds = measureBounds(selected.node);
- if (!collectTriangles(selected.node).tris.length)
- throw new Error(`subject ${selected.path} has no visible geometry`);
+ const { triangles, ...bounds } = measureDrawnGeometry(selected.node);
+ if (!triangles) throw new Error(`subject ${selected.path} has no visible geometry`);
const request = shot.camera ?? { type: 'orbit' };
let camera: ResolvedAssetCameraV1;
if (request.type === 'orbit') {
diff --git a/src/views/capture-cache.ts b/src/views/capture-cache.ts
index 6dcd6d23..cea92be6 100644
--- a/src/views/capture-cache.ts
+++ b/src/views/capture-cache.ts
@@ -227,6 +227,7 @@ export function createCachedRenderPort(
reused: selectors.length - missing.length,
total: selectors.length,
},
+ captureCacheHits: selectors.map((_, index) => !missing.includes(index)),
};
};
}
diff --git a/src/views/capture-limits.ts b/src/views/capture-limits.ts
index 2dafc490..fac60dbf 100644
--- a/src/views/capture-limits.ts
+++ b/src/views/capture-limits.ts
@@ -9,6 +9,7 @@ export interface CaptureLimits {
* is its top legacy rung; the capture pixel and byte budgets below bound the sheet.
*/
export const MAX_CAPTURE_SHOT_SIZE = 2048;
+export const MIN_CAPTURE_SHOT_SIZE = 128;
export const DEFAULT_CAPTURE_LIMITS = Object.freeze({
maxTotalPixels: 24_000_000,
maxOutputBytes: 32 * 1024 * 1024,
@@ -25,12 +26,36 @@ export function resolveCaptureLimits(limits: CaptureLimits = {}) {
}
return result;
}
+/** Pixels a capture allocates: every cell, and the sheet they compose into when one is built. */
+function capturePixels(cells: number, size: number, cols: number, compose: boolean): number {
+ const rows = Math.ceil(cells / cols);
+ return (
+ cells * size * size +
+ (compose ? (cols * size + (cols + 1) * PAD) * (rows * size + (rows + 1) * PAD) : 0)
+ );
+}
+/** Largest shot size under the budget, or undefined when even the smallest shot is over it. */
+function largestShotSize(
+ cells: number,
+ cols: number,
+ compose: boolean,
+ maxTotalPixels: number,
+): number | undefined {
+ for (let size = MAX_CAPTURE_SHOT_SIZE; size >= MIN_CAPTURE_SHOT_SIZE; size--)
+ if (capturePixels(cells, size, cols, compose) <= maxTotalPixels) return size;
+ return undefined;
+}
+/**
+ * `nameFit` is for a capture whose caller chose the shots and their size: the error then says
+ * which sizes fit, since the bare count gives a model nothing to change.
+ */
export function enforceCapturePixels(
cells: number,
size: number,
cols: number,
limits?: CaptureLimits,
compose = true,
+ nameFit = false,
) {
if (
!Number.isSafeInteger(cells) ||
@@ -41,14 +66,22 @@ export function enforceCapturePixels(
cols < 1
)
throw new Error('invalid capture dimensions');
- const pixels =
- cells * size * size +
- (compose
- ? (cols * size + (cols + 1) * PAD) *
- (Math.ceil(cells / cols) * size + (Math.ceil(cells / cols) + 1) * PAD)
- : 0);
- if (pixels > resolveCaptureLimits(limits).maxTotalPixels)
- throw new Error(`capture pixel budget exceeded: ${pixels}`);
+ const pixels = capturePixels(cells, size, cols, compose);
+ const { maxTotalPixels } = resolveCaptureLimits(limits);
+ if (pixels > maxTotalPixels) {
+ const exceeded = `capture pixel budget exceeded: ${pixels} pixels against a limit of ${maxTotalPixels}`;
+ if (!nameFit) throw new Error(`${exceeded}.`);
+ const asGrid = compose ? largestShotSize(cells, cols, true, maxTotalPixels) : undefined;
+ const separate = largestShotSize(cells, cols, false, maxTotalPixels);
+ let fits = 'Use fewer shots.';
+ if (separate !== undefined)
+ fits = compose
+ ? `Largest size that fits: ${asGrid ?? 'none'} as a grid, ${separate} with output: "separate".`
+ : `Largest size that fits: ${separate}.`;
+ throw new Error(
+ `${exceeded} (${cells} shots at size ${size}${compose ? ', plus their grid sheet' : ''}). ${fits}`,
+ );
+ }
return pixels;
}
export function enforceCaptureBytes(images: readonly Uint8Array[], limits?: CaptureLimits) {
diff --git a/src/views/glb.ts b/src/views/glb.ts
index c085942b..c80b3699 100644
--- a/src/views/glb.ts
+++ b/src/views/glb.ts
@@ -244,6 +244,10 @@ export function geometryFlatTextureReasonCode(mimeType: string | null): GlbGeome
}
function decodedAccessor(accessor: Accessor): Float64Array {
+ // An unnormalized element reads as the stored value, so the array copies directly. This is the
+ // geometry of every shot and every repeat: a per-element read costs seconds on a large asset.
+ const stored = accessor.getArray();
+ if (stored && !accessor.getNormalized()) return new Float64Array(stored);
const itemSize = accessor.getElementSize();
const output = new Float64Array(accessor.getCount() * itemSize);
const element: number[] = [];
@@ -256,17 +260,26 @@ function decodedAccessor(accessor: Accessor): Float64Array {
return output;
}
+/** The same decode as a float attribute takes, stored the way a BufferAttribute holds it. */
+function decodedFloat32(accessor: Accessor): Float32Array {
+ const stored = accessor.getArray();
+ return new Float32Array(stored && !accessor.getNormalized() ? stored : decodedAccessor(accessor));
+}
+
function triangleIndices(
primitive: import('@gltf-transform/core').Primitive,
vertexCount: number,
): Uint32Array | undefined {
const sourceAccessor = primitive.getIndices();
- const source = sourceAccessor
- ? Array.from(decodedAccessor(sourceAccessor), (value) => Math.trunc(value))
- : Array.from({ length: vertexCount }, (_, index) => index);
+ let source: Uint32Array;
+ if (sourceAccessor) source = new Uint32Array(decodedAccessor(sourceAccessor));
+ else {
+ source = new Uint32Array(vertexCount);
+ for (let index = 0; index < vertexCount; index++) source[index] = index;
+ }
switch (primitive.getMode()) {
case Primitive.Mode.TRIANGLES:
- return Uint32Array.from(source);
+ return source;
case Primitive.Mode.TRIANGLE_STRIP: {
const triangles: number[] = [];
for (let index = 0; index + 2 < source.length; index++) {
@@ -675,16 +688,10 @@ function reviewSceneFromDocument(
const atlasBinding = primitive.getExtras()['kilnAtlasBinding'];
if (atlasBinding !== undefined && atlas)
geometry.userData.kilnAtlasBinding = expandAtlasBinding(atlasBinding, atlas);
- geometry.setAttribute(
- 'position',
- new BufferAttribute(Float32Array.from(decodedAccessor(position)), 3),
- );
+ geometry.setAttribute('position', new BufferAttribute(decodedFloat32(position), 3));
const normal = primitive.getAttribute('NORMAL');
if (normal) {
- geometry.setAttribute(
- 'normal',
- new BufferAttribute(Float32Array.from(decodedAccessor(normal)), 3),
- );
+ geometry.setAttribute('normal', new BufferAttribute(decodedFloat32(normal), 3));
}
// Texture bindings retain their UV channel, so retain the matching vertex data too.
for (let channel = 0; channel < 4; channel++) {
@@ -692,21 +699,18 @@ function reviewSceneFromDocument(
if (uv)
geometry.setAttribute(
channel ? `uv${channel}` : 'uv',
- new BufferAttribute(Float32Array.from(decodedAccessor(uv)), 2),
+ new BufferAttribute(decodedFloat32(uv), 2),
);
}
const color = primitive.getAttribute('COLOR_0');
if (color)
geometry.setAttribute(
'color',
- new BufferAttribute(Float32Array.from(decodedAccessor(color)), color.getElementSize()),
+ new BufferAttribute(decodedFloat32(color), color.getElementSize()),
);
const tangent = primitive.getAttribute('TANGENT');
if (tangent) {
- geometry.setAttribute(
- 'tangent',
- new BufferAttribute(Float32Array.from(decodedAccessor(tangent)), 4),
- );
+ geometry.setAttribute('tangent', new BufferAttribute(decodedFloat32(tangent), 4));
}
geometry.setIndex(new BufferAttribute(indices, 1));
if (targetCount) {
@@ -737,7 +741,7 @@ function reviewSceneFromDocument(
const attributes = targets.map((target) => {
const attribute = target.getAttribute(semantic);
const values = attribute
- ? Float32Array.from(decodedAccessor(attribute))
+ ? decodedFloat32(attribute)
: new Float32Array(position.getCount() * 3);
if (!values.every(Number.isFinite)) morphError(`nonfinite ${semantic} displacement.`);
return new BufferAttribute(values, 3);
@@ -770,10 +774,7 @@ function reviewSceneFromDocument(
'skinIndex',
new BufferAttribute(Uint16Array.from(decodedAccessor(skinIndices)), 4),
);
- geometry.setAttribute(
- 'skinWeight',
- new BufferAttribute(Float32Array.from(decodedAccessor(skinWeights)), 4),
- );
+ geometry.setAttribute('skinWeight', new BufferAttribute(decodedFloat32(skinWeights), 4));
}
const threeMaterial = new MeshStandardMaterial({
vertexColors: color !== null,
diff --git a/src/views/port.ts b/src/views/port.ts
index ddf8f069..1e9b1367 100644
--- a/src/views/port.ts
+++ b/src/views/port.ts
@@ -5,7 +5,12 @@ import {
type CaptureLimits,
} from './capture-limits';
import type { PbrRenderPort } from '../composer/render-port';
-import { validateResolvedAssetCamera, type ResolvedAssetCameraV1 } from './camera';
+import {
+ validateResolvedAssetCamera,
+ type ResolvedAssetCameraV1,
+ type ResolvedCameraShotV1,
+} from './camera';
+import type { DerivativeCellRenderResult } from './index';
import {
resolveGridCapture,
type CaptureConfig,
@@ -15,6 +20,9 @@ import {
import { decodePng } from './png';
import { compositeViewPngGrid } from './grid';
export const DEFAULT_VIEW_RENDER_TIMEOUT_MS = 8000;
+/** What one render request may carry; the render service refuses anything more. */
+export const MAX_CAMERAS_PER_REQUEST = 12;
+export const MAX_PIXELS_PER_REQUEST = 16_777_216;
export async function sha256Bytes(bytes: Uint8Array): Promise<`sha256:${string}`> {
const input = new Uint8Array(bytes.byteLength);
@@ -47,6 +55,7 @@ export type PortViewPngsOutcome =
pngs: Uint8Array[];
rendererId: string;
captureCache?: { hit: boolean; reused: number; total: number };
+ captureCacheHits?: boolean[];
derivativeFidelityAttested: boolean;
inputGlbSha256?: `sha256:${string}`;
}
@@ -161,6 +170,7 @@ export async function captureViewPngsViaPort(
pngs: result.viewsPng.map((png) => Uint8Array.from(png)),
rendererId: result.rendererId,
...(result.captureCache ? { captureCache: result.captureCache } : {}),
+ ...(result.captureCacheHits ? { captureCacheHits: result.captureCacheHits } : {}),
derivativeFidelityAttested: result.derivativeFidelity?.materialFaithful === true,
...(result.derivativeFidelity ? { inputGlbSha256 } : {}),
};
@@ -172,6 +182,111 @@ export async function captureViewPngsViaPort(
}
}
+/** How many shots of one size go in each render request, in order. */
+export function exactShotRequestSizes(shots: number, size: number): number[] {
+ const fit = Math.max(
+ 1,
+ Math.min(MAX_CAMERAS_PER_REQUEST, Math.floor(MAX_PIXELS_PER_REQUEST / (size * size))),
+ );
+ const sizes: number[] = [];
+ for (let left = shots; left > 0; left -= fit) sizes.push(Math.min(left, fit));
+ return sizes;
+}
+
+/**
+ * The shot indices of each render request. Projections stay in separate requests: the renderer
+ * compiles a material's view direction for the first camera that draws it and reuses that shader
+ * for the scene's later cameras, so a perspective camera after an orthographic one in the same
+ * request comes back shaded wrong.
+ */
+function exactShotRequests(shots: readonly ResolvedCameraShotV1[], size: number): number[][] {
+ const byProjection = new Map<string, number[]>();
+ for (const [index, shot] of shots.entries()) {
+ const group = byProjection.get(shot.camera.projection);
+ if (group) group.push(index);
+ else byProjection.set(shot.camera.projection, [index]);
+ }
+ const requests: number[][] = [];
+ for (const indices of byProjection.values()) {
+ let start = 0;
+ for (const count of exactShotRequestSizes(indices.length, size)) {
+ requests.push(indices.slice(start, start + count));
+ start += count;
+ }
+ }
+ return requests;
+}
+
+/**
+ * Draw shots that change only the camera from the artifact bytes themselves: one request per
+ * projection and service limit, so the renderer loads the scene once for them and a capture cache
+ * answers before any upload. `timeoutMs` is one shot's deadline and each request gets one per camera
+ * it carries, as separate requests would have; {@link captureViewPngsViaPort} enforces it, the
+ * single owner of that policy. Never throws. A shot left undefined was not drawn, because its request failed or
+ * its renderer differed from the earlier ones, and takes the caller's per-shot route with its own
+ * degrade; a cancellation surfaces there too.
+ */
+export async function captureExactArtifactShotsViaPort(
+ port: PbrRenderPort,
+ glb: Buffer | Uint8Array,
+ timeoutMs: number,
+ shots: readonly ResolvedCameraShotV1[],
+ size: number,
+ options: {
+ /** Whether these bytes are the artifact a caller can select: see {@link ViewFidelityV1}. */
+ exactArtifact: boolean;
+ limits?: CaptureLimits;
+ backdrop?: import('./background').BackdropId;
+ execution?: { signal?: AbortSignal };
+ },
+): Promise<(DerivativeCellRenderResult | undefined)[]> {
+ const cells: (DerivativeCellRenderResult | undefined)[] = shots.map(() => undefined);
+ let rendererId: string | undefined;
+ for (const indices of exactShotRequests(shots, size)) {
+ const batch = indices.map((index) => shots[index]!);
+ // `timeoutMs` is one shot's deadline; a request draws a view per camera, so it gets one each.
+ const result = await captureViewPngsViaPort(
+ port,
+ glb,
+ timeoutMs * batch.length,
+ batch.map(
+ ({ camera }) =>
+ camera.position.map((n, axis) => n - camera.target[axis]!) as [number, number, number],
+ ),
+ size,
+ batch.map((shot) => shot.camera),
+ options.limits,
+ options.backdrop,
+ options.execution,
+ );
+ if (!result.ok || !result.derivativeFidelityAttested || !result.inputGlbSha256) break;
+ if (rendererId !== undefined && rendererId !== result.rendererId) break;
+ rendererId = result.rendererId;
+ for (const [index, shot] of batch.entries()) {
+ const hit = result.captureCacheHits?.[index];
+ cells[indices[index]!] = {
+ png: Buffer.from(result.pngs[index]!),
+ receipt: {
+ version: 'kiln.view-fidelity.v1',
+ derivativeLabel: shot.name,
+ requested: 'full-preferred',
+ delivered: 'full-material',
+ exactArtifact: options.exactArtifact,
+ rendererId: result.rendererId,
+ materialFaithful: true,
+ degraded: false,
+ inputGlbSha256: result.inputGlbSha256,
+ camera: shot.camera,
+ cameraFidelity: 'echo-validated',
+ ...(hit === undefined ? {} : { captureCache: { hit, reused: hit ? 1 : 0, total: 1 } }),
+ ...(options.exactArtifact ? {} : { reasonCodes: ['IN_LOOP_BUILD_NOT_PERSISTED'] }),
+ },
+ };
+ }
+ }
+ return cells;
+}
+
/**
* Call the host view-render port with the ALREADY-PRODUCED GLB bytes and
* composite its per-view PNGs into the same grid the CPU path emits.
@@ -205,22 +320,21 @@ export async function captureViewsViaPort(
const { loadGlbReviewScene } = await import('./index');
const { renderCaptureGrid } = await import('./camera-capture');
const { withoutHiddenMeshes } = await import('./camera');
- const { renderSceneToGLB } = await import('../render');
+ const { renderReviewDerivativeGlb } = await import('../render');
const loaded = await loadGlbReviewScene(Uint8Array.from(glb));
- let rendererId = '';
const grid = await renderCaptureGrid(
loaded.root,
capture,
async (input) => {
execution?.signal?.throwIfAborted();
// An isolated shot hides the other meshes; send the GPU only what it may draw.
- const derivative = await renderSceneToGLB(
+ const derivative = await renderReviewDerivativeGlb(
withoutHiddenMeshes(input.root as import('three').Object3D),
- { derivative: true, gltfExporter: 'three' },
+ { gltfExporter: 'three' },
);
const result = await captureViewPngsViaPort(
port,
- derivative.bytes,
+ derivative,
timeoutMs,
[input.view.dir],
input.size,
@@ -232,9 +346,6 @@ export async function captureViewsViaPort(
if (!result.ok) throw new Error(result.reason);
if (!result.derivativeFidelityAttested || !result.inputGlbSha256)
throw new Error('advanced capture requires derivative material receipt');
- if (rendererId && rendererId !== result.rendererId)
- throw new Error('capture renderer changed between cells');
- rendererId = result.rendererId;
return {
png: Buffer.from(result.pngs[0]!),
receipt: {
@@ -254,11 +365,23 @@ export async function captureViewsViaPort(
};
},
limits,
+ {
+ renderExactShots: ({ shots, size, backdrop }) =>
+ captureExactArtifactShotsViaPort(port, glb, timeoutMs, shots, size, {
+ // These are the bytes the caller produced, which is what it asked to see.
+ exactArtifact: true,
+ ...(limits ? { limits } : {}),
+ backdrop,
+ ...(execution ? { execution } : {}),
+ }),
+ },
);
+ const rendererIds = new Set(grid.derivativeReceipts.map((receipt) => receipt.rendererId));
+ if (rendererIds.size > 1) throw new Error('capture renderer changed between cells');
return {
ok: true,
png: grid.png,
- rendererId,
+ rendererId: grid.derivativeReceipts[0]!.rendererId,
capture: grid.capture!,
width: grid.width,
height: grid.height,
diff --git a/src/views/raster.ts b/src/views/raster.ts
index 88384ecc..eb79d459 100644
--- a/src/views/raster.ts
+++ b/src/views/raster.ts
@@ -525,22 +525,119 @@ export function rasterizeView(
return out;
}
-/** World-space AABB of a (possibly sandbox-created) scene's drawable geometry.
- * Reuses the rasterizer's own triangle collection so the box matches exactly what
- * gets drawn. Empty scenes report a zero box. Used by the animation grid to union
- * bounds across posed frames into one steady camera framing. */
+/** The position attribute and world matrix of a drawn mesh, under the rasterizer's own rules. */
+function drawnMeshPositions(obj: unknown):
+ | {
+ mesh: DuckMesh;
+ position: DuckAttribute;
+ matrix: ArrayLike<number>;
+ }
+ | undefined {
+ const mesh = obj as DuckMesh;
+ if (!mesh.isMesh) return undefined;
+ const position = mesh.geometry?.getAttribute?.('position');
+ const matrix = mesh.matrixWorld?.elements;
+ if (position?.itemSize !== 3 || !matrix) return undefined;
+ return { mesh, position, matrix };
+}
+
+/**
+ * The box and triangle count of what `collectTriangles` draws, in one walk over positions: no
+ * per-triangle record, so measuring a scene costs its vertices and not its garbage. The box covers
+ * every position of every drawn mesh, as the rasterizer's does, and is zero when nothing draws.
+ */
+export function measureDrawnGeometry(root: unknown): {
+ min: [number, number, number];
+ max: [number, number, number];
+ triangles: number;
+} {
+ updateSurfaceMatrices(root as DuckObject3D);
+ const min: Vec3 = [Infinity, Infinity, Infinity];
+ const max: Vec3 = [-Infinity, -Infinity, -Infinity];
+ let triangles = 0;
+ forEachDrawn(root as DuckObject3D, (obj) => {
+ const drawn = drawnMeshPositions(obj);
+ if (!drawn) return;
+ const { mesh, position, matrix: m } = drawn;
+ const readVertex = surfaceVertexReader(mesh, position);
+ for (let i = 0; i < position.count; i++) {
+ const { x, y, z } = readVertex(i);
+ const wx = m[0]! * x + m[4]! * y + m[8]! * z + m[12]!;
+ const wy = m[1]! * x + m[5]! * y + m[9]! * z + m[13]!;
+ const wz = m[2]! * x + m[6]! * y + m[10]! * z + m[14]!;
+ if (wx < min[0]) min[0] = wx;
+ if (wy < min[1]) min[1] = wy;
+ if (wz < min[2]) min[2] = wz;
+ if (wx > max[0]) max[0] = wx;
+ if (wy > max[1]) max[1] = wy;
+ if (wz > max[2]) max[2] = wz;
+ }
+ triangles += Math.floor((mesh.geometry!.index?.count ?? position.count) / 3);
+ });
+ if (!Number.isFinite(min[0])) return { min: [0, 0, 0], max: [0, 0, 0], triangles };
+ return { min, max, triangles };
+}
+
+/** How far `at` lies outside the span of three coordinates; zero inside it. */
+function gapToInterval(a: number, b: number, c: number, at: number): number {
+ return Math.max(Math.min(a, b, c) - at, 0, at - Math.max(a, b, c));
+}
+
+/**
+ * Distance from a point to the nearest drawn triangle's world box, without a record per triangle.
+ * Infinity when nothing draws. Each mesh's world positions are computed once and shared by its
+ * triangles.
+ */
+export function nearestDrawnTriangleDistance(
+ root: unknown,
+ point: readonly [number, number, number],
+): number {
+ updateSurfaceMatrices(root as DuckObject3D);
+ const [px, py, pz] = point;
+ let nearest = Number.POSITIVE_INFINITY;
+ forEachDrawn(root as DuckObject3D, (obj) => {
+ if (nearest === 0) return;
+ const drawn = drawnMeshPositions(obj);
+ if (!drawn) return;
+ const { mesh, position, matrix: m } = drawn;
+ const readVertex = surfaceVertexReader(mesh, position);
+ const world = new Float64Array(position.count * 3);
+ for (let i = 0; i < position.count; i++) {
+ const { x, y, z } = readVertex(i);
+ world[i * 3] = m[0]! * x + m[4]! * y + m[8]! * z + m[12]!;
+ world[i * 3 + 1] = m[1]! * x + m[5]! * y + m[9]! * z + m[13]!;
+ world[i * 3 + 2] = m[2]! * x + m[6]! * y + m[10]! * z + m[14]!;
+ }
+ const index = mesh.geometry!.index;
+ const slots = index ? index.count : position.count;
+ for (let i = 0; i + 2 < slots && nearest !== 0; i += 3) {
+ const a = (index ? index.array[i]! : i) * 3;
+ const b = (index ? index.array[i + 1]! : i + 1) * 3;
+ const c = (index ? index.array[i + 2]! : i + 2) * 3;
+ const dx = gapToInterval(world[a]!, world[b]!, world[c]!, px);
+ const dy = gapToInterval(world[a + 1]!, world[b + 1]!, world[c + 1]!, py);
+ const dz = gapToInterval(world[a + 2]!, world[b + 2]!, world[c + 2]!, pz);
+ nearest = Math.min(nearest, Math.sqrt(dx * dx + dy * dy + dz * dz));
+ }
+ });
+ return nearest;
+}
+
+/** World-space AABB of a (possibly sandbox-created) scene's drawable geometry: the box
+ * the rasterizer draws within. Empty scenes report a zero box. Used by the animation
+ * grid to union bounds across posed frames into one steady camera framing. */
export function measureBounds(root: unknown): {
min: [number, number, number];
max: [number, number, number];
} {
- const { bbox } = collectTriangles(root as DuckObject3D);
- return { min: [...bbox.min], max: [...bbox.max] };
+ const { min, max } = measureDrawnGeometry(root);
+ return { min, max };
}
/** Unlike camera framing, an empty part has no measurable geometry bounds. */
export function measurePartBounds(root: unknown): ReturnType<typeof measureBounds> | null {
- const { tris, bbox } = collectTriangles(root as DuckObject3D);
- return tris.length ? { min: [...bbox.min], max: [...bbox.max] } : null;
+ const { min, max, triangles } = measureDrawnGeometry(root);
+ return triangles ? { min, max } : null;
}
/**