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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Export each shot derivative once and decode each frame once (#348)
Matthew Kissinger7b48cac1855b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cb934d0e..f8335143 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,26 @@ does not publish a package.## Unreleased+- A review shot no longer exports the same derivative GLB, or decodes the same frame, more than once.+ Measured on the 2,635,224-triangle cathedral against a warm GPU service (two runs each):+ - Shots that draw the same scene state share one derivative export, within a call and across calls on+ the same artifact. A repeated isolated shot goes from 3.8–4.2 s to 1.6–1.9 s, the same part from a new+ camera from 6.0–6.2 s to 2.3–2.8 s, and a repeated `kiln_inspect` shot from 5.6–5.9 s to 1.5–1.7 s.+ The key is read off the scene as the shot leaves it, not off the request. It covers:+ - the artifact hash and the export options;+ - every node's visibility, transform and place in the tree;+ - each geometry attribute's identity and edit version;+ - every material property, and each texture's identity, version and transform;+ - morph weights, skinned bone poses and instance buffers.++ A hidden part or a posed clip therefore exports its own bytes. A shot of a lower level of detail,+ or a scene holding anything added after it was loaded, has no key and exports every time, as+ before. The host keeps up to 64 MB of derivatives for its lifetime.+ - The capture cache's check, the port's trust check and the annotator decode one frame once between+ them, keyed by its bytes. A fully cached 9-shot call goes from 4.0–4.6 s to 2.8 s. The host keeps up+ to 64 MB of decoded frames for its lifetime.+ - Images, hashes and receipts are unchanged.+- `kiln_render` and `kiln_edit` draw `shots` that change only the camera from the artifact itself, in onerequest per projection and service limit, after asking the capture cache. On a 2.6M-triangle cathedral onNode 22.23.4, nine shots at 1000 px on a built program went from 301 s to 7.1 s, all nine cached fromdiff --git a/src/tools/__tests__/derivative-reuse.test.ts b/src/tools/__tests__/derivative-reuse.test.tsnew file mode 100644index 00000000..835ab962--- /dev/null+++ b/src/tools/__tests__/derivative-reuse.test.ts@@ -0,0 +1,181 @@+import { createHash } from 'node:crypto';+import { describe, expect, spyOn, test } from 'bun:test';++import * as renderModule from '../../render';+import * as pngModule from '../../views/png';+import type { PbrRenderPort, PbrRenderRequest } from '../../composer/render-port';+import { encodePng } from '../../views';+import { captureViewsViaPort } from '../../views/port';+import {+ createKilnProgramToolRegistry,+ type KilnInspectResult,+ type KilnRenderViewsResult,+ type KilnToolContext,+} from '../registry';++/** The host's tool set, so the capture cache wraps the port as it does in a session. */+function tool(name: string, context: KilnToolContext) {+ const def = createKilnProgramToolRegistry(context).find((candidate) => candidate.name === name);+ if (!def) throw new Error(`no ${name}`);+ return def;+}++const CODE = `+const meta = { name: 'pair', category: 'prop' };+function build() {+ const root = createRoot('Root');+ createPart('Left', boxGeo(1, 1, 1), gameMaterial('#cc3333'), { parent: root, position: [-1, 0, 0] });+ createPart('Right', boxGeo(1, 1, 1), gameMaterial('#3333cc'), { parent: root, position: [1, 0, 0] });+ return root;+}`;++function framePng(size: number, seed: number): Uint8Array {+ const rgb = new Uint8Array(size * size * 3);+ for (let i = 0; i < rgb.length; i++) rgb[i] = (i + seed * 13) % 251;+ return new Uint8Array(encodePng(rgb, size, size));+}++const sha = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;++/** Frames carry `salt`, so one test's frames are never already decoded by another's. */+function gpuPort(requests: PbrRenderRequest[], salt = 0): PbrRenderPort {+ return async (request) => {+ requests.push(request);+ return {+ ok: true,+ rendererId: 'gpu:derivative-reuse',+ cameras: request.cameras,+ width: request.width,+ height: request.height,+ viewsPng: (request.cameras ?? []).map((_, i) =>+ framePng(request.width!, salt * 1000 + requests.length * 10 + i),+ ),+ derivativeFidelity: {+ materialFaithful: true,+ inputGlbSha256: sha(request.glb) as `sha256:${string}`,+ },+ };+ };+}++const orbit = (azimuthDeg: number, extra: Record<string, unknown> = {}) => ({+ name: `S${azimuthDeg}`,+ camera: { type: 'orbit', azimuthDeg, elevationDeg: 20 },+ ...extra,+});++describe('one derivative export per scene state', () => {+ test('isolated shots of one part share one export, and a later call on the same artifact reuses it', async () => {+ const requests: PbrRenderRequest[] = [];+ const def = tool('kiln_render', {+ viewRenderPort: gpuPort(requests),+ captureCacheIdentity: 'derivative-reuse-1',+ });+ const exportSpy = spyOn(renderModule, 'renderReviewDerivativeGlb');+ try {+ const isolate = (az: number, part = 'Left') =>+ orbit(az, { subject: { path: `/pair[0]/Root[0]/Mesh_${part}[0]` }, visibility: 'isolate' });+ const first = (await def.run({+ code: CODE,+ capture: {+ version: 'kiln.capture.v1',+ size: 128,+ shots: [isolate(30), isolate(60), isolate(90), isolate(30, 'Right')],+ },+ })) as KilnRenderViewsResult;+ expect(first.ok).toBe(true);+ expect(requests).toHaveLength(4);+ // The left part three times and the right part once: two scene states, two exports.+ expect(exportSpy).toHaveBeenCalledTimes(2);+ const hashes = requests.map((request) => sha(request.glb));+ expect(new Set(hashes.slice(0, 3)).size).toBe(1);+ expect(hashes[3]).not.toBe(hashes[0]);++ // A new call loads the artifact again; a new camera on a known state exports nothing.+ const second = (await def.run({+ programRef: (first as { programRef?: string }).programRef!,+ capture: { version: 'kiln.capture.v1', size: 128, shots: [isolate(120)] },+ })) as KilnRenderViewsResult;+ expect(second.ok).toBe(true);+ expect(exportSpy).toHaveBeenCalledTimes(2);+ expect(sha(requests[4]!.glb)).toBe(hashes[0]!);+ } finally {+ exportSpy.mockRestore();+ }+ });++ test('a shot that hides a part, or draws back faces, exports its own state', async () => {+ const requests: PbrRenderRequest[] = [];+ const def = tool('kiln_render', {+ viewRenderPort: gpuPort(requests),+ captureCacheIdentity: 'derivative-reuse-2',+ });+ const result = (await def.run({+ code: CODE,+ capture: {+ version: 'kiln.capture.v2',+ size: 128,+ shots: [orbit(0), orbit(0, { name: 'hidden', hide: ['/pair[0]/Root[0]/Mesh_Right[0]'] })],+ },+ })) as KilnRenderViewsResult;+ expect(result.ok).toBe(true);+ expect(requests).toHaveLength(2);+ expect(sha(requests[0]!.glb)).not.toBe(sha(requests[1]!.glb));+ });++ test('a repeated kiln_inspect shot reuses the export and decodes its frame once', async () => {+ const requests: PbrRenderRequest[] = [];+ const def = tool('kiln_inspect', {+ viewRenderPort: gpuPort(requests, 3),+ captureCacheIdentity: 'derivative-reuse-3',+ });+ const shot = orbit(41);+ const decodeSpy = spyOn(pngModule, 'decodePng');+ let exportSpy: ReturnType<typeof spyOn> | undefined;+ try {+ const first = (await def.run({ code: CODE, shot, detail: 'full' })) as KilnInspectResult;+ expect(first.ok).toBe(true);+ // The cache check, the port's trust check and the annotator read one new frame: one decode.+ expect(decodeSpy).toHaveBeenCalledTimes(1);+ exportSpy = spyOn(renderModule, 'renderReviewDerivativeGlb');+ const second = (await def.run({ code: CODE, shot, detail: 'full' })) as KilnInspectResult;+ expect(second.ok).toBe(true);+ expect(second.viewFidelity?.receipts[0]?.captureCache?.hit).toBe(true);+ expect(second.pngBase64).toBe(first.pngBase64);+ expect(exportSpy).toHaveBeenCalledTimes(0);+ expect(decodeSpy).toHaveBeenCalledTimes(1);+ } finally {+ exportSpy?.mockRestore();+ decodeSpy.mockRestore();+ }+ });+});++describe('one derivative export per scene state, generation path', () => {+ test('captureViewsViaPort exports each hidden-part state once', async () => {+ const source = await renderModule.renderSceneToGLB(+ (await renderModule.executeKilnCode(CODE)).root,+ );+ const requests: PbrRenderRequest[] = [];+ const exportSpy = spyOn(renderModule, 'renderReviewDerivativeGlb');+ try {+ const hideRight = (azimuthDeg: number) => ({+ name: `H${azimuthDeg}`,+ camera: { type: 'orbit' as const, azimuthDeg, elevationDeg: 20 },+ hide: ['Mesh_Right'],+ });+ const result = await captureViewsViaPort(gpuPort(requests), source.bytes, 5000, {+ version: 'kiln.capture.v2',+ size: 128,+ shots: [hideRight(0), hideRight(90), { ...hideRight(180), hide: ['Mesh_Left'] }],+ });+ expect(result.ok).toBe(true);+ expect(requests).toHaveLength(3);+ expect(exportSpy).toHaveBeenCalledTimes(2);+ expect(sha(requests[0]!.glb)).toBe(sha(requests[1]!.glb));+ expect(sha(requests[2]!.glb)).not.toBe(sha(requests[0]!.glb));+ } finally {+ exportSpy.mockRestore();+ }+ });+});diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 8b05a473..26eaa924 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -471,6 +471,11 @@ async function loadEvaluatedReviewScene(code: string, context: KilnToolContext)}const { loadGlbReviewScene } = await import('../views');const scene = await loadGlbReviewScene(rendered.glb);+ // Shots of one scene state, in this call or a later one on the same artifact, share an export.+ (await import('../views/derivative-memo')).registerReviewArtifact(+ scene.root,+ rendered.artifactGlbSha256,+ );return { rendered, ...scene };}@@ -501,25 +506,34 @@ async function renderDerivativeCell(input: import('../views').DerivativeCellRenderInput,context: KilnToolContext,): Promise<import('../views').DerivativeCellRenderResult> {- let derivativeRoot = input.root as THREE.Object3D;- if (input.backfaceCull === false) {- const { cloneReviewScene } = await import('../views/scene-copy');- derivativeRoot = cloneReviewScene(derivativeRoot, { omitHidden: true, doubleSided: true });- }- // `withCameraVisibility` and `isolateSubtree` express isolation by clearing- // `mesh.visible`. The CPU rasterizer culls on that flag (see views/raster.ts),- // but glTF carries no per-mesh visibility, so serializing unfiltered ships the- // hidden geometry to the GPU service and makes isolate a silent no-op on exactly- // the material-faithful path it is most useful on. Prune on a copy: the caller- // restores `.visible` afterwards and must not observe a mutated scene. Required- // joint ancestors survive as transform-only nodes in the derivative.- const { withoutHiddenMeshes } = await import('../views/camera');- derivativeRoot = withoutHiddenMeshes(derivativeRoot);- // 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 exportDerivative = async () => {+ let derivativeRoot = input.root as THREE.Object3D;+ if (input.backfaceCull === false) {+ const { cloneReviewScene } = await import('../views/scene-copy');+ derivativeRoot = cloneReviewScene(derivativeRoot, { omitHidden: true, doubleSided: true });+ }+ // `withCameraVisibility` and `isolateSubtree` express isolation by clearing+ // `mesh.visible`. The CPU rasterizer culls on that flag (see views/raster.ts),+ // but glTF carries no per-mesh visibility, so serializing unfiltered ships the+ // hidden geometry to the GPU service and makes isolate a silent no-op on exactly+ // the material-faithful path it is most useful on. Prune on a copy: the caller+ // restores `.visible` afterwards and must not observe a mutated scene. Required+ // joint ancestors survive as transform-only nodes in the derivative.+ const { withoutHiddenMeshes } = await import('../views/camera');+ derivativeRoot = withoutHiddenMeshes(derivativeRoot);+ // 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.+ return renderReviewDerivativeGlb(derivativeRoot, { gltfExporter: 'three' });+ };+ // Shots of one scene state share an export. The key is read off the scene as it stands+ // for this shot, not off the request; see views/derivative-memo.ts.+ const { derivativeGlbMemo, derivativeStateKey } = await import('../views/derivative-memo');+ const derivativeGlb = await derivativeGlbMemo.bytes(+ derivativeStateKey(input.root, { backfaceCull: input.backfaceCull !== false }),+ exportDerivative,+ );const { cameraFromBounds, measureBounds } = await import('../views');const camera =input.camera ??@@ -530,7 +544,6 @@ async function renderDerivativeCell(undefined,measureBounds(input.root),);- const derivativeGlb = Uint8Array.from(reviewBytes);const inputGlbSha256 = await sha256Glb(derivativeGlb);let degradeReason: string | undefined;const derivativeReasonCodes: ViewFidelityReasonCode[] = [];diff --git a/src/views/__tests__/derivative-memo.test.ts b/src/views/__tests__/derivative-memo.test.tsnew file mode 100644index 00000000..afd4ac7e--- /dev/null+++ b/src/views/__tests__/derivative-memo.test.ts@@ -0,0 +1,301 @@+import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';+import { renderSceneToGLB } from '../../render';+import { loadGlbReviewScene } from '../glb';+import {+ createDerivativeGlbMemo,+ derivativeStateKey,+ registerReviewArtifact,+} from '../derivative-memo';++const SHA = 'sha256:aaaa';++async function fixtureBytes(): Promise<Uint8Array> {+ const root = new THREE.Group();+ root.name = 'Root';+ const left = new THREE.Group();+ left.name = 'Left';+ left.position.set(-1, 0, 0);+ const right = new THREE.Group();+ right.name = 'Right';+ right.position.set(1, 0, 0);+ const red = new THREE.MeshStandardMaterial({ color: '#cc3333' });+ const blue = new THREE.MeshStandardMaterial({ color: '#3333cc' });+ const box = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), red);+ box.name = 'Box';+ const ball = new THREE.Mesh(new THREE.SphereGeometry(0.5, 8, 6), blue);+ ball.name = 'Ball';+ left.add(box);+ right.add(ball);+ root.add(left, right);+ return Uint8Array.from(+ (await renderSceneToGLB(root, { derivative: true, gltfExporter: 'three' })).bytes,+ );+}++async function loaded(bytes: Uint8Array, sha = SHA) {+ const { root } = await loadGlbReviewScene(bytes);+ registerReviewArtifact(root, sha);+ return root as THREE.Object3D;+}++const find = (root: THREE.Object3D, name: string) => root.getObjectByName(name)!;+const meshes = (root: THREE.Object3D) => {+ const found: THREE.Mesh[] = [];+ root.traverse((node) => {+ if ((node as THREE.Mesh).isMesh) found.push(node as THREE.Mesh);+ });+ return found;+};++describe('derivative state key', () => {+ test('two loads of the same artifact bytes share a key', async () => {+ const bytes = await fixtureBytes();+ const a = await loaded(bytes);+ const b = await loaded(bytes);+ const key = derivativeStateKey(a, {});+ expect(key).toBeString();+ expect(derivativeStateKey(b, {})).toBe(key!);+ });++ test('an unregistered scene, or a node added after registration, has no key', async () => {+ const bytes = await fixtureBytes();+ const { root } = await loadGlbReviewScene(bytes);+ expect(derivativeStateKey(root, {})).toBeUndefined();+ const registered = await loaded(bytes);+ registered.add(new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial()));+ expect(derivativeStateKey(registered, {})).toBeUndefined();+ });++ test('another artifact hash or other export options change the key', async () => {+ const bytes = await fixtureBytes();+ const a = await loaded(bytes);+ const b = await loaded(bytes, 'sha256:bbbb');+ const key = derivativeStateKey(a, {});+ expect(derivativeStateKey(b, {})).not.toBe(key!);+ expect(derivativeStateKey(a, { backfaceCull: false })).not.toBe(key!);+ expect(derivativeStateKey(a, { requirements: { profile: 'x' } })).not.toBe(key!);+ });++ test('every scene change an export reads changes the key, and undoing it restores the key', async () => {+ const root = await loaded(await fixtureBytes());+ const key = derivativeStateKey(root, {})!;+ const [box, ball] = meshes(root) as [THREE.Mesh, THREE.Mesh];+ /** Set one field and return how to put it back. */+ const set = <T extends object, K extends keyof T>(target: T, field: K, value: T[K]) => {+ const own = target[field];+ target[field] = value;+ return () => {+ target[field] = own;+ };+ };+ const changes: Array<[string, () => () => void]> = [+ ['a hidden mesh', () => set(box, 'visible', false)],+ ['a hidden group', () => set(find(root, 'Left'), 'visible', false)],+ ['a moved node', () => set(find(root, 'Right').position, 'x', 2)],+ ['a rotated node', () => set(find(root, 'Right').rotation, 'y', 0.5)],+ [+ 'another geometry on a mesh',+ () => {+ const own = box.geometry;+ box.geometry = ball.geometry;+ return () => (box.geometry = own);+ },+ ],+ [+ 'another material on a mesh',+ () => {+ const own = box.material;+ box.material = ball.material;+ return () => (box.material = own);+ },+ ],+ [+ 'an edited material',+ () => {+ const material = box.material as THREE.MeshStandardMaterial;+ material.needsUpdate = true;+ return () => {};+ },+ ],+ [+ 'a fresh attribute in place of one',+ () => {+ const own = box.geometry.getAttribute('position');+ box.geometry.setAttribute('position', own.clone());+ return () => box.geometry.setAttribute('position', own);+ },+ ],+ [+ 'a recoloured material, without needsUpdate',+ () => {+ const color = (box.material as THREE.MeshStandardMaterial).color;+ const own = color.getHex();+ color.setHex(0x00ff00);+ return () => color.setHex(own);+ },+ ],+ [+ 'a changed opacity, without needsUpdate',+ () => set(box.material as THREE.MeshStandardMaterial, 'opacity', 0.5),+ ],+ [+ 'a texture added to a material',+ () => set(box.material as THREE.MeshStandardMaterial, 'map', new THREE.Texture()),+ ],+ [+ 'an edited vertex buffer',+ () => {+ box.geometry.getAttribute('position').needsUpdate = true;+ return () => {};+ },+ ],+ [+ // A level-of-detail swap: one node takes another's place in the tree.+ 'a reparented node',+ () => {+ const right = find(root, 'Right');+ const left = find(root, 'Left');+ left.add(right);+ return () => root.add(right);+ },+ ],+ ];+ for (const [name, apply] of changes) {+ const before = derivativeStateKey(root, {});+ const undo = apply();+ const changed = derivativeStateKey(root, {});+ expect({ name, changed: changed !== before }).toEqual({ name, changed: true });+ undo();+ }+ // Version bumps cannot be undone, so only the reversible changes restore the first key.+ const fresh = await loaded(await fixtureBytes());+ expect(derivativeStateKey(fresh, {})).toBe(key);+ });++ test('a subtree is keyed by its own nodes and placement', async () => {+ const root = await loaded(await fixtureBytes());+ const left = find(root, 'Left');+ const key = derivativeStateKey(left, {});+ expect(key).toBeString();+ expect(key).not.toBe(derivativeStateKey(root, {}));+ find(root, 'Right').position.x++;+ expect(derivativeStateKey(left, {})).toBe(key!);+ });+});++describe('derivative state key, textures, morphs, skins and instances', () => {+ test('a texture transform, a morph weight, a skinned pose and an instance buffer each count', () => {+ const root = new THREE.Group();+ const texture = new THREE.Texture();+ const morphGeometry = new THREE.BoxGeometry();+ morphGeometry.morphAttributes['position'] = [morphGeometry.getAttribute('position').clone()];+ const morphed = new THREE.Mesh(morphGeometry, new THREE.MeshStandardMaterial({ map: texture }));+ morphed.updateMorphTargets();+ root.add(morphed);+ const body = new THREE.Group();+ const skinGeometry = new THREE.BoxGeometry(1, 1, 1);+ const count = skinGeometry.getAttribute('position').count;+ skinGeometry.setAttribute(+ 'skinIndex',+ new THREE.Uint16BufferAttribute(new Uint16Array(count * 4), 4),+ );+ skinGeometry.setAttribute(+ 'skinWeight',+ new THREE.Float32BufferAttribute(+ Array.from({ length: count * 4 }, (_, i) => (i % 4 === 0 ? 1 : 0)),+ 4,+ ),+ );+ const skinned = new THREE.SkinnedMesh(skinGeometry, new THREE.MeshStandardMaterial());+ // The bone sits outside the subtree that holds its skin.+ const bone = new THREE.Bone();+ root.add(bone);+ body.add(skinned);+ root.add(body);+ root.updateMatrixWorld(true);+ skinned.bind(new THREE.Skeleton([bone]));+ const instanced = new THREE.InstancedMesh(+ new THREE.BoxGeometry(),+ new THREE.MeshStandardMaterial(),+ 2,+ );+ root.add(instanced);+ registerReviewArtifact(root, SHA);++ const changes: Array<[string, unknown, () => void, () => void]> = [+ ['a moved texture', root, () => texture.offset.set(0.5, 0), () => texture.offset.set(0, 0)],+ [+ 'a morph weight',+ root,+ () => (morphed.morphTargetInfluences![0] = 0.5),+ () => (morphed.morphTargetInfluences![0] = 0),+ ],+ ['a skinned pose', body, () => (bone.rotation.z = 0.5), () => (bone.rotation.z = 0)],+ ];+ for (const [name, keyed, apply, undo] of changes) {+ const before = derivativeStateKey(keyed, {});+ expect(before).toBeString();+ apply();+ expect({ name, changed: derivativeStateKey(keyed, {}) !== before }).toEqual({+ name,+ changed: true,+ });+ undo();+ expect({ name, restored: derivativeStateKey(keyed, {}) === before }).toEqual({+ name,+ restored: true,+ });+ }+ const whole = derivativeStateKey(root, {});+ instanced.setMatrixAt(1, new THREE.Matrix4().makeTranslation(3, 0, 0));+ instanced.instanceMatrix.needsUpdate = true;+ expect(derivativeStateKey(root, {})).not.toBe(whole!);+ });+});++describe('derivative GLB memo', () => {+ test('returns a copy of the stored bytes and exports only on a miss', async () => {+ const memo = createDerivativeGlbMemo();+ let exports = 0;+ const produce = async () => {+ exports++;+ return new Uint8Array([1, 2, 3]);+ };+ const first = await memo.bytes('k', produce);+ first[0] = 9;+ expect(await memo.bytes('k', produce)).toEqual(new Uint8Array([1, 2, 3]));+ expect(exports).toBe(1);+ await memo.bytes(undefined, produce);+ await memo.bytes(undefined, produce);+ expect(exports).toBe(3);+ });++ test('holds no more bytes than its budget, oldest out first', async () => {+ const memo = createDerivativeGlbMemo(5);+ let exports = 0;+ const produce = (n: number) => async () => {+ exports++;+ return new Uint8Array(n);+ };+ await memo.bytes('a', produce(2));+ await memo.bytes('b', produce(2));+ await memo.bytes('c', produce(2));+ expect(memo.stats()).toEqual({ entries: 2, bytes: 4, maxBytes: 5 });+ await memo.bytes('c', produce(2));+ await memo.bytes('b', produce(2));+ expect(exports).toBe(3);+ await memo.bytes('a', produce(2));+ expect(exports).toBe(4);+ await memo.bytes('big', produce(6));+ expect(memo.stats().entries).toBe(2);+ });++ test('a failed export is not stored', async () => {+ const memo = createDerivativeGlbMemo();+ await expect(memo.bytes('k', async () => Promise.reject(new Error('boom')))).rejects.toThrow(+ 'boom',+ );+ expect(memo.stats().entries).toBe(0);+ });+});diff --git a/src/views/__tests__/png-memo.test.ts b/src/views/__tests__/png-memo.test.tsnew file mode 100644index 00000000..66a05082--- /dev/null+++ b/src/views/__tests__/png-memo.test.ts@@ -0,0 +1,66 @@+import { describe, expect, spyOn, test } from 'bun:test';+import * as pngModule from '../png';+import { encodePng } from '../png';+import { createPngDecodeMemo, decodePngShared } from '../png-memo';++function frame(seed: number, size = 16): Uint8Array {+ const rgb = new Uint8Array(size * size * 3);+ for (let i = 0; i < rgb.length; i++) rgb[i] = (i * 7 + seed * 31) % 256;+ return new Uint8Array(encodePng(rgb, size, size));+}++describe('decoding each frame once', () => {+ test('equal bytes decode once and every caller gets its own pixels', () => {+ const decode = spyOn(pngModule, 'decodePng');+ try {+ const memo = createPngDecodeMemo();+ const png = frame(1);+ const first = memo(png);+ // A copy with equal bytes, as the port, the cache and the annotator each hold.+ const second = memo(Uint8Array.from(png));+ expect(decode).toHaveBeenCalledTimes(1);+ expect(second).toEqual(pngModule.decodePng(png));+ first.rgb.fill(0);+ expect(memo(png).rgb).toEqual(pngModule.decodePng(png).rgb);+ } finally {+ decode.mockRestore();+ }+ });++ test('different bytes decode separately', () => {+ const memo = createPngDecodeMemo();+ expect(memo(frame(1)).rgb).not.toEqual(memo(frame(2)).rgb);+ });++ test('a malformed frame throws every time and is never stored', () => {+ const memo = createPngDecodeMemo();+ const bad = new Uint8Array([1, 2, 3]);+ expect(() => memo(bad)).toThrow('bad signature');+ expect(() => memo(bad)).toThrow('bad signature');+ });++ test('the memo keeps no more decoded bytes than its budget', () => {+ const decode = spyOn(pngModule, 'decodePng');+ try {+ // 16x16 RGB is 768 bytes; a budget of 1,600 holds two frames.+ const memo = createPngDecodeMemo(1_600);+ const [a, b, c] = [frame(1), frame(2), frame(3)];+ memo(a);+ memo(b);+ memo(c);+ expect(decode).toHaveBeenCalledTimes(3);+ memo(c);+ memo(b);+ expect(decode).toHaveBeenCalledTimes(3);+ memo(a);+ expect(decode).toHaveBeenCalledTimes(4);+ } finally {+ decode.mockRestore();+ }+ });++ test('the shared decoder matches decodePng', () => {+ const png = frame(4);+ expect(decodePngShared(png)).toEqual(pngModule.decodePng(png));+ });+});diff --git a/src/views/camera-capture.ts b/src/views/camera-capture.tsindex d5f7a220..6a70d112 100644--- a/src/views/camera-capture.ts+++ b/src/views/camera-capture.ts@@ -15,7 +15,8 @@ import {import { resolveCaptureBackdrop, type CaptureConfig } from './capture';import type { BackdropId } from './background';import type { DerivativeCellRenderer, DerivativeCellRenderResult, ViewGridResult } from './index';-import { encodePng, decodePng } from './png';+import { encodePng } from './png';+import { decodePngShared } from './png-memo';import { compositeCellGrid, PAD } from './grid';import { annotateViewCell } from './annotate';import type { DerivativeViewReceiptV1 } from '../composer/render-port';@@ -149,7 +150,7 @@ export async function renderCaptureGrid(return encodePng(rasterizeCamera(root, shot.camera, size, true, backdrop), size, size);}),));- const decoded = decodePng(png);+ const decoded = decodePngShared(png);if (decoded.width !== size || decoded.height !== size)throw new Error('capture cell dimensions do not match request');annotateViewCell(decoded.rgb, size, view);diff --git a/src/views/capture-cache.ts b/src/views/capture-cache.tsindex cea92be6..79b2aa7b 100644--- a/src/views/capture-cache.ts+++ b/src/views/capture-cache.ts@@ -7,7 +7,7 @@ import {} from '../composer/render-port';import type { GlbViewCellResult } from './index';import type { ResolvedAssetCameraV1 } from './camera';-import { decodePng } from './png';+import { decodePngShared } from './png-memo';import { enforcePngCaptureBudget } from './capture-limits';export type CaptureCacheEntry =| { kind: 'gpu'; result: PbrRenderResult }@@ -110,7 +110,7 @@ function usable(result: PbrRenderResult, request: PbrRenderRequest, hash: stringreturn false;enforcePngCaptureBudget(result.viewsPng);for (const png of result.viewsPng) {- const image = decodePng(png);+ const image = decodePngShared(png);if (image.width !== image.height ||(request.cameras && (image.width !== request.width || image.height !== request.height))@@ -251,7 +251,7 @@ export async function captureCpuCell(const valid = (result: GlbViewCellResult) => {try {enforcePngCaptureBudget([result.png]);- const image = decodePng(result.png);+ const image = decodePngShared(result.png);return (result.inputGlbSha256 === snapshot.artifactGlbSha256 &&image.width === snapshot.size &&diff --git a/src/views/derivative-memo.ts b/src/views/derivative-memo.tsnew file mode 100644index 00000000..fe5595a7--- /dev/null+++ b/src/views/derivative-memo.ts@@ -0,0 +1,298 @@+import { createHash } from 'node:crypto';+import type {+ BufferAttribute,+ BufferGeometry,+ InstancedMesh,+ InterleavedBufferAttribute,+ Material,+ Mesh,+ Object3D,+ SkinnedMesh,+ Texture,+} from 'three';++/**+ * A review shot sends the GPU a derivative GLB: the review scene, exported as it stands for that+ * shot. Shots of one scene state, and later calls on the same artifact, export the same bytes,+ * and on a large asset each export costs seconds. This memo keeps those bytes under a key that+ * names the artifact and everything about the scene that the export reads.+ *+ * The key is built from the scene, not from the shot request, so a request input nobody listed+ * cannot reuse stale bytes. It names:+ * - every node: its identity, its parent's, name, visibility, transform and userData;+ * - every mesh's geometry and each of its attributes (and morph attributes and index) by+ * identity and edit `version`, its draw range and groups, and its morph weights;+ * - every material property by value, and each texture a material holds by identity, edit+ * `version` and transform;+ * - every skin's bind matrix and its bones' world poses, and every instance buffer's version;+ * - the subtree's ancestors, the same way.+ *+ * A scene is keyed only once it is registered with the hash of the GLB it was loaded from, and+ * only while every node, geometry, attribute, material and texture in it was there at+ * registration. Anything new (a fresh attribute, a swapped-in level of detail, a new texture)+ * gives no key, and the export runs. What the key cannot see is an edit inside an attribute's+ * array or a texture's image that does not bump its `version`. three needs that bump+ * (`needsUpdate`) to draw such an edit too, and no review path makes one.+ */++interface Registration {+ artifact: string;+ ids: WeakMap<object, number>;+}++const registrations = new WeakMap<object, Registration>();++const materialsOf = (mesh: Mesh): Material[] =>+ Array.isArray(mesh.material) ? mesh.material : [mesh.material];++/** Number every node, geometry, attribute, material and texture of a scene loaded from `artifact`. */+export function registerReviewArtifact(root: unknown, artifact: string): void {+ const scene = root as Object3D;+ const registration: Registration = { artifact, ids: new WeakMap() };+ let next = 0;+ const number = (value: object) => {+ if (!registration.ids.has(value)) registration.ids.set(value, next++);+ };+ const numberAttribute = (attribute: BufferAttribute | InterleavedBufferAttribute) => {+ number(attribute);+ if ((attribute as InterleavedBufferAttribute).isInterleavedBufferAttribute)+ number((attribute as InterleavedBufferAttribute).data);+ };+ scene.traverse((node) => {+ number(node);+ registrations.set(node, registration);+ const mesh = node as Mesh;+ if (mesh.geometry) {+ number(mesh.geometry);+ for (const attribute of Object.values(mesh.geometry.attributes)) numberAttribute(attribute);+ for (const list of Object.values(+ mesh.geometry.morphAttributes as Record<string, Array<BufferAttribute>>,+ ))+ for (const attribute of list) numberAttribute(attribute);+ if (mesh.geometry.index) number(mesh.geometry.index);+ }+ if (mesh.material)+ for (const material of materialsOf(mesh)) {+ number(material);+ for (const value of Object.values(material))+ if ((value as Texture | null)?.isTexture) number(value as Texture);+ }+ });+}++class Unkeyable extends Error {}++/** An interleaved attribute's edits bump its shared buffer's version. */+const versionOf = (attribute: BufferAttribute | InterleavedBufferAttribute) =>+ (attribute as InterleavedBufferAttribute).isInterleavedBufferAttribute+ ? (attribute as InterleavedBufferAttribute).data.version+ : (attribute as BufferAttribute).version;++/** An attribute by identity and edit version: a fresh attribute in its place has no id. */+const attributeState = (+ attribute: BufferAttribute | InterleavedBufferAttribute,+ id: (value: object) => number,+) => [+ id(attribute),+ (attribute as InterleavedBufferAttribute).isInterleavedBufferAttribute+ ? id((attribute as InterleavedBufferAttribute).data)+ : null,+ versionOf(attribute),+];++function geometryState(geometry: BufferGeometry, id: (value: object) => number): unknown[] {+ const attributes = Object.keys(geometry.attributes)+ .sort()+ .map((name) => [name, attributeState(geometry.attributes[name]!, id)]);+ const morphAttributes = geometry.morphAttributes as Record<+ string,+ Array<BufferAttribute | InterleavedBufferAttribute>+ >;+ const morphs = Object.keys(morphAttributes)+ .sort()+ .map((name) => [+ name,+ morphAttributes[name]!.map((attribute) => attributeState(attribute, id)),+ ]);+ return [+ id(geometry),+ attributes,+ morphs,+ geometry.index ? [id(geometry.index), geometry.index.version] : null,+ geometry.drawRange.start,+ Number.isFinite(geometry.drawRange.count) ? geometry.drawRange.count : null,+ geometry.groups.map((group) => [group.start, group.count, group.materialIndex ?? null]),+ ];+}++const textureState = (texture: Texture, id: (value: object) => number) => [+ id(texture),+ texture.version,+ texture.channel,+ texture.offset.toArray(),+ texture.repeat.toArray(),+ texture.center.toArray(),+ texture.rotation,+ texture.matrixAutoUpdate,+ Array.from(texture.matrix.elements),+ texture.wrapS,+ texture.wrapT,+ texture.flipY,+ texture.colorSpace,+ texture.magFilter,+ texture.minFilter,+];++/** Fields that differ between two loads of the same bytes, or that only three's runtime uses. */+const UNSTABLE_MATERIAL_FIELDS = new Set(['uuid', 'id', '_listeners']);++/** Every own property of a material, by value; textures by identity, version and transform. */+function materialState(material: Material, id: (value: object) => number): unknown {+ const fields: unknown[] = [id(material), material.type];+ for (const name of Object.keys(material).sort()) {+ if (UNSTABLE_MATERIAL_FIELDS.has(name)) continue;+ const value = (material as unknown as Record<string, unknown>)[name];+ if (typeof value === 'function') continue;+ if (+ value === null ||+ value === undefined ||+ ['string', 'number', 'boolean'].includes(typeof value)+ )+ fields.push(name, value ?? null);+ else if ((value as Texture).isTexture) fields.push(name, textureState(value as Texture, id));+ else if (typeof (value as { toArray?: unknown }).toArray === 'function')+ fields.push(name, (value as { toArray(): unknown[] }).toArray());+ // `defines`, `userData`, `clippingPlanes` and other plain data. A value that is not data+ // (a cycle, a BigInt) throws here, and the scene has no key.+ else fields.push(name, JSON.stringify(value));+ }+ return fields;+}++function nodeState(+ node: Object3D,+ id: (value: object) => number,+ materials: Map<Material, unknown>,+): unknown[] {+ const state: unknown[] = [+ id(node),+ node.parent ? id(node.parent) : null,+ node.name,+ node.visible,+ node.position.toArray(),+ node.quaternion.toArray(),+ node.scale.toArray(),+ node.matrixAutoUpdate,+ Array.from(node.matrix.elements),+ JSON.stringify(node.userData),+ ];+ const mesh = node as Mesh;+ if (mesh.geometry) state.push(geometryState(mesh.geometry, id));+ if (mesh.material)+ state.push(+ materialsOf(mesh).map((material) => {+ // Shared by many meshes: describe each once per key.+ if (!materials.has(material)) materials.set(material, materialState(material, id));+ return id(material);+ }),+ );+ if (mesh.morphTargetInfluences) state.push(Array.from(mesh.morphTargetInfluences));+ const skinned = node as SkinnedMesh;+ if (skinned.isSkinnedMesh)+ state.push(+ Array.from(skinned.bindMatrix.elements),+ skinned.bindMode,+ // A bone may sit outside the keyed subtree; its world pose moves the skin all the same.+ skinned.skeleton.bones.map((bone) => {+ bone.updateWorldMatrix(true, false);+ return [id(bone), Array.from(bone.matrixWorld.elements)];+ }),+ );+ const instanced = node as InstancedMesh;+ if (instanced.isInstancedMesh)+ state.push(+ instanced.count,+ instanced.instanceMatrix.version,+ instanced.instanceColor?.version ?? null,+ );+ return state;+}++/**+ * The key of `root` as an export would read it now, with the export's own `options`, or+ * `undefined` when the scene is not registered, holds something added since, or cannot be+ * described as data.+ */+export function derivativeStateKey(root: unknown, options: unknown): string | undefined {+ const scene = root as Object3D;+ const registration = registrations.get(scene);+ if (!registration) return undefined;+ const id = (value: object) => {+ const known = registration.ids.get(value);+ if (known === undefined) throw new Unkeyable();+ return known;+ };+ try {+ const materials = new Map<Material, unknown>();+ const nodes: unknown[] = [];+ scene.traverse((node) => {+ if (registrations.get(node) !== registration) throw new Unkeyable();+ nodes.push(nodeState(node, id, materials));+ });+ // A subtree's placement is its ancestors'.+ const ancestors: unknown[] = [];+ for (let node = scene.parent; node; node = node.parent)+ ancestors.push(nodeState(node, id, materials));+ return createHash('sha256')+ .update(+ JSON.stringify({+ version: 'kiln.derivative-memo.v1',+ artifact: registration.artifact,+ options,+ nodes,+ ancestors,+ materials: [...materials.values()],+ }),+ )+ .digest('hex');+ } catch {+ return undefined;+ }+}++export interface DerivativeGlbMemo {+ /** The bytes stored under `key`, or `produce`'s, stored when `key` is defined. */+ bytes(key: string | undefined, produce: () => Promise<Uint8Array>): Promise<Uint8Array>;+ stats(): { entries: number; bytes: number; maxBytes: number };+}++/** A byte-bounded store of derivative GLBs, least recently used out first. */+export function createDerivativeGlbMemo(maxBytes = 64 * 1024 * 1024): DerivativeGlbMemo {+ const entries = new Map<string, Uint8Array>();+ let held = 0;+ return {+ async bytes(key, produce) {+ const hit = key === undefined ? undefined : entries.get(key);+ if (hit) {+ entries.delete(key!);+ entries.set(key!, hit);+ return Uint8Array.from(hit);+ }+ const produced = Uint8Array.from(await produce());+ if (key !== undefined && produced.byteLength <= maxBytes) {+ while (held + produced.byteLength > maxBytes) {+ const [oldest, value] = entries.entries().next().value!;+ entries.delete(oldest);+ held -= value.byteLength;+ }+ entries.set(key, Uint8Array.from(produced));+ held += produced.byteLength;+ }+ return produced;+ },+ stats: () => ({ entries: entries.size, bytes: held, maxBytes }),+ };+}++/** The host's shared derivative store. Keys name the artifact, so sessions never collide. */+export const derivativeGlbMemo = createDerivativeGlbMemo();diff --git a/src/views/grid.ts b/src/views/grid.tsindex ddeceed9..737d218a 100644--- a/src/views/grid.ts+++ b/src/views/grid.ts@@ -8,7 +8,8 @@*/import { annotateViewCell } from './annotate';-import { decodePng, encodePng } from './png';+import { encodePng } from './png';+import { decodePngShared } from './png-memo';export const PAD = 4;export const PAD_COLOR: [number, number, number] = [10, 11, 13];@@ -95,7 +96,7 @@ export function compositeViewPngGrid(`compositeViewPngGrid: ${views.length} view specs for ${pngs.length} PNGs — they must align 1:1`,);}- const decoded = pngs.map((png) => decodePng(png));+ const decoded = pngs.map((png) => decodePngShared(png));const size = decoded[0]!.width;for (const d of decoded) {if (d.width !== size || d.height !== size) {@@ -105,7 +106,7 @@ export function compositeViewPngGrid(}}if (views) {- // decodePng returns cell-owned buffers, so this mutates nothing the caller+ // decodePngShared returns cell-owned buffers, so this mutates nothing the caller// still holds — the host's PNG bytes are untouched.for (let i = 0; i < decoded.length; i++) annotateViewCell(decoded[i]!.rgb, size, views[i]!);}diff --git a/src/views/index.ts b/src/views/index.tsindex 099f3976..7beb2d78 100644--- a/src/views/index.ts+++ b/src/views/index.ts@@ -41,7 +41,7 @@ import {type ViewSpec,} from './raster';import { encodePng } from './png';-import { decodePng } from './png';+import { decodePngShared } from './png-memo';import { compositeCellGrid } from './grid';import { annotateViewCell } from './annotate';import { resolveGridCapture, type CaptureConfig, type CaptureShape } from './capture';@@ -425,7 +425,7 @@ export async function renderViewGrid(}),);if (result.captureCache?.hit) reused++;- cell = decodePng(result.png).rgb;+ cell = decodePngShared(result.png).rgb;} else cell = rasterizeView(root, views[vi]!.dir, rasterOptions);// H-30: view name + axis gnomon, via the annotator the GPU port shares.annotateViewCell(cell, size, views[vi]!);@@ -871,7 +871,7 @@ export async function renderClipAnimation(const rendered = resolvedShot? await withCameraVisibility(root, resolvedShot, produce): await produce();- const decoded = decodePng(rendered.png);+ const decoded = decodePngShared(rendered.png);if (decoded.width !== size || decoded.height !== size) {throw new Error(`derivative animation cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`,@@ -1033,7 +1033,7 @@ export async function renderInteriorGrid(size,backfaceCull: false,});- const decoded = decodePng(rendered.png);+ const decoded = decodePngShared(rendered.png);if (decoded.width !== size || decoded.height !== size) {throw new Error(`derivative interior cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`,diff --git a/src/views/png-memo.ts b/src/views/png-memo.tsnew file mode 100644index 00000000..2791396a--- /dev/null+++ b/src/views/png-memo.ts@@ -0,0 +1,41 @@+import { createHash } from 'node:crypto';+import * as png from './png';+import type { DecodedPng } from './png';++/**+ * One frame passes three readers on its way to a model: the capture cache's check, the port's+ * trust check and the annotator. Each holds its own copy of the same bytes, so a decode keyed by+ * those bytes' SHA-256 lets the first reader decode and the others reuse it. Decoding is a pure+ * function of the bytes; every caller gets its own pixel buffer, because annotation draws on it.+ * A frame that fails to decode is never stored, so it fails for every reader.+ */+export function createPngDecodeMemo(+ maxBytes = 64 * 1024 * 1024,+): (bytes: Uint8Array) => DecodedPng {+ const entries = new Map<string, DecodedPng>();+ let held = 0;+ return (bytes) => {+ const key = createHash('sha256').update(bytes).digest('hex');+ const hit = entries.get(key);+ if (hit) {+ entries.delete(key);+ entries.set(key, hit);+ return { ...hit, rgb: Uint8Array.from(hit.rgb) };+ }+ const decoded = png.decodePng(bytes);+ const size = decoded.rgb.byteLength;+ if (size <= maxBytes) {+ while (held + size > maxBytes) {+ const [oldest, value] = entries.entries().next().value!;+ entries.delete(oldest);+ held -= value.rgb.byteLength;+ }+ entries.set(key, { ...decoded, rgb: Uint8Array.from(decoded.rgb) });+ held += size;+ }+ return decoded;+ };+}++/** The host's shared frame decoder. */+export const decodePngShared = createPngDecodeMemo();diff --git a/src/views/port.ts b/src/views/port.tsindex 1e9b1367..0671ec9c 100644--- a/src/views/port.ts+++ b/src/views/port.ts@@ -17,7 +17,7 @@ import {type CaptureShape,type ResolvedCapture,} from './capture';-import { decodePng } from './png';+import { decodePngShared } from './png-memo';import { compositeViewPngGrid } from './grid';export const DEFAULT_VIEW_RENDER_TIMEOUT_MS = 8000;/** What one render request may carry; the render service refuses anything more. */@@ -155,7 +155,7 @@ export async function captureViewPngsViaPort(// pixels is a degrade, never a successful material attestation.enforcePngCaptureBudget(result.viewsPng, limits);for (const png of result.viewsPng) {- const decoded = decodePng(png);+ const decoded = decodePngShared(png);if (exactCameras && (decoded.width !== size || decoded.height !== size))return { ok: false, reason: 'camera PNG dimensions mismatch' };if (decoded.width !== decoded.height) {@@ -321,16 +321,29 @@ export async function captureViewsViaPort(const { renderCaptureGrid } = await import('./camera-capture');const { withoutHiddenMeshes } = await import('./camera');const { renderReviewDerivativeGlb } = await import('../render');+ const { derivativeGlbMemo, derivativeStateKey, registerReviewArtifact } = await import(+ './derivative-memo'+ );+ const { createHash } = await import('node:crypto');const loaded = await loadGlbReviewScene(Uint8Array.from(glb));+ registerReviewArtifact(+ loaded.root,+ `sha256:${createHash('sha256').update(glb).digest('hex')}`,+ );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 renderReviewDerivativeGlb(- withoutHiddenMeshes(input.root as import('three').Object3D),- { gltfExporter: 'three' },+ // Shots of one scene state share that export.+ const derivative = await derivativeGlbMemo.bytes(+ derivativeStateKey(input.root, { backfaceCull: true }),+ () =>+ renderReviewDerivativeGlb(+ withoutHiddenMeshes(input.root as import('three').Object3D),+ { gltfExporter: 'three' },+ ),);const result = await captureViewPngsViaPort(port,