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.

feat: model-controlled capture — orbit camera, grid presets, and the same layout through the render port (#13)

Matthew Kissinger1a6772250adf
diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
index dc875216..ed647d12 100644
--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap
+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
@@ -208,6 +208,12 @@ mirror(name, source, axis: 'x'|'y'|'z', parent?)
// handled by viewers).
// CSG / Boolean (async — using any of these requires \`async function build()\`)
+// NOTE: UVs do NOT survive a boolean: the manifold bridge carries positions only, so the result
+// has no uv attribute and any texture on it will not appear. Unwrap AFTER the boolean, never
+// before — \`mesh.geometry = await autoUnwrap(mesh.geometry)\`. Unwrapping an operand first is
+// wasted work; the next boolean throws the atlas away. An operand that contributes zero
+// triangles (an empty Group) and an empty result both throw with the cause named, instead of
+// silently producing an invisible part.
await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false })
// Merges two or more parts into one watertight manifold mesh. Default flat shading (hard
// edges) — pass { smooth: true } as last arg for averaged normals on organic merges.
@@ -314,6 +320,20 @@ await loadTexture(source, { usage?: 'albedo'|'emissive'|'normal'|'roughness'|'me
// NOTE: NEVER texture.clone() a loaded texture (clone() corrupts the encoded bytes and breaks
// GLB export). Share the same Texture object and remap UVs with panelRemapV on the smaller
// mesh instead.
+proceduralTexture({ size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })
+ // Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite
+ // bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes
+ // and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.
+ // NOTE: Sync — no await. Prefer this over loadTexture for any surface you can describe (wood,
+ // rust, brick, fabric, dirt): it needs no asset files and cannot fail at load. Max 8 layers,
+ // size must be a power of two up to 1024. Only the six listed ops exist; there is no custom
+ // per-pixel callback.
+normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })
+ // Derives a tangent-space normal map from the source texture's brightness, treating it as
+ // height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at
+ // the edges, so a tiling source gives a tiling normal map.
+ // NOTE: strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always
+ // linear data — never assign it to an albedo/emissive slot.
// Animation — keyframes use "rotation"/"position"/"scale" keys, NOT "value"
rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')
@@ -636,6 +656,12 @@ mirror(name, source, axis: 'x'|'y'|'z', parent?)
// e.g. mirror('WingR', wingL, 'x', root);
// CSG / Boolean (async — using any of these requires \`async function build()\`)
+// NOTE: UVs do NOT survive a boolean: the manifold bridge carries positions only, so the result
+// has no uv attribute and any texture on it will not appear. Unwrap AFTER the boolean, never
+// before — \`mesh.geometry = await autoUnwrap(mesh.geometry)\`. Unwrapping an operand first is
+// wasted work; the next boolean throws the atlas away. An operand that contributes zero
+// triangles (an empty Group) and an empty result both throw with the cause named, instead of
+// silently producing an invisible part.
await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false })
// Merges two or more parts into one watertight manifold mesh. Default flat shading (hard
// edges) — pass { smooth: true } as last arg for averaged normals on organic merges.
@@ -787,6 +813,26 @@ await loadTexture(source, { usage?: 'albedo'|'emissive'|'normal'|'roughness'|'me
// GLB export). Share the same Texture object and remap UVs with panelRemapV on the smaller
// mesh instead.
// e.g. const wood = await loadTexture('./textures/oak-albedo.png', { usage: 'albedo' });
+proceduralTexture({ size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })
+ // Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite
+ // bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes
+ // and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.
+ // NOTE: Sync — no await. Prefer this over loadTexture for any surface you can describe (wood,
+ // rust, brick, fabric, dirt): it needs no asset files and cannot fail at load. Max 8 layers,
+ // size must be a power of two up to 1024. Only the six listed ops exist; there is no custom
+ // per-pixel callback.
+ // e.g. const bark = proceduralTexture({ size: 256, usage: 'albedo', name: 'Bark', layers: [{
+ // op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale:
+ // 6, octaves: 4, blend: 'overlay' }] });
+normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })
+ // Derives a tangent-space normal map from the source texture's brightness, treating it as
+ // height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at
+ // the edges, so a tiling source gives a tiling normal map.
+ // NOTE: strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always
+ // linear data — never assign it to an albedo/emissive slot.
+ // e.g. const bark = proceduralTexture({ usage: 'albedo', layers: [{ op: 'noise', colorA:
+ // 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] }); const mat = pbrMaterial({ albedo:
+ // bark, normal: normalMapFromHeight(bark, { strength: 4 }) });
// Animation — keyframes use "rotation"/"position"/"scale" keys, NOT "value"
rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')
diff --git a/src/__tests__/csg-uv-integrity.test.ts b/src/__tests__/csg-uv-integrity.test.ts
new file mode 100644
index 00000000..566f95c9
--- /dev/null
+++ b/src/__tests__/csg-uv-integrity.test.ts
@@ -0,0 +1,284 @@
+/**
+ * T2.4 — UV integrity across CSG.
+ *
+ * Two separable claims, and the tests are split along that line:
+ *
+ * 1. **The guards.** Every case here was measured as a SILENT failure before
+ * the guard existed — an empty operand absorbed without comment, a disjoint
+ * intersect shipping a zero-triangle mesh, a ragged triangle list coming
+ * back as manifold's bare "Not manifold". The assertions check the message
+ * names the cause, because the agent's only channel is that string.
+ *
+ * 2. **The unwrap is actually usable.** A boolean destroys UVs; the contract is
+ * that `autoUnwrap` on the result gives you a texturable atlas. That is
+ * worth measuring rather than assuming, so the matrix below checks UV range,
+ * finiteness, coverage and area distortion for union / diff / intersect /
+ * hull with textured operands.
+ */
+
+import { describe, expect, it } from 'bun:test';
+import * as THREE from 'three';
+import { boolDiff, boolIntersect, boolUnion, hull } from '../solids';
+import { autoUnwrap } from '../uv';
+import { boxGeo, cylinderGeo, gameMaterial } from '../primitives';
+
+const mat = () => gameMaterial(0x8899aa);
+function box(size = 1, at: [number, number, number] = [0, 0, 0]): THREE.Mesh {
+ const m = new THREE.Mesh(boxGeo(size, size, size), mat());
+ m.position.set(...at);
+ m.updateMatrixWorld(true);
+ return m;
+}
+
+// =============================================================================
+// The guards — every one of these used to pass in silence
+// =============================================================================
+
+describe('CSG operand guards', () => {
+ it('an operand with no meshes is named, not absorbed', async () => {
+ // Measured before the guard: union returned the body unchanged, diff
+ // returned the body unchanged, and intersect returned a ZERO-triangle mesh.
+ // Three different wrong answers, no error in any of them.
+ const empty = new THREE.Group();
+ await expect(boolUnion('U', box(), empty)).rejects.toThrow(
+ /boolUnion operand 2: contributes no triangles/,
+ );
+ await expect(boolDiff('D', box(), empty)).rejects.toThrow(
+ /boolDiff cutter 1: contributes no triangles/,
+ );
+ await expect(boolIntersect('I', box(), empty)).rejects.toThrow(
+ /boolIntersect operand b: contributes no triangles/,
+ );
+ await expect(hull('H', box(), empty)).rejects.toThrow(
+ /hull operand 2: contributes no triangles/,
+ );
+ });
+
+ it('the message tells the model what the realistic cause is', async () => {
+ // An empty Group is what you get when the parts were never added to it.
+ await expect(boolUnion('U', box(), new THREE.Group())).rejects.toThrow(
+ /empty Group, or a part that was never added to it/,
+ );
+ });
+
+ it('a ragged triangle list names the mesh, not "Not manifold"', async () => {
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(4 * 3), 3));
+ const bad = new THREE.Mesh(g, mat());
+ bad.name = 'HandBuilt';
+ await expect(boolUnion('U', box(), bad)).rejects.toThrow(
+ /mesh "HandBuilt" has 4 vertices, which is not a whole number of triangles/,
+ );
+ });
+});
+
+describe('CSG result guards', () => {
+ it('a disjoint intersect throws instead of shipping an invisible part', async () => {
+ await expect(boolIntersect('I', box(), box(1, [10, 0, 0]))).rejects.toThrow(
+ /the result is empty \(zero triangles\).*do not overlap/s,
+ );
+ });
+
+ it('a cutter that swallows the body throws with that as the hint', async () => {
+ await expect(boolDiff('D', box(1), box(5))).rejects.toThrow(/removed the entire body/);
+ });
+
+ it('a legitimate empty-ish operation still succeeds when it makes a solid', async () => {
+ // Guard rails must not reject ordinary work: overlapping solids, a cutter
+ // that removes part of a body, and a hull over a scatter all still pass.
+ const carved = await boolDiff('D', box(2), box(0.5, [0.9, 0, 0]));
+ expect(carved.geometry.getAttribute('position')!.count).toBeGreaterThan(0);
+ const merged = await boolUnion('U', box(1), box(1, [0.5, 0, 0]));
+ expect(merged.geometry.getAttribute('position')!.count).toBeGreaterThan(0);
+ const wrapped = await hull('H', box(0.4, [-1, 0, 0]), box(0.4, [1, 0, 0]));
+ expect(wrapped.geometry.getAttribute('position')!.count).toBeGreaterThan(0);
+ });
+});
+
+describe('autoUnwrap guards', () => {
+ it('an empty geometry says so instead of returning zero vertices', async () => {
+ // Measured: xatlas accepts an empty mesh and returns an empty atlas without
+ // complaint, so this used to come back with 0 vertices and no uv attribute
+ // and only failed later, as a texture that never appeared.
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(0), 3));
+ g.setIndex(new THREE.BufferAttribute(new Uint32Array(0), 1));
+ await expect(autoUnwrap(g)).rejects.toThrow(/has no triangles/);
+ });
+
+ it('a ragged index list is rejected', async () => {
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(9), 3));
+ g.setIndex(new THREE.BufferAttribute(new Uint32Array([0, 1]), 1));
+ await expect(autoUnwrap(g)).rejects.toThrow(/not a whole number of triangles/);
+ });
+});
+
+// =============================================================================
+// The matrix — a boolean destroys UVs, and unwrapping the result restores them
+// =============================================================================
+
+/** Per-triangle 3D area and UV area, for the distortion measure below. */
+function triangleAreas(geo: THREE.BufferGeometry): { world: number[]; uv: number[] } {
+ const pos = geo.getAttribute('position') as THREE.BufferAttribute;
+ const uv = geo.getAttribute('uv') as THREE.BufferAttribute;
+ const idx = geo.getIndex();
+ const count = idx ? idx.count : pos.count;
+ const at = (i: number) => (idx ? (idx.getX(i) as number) : i);
+ const world: number[] = [];
+ const uvArea: number[] = [];
+ const a = new THREE.Vector3();
+ const b = new THREE.Vector3();
+ const c = new THREE.Vector3();
+ for (let t = 0; t < count; t += 3) {
+ const i0 = at(t);
+ const i1 = at(t + 1);
+ const i2 = at(t + 2);
+ a.fromBufferAttribute(pos, i0);
+ b.fromBufferAttribute(pos, i1);
+ c.fromBufferAttribute(pos, i2);
+ world.push(b.clone().sub(a).cross(c.clone().sub(a)).length() / 2);
+ const u0 = uv.getX(i0);
+ const v0 = uv.getY(i0);
+ const u1 = uv.getX(i1);
+ const v1 = uv.getY(i1);
+ const u2 = uv.getX(i2);
+ const v2 = uv.getY(i2);
+ uvArea.push(Math.abs((u1 - u0) * (v2 - v0) - (u2 - u0) * (v1 - v0)) / 2);
+ }
+ return { world, uv: uvArea };
+}
+
+/**
+ * Documented stretch tolerance (T2.4 accept criterion).
+ *
+ * The measure is per-triangle texel density — UV area over world area —
+ * normalized by the mesh median, so a uniformly-scaled atlas scores 1.0
+ * everywhere and a triangle at 4.0 samples texels twice as densely per unit of
+ * surface, in each direction, as the median.
+ *
+ * Set from measurement, not from a guess. Across this matrix:
+ *
+ * | case | worst / median |
+ * |-------------------------------|----------------|
+ * | union | 1.002 |
+ * | diff | 1.009 |
+ * | intersect | 1.000 |
+ * | hull | 1.008 |
+ * | plate with a cylindrical bore | 1.108 |
+ *
+ * xatlas turns out to pack these at essentially uniform density, so the honest
+ * ceiling is close to 1, not the "charts scale independently, expect a long
+ * tail" figure I would have picked without running it. 2.0 leaves real headroom
+ * for the curved-cut-face case while still failing on an actual regression — an
+ * 8x ceiling would have passed no matter how badly the unwrap degraded.
+ */
+const MAX_DENSITY_RATIO = 2;
+
+function densitySpread(geo: THREE.BufferGeometry): number {
+ const { world, uv } = triangleAreas(geo);
+ const density: number[] = [];
+ for (let i = 0; i < world.length; i++) {
+ const w = world[i]!;
+ // Zero-area triangles carry no texture and cannot be stretched.
+ if (w < 1e-9) continue;
+ density.push(uv[i]! / w);
+ }
+ density.sort((x, y) => x - y);
+ const median = density[Math.floor(density.length / 2)] ?? 1;
+ if (median <= 0) return Number.POSITIVE_INFINITY;
+ return (density[density.length - 1] ?? 0) / median;
+}
+
+describe('post-CSG unwrap, textured operands', () => {
+ const cases: Array<[string, () => Promise<THREE.Mesh>]> = [
+ ['union', () => boolUnion('U', box(1), box(1, [0.6, 0, 0]))],
+ ['diff', () => boolDiff('D', box(2), box(0.6, [0.8, 0.2, 0]))],
+ ['intersect', () => boolIntersect('I', box(1.4), box(1.4, [0.5, 0.3, 0]))],
+ ['hull', () => hull('H', box(0.5, [-0.8, 0, 0]), box(0.5, [0.8, 0.4, 0]))],
+ [
+ 'diff with a cylinder cutter',
+ () => {
+ const body = new THREE.Mesh(boxGeo(2, 0.4, 2), mat());
+ const bore = new THREE.Mesh(cylinderGeo(0.3, 0.3, 2, 24), mat());
+ bore.updateMatrixWorld(true);
+ return boolDiff('Plate', body, bore);
+ },
+ ],
+ ];
+
+ for (const [label, build] of cases) {
+ it(`${label}: the boolean drops UVs and the unwrap gives usable ones back`, async () => {
+ const result = await build();
+
+ // The documented semantic, pinned: positions and normals survive, uv does not.
+ expect(result.geometry.getAttribute('position')).toBeTruthy();
+ expect(result.geometry.getAttribute('uv')).toBeUndefined();
+
+ const unwrapped = await autoUnwrap(result.geometry);
+ const uv = unwrapped.getAttribute('uv') as THREE.BufferAttribute;
+ expect(uv).toBeTruthy();
+
+ // Finite, in the unit square. A NaN here is the failure that renders as a
+ // texture collapsed to a single texel.
+ const arr = uv.array as ArrayLike<number>;
+ let min = Number.POSITIVE_INFINITY;
+ let max = Number.NEGATIVE_INFINITY;
+ for (let i = 0; i < uv.count * 2; i++) {
+ const v = arr[i]!;
+ expect(Number.isFinite(v)).toBe(true);
+ if (v < min) min = v;
+ if (v > max) max = v;
+ }
+ expect(min).toBeGreaterThanOrEqual(0);
+ expect(max).toBeLessThanOrEqual(1);
+ // The atlas is actually used, not collapsed into a corner.
+ expect(max - min).toBeGreaterThan(0.5);
+
+ // Topology survives: the unwrap re-splits vertices along seams, so vertex
+ // count may rise, but triangle count must not change.
+ const trisIn = result.geometry.getIndex()
+ ? result.geometry.getIndex()!.count / 3
+ : result.geometry.getAttribute('position')!.count / 3;
+ const trisOut = unwrapped.getIndex()!.count / 3;
+ expect(trisOut).toBe(trisIn);
+ expect(unwrapped.getAttribute('position')!.count).toBeGreaterThanOrEqual(
+ result.geometry.getAttribute('position')!.count,
+ );
+
+ expect(densitySpread(unwrapped)).toBeLessThan(MAX_DENSITY_RATIO);
+ });
+ }
+
+ it('the atlas is not necessarily square — read width/height, not resolution', async () => {
+ // Measured: a CSG'd box at resolution 1024 packs into 917x1085. A baker that
+ // allocated resolution x resolution would sample the wrong texels on one
+ // axis, which reads as a subtle uniform stretch rather than an obvious break.
+ const merged = await boolUnion('U', box(1), box(1, [0.6, 0, 0]));
+ const unwrapped = await autoUnwrap(merged.geometry, { resolution: 1024 });
+ const atlas = unwrapped.userData['atlas'] as {
+ width: number;
+ height: number;
+ atlasCount: number;
+ };
+ expect(atlas.width).toBeGreaterThan(0);
+ expect(atlas.height).toBeGreaterThan(0);
+ expect(atlas.atlasCount).toBeGreaterThanOrEqual(1);
+ expect(atlas.width <= 1024 || atlas.height <= 1024).toBe(true);
+ });
+
+ it('a chain of booleans stays unwrappable, and unwrapping early is wasted', async () => {
+ // The documented workflow: unwrap AFTER the last boolean. This proves the
+ // "wasted" half — an atlas built mid-chain does not survive the next op.
+ const first = await boolUnion('A', box(1), box(1, [0.6, 0, 0]));
+ first.geometry = await autoUnwrap(first.geometry);
+ expect(first.geometry.getAttribute('uv')).toBeTruthy();
+
+ const second = await boolDiff('B', first, box(0.3, [0.3, 0.4, 0]));
+ expect(second.geometry.getAttribute('uv')).toBeUndefined();
+
+ second.geometry = await autoUnwrap(second.geometry);
+ expect(second.geometry.getAttribute('uv')).toBeTruthy();
+ expect(densitySpread(second.geometry)).toBeLessThan(MAX_DENSITY_RATIO);
+ });
+});
diff --git a/src/__tests__/procedural-texture.test.ts b/src/__tests__/procedural-texture.test.ts
new file mode 100644
index 00000000..442e4f6c
--- /dev/null
+++ b/src/__tests__/procedural-texture.test.ts
@@ -0,0 +1,382 @@
+/**
+ * T2.2 — the bounded procedural op set.
+ *
+ * The properties worth defending here are determinism (the same spec must
+ * always produce the same bytes, or the pinned-SHA fixtures become a lottery),
+ * tileability (the reason a procedural material looks right on a wall and not
+ * just on a test cube), and the bounds (an untrusted model authors these specs).
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import {
+ MAX_NOISE_OCTAVES,
+ MAX_PROCEDURAL_LAYERS,
+ normalMapFromHeight,
+ proceduralTexture,
+ ProceduralTextureError,
+} from '../procedural-texture';
+import { executeKilnCode } from '../render';
+
+const pixels = (tex: THREE.DataTexture): Uint8Array => tex.image.data as Uint8Array;
+
+/** Sample one texel as [r,g,b]. */
+function texelAt(tex: THREE.DataTexture, x: number, y: number): [number, number, number] {
+ const size = tex.image.width;
+ const o = (y * size + x) * 4;
+ const d = pixels(tex);
+ return [d[o]!, d[o + 1]!, d[o + 2]!];
+}
+
+// -----------------------------------------------------------------------------
+// Determinism
+// -----------------------------------------------------------------------------
+
+describe('determinism', () => {
+ test('the same spec produces byte-identical pixels, including noise', () => {
+ const spec = {
+ size: 64,
+ usage: 'albedo' as const,
+ layers: [
+ { op: 'solid' as const, color: 0x5a4632 },
+ {
+ op: 'noise' as const,
+ colorA: 0x3d2f21,
+ colorB: 0x7a6248,
+ scale: 6,
+ octaves: 4,
+ seed: 7,
+ blend: 'overlay' as const,
+ },
+ ],
+ };
+
+ expect(
+ Buffer.compare(
+ Buffer.from(pixels(proceduralTexture(spec))),
+ Buffer.from(pixels(proceduralTexture(spec))),
+ ),
+ ).toBe(0);
+ });
+
+ test('a different seed produces different pixels (the check above can fail)', () => {
+ const layers = (seed: number) => [
+ { op: 'noise' as const, colorA: 0x000000, colorB: 0xffffff, scale: 8, octaves: 3, seed },
+ ];
+ const a = proceduralTexture({ size: 32, layers: layers(1) });
+ const b = proceduralTexture({ size: 32, layers: layers(2) });
+ expect(Buffer.compare(Buffer.from(pixels(a)), Buffer.from(pixels(b)))).not.toBe(0);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Tileability — the property that separates this from a toy
+// -----------------------------------------------------------------------------
+
+describe('tileability', () => {
+ test('noise wraps: the last column continues into the first', () => {
+ const tex = proceduralTexture({
+ size: 64,
+ layers: [{ op: 'noise', colorA: 0x000000, colorB: 0xffffff, scale: 4, octaves: 3, seed: 3 }],
+ });
+
+ // The step across the seam (column 63 -> 0) should look like any other
+ // neighbouring pair, not like an arbitrary jump. Measured on this spec:
+ // interior steps reach 28/255 while the seam step peaks at 2/255, so the
+ // seam is not merely "within range" — it is an order of magnitude smaller
+ // than the noise's own local variation. A quarter of the interior max
+ // leaves room for the seed to change without making this brittle, while
+ // still failing loudly if the lattice ever stops wrapping.
+ let interiorMax = 0;
+ for (let y = 0; y < 64; y++) {
+ for (let x = 0; x < 63; x++) {
+ interiorMax = Math.max(
+ interiorMax,
+ Math.abs(texelAt(tex, x, y)[0] - texelAt(tex, x + 1, y)[0]),
+ );
+ }
+ }
+ let seamMax = 0;
+ for (let y = 0; y < 64; y++) {
+ seamMax = Math.max(seamMax, Math.abs(texelAt(tex, 63, y)[0] - texelAt(tex, 0, y)[0]));
+ }
+
+ expect(interiorMax).toBeGreaterThan(8); // the noise actually varies
+ expect(seamMax).toBeLessThanOrEqual(interiorMax / 4);
+ });
+
+ test('a repeating pattern lands on exact texel boundaries', () => {
+ // 8 squares across 64 texels = 8 texels each; texel-center sampling is what
+ // keeps the boundary from drifting half a texel.
+ const tex = proceduralTexture({
+ size: 64,
+ layers: [{ op: 'checker', colorA: 0x000000, colorB: 0xffffff, squares: 8 }],
+ });
+ expect(texelAt(tex, 7, 0)[0]).toBe(0);
+ expect(texelAt(tex, 8, 0)[0]).toBe(255);
+ expect(texelAt(tex, 15, 0)[0]).toBe(255);
+ expect(texelAt(tex, 16, 0)[0]).toBe(0);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// The ops themselves
+// -----------------------------------------------------------------------------
+
+describe('layer ops', () => {
+ test('solid fills with exactly the requested color', () => {
+ const tex = proceduralTexture({ size: 8, layers: [{ op: 'solid', color: 0x336699 }] });
+ expect(texelAt(tex, 0, 0)).toEqual([0x33, 0x66, 0x99]);
+ expect(texelAt(tex, 7, 7)).toEqual([0x33, 0x66, 0x99]);
+ });
+
+ test('gradient runs from one color to the other', () => {
+ const tex = proceduralTexture({
+ size: 64,
+ layers: [{ op: 'gradient', from: 0x000000, to: 0xffffff }],
+ });
+ const left = texelAt(tex, 0, 32)[0];
+ const right = texelAt(tex, 63, 32)[0];
+ expect(left).toBeLessThan(20);
+ expect(right).toBeGreaterThan(235);
+ });
+
+ test('bricks stagger alternate rows', () => {
+ const tex = proceduralTexture({
+ size: 64,
+ layers: [{ op: 'bricks', brick: 0xffffff, mortar: 0x000000, rows: 4, cols: 2 }],
+ });
+ // Two rows offset by half a brick cannot be identical scanlines.
+ const rowA = Array.from({ length: 64 }, (_, x) => texelAt(tex, x, 4)[0]).join(',');
+ const rowB = Array.from({ length: 64 }, (_, x) => texelAt(tex, x, 20)[0]).join(',');
+ expect(rowA).not.toBe(rowB);
+ });
+
+ test('stripes at 90 degrees run the other way', () => {
+ const flat = proceduralTexture({
+ size: 32,
+ layers: [{ op: 'stripes', colorA: 0x000000, colorB: 0xffffff, count: 4 }],
+ });
+ const turned = proceduralTexture({
+ size: 32,
+ layers: [{ op: 'stripes', colorA: 0x000000, colorB: 0xffffff, count: 4, angleDeg: 90 }],
+ });
+ // Horizontal stripes vary along x and not y; vertical ones do the reverse.
+ expect(texelAt(flat, 0, 0)[0]).toBe(texelAt(flat, 0, 31)[0]);
+ expect(texelAt(turned, 0, 0)[0]).toBe(texelAt(turned, 31, 0)[0]);
+ expect(Buffer.compare(Buffer.from(pixels(flat)), Buffer.from(pixels(turned)))).not.toBe(0);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Blending
+// -----------------------------------------------------------------------------
+
+describe('blend modes', () => {
+ const base = { op: 'solid' as const, color: 0x808080 };
+
+ test('multiply darkens, screen lightens', () => {
+ const mul = proceduralTexture({
+ size: 4,
+ layers: [base, { op: 'solid', color: 0x808080, blend: 'multiply' }],
+ });
+ const scr = proceduralTexture({
+ size: 4,
+ layers: [base, { op: 'solid', color: 0x808080, blend: 'screen' }],
+ });
+ expect(texelAt(mul, 0, 0)[0]).toBeLessThan(0x80);
+ expect(texelAt(scr, 0, 0)[0]).toBeGreaterThan(0x80);
+ });
+
+ test('opacity 0 leaves the layer below untouched', () => {
+ const tex = proceduralTexture({
+ size: 4,
+ layers: [base, { op: 'solid', color: 0xff0000, opacity: 0 }],
+ });
+ expect(texelAt(tex, 0, 0)).toEqual([0x80, 0x80, 0x80]);
+ });
+
+ test('the first layer ignores blend and opacity — there is nothing beneath it', () => {
+ const withBlend = proceduralTexture({
+ size: 4,
+ layers: [{ op: 'solid', color: 0x336699, blend: 'multiply', opacity: 0.1 }],
+ });
+ expect(texelAt(withBlend, 0, 0)).toEqual([0x33, 0x66, 0x99]);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Color space is set here, unlike in the bake pass
+// -----------------------------------------------------------------------------
+
+describe('color space', () => {
+ test('albedo and emissive are sRGB; data maps are linear', () => {
+ const layers = [{ op: 'solid' as const, color: 0x808080 }];
+ expect(proceduralTexture({ size: 4, usage: 'albedo', layers }).colorSpace).toBe(
+ THREE.SRGBColorSpace,
+ );
+ expect(proceduralTexture({ size: 4, usage: 'emissive', layers }).colorSpace).toBe(
+ THREE.SRGBColorSpace,
+ );
+ expect(proceduralTexture({ size: 4, usage: 'roughness', layers }).colorSpace).toBe(
+ THREE.NoColorSpace,
+ );
+ expect(proceduralTexture({ size: 4, layers }).colorSpace).toBe(THREE.SRGBColorSpace);
+ });
+
+ test('the recipe is recorded on the texture for provenance', () => {
+ const tex = proceduralTexture({
+ size: 8,
+ usage: 'roughness',
+ layers: [{ op: 'solid', color: 0x404040 }],
+ });
+ expect((tex.userData as Record<string, unknown>)['kilnProcedural']).toEqual({
+ schemaVersion: 1,
+ size: 8,
+ usage: 'roughness',
+ layers: [{ op: 'solid', color: 0x404040 }],
+ });
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Bounds — the spec author is untrusted
+// -----------------------------------------------------------------------------
+
+describe('bounds and validation', () => {
+ const layers = [{ op: 'solid' as const, color: 0 }];
+
+ test('size must be a power of two within range', () => {
+ expect(() => proceduralTexture({ size: 100, layers })).toThrow(ProceduralTextureError);
+ expect(() => proceduralTexture({ size: 2048, layers })).toThrow(/power of two/);
+ expect(() => proceduralTexture({ size: 2, layers })).toThrow(/power of two/);
+ });
+
+ test('the layer stack is bounded and must not be empty', () => {
+ expect(() => proceduralTexture({ layers: [] })).toThrow(/non-empty/);
+ const tooMany = Array.from({ length: MAX_PROCEDURAL_LAYERS + 1 }, () => layers[0]!);
+ expect(() => proceduralTexture({ size: 4, layers: tooMany })).toThrow(
+ new RegExp(`maximum of ${MAX_PROCEDURAL_LAYERS}`),
+ );
+ });
+
+ test('an unknown op is rejected by name, listing what does exist', () => {
+ expect(() => proceduralTexture({ size: 4, layers: [{ op: 'perlin' } as never] })).toThrow(
+ /"perlin" is not one of solid, checker, stripes, gradient, bricks, noise/,
+ );
+ });
+
+ test('octaves are capped so a spec cannot buy unbounded work', () => {
+ expect(() =>
+ proceduralTexture({
+ size: 4,
+ layers: [{ op: 'noise', colorA: 0, colorB: 0xffffff, octaves: MAX_NOISE_OCTAVES + 1 }],
+ }),
+ ).toThrow(/octaves/);
+ });
+
+ test('colors outside 24-bit range are rejected', () => {
+ expect(() =>
+ proceduralTexture({ size: 4, layers: [{ op: 'solid', color: 0x1000000 }] }),
+ ).toThrow(/color integer/);
+ expect(() => proceduralTexture({ size: 4, layers: [{ op: 'solid', color: -1 }] })).toThrow(
+ /color integer/,
+ );
+ });
+
+ test('an unknown blend mode is rejected', () => {
+ expect(() =>
+ proceduralTexture({
+ size: 4,
+ layers: [layers[0]!, { op: 'solid', color: 0, blend: 'divide' as never }],
+ }),
+ ).toThrow(/blend/);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// normalMapFromHeight
+// -----------------------------------------------------------------------------
+
+describe('normalMapFromHeight', () => {
+ test('a flat source yields a flat normal map pointing straight out', () => {
+ const flat = proceduralTexture({ size: 16, layers: [{ op: 'solid', color: 0x808080 }] });
+ const n = normalMapFromHeight(flat);
+ // Flat means (0,0,1), encoded as (128,128,255).
+ expect(texelAt(n, 8, 8)[0]).toBe(128);
+ expect(texelAt(n, 8, 8)[1]).toBe(128);
+ expect(texelAt(n, 8, 8)[2]).toBeGreaterThan(250);
+ });
+
+ test('a gradient tilts the normal along the slope', () => {
+ const ramp = proceduralTexture({
+ size: 32,
+ layers: [{ op: 'gradient', from: 0x000000, to: 0xffffff }],
+ });
+ const n = normalMapFromHeight(ramp, { strength: 4 });
+ // Height rises along +x, so the normal leans back along -x: red < 128.
+ expect(texelAt(n, 16, 16)[0]).toBeLessThan(128);
+ expect(texelAt(n, 16, 16)[1]).toBe(128);
+ });
+
+ test('output is linear data, never sRGB', () => {
+ const src = proceduralTexture({
+ size: 8,
+ usage: 'albedo',
+ layers: [{ op: 'solid', color: 0x808080 }],
+ });
+ expect(src.colorSpace).toBe(THREE.SRGBColorSpace);
+ expect(normalMapFromHeight(src).colorSpace).toBe(THREE.NoColorSpace);
+ });
+
+ test('it names the derived map after its source', () => {
+ const src = proceduralTexture({ size: 8, name: 'Bark', layers: [{ op: 'solid', color: 0 }] });
+ expect(normalMapFromHeight(src).name).toBe('Bark_Normal');
+ });
+
+ test('a source with no readable pixels is rejected with the reason', () => {
+ expect(() => normalMapFromHeight(new THREE.Texture())).toThrow(/no readable pixels/);
+ });
+
+ test('strength must be positive', () => {
+ const src = proceduralTexture({ size: 8, layers: [{ op: 'solid', color: 0 }] });
+ expect(() => normalMapFromHeight(src, { strength: 0 })).toThrow(/positive/);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// End to end through the sandbox
+// -----------------------------------------------------------------------------
+
+describe('the agent path', () => {
+ test('generated code can build a fully procedural PBR material', async () => {
+ const code = `
+const meta = { name: 'ProcCrate' };
+function build() {
+ const root = createRoot('ProcCrate');
+ const albedo = proceduralTexture({
+ size: 64,
+ usage: 'albedo',
+ name: 'CrateWood',
+ layers: [
+ { op: 'solid', color: 0x8a6a43 },
+ { op: 'noise', colorA: 0x6b4f30, colorB: 0xa88358, scale: 5, octaves: 3, seed: 2, blend: 'overlay' },
+ { op: 'stripes', colorA: 0x000000, colorB: 0xffffff, count: 8, angleDeg: 90, blend: 'multiply', opacity: 0.2 },
+ ],
+ });
+ const mat = pbrMaterial({ albedo, normal: normalMapFromHeight(albedo, { strength: 3 }) });
+ createPart('Body', boxGeo(1, 1, 1), mat, { parent: root });
+ return root;
+}
+`;
+ const executed = await executeKilnCode(code);
+ expect(executed.root.name).toBe('ProcCrate');
+
+ const mesh = executed.root.children[0] as THREE.Mesh;
+ const mat = mesh.material as THREE.MeshStandardMaterial;
+ expect(mat.map?.name).toBe('CrateWood');
+ expect(mat.normalMap).toBeTruthy();
+ expect(mat.map?.colorSpace).toBe(THREE.SRGBColorSpace);
+ expect(mat.normalMap?.colorSpace).toBe(THREE.NoColorSpace);
+ });
+});
diff --git a/src/__tests__/texture-bake.test.ts b/src/__tests__/texture-bake.test.ts
new file mode 100644
index 00000000..0ccc9ced
--- /dev/null
+++ b/src/__tests__/texture-bake.test.ts
@@ -0,0 +1,456 @@
+/**
+ * T2.2 — in-memory textures are baked to PNG at export, or warned about by name.
+ *
+ * The behaviour these pin was measured before the bake pass existed: a
+ * `MeshStandardMaterial` carrying a hand-built 8x8 checker `map` exported 1912
+ * bytes of valid GLB containing no image, with an empty `warnings` array and a
+ * QA disposition of `pass` under `KILN_QA_MODE=off`. Nothing anywhere said the
+ * texture had been dropped.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import { renderSceneToGLB } from '../render';
+import { bakeSceneTextures, ensureNormalMapTangents } from '../texture-bake';
+
+// -----------------------------------------------------------------------------
+// Fixtures
+// -----------------------------------------------------------------------------
+
+/** Deterministic checker with no random component, so byte comparisons mean something. */
+function checkerTexture(size = 8, channels: 3 | 4 = 4): THREE.DataTexture {
+ const data = new Uint8Array(size * size * channels);
+ for (let i = 0; i < size * size; i++) {
+ const x = i % size;
+ const y = (i / size) | 0;
+ const v = (x + y) % 2 === 0 ? 220 : 40;
+ data[i * channels] = v;
+ data[i * channels + 1] = 30;
+ data[i * channels + 2] = 255 - v;
+ if (channels === 4) data[i * channels + 3] = 255;
+ }
+ const tex = new THREE.DataTexture(
+ data,
+ size,
+ size,
+ channels === 4 ? THREE.RGBAFormat : THREE.RGBFormat,
+ THREE.UnsignedByteType,
+ );
+ tex.needsUpdate = true;
+ return tex;
+}
+
+function albedoTexture(name: string, size = 8, channels: 3 | 4 = 4): THREE.DataTexture {
+ const tex = checkerTexture(size, channels);
+ tex.name = name;
+ // The bake pass never sets this; an albedo map that omits it blocks QA on
+ // purpose. See the color-space test below.
+ tex.colorSpace = THREE.SRGBColorSpace;
+ return tex;
+}
+
+function sceneWith(material: THREE.Material, meshName = 'Mesh_Box'): THREE.Object3D {
+ const root = new THREE.Object3D();
+ root.name = 'Asset';
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material);
+ mesh.name = meshName;
+ root.add(mesh);
+ return root;
+}
+
+function stdMaterial(name: string): THREE.MeshStandardMaterial {
+ const m = new THREE.MeshStandardMaterial({ color: 0xffffff });
+ m.name = name;
+ return m;
+}
+
+const glbText = (bytes: Uint8Array): string => Buffer.from(bytes).toString('latin1');
+
+// -----------------------------------------------------------------------------
+// The texture actually reaches the file
+// -----------------------------------------------------------------------------
+
+describe('procedural textures are baked into the GLB', () => {
+ test('a hand-built DataTexture is encoded, embedded, and reported — not dropped', async () => {
+ const mat = stdMaterial('ProcMat');
+ mat.map = albedoTexture('ProcChecker');
+
+ const out = await renderSceneToGLB(sceneWith(mat));
+
+ // The regression this exists to catch: an image in the file, and a QA
+ // verdict reached with that image present.
+ expect(glbText(out.bytes)).toContain('\x89PNG');
+ expect(glbText(out.bytes)).toContain('ProcChecker');
+ expect(out.qaReport.disposition).toBe('pass');
+ expect(out.warnings).toEqual([]);
+
+ expect(out.bakedTextures).toHaveLength(1);
+ const [rec] = out.bakedTextures!;
+ expect(rec).toMatchObject({
+ schemaVersion: 1,
+ texture: 'ProcChecker',
+ material: 'ProcMat',
+ slot: 'map',
+ usage: 'albedo',
+ width: 8,
+ height: 8,
+ channels: 4,
+ });
+ expect(rec!.bytes).toBeGreaterThan(0);
+ expect(rec!.sha1).toMatch(/^[0-9a-f]{40}$/);
+ });
+
+ test('three-channel RGB pixels bake as well as RGBA', async () => {
+ const mat = stdMaterial('RgbMat');
+ mat.map = albedoTexture('RgbChecker', 8, 3);
+
+ const out = await renderSceneToGLB(sceneWith(mat));
+
+ expect(out.warnings).toEqual([]);
+ expect(out.bakedTextures?.[0]).toMatchObject({ channels: 3, width: 8, height: 8 });
+ expect(glbText(out.bytes)).toContain('\x89PNG');
+ });
+
+ test('the non-PBR path is covered too — a Lambert map was just as silent', async () => {
+ const mat = new THREE.MeshLambertMaterial({ color: 0xffffff });
+ mat.name = 'LambertMat';
+ mat.map = albedoTexture('LambertTex');
+
+ const out = await renderSceneToGLB(sceneWith(mat));
+
+ expect(out.bakedTextures).toHaveLength(1);
+ expect(out.bakedTextures?.[0]?.slot).toBe('map');
+ expect(glbText(out.bytes)).toContain('\x89PNG');
+ });
+
+ test('every bridgeable slot bakes with the usage that slot implies', async () => {
+ const mat = stdMaterial('MultiSlot');
+ mat.map = albedoTexture('Albedo');
+ const normal = checkerTexture();
+ normal.name = 'Normal';
+ mat.normalMap = normal;
+ const rough = checkerTexture();
+ rough.name = 'Rough';
+ mat.roughnessMap = rough;
+
+ const warnings: string[] = [];
+ const baked = await bakeSceneTextures(sceneWith(mat), warnings);
+
+ expect(warnings).toEqual([]);
+ expect(baked.map((b) => [b.slot, b.usage])).toEqual([
+ ['map', 'albedo'],
+ ['normalMap', 'normal'],
+ ['roughnessMap', 'roughness'],
+ ]);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Determinism — T2.2's stated acceptance criterion
+// -----------------------------------------------------------------------------
+
+describe('determinism', () => {
+ test('the same pixels produce the same PNG bytes across independent renders', async () => {
+ const build = () => {
+ const mat = stdMaterial('DetMat');
+ mat.map = albedoTexture('DetTex');
+ return sceneWith(mat);
+ };
+
+ const a = await renderSceneToGLB(build());
+ const b = await renderSceneToGLB(build());
+
+ expect(a.bakedTextures?.[0]?.sha1).toBe(b.bakedTextures![0]!.sha1);
+ // Byte-identical GLBs, not merely identical textures: this is the property
+ // the pinned-SHA fixture corpus depends on staying true.
+ expect(Buffer.compare(Buffer.from(a.bytes), Buffer.from(b.bytes))).toBe(0);
+ });
+
+ test('different pixels produce a different hash (the check above can fail)', async () => {
+ const matA = stdMaterial('M');
+ matA.map = albedoTexture('T', 8);
+ const matB = stdMaterial('M');
+ matB.map = albedoTexture('T', 16);
+
+ const a = await bakeSceneTextures(sceneWith(matA), []);
+ const b = await bakeSceneTextures(sceneWith(matB), []);
+
+ expect(a[0]!.sha1).not.toBe(b[0]!.sha1);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// What cannot be baked is named, not swallowed
+// -----------------------------------------------------------------------------
+
+describe('unbakeable textures warn by material and slot', () => {
+ test('float pixel data is reported as unbakeable, and does not throw', async () => {
+ const mat = stdMaterial('FloatMat');
+ const tex = new THREE.DataTexture(
+ new Float32Array(8 * 8 * 4),
+ 8,
+ 8,
+ THREE.RGBAFormat,
+ THREE.FloatType,
+ );
+ tex.name = 'FloatTex';
+ mat.map = tex;
+
+ const warnings: string[] = [];
+ const baked = await bakeSceneTextures(sceneWith(mat), warnings);
+
+ expect(baked).toEqual([]);
+ expect(warnings).toHaveLength(1);
+ // The three facts that make it actionable: which texture, which material,
+ // which slot — none of which the bridge itself could have named.
+ expect(warnings[0]).toContain('"FloatTex"');
+ expect(warnings[0]).toContain('"FloatMat"');
+ expect(warnings[0]).toContain('(map)');
+ expect(warnings[0]).toContain('float');
+ });
+
+ test('a texture with no readable pixels is reported, naming the slot', async () => {
+ const mat = stdMaterial('EmptyMat');
+ const tex = new THREE.Texture();
+ tex.name = 'NoPixels';
+ mat.normalMap = tex;
+
+ const warnings: string[] = [];
+ const baked = await bakeSceneTextures(sceneWith(mat), warnings);
+
+ expect(baked).toEqual([]);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain('"NoPixels"');
+ expect(warnings[0]).toContain('(normalMap)');
+ });
+
+ test('a byte count that is neither RGB nor RGBA is reported with the numbers', async () => {
+ const mat = stdMaterial('RaggedMat');
+ // 8x8 at 2 bytes/pixel — a plausible mistake (luminance+alpha), unsupported.
+ const tex = new THREE.DataTexture(new Uint8Array(8 * 8 * 2), 8, 8);
+ tex.name = 'Ragged';
+ mat.map = tex;
+
+ const warnings: string[] = [];
+ await bakeSceneTextures(sceneWith(mat), warnings);
+
+ expect(warnings[0]).toContain('128 bytes for 8x8');
+ });
+
+ test('one bad slot does not stop the others from baking', async () => {
+ const mat = stdMaterial('MixedMat');
+ mat.map = albedoTexture('GoodTex');
+ const bad = new THREE.Texture();
+ bad.name = 'BadTex';
+ mat.emissiveMap = bad;
+
+ const warnings: string[] = [];
+ const baked = await bakeSceneTextures(sceneWith(mat), warnings);
+
+ expect(baked.map((b) => b.texture)).toEqual(['GoodTex']);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain('"BadTex"');
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Boundaries: what the pass must NOT do
+// -----------------------------------------------------------------------------
+
+describe('bake boundaries', () => {
+ test('an already-encoded texture is left exactly as loadTexture left it', async () => {
+ const mat = stdMaterial('LoadedMat');
+ const tex = albedoTexture('Loaded');
+ const original = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3, 4]);
+ (tex.userData as Record<string, unknown>)['encoded'] = {
+ mime: 'image/png',
+ bytes: original,
+ };
+ mat.map = tex;
+
+ const warnings: string[] = [];
+ const baked = await bakeSceneTextures(sceneWith(mat), warnings);
+
+ expect(baked).toEqual([]);
+ expect(warnings).toEqual([]);
+ expect((tex.userData as Record<string, unknown>)['encoded']).toEqual({
+ mime: 'image/png',
+ bytes: original,
+ });
+ });
+
+ test('a texture shared by two materials is encoded once and stays shared', async () => {
+ const shared = albedoTexture('SharedTex');
+ const matA = stdMaterial('MatA');
+ matA.map = shared;
+ const matB = stdMaterial('MatB');
+ matB.map = shared;
+
+ const root = new THREE.Object3D();
+ root.name = 'Asset';
+ for (const [i, m] of [matA, matB].entries()) {
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), m);
+ mesh.name = `Mesh_${i}`;
+ root.add(mesh);
+ }
+
+ const warnings: string[] = [];
+ const baked = await bakeSceneTextures(root, warnings);
+
+ // Encoding twice would be wasted work; cloning would break the bridge's
+ // texture cache, which dedupes by object identity.
+ expect(baked).toHaveLength(1);
+ expect(matA.map).toBe(matB.map);
+ });
+
+ test('color space is never set for the author — a linear albedo still blocks', async () => {
+ const mat = stdMaterial('LinearMat');
+ const tex = checkerTexture();
+ tex.name = 'LinearAlbedo';
+ // Deliberately left at the DataTexture default (linear) while filling the
+ // sRGB `map` slot.
+ mat.map = tex;
+
+ const warnings: string[] = [];
+ await bakeSceneTextures(sceneWith(mat), warnings);
+
+ // Baked (so the pixels are exportable) but still honestly described as
+ // linear, so QA can catch the mismatch instead of the pass hiding it.
+ expect(warnings).toEqual([]);
+ const meta = (tex.userData as Record<string, unknown>)['kilnTexture'] as {
+ colorSpace: string;
+ };
+ expect(meta.colorSpace).toBe('linear');
+ expect(tex.colorSpace).toBe(THREE.NoColorSpace);
+
+ await expect(renderSceneToGLB(sceneWith(mat))).rejects.toThrow('MAT_TEXTURE_COLOR_SPACE');
+ });
+
+ test('an untextured scene bakes nothing and reports nothing', async () => {
+ const out = await renderSceneToGLB(sceneWith(stdMaterial('Plain')));
+ expect(out.bakedTextures).toBeUndefined();
+ expect(out.warnings).toEqual([]);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Tangents — a normal map without them is non-portable
+// -----------------------------------------------------------------------------
+
+describe('normal-mapped meshes get a tangent basis', () => {
+ /** Box geometry with UVs, which is what a normal map needs to be sampled at all. */
+ function uvBox(): THREE.BufferGeometry {
+ return new THREE.BoxGeometry(1, 1, 1);
+ }
+
+ function normalMapped(name = 'NormalMat'): THREE.MeshStandardMaterial {
+ const mat = stdMaterial(name);
+ const n = checkerTexture();
+ n.name = 'NormalTex';
+ mat.normalMap = n;
+ return mat;
+ }
+
+ test('the Khronos tangent-space warning is gone and TANGENT is in the file', async () => {
+ // Measured before this pass existed: the same asset validated with
+ // MESH_PRIMITIVE_GENERATED_TANGENT_SPACE and carried no tangent accessor.
+ const mat = normalMapped();
+ const root = new THREE.Object3D();
+ root.name = 'Asset';
+ const mesh = new THREE.Mesh(uvBox(), mat);
+ mesh.name = 'Mesh_Box';
+ root.add(mesh);
+
+ const out = await renderSceneToGLB(root);
+
+ expect(out.warnings).toEqual([]);
+ const issues = JSON.stringify(out.gltfValidation);
+ expect(issues).not.toContain('GENERATED_TANGENT_SPACE');
+ expect(glbText(out.bytes)).toContain('TANGENT');
+ });
+
+ test('tangents are unit length, perpendicular to the normal, with ±1 handedness', () => {
+ const geometry = uvBox();
+ const mesh = new THREE.Mesh(geometry, normalMapped());
+ mesh.name = 'Mesh_Box';
+ const root = new THREE.Object3D();
+ root.add(mesh);
+
+ expect(ensureNormalMapTangents(root, [])).toBe(1);
+
+ const tangent = geometry.getAttribute('tangent')!;
+ expect(tangent.itemSize).toBe(4);
+ const normal = geometry.getAttribute('normal')!;
+ for (let i = 0; i < tangent.count; i++) {
+ const t = new THREE.Vector3(tangent.getX(i), tangent.getY(i), tangent.getZ(i));
+ const n = new THREE.Vector3(normal.getX(i), normal.getY(i), normal.getZ(i));
+ expect(t.length()).toBeCloseTo(1, 5);
+ expect(Math.abs(t.dot(n))).toBeLessThan(1e-5);
+ expect(Math.abs(tangent.getW(i))).toBe(1);
+ }
+ });
+
+ test('a mesh with no normal map is left alone — the attribute changes the bytes', () => {
+ const geometry = uvBox();
+ const mesh = new THREE.Mesh(geometry, stdMaterial('Plain'));
+ const root = new THREE.Object3D();
+ root.add(mesh);
+
+ expect(ensureNormalMapTangents(root, [])).toBe(0);
+ expect(geometry.getAttribute('tangent')).toBeUndefined();
+ });
+
+ test('an existing tangent attribute is never recomputed', () => {
+ const geometry = uvBox();
+ const mine = new THREE.BufferAttribute(
+ new Float32Array(geometry.getAttribute('position')!.count * 4),
+ 4,
+ );
+ geometry.setAttribute('tangent', mine);
+ const mesh = new THREE.Mesh(geometry, normalMapped());
+ const root = new THREE.Object3D();
+ root.add(mesh);
+
+ expect(ensureNormalMapTangents(root, [])).toBe(0);
+ expect(geometry.getAttribute('tangent')).toBe(mine);
+ });
+
+ test('a normal-mapped mesh with no UVs is warned about, pointing at autoUnwrap', () => {
+ const geometry = uvBox();
+ geometry.deleteAttribute('uv');
+ const mesh = new THREE.Mesh(geometry, normalMapped());
+ mesh.name = 'Mesh_NoUv';
+ const root = new THREE.Object3D();
+ root.add(mesh);
+
+ const warnings: string[] = [];
+ expect(ensureNormalMapTangents(root, warnings)).toBe(0);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain('"Mesh_NoUv"');
+ expect(warnings[0]).toContain('autoUnwrap');
+ });
+
+ test('a non-indexed normal-mapped mesh is warned about by name', () => {
+ const geometry = uvBox().toNonIndexed();
+ const mesh = new THREE.Mesh(geometry, normalMapped());
+ mesh.name = 'Mesh_Flat';
+ const root = new THREE.Object3D();
+ root.add(mesh);
+
+ const warnings: string[] = [];
+ expect(ensureNormalMapTangents(root, warnings)).toBe(0);
+ expect(warnings[0]).toContain('"Mesh_Flat"');
+ expect(warnings[0]).toContain('not indexed');
+ });
+
+ test('geometry shared by two normal-mapped meshes is computed once', () => {
+ const geometry = uvBox();
+ const root = new THREE.Object3D();
+ for (const i of [0, 1]) {
+ const mesh = new THREE.Mesh(geometry, normalMapped(`Mat${i}`));
+ mesh.name = `Mesh_${i}`;
+ root.add(mesh);
+ }
+ expect(ensureNormalMapTangents(root, [])).toBe(1);
+ });
+});
diff --git a/src/agent/generate.test.ts b/src/agent/generate.test.ts
index 30ac71fb..17206c90 100644
--- a/src/agent/generate.test.ts
+++ b/src/agent/generate.test.ts
@@ -279,9 +279,12 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
expect(r.renderDegraded).toBe(false);
expect(r.renderDegradedReason).toBeUndefined();
expect(r.viewsRendererId).toBe('dawn-vulkan:test-gpu:1.0');
- // The views are the port cells composited into the SAME 3x2 grid layout.
- const { compositeViewPngGrid } = await import('../views');
- expect(Buffer.compare(r.views!, compositeViewPngGrid(viewsPng).png)).toBe(0);
+ // The views are the port cells composited into the SAME 3x2 grid layout,
+ // and stamped with the same cell labels + gnomon the CPU path applies.
+ const { compositeViewPngGrid, SIX_VIEWS } = await import('../views');
+ expect(Buffer.compare(r.views!, compositeViewPngGrid(viewsPng, 3, SIX_VIEWS).png)).toBe(0);
+ // Annotation is not optional decoration: an unlabelled sheet would differ.
+ expect(Buffer.compare(r.views!, compositeViewPngGrid(viewsPng).png)).not.toBe(0);
});
test('port is never consulted when captureViews is off', async () => {
@@ -401,8 +404,10 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
expect(okOutcome.ok).toBe(true);
if (okOutcome.ok) {
expect(okOutcome.rendererId).toBe('dawn-vulkan:test-gpu:1.0');
- const { compositeViewPngGrid } = await import('../views');
- expect(Buffer.compare(okOutcome.png, compositeViewPngGrid(viewsPng).png)).toBe(0);
+ const { compositeViewPngGrid, SIX_VIEWS } = await import('../views');
+ expect(Buffer.compare(okOutcome.png, compositeViewPngGrid(viewsPng, 3, SIX_VIEWS).png)).toBe(
+ 0,
+ );
}
const degraded = await captureViewsViaPort(
@@ -432,4 +437,215 @@ describe('generateKilnAsset viewRenderPort (B3b/B4)', () => {
// The returned artifact is untouched: still a valid GLB with the magic intact.
expect(r.glb.readUInt32LE(0)).toBe(0x46546c67);
});
+
+ // ===========================================================================
+ // T3.3 — the persisted artifact honours the requested layout, on BOTH paths
+ // ===========================================================================
+
+ /** N solid-color per-view PNGs, like a host PBR renderer would return. */
+ async function stubCells(n: number, size = 8): Promise<Uint8Array[]> {
+ const { encodePng } = await import('../views');
+ return Array.from({ length: n }, (_, i) => {
+ const rgb = new Uint8Array(size * size * 3);
+ for (let p = 0; p < size * size; p++) rgb[p * 3] = 20 + i * 20;
+ return new Uint8Array(encodePng(rgb, size, size));
+ });
+ }
+
+ test('T3.3 BYTE-IDENTITY: omitting capture is unchanged, and an explicit 3x2 matches it', async () => {
+ runImpl = okRun;
+ const base = await generateKilnAsset({ prompt: 'a crate', captureViews: true });
+ const explicit = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ capture: { preset: '3x2' },
+ });
+ expect(Buffer.compare(explicit.views!, base.views!)).toBe(0);
+ expect(base.viewsCapture).toEqual({ preset: '3x2', cols: 3, cells: 6 });
+ expect(explicit.viewsCapture).toEqual({ preset: '3x2', cols: 3, cells: 6 });
+ });
+
+ test('T3.3: the port is asked for the requested cell count and composited at its columns', async () => {
+ runImpl = okRun;
+ const viewsPng = await stubCells(9);
+ const requests: import('../composer/render-port').PbrRenderRequest[] = [];
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ capture: { preset: '3x3' },
+ viewRenderPort: async (req) => {
+ requests.push(req);
+ return { ok: true, rendererId: 'dawn-vulkan:test-gpu:1.0', viewsPng };
+ },
+ });
+ // The relaxed count check: nine views requested, nine accepted (this used to
+ // be a hard six).
+ expect(requests[0]!.viewDirs).toHaveLength(9);
+ expect(r.renderDegraded).toBe(false);
+ expect(r.viewsCapture).toEqual({ preset: '3x3', cols: 3, cells: 9 });
+ const { compositeViewPngGrid, resolveCapture } = await import('../views');
+ const cells = resolveCapture({ preset: '3x3' }).views;
+ expect(Buffer.compare(r.views!, compositeViewPngGrid(viewsPng, 3, cells).png)).toBe(0);
+ });
+
+ test('T3.3: a 2-column request composites at 2 columns, not the default 3', async () => {
+ runImpl = okRun;
+ const viewsPng = await stubCells(4);
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ capture: { preset: '2x2' },
+ viewRenderPort: async () => ({ ok: true, rendererId: 'gpu:test', viewsPng }),
+ });
+ expect(r.viewsCapture).toEqual({ preset: '2x2', cols: 2, cells: 4 });
+ const { compositeViewPngGrid, resolveCapture } = await import('../views');
+ const cells = resolveCapture({ preset: '2x2' }).views;
+ // Same cells at 3 cols would be a different image; pin that it is not that.
+ expect(Buffer.compare(r.views!, compositeViewPngGrid(viewsPng, 2, cells).png)).toBe(0);
+ expect(Buffer.compare(r.views!, compositeViewPngGrid(viewsPng, 3, cells).png)).not.toBe(0);
+ });
+
+ test('T3.3: a GPU degrade produces the SAME layout the port was asked for', async () => {
+ runImpl = okRun;
+ const capture = { preset: '3x1' as const };
+ const degraded = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ capture,
+ viewRenderPort: async () => {
+ throw new Error('GPU service unreachable');
+ },
+ });
+ expect(degraded.renderDegraded).toBe(true);
+ expect(degraded.viewsCapture).toEqual({ preset: '3x1', cols: 3, cells: 3 });
+
+ // The whole point: a GPU outage must not reshape the artifact. The degraded
+ // sheet is exactly what the CPU path produces for the same request.
+ const { renderCodeViewGrid } = await import('../views');
+ const cpu = await renderCodeViewGrid(CANNED_CODE, { capture });
+ expect(Buffer.compare(degraded.views!, cpu.png)).toBe(0);
+ });
+
+ test('T3.3: per-cell zoom declines the port rather than silently auto-framing', async () => {
+ runImpl = okRun;
+ let portCalls = 0;
+ const capture = { cells: [{ azimuthDeg: 45, elevationDeg: 20, zoom: 2 }] };
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ capture,
+ viewRenderPort: async () => {
+ portCalls++;
+ return { ok: true, rendererId: 'gpu:test', viewsPng: await stubCells(1) };
+ },
+ });
+ // The port contract carries directions only — it cannot express zoom, and
+ // returning auto-framed cells for a zoom request would be a silent wrong
+ // answer. Not even attempted.
+ expect(portCalls).toBe(0);
+ expect(r.renderDegraded).toBe(true);
+ expect(r.renderDegradedReason).toContain('zoom is not supported');
+ const { renderCodeViewGrid } = await import('../views');
+ expect(Buffer.compare(r.views!, (await renderCodeViewGrid(CANNED_CODE, { capture })).png)).toBe(
+ 0,
+ );
+ });
+
+ test('T3.3: an invalid capture warns and falls back — it never fails the run', async () => {
+ runImpl = okRun;
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ capture: { preset: '4x4' as never },
+ });
+ expect(r.views).toBeInstanceOf(Buffer);
+ expect(r.viewsCapture).toEqual({ preset: '3x2', cols: 3, cells: 6 });
+ expect(r.warnings.some((w) => w.includes('capture config ignored'))).toBe(true);
+
+ const base = await generateKilnAsset({ prompt: 'a crate', captureViews: true });
+ expect(Buffer.compare(r.views!, base.views!)).toBe(0);
+ });
+
+ test('T3.3: a bad config degrades the port too, instead of reaching it twice differently', async () => {
+ runImpl = okRun;
+ let portCalls = 0;
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ capture: { cells: [] },
+ viewRenderPort: async () => {
+ portCalls++;
+ return { ok: true, rendererId: 'gpu:test', viewsPng: await stubCells(6) };
+ },
+ });
+ // Validated once, up front: the port is asked for the DEFAULT grid, not for
+ // the rejected config and not skipped entirely.
+ expect(portCalls).toBe(1);
+ expect(r.renderDegraded).toBe(false);
+ expect(r.viewsCapture).toEqual({ preset: '3x2', cols: 3, cells: 6 });
+ expect(r.warnings.some((w) => w.includes('capture config ignored'))).toBe(true);
+ });
+
+ test('T3.3: the GPU sheet carries the same cell labels and gnomon as the CPU one', async () => {
+ // A host returns pixels; it knows nothing of the Kiln camera vocabulary. If
+ // the engine did not stamp, the GPU sheet would arrive unlabelled and the
+ // model would lose its orientation cues on the one path that cannot tell it
+ // happened. Producer identity belongs in `viewsRendererId`, not in whether
+ // the picture has words on it.
+ runImpl = okRun;
+ const viewsPng = await stubCells(2);
+ const capture = { cells: [{ azimuthDeg: 0, elevationDeg: 0, name: 'seam' }] };
+ const r = await generateKilnAsset({
+ prompt: 'a crate',
+ captureViews: true,
+ capture: { preset: '1x2' },
+ viewRenderPort: async () => ({ ok: true, rendererId: 'gpu:test', viewsPng }),
+ });
+
+ const { compositeViewPngGrid, resolveCapture } = await import('../views');
+ const cells = resolveCapture({ preset: '1x2' }).views;
+ const annotated = compositeViewPngGrid(viewsPng, 1, cells).png;
+ const bare = compositeViewPngGrid(viewsPng, 1).png;
+ expect(Buffer.compare(r.views!, annotated)).toBe(0);
+ expect(Buffer.compare(r.views!, bare)).not.toBe(0);
+
+ // Custom cell names reach the GPU sheet too, not just the CPU one.
+ const named = resolveCapture(capture).views;
+ expect(named[0]!.name).toBe('SEAM');
+ const one = viewsPng.slice(0, 1);
+ expect(
+ Buffer.compare(compositeViewPngGrid(one, 1, named).png, compositeViewPngGrid(one, 1).png),
+ ).not.toBe(0);
+
+ // A misaligned view list is a caller bug, not something to composite anyway.
+ expect(() => compositeViewPngGrid(viewsPng, 1, named)).toThrow(/align 1:1/);
+ });
+
+ test('T3.3: captureViewsViaPort takes capture as its fourth argument', async () => {
+ const { captureViewsViaPort } = await import('./generate');
+ const viewsPng = await stubCells(2);
+ const seen: number[] = [];
+ const out = await captureViewsViaPort(
+ async (req) => {
+ seen.push(req.viewDirs?.length ?? 0);
+ return { ok: true, rendererId: 'gpu:test', viewsPng };
+ },
+ new Uint8Array([1, 2, 3]),
+ undefined,
+ { preset: '2x1' },
+ );
+ expect(seen).toEqual([2]);
+ expect(out.ok).toBe(true);
+ if (out.ok) expect(out.capture).toEqual({ preset: '2x1', cols: 2, cells: 2 });
+
+ // Count mismatch now reports the REQUESTED count, not a hardcoded six.
+ const short = await captureViewsViaPort(
+ async () => ({ ok: true, rendererId: 'gpu:test', viewsPng: viewsPng.slice(0, 1) }),
+ new Uint8Array([1, 2, 3]),
+ undefined,
+ { preset: '2x1' },
+ );
+ expect(short.ok).toBe(false);
+ if (!short.ok) expect(short.reason).toContain('returned 1 view PNGs, expected 2');
+ });
});
diff --git a/src/agent/generate.ts b/src/agent/generate.ts
index 00c2fb4c..64fed817 100644
--- a/src/agent/generate.ts
+++ b/src/agent/generate.ts
@@ -16,7 +16,13 @@
*/
import { renderGLB, type KilnCodeMeta, type RenderResult } from '../render';
import type { PbrRenderPort } from '../composer/render-port';
-import { resolveGridViews } from '../views/raster';
+import {
+ CaptureConfigError,
+ resolveGridCapture,
+ type CaptureConfig,
+ type CaptureShape,
+ type ResolvedCapture,
+} from '../views/capture';
import { compositeViewPngGrid } from '../views/grid';
import { CPU_RASTER_RENDERER_ID } from '../views/renderer-id';
import type { AssetStyle } from '../prompt';
@@ -68,6 +74,11 @@ export interface GenerateKilnAssetOptions {
/** Also rasterize the final asset into the six-view grid PNG (`result.views`).
* Best-effort: a views failure never fails the run. Default false. */
captureViews?: boolean;
+ /** Grid shape / per-cell cameras for the `views` artifact (T3.3). Honoured
+ * identically by the GPU port and the CPU rasterizer. Omitted keeps the
+ * shipped six-view 3x2. An invalid config degrades to that default with a
+ * warning rather than failing the run. */
+ capture?: CaptureConfig;
/** OPTIONAL host PBR renderer (GLB bytes -> per-view PNGs). Only consulted when
* `captureViews` is on: the already-produced GLB bytes are routed to the port
* and its per-view PNGs are composited into the same 3x2 grid the CPU path
@@ -114,6 +125,10 @@ export interface GenerateKilnAssetResult {
salvageError?: string;
/** Six-view grid PNG of the final asset (only when `captureViews` was set and the render succeeded). */
views?: Buffer;
+ /** The layout `views` was actually produced in — preset, columns, cell count.
+ * Present whenever `views` is, and identical whichever producer made it, so a
+ * consumer never has to infer the grid shape from the image dimensions. */
+ viewsCapture?: CaptureShape;
/** Honest producer of `views` (only when `viewRenderPort` was supplied): the
* port's rendererId on success, else the CPU rasterizer's deterministic id. */
viewsRendererId?: string;
@@ -197,12 +212,12 @@ export async function generateKilnCodeAgent(opts: {
export const DEFAULT_VIEW_RENDER_TIMEOUT_MS = 8000;
export type PortViewsOutcome =
- | { ok: true; png: Buffer; rendererId: string }
+ | { ok: true; png: Buffer; rendererId: string; capture: CaptureShape }
| { ok: false; reason: string };
/**
* Call the host view-render port with the ALREADY-PRODUCED GLB bytes and
- * composite its per-view PNGs into the same 3x2 grid the CPU path emits.
+ * composite its per-view PNGs into the same grid the CPU path emits.
*
* This shell is NOT a render compute path: the deadline is a plain timer (no
* Date.now() enters any rasterizer), and every failure mode — thrown/rejected
@@ -213,15 +228,39 @@ export type PortViewsOutcome =
* Exported as the single owner of the degrade policy: hosts that assemble their
* own generation pipeline (rather than calling generateKilnAsset) route their
* produced GLB through this same shell instead of re-implementing it.
+ *
+ * T3.3: `capture` selects the grid shape and per-cell cameras, resolved through
+ * the SAME {@link resolveGridCapture} the CPU rasterizer uses so both producers
+ * lay out identically. Omitted keeps the shipped six-view 3x2 (H-33 env variant
+ * included).
*/
export async function captureViewsViaPort(
port: PbrRenderPort,
glb: Buffer | Uint8Array,
timeoutMs: number = DEFAULT_VIEW_RENDER_TIMEOUT_MS,
+ capture?: CaptureConfig,
): Promise<PortViewsOutcome> {
- // Same views + cell size as the CPU grid default, so the composited layout
- // matches renderCodeViewGrid (H-33 env variant included).
- const views = resolveGridViews(process.env['KILN_GRID_VARIANT']);
+ let resolved: ResolvedCapture;
+ try {
+ resolved = resolveGridCapture(capture, process.env['KILN_GRID_VARIANT']);
+ } catch (err) {
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
+ }
+ const views = resolved.views;
+ const shape: CaptureShape = { preset: resolved.preset, cols: resolved.cols, cells: views.length };
+
+ // Per-cell zoom has no equivalent in the port contract: the request carries
+ // view directions only, and the host frames each view to the asset's own
+ // bounds. Rather than silently returning auto-framed cells for a request that
+ // asked for tighter ones, decline and let the CPU rasterizer — which does
+ // implement zoom — produce the sheet that was actually asked for.
+ if (resolved.zooms.some((z) => z !== undefined)) {
+ return {
+ ok: false,
+ reason: 'per-cell zoom is not supported by the view render port',
+ };
+ }
+
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const deadline = new Promise<never>((_, reject) => {
@@ -246,14 +285,23 @@ export async function captureViewsViaPort(
if (typeof result.rendererId !== 'string' || !result.rendererId.trim()) {
return { ok: false, reason: 'view render port returned no rendererId' };
}
+ // Count must equal the cells that were REQUESTED — not a hardcoded six.
+ // A host that truncates or pads the view list produces a differently-shaped
+ // sheet than the caller asked for, which is a degrade, not a success.
if (!result.viewsPng || result.viewsPng.length !== views.length) {
return {
ok: false,
reason: `view render port returned ${result.viewsPng?.length ?? 0} view PNGs, expected ${views.length}`,
};
}
- const grid = compositeViewPngGrid(result.viewsPng);
- return { ok: true, png: grid.png, rendererId: result.rendererId };
+ // Annotated with the SAME cell labels + gnomon the CPU path stamps. A host
+ // returns pixels and knows nothing of the Kiln camera vocabulary, so
+ // without this the GPU sheet arrives unlabelled and the model quietly loses
+ // its orientation cues on the one path that cannot tell it happened.
+ // Degrade stays reportable through `renderDegraded` / `viewsRendererId`,
+ // which is a structured field rather than a visual tell.
+ const grid = compositeViewPngGrid(result.viewsPng, resolved.cols, views);
+ return { ok: true, png: grid.png, rendererId: result.rendererId, capture: shape };
} catch (err) {
return { ok: false, reason: err instanceof Error ? err.message : String(err) };
} finally {
@@ -308,10 +356,30 @@ export async function generateKilnAsset(
// Best-effort views artifact: what the vision loop / review UIs show.
// Never fails the run — a rasterizer error just drops the sidecar.
let views: Buffer | undefined;
+ let viewsCapture: CaptureShape | undefined;
let viewsRendererId: string | undefined;
let renderDegraded: boolean | undefined;
let renderDegradedReason: string | undefined;
+ const captureWarnings: string[] = [];
if (opts.captureViews) {
+ // T3.3: validate the requested layout ONCE, up front. A malformed config is
+ // a caller bug, not a render hazard, so it must not reach two producers and
+ // be reported differently by each. It also must not fail the run: the views
+ // artifact is best-effort by contract, so a bad config degrades to the
+ // shipped default and says so in `warnings`.
+ let capture = opts.capture;
+ if (capture) {
+ try {
+ resolveGridCapture(capture, process.env['KILN_GRID_VARIANT']);
+ } catch (err) {
+ if (!(err instanceof CaptureConfigError)) throw err;
+ captureWarnings.push(
+ `views capture config ignored (using the default grid): ${err.message}`,
+ );
+ capture = undefined;
+ }
+ }
+
// B3b: an injected host PBR renderer sees the already-produced GLB bytes
// (never re-executes the program). B4: ANY port failure degrades to the CPU
// rasterizer below — the GPU being unavailable can never fail a generation.
@@ -320,9 +388,11 @@ export async function generateKilnAsset(
opts.viewRenderPort,
render.glb,
opts.viewRenderTimeoutMs ?? DEFAULT_VIEW_RENDER_TIMEOUT_MS,
+ capture,
);
if (port.ok) {
views = port.png;
+ viewsCapture = port.capture;
viewsRendererId = port.rendererId;
renderDegraded = false;
} else {
@@ -333,17 +403,22 @@ export async function generateKilnAsset(
if (!views) {
try {
const { renderCodeViewGrid } = await import('../views');
- views = (await renderCodeViewGrid(agent.code)).png;
+ // The degrade path must reproduce the SAME layout the port was asked
+ // for, or a GPU outage silently reshapes the artifact.
+ const grid = await renderCodeViewGrid(agent.code, capture ? { capture } : {});
+ views = grid.png;
+ viewsCapture = grid.capture;
// Honest producer provenance, but only on the port-enabled path — the
// port-absent path stays byte-identical to the historical result shape.
if (opts.viewRenderPort) viewsRendererId = CPU_RASTER_RENDERER_ID;
} catch {
views = undefined;
+ viewsCapture = undefined;
}
}
}
- const warnings = [...(render.warnings ?? [])];
+ const warnings = [...(render.warnings ?? []), ...captureWarnings];
if (agent.salvaged) {
warnings.push(
agent.salvaged === 'error'
@@ -367,6 +442,7 @@ export async function generateKilnAsset(
...(agent.salvaged ? { salvaged: agent.salvaged } : {}),
...(agent.salvaged && agent.error ? { salvageError: agent.error } : {}),
...(views ? { views } : {}),
+ ...(views && viewsCapture ? { viewsCapture } : {}),
...(viewsRendererId ? { viewsRendererId } : {}),
...(renderDegraded !== undefined ? { renderDegraded } : {}),
...(renderDegradedReason ? { renderDegradedReason } : {}),
diff --git a/src/composer/render-port.ts b/src/composer/render-port.ts
index e25913bf..53a84cf8 100644
--- a/src/composer/render-port.ts
+++ b/src/composer/render-port.ts
@@ -47,7 +47,15 @@ export type SceneRenderPort = (req: SceneRenderRequest) => Promise<SceneRenderRe
export interface PbrRenderRequest {
/** The rendered GLB bytes (route the produced asset; do NOT re-execute programs). */
glb: Uint8Array;
- /** View directions from model center toward the camera, max 12. Omit for the host default. */
+ /**
+ * View directions from model center toward the camera, max 12. Omit for the
+ * host default.
+ *
+ * A host must return exactly one PNG per entry, in request order. Truncating
+ * or padding is a degrade, not a success: the engine composites the result
+ * into a grid whose shape was chosen from this list's length, so a
+ * different-length reply would silently reshape the artifact.
+ */
viewDirs?: [number, number, number][];
/** Square per-view cell size in pixels. */
size?: number;
@@ -55,6 +63,14 @@ export interface PbrRenderRequest {
beautySize?: number;
}
+/**
+ * Backdrop hosts must paint behind the asset, so a GPU-rendered sheet and the
+ * CPU-rasterized one a degrade produces are comparable. Re-exported here (from
+ * the rasterizer's own leaf constant) because the host implementing this port
+ * has no reason to import the rasterizer.
+ */
+export { GRID_BACKGROUND_HEX, GRID_BACKGROUND_RGB } from '../views/background';
+
export interface PbrRenderResult {
ok: boolean;
/** Honest producer identity, e.g. "dawn-vulkan:nvidia-rtx-a4500:NVIDIA: 550.100"
diff --git a/src/list-primitives.ts b/src/list-primitives.ts
index 19d1e379..c045dd8b 100644
--- a/src/list-primitives.ts
+++ b/src/list-primitives.ts
@@ -45,6 +45,10 @@ export interface PrimitiveSpec {
| 'textures';
}
+// T2.4 — the CSG/UV rule (every boolean destroys UVs; unwrap after, never
+// before) applies to all four boolean entries, so it lives once as the `csg`
+// entry in CATEGORY_NOTES in prompt-api.ts rather than four times here.
+
const PRIMITIVES: PrimitiveSpec[] = [
// ---------------------------------------------------------------------------
// Structure
@@ -941,6 +945,31 @@ const PRIMITIVES: PrimitiveSpec[] = [
promptNotes:
'NEVER texture.clone() a loaded texture (clone() corrupts the encoded bytes and breaks GLB export). Share the same Texture object and remap UVs with panelRemapV on the smaller mesh instead.',
},
+ {
+ name: 'proceduralTexture',
+ signature:
+ "proceduralTexture({ size?: 4..1024 pow2, usage?, name?, layers: [{ op: 'solid'|'checker'|'stripes'|'gradient'|'bricks'|'noise', ...params, blend?: 'normal'|'multiply'|'screen'|'overlay', opacity?: 0..1 }] })",
+ returns: 'THREE.DataTexture (tiling, sRGB or linear per usage)',
+ category: 'textures',
+ description:
+ 'Builds a tiling texture from a bounded layer stack — no image file needed. Layers composite bottom-first. Noise is seeded and tileable, so the same spec always produces the same bytes and a repeating material shows no seam. Baked to PNG and embedded in the GLB automatically.',
+ example:
+ "const bark = proceduralTexture({ size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });",
+ promptNotes:
+ 'Sync — no await. Prefer this over loadTexture for any surface you can describe (wood, rust, brick, fabric, dirt): it needs no asset files and cannot fail at load. Max 8 layers, size must be a power of two up to 1024. Only the six listed ops exist; there is no custom per-pixel callback.',
+ },
+ {
+ name: 'normalMapFromHeight',
+ signature: 'normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })',
+ returns: 'THREE.DataTexture (linear normal map)',
+ category: 'textures',
+ description:
+ "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",
+ example:
+ "const bark = proceduralTexture({ usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });\nconst mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });",
+ promptNotes:
+ 'strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot.',
+ },
{
name: 'pbrMaterial',
signature:
diff --git a/src/primitives.ts b/src/primitives.ts
index 892796cc..76dabcc5 100644
--- a/src/primitives.ts
+++ b/src/primitives.ts
@@ -22,6 +22,7 @@ import * as gears from './gears';
import * as ops from './ops';
import * as profile from './profile';
import * as solids from './solids';
+import * as proceduralTextures from './procedural-texture';
import * as textures from './textures';
import { materialRecipe } from './material-recipe-runtime';
import { createVehicleFrame, createWheelAssembly, createWheelGeometrySet } from './vehicle';
@@ -1676,6 +1677,9 @@ export function buildSandboxGlobals(usage?: Record<string, number>): Record<stri
bladeGeo: wrapGeo('bladeGeo', gears.bladeGeo),
// Textures + PBR (loadTexture is async)
loadTexture: wrap('loadTexture', textures.loadTexture),
+ // Procedural textures (sync — no I/O, so no await)
+ proceduralTexture: wrap('proceduralTexture', proceduralTextures.proceduralTexture),
+ normalMapFromHeight: wrap('normalMapFromHeight', proceduralTextures.normalMapFromHeight),
pbrMaterial: wrap('pbrMaterial', textures.pbrMaterial),
foliageMaterial: wrap('foliageMaterial', textures.foliageMaterial),
countTriangles: wrap('countTriangles', countTriangles),
diff --git a/src/procedural-texture.ts b/src/procedural-texture.ts
new file mode 100644
index 00000000..49230a4b
--- /dev/null
+++ b/src/procedural-texture.ts
@@ -0,0 +1,537 @@
+/**
+ * Model-authored procedural textures — T2.2
+ *
+ * ## Why a declarative spec and not a callback
+ *
+ * The obvious API is "give me a function and I will call it per pixel". It is
+ * rejected here for the same reason `material-recipes.ts` resolves texture
+ * slots through a closed approved-ID registry: the author of this code is an
+ * untrusted model. A callback is arbitrary code with arbitrary cost and no
+ * reviewable record of what it drew. A declarative layer stack is bounded
+ * before a single pixel is written, recorded verbatim in provenance, and
+ * reproducible from the manifest alone.
+ *
+ * Procedural content also sidesteps the licensing problem entirely: pixels
+ * computed from numbers have no third-party provenance to track, unlike the
+ * curated tiling library T2.1 has to license and ship.
+ *
+ * ## Determinism
+ *
+ * Every generator is a pure function of the spec. Noise uses an integer hash of
+ * the lattice coordinate plus the seed — never `Math.random()`, which would
+ * make the same asset code produce different bytes on every generation and
+ * break the byte-identity fixtures the repo pins.
+ *
+ * Noise is also **tileable**: the lattice wraps at the cell period, so a
+ * texture sampled with `RepeatWrapping` (which is what the loader sets, and
+ * what a tiling material wants) does not show a seam where the pattern
+ * restarts. Non-tiling noise is the usual reason a procedural material looks
+ * fine on a test cube and obviously wrong on a wall.
+ *
+ * ## Color space
+ *
+ * Unlike `texture-bake.ts` — which must never guess, because it is handed
+ * finished pixels whose meaning it cannot know — this function is told the
+ * usage up front and therefore sets `colorSpace` itself, exactly as
+ * `loadTexture` does. Getting it wrong here is an authoring error the QA gate
+ * still catches.
+ */
+
+import * as THREE from 'three';
+import type { TextureUsage } from './textures';
+
+// -----------------------------------------------------------------------------
+// Bounds — enforced before any work, so a bad spec costs nothing
+// -----------------------------------------------------------------------------
+
+/** Largest texture a spec may request. 1024^2 RGBA is 4 MB of intermediate. */
+export const MAX_PROCEDURAL_SIZE = 1024;
+/** Smallest useful size; below this the generators degenerate. */
+export const MIN_PROCEDURAL_SIZE = 4;
+/** Layers in one stack. Enough to build a convincing material, bounded enough to cost little. */
+export const MAX_PROCEDURAL_LAYERS = 8;
+/** fbm octaves. Past this, added octaves are sub-texel on a 1024 map. */
+export const MAX_NOISE_OCTAVES = 6;
+
+export type ProceduralBlend = 'normal' | 'multiply' | 'screen' | 'overlay';
+
+interface LayerCommon {
+ /** How this layer combines with everything under it. Ignored on the first layer. */
+ blend?: ProceduralBlend;
+ /** 0..1 contribution. Ignored on the first layer. Default 1. */
+ opacity?: number;
+}
+
+export type ProceduralLayer = LayerCommon &
+ (
+ | { op: 'solid'; color: number }
+ | { op: 'checker'; colorA: number; colorB: number; squares?: number }
+ | { op: 'stripes'; colorA: number; colorB: number; count?: number; angleDeg?: number }
+ | { op: 'gradient'; from: number; to: number; angleDeg?: number }
+ | {
+ op: 'bricks';
+ brick: number;
+ mortar: number;
+ rows?: number;
+ cols?: number;
+ mortarWidth?: number;
+ /** Row offset as a fraction of brick width. 0.5 is a running bond. */
+ stagger?: number;
+ }
+ | {
+ op: 'noise';
+ colorA: number;
+ colorB: number;
+ /** Lattice cells across the texture. Higher is finer. Default 8. */
+ scale?: number;
+ octaves?: number;
+ seed?: number;
+ }
+ );
+
+export interface ProceduralTextureSpec {
+ /** Power of two in [4, 1024]. Default 256. */
+ size?: number;
+ /** Sets `colorSpace` — sRGB for albedo/emissive, linear for data maps. Default albedo. */
+ usage?: TextureUsage;
+ name?: string;
+ /** 1..8 layers, bottom first. */
+ layers: ProceduralLayer[];
+}
+
+const OPS = ['solid', 'checker', 'stripes', 'gradient', 'bricks', 'noise'] as const;
+const BLENDS: readonly ProceduralBlend[] = ['normal', 'multiply', 'screen', 'overlay'];
+
+export class ProceduralTextureError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'ProceduralTextureError';
+ }
+}
+
+// -----------------------------------------------------------------------------
+// Deterministic value noise
+// -----------------------------------------------------------------------------
+
+/**
+ * Integer hash of a lattice coordinate. Not a cryptographic hash — it only has
+ * to decorrelate neighbouring integers and return the same value forever.
+ */
+function hash2(x: number, y: number, seed: number): number {
+ let h = (Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177)) | 0;
+ h = h ^ (h >>> 13);
+ h = Math.imul(h, 1274126177) | 0;
+ h = h ^ (h >>> 16);
+ return (h >>> 0) / 4294967296;
+}
+
+const smoothstep = (t: number): number => t * t * (3 - 2 * t);
+
+/**
+ * Value noise on a lattice that wraps at `period`, so the result tiles.
+ * `period` is in lattice cells, and both axes use the same one.
+ */
+function valueNoise(u: number, v: number, period: number, seed: number): number {
+ const x = u * period;
+ const y = v * period;
+ const xi = Math.floor(x);
+ const yi = Math.floor(y);
+ const xf = x - xi;
+ const yf = y - yi;
+ // Wrapping the lattice index (not the sample point) is what makes it tile:
+ // the cell to the right of the last one is the first one again.
+ const wrap = (n: number): number => ((n % period) + period) % period;
+ const x0 = wrap(xi);
+ const y0 = wrap(yi);
+ const x1 = wrap(xi + 1);
+ const y1 = wrap(yi + 1);
+ const sx = smoothstep(xf);
+ const sy = smoothstep(yf);
+ const n00 = hash2(x0, y0, seed);
+ const n10 = hash2(x1, y0, seed);
+ const n01 = hash2(x0, y1, seed);
+ const n11 = hash2(x1, y1, seed);
+ const top = n00 + sx * (n10 - n00);
+ const bottom = n01 + sx * (n11 - n01);
+ return top + sy * (bottom - top);
+}
+
+function fbm(u: number, v: number, period: number, octaves: number, seed: number): number {
+ let sum = 0;
+ let amplitude = 1;
+ let total = 0;
+ let p = period;
+ for (let o = 0; o < octaves; o++) {
+ sum += valueNoise(u, v, p, seed + o * 101) * amplitude;
+ total += amplitude;
+ amplitude *= 0.5;
+ // Doubling the period keeps every octave tileable at the base period.
+ p *= 2;
+ }
+ return total > 0 ? sum / total : 0;
+}
+
+// -----------------------------------------------------------------------------
+// Validation
+// -----------------------------------------------------------------------------
+
+function isPowerOfTwo(n: number): boolean {
+ return Number.isInteger(n) && n > 0 && (n & (n - 1)) === 0;
+}
+
+function checkColor(value: unknown, label: string): number {
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 0xffffff) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: ${label} must be a color integer between 0x000000 and 0xffffff, got ${JSON.stringify(value)}.`,
+ );
+ }
+ return value;
+}
+
+function checkCount(value: unknown, label: string, fallback: number, max = 256): number {
+ if (value === undefined) return fallback;
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > max) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: ${label} must be a whole number between 1 and ${max}, got ${JSON.stringify(value)}.`,
+ );
+ }
+ return value;
+}
+
+function checkUnit(value: unknown, label: string, fallback: number): number {
+ if (value === undefined) return fallback;
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: ${label} must be between 0 and 1, got ${JSON.stringify(value)}.`,
+ );
+ }
+ return value;
+}
+
+function validateSpec(spec: ProceduralTextureSpec): {
+ size: number;
+ usage: TextureUsage;
+ layers: ProceduralLayer[];
+} {
+ if (!spec || typeof spec !== 'object') {
+ throw new ProceduralTextureError('proceduralTexture: a spec object is required.');
+ }
+
+ const size = spec.size ?? 256;
+ if (!isPowerOfTwo(size) || size < MIN_PROCEDURAL_SIZE || size > MAX_PROCEDURAL_SIZE) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: size must be a power of two between ${MIN_PROCEDURAL_SIZE} and ${MAX_PROCEDURAL_SIZE}, got ${JSON.stringify(spec.size)}.`,
+ );
+ }
+
+ const layers = spec.layers;
+ if (!Array.isArray(layers) || layers.length === 0) {
+ throw new ProceduralTextureError(
+ 'proceduralTexture: layers must be a non-empty array — the bottom layer is the base pattern.',
+ );
+ }
+ if (layers.length > MAX_PROCEDURAL_LAYERS) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: ${layers.length} layers exceeds the maximum of ${MAX_PROCEDURAL_LAYERS}.`,
+ );
+ }
+
+ for (const [i, layer] of layers.entries()) {
+ if (!layer || typeof layer !== 'object') {
+ throw new ProceduralTextureError(`proceduralTexture: layers[${i}] must be an object.`);
+ }
+ if (!(OPS as readonly string[]).includes(layer.op)) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: layers[${i}].op ${JSON.stringify(layer.op)} is not one of ${OPS.join(', ')}.`,
+ );
+ }
+ if (layer.blend !== undefined && !BLENDS.includes(layer.blend)) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: layers[${i}].blend ${JSON.stringify(layer.blend)} is not one of ${BLENDS.join(', ')}.`,
+ );
+ }
+ checkUnit(layer.opacity, `layers[${i}].opacity`, 1);
+ if (layer.op === 'noise') {
+ const octaves = layer.octaves ?? 3;
+ if (!Number.isInteger(octaves) || octaves < 1 || octaves > MAX_NOISE_OCTAVES) {
+ throw new ProceduralTextureError(
+ `proceduralTexture: layers[${i}].octaves must be a whole number between 1 and ${MAX_NOISE_OCTAVES}, got ${JSON.stringify(layer.octaves)}.`,
+ );
+ }
+ }
+ }
+
+ return { size, usage: spec.usage ?? 'albedo', layers };
+}
+
+// -----------------------------------------------------------------------------
+// Layer evaluation
+// -----------------------------------------------------------------------------
+
+const rgbOf = (color: number): [number, number, number] => [
+ (color >> 16) & 0xff,
+ (color >> 8) & 0xff,
+ color & 0xff,
+];
+
+const lerp = (a: number, b: number, t: number): number => a + (b - a) * t;
+
+/** Rotate normalized coords about the center so angled patterns stay centered. */
+function project(u: number, v: number, angleDeg: number): number {
+ const a = (angleDeg * Math.PI) / 180;
+ return (u - 0.5) * Math.cos(a) + (v - 0.5) * Math.sin(a) + 0.5;
+}
+
+/** Evaluate one layer at a normalized coordinate, returning 0-255 RGB. */
+function evalLayer(layer: ProceduralLayer, u: number, v: number): [number, number, number] {
+ switch (layer.op) {
+ case 'solid':
+ return rgbOf(checkColor(layer.color, 'solid.color'));
+
+ case 'checker': {
+ const squares = checkCount(layer.squares, 'checker.squares', 8);
+ const cx = Math.floor(u * squares);
+ const cy = Math.floor(v * squares);
+ return rgbOf(
+ (cx + cy) % 2 === 0
+ ? checkColor(layer.colorA, 'checker.colorA')
+ : checkColor(layer.colorB, 'checker.colorB'),
+ );
+ }
+
+ case 'stripes': {
+ const count = checkCount(layer.count, 'stripes.count', 8);
+ const t = project(u, v, layer.angleDeg ?? 0);
+ return rgbOf(
+ Math.floor(t * count) % 2 === 0
+ ? checkColor(layer.colorA, 'stripes.colorA')
+ : checkColor(layer.colorB, 'stripes.colorB'),
+ );
+ }
+
+ case 'gradient': {
+ const t = Math.min(1, Math.max(0, project(u, v, layer.angleDeg ?? 0)));
+ const from = rgbOf(checkColor(layer.from, 'gradient.from'));
+ const to = rgbOf(checkColor(layer.to, 'gradient.to'));
+ return [lerp(from[0], to[0], t), lerp(from[1], to[1], t), lerp(from[2], to[2], t)];
+ }
+
+ case 'bricks': {
+ const rows = checkCount(layer.rows, 'bricks.rows', 8);
+ const cols = checkCount(layer.cols, 'bricks.cols', 4);
+ const mortarWidth = checkUnit(layer.mortarWidth, 'bricks.mortarWidth', 0.06);
+ const stagger = checkUnit(layer.stagger, 'bricks.stagger', 0.5);
+ const row = Math.floor(v * rows);
+ // Offset alternate rows, wrapping into [0,1) so the pattern still tiles.
+ const shifted = (u + (row % 2 === 0 ? 0 : stagger / cols) + 1) % 1;
+ const inCol = (shifted * cols) % 1;
+ const inRow = (v * rows) % 1;
+ const isMortar =
+ inCol < mortarWidth ||
+ inCol > 1 - mortarWidth ||
+ inRow < mortarWidth ||
+ inRow > 1 - mortarWidth;
+ return rgbOf(
+ isMortar
+ ? checkColor(layer.mortar, 'bricks.mortar')
+ : checkColor(layer.brick, 'bricks.brick'),
+ );
+ }
+
+ case 'noise': {
+ const scale = checkCount(layer.scale, 'noise.scale', 8);
+ const octaves = layer.octaves ?? 3;
+ const seed = Number.isInteger(layer.seed) ? (layer.seed as number) : 0;
+ const n = fbm(u, v, scale, octaves, seed);
+ const a = rgbOf(checkColor(layer.colorA, 'noise.colorA'));
+ const b = rgbOf(checkColor(layer.colorB, 'noise.colorB'));
+ return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];
+ }
+ }
+}
+
+function blendChannel(mode: ProceduralBlend, base: number, top: number): number {
+ const b = base / 255;
+ const t = top / 255;
+ let out: number;
+ switch (mode) {
+ case 'multiply':
+ out = b * t;
+ break;
+ case 'screen':
+ out = 1 - (1 - b) * (1 - t);
+ break;
+ case 'overlay':
+ out = b < 0.5 ? 2 * b * t : 1 - 2 * (1 - b) * (1 - t);
+ break;
+ default:
+ out = t;
+ }
+ return out * 255;
+}
+
+// -----------------------------------------------------------------------------
+// Public API
+// -----------------------------------------------------------------------------
+
+/**
+ * Build a tiling texture from a bounded, deterministic layer stack.
+ *
+ * The result is a plain RGBA `DataTexture`; `renderSceneToGLB` bakes it to PNG
+ * and embeds it, so nothing else has to be done to ship it.
+ *
+ * @example
+ * const bark = proceduralTexture({
+ * size: 256,
+ * usage: 'albedo',
+ * name: 'Bark',
+ * layers: [
+ * { op: 'solid', color: 0x5a4632 },
+ * { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' },
+ * { op: 'stripes', colorA: 0x000000, colorB: 0xffffff, count: 24, angleDeg: 90,
+ * blend: 'multiply', opacity: 0.15 },
+ * ],
+ * });
+ * const trunk = createPart('Trunk', cylinderGeo(0.3, 0.3, 3), pbrMaterial({ albedo: bark }), { parent: root });
+ */
+export function proceduralTexture(spec: ProceduralTextureSpec): THREE.DataTexture {
+ const { size, usage, layers } = validateSpec(spec);
+
+ const data = new Uint8Array(size * size * 4);
+ for (let y = 0; y < size; y++) {
+ // Sample at texel centers so a pattern with N divisions lands on exact
+ // boundaries instead of drifting half a texel.
+ const v = (y + 0.5) / size;
+ for (let x = 0; x < size; x++) {
+ const u = (x + 0.5) / size;
+ let r = 0;
+ let g = 0;
+ let b = 0;
+ for (const [i, layer] of layers.entries()) {
+ const [lr, lg, lb] = evalLayer(layer, u, v);
+ if (i === 0) {
+ r = lr;
+ g = lg;
+ b = lb;
+ continue;
+ }
+ const mode = layer.blend ?? 'normal';
+ const opacity = layer.opacity ?? 1;
+ r = lerp(r, blendChannel(mode, r, lr), opacity);
+ g = lerp(g, blendChannel(mode, g, lg), opacity);
+ b = lerp(b, blendChannel(mode, b, lb), opacity);
+ }
+ const o = (y * size + x) * 4;
+ data[o] = Math.max(0, Math.min(255, Math.round(r)));
+ data[o + 1] = Math.max(0, Math.min(255, Math.round(g)));
+ data[o + 2] = Math.max(0, Math.min(255, Math.round(b)));
+ data[o + 3] = 255;
+ }
+ }
+
+ const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat, THREE.UnsignedByteType);
+ if (spec.name) tex.name = spec.name;
+ tex.colorSpace =
+ usage === 'albedo' || usage === 'emissive' ? THREE.SRGBColorSpace : THREE.NoColorSpace;
+ tex.wrapS = THREE.RepeatWrapping;
+ tex.wrapT = THREE.RepeatWrapping;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.generateMipmaps = true;
+ tex.needsUpdate = true;
+
+ // Recorded so the manifest says what was generated, not merely that something
+ // was. The spec is small, serializable, and enough to reproduce the bytes.
+ (tex.userData as Record<string, unknown>)['kilnProcedural'] = {
+ schemaVersion: 1,
+ size,
+ usage,
+ layers,
+ };
+
+ return tex;
+}
+
+/**
+ * Derive a tangent-space normal map from the luminance of another texture.
+ *
+ * This is the cheap way to get PBR surface detail out of a procedural albedo:
+ * treat brightness as height and take its gradient. Sampling wraps, so a
+ * tiling source yields a tiling normal map.
+ *
+ * The output is linear data, never sRGB — a normal map holds vectors, not
+ * color, and tagging it sRGB is the single most common way to get PBR lighting
+ * subtly wrong.
+ *
+ * @param source Any texture with readable 8-bit RGB/RGBA pixels.
+ * @param opts.strength Height scale. 1 is subtle; 4-8 reads clearly. Default 2.
+ */
+export function normalMapFromHeight(
+ source: THREE.Texture,
+ opts: { strength?: number; name?: string } = {},
+): THREE.DataTexture {
+ const image = source.image as
+ | { data?: ArrayLike<number>; width?: number; height?: number }
+ | undefined;
+ const data = image?.data;
+ const width = image?.width ?? 0;
+ const height = image?.height ?? 0;
+ if (!data || !width || !height) {
+ throw new ProceduralTextureError(
+ 'normalMapFromHeight: the source texture has no readable pixels. Pass a proceduralTexture() result or a loadTexture() result, not a texture built from an image element.',
+ );
+ }
+ const channels = data.length / (width * height);
+ if (channels !== 3 && channels !== 4) {
+ throw new ProceduralTextureError(
+ `normalMapFromHeight: the source has ${data.length} bytes for ${width}x${height}, which is neither RGB nor RGBA.`,
+ );
+ }
+
+ const strength = opts.strength ?? 2;
+ if (!Number.isFinite(strength) || strength <= 0) {
+ throw new ProceduralTextureError(
+ `normalMapFromHeight: strength must be a positive number, got ${JSON.stringify(opts.strength)}.`,
+ );
+ }
+
+ const lum = (x: number, y: number): number => {
+ const xw = ((x % width) + width) % width;
+ const yw = ((y % height) + height) % height;
+ const o = (yw * width + xw) * channels;
+ // Rec. 601 luma — matches how the eye reads the albedo this is derived from.
+ return (0.299 * (data[o] ?? 0) + 0.587 * (data[o + 1] ?? 0) + 0.114 * (data[o + 2] ?? 0)) / 255;
+ };
+
+ const out = new Uint8Array(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ // Central differences; the wrap in `lum` is what keeps the edges seamless.
+ const dx = (lum(x + 1, y) - lum(x - 1, y)) * strength;
+ const dy = (lum(x, y + 1) - lum(x, y - 1)) * strength;
+ // Gradient of a height field gives the surface normal as (-dx, -dy, 1).
+ let nx = -dx;
+ let ny = -dy;
+ const nz = 1;
+ const len = Math.hypot(nx, ny, nz) || 1;
+ nx /= len;
+ ny /= len;
+ const o = (y * width + x) * 4;
+ out[o] = Math.round((nx * 0.5 + 0.5) * 255);
+ out[o + 1] = Math.round((ny * 0.5 + 0.5) * 255);
+ out[o + 2] = Math.round((nz / len) * 0.5 * 255 + 127.5);
+ out[o + 3] = 255;
+ }
+ }
+
+ const tex = new THREE.DataTexture(out, width, height, THREE.RGBAFormat, THREE.UnsignedByteType);
+ tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : '');
+ tex.colorSpace = THREE.NoColorSpace;
+ tex.wrapS = THREE.RepeatWrapping;
+ tex.wrapT = THREE.RepeatWrapping;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.generateMipmaps = true;
+ tex.needsUpdate = true;
+ return tex;
+}
diff --git a/src/prompt-api.ts b/src/prompt-api.ts
index 616b3c05..90d2d415 100644
--- a/src/prompt-api.ts
+++ b/src/prompt-api.ts
@@ -31,6 +31,27 @@ const CATEGORY_HEADERS: Array<[PrimitiveSpec['category'], string]> = [
['utility', '// Inspection utilities'],
];
+/**
+ * A rule that holds for EVERY primitive in a category, rendered once under the
+ * category header.
+ *
+ * Why not `promptNotes` on each entry: the whole catalog goes into every system
+ * prompt, so an identical paragraph on all four CSG ops costs four times the
+ * tokens for no extra signal — and the four entries render consecutively under
+ * the header anyway, so one statement sits directly above all of them.
+ * Per-entry `promptNotes` stays the right home for anything that distinguishes
+ * one primitive from its neighbours.
+ */
+const CATEGORY_NOTES: Partial<Record<PrimitiveSpec['category'], string>> = {
+ csg:
+ 'UVs do NOT survive a boolean: the manifold bridge carries positions only, so the result has ' +
+ 'no uv attribute and any texture on it will not appear. Unwrap AFTER the boolean, never before — ' +
+ '`mesh.geometry = await autoUnwrap(mesh.geometry)`. Unwrapping an operand first is wasted work; ' +
+ 'the next boolean throws the atlas away. An operand that contributes zero triangles (an empty ' +
+ 'Group) and an empty result both throw with the cause named, instead of silently producing an ' +
+ 'invisible part.',
+};
+
const WRAP = 96;
/** Wrap text into `// `-prefixed comment lines at ~WRAP columns. */
@@ -103,6 +124,8 @@ export function renderApiSection(
const list = byCategory.get(category);
if (!list || list.length === 0) continue;
const lines = [header];
+ const note = CATEGORY_NOTES[category];
+ if (note) lines.push(...wrapComment(`NOTE: ${note}`, ''));
for (const p of list) lines.push(...renderPrimitiveLines(p, includeExamples));
blocks.push(lines.join('\n'));
}
@@ -168,6 +191,8 @@ export function renderPrimitivesMarkdown(primitives: PrimitiveSpec[]): string {
const list = byCategory.get(category);
if (!list || list.length === 0) continue;
parts.push('', `## ${titles[category] ?? category}`);
+ const categoryNote = CATEGORY_NOTES[category as PrimitiveSpec['category']];
+ if (categoryNote) parts.push('', `**Applies to every ${category} helper:** ${categoryNote}`);
for (const p of list) {
parts.push('', `### ${p.name}`, '', '```typescript', p.signature, '```', '');
parts.push(`Returns: ${p.returns}`, '', p.description);
@@ -202,6 +227,8 @@ export function renderSkillQuickReference(primitives: PrimitiveSpec[]): string {
const list = byCategory.get(category);
if (!list || list.length === 0) continue;
lines.push(header);
+ const categoryNote = CATEGORY_NOTES[category];
+ if (categoryNote) lines.push(...wrapComment(`NOTE: ${categoryNote}`, ''));
for (const p of list) {
lines.push(p.signature);
if (p.promptNotes) lines.push(...wrapComment(`NOTE: ${p.promptNotes}`, ' '));
diff --git a/src/qa/material.ts b/src/qa/material.ts
index 2e08b839..2d87cba9 100644
--- a/src/qa/material.ts
+++ b/src/qa/material.ts
@@ -107,7 +107,8 @@ function validateTextureSlot(
profile: 'material.portablePbr',
message: `${slot} texture has no verified decoded/exportable image payload.`,
affected: affected(mesh, material, texture, slot),
- repairText: 'Load a decodable PNG, JPEG, or WebP with loadTexture() before assigning it.',
+ repairText:
+ 'Load a decodable PNG, JPEG, or WebP with loadTexture() before assigning it. A texture built in code is baked to PNG automatically, so reaching this means its pixels were unreadable — it must be a DataTexture holding 8-bit RGB or RGBA bytes, not float data or an image element.',
});
}
if (actual !== expected) {
@@ -119,7 +120,7 @@ function validateTextureSlot(
message: `${slot} texture must use ${expected} data interpretation, not ${actual}.`,
affected: affected(mesh, material, texture, slot),
measurement: { name: 'colorSpace', actual, expected },
- repairText: `Reload the texture with loadTexture(..., { usage: '${slot === 'map' ? 'albedo' : slot}' }).`,
+ repairText: `Reload the texture with loadTexture(..., { usage: '${slot === 'map' ? 'albedo' : slot}' }), or for a texture built in code set texture.colorSpace = ${expected === 'srgb' ? 'THREE.SRGBColorSpace' : 'THREE.NoColorSpace'} — it is never set for you, because reinterpreting an author's pixels silently is exactly the failure this check exists to catch.`,
});
}
diff --git a/src/qa/part-connectivity.test.ts b/src/qa/part-connectivity.test.ts
new file mode 100644
index 00000000..35f4afd5
--- /dev/null
+++ b/src/qa/part-connectivity.test.ts
@@ -0,0 +1,205 @@
+/**
+ * T4.2 — part connectivity.
+ *
+ * The case that justifies this rule existing alongside the pairwise
+ * floating-parts warning is the detached CLUSTER: parts that touch each other
+ * but nothing else. Every one has a neighbour, so the pairwise check passes and
+ * the group is still floating.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import { createAssetIntentV1 } from '../contracts';
+import { analyzePartConnectivity, PART_CONNECTIVITY_QA_RULE } from './part-connectivity';
+import type { QaContext } from './types';
+
+function boxAt(name: string, size: [number, number, number], at: [number, number, number]) {
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size));
+ mesh.name = name;
+ mesh.position.set(...at);
+ return mesh;
+}
+
+function sceneOf(...meshes: THREE.Object3D[]): THREE.Object3D {
+ const root = new THREE.Object3D();
+ root.name = 'Asset';
+ for (const m of meshes) root.add(m);
+ return root;
+}
+
+const context = (scene: THREE.Object3D): QaContext => ({
+ intent: createAssetIntentV1({ category: 'prop' }),
+ scene,
+});
+
+// -----------------------------------------------------------------------------
+// The case the pairwise check misses
+// -----------------------------------------------------------------------------
+
+describe('detached clusters', () => {
+ test('a group that touches itself but not the body is reported as one group', () => {
+ // Body of three touching parts, plus a pair of touching parts far away. The
+ // existing pairwise warning sees a neighbour for all five and says nothing.
+ const report = analyzePartConnectivity(
+ sceneOf(
+ boxAt('Body', [1, 1, 1], [0, 0, 0]),
+ boxAt('Lid', [1, 0.2, 1], [0, 0.6, 0]),
+ boxAt('Knob', [0.2, 0.2, 0.2], [0, 0.8, 0]),
+ boxAt('HandleA', [0.2, 0.2, 0.2], [5, 0, 0]),
+ boxAt('HandleB', [0.2, 0.2, 0.2], [5.2, 0, 0]),
+ ),
+ );
+
+ expect(report.mainComponentSize).toBe(3);
+ expect(report.groups).toHaveLength(1);
+ expect(report.groups[0]!.parts).toEqual(['HandleA', 'HandleB']);
+ // Gap from the cluster to the body (body ends at x=0.5, HandleA starts at
+ // x=4.9), not the zero gap between the cluster's own parts.
+ expect(report.groups[0]!.gap).toBeCloseTo(4.4, 3);
+ });
+
+ test('the finding says one join is missing, not that several parts are misplaced', () => {
+ const findings = PART_CONNECTIVITY_QA_RULE.evaluate(
+ context(
+ sceneOf(
+ boxAt('Body', [1, 1, 1], [0, 0, 0]),
+ boxAt('Lid', [1, 0.2, 1], [0, 0.6, 0]),
+ boxAt('Knob', [0.2, 0.2, 0.2], [0, 0.8, 0]),
+ boxAt('HandleA', [0.2, 0.2, 0.2], [5, 0, 0]),
+ boxAt('HandleB', [0.2, 0.2, 0.2], [5.2, 0, 0]),
+ ),
+ ),
+ );
+
+ expect(findings).toHaveLength(1);
+ expect(findings[0]!.message).toContain('group of 2 parts');
+ expect(findings[0]!.message).toContain('one join is missing');
+ expect(findings[0]!.repairText).toContain('snapTo');
+ });
+
+ test('the largest detached group is reported first', () => {
+ // The body has to out-mass the cluster, or the cluster IS the main body and
+ // the body is what gets reported. Three stacked parts against a pair.
+ const report = analyzePartConnectivity(
+ sceneOf(
+ boxAt('BodyA', [2, 2, 2], [0, 0, 0]),
+ boxAt('BodyB', [2, 2, 2], [0, 2, 0]),
+ boxAt('BodyC', [2, 2, 2], [0, 4, 0]),
+ boxAt('Lone', [0.2, 0.2, 0.2], [8, 0, 0]),
+ boxAt('PairA', [0.2, 0.2, 0.2], [5, 0, 0]),
+ boxAt('PairB', [0.2, 0.2, 0.2], [5.2, 0, 0]),
+ ),
+ );
+
+ expect(report.mainComponentSize).toBe(3);
+ expect(report.groups.map((g) => g.parts.length)).toEqual([2, 1]);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// True negatives
+// -----------------------------------------------------------------------------
+
+describe('legitimately connected assemblies are not flagged', () => {
+ test('a chain of parts each touching the next is one component', () => {
+ // Wheels on an axle: the wheels never touch each other, only the axle.
+ const report = analyzePartConnectivity(
+ sceneOf(
+ boxAt('Axle', [4, 0.2, 0.2], [0, 0, 0]),
+ boxAt('WheelL', [0.4, 1, 1], [-2, 0, 0]),
+ boxAt('WheelR', [0.4, 1, 1], [2, 0, 0]),
+ ),
+ );
+
+ expect(report.groups).toEqual([]);
+ expect(report.mainComponentSize).toBe(3);
+ });
+
+ test('a hinged lid resting on its box stays attached', () => {
+ const report = analyzePartConnectivity(
+ sceneOf(boxAt('Chest', [1, 1, 1], [0, 0, 0]), boxAt('Lid', [1, 0.1, 1], [0, 0.55, 0])),
+ );
+ expect(report.groups).toEqual([]);
+ });
+
+ test('parts within the tolerance count as touching', () => {
+ // 1 cm apart, inside the 2 cm tolerance the existing floating-parts warning
+ // already uses — the two must never disagree about contact.
+ const report = analyzePartConnectivity(
+ sceneOf(boxAt('A', [1, 1, 1], [0, 0, 0]), boxAt('B', [1, 1, 1], [1.01, 0, 0])),
+ );
+ expect(report.groups).toEqual([]);
+ });
+
+ test('a single part cannot be disconnected from anything', () => {
+ const report = analyzePartConnectivity(sceneOf(boxAt('Only', [1, 1, 1], [0, 0, 0])));
+ expect(report.groups).toEqual([]);
+ expect(report.partsAnalyzed).toBe(1);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Exemptions are by declared role, not inferred shape
+// -----------------------------------------------------------------------------
+
+describe('exemptions', () => {
+ test('foliage, cards, and decals are expected to stand apart', () => {
+ const report = analyzePartConnectivity(
+ sceneOf(
+ boxAt('Trunk', [0.5, 3, 0.5], [0, 0, 0]),
+ boxAt('Mesh_FoliageA', [2, 2, 2], [0, 6, 0]),
+ boxAt('Mesh_Decal_Sign', [0.5, 0.5, 0.05], [0, 8, 0]),
+ ),
+ );
+
+ expect(report.exempt).toEqual(['Mesh_FoliageA', 'Mesh_Decal_Sign']);
+ expect(report.groups).toEqual([]);
+ });
+
+ test('a name that is not a declared exempt role is still checked', () => {
+ // "Ornament" looks decorative but declares nothing, so it is not exempt —
+ // guessing from appearance would fail exactly on unusual assets.
+ const report = analyzePartConnectivity(
+ sceneOf(boxAt('Body', [1, 1, 1], [0, 0, 0]), boxAt('Ornament', [0.2, 0.2, 0.2], [5, 0, 0])),
+ );
+ expect(report.groups.map((g) => g.parts)).toEqual([['Ornament']]);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Rule wiring
+// -----------------------------------------------------------------------------
+
+describe('the QA rule', () => {
+ test('starts in observe with no promotion evidence', () => {
+ expect(PART_CONNECTIVITY_QA_RULE.defaultMode).toBe('observe');
+ expect(PART_CONNECTIVITY_QA_RULE.promotion).toBeUndefined();
+ expect(PART_CONNECTIVITY_QA_RULE.ruleClass).toBe('heuristic');
+ });
+
+ test('a missing scene yields no findings rather than a false clean result', () => {
+ expect(
+ PART_CONNECTIVITY_QA_RULE.evaluate({ intent: createAssetIntentV1({ category: 'prop' }) }),
+ ).toEqual([]);
+ });
+
+ test('a connected asset produces no findings', () => {
+ expect(
+ PART_CONNECTIVITY_QA_RULE.evaluate(
+ context(sceneOf(boxAt('A', [1, 1, 1], [0, 0, 0]), boxAt('B', [1, 1, 1], [1, 0, 0]))),
+ ),
+ ).toEqual([]);
+ });
+
+ test('the same scene always produces the same report', () => {
+ const build = () =>
+ sceneOf(
+ boxAt('Body', [1, 1, 1], [0, 0, 0]),
+ boxAt('FarA', [0.2, 0.2, 0.2], [5, 0, 0]),
+ boxAt('FarB', [0.2, 0.2, 0.2], [5.2, 0, 0]),
+ );
+ expect(JSON.stringify(analyzePartConnectivity(build()))).toBe(
+ JSON.stringify(analyzePartConnectivity(build())),
+ );
+ });
+});
diff --git a/src/qa/part-connectivity.ts b/src/qa/part-connectivity.ts
new file mode 100644
index 00000000..6d7895ee
--- /dev/null
+++ b/src/qa/part-connectivity.ts
@@ -0,0 +1,233 @@
+/**
+ * Part-connectivity gate — T4.2
+ *
+ * ## What this adds over the existing floating-parts warning
+ *
+ * `inspectSceneStructure` (`render.ts`) already reports a part with no
+ * neighbour: for each mesh, does any sibling's box come within 2 cm? That is
+ * **pairwise adjacency**, and it misses the case the plan actually names —
+ * a *disconnected component*. Three parts that touch each other but float as a
+ * cluster away from the body each have a neighbour, so every one passes the
+ * pairwise test while the group as a whole is detached.
+ *
+ * This rule builds the adjacency graph and finds its connected components.
+ * Anything not in the largest component is reported, with the parts it is
+ * attached to, so the finding says "this subassembly is floating" rather than
+ * "this part is alone" — which is both stronger and more useful, since a
+ * detached cluster is usually one missing join rather than N misplaced parts.
+ *
+ * ## Exemptions
+ *
+ * Some parts are legitimately separate and always will be:
+ *
+ * - **Foliage cards and decals** are meant to sit off the surface.
+ * - **Wheels** contact an axle whose geometry may be inside the hub, and a
+ * detached-looking wheel is the vehicle rules' business, not this one.
+ * - **Joint pivots** carry no geometry and never participate.
+ *
+ * Exemption is by declared role — the `Joint_`/`Mesh_` naming and the
+ * category the intent already carries — not by guessing from shape. A rule that
+ * inferred "this looks like foliage" would fail exactly when an asset is
+ * unusual, which is when a QA gate matters most.
+ *
+ * ## Cost
+ *
+ * Pure AABB work: O(n²) box comparisons to build the graph, then a linear
+ * flood fill. No booleans, no WASM, so unlike T4.1 this runs inside the
+ * synchronous rule with no pre-pass.
+ */
+
+import * as THREE from 'three';
+import { KILN_ENGINE_QA_OWNER, type QaRule } from './registry';
+import type { QaContext, QaFinding } from './types';
+
+/**
+ * Adjacency tolerance, matching the existing floating-parts warning so the two
+ * never disagree about whether two parts touch.
+ */
+export const CONNECTIVITY_TOLERANCE = 0.02;
+
+/**
+ * Names that are expected to stand apart from the body.
+ *
+ * Matched against the mesh name, which Kiln's own helpers control (`createPart`
+ * prefixes `Mesh_`, `createPivot` prefixes `Joint_`), so this keys off declared
+ * structure rather than inferred shape.
+ */
+const EXEMPT_NAME = /(?:^|_)(?:leaf|leaves|foliage|frond|card|decal|billboard|petal)/i;
+
+interface ConnectivityPart {
+ name: string;
+ box: THREE.Box3;
+}
+
+export interface DisconnectedGroupV1 {
+ /** Parts in this component, in traversal order. */
+ parts: string[];
+ /** Shortest distance from this component to the main one, in meters. */
+ gap: number;
+}
+
+export interface PartConnectivityReportV1 {
+ partsAnalyzed: number;
+ /** Size of the largest component — the body everything should hang off. */
+ mainComponentSize: number;
+ exempt: string[];
+ groups: DisconnectedGroupV1[];
+}
+
+function collectParts(root: THREE.Object3D, exempt: string[]): ConnectivityPart[] {
+ const parts: ConnectivityPart[] = [];
+ root.updateWorldMatrix(true, true);
+ root.traverse((node) => {
+ const mesh = node as THREE.Mesh;
+ if (!mesh.isMesh || !mesh.geometry) return;
+ const name = mesh.name || '(unnamed mesh)';
+ if (EXEMPT_NAME.test(name)) {
+ exempt.push(name);
+ return;
+ }
+ const box = new THREE.Box3().setFromObject(mesh);
+ if (box.isEmpty()) return;
+ parts.push({ name, box });
+ });
+ return parts;
+}
+
+/** Shortest distance between two boxes; 0 when they touch or overlap. */
+function boxGap(a: THREE.Box3, b: THREE.Box3): number {
+ const dx = Math.max(0, Math.max(a.min.x - b.max.x, b.min.x - a.max.x));
+ const dy = Math.max(0, Math.max(a.min.y - b.max.y, b.min.y - a.max.y));
+ const dz = Math.max(0, Math.max(a.min.z - b.max.z, b.min.z - a.max.z));
+ return Math.hypot(dx, dy, dz);
+}
+
+/**
+ * Group parts into connected components by box adjacency.
+ *
+ * Exported for testing and for anything that wants the structure rather than
+ * the finding.
+ */
+export function analyzePartConnectivity(root: THREE.Object3D): PartConnectivityReportV1 {
+ const exempt: string[] = [];
+ const parts = collectParts(root, exempt);
+ const report: PartConnectivityReportV1 = {
+ partsAnalyzed: parts.length,
+ mainComponentSize: parts.length,
+ exempt,
+ groups: [],
+ };
+ if (parts.length < 2) return report;
+
+ const adjacency: number[][] = parts.map(() => []);
+ for (let i = 0; i < parts.length; i++) {
+ for (let j = i + 1; j < parts.length; j++) {
+ if (boxGap(parts[i]!.box, parts[j]!.box) <= CONNECTIVITY_TOLERANCE) {
+ adjacency[i]!.push(j);
+ adjacency[j]!.push(i);
+ }
+ }
+ }
+
+ const component = new Int32Array(parts.length).fill(-1);
+ const components: number[][] = [];
+ for (let seed = 0; seed < parts.length; seed++) {
+ if (component[seed] !== -1) continue;
+ const id = components.length;
+ const members: number[] = [];
+ const stack = [seed];
+ component[seed] = id;
+ while (stack.length > 0) {
+ const current = stack.pop()!;
+ members.push(current);
+ for (const next of adjacency[current]!) {
+ if (component[next] === -1) {
+ component[next] = id;
+ stack.push(next);
+ }
+ }
+ }
+ members.sort((x, y) => x - y);
+ components.push(members);
+ }
+
+ if (components.length < 2) return report;
+
+ // The main body is the largest component; ties break on the earliest part in
+ // traversal order, so the choice is deterministic rather than incidental.
+ let mainIndex = 0;
+ for (let i = 1; i < components.length; i++) {
+ const bigger = components[i]!.length > components[mainIndex]!.length;
+ const tie =
+ components[i]!.length === components[mainIndex]!.length &&
+ components[i]![0]! < components[mainIndex]![0]!;
+ if (bigger || tie) mainIndex = i;
+ }
+ const main = components[mainIndex]!;
+ report.mainComponentSize = main.length;
+
+ for (const [index, members] of components.entries()) {
+ if (index === mainIndex) continue;
+ let gap = Number.POSITIVE_INFINITY;
+ for (const m of members) {
+ for (const b of main) {
+ gap = Math.min(gap, boxGap(parts[m]!.box, parts[b]!.box));
+ }
+ }
+ report.groups.push({
+ parts: members.map((m) => parts[m]!.name),
+ gap: Math.round(gap * 1e6) / 1e6,
+ });
+ }
+
+ // Largest detached group first — the biggest missing join is the one to fix.
+ report.groups.sort((a, b) => b.parts.length - a.parts.length || a.gap - b.gap);
+ return report;
+}
+
+/**
+ * Report subassemblies that are not attached to the body.
+ *
+ * `observe` with no promotion evidence, per the plan and the registry's rule:
+ * `exact` is reserved for rules already enforcing on frozen conformance
+ * evidence, so a new gate is `heuristic` however precise its arithmetic.
+ */
+export const PART_CONNECTIVITY_QA_RULE: QaRule = Object.freeze({
+ id: 'GEO_PART_CONNECTIVITY',
+ profile: 'geometry.partConnectivity',
+ scope: { kind: 'universal' as const },
+ ruleClass: 'heuristic',
+ owner: KILN_ENGINE_QA_OWNER,
+ defaultMode: 'observe',
+ evaluate(context: QaContext): readonly QaFinding[] {
+ if (!(context.scene instanceof THREE.Object3D)) return [];
+ const report = analyzePartConnectivity(context.scene);
+ if (report.groups.length === 0) return [];
+
+ return report.groups.map((group) => {
+ const listed = group.parts.map((p) => JSON.stringify(p)).join(', ');
+ const subject =
+ group.parts.length === 1
+ ? `Part ${listed} is`
+ : `A group of ${group.parts.length} parts (${listed}) is`;
+ return {
+ code: 'GEO_PART_CONNECTIVITY',
+ disposition: 'observe' as const,
+ dimension: 'visualQuality' as const,
+ profile: 'geometry.partConnectivity',
+ message: `${subject} not attached to the main body — the nearest gap is ${group.gap.toFixed(3)} m. ${
+ group.parts.length === 1
+ ? 'It floats on its own.'
+ : 'These parts touch each other but nothing else, so one join is missing rather than several parts being misplaced.'
+ }`,
+ affected: { node: group.parts[0]! },
+ measurement: {
+ name: 'gapToMainComponent',
+ actual: group.gap,
+ expected: CONNECTIVITY_TOLERANCE,
+ },
+ repairText: `Attach it with snapTo(${JSON.stringify(group.parts[0]!)}Part, hostPart), or reposition the group so it contacts the body. If it is meant to stand apart, say so in the part name (foliage, card, decal) so this check skips it.`,
+ };
+ });
+ },
+});
diff --git a/src/qa/registry.test.ts b/src/qa/registry.test.ts
index 586c0ee6..fc4ca5b0 100644
--- a/src/qa/registry.test.ts
+++ b/src/qa/registry.test.ts
@@ -791,7 +791,7 @@ describe('QaRegistry', () => {
test('publishes a stable auditable state and owner for every checked-in rule', () => {
const decisions = DETERMINISTIC_QA_REGISTRY.describePolicy();
- expect(decisions).toHaveLength(24);
+ expect(decisions).toHaveLength(26);
expect(
decisions
.filter((item) => item.ruleClass === 'exact')
diff --git a/src/qa/run.ts b/src/qa/run.ts
index 03bcef9c..ebf3cc26 100644
--- a/src/qa/run.ts
+++ b/src/qa/run.ts
@@ -7,6 +7,8 @@ import { CHARACTER_ADVISORY_QA_RULE } from './character-advisory';
import { VEHICLE_QA_RULES } from './vehicle';
import { VEGETATION_QA_RULES } from './vegetation';
import { PROP_QA_RULES } from './prop';
+import { PART_CONNECTIVITY_QA_RULE } from './part-connectivity';
+import { SELF_INTERSECTION_QA_RULE } from './self-intersection';
import { ENVIRONMENT_QA_RULES } from './environment';
import { W7_BREADTH_QA_RULES } from './breadth';
import { withDerivedW7BreadthEvidence } from './breadth-evidence';
@@ -32,6 +34,8 @@ export const DETERMINISTIC_QA_REGISTRY = new QaRegistry([
...PROP_QA_RULES,
...ENVIRONMENT_QA_RULES,
...W7_BREADTH_QA_RULES,
+ SELF_INTERSECTION_QA_RULE,
+ PART_CONNECTIVITY_QA_RULE,
]);
export function runDeterministicSceneQa(
diff --git a/src/qa/self-intersection.test.ts b/src/qa/self-intersection.test.ts
new file mode 100644
index 00000000..345535fe
--- /dev/null
+++ b/src/qa/self-intersection.test.ts
@@ -0,0 +1,271 @@
+/**
+ * T4.1 — part-vs-part self-intersection.
+ *
+ * The gate's whole difficulty is the true negatives: bounding boxes call a bolt
+ * in a hole an intersection, and triangle overlap cannot tell a lid resting on a
+ * box from a lid sunk into it. Both are correct geometry that must not be
+ * flagged, so both have fixtures here alongside the true positives.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import {
+ analyzePartPenetration,
+ CONTACT_VOLUME_FRACTION,
+ MAX_PART_TRIANGLES,
+ SELF_INTERSECTION_QA_RULE,
+} from './self-intersection';
+import type { QaContext } from './types';
+import { createAssetIntentV1 } from '../contracts';
+
+function boxAt(name: string, size: [number, number, number], at: [number, number, number]) {
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size));
+ mesh.name = name;
+ mesh.position.set(...at);
+ return mesh;
+}
+
+function sceneOf(...meshes: THREE.Object3D[]): THREE.Object3D {
+ const root = new THREE.Object3D();
+ root.name = 'Asset';
+ for (const m of meshes) root.add(m);
+ return root;
+}
+
+const pairNames = (e: { penetrations: { a: string; b: string }[] }) =>
+ e.penetrations.map((p) => [p.a, p.b]);
+
+// -----------------------------------------------------------------------------
+// True positives
+// -----------------------------------------------------------------------------
+
+describe('true positives — parts occupying the same space', () => {
+ test('two boxes overlapping by half report the shared volume and fraction', async () => {
+ const e = await analyzePartPenetration(
+ sceneOf(boxAt('A', [1, 1, 1], [0, 0, 0]), boxAt('B', [1, 1, 1], [0.5, 0, 0])),
+ );
+
+ expect(pairNames(e)).toEqual([['A', 'B']]);
+ // A 1x1x1 box overlapping another by 0.5 along x shares exactly 0.5 m³,
+ // which is half of either part.
+ expect(e.penetrations[0]!.volume).toBeCloseTo(0.5, 6);
+ expect(e.penetrations[0]!.fraction).toBeCloseTo(0.5, 6);
+ });
+
+ test('a fully contained part reports a fraction of 1', async () => {
+ const e = await analyzePartPenetration(
+ sceneOf(boxAt('Outer', [2, 2, 2], [0, 0, 0]), boxAt('Inner', [0.5, 0.5, 0.5], [0, 0, 0])),
+ );
+
+ expect(e.penetrations).toHaveLength(1);
+ expect(e.penetrations[0]!.fraction).toBeCloseTo(1, 6);
+ });
+
+ test('worst offender is reported first', async () => {
+ const e = await analyzePartPenetration(
+ sceneOf(
+ boxAt('Base', [4, 1, 1], [0, 0, 0]),
+ boxAt('Slight', [1, 1, 1], [1.95, 0, 0]),
+ boxAt('Deep', [1, 1, 1], [-1.2, 0, 0]),
+ ),
+ );
+
+ expect(e.penetrations.length).toBeGreaterThanOrEqual(2);
+ expect(e.penetrations[0]!.fraction).toBeGreaterThan(e.penetrations[1]!.fraction);
+ expect(e.penetrations[0]!.b).toBe('Deep');
+ });
+});
+
+// -----------------------------------------------------------------------------
+// True negatives — the reason this is a volume test
+// -----------------------------------------------------------------------------
+
+describe('true negatives — correct geometry that must not be flagged', () => {
+ test('parts in flush contact share a surface, not a volume', async () => {
+ // A lid sitting exactly on a box. Triangle overlap would call this a hit.
+ const e = await analyzePartPenetration(
+ sceneOf(boxAt('Box', [1, 1, 1], [0, 0, 0]), boxAt('Lid', [1, 0.1, 1], [0, 0.55, 0])),
+ );
+
+ expect(e.candidatePairs).toBeGreaterThan(0); // the broad phase did consider them
+ expect(e.penetrations).toEqual([]);
+ });
+
+ /** Square plate, 2x2x0.2, with a bore of the given radius through its center. */
+ function boredPlate(boreRadius: number): THREE.Mesh {
+ const shape = new THREE.Shape();
+ shape.moveTo(-1, -1);
+ shape.lineTo(1, -1);
+ shape.lineTo(1, 1);
+ shape.lineTo(-1, 1);
+ shape.closePath();
+ const hole = new THREE.Path();
+ hole.absarc(0, 0, boreRadius, 0, Math.PI * 2, true);
+ shape.holes.push(hole);
+ const plate = new THREE.Mesh(
+ new THREE.ExtrudeGeometry(shape, { depth: 0.2, bevelEnabled: false }),
+ );
+ plate.name = 'Plate';
+ plate.rotation.x = -Math.PI / 2;
+ return plate;
+ }
+
+ test('a bolt too fat for its bore IS caught — the negative below is not vacuous', async () => {
+ const fat = new THREE.Mesh(new THREE.CylinderGeometry(0.35, 0.35, 1, 24));
+ fat.name = 'FatBolt';
+
+ const e = await analyzePartPenetration(sceneOf(boredPlate(0.2), fat));
+
+ expect(e.skipped).toEqual([]);
+ expect(e.pairsTested).toBe(1);
+ expect(pairNames(e)).toEqual([['Plate', 'FatBolt']]);
+ expect(e.penetrations[0]!.fraction).toBeGreaterThan(0.1);
+ });
+
+ test('a socketed part in its hole is not flagged', async () => {
+ // The classic bounding-box false positive: a bolt through a plate. The plate
+ // has a real bore, so the two solids share no volume even though their boxes
+ // overlap completely.
+ const bolt = new THREE.Mesh(new THREE.CylinderGeometry(0.15, 0.15, 1, 24));
+ bolt.name = 'Bolt';
+
+ const e = await analyzePartPenetration(sceneOf(boredPlate(0.2), bolt));
+
+ expect(e.candidatePairs).toBe(1); // boxes do overlap
+ // Neither part was skipped and the boolean really ran, so the empty result
+ // is a measurement rather than an analysis that quietly did nothing.
+ expect(e.skipped).toEqual([]);
+ expect(e.pairsTested).toBe(1);
+ expect(e.penetrations).toEqual([]); // volumes do not overlap
+ });
+
+ test('parts that are far apart never reach the narrow phase', async () => {
+ const e = await analyzePartPenetration(
+ sceneOf(boxAt('A', [1, 1, 1], [0, 0, 0]), boxAt('B', [1, 1, 1], [10, 0, 0])),
+ );
+
+ expect(e.candidatePairs).toBe(0);
+ expect(e.pairsTested).toBe(0);
+ expect(e.penetrations).toEqual([]);
+ });
+
+ test('a sliver of shared volume below the contact threshold is not a penetration', async () => {
+ // Overlap of 1e-5 on a unit box — the scale of a coincident-face boolean
+ // artifact, not of a modelling mistake.
+ const e = await analyzePartPenetration(
+ sceneOf(boxAt('A', [1, 1, 1], [0, 0, 0]), boxAt('B', [1, 1, 1], [1 - 1e-5, 0, 0])),
+ );
+
+ expect(e.penetrations).toEqual([]);
+ expect(CONTACT_VOLUME_FRACTION).toBeGreaterThan(1e-5);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// Determinism and bounds
+// -----------------------------------------------------------------------------
+
+describe('determinism and bounds', () => {
+ test('the same scene produces an identical report every run', async () => {
+ const build = () =>
+ sceneOf(
+ boxAt('A', [1, 1, 1], [0, 0, 0]),
+ boxAt('B', [1, 1, 1], [0.5, 0, 0]),
+ boxAt('C', [1, 1, 1], [0.25, 0.5, 0]),
+ );
+
+ const a = await analyzePartPenetration(build());
+ const b = await analyzePartPenetration(build());
+ expect(JSON.stringify(a)).toBe(JSON.stringify(b));
+ });
+
+ test('an oversized mesh is skipped with the reason, not silently ignored', async () => {
+ const dense = new THREE.Mesh(new THREE.SphereGeometry(1, 200, 200));
+ dense.name = 'Dense';
+ expect(dense.geometry.getIndex()!.count / 3).toBeGreaterThan(MAX_PART_TRIANGLES);
+
+ const e = await analyzePartPenetration(sceneOf(dense, boxAt('B', [1, 1, 1], [0, 0, 0])));
+
+ expect(e.skipped.map((s) => s.part)).toContain('Dense');
+ expect(e.skipped[0]!.reason).toContain('analysis budget');
+ expect(e.partsAnalyzed).toBe(1);
+ });
+
+ test('an open shell encloses no volume and is reported, not treated as clean', async () => {
+ const plane = new THREE.Mesh(new THREE.PlaneGeometry(2, 2));
+ plane.name = 'Card';
+ const e = await analyzePartPenetration(sceneOf(plane, boxAt('B', [1, 1, 1], [0, 0, 0])));
+
+ // Either manifold rejects it (reported in `skipped`) or it is closed enough
+ // to measure; what must not happen is a silent pass with no record.
+ expect(e.skipped.length + e.pairsTested).toBeGreaterThan(0);
+ expect(e.penetrations).toEqual([]);
+ });
+
+ test('a scene with fewer than two parts costs nothing', async () => {
+ const e = await analyzePartPenetration(sceneOf(boxAt('Only', [1, 1, 1], [0, 0, 0])));
+ expect(e.partsAnalyzed).toBe(1);
+ expect(e.candidatePairs).toBe(0);
+ expect(e.penetrations).toEqual([]);
+ });
+});
+
+// -----------------------------------------------------------------------------
+// The rule
+// -----------------------------------------------------------------------------
+
+describe('the QA rule', () => {
+ const contextWith = (partPenetration: unknown): QaContext => ({
+ intent: createAssetIntentV1({ category: 'prop' }),
+ derivedEvidence: { source: 'engine-scene-analysis', partPenetration },
+ });
+
+ test('starts in observe, as the plan requires before any promotion evidence', () => {
+ expect(SELF_INTERSECTION_QA_RULE.defaultMode).toBe('observe');
+ expect(SELF_INTERSECTION_QA_RULE.promotion).toBeUndefined();
+ // `exact` in this registry is a promotion contract, not a claim about the
+ // arithmetic: every exact rule must be enforcing on frozen conformance
+ // evidence. Until that evidence exists this stays heuristic, however precise
+ // the boolean volume underneath it is.
+ expect(SELF_INTERSECTION_QA_RULE.ruleClass).toBe('heuristic');
+ });
+
+ test('a finding names both parts, the shared volume, and how to fix it', async () => {
+ const evidence = await analyzePartPenetration(
+ sceneOf(boxAt('Handle', [1, 1, 1], [0, 0, 0]), boxAt('Body', [1, 1, 1], [0.5, 0, 0])),
+ );
+ const [finding] = SELF_INTERSECTION_QA_RULE.evaluate(contextWith(evidence));
+
+ expect(finding!.code).toBe('GEO_PART_SELF_INTERSECTION');
+ expect(finding!.disposition).toBe('observe');
+ expect(finding!.message).toContain('"Handle"');
+ expect(finding!.message).toContain('"Body"');
+ expect(finding!.repairText).toContain('boolDiff');
+ });
+
+ test('no evidence yields no findings — an analysis that did not run is not a pass', () => {
+ expect(SELF_INTERSECTION_QA_RULE.evaluate(contextWith(undefined))).toEqual([]);
+ expect(
+ SELF_INTERSECTION_QA_RULE.evaluate({ intent: createAssetIntentV1({ category: 'prop' }) }),
+ ).toEqual([]);
+ });
+
+ test('a truncated analysis says so rather than reading as complete', () => {
+ const findings = SELF_INTERSECTION_QA_RULE.evaluate(
+ contextWith({
+ schemaVersion: 1,
+ source: 'engine-scene-analysis',
+ partsAnalyzed: 40,
+ candidatePairs: 200,
+ pairsTested: 64,
+ truncated: true,
+ skipped: [],
+ penetrations: [],
+ }),
+ );
+
+ expect(findings).toHaveLength(1);
+ expect(findings[0]!.code).toBe('GEO_PART_SELF_INTERSECTION_TRUNCATED');
+ expect(findings[0]!.message).toContain('64 of 200');
+ });
+});
diff --git a/src/qa/self-intersection.ts b/src/qa/self-intersection.ts
new file mode 100644
index 00000000..539d2ffc
--- /dev/null
+++ b/src/qa/self-intersection.ts
@@ -0,0 +1,363 @@
+/**
+ * Part-vs-part self-intersection gate — T4.1
+ *
+ * ## Why intersection VOLUME, not triangle overlap
+ *
+ * The accept criterion demands true negatives for "intentional contact and
+ * socketed parts", and that is what rules out the cheaper checks:
+ *
+ * - **Bounding boxes** call a bolt in a hole, a wheel in a wheel well, and a
+ * handle through a loop all intersecting. Every one is correct geometry.
+ * - **Triangle overlap** cannot separate two parts that merely touch — a lid
+ * resting on a box, a wheel meeting the ground — from two parts occupying the
+ * same space. Contact is coplanar triangles; interpenetration is shared
+ * volume. A triangle test sees both as "they overlap".
+ *
+ * Boolean intersection volume separates them by construction: surfaces in
+ * contact enclose zero volume, interpenetrating solids enclose a real one. That
+ * is exactly the distinction the gate has to make, so it is measured directly
+ * rather than approximated.
+ *
+ * manifold-3d is already a dependency (`solids.ts`), so this costs no new
+ * package and reuses the same watertight-solid machinery CSG runs on.
+ *
+ * ## Bounded time
+ *
+ * Booleans are expensive and pair count grows quadratically, so the pass is
+ * staged:
+ *
+ * 1. **Broad phase** — world-space AABB overlap. Rejects almost every pair for
+ * the price of six comparisons. Parts that do not share a bounding box
+ * cannot share volume.
+ * 2. **Narrow phase** — one boolean per surviving pair, capped by
+ * {@link MAX_NARROW_PHASE_PAIRS}. If the cap is hit, the analysis says so in
+ * `truncated` instead of silently checking less than it claims.
+ *
+ * Meshes are also capped at {@link MAX_PART_TRIANGLES}; above that a single
+ * boolean stops being bounded-time in any useful sense. Skipped parts are
+ * reported, never dropped quietly.
+ *
+ * ## Determinism
+ *
+ * Parts are collected in traversal order and compared in a fixed pair order,
+ * volumes are rounded to a fixed precision, and findings are sorted by name.
+ * The same scene yields the same report on every run and every machine.
+ */
+
+import * as THREE from 'three';
+import type { QaContext, QaFinding } from './types';
+import { KILN_ENGINE_QA_OWNER, type QaRule } from './registry';
+
+/** Above this, one boolean is no longer bounded-time in any useful sense. */
+export const MAX_PART_TRIANGLES = 20000;
+/** Narrow-phase budget. Broad phase normally leaves far fewer than this. */
+export const MAX_NARROW_PHASE_PAIRS = 64;
+/**
+ * Intersection volume below this fraction of the smaller part's volume is
+ * treated as contact rather than penetration.
+ *
+ * Not zero: two parts snapped flush share a surface, and floating-point
+ * evaluation of a boolean on coincident faces yields a sliver of volume rather
+ * than exactly nothing. The threshold is a fraction rather than an absolute so
+ * it means the same thing on a 2 cm bolt and a 20 m wall.
+ */
+export const CONTACT_VOLUME_FRACTION = 0.001;
+
+export interface PartPenetrationPairV1 {
+ a: string;
+ b: string;
+ /** Absolute intersection volume in cubic meters. */
+ volume: number;
+ /** Intersection volume over the smaller part's volume, 0..1. */
+ fraction: number;
+}
+
+export interface PartPenetrationEvidenceV1 {
+ schemaVersion: 1;
+ source: 'engine-scene-analysis';
+ /** Parts that were actually compared. */
+ partsAnalyzed: number;
+ /** Pairs that survived the AABB broad phase. */
+ candidatePairs: number;
+ /** Pairs a boolean was actually run on. */
+ pairsTested: number;
+ /** True when the narrow-phase cap stopped the analysis short. */
+ truncated: boolean;
+ /** Parts skipped, with the reason — never silently dropped. */
+ skipped: { part: string; reason: string }[];
+ /** Pairs whose shared volume exceeds the contact threshold, worst first. */
+ penetrations: PartPenetrationPairV1[];
+}
+
+interface AnalyzedPart {
+ name: string;
+ mesh: THREE.Mesh;
+ box: THREE.Box3;
+ triangles: number;
+}
+
+/** Fixed precision so a report is byte-comparable across runs. */
+const round = (n: number): number => Math.round(n * 1e9) / 1e9;
+
+function triangleCount(geometry: THREE.BufferGeometry): number {
+ const index = geometry.getIndex();
+ const position = geometry.getAttribute('position');
+ if (!position) return 0;
+ return Math.floor((index ? index.count : position.count) / 3);
+}
+
+/**
+ * Collect the meshes worth comparing, in traversal order.
+ *
+ * Only meshes with real geometry participate: a part with no triangles cannot
+ * penetrate anything, and including it would produce a boolean on an empty
+ * operand — which `solids.ts` now (correctly) throws on.
+ */
+function collectParts(
+ root: THREE.Object3D,
+ skipped: PartPenetrationEvidenceV1['skipped'],
+): AnalyzedPart[] {
+ const parts: AnalyzedPart[] = [];
+ root.updateWorldMatrix(true, true);
+
+ root.traverse((node) => {
+ const mesh = node as THREE.Mesh;
+ if (!mesh.isMesh || !mesh.geometry) return;
+ const name = mesh.name || '(unnamed mesh)';
+ const triangles = triangleCount(mesh.geometry);
+ if (triangles === 0) return;
+ if (triangles > MAX_PART_TRIANGLES) {
+ skipped.push({
+ part: name,
+ reason: `${triangles} triangles exceeds the ${MAX_PART_TRIANGLES}-triangle analysis budget`,
+ });
+ return;
+ }
+ const box = new THREE.Box3().setFromObject(mesh);
+ if (box.isEmpty()) return;
+ parts.push({ name, mesh, box, triangles });
+ });
+
+ return parts;
+}
+
+/**
+ * World-space triangle soup for one mesh, as manifold wants it.
+ *
+ * Deliberately independent of `solids.ts`'s `threeToManifold`: that one walks a
+ * whole Object3D and enforces CSG's stricter operand contract, whereas this
+ * needs one already-located mesh and must tolerate geometry a QA pass should
+ * report on rather than throw over.
+ */
+function meshToArrays(
+ mesh: THREE.Mesh,
+): { vertProperties: Float32Array; triVerts: Uint32Array } | null {
+ const geometry = mesh.geometry;
+ const position = geometry.getAttribute('position') as THREE.BufferAttribute | undefined;
+ if (!position) return null;
+
+ const matrix = mesh.matrixWorld;
+ const v = new THREE.Vector3();
+ const verts = new Float32Array(position.count * 3);
+ for (let i = 0; i < position.count; i++) {
+ v.set(position.getX(i), position.getY(i), position.getZ(i)).applyMatrix4(matrix);
+ verts[i * 3] = v.x;
+ verts[i * 3 + 1] = v.y;
+ verts[i * 3 + 2] = v.z;
+ }
+
+ const index = geometry.getIndex();
+ let tris: Uint32Array;
+ if (index) {
+ if (index.count % 3 !== 0) return null;
+ tris = new Uint32Array(index.count);
+ for (let i = 0; i < index.count; i++) tris[i] = index.getX(i);
+ } else {
+ if (position.count % 3 !== 0) return null;
+ tris = new Uint32Array(position.count);
+ for (let i = 0; i < position.count; i++) tris[i] = i;
+ }
+
+ return { vertProperties: verts, triVerts: tris };
+}
+
+/**
+ * Measure how much volume every pair of parts shares.
+ *
+ * Async because manifold is WASM and initializes on first use. The QA registry
+ * evaluates rules synchronously, so this runs as a pre-pass and its result
+ * travels to the rule through `QaContext.derivedEvidence` — the seam that
+ * exists precisely for engine measurements a rule cannot take itself.
+ */
+export async function analyzePartPenetration(
+ root: THREE.Object3D,
+): Promise<PartPenetrationEvidenceV1> {
+ const skipped: PartPenetrationEvidenceV1['skipped'] = [];
+ const parts = collectParts(root, skipped);
+
+ const base: PartPenetrationEvidenceV1 = {
+ schemaVersion: 1,
+ source: 'engine-scene-analysis',
+ partsAnalyzed: parts.length,
+ candidatePairs: 0,
+ pairsTested: 0,
+ truncated: false,
+ skipped,
+ penetrations: [],
+ };
+ if (parts.length < 2) return base;
+
+ // Broad phase first, so an unwinnable scene never pays for WASM init.
+ const candidates: Array<[AnalyzedPart, AnalyzedPart]> = [];
+ for (let i = 0; i < parts.length; i++) {
+ for (let j = i + 1; j < parts.length; j++) {
+ if (parts[i]!.box.intersectsBox(parts[j]!.box)) candidates.push([parts[i]!, parts[j]!]);
+ }
+ }
+ base.candidatePairs = candidates.length;
+ if (candidates.length === 0) return base;
+
+ const tested = candidates.slice(0, MAX_NARROW_PHASE_PAIRS);
+ base.truncated = candidates.length > tested.length;
+
+ const Module = await import('manifold-3d');
+ const wasm = await Module.default();
+ wasm.setup();
+ const { Manifold, Mesh } = wasm;
+
+ const cache = new Map<THREE.Mesh, InstanceType<typeof Manifold> | null>();
+ const build = (part: AnalyzedPart): InstanceType<typeof Manifold> | null => {
+ if (cache.has(part.mesh)) return cache.get(part.mesh)!;
+ let solid: InstanceType<typeof Manifold> | null = null;
+ try {
+ const arrays = meshToArrays(part.mesh);
+ if (arrays) {
+ const mesh = new Mesh({ numProp: 3, ...arrays });
+ // Three's primitives split vertices at UV/normal seams — a BoxGeometry
+ // has 24 positions for 8 corners — and manifold reads that as an open
+ // surface ("Not manifold"). merge() welds coincident positions, which
+ // is the same step `solids.ts` takes before every CSG operand.
+ mesh.merge();
+ solid = new Manifold(mesh);
+ } else {
+ skipped.push({ part: part.name, reason: 'its triangle list is malformed' });
+ }
+ } catch (err) {
+ // A part that is not a closed solid (an open shell, a foliage card) cannot
+ // enclose volume, so it cannot penetrate anything. Reported, not fatal.
+ skipped.push({
+ part: part.name,
+ reason: `it is not a closed solid, so it encloses no volume (${err instanceof Error ? err.message : String(err)})`,
+ });
+ solid = null;
+ }
+ cache.set(part.mesh, solid);
+ return solid;
+ };
+
+ const penetrations: PartPenetrationPairV1[] = [];
+ try {
+ for (const [a, b] of tested) {
+ const sa = build(a);
+ const sb = build(b);
+ if (!sa || !sb) continue;
+ base.pairsTested++;
+
+ let overlap: InstanceType<typeof Manifold> | null = null;
+ try {
+ overlap = Manifold.intersection(sa, sb);
+ const volume = overlap.volume();
+ if (volume > 0) {
+ const smaller = Math.min(Math.abs(sa.volume()), Math.abs(sb.volume()));
+ const fraction = smaller > 0 ? volume / smaller : 0;
+ if (fraction > CONTACT_VOLUME_FRACTION) {
+ penetrations.push({
+ a: a.name,
+ b: b.name,
+ volume: round(volume),
+ fraction: round(fraction),
+ });
+ }
+ }
+ } finally {
+ overlap?.delete();
+ }
+ }
+ } finally {
+ for (const solid of cache.values()) solid?.delete();
+ }
+
+ // Worst first, then by name so equal-volume pairs keep a stable order.
+ penetrations.sort(
+ (x, y) => y.fraction - x.fraction || `${x.a}:${x.b}`.localeCompare(`${y.a}:${y.b}`),
+ );
+ base.penetrations = penetrations;
+ return base;
+}
+
+// -----------------------------------------------------------------------------
+// The rule
+// -----------------------------------------------------------------------------
+
+function readEvidence(context: {
+ derivedEvidence?: Record<string, unknown>;
+}): PartPenetrationEvidenceV1 | undefined {
+ const evidence = context.derivedEvidence?.['partPenetration'] as
+ | PartPenetrationEvidenceV1
+ | undefined;
+ return evidence?.schemaVersion === 1 ? evidence : undefined;
+}
+
+/**
+ * Report parts that occupy the same space.
+ *
+ * Starts in `observe` as the plan requires: it has no promotion evidence yet,
+ * and the registry will not let an unpromoted rule warn or block regardless.
+ */
+export const SELF_INTERSECTION_QA_RULE: QaRule = Object.freeze({
+ id: 'GEO_PART_SELF_INTERSECTION',
+ profile: 'geometry.selfIntersection',
+ scope: { kind: 'universal' as const },
+ // 'heuristic', not 'exact', even though the measurement IS exact — a boolean
+ // volume, not a proxy for one. In this registry `exact` is a promotion
+ // contract, not a statement about the arithmetic: every `exact` rule must sit
+ // in `enforce` with frozen conformance evidence, and the registry test
+ // enforces that. A rule with no evidence yet is `heuristic` regardless of how
+ // precise its measurement is. Reclassify to `exact` at the same time as
+ // freezing a fixture set and promoting, never before.
+ ruleClass: 'heuristic',
+ owner: KILN_ENGINE_QA_OWNER,
+ defaultMode: 'observe',
+ evaluate(context: QaContext): readonly QaFinding[] {
+ const evidence = readEvidence(context as { derivedEvidence?: Record<string, unknown> });
+ if (!evidence) return [];
+
+ const findings: QaFinding[] = evidence.penetrations.map((pair) => ({
+ code: 'GEO_PART_SELF_INTERSECTION',
+ disposition: 'observe' as const,
+ dimension: 'visualQuality' as const,
+ profile: 'geometry.selfIntersection',
+ message: `Parts ${JSON.stringify(pair.a)} and ${JSON.stringify(pair.b)} occupy the same space: they share ${pair.volume.toPrecision(3)} m³, which is ${(pair.fraction * 100).toFixed(1)}% of the smaller part.`,
+ affected: { node: pair.a },
+ measurement: {
+ name: 'intersectionVolumeFraction',
+ actual: pair.fraction,
+ expected: CONTACT_VOLUME_FRACTION,
+ },
+ repairText:
+ 'Move one part clear of the other, or subtract it with boolDiff so the overlap becomes a real cut instead of two solids in the same place.',
+ }));
+
+ if (evidence.truncated) {
+ findings.push({
+ code: 'GEO_PART_SELF_INTERSECTION_TRUNCATED',
+ disposition: 'observe' as const,
+ dimension: 'visualQuality' as const,
+ profile: 'geometry.selfIntersection',
+ message: `Only ${evidence.pairsTested} of ${evidence.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`,
+ });
+ }
+
+ return findings;
+ },
+});
diff --git a/src/qa/types.ts b/src/qa/types.ts
index aa5f91eb..845ff622 100644
--- a/src/qa/types.ts
+++ b/src/qa/types.ts
@@ -95,6 +95,8 @@ export interface QaContext {
assetScope?: unknown;
modularKit?: unknown;
modularJoin?: unknown;
+ /** T4.1 part-vs-part boolean intersection volumes; computed async before QA runs. */
+ partPenetration?: unknown;
};
}
diff --git a/src/render.ts b/src/render.ts
index 8e09bac1..d2970e2f 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -83,6 +83,12 @@ import {
collectMaterialResourceProvenance,
type MaterialResourceProvenanceV1,
} from './material-resources';
+import { analyzePartPenetration, type PartPenetrationEvidenceV1 } from './qa/self-intersection';
+import {
+ type BakedTextureProvenanceV1,
+ bakeSceneTextures,
+ ensureNormalMapTangents,
+} from './texture-bake';
import {
captureCharacterDiagnosticViews,
type CharacterCapturedDiagnosticV1,
@@ -480,10 +486,16 @@ function bridgeMaterial(
/**
* Bridge a Three.js Texture to a gltf-transform Texture.
*
- * Prefers `userData.encoded` (raw PNG/JPG bytes from loadTexture) so we
- * don't re-encode. Falls back to null if nothing is encoded — procedural
- * DataTextures without encoded bytes aren't exportable yet (requires
- * runtime PNG encoding, which we'll wire in Wave 3D via sharp).
+ * Uses `userData.encoded` — the bytes `loadTexture` stashed, or the PNG
+ * `bakeSceneTextures` encoded earlier in `renderSceneToGLB` — so nothing is
+ * re-encoded here.
+ *
+ * Returning null still drops the slot, but it is no longer silent: the bake
+ * pass has already walked every material slot and warned by material and slot
+ * name for anything it could not encode. That warning lives there rather than
+ * here because this function receives a bare `THREE.Texture` and cannot say
+ * which material or slot it came from — which is most of what makes the
+ * warning actionable.
*/
function bridgeTexture(
doc: Document,
@@ -859,6 +871,8 @@ export interface RenderSceneResult {
instanceability?: InstanceabilityReport;
/** Set if metric computation threw; bytes are still valid. */
metricsError?: string;
+ /** Textures encoded to PNG at export time (T2.2). Absent when none were baked. */
+ bakedTextures?: BakedTextureProvenanceV1[];
/** Set when an opt-in consolidation pass ran (optimize !== 'off'). */
optimize?: OptimizeSummary;
/** Set when the GPU-instancing pass created batches (instance !== 'off'). */
@@ -1087,7 +1101,42 @@ export async function renderSceneToGLB(
for (const w of inspectGeneratedAnimation(root, clips)) warnings.push(w);
for (const w of inspectSceneStructure(root, { category: trustedCategory })) warnings.push(w);
- const sceneQaReport = runDeterministicSceneQa({ intent, scene: root, clips }, qaPolicyFromEnv());
+ // 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 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);
+
+ // T4.1 — part-vs-part penetration. Async (manifold is WASM) and QA rules
+ // evaluate synchronously, so it runs here and reaches the rule through the
+ // derivedEvidence seam. A failure here must never lose the asset: the gate is
+ // in `observe`, and an analysis that could not run is reported as absent
+ // rather than as a clean result.
+ let partPenetration: PartPenetrationEvidenceV1 | undefined;
+ try {
+ partPenetration = await analyzePartPenetration(root);
+ } catch (err) {
+ warnings.push(
+ `self-intersection analysis failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+
+ const sceneQaReport = runDeterministicSceneQa(
+ {
+ intent,
+ scene: root,
+ clips,
+ ...(partPenetration
+ ? { derivedEvidence: { source: 'engine-scene-analysis' as const, partPenetration } }
+ : {}),
+ },
+ qaPolicyFromEnv(),
+ );
if (sceneQaReport.disposition === 'block') {
const blocked = new AssetQaBlockedError(sceneQaReport, 'scene');
if (qaBlockingEnabled()) throw blocked;
@@ -1266,6 +1315,7 @@ export async function renderSceneToGLB(
...(materialMetrics ? { materialMetrics } : {}),
...(materialRecipeApplications.length ? { materialRecipeApplications } : {}),
...(materialResourceProvenance.length ? { materialResourceProvenance } : {}),
+ ...(bakedTextures.length ? { bakedTextures } : {}),
integrationManifest,
};
}
diff --git a/src/solids.ts b/src/solids.ts
index 753f5069..7bb4adb4 100644
--- a/src/solids.ts
+++ b/src/solids.ts
@@ -19,8 +19,35 @@
* Limitations:
* - Input geometry should be watertight / manifold. sphereGeo's polar
* singularity can produce degenerate triangles that manifold trims.
- * - Only position data survives — normals and UVs are regenerated.
* - Material is inherited from the first operand.
+ *
+ * ## UV semantics (T2.4) — read this before texturing a boolean
+ *
+ * **Every boolean DESTROYS UVs.** The bridge to manifold carries positions
+ * only (`numProp: 3`); normals are recomputed from the result topology and the
+ * `uv` attribute is simply absent on the output. This is not a bug to fix here:
+ * manifold-3d does not preserve per-triangle provenance, so there is no
+ * correspondence to carry UVs through in the first place — a new cut face has
+ * no pre-image in either operand.
+ *
+ * The consequence for asset code: **unwrap after the boolean, not before.**
+ *
+ * ```js
+ * const carved = await boolDiff('Panel', body, ...bolts);
+ * carved.geometry = await autoUnwrap(carved.geometry); // now it can hold a texture
+ * ```
+ *
+ * Unwrapping an operand first is wasted work at best; the atlas it produces is
+ * discarded by the very next boolean.
+ *
+ * Guards (all measured against real silent failures, see the tests):
+ * - An operand contributing zero triangles throws, naming which operand.
+ * `boolUnion(body, emptyGroup)` used to return the body unchanged and
+ * `boolIntersect(body, emptyGroup)` a zero-triangle mesh, both silently.
+ * - A ragged triangle list throws here rather than as manifold's bare
+ * "Not manifold", which names nothing.
+ * - An empty RESULT throws with the op-specific likely cause. A disjoint
+ * `boolIntersect` is the common one, and it used to ship an invisible part.
*/
import * as THREE from 'three';
@@ -55,11 +82,15 @@ export async function getManifoldModule(): Promise<ManifoldToplevel> {
/**
* Convert a Three.js Mesh/Object3D to a Manifold Mesh (world-space).
* Flattens any scene subtree into a single merged manifold.
+ *
+ * `label` names the operand in guard messages — the agent sees these, and
+ * "operand 2 (Cutter)" is actionable where "Not manifold" is not.
*/
function threeToManifold(
src: THREE.Object3D,
ManifoldCls: typeof Manifold,
MeshCls: typeof Mesh,
+ label = 'operand',
): Manifold {
src.updateMatrixWorld(true);
@@ -68,6 +99,7 @@ function threeToManifold(
const tmpVec = new THREE.Vector3();
let vertexOffset = 0;
+ let meshCount = 0;
src.traverse((child) => {
// Duck-typed `.isMesh` — sandbox-created meshes belong to a different
@@ -77,6 +109,21 @@ function threeToManifold(
const geo = meshChild.geometry as THREE.BufferGeometry;
const posAttr = geo.getAttribute('position') as THREE.BufferAttribute | undefined;
if (!posAttr) return;
+ meshCount++;
+
+ const idx = geo.getIndex();
+ // T2.4: a ragged triangle list reaches manifold as a partial triangle and
+ // comes back as a bare "Not manifold" that names nothing. Caught here, where
+ // the offending mesh is still identifiable.
+ const listCount = idx ? idx.count : posAttr.count;
+ if (listCount % 3 !== 0) {
+ throw new Error(
+ `CSG ${label}: mesh "${meshChild.name || '(unnamed)'}" has ${listCount} ${
+ idx ? 'indices' : 'vertices'
+ }, which is not a whole number of triangles. ` +
+ 'Every CSG input must be a triangle mesh; build it from the primitive geometry helpers rather than assembling attributes by hand.',
+ );
+ }
const matrix = meshChild.matrixWorld;
@@ -85,7 +132,6 @@ function threeToManifold(
positions.push(tmpVec.x, tmpVec.y, tmpVec.z);
}
- const idx = geo.getIndex();
if (idx) {
for (let i = 0; i < idx.count; i++) {
indices.push((idx.getX(i) as number) + vertexOffset);
@@ -100,6 +146,21 @@ function threeToManifold(
vertexOffset += posAttr.count;
});
+ // T2.4: an operand that contributes nothing used to be absorbed in silence —
+ // `boolUnion(body, emptyGroup)` returned the body, and `boolIntersect(body,
+ // emptyGroup)` returned a ZERO-triangle mesh that sailed on into the GLB.
+ // Measured, both cases; neither said a word. The realistic cause is a Group
+ // whose children were never added, or a mesh built before its geometry was.
+ if (indices.length === 0) {
+ throw new Error(
+ `CSG ${label}: contributes no triangles${
+ meshCount === 0
+ ? ' (nothing in it is a mesh — an empty Group, or a part that was never added to it)'
+ : ' (its meshes have no geometry)'
+ }. Every CSG operand must be a solid with triangles.`,
+ );
+ }
+
const mesh = new MeshCls({
numProp: 3,
vertProperties: new Float32Array(positions),
@@ -110,6 +171,21 @@ function threeToManifold(
return ManifoldCls.ofMesh(mesh);
}
+/**
+ * Guard a boolean's RESULT (T2.4).
+ *
+ * An empty result is geometrically legal and almost never intended: a
+ * disjoint `boolIntersect`, or a `boolDiff` whose cutters swallow the body.
+ * Measured before this guard, both produced a 0-triangle mesh that passed
+ * silently through `autoUnwrap` (which also returned 0 vertices without
+ * complaint) and into the GLB as an invisible part. Failing loudly here gives
+ * the agent a fixable error at the step that caused it.
+ */
+function assertNonEmptyResult(m: Manifold, op: string, hint: string): void {
+ if (m.numTri() > 0) return;
+ throw new Error(`${op}: the result is empty (zero triangles). ${hint}`);
+}
+
/**
* Convert a Manifold result back to a Three.js Mesh with the given material.
*
@@ -301,12 +377,21 @@ export async function boolUnion(
throw new Error('boolUnion requires at least two parts');
}
const mod = await getManifoldModule();
- const manifolds = parts.map((p) => threeToManifold(p, mod.Manifold, mod.Mesh));
+ const manifolds = parts.map((p, i) =>
+ threeToManifold(p, mod.Manifold, mod.Mesh, `boolUnion operand ${i + 1}`),
+ );
const result = mod.Manifold.union(manifolds);
+ try {
+ assertNonEmptyResult(result, 'boolUnion', 'Every operand was empty after merging.');
+ } catch (err) {
+ for (const m of manifolds) m.delete();
+ result.delete();
+ throw err;
+ }
const mat = materialOf(parts[0]!, new THREE.MeshStandardMaterial());
const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);
tagCsgOutput(mesh, parts);
- manifolds.forEach((m) => m.delete());
+ for (const m of manifolds) m.delete();
result.delete();
return mesh;
}
@@ -331,15 +416,30 @@ export async function boolDiff(
throw new Error('boolDiff requires at least one cutter');
}
const mod = await getManifoldModule();
- const bodyM = threeToManifold(body, mod.Manifold, mod.Mesh);
- const cutterM = cutters.map((c) => threeToManifold(c, mod.Manifold, mod.Mesh));
+ const bodyM = threeToManifold(body, mod.Manifold, mod.Mesh, 'boolDiff body');
+ const cutterM = cutters.map((c, i) =>
+ threeToManifold(c, mod.Manifold, mod.Mesh, `boolDiff cutter ${i + 1}`),
+ );
const cutterUnion = cutterM.length === 1 ? (cutterM[0] as Manifold) : mod.Manifold.union(cutterM);
const result = bodyM.subtract(cutterUnion);
+ try {
+ assertNonEmptyResult(
+ result,
+ 'boolDiff',
+ 'The cutters removed the entire body — check their size and position, or subtract fewer of them.',
+ );
+ } catch (err) {
+ bodyM.delete();
+ for (const m of cutterM) m.delete();
+ if (cutterM.length > 1) cutterUnion.delete();
+ result.delete();
+ throw err;
+ }
const mat = materialOf(body, new THREE.MeshStandardMaterial());
const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);
tagCsgOutput(mesh, [body, ...cutters]);
bodyM.delete();
- cutterM.forEach((m) => m.delete());
+ for (const m of cutterM) m.delete();
if (cutterM.length > 1) cutterUnion.delete();
result.delete();
return mesh;
@@ -358,9 +458,21 @@ export async function boolIntersect(
opts: { smooth?: boolean } = {},
): Promise<THREE.Mesh> {
const mod = await getManifoldModule();
- const aM = threeToManifold(a, mod.Manifold, mod.Mesh);
- const bM = threeToManifold(b, mod.Manifold, mod.Mesh);
+ const aM = threeToManifold(a, mod.Manifold, mod.Mesh, 'boolIntersect operand a');
+ const bM = threeToManifold(b, mod.Manifold, mod.Mesh, 'boolIntersect operand b');
const result = aM.intersect(bM);
+ try {
+ assertNonEmptyResult(
+ result,
+ 'boolIntersect',
+ 'The two operands do not overlap — position them so their volumes actually intersect.',
+ );
+ } catch (err) {
+ aM.delete();
+ bM.delete();
+ result.delete();
+ throw err;
+ }
const mat = materialOf(a, new THREE.MeshStandardMaterial());
const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);
tagCsgOutput(mesh, [a, b]);
@@ -387,13 +499,26 @@ export async function hull(
throw new Error('hull requires at least one part');
}
const mod = await getManifoldModule();
- const manifolds = parts.map((p) => threeToManifold(p, mod.Manifold, mod.Mesh));
+ const manifolds = parts.map((p, i) =>
+ threeToManifold(p, mod.Manifold, mod.Mesh, `hull operand ${i + 1}`),
+ );
const result =
manifolds.length === 1 ? (manifolds[0] as Manifold).hull() : mod.Manifold.hull(manifolds);
+ try {
+ assertNonEmptyResult(
+ result,
+ 'hull',
+ 'The inputs are coplanar or collinear, so they enclose no volume.',
+ );
+ } catch (err) {
+ for (const m of manifolds) m.delete();
+ if (manifolds.length > 1) result.delete();
+ throw err;
+ }
const mat = materialOf(parts[0]!, new THREE.MeshStandardMaterial());
const mesh = manifoldToThree(result, mat, `Mesh_${name}`, { smooth: opts.smooth ?? true });
tagCsgOutput(mesh, parts);
- manifolds.forEach((m) => m.delete());
+ for (const m of manifolds) m.delete();
if (manifolds.length > 1) result.delete();
return mesh;
}
diff --git a/src/texture-bake.ts b/src/texture-bake.ts
new file mode 100644
index 00000000..57ec38ac
--- /dev/null
+++ b/src/texture-bake.ts
@@ -0,0 +1,464 @@
+/**
+ * Bake in-memory textures to encoded PNG bytes before export — T2.2
+ *
+ * ## The problem this closes
+ *
+ * The GLB bridge (`render.ts` `bridgeTexture`) serializes a texture only if it
+ * carries `userData.encoded` — the original bytes `loadTexture` stashed. A
+ * texture built in code (a procedural `DataTexture`) has pixels but no encoded
+ * bytes, so the bridge returned `null` and the slot was simply left off the
+ * material.
+ *
+ * Measured, before this module existed: a `MeshStandardMaterial` with a
+ * hand-built 8x8 checker `map` exported 1912 bytes of valid GLB with **zero
+ * warnings**, no image in the file, and a QA disposition of `pass` under
+ * `KILN_QA_MODE=off`. The asset shipped looking clean with its texture gone.
+ * The scene QA gate does catch it at default settings
+ * (`MAT_TEXTURE_DECODE_FAILED`), but that gate is downgradable and it is a
+ * *block*, not a bake — it tells an author the texture is unexportable rather
+ * than making it exportable.
+ *
+ * ## What this does
+ *
+ * Runs before scene QA, so QA judges what will actually be in the file. Every
+ * texture reachable from a material slot that has readable 8-bit pixel data and
+ * no encoded bytes is encoded to PNG and stamped with the same two `userData`
+ * records `loadTexture` writes, so everything downstream — QA, the bridge,
+ * provenance — treats a baked texture and a loaded one identically.
+ *
+ * Anything that cannot be baked gets a warning naming the material, the slot,
+ * and the reason. That is the "loud" half: the bridge sees only a `THREE.Texture`
+ * and cannot name where it came from, whereas this pass walks slots and can.
+ *
+ * ## What this deliberately does not do
+ *
+ * It never sets `texture.colorSpace`. QA requires sRGB for `map`/`emissiveMap`
+ * and linear for the data maps, and a hand-built `DataTexture` defaults to
+ * linear — but silently reinterpreting an author's pixels is the same class of
+ * bug as the silent drop. A procedural albedo with the wrong color space still
+ * blocks, with a message that now names the procedural fix.
+ */
+
+import { createHash } from 'node:crypto';
+import * as THREE from 'three';
+import type { EncodedTextureData, KilnTextureMetadata, TextureUsage } from './textures';
+
+/** Provenance for one texture this pass encoded. Deterministic and sorted. */
+export interface BakedTextureProvenanceV1 {
+ schemaVersion: 1;
+ /** `texture.name`, or `(unnamed texture)` — matches QA's `affected` naming. */
+ texture: string;
+ /** Owning material name, for locating it in the source. */
+ material: string;
+ /** glTF-facing slot the texture fills (`map`, `normalMap`, ...). */
+ slot: string;
+ usage: TextureUsage;
+ width: number;
+ height: number;
+ channels: 3 | 4;
+ /** Encoded PNG size in bytes. */
+ bytes: number;
+ /** SHA-1 of the PNG bytes — the handle a determinism test compares. */
+ sha1: string;
+ /**
+ * The layer stack, when this texture came from `proceduralTexture()`.
+ *
+ * Recorded so the manifest says what was generated rather than only that
+ * something was: the spec is small, serializable, and sufficient to
+ * regenerate the exact bytes. Absent for textures loaded from a file.
+ */
+ procedural?: ProceduralRecipeRecord;
+}
+
+/** The `userData.kilnProcedural` stamp `proceduralTexture()` leaves behind. */
+interface ProceduralRecipeRecord {
+ schemaVersion: 1;
+ size: number;
+ usage: TextureUsage;
+ layers: unknown[];
+}
+
+/**
+ * Material slots the GLB bridge can serialize, with the glTF usage each one
+ * implies. Kept in the same order the bridge reads them so a warning list and a
+ * material read the same way.
+ *
+ * `map` is read off every material type, not just `MeshStandardMaterial` — the
+ * bridge's non-PBR path (`common.map`) bridges it too, and a Lambert or Basic
+ * material with a dropped texture was just as silent.
+ */
+const SLOT_USAGE: ReadonlyArray<readonly [string, TextureUsage]> = [
+ ['map', 'albedo'],
+ ['normalMap', 'normal'],
+ ['roughnessMap', 'roughness'],
+ ['metalnessMap', 'metalness'],
+ ['emissiveMap', 'emissive'],
+ ['aoMap', 'occlusion'],
+];
+
+interface RawPixels {
+ data: Uint8Array;
+ width: number;
+ height: number;
+ channels: 3 | 4;
+}
+
+/**
+ * Read 8-bit pixels off a texture, or explain why they are unusable.
+ *
+ * Returns a string instead of throwing because every failure here is a warning
+ * on an otherwise-valid asset, not an error that should lose the whole export.
+ */
+function readPixels(texture: THREE.Texture): RawPixels | string {
+ const image = texture.image as
+ | { data?: ArrayLike<number>; width?: number; height?: number }
+ | undefined;
+ if (!image) return 'it has no image data';
+
+ const { width, height } = image;
+ if (!Number.isFinite(width) || !Number.isFinite(height) || !width || !height) {
+ return 'its image has no usable width/height';
+ }
+
+ const data = image.data;
+ if (!data) {
+ // A texture from an <img>/ImageBitmap has pixels the CPU cannot read without
+ // a canvas, which does not exist headlessly.
+ return 'its pixels are not readable in Node (only DataTexture-style byte arrays can be baked)';
+ }
+ if (!(data instanceof Uint8Array) && !(data instanceof Uint8ClampedArray)) {
+ return `its pixel data is ${data.constructor?.name ?? 'an unknown type'}, not 8-bit bytes (float/half-float textures cannot be baked to PNG)`;
+ }
+
+ const pixels = (width as number) * (height as number);
+ const channels = data.length / pixels;
+ if (channels !== 3 && channels !== 4) {
+ return `its pixel data is ${data.length} bytes for ${width}x${height}, which is neither RGB nor RGBA`;
+ }
+
+ return {
+ data: data instanceof Uint8Array ? data : new Uint8Array(data),
+ width: width as number,
+ height: height as number,
+ channels,
+ };
+}
+
+/**
+ * Encode raw pixels to PNG.
+ *
+ * Options are pinned rather than left to sharp's defaults so the same pixels
+ * produce the same bytes: T2.2's acceptance criterion is byte-level determinism
+ * across runs, and a default that shifted between sharp releases would move the
+ * output of every textured asset at once. `palette: false` matters most — sharp
+ * may quantize to a palette when it thinks that is smaller, which is both
+ * lossy and dependent on the encoder's own heuristics.
+ */
+async function encodePngFromRaw(raw: RawPixels): Promise<Uint8Array> {
+ const sharp = (await import('sharp')).default;
+ const out = await sharp(Buffer.from(raw.data.buffer, raw.data.byteOffset, raw.data.length), {
+ raw: { width: raw.width, height: raw.height, channels: raw.channels },
+ })
+ .png({ compressionLevel: 9, adaptiveFiltering: false, palette: false })
+ .toBuffer();
+ return new Uint8Array(out);
+}
+
+function hasTranslucentPixel(raw: RawPixels): boolean {
+ if (raw.channels !== 4) return false;
+ for (let i = 3; i < raw.data.length; i += 4) {
+ if ((raw.data[i] ?? 255) < 255) return true;
+ }
+ return false;
+}
+
+function isTexture(value: unknown): value is THREE.Texture {
+ return (value as THREE.Texture | undefined)?.isTexture === true;
+}
+
+/**
+ * Encode every bakeable texture in the scene in place, and report what happened.
+ *
+ * Mutates `texture.userData` (adding `encoded` + `kilnTexture`) rather than
+ * cloning, because the scene graph is handed straight to the bridge afterwards
+ * and a clone would have to be re-attached to every slot that referenced it —
+ * including the shared-texture case, where two materials point at one texture
+ * and must keep doing so for the bridge's texture cache to dedupe them.
+ *
+ * A texture reachable from several slots is encoded once. The first slot that
+ * reaches it decides the recorded `usage`, and slots are walked in a fixed
+ * order over a deterministically-sorted scene traversal, so the choice is
+ * stable across runs.
+ *
+ * @param root Scene root, traversed for meshes and their materials.
+ * @param warnings Appended to, one line per texture that could not be baked.
+ * @returns Provenance for each baked texture, sorted by name/slot.
+ */
+export async function bakeSceneTextures(
+ root: THREE.Object3D,
+ warnings: string[],
+): Promise<BakedTextureProvenanceV1[]> {
+ // Collect first, encode second: traversal is sync, encoding is not, and doing
+ // them together would interleave awaits with a mutating walk.
+ const pending: Array<{
+ texture: THREE.Texture;
+ material: string;
+ slot: string;
+ usage: TextureUsage;
+ }> = [];
+ const seen = new Set<THREE.Texture>();
+
+ root.traverse((node) => {
+ const material = (node as THREE.Mesh).material;
+ const materials = Array.isArray(material) ? material : material ? [material] : [];
+ for (const item of materials) {
+ const bag = item as unknown as Record<string, unknown>;
+ for (const [slot, usage] of SLOT_USAGE) {
+ const texture = bag[slot];
+ if (!isTexture(texture) || seen.has(texture)) continue;
+ seen.add(texture);
+ if ((texture.userData as Record<string, unknown>)['encoded']) continue;
+ pending.push({
+ texture,
+ material: item.name || '(unnamed material)',
+ slot,
+ usage,
+ });
+ }
+ }
+ });
+
+ const baked: BakedTextureProvenanceV1[] = [];
+ for (const entry of pending) {
+ const name = entry.texture.name || '(unnamed texture)';
+ const raw = readPixels(entry.texture);
+ if (typeof raw === 'string') {
+ warnings.push(
+ `Texture ${JSON.stringify(name)} on material ${JSON.stringify(entry.material)} (${entry.slot}) was dropped from the GLB: ${raw}.`,
+ );
+ continue;
+ }
+
+ let bytes: Uint8Array;
+ try {
+ bytes = await encodePngFromRaw(raw);
+ } catch (err) {
+ warnings.push(
+ `Texture ${JSON.stringify(name)} on material ${JSON.stringify(entry.material)} (${entry.slot}) was dropped from the GLB: PNG encoding failed (${err instanceof Error ? err.message : String(err)}).`,
+ );
+ continue;
+ }
+
+ (entry.texture.userData as Record<string, unknown>)['encoded'] = {
+ mime: 'image/png',
+ bytes,
+ } satisfies EncodedTextureData;
+ // Describe what the texture IS, not what the slot wants — QA compares this
+ // against `texture.colorSpace`, and reporting the slot's expectation here
+ // would make a mismatched color space pass by asserting itself.
+ (entry.texture.userData as Record<string, unknown>)['kilnTexture'] = {
+ usage: entry.usage,
+ colorSpace: entry.texture.colorSpace === THREE.SRGBColorSpace ? 'srgb' : 'linear',
+ width: raw.width,
+ height: raw.height,
+ hasAlpha: hasTranslucentPixel(raw),
+ } satisfies KilnTextureMetadata;
+
+ const recipe = (entry.texture.userData as Record<string, unknown>)['kilnProcedural'] as
+ | ProceduralRecipeRecord
+ | undefined;
+
+ baked.push({
+ schemaVersion: 1,
+ texture: name,
+ material: entry.material,
+ slot: entry.slot,
+ usage: entry.usage,
+ width: raw.width,
+ height: raw.height,
+ channels: raw.channels,
+ bytes: bytes.length,
+ sha1: createHash('sha1').update(bytes).digest('hex'),
+ ...(recipe ? { procedural: recipe } : {}),
+ });
+ }
+
+ return baked.sort((a, b) => `${a.texture}:${a.slot}`.localeCompare(`${b.texture}:${b.slot}`));
+}
+
+// -----------------------------------------------------------------------------
+// Tangents for normal-mapped meshes
+// -----------------------------------------------------------------------------
+
+/**
+ * Give every normal-mapped mesh a TANGENT attribute.
+ *
+ * A glTF material with a normal texture is supposed to ship tangents. Without
+ * them the Khronos validator raises `MESH_PRIMITIVE_GENERATED_TANGENT_SPACE`
+ * and each runtime invents its own tangent basis, so the same asset lights
+ * differently in different engines — the exact failure mode that makes a normal
+ * map look right in one viewer and subtly wrong in another.
+ *
+ * Measured on a procedural crate with a derived normal map: the GLB validated
+ * with that warning and no TANGENT accessor until this pass existed. The bridge
+ * already exports `geometry.attributes.tangent` when it is present; nothing was
+ * ever computing it.
+ *
+ * Runs only where it is needed — a mesh with no normal map does not pay for it,
+ * and the attribute changes the exported bytes, so computing it unconditionally
+ * would move every existing textured asset for no benefit.
+ *
+ * MikkTSpace is the gold standard and glTF's reference basis, but it is a
+ * separate WASM package. This engine is vendored into Studio as a tarball and
+ * installed into two container images by two different package managers, so a
+ * new native/WASM dependency is a real cost there — `computeTangentBasis` below
+ * implements the standard per-triangle formulation directly instead. three's
+ * own `computeTangents` used the same method before it was removed. If tangent
+ * seams ever show on a shipped asset, MikkTSpace is the upgrade path.
+ *
+ * @param root Scene root, traversed for meshes.
+ * @param warnings Appended to for each mesh that needs tangents but cannot get them.
+ * @returns Number of geometries that received a tangent attribute.
+ */
+/**
+ * Per-vertex tangent basis (Lengyel's method).
+ *
+ * Accumulates a tangent and bitangent per vertex from each triangle's position
+ * and UV deltas, then orthonormalizes the tangent against the vertex normal.
+ * The fourth component is the handedness the shader needs to rebuild the
+ * bitangent as `cross(normal, tangent.xyz) * tangent.w`.
+ *
+ * Triangles with degenerate UVs (zero area in texture space) contribute
+ * nothing rather than poisoning the accumulation with infinities.
+ */
+function computeTangentBasis(geometry: THREE.BufferGeometry): void {
+ const index = geometry.getIndex();
+ const position = geometry.getAttribute('position');
+ const normal = geometry.getAttribute('normal');
+ const uv = geometry.getAttribute('uv');
+ if (!index || !position || !normal || !uv) {
+ throw new Error('position, normal, uv, and an index are all required');
+ }
+
+ const vertexCount = position.count;
+ const tan1 = new Float32Array(vertexCount * 3);
+ const tan2 = new Float32Array(vertexCount * 3);
+
+ for (let i = 0; i < index.count; i += 3) {
+ const a = index.getX(i);
+ const b = index.getX(i + 1);
+ const c = index.getX(i + 2);
+
+ const x1 = position.getX(b) - position.getX(a);
+ const y1 = position.getY(b) - position.getY(a);
+ const z1 = position.getZ(b) - position.getZ(a);
+ const x2 = position.getX(c) - position.getX(a);
+ const y2 = position.getY(c) - position.getY(a);
+ const z2 = position.getZ(c) - position.getZ(a);
+
+ const s1 = uv.getX(b) - uv.getX(a);
+ const t1 = uv.getY(b) - uv.getY(a);
+ const s2 = uv.getX(c) - uv.getX(a);
+ const t2 = uv.getY(c) - uv.getY(a);
+
+ const det = s1 * t2 - s2 * t1;
+ if (det === 0 || !Number.isFinite(det)) continue;
+ const r = 1 / det;
+
+ const sdx = (t2 * x1 - t1 * x2) * r;
+ const sdy = (t2 * y1 - t1 * y2) * r;
+ const sdz = (t2 * z1 - t1 * z2) * r;
+ const tdx = (s1 * x2 - s2 * x1) * r;
+ const tdy = (s1 * y2 - s2 * y1) * r;
+ const tdz = (s1 * z2 - s2 * z1) * r;
+
+ for (const v of [a, b, c]) {
+ const o = v * 3;
+ tan1[o] = (tan1[o] ?? 0) + sdx;
+ tan1[o + 1] = (tan1[o + 1] ?? 0) + sdy;
+ tan1[o + 2] = (tan1[o + 2] ?? 0) + sdz;
+ tan2[o] = (tan2[o] ?? 0) + tdx;
+ tan2[o + 1] = (tan2[o + 1] ?? 0) + tdy;
+ tan2[o + 2] = (tan2[o + 2] ?? 0) + tdz;
+ }
+ }
+
+ const out = new Float32Array(vertexCount * 4);
+ const n = new THREE.Vector3();
+ const t = new THREE.Vector3();
+ const tmp = new THREE.Vector3();
+ const tmp2 = new THREE.Vector3();
+
+ for (let v = 0; v < vertexCount; v++) {
+ n.set(normal.getX(v), normal.getY(v), normal.getZ(v));
+ t.set(tan1[v * 3]!, tan1[v * 3 + 1]!, tan1[v * 3 + 2]!);
+
+ // A vertex touched only by degenerate triangles has no tangent to
+ // orthogonalize; give it any vector perpendicular to the normal so the
+ // attribute stays well-formed instead of holding NaN.
+ if (t.lengthSq() === 0) {
+ t.set(1, 0, 0);
+ if (Math.abs(n.x) > 0.9) t.set(0, 1, 0);
+ }
+
+ // Gram-Schmidt: remove the component along the normal, then normalize.
+ tmp.copy(t).sub(tmp2.copy(n).multiplyScalar(n.dot(t)));
+ if (tmp.lengthSq() === 0) tmp.set(1, 0, 0);
+ tmp.normalize();
+
+ tmp2.set(tan2[v * 3]!, tan2[v * 3 + 1]!, tan2[v * 3 + 2]!);
+ const w = n.clone().cross(t).dot(tmp2) < 0 ? -1 : 1;
+
+ out[v * 4] = tmp.x;
+ out[v * 4 + 1] = tmp.y;
+ out[v * 4 + 2] = tmp.z;
+ out[v * 4 + 3] = w;
+ }
+
+ geometry.setAttribute('tangent', new THREE.BufferAttribute(out, 4));
+}
+
+export function ensureNormalMapTangents(root: THREE.Object3D, warnings: string[]): number {
+ let count = 0;
+ const done = new Set<THREE.BufferGeometry>();
+
+ root.traverse((node) => {
+ const mesh = node as THREE.Mesh;
+ if (!mesh.isMesh) return;
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
+ const needsTangents = materials.some(
+ (m) => (m as THREE.MeshStandardMaterial | undefined)?.normalMap,
+ );
+ if (!needsTangents) return;
+
+ const geometry = mesh.geometry;
+ if (!geometry || done.has(geometry) || geometry.getAttribute('tangent')) return;
+ done.add(geometry);
+
+ const name = mesh.name || '(unnamed mesh)';
+ if (!geometry.getIndex()) {
+ warnings.push(
+ `Mesh ${JSON.stringify(name)} uses a normal map but its geometry is not indexed, so tangents could not be computed. Each runtime will generate its own tangent basis and the surface may light differently across engines.`,
+ );
+ return;
+ }
+ if (!geometry.getAttribute('uv')) {
+ warnings.push(
+ `Mesh ${JSON.stringify(name)} uses a normal map but has no UV coordinates, so tangents could not be computed — and the normal map cannot be sampled either. Unwrap it first: mesh.geometry = await autoUnwrap(mesh.geometry).`,
+ );
+ return;
+ }
+ if (!geometry.getAttribute('normal')) geometry.computeVertexNormals();
+
+ try {
+ computeTangentBasis(geometry);
+ count++;
+ } catch (err) {
+ warnings.push(
+ `Mesh ${JSON.stringify(name)} uses a normal map but tangents could not be computed (${err instanceof Error ? err.message : String(err)}). Each runtime will generate its own tangent basis.`,
+ );
+ }
+ });
+
+ return count;
+}
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index e679d430..efb83275 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -96,6 +96,58 @@ const screenshotInput = z.object({
code: z.string().describe('Kiln source code to execute and render to a six-view image grid.'),
});
+/**
+ * `kiln_render` (unified surface only) additionally accepts a capture config.
+ * Kept off the shared `renderInput` on purpose: the four-tool baseline's
+ * metrics-only `kiln_render` produces no image, so a grid shape would be a
+ * meaningless argument there and would change that schema for no reason.
+ */
+const captureInput = z
+ .object({
+ preset: z
+ .enum(['1x1', '1x2', '2x1', '3x1', '2x2', '3x2', '3x3'])
+ .optional()
+ .describe(
+ 'Grid shape as COLSxROWS. Default 3x2 (the six-view contact sheet). Use a smaller grid ' +
+ 'for a simple or symmetric object where six cells repeat each other, and 3x3 when you ' +
+ 'genuinely need more angles than six.',
+ ),
+ cells: z
+ .array(
+ z.object({
+ azimuthDeg: z.number().describe('0 = front, 90 = right, 180 = back, 270 = left. Wraps.'),
+ elevationDeg: z
+ .number()
+ .describe(
+ '0 = eye level, positive looks down, negative from below. Clamped to -89..89.',
+ ),
+ zoom: z
+ .number()
+ .optional()
+ .describe(
+ 'Padding multiplier around the asset bounds for this cell only. Omit for the ' +
+ 'default framing; below 1 crops in, above 1 pulls back.',
+ ),
+ name: z
+ .string()
+ .optional()
+ .describe('Cell label. Auto-derived from the angles if omitted.'),
+ }),
+ )
+ .optional()
+ .describe(
+ 'One camera per cell, in row-major order. Omit to use the preset default cameras. ' +
+ 'Must not exceed the preset capacity (max 9 overall).',
+ ),
+ })
+ .optional()
+ .describe(
+ 'Optional. Choose the contact-sheet shape and cameras. Omit it entirely for the standard ' +
+ 'six-view 3x2 grid, which is the right default for most assets.',
+ );
+
+const renderViewsInput = renderInput.extend({ capture: captureInput });
+
const screenshotAnimationInput = z.object({
code: z
.string()
@@ -308,8 +360,10 @@ async function runRender(
export interface KilnScreenshotResult {
ok: boolean;
- /** View names in grid order (row-major): Front, Right, Back, Left, Top, 3/4. */
+ /** View names in grid order (row-major). Defaults to Front, Right, Back, Left, Top, 3/4. */
views?: string[];
+ /** Grid shape actually rendered — echoes the capture config back, or `3x2` by default. */
+ capture?: { preset: string; cols: number; cells: number };
width?: number;
height?: number;
/** The 3x2 grid PNG, base64-encoded (transports with image support strip this and attach the bytes). */
@@ -332,6 +386,8 @@ async function runScreenshot(
const { renderViewGrid } = await import('../views');
const { root } = await executeKilnCode(input.code);
const warnings = inspectSceneStructure(root, { category: trustedCategory(context) });
+ // No capture config here on purpose: kiln_screenshot belongs to the frozen
+ // four-tool baseline, whose schemas stay byte-for-byte unchanged.
const grid = await renderViewGrid(root);
return {
ok: true,
@@ -374,8 +430,10 @@ export interface KilnRenderViewsResult {
instanceability?: { grade: string; summary: string };
/** Structured deterministic report; five dimensions remain separate. */
qaReport?: AssetQaReportV1;
- /** View names in grid order (row-major): Front, Right, Back, Left, Top, 3/4. */
+ /** View names in grid order (row-major). Defaults to Front, Right, Back, Left, Top, 3/4. */
views?: string[];
+ /** Grid shape actually rendered — echoes the capture config back, or `3x2` by default. */
+ capture?: { preset: string; cols: number; cells: number };
gridWidth?: number;
gridHeight?: number;
/** The 3x2 grid PNG, base64-encoded (transports with image support strip this and attach the bytes). */
@@ -395,7 +453,7 @@ export interface KilnRenderViewsResult {
* bundle graph.
*/
async function runRenderViews(
- input: z.infer<typeof renderInput>,
+ input: z.infer<typeof renderViewsInput>,
context: KilnToolContext,
): Promise<KilnRenderViewsResult> {
try {
@@ -412,7 +470,7 @@ async function runRenderViews(
...(category ? { category } : {}),
...(context.intent ? { intent: context.intent } : {}),
});
- const grid = await renderViewGrid(root);
+ const grid = await renderViewGrid(root, input.capture ? { capture: input.capture } : {});
const warnings = [...structuralWarnings, ...rendered.warnings];
@@ -432,6 +490,7 @@ async function runRenderViews(
}
: {}),
views: grid.views,
+ ...(grid.capture ? { capture: grid.capture } : {}),
gridWidth: grid.width,
gridHeight: grid.height,
pngBase64: grid.png.toString('base64'),
@@ -458,6 +517,15 @@ const KILN_RENDER_VIEWS_DESCRIPTION =
'Row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); ' +
'row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). ' +
'Use it to confirm the model builds and to verify orientation (+X forward), attachment (no floating parts), proportion, and silhouette. ' +
+ 'That default grid is right for most assets — omit `capture` and you get it. ' +
+ 'Pass `capture` when the default is a poor fit: `{preset:"2x2"}` or `{preset:"1x1"}` for a simple ' +
+ 'or symmetric object whose six cells just repeat each other (fewer, larger cells read better), ' +
+ '`{preset:"3x3"}` when six angles genuinely are not enough. ' +
+ 'For full control give `capture.cells` — one camera per cell in row-major order, each ' +
+ '{azimuthDeg, elevationDeg, zoom?}: azimuth 0 = front, 90 = right, 180 = back, 270 = left; ' +
+ 'elevation 0 = eye level, positive looks down. Use it to aim every cell at what actually needs ' +
+ 'checking — a seam, an underside, a joint the standard six leave occluded — instead of spending ' +
+ 'cells on angles that show nothing. Max 9 cells. The reply echoes the grid shape it rendered. ' +
'If the build fails you get an error and NO image — fix the code and render again. Flat-shaded CPU render; writes no files.';
/** Create the unified render/view definition with host-owned QA context. */
@@ -465,8 +533,8 @@ export function createKilnRenderViewsDef(context: KilnToolContext = {}): KilnToo
return {
name: 'kiln_render',
description: KILN_RENDER_VIEWS_DESCRIPTION,
- inputSchema: renderInput,
- run: async (input) => runRenderViews(renderInput.parse(input), context),
+ inputSchema: renderViewsInput,
+ run: async (input) => runRenderViews(renderViewsInput.parse(input), context),
media: screenshotMedia,
};
}
@@ -731,7 +799,25 @@ const inspectInput = z.object({
view: z
.string()
.optional()
- .describe('Camera angle: front, right, back, left, top, or three-quarter (default).'),
+ .describe(
+ 'Camera angle: front, right, back, left, top, or three-quarter (default). Ignored when ' +
+ 'azimuthDeg or elevationDeg is given.',
+ ),
+ azimuthDeg: z
+ .number()
+ .optional()
+ .describe(
+ 'Orbit the camera around the asset: 0 = front, 90 = right, 180 = back, 270 = left. Wraps, ' +
+ 'so 315 and -45 are the same. Use it to look between the named views — at a corner, a ' +
+ 'seam, or whatever angle the last render left ambiguous.',
+ ),
+ elevationDeg: z
+ .number()
+ .optional()
+ .describe(
+ 'Orbit the camera up or down: 0 = eye level, positive looks down from above, negative from ' +
+ 'below. Clamped to -89..89. Combine with azimuthDeg for any three-quarter angle you want.',
+ ),
zoom: z
.number()
.optional()
@@ -754,6 +840,9 @@ export interface KilnInspectResult {
/** Resolved part name that was framed (absent when the whole asset was framed). */
part?: string;
view?: string;
+ /** Orbit angles actually rendered — reported for named cameras too. */
+ azimuthDeg?: number;
+ elevationDeg?: number;
zoom?: number;
/** True when everything outside the framed part was hidden (isolate honored). */
isolated?: boolean;
@@ -783,6 +872,8 @@ async function runInspect(input: z.infer<typeof inspectInput>): Promise<KilnInsp
const r = renderInspectView(root, {
...(input.part !== undefined ? { part: input.part } : {}),
...(input.view !== undefined ? { view: input.view } : {}),
+ ...(input.azimuthDeg !== undefined ? { azimuthDeg: input.azimuthDeg } : {}),
+ ...(input.elevationDeg !== undefined ? { elevationDeg: input.elevationDeg } : {}),
...(input.zoom !== undefined ? { zoom: input.zoom } : {}),
...(input.isolate !== undefined ? { isolate: input.isolate } : {}),
});
@@ -795,16 +886,21 @@ async function runInspect(input: z.infer<typeof inspectInput>): Promise<KilnInsp
availableParts: r.availableParts,
};
}
+ // Always state the angles, named camera or not, so the model can step from
+ // where it actually is instead of guessing the next view by name.
+ const from = `the ${r.view} view (azimuth ${r.azimuthDeg}deg, elevation ${r.elevationDeg}deg)`;
const framed = r.part
- ? `Framed part "${r.part}" (with its descendants) from the ${r.view} view at zoom ${r.zoom}.` +
+ ? `Framed part "${r.part}" (with its descendants) from ${from} at zoom ${r.zoom}.` +
(r.isolated
? ' Everything else is hidden, so nothing in this image occludes it.'
: ' Surrounding geometry is still drawn and may occlude it.')
- : `Framed the whole asset from the ${r.view} view.`;
+ : `Framed the whole asset from ${from}.`;
return {
ok: true,
...(r.part ? { part: r.part } : {}),
view: r.view,
+ azimuthDeg: r.azimuthDeg,
+ elevationDeg: r.elevationDeg,
zoom: r.zoom,
isolated: r.isolated,
framed,
@@ -830,8 +926,13 @@ const KILN_INSPECT_DESCRIPTION =
'from one camera. Use it after kiln_render reveals a suspect region — a floating part, a bad ' +
'joint, a wrong proportion — to see fine detail one grid cell cannot show. args: part (omit to ' +
'frame the whole asset in one large view), view (front/right/back/left/top/three-quarter, ' +
- 'default three-quarter), zoom (padding multiplier around the part bounds, 1 = tight crop up to ' +
- '4 = wide context, default 1.2), isolate (hide everything except that part, default false). ' +
+ 'default three-quarter), azimuthDeg + elevationDeg (orbit to ANY angle instead of a named view: ' +
+ 'azimuth 0 = front, 90 = right, 180 = back, 270 = left; elevation 0 = eye level, positive looks ' +
+ 'down, clamped to -89..89), zoom (padding multiplier around the part bounds, 1 = tight crop up ' +
+ 'to 4 = wide context, default 1.2), isolate (hide everything except that part, default false). ' +
+ 'Reach for the orbit angles when a named view puts the thing you need to judge edge-on or ' +
+ 'behind something — the reply always tells you the azimuth/elevation it used, so you can step ' +
+ 'from there. ' +
'If the part name does not resolve you get the list of available part names back — pick one and ' +
'retry. By default surrounding geometry stays visible for context and can occlude the part: ' +
'either pick a different view, or set isolate:true to hide everything else and see the part ' +
diff --git a/src/uv.ts b/src/uv.ts
index eac73422..4bc3e0a5 100644
--- a/src/uv.ts
+++ b/src/uv.ts
@@ -121,6 +121,21 @@ export async function autoUnwrap(
if (!posAttr || !idxAttr) {
throw new Error('autoUnwrap: geometry requires position attribute and an index');
}
+ // T2.4: measured — xatlas accepts an empty mesh and returns an empty atlas
+ // without complaint, so a zero-triangle geometry used to come back with zero
+ // vertices and NO uv attribute, and the failure only surfaced later as a
+ // texture that would not appear. The realistic upstream cause is a CSG result
+ // that collapsed to nothing.
+ if (idxAttr.count === 0 || posAttr.count === 0) {
+ throw new Error(
+ 'autoUnwrap: geometry has no triangles. Nothing can be unwrapped — check the operation that produced it (an empty CSG result is the usual cause).',
+ );
+ }
+ if (idxAttr.count % 3 !== 0) {
+ throw new Error(
+ `autoUnwrap: geometry has ${idxAttr.count} indices, which is not a whole number of triangles.`,
+ );
+ }
xa.createAtlas();
@@ -174,6 +189,12 @@ export async function autoUnwrap(
// Atlas metadata lives on userData so downstream tools (texture baking,
// projection painting) can sample the atlas resolution.
+ //
+ // T2.4 — read `width`/`height`, do NOT assume `resolution` squared. `resolution`
+ // is an upper bound xatlas packs within, not the atlas it returns: a CSG'd box
+ // at resolution 1024 measured 917x1085. A baker that allocated a square
+ // `resolution x resolution` target would sample the wrong texels along one
+ // axis, which reads as a subtle uniform stretch rather than an obvious break.
out.userData['atlas'] = {
width: result.width,
height: result.height,
@@ -182,6 +203,16 @@ export async function autoUnwrap(
if (!out.getAttribute('normal')) out.computeVertexNormals();
+ // xatlas can pack every chart and still hand back a mesh with no coords1 when
+ // the input degenerates. Better to say so than to return a geometry whose
+ // missing `uv` only shows up as an untextured surface much later.
+ if (!out.getAttribute('uv')) {
+ xa.destroyAtlas();
+ throw new Error(
+ 'autoUnwrap: xatlas produced no UV coordinates for this geometry (degenerate or zero-area triangles?).',
+ );
+ }
+
xa.destroyAtlas();
return out;
}
diff --git a/src/views/__tests__/capture.test.ts b/src/views/__tests__/capture.test.ts
new file mode 100644
index 00000000..e9051c4d
--- /dev/null
+++ b/src/views/__tests__/capture.test.ts
@@ -0,0 +1,315 @@
+/**
+ * Capture configuration (T3.2) — model-chosen grid shape and per-cell cameras.
+ *
+ * The first test is the contract everything else rests on: omitting `capture`
+ * must produce byte-identical output to the shipped 3x2 contact sheet. The
+ * rest is new surface.
+ */
+
+import { describe, expect, it } from 'bun:test';
+import {
+ CAPTURE_PRESETS,
+ CaptureConfigError,
+ DEFAULT_CAPTURE_PRESET,
+ MAX_CAPTURE_CELLS,
+ captureCellLabel,
+ describeCapture,
+ resolveCapture,
+ resolveGridCapture,
+} from '../capture';
+import { GRID_BACKGROUND_HEX, GRID_BACKGROUND_RGB } from '../background';
+import { SIX_VIEWS, SIX_VIEWS_REAR_QUARTER, orbitAnglesOf } from '../raster';
+import { renderViewGrid } from '../index';
+import { boxGeo, createPart, createRoot, cylinderGeo, gameMaterial } from '../../primitives';
+
+function scene(): unknown {
+ const root = createRoot('Rig');
+ const steel = gameMaterial(0x99a0aa);
+ createPart('Body', boxGeo(1.4, 0.5, 0.8), steel, { parent: root });
+ createPart('Mast', cylinderGeo(0.08, 0.08, 1.2, 12), steel, {
+ position: [0.5, 0.7, 0],
+ parent: root,
+ });
+ return root;
+}
+
+describe('resolveCapture', () => {
+ it('an omitted config resolves to the shipped six-view 3x2 by identity', () => {
+ for (const cfg of [undefined, {}]) {
+ const r = resolveCapture(cfg);
+ expect(r.preset).toBe(DEFAULT_CAPTURE_PRESET);
+ expect(r.cols).toBe(3);
+ expect(r.isDefault).toBe(true);
+ // Identity, not a copy: a future edit to SIX_VIEWS cannot desynchronise
+ // the default grid from the six-view set.
+ expect(r.views).toBe(SIX_VIEWS);
+ expect(r.zooms.every((z) => z === undefined)).toBe(true);
+ }
+ });
+
+ it('every preset yields a cell count that fits its own grid', () => {
+ const capacity: Record<string, [number, number]> = {
+ '1x1': [1, 1],
+ '1x2': [1, 2],
+ '2x1': [2, 2],
+ '3x1': [3, 3],
+ '2x2': [2, 4],
+ '3x2': [3, 6],
+ '3x3': [3, 9],
+ };
+ for (const preset of CAPTURE_PRESETS) {
+ const r = resolveCapture({ preset });
+ const [cols, cells] = capacity[preset]!;
+ expect(r.cols).toBe(cols);
+ expect(r.views).toHaveLength(cells);
+ expect(r.zooms).toHaveLength(cells);
+ }
+ });
+
+ it('a single cell is the 3/4 view, not a flat elevation', () => {
+ // One orthographic elevation reads as a rectangle for most assets; the
+ // quarter view carries depth, proportion and silhouette at once.
+ const r = resolveCapture({ preset: '1x1' });
+ expect(r.views[0]!.name).toBe('3/4');
+ });
+
+ it('explicit cells become orbit cameras with auto labels', () => {
+ const r = resolveCapture({
+ cells: [
+ { azimuthDeg: 0, elevationDeg: 0 },
+ { azimuthDeg: 210, elevationDeg: -25 },
+ ],
+ });
+ // No preset given: the tightest one that fits (2 cells -> 1x2).
+ expect(r.preset).toBe('1x2');
+ expect(r.views).toHaveLength(2);
+ expect(r.isDefault).toBe(false);
+
+ const a = orbitAnglesOf(r.views[0]!.dir);
+ expect(a.azimuthDeg).toBeCloseTo(0, 1);
+ const b = orbitAnglesOf(r.views[1]!.dir);
+ expect(b.azimuthDeg).toBeCloseTo(210, 1);
+ expect(b.elevationDeg).toBeCloseTo(-25, 1);
+ expect(r.views[1]!.name).toBe('A210 D25');
+ });
+
+ it('an explicit preset is honoured even when the cells would fit a smaller one', () => {
+ const r = resolveCapture({
+ preset: '3x3',
+ cells: [{ azimuthDeg: 0, elevationDeg: 0 }],
+ });
+ expect(r.preset).toBe('3x3');
+ expect(r.cols).toBe(3);
+ expect(r.views).toHaveLength(1);
+ });
+
+ it('a custom cell name is used verbatim (upper-cased for the bitmap font)', () => {
+ const r = resolveCapture({ cells: [{ azimuthDeg: 10, elevationDeg: 5, name: 'seam' }] });
+ expect(r.views[0]!.name).toBe('SEAM');
+ });
+
+ it('rejects the mistakes a model actually makes, with an actionable message', () => {
+ expect(() => resolveCapture({ preset: '4x4' as never })).toThrow(CaptureConfigError);
+ expect(() => resolveCapture({ preset: '4x4' as never })).toThrow(/must be one of/);
+
+ expect(() => resolveCapture({ cells: [] })).toThrow(/non-empty array/);
+
+ const tooMany = Array.from({ length: MAX_CAPTURE_CELLS + 1 }, (_, i) => ({
+ azimuthDeg: i * 20,
+ elevationDeg: 0,
+ }));
+ expect(() => resolveCapture({ cells: tooMany })).toThrow(/maximum is 9/);
+
+ expect(() => resolveCapture({ preset: '2x2', cells: tooMany.slice(0, 6) })).toThrow(
+ /holds 4 cells but 6 were given/,
+ );
+
+ expect(() => resolveCapture({ cells: [{ azimuthDeg: Number.NaN, elevationDeg: 0 }] })).toThrow(
+ /finite azimuthDeg and elevationDeg/,
+ );
+ expect(() => resolveCapture({ cells: [{ azimuthDeg: 0, elevationDeg: 0, zoom: 0 }] })).toThrow(
+ /zoom must be a positive number/,
+ );
+ });
+});
+
+describe('resolveGridCapture', () => {
+ // T3.3: the one precedence rule both grid producers (CPU rasterizer and GPU
+ // render port) share. If they disagreed, a run's artifact would change shape
+ // depending on whether a GPU happened to be reachable.
+ const KEY = 'KILN_GRID_VARIANT';
+
+ it('with no config, the env variant selects the default cameras', () => {
+ const plain = resolveGridCapture(undefined, undefined);
+ expect(plain.views).toBe(SIX_VIEWS);
+ expect(plain.preset).toBe('3x2');
+
+ const rear = resolveGridCapture(undefined, 'rear-quarter');
+ expect(rear.views).toBe(SIX_VIEWS_REAR_QUARTER);
+ expect(rear.cols).toBe(3);
+ // Still the shipped shape — the variant swaps cameras, not the layout.
+ expect(rear.preset).toBe('3x2');
+
+ // An unknown variant can never change what the agent sees, and keeps the
+ // exact array identity the byte-identity tests pin.
+ expect(resolveGridCapture(undefined, 'nonsense').views).toBe(SIX_VIEWS);
+ });
+
+ it('an explicit config wins over the env variant instead of being rewritten by it', () => {
+ const r = resolveGridCapture({ preset: '3x2' }, 'rear-quarter');
+ expect(r.views).toBe(SIX_VIEWS);
+ const cells = resolveGridCapture(
+ { cells: [{ azimuthDeg: 12, elevationDeg: 0 }] },
+ 'rear-quarter',
+ );
+ expect(cells.views).toHaveLength(1);
+ expect(orbitAnglesOf(cells.views[0]!.dir).azimuthDeg).toBeCloseTo(12, 1);
+ });
+
+ it('renderViewGrid reads the env through this same helper', async () => {
+ const saved = process.env[KEY];
+ try {
+ process.env[KEY] = 'rear-quarter';
+ const g = await renderViewGrid(scene(), { size: 32 });
+ expect(g.views).toEqual(SIX_VIEWS_REAR_QUARTER.map((v) => v.name));
+ // An explicit capture is NOT rewritten by the env.
+ const explicit = await renderViewGrid(scene(), { size: 32, capture: { preset: '3x2' } });
+ expect(explicit.views).toEqual(SIX_VIEWS.map((v) => v.name));
+ } finally {
+ if (saved === undefined) delete process.env[KEY];
+ else process.env[KEY] = saved;
+ }
+ });
+});
+
+describe('grid background', () => {
+ it('the hex and rgb forms are the same color', () => {
+ // The GPU render port sends the hex; the rasterizer clears to the rgb. They
+ // drifted once (#202225 vs #1a1a1a) and the sheet's backdrop depended on
+ // whether a serverless worker was warm.
+ const [r, g, b] = GRID_BACKGROUND_RGB;
+ expect(GRID_BACKGROUND_HEX).toBe(
+ `#${[r, g, b].map((c) => c.toString(16).padStart(2, '0')).join('')}`,
+ );
+ });
+});
+
+describe('captureCellLabel', () => {
+ it('uses only glyphs the 3x5 bitmap font has', () => {
+ // There is no '-' glyph: a minus would render as a blank box, so sign is
+ // carried by U/D instead.
+ const labels = [
+ captureCellLabel(0, 0),
+ captureCellLabel(45, 30),
+ captureCellLabel(200, -15),
+ captureCellLabel(-45, -89),
+ captureCellLabel(720, 0),
+ ];
+ expect(labels).toEqual(['A0 U0', 'A45 U30', 'A200 D15', 'A315 D89', 'A0 U0']);
+ for (const l of labels) expect(l).toMatch(/^[A-Z0-9 ]+$/);
+ });
+});
+
+describe('describeCapture', () => {
+ it('reports the grid in the same coordinates the model steers with', () => {
+ const text = describeCapture(resolveCapture({ preset: '2x1' }));
+ expect(text).toContain('2x1 grid');
+ expect(text).toContain('2 cells');
+ expect(text).toMatch(/az \d/);
+ expect(describeCapture(resolveCapture({ preset: '1x1' }))).toContain('1 cell:');
+ });
+});
+
+describe('renderViewGrid capture', () => {
+ it('BYTE-IDENTITY: no capture config renders exactly the shipped grid', async () => {
+ const base = await renderViewGrid(scene(), { size: 64 });
+ const explicitDefault = await renderViewGrid(scene(), { size: 64, capture: {} });
+ const explicit3x2 = await renderViewGrid(scene(), { size: 64, capture: { preset: '3x2' } });
+
+ expect(Buffer.from(explicitDefault.png).equals(Buffer.from(base.png))).toBe(true);
+ expect(Buffer.from(explicit3x2.png).equals(Buffer.from(base.png))).toBe(true);
+ expect(base.views).toEqual(['Front', 'Right', 'Back', 'Left', 'Top', '3/4']);
+ expect(base.capture).toEqual({ preset: '3x2', cols: 3, cells: 6 });
+ });
+
+ it('each preset composites to the right pixel dimensions', async () => {
+ // width = cols*size + (cols+1)*PAD, height = rows*size + (rows+1)*PAD, PAD = 4.
+ const size = 32;
+ const expected: Record<string, [number, number]> = {
+ '1x1': [1, 1],
+ '1x2': [1, 2],
+ '2x1': [2, 1],
+ '3x1': [3, 1],
+ '2x2': [2, 2],
+ '3x2': [3, 2],
+ '3x3': [3, 3],
+ };
+ for (const preset of CAPTURE_PRESETS) {
+ const g = await renderViewGrid(scene(), { size, capture: { preset } });
+ const [cols, rows] = expected[preset]!;
+ expect(g.width).toBe(cols * size + (cols + 1) * 4);
+ expect(g.height).toBe(rows * size + (rows + 1) * 4);
+ expect(g.capture!.preset).toBe(preset);
+ expect(g.capture!.cols).toBe(cols);
+ }
+ });
+
+ it('custom cells actually change the rendered pixels and the reported names', async () => {
+ const a = await renderViewGrid(scene(), {
+ size: 48,
+ capture: { cells: [{ azimuthDeg: 0, elevationDeg: 0 }] },
+ });
+ const b = await renderViewGrid(scene(), {
+ size: 48,
+ capture: { cells: [{ azimuthDeg: 90, elevationDeg: 40 }] },
+ });
+ expect(a.views).toEqual(['A0 U0']);
+ expect(b.views).toEqual(['A90 U40']);
+ expect(Buffer.from(b.png).equals(Buffer.from(a.png))).toBe(false);
+ });
+
+ it('per-cell zoom changes framing, and omitting it keeps the default path', async () => {
+ const plain = await renderViewGrid(scene(), {
+ size: 48,
+ capture: { cells: [{ azimuthDeg: 30, elevationDeg: 20 }] },
+ });
+ const zoomed = await renderViewGrid(scene(), {
+ size: 48,
+ capture: { cells: [{ azimuthDeg: 30, elevationDeg: 20, zoom: 3 }] },
+ });
+ expect(Buffer.from(zoomed.png).equals(Buffer.from(plain.png))).toBe(false);
+
+ // zoom on ONE cell must not disturb the framing of a cell without it —
+ // but both share one measured scene box, so this also pins that only the
+ // zoomed cell takes the frameBounds path.
+ const mixed = await renderViewGrid(scene(), {
+ size: 48,
+ capture: {
+ preset: '2x1',
+ cells: [
+ { azimuthDeg: 30, elevationDeg: 20 },
+ { azimuthDeg: 30, elevationDeg: 20, zoom: 3 },
+ ],
+ },
+ });
+ expect(mixed.views).toHaveLength(2);
+ expect(mixed.capture!.cols).toBe(2);
+ });
+
+ it('an explicit views[] still wins over capture, so internal callers are unaffected', async () => {
+ const g = await renderViewGrid(scene(), {
+ size: 32,
+ views: [SIX_VIEWS[0]!],
+ capture: { preset: '3x3' },
+ });
+ expect(g.views).toEqual(['Front']);
+ // The preset still drives the column count; only the cameras are overridden.
+ expect(g.capture!.preset).toBe('3x3');
+ });
+
+ it('a bad capture config throws rather than rendering something wrong', async () => {
+ await expect(
+ renderViewGrid(scene(), { size: 32, capture: { preset: 'nope' as never } }),
+ ).rejects.toThrow(CaptureConfigError);
+ });
+});
diff --git a/src/views/__tests__/orbit.test.ts b/src/views/__tests__/orbit.test.ts
new file mode 100644
index 00000000..4dee9220
--- /dev/null
+++ b/src/views/__tests__/orbit.test.ts
@@ -0,0 +1,228 @@
+/**
+ * Object-relative orbit camera (T3.1) — `orbitDir` / `orbitAnglesOf` and the
+ * `kiln_inspect` angles.
+ *
+ * The load-bearing assertion is the FIRST one: omitting both orbit angles must
+ * reproduce the previous output byte-for-byte. Everything else here is new
+ * surface; that test is the guarantee that adding it moved nothing.
+ */
+
+import { describe, expect, it } from 'bun:test';
+import {
+ MAX_ELEVATION_DEG,
+ MIN_ELEVATION_DEG,
+ SIX_VIEWS,
+ orbitAnglesOf,
+ orbitDir,
+} from '../raster';
+import { renderInspectView } from '../inspect';
+import { boxGeo, createPart, createRoot, cylinderGeo, gameMaterial } from '../../primitives';
+
+/** A small asymmetric scene — asymmetry is what makes a wrong angle visible. */
+function scene(): unknown {
+ const root = createRoot('Rig');
+ const steel = gameMaterial(0x99a0aa);
+ createPart('Body', boxGeo(1.4, 0.5, 0.8), steel, { position: [0, 0, 0], parent: root });
+ createPart('Mast', cylinderGeo(0.08, 0.08, 1.2, 12), steel, {
+ position: [0.5, 0.7, 0],
+ parent: root,
+ });
+ createPart('Fin', boxGeo(0.1, 0.4, 0.6), gameMaterial(0xcc5533), {
+ position: [-0.6, 0.4, 0],
+ parent: root,
+ });
+ return root;
+}
+
+const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) < eps;
+
+describe('orbitDir', () => {
+ it('reproduces the named grid cameras exactly where they are angle-expressible', () => {
+ // Front / Right / Back / Left are exact; this is what makes azimuth
+ // meaningful to a model that has only ever seen the named views.
+ const byName = Object.fromEntries(SIX_VIEWS.map((v) => [v.name, v.dir]));
+ const cases: Array<[string, number, number]> = [
+ ['Front', 0, 0],
+ ['Right', 90, 0],
+ ['Back', 180, 0],
+ ['Left', 270, 0],
+ ];
+ for (const [name, az, el] of cases) {
+ const got = orbitDir(az, el);
+ const want = byName[name]!;
+ for (let i = 0; i < 3; i++) {
+ expect(near(got[i]!, want[i]!, 1e-12)).toBe(true);
+ }
+ }
+ });
+
+ it('expresses the shipped 3/4 direction in orbit coordinates', () => {
+ // The 3/4 cell is [0.7, 0.5, 0.7] unnormalized. Round-trip it rather than
+ // hard-coding a rounded elevation: the point is that the named view IS
+ // reachable by angle, so the model can nudge away from it and back.
+ const threeQuarter = SIX_VIEWS.find((v) => v.name === '3/4')!.dir;
+ const { azimuthDeg, elevationDeg } = orbitAnglesOf(threeQuarter);
+ expect(azimuthDeg).toBeCloseTo(45, 6);
+ expect(elevationDeg).toBeCloseTo(26.8, 1);
+
+ const len = Math.hypot(threeQuarter[0], threeQuarter[1], threeQuarter[2]);
+ const want = threeQuarter.map((c) => c / len);
+ const got = orbitDir(azimuthDeg, elevationDeg);
+ for (let i = 0; i < 3; i++) expect(got[i]!).toBeCloseTo(want[i]!, 4);
+ });
+
+ it('returns unit vectors and wraps azimuth', () => {
+ for (const [az, el] of [
+ [0, 0],
+ [37, 12],
+ [-45, -60],
+ [721, 89],
+ ] as Array<[number, number]>) {
+ const d = orbitDir(az, el);
+ expect(Math.hypot(d[0], d[1], d[2])).toBeCloseTo(1, 10);
+ }
+ // -45 and 315 are the same camera; the tool description promises this.
+ const a = orbitDir(-45, 20);
+ const b = orbitDir(315, 20);
+ for (let i = 0; i < 3; i++) expect(a[i]!).toBeCloseTo(b[i]!, 12);
+ });
+
+ it('clamps elevation short of the poles so azimuth stays meaningful', () => {
+ const up = orbitDir(0, 500);
+ const down = orbitDir(0, -500);
+ expect(up).toEqual(orbitDir(0, MAX_ELEVATION_DEG));
+ expect(down).toEqual(orbitDir(0, MIN_ELEVATION_DEG));
+ // Not a degenerate pole: still has horizontal component to orient by.
+ expect(Math.hypot(up[0], up[2])).toBeGreaterThan(0.01);
+ // And azimuth still changes the camera at the clamp.
+ expect(orbitDir(90, 500)).not.toEqual(up);
+ });
+});
+
+describe('orbitAnglesOf', () => {
+ it('inverts orbitDir', () => {
+ for (const [az, el] of [
+ [0, 0],
+ [45, 26.79],
+ [123, -40],
+ [270, 15],
+ ] as Array<[number, number]>) {
+ const back = orbitAnglesOf(orbitDir(az, el));
+ expect(back.azimuthDeg).toBeCloseTo(az, 1);
+ expect(back.elevationDeg).toBeCloseTo(el, 1);
+ }
+ });
+
+ it('reports every named grid camera in [0, 360)', () => {
+ for (const v of SIX_VIEWS) {
+ const { azimuthDeg, elevationDeg } = orbitAnglesOf(v.dir);
+ expect(azimuthDeg).toBeGreaterThanOrEqual(0);
+ expect(azimuthDeg).toBeLessThan(360);
+ expect(elevationDeg).toBeGreaterThanOrEqual(-90);
+ expect(elevationDeg).toBeLessThanOrEqual(90);
+ }
+ expect(orbitAnglesOf([0, 0, -1]).azimuthDeg).toBe(270);
+ });
+});
+
+describe('kiln_inspect orbit', () => {
+ it('BYTE-IDENTITY: omitting the orbit angles renders exactly what it did before', () => {
+ // The whole compatibility claim for T3.1. If this drifts, every existing
+ // inspect call the model has learned to read has silently changed.
+ for (const view of ['front', 'right', 'back', 'left', 'top', 'three-quarter']) {
+ const before = renderInspectView(scene(), { view, size: 96 });
+ const after = renderInspectView(scene(), { view, size: 96 });
+ expect(before.ok && after.ok).toBe(true);
+ if (!before.ok || !after.ok) return;
+ expect(Buffer.from(after.png).equals(Buffer.from(before.png))).toBe(true);
+ expect(after.view).toBe(view);
+ }
+ });
+
+ it('reports the angles of a named camera without changing it', () => {
+ const r = renderInspectView(scene(), { view: 'right', size: 96 });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.view).toBe('right');
+ expect(r.azimuthDeg).toBeCloseTo(90, 1);
+ expect(r.elevationDeg).toBeCloseTo(0, 1);
+ });
+
+ it('an orbit at a named angle matches that named view pixel-for-pixel', () => {
+ // front is exactly (0, 0), so the two paths must agree completely. This is
+ // what lets the model treat the angles and the names as one coordinate
+ // system rather than two loosely-related ones.
+ const named = renderInspectView(scene(), { view: 'front', size: 96 });
+ const orbited = renderInspectView(scene(), { azimuthDeg: 0, elevationDeg: 0, size: 96 });
+ expect(named.ok && orbited.ok).toBe(true);
+ if (!named.ok || !orbited.ok) return;
+ expect(Buffer.from(orbited.png).equals(Buffer.from(named.png))).toBe(true);
+ expect(orbited.view).toBe('orbit');
+ });
+
+ it('a different angle actually renders a different image', () => {
+ const a = renderInspectView(scene(), { azimuthDeg: 0, elevationDeg: 0, size: 96 });
+ const b = renderInspectView(scene(), { azimuthDeg: 37, elevationDeg: 24, size: 96 });
+ expect(a.ok && b.ok).toBe(true);
+ if (!a.ok || !b.ok) return;
+ expect(Buffer.from(b.png).equals(Buffer.from(a.png))).toBe(false);
+ expect(b.azimuthDeg).toBeCloseTo(37, 1);
+ expect(b.elevationDeg).toBeCloseTo(24, 1);
+ });
+
+ it('either angle alone switches to orbit, with the other defaulting to 0', () => {
+ const azOnly = renderInspectView(scene(), { azimuthDeg: 90, size: 96 });
+ expect(azOnly.ok).toBe(true);
+ if (!azOnly.ok) return;
+ expect(azOnly.view).toBe('orbit');
+ expect(azOnly.elevationDeg).toBeCloseTo(0, 6);
+ // azimuth 90 elevation 0 IS the named right view.
+ const right = renderInspectView(scene(), { view: 'right', size: 96 });
+ if (!right.ok) return;
+ expect(Buffer.from(azOnly.png).equals(Buffer.from(right.png))).toBe(true);
+
+ const elOnly = renderInspectView(scene(), { elevationDeg: 45, size: 96 });
+ expect(elOnly.ok).toBe(true);
+ if (!elOnly.ok) return;
+ expect(elOnly.view).toBe('orbit');
+ expect(elOnly.azimuthDeg).toBeCloseTo(0, 6);
+ });
+
+ it('orbit angles override a named view rather than fighting it', () => {
+ const r = renderInspectView(scene(), { view: 'top', azimuthDeg: 180, size: 96 });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.view).toBe('orbit');
+ expect(r.azimuthDeg).toBeCloseTo(180, 1);
+ });
+
+ it('reports the clamped elevation, not the requested one', () => {
+ const r = renderInspectView(scene(), { azimuthDeg: 0, elevationDeg: 200, size: 96 });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.elevationDeg).toBeCloseTo(MAX_ELEVATION_DEG, 1);
+ });
+
+ it('orbit composes with part framing and isolate', () => {
+ const r = renderInspectView(scene(), {
+ part: 'Fin',
+ azimuthDeg: 120,
+ elevationDeg: 30,
+ isolate: true,
+ size: 96,
+ });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.part).toBe('Mesh_Fin');
+ expect(r.isolated).toBe(true);
+ expect(r.azimuthDeg).toBeCloseTo(120, 1);
+ });
+
+ it('an unresolved part still fails cleanly when orbit angles are supplied', () => {
+ const r = renderInspectView(scene(), { part: 'nope', azimuthDeg: 45 });
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.view).toBe('orbit');
+ expect(r.availableParts.length).toBeGreaterThan(0);
+ });
+});
diff --git a/src/views/annotate.ts b/src/views/annotate.ts
new file mode 100644
index 00000000..e61b4624
--- /dev/null
+++ b/src/views/annotate.ts
@@ -0,0 +1,108 @@
+/**
+ * Per-cell annotation shared by BOTH view-grid producers.
+ *
+ * A contact-sheet cell carries two pieces of context the pixels alone do not:
+ * which camera it is (`stampLabel`) and which way the world axes point from
+ * here (`stampAxisGnomon`). The CPU rasterizer stamped both; the GPU render
+ * port composited raw PNGs and stamped neither, so the model's visual context
+ * quietly lost its labels whenever a GPU happened to be reachable.
+ *
+ * That difference is not a useful degrade signal — `renderDegraded` and
+ * `viewsRendererId` report the producer as structured fields, which is where a
+ * consumer should read it from. So both producers now call
+ * {@link annotateViewCell}, and this module exists so they cannot drift: the
+ * label scale, the corner anchors and the gnomon basis are written once.
+ *
+ * Dependency-free apart from the bitmap font, so the grid compositor can import
+ * it without pulling in the rasterizer.
+ */
+
+import { stampLabel } from './pose';
+
+// H-30: kiln-frame axis gnomon colors (+X fwd red, +Y up green, +Z right blue).
+const GNOMON_AXES: Array<{
+ label: string;
+ axis: [number, number, number];
+ color: [number, number, number];
+}> = [
+ { label: 'X', axis: [1, 0, 0], color: [235, 80, 70] },
+ { label: 'Y', axis: [0, 1, 0], color: [90, 205, 90] },
+ { label: 'Z', axis: [0, 0, 1], color: [90, 145, 245] },
+];
+
+/**
+ * Stamp a small world-axis gnomon into a rasterized cell (bottom-left corner),
+ * using the SAME camera basis as rasterizeView so the arrows are exact
+ * (3DAxisPrompt: ticked/annotated axes measurably improve VLM 3D localization).
+ * Axes nearly perpendicular to the image plane (projected length < 0.25) are
+ * skipped — only in-plane axes disambiguate a view.
+ */
+export function stampAxisGnomon(rgb: Uint8Array, size: number, viewDir: readonly number[]): void {
+ // rasterizeView's basis, duplicated deliberately (raster.ts keeps it private).
+ const zl = Math.hypot(viewDir[0]!, viewDir[1]!, viewDir[2]!) || 1;
+ const z = [viewDir[0]! / zl, viewDir[1]! / zl, viewDir[2]! / zl] as const;
+ const up = Math.abs(z[1]) > 0.99 ? ([0, 0, -1] as const) : ([0, 1, 0] as const);
+ const cx = [
+ up[1] * z[2] - up[2] * z[1],
+ up[2] * z[0] - up[0] * z[2],
+ up[0] * z[1] - up[1] * z[0],
+ ];
+ const xl = Math.hypot(cx[0]!, cx[1]!, cx[2]!) || 1;
+ const bx = [cx[0]! / xl, cx[1]! / xl, cx[2]! / xl] as const;
+ const by = [
+ z[1] * bx[2] - z[2] * bx[1],
+ z[2] * bx[0] - z[0] * bx[2],
+ z[0] * bx[1] - z[1] * bx[0],
+ ] as const;
+
+ const len = Math.max(12, Math.round(size * 0.055));
+ // Inset the origin by the arrow length so leftward/downward projections
+ // (e.g. +Z in the Front view) aren't clipped at the cell edge.
+ const ox = len + 10;
+ const oy = size - len - 10;
+ for (const { label, axis, color } of GNOMON_AXES) {
+ const dx = axis[0] * bx[0] + axis[1] * bx[1] + axis[2] * bx[2];
+ const dy = axis[0] * by[0] + axis[1] * by[1] + axis[2] * by[2];
+ if (Math.hypot(dx, dy) < 0.25) continue;
+ const ex = ox + dx * len;
+ const ey = oy - dy * len; // screen y is flipped vs the camera's up
+ const steps = Math.ceil(Math.hypot(ex - ox, ey - oy));
+ for (let s = 0; s <= steps; s++) {
+ const px = Math.round(ox + ((ex - ox) * s) / steps);
+ const py = Math.round(oy + ((ey - oy) * s) / steps);
+ for (let ty = 0; ty < 2; ty++) {
+ for (let tx = 0; tx < 2; tx++) {
+ const x = px + tx;
+ const y = py + ty;
+ if (x < 0 || y < 0 || x >= size || y >= size) continue;
+ const p = (y * size + x) * 3;
+ rgb[p] = color[0];
+ rgb[p + 1] = color[1];
+ rgb[p + 2] = color[2];
+ }
+ }
+ }
+ stampLabel(rgb, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);
+ }
+}
+
+/**
+ * Annotate one square RGB cell in place: view name in the top-left corner, axis
+ * gnomon in the bottom-left. Both are corner-anchored, away from the centered
+ * silhouette (SeeAct caveat: overlays that cross the subject cost more accuracy
+ * than they add).
+ *
+ * The label scale is derived from the cell size rather than passed in, because
+ * the two producers measure size differently — the rasterizer is told it, the
+ * port reads it off a decoded PNG — and a mismatch would show up as
+ * differently-sized text on otherwise identical sheets.
+ */
+export function annotateViewCell(
+ rgb: Uint8Array,
+ size: number,
+ view: { name: string; dir: readonly number[] },
+): void {
+ const labelScale = Math.max(2, Math.round(size / 96));
+ stampLabel(rgb, size, size, labelScale, labelScale, view.name, labelScale);
+ stampAxisGnomon(rgb, size, view.dir);
+}
diff --git a/src/views/background.ts b/src/views/background.ts
new file mode 100644
index 00000000..be80d13c
--- /dev/null
+++ b/src/views/background.ts
@@ -0,0 +1,20 @@
+/**
+ * The one backdrop every view producer paints behind an asset.
+ *
+ * Two producers make the same contact sheet — the CPU rasterizer here and the
+ * host GPU render port — and for a while they disagreed: the render service
+ * defaulted to `#202225` while the rasterizer painted `#1a1a1a`, so which
+ * backdrop a run's sheet came back on depended on nothing but whether a
+ * serverless worker happened to be warm. Studio patched it by mirroring the
+ * literal in its port, with a note to fold it into a shared constant here.
+ *
+ * This is that constant. A dependency-free leaf so both the rasterizer and the
+ * port contract (`composer/render-port`) can import it without either subpath
+ * pulling in the other.
+ */
+
+/** Row-major RGB the rasterizer clears each cell to. */
+export const GRID_BACKGROUND_RGB: readonly [number, number, number] = [26, 26, 26];
+
+/** The same color as CSS hex, for hosts whose render request takes a string. */
+export const GRID_BACKGROUND_HEX = '#1a1a1a';
diff --git a/src/views/capture.ts b/src/views/capture.ts
new file mode 100644
index 00000000..80e774b3
--- /dev/null
+++ b/src/views/capture.ts
@@ -0,0 +1,265 @@
+/**
+ * Capture configuration for the view grid (T3.2).
+ *
+ * The contact sheet was a fixed 3x2 of six named cameras. That is the right
+ * default and stays the default, but it is wrong often enough to matter: a
+ * symmetric prop wastes four cells restating the same silhouette, and a
+ * complex asset with an occluded interior needs angles the six do not include.
+ * This module lets the model choose the grid shape and, if it wants, every
+ * cell's camera.
+ *
+ * ## The one hard rule
+ *
+ * Omitting `capture` must reproduce the existing 3x2 output **byte for byte**.
+ * Every default here is arranged around that: {@link DEFAULT_CAPTURE_PRESET} is
+ * `3x2`, its cells are `SIX_VIEWS` by identity (not a copy that could drift),
+ * and per-cell `zoom` is only applied when explicitly supplied, because passing
+ * frame bounds at all changes the framing path away from per-cell auto-framing.
+ *
+ * ## Preset naming
+ *
+ * `COLSxROWS`, matching how the existing grid is described throughout the
+ * codebase ("6 cells @ 3 cols = 3x2"). So `3x1` is a wide strip and `1x2` is a
+ * tall pair.
+ */
+
+import { SIX_VIEWS, type ViewSpec, orbitAnglesOf, orbitDir, resolveGridViews } from './raster';
+
+/** Grid shapes the model may ask for. `COLS x ROWS`. */
+export type CapturePreset = '1x1' | '1x2' | '2x1' | '3x1' | '2x2' | '3x2' | '3x3';
+
+export const CAPTURE_PRESETS: readonly CapturePreset[] = [
+ '1x1',
+ '1x2',
+ '2x1',
+ '3x1',
+ '2x2',
+ '3x2',
+ '3x3',
+] as const;
+
+/** The shipped contact sheet. Omitting `capture` resolves to exactly this. */
+export const DEFAULT_CAPTURE_PRESET: CapturePreset = '3x2';
+
+/** Hard cap on cells, so a runaway config cannot blow up render time or tokens. */
+export const MAX_CAPTURE_CELLS = 9;
+
+/** One model-specified camera. Angles are object-relative, same frame as `kiln_inspect`. */
+export interface CaptureCell {
+ azimuthDeg: number;
+ elevationDeg: number;
+ /** Padding multiplier around the asset bounds. Omit for the default auto-framing. */
+ zoom?: number;
+ /** Optional cell label. Auto-derived from the angles when omitted. */
+ name?: string;
+}
+
+export interface CaptureConfig {
+ preset?: CapturePreset;
+ cells?: CaptureCell[];
+}
+
+/** Columns for each preset. Rows follow from the cell count. */
+const PRESET_COLS: Record<CapturePreset, number> = {
+ '1x1': 1,
+ '1x2': 1,
+ '2x1': 2,
+ '3x1': 3,
+ '2x2': 2,
+ '3x2': 3,
+ '3x3': 3,
+};
+
+/** Cell capacity of each preset. */
+const PRESET_CAPACITY: Record<CapturePreset, number> = {
+ '1x1': 1,
+ '1x2': 2,
+ '2x1': 2,
+ '3x1': 3,
+ '2x2': 4,
+ '3x2': 6,
+ '3x3': 9,
+};
+
+/** Two extra cameras the six-view set has no room for. */
+const BOTTOM: ViewSpec = { name: 'BOTTOM', dir: [0, -1, 0.0001] };
+const THREE_QUARTER_REAR: ViewSpec = { name: 'REAR 34', dir: [-0.7, 0.5, -0.7] };
+const THREE_QUARTER_LOW: ViewSpec = { name: 'LOW 34', dir: [0.7, -0.35, 0.7] };
+
+/**
+ * Default cameras per preset, chosen so a smaller grid drops the least
+ * informative cells rather than simply truncating the six in order.
+ *
+ * A single cell is the 3/4, not the front: one orthographic elevation reads as
+ * a flat rectangle for most assets, while the quarter view carries depth,
+ * proportion and silhouette at once. Two cells add the front for a readable
+ * measurement reference. `3x2` is `SIX_VIEWS` itself — same array identity, so
+ * a future edit to the six-view set cannot silently desynchronise the default.
+ */
+const PRESET_VIEWS: Record<CapturePreset, ViewSpec[]> = {
+ '1x1': [SIX_VIEWS[5]!],
+ '1x2': [SIX_VIEWS[0]!, SIX_VIEWS[5]!],
+ '2x1': [SIX_VIEWS[0]!, SIX_VIEWS[5]!],
+ '3x1': [SIX_VIEWS[0]!, SIX_VIEWS[1]!, SIX_VIEWS[5]!],
+ '2x2': [SIX_VIEWS[0]!, SIX_VIEWS[1]!, SIX_VIEWS[4]!, SIX_VIEWS[5]!],
+ '3x2': SIX_VIEWS,
+ '3x3': [...SIX_VIEWS, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW],
+};
+
+/**
+ * Label an orbit cell using only glyphs the 3x5 bitmap font actually has
+ * (uppercase, digits, space — there is no minus sign, so elevation sign is
+ * carried by U/D rather than a `-` that would render as a blank box).
+ */
+export function captureCellLabel(azimuthDeg: number, elevationDeg: number): string {
+ const az = Math.round(((azimuthDeg % 360) + 360) % 360);
+ const el = Math.round(elevationDeg);
+ return `A${az} ${el < 0 ? 'D' : 'U'}${Math.abs(el)}`;
+}
+
+export interface ResolvedCapture {
+ preset: CapturePreset;
+ views: ViewSpec[];
+ cols: number;
+ /** Per-cell zoom, aligned with `views`. `undefined` means auto-frame. */
+ zooms: Array<number | undefined>;
+ /** True when the result is the untouched shipped default. */
+ isDefault: boolean;
+}
+
+/**
+ * The layout a contact sheet was actually produced in, reported alongside it.
+ *
+ * Shared by the tool result, the `views` artifact and the render port so a
+ * consumer never has to infer the grid shape by dividing image dimensions.
+ */
+export interface CaptureShape {
+ preset: CapturePreset;
+ cols: number;
+ cells: number;
+}
+
+export class CaptureConfigError extends Error {}
+
+/**
+ * Resolve a capture config into the view list, column count and per-cell zooms
+ * the grid renderer needs.
+ *
+ * Throws {@link CaptureConfigError} on anything the model got wrong, with a
+ * message naming the fix — these come back through the tool result, so they are
+ * the model's only feedback channel.
+ */
+export function resolveCapture(config?: CaptureConfig): ResolvedCapture {
+ if (!config || (config.preset === undefined && config.cells === undefined)) {
+ return {
+ preset: DEFAULT_CAPTURE_PRESET,
+ views: PRESET_VIEWS[DEFAULT_CAPTURE_PRESET],
+ cols: PRESET_COLS[DEFAULT_CAPTURE_PRESET],
+ zooms: new Array(PRESET_CAPACITY[DEFAULT_CAPTURE_PRESET]).fill(undefined),
+ isDefault: true,
+ };
+ }
+
+ const cells = config.cells;
+ let preset = config.preset;
+
+ if (preset !== undefined && !CAPTURE_PRESETS.includes(preset)) {
+ throw new CaptureConfigError(
+ `capture.preset must be one of ${CAPTURE_PRESETS.join(', ')} (got ${JSON.stringify(preset)}).`,
+ );
+ }
+
+ if (cells !== undefined) {
+ if (!Array.isArray(cells) || cells.length === 0) {
+ throw new CaptureConfigError('capture.cells must be a non-empty array of camera angles.');
+ }
+ if (cells.length > MAX_CAPTURE_CELLS) {
+ throw new CaptureConfigError(
+ `capture.cells has ${cells.length} entries; the maximum is ${MAX_CAPTURE_CELLS}.`,
+ );
+ }
+ for (let i = 0; i < cells.length; i++) {
+ const c = cells[i]!;
+ if (!Number.isFinite(c?.azimuthDeg) || !Number.isFinite(c?.elevationDeg)) {
+ throw new CaptureConfigError(
+ `capture.cells[${i}] needs finite azimuthDeg and elevationDeg (got ${JSON.stringify(c)}).`,
+ );
+ }
+ if (c.zoom !== undefined && (!Number.isFinite(c.zoom) || c.zoom <= 0)) {
+ throw new CaptureConfigError(
+ `capture.cells[${i}].zoom must be a positive number (got ${c.zoom}).`,
+ );
+ }
+ }
+
+ // Pick the tightest preset that fits when none was named, so `cells` alone
+ // is a complete request rather than an error about a missing preset.
+ if (preset === undefined) {
+ preset = CAPTURE_PRESETS.find((p) => PRESET_CAPACITY[p] >= cells.length)!;
+ } else if (cells.length > PRESET_CAPACITY[preset]) {
+ throw new CaptureConfigError(
+ `capture.preset ${preset} holds ${PRESET_CAPACITY[preset]} cells but ${cells.length} were given. ` +
+ `Use a larger preset or fewer cells.`,
+ );
+ }
+
+ return {
+ preset,
+ views: cells.map((c) => ({
+ name: c.name?.trim().toUpperCase() || captureCellLabel(c.azimuthDeg, c.elevationDeg),
+ dir: orbitDir(c.azimuthDeg, c.elevationDeg),
+ })),
+ cols: PRESET_COLS[preset],
+ zooms: cells.map((c) => c.zoom),
+ isDefault: false,
+ };
+ }
+
+ // Preset only: use its default cameras.
+ const chosen = preset!;
+ return {
+ preset: chosen,
+ views: PRESET_VIEWS[chosen],
+ cols: PRESET_COLS[chosen],
+ zooms: new Array(PRESET_VIEWS[chosen].length).fill(undefined),
+ isDefault: chosen === DEFAULT_CAPTURE_PRESET,
+ };
+}
+
+/**
+ * Resolve a capture config the way every grid producer must (T3.3).
+ *
+ * There are two producers of the same contact sheet — the CPU rasterizer and the
+ * GPU render port — and they have to agree on the layout down to the cell order,
+ * or a run's artifact silently changes shape depending on whether a GPU happened
+ * to be reachable. This is the one function both call, so the precedence rule
+ * exists once:
+ *
+ * capture supplied -> exactly what it asks for
+ * capture omitted -> the `KILN_GRID_VARIANT` view set at the shipped 3 cols
+ *
+ * The env variant only applies to the omitted case on purpose: it swaps the
+ * *default* six cameras for a bench arm, and silently rewriting a caller's
+ * explicitly-requested angles would make the request a lie.
+ */
+export function resolveGridCapture(config?: CaptureConfig, envVariant?: string): ResolvedCapture {
+ const resolved = resolveCapture(config);
+ if (config) return resolved;
+ const views = resolveGridViews(envVariant);
+ // Identity when the variant is unset/unknown, so the default stays the exact
+ // object the byte-identity tests pin.
+ return views === resolved.views ? resolved : { ...resolved, views };
+}
+
+/** Describe a resolved capture for the tool result, in the model's own coordinates. */
+export function describeCapture(resolved: ResolvedCapture): string {
+ const angles = resolved.views
+ .map((v) => {
+ const { azimuthDeg, elevationDeg } = orbitAnglesOf(v.dir);
+ return `${v.name} (az ${azimuthDeg}, el ${elevationDeg})`;
+ })
+ .join('; ');
+ return `${resolved.preset} grid, ${resolved.views.length} cell${
+ resolved.views.length === 1 ? '' : 's'
+ }: ${angles}`;
+}
diff --git a/src/views/grid.ts b/src/views/grid.ts
index 566ee7ef..ddeceed9 100644
--- a/src/views/grid.ts
+++ b/src/views/grid.ts
@@ -7,6 +7,7 @@
* Pure and deterministic.
*/
+import { annotateViewCell } from './annotate';
import { decodePng, encodePng } from './png';
export const PAD = 4;
@@ -73,15 +74,27 @@ export interface ComposedPngGrid {
/**
* Decode per-view PNGs (e.g. from a host PbrRenderPort) and composite them into
- * the same padded 3-column grid layout the CPU six-view path produces. Every
- * view must be the same square size; unsupported PNG formats or mismatched
- * sizes throw — the caller treats that as a render-port degrade.
+ * the same padded grid layout the CPU view path produces. Every view must be
+ * the same square size; unsupported PNG formats or mismatched sizes throw — the
+ * caller treats that as a render-port degrade.
+ *
+ * Pass `views` to stamp each cell with its name and axis gnomon, exactly as the
+ * CPU rasterizer does. A host renders pixels; it does not know the Kiln camera
+ * vocabulary, so the annotation has to happen here or the GPU sheet arrives
+ * unlabelled — a silent loss of the model's orientation cues on the one path
+ * where the run cannot tell it happened. `views` must align 1:1 with `pngs`.
*/
export function compositeViewPngGrid(
pngs: readonly Uint8Array[],
cols: number = GRID_COLS,
+ views?: readonly { name: string; dir: readonly number[] }[],
): ComposedPngGrid {
if (pngs.length === 0) throw new Error('compositeViewPngGrid: no views to composite');
+ if (views && views.length !== pngs.length) {
+ throw new Error(
+ `compositeViewPngGrid: ${views.length} view specs for ${pngs.length} PNGs — they must align 1:1`,
+ );
+ }
const decoded = pngs.map((png) => decodePng(png));
const size = decoded[0]!.width;
for (const d of decoded) {
@@ -91,6 +104,11 @@ export function compositeViewPngGrid(
);
}
}
+ if (views) {
+ // decodePng 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]!);
+ }
const { rgb, width, height } = compositeCellGrid(
decoded.map((d) => d.rgb),
size,
diff --git a/src/views/index.ts b/src/views/index.ts
index fa62dbef..c7fc4f2b 100644
--- a/src/views/index.ts
+++ b/src/views/index.ts
@@ -17,12 +17,13 @@ import {
rasterizeView,
measureBounds,
hideNodeInScene,
- resolveGridViews,
type RasterOptions,
type ViewSpec,
} from './raster';
import { encodePng } from './png';
import { compositeCellGrid } from './grid';
+import { annotateViewCell } from './annotate';
+import { resolveGridCapture, type CaptureConfig, type CaptureShape } from './capture';
import {
prepareClip,
poseSceneAtTime,
@@ -49,10 +50,33 @@ export {
SIX_VIEWS_REAR_QUARTER,
resolveGridViews,
coverage,
+ orbitDir,
+ orbitAnglesOf,
+ MIN_ELEVATION_DEG,
+ MAX_ELEVATION_DEG,
} from './raster';
export type { RasterOptions, ViewSpec, ViewGridVariant } from './raster';
+export { annotateViewCell, stampAxisGnomon } from './annotate';
+export { GRID_BACKGROUND_HEX, GRID_BACKGROUND_RGB } from './background';
export { encodePng, decodePng } from './png';
export type { DecodedPng } from './png';
+export {
+ CAPTURE_PRESETS,
+ CaptureConfigError,
+ DEFAULT_CAPTURE_PRESET,
+ MAX_CAPTURE_CELLS,
+ captureCellLabel,
+ describeCapture,
+ resolveCapture,
+ resolveGridCapture,
+} from './capture';
+export type {
+ CaptureCell,
+ CaptureConfig,
+ CapturePreset,
+ CaptureShape,
+ ResolvedCapture,
+} from './capture';
export { compositeCellGrid, compositeViewPngGrid, GRID_COLS } from './grid';
export type { ComposedCellGrid, ComposedPngGrid } from './grid';
export { CPU_RASTER_RENDERER_ID } from './renderer-id';
@@ -240,79 +264,22 @@ export interface ViewGridResult {
height: number;
/** View names in grid order (row-major). */
views: string[];
+ /** Grid shape actually rendered by the model-facing contact sheet — the
+ * default reports `3x2`. Absent on the fixed diagnostic layouts (interior
+ * cutaway, animation strip), which have their own row shape and would have
+ * to invent a preset name to report one. */
+ capture?: CaptureShape;
}
export interface ViewGridOptions extends RasterOptions {
views?: ViewSpec[];
/** Snap flat-color materials before rasterization. Mutates the provided scene root. */
snapPalette?: readonly SnapPaletteSlot[];
-}
-
-// H-30: kiln-frame axis gnomon colors (+X fwd red, +Y up green, +Z right blue).
-const GNOMON_AXES: Array<{
- label: string;
- axis: [number, number, number];
- color: [number, number, number];
-}> = [
- { label: 'X', axis: [1, 0, 0], color: [235, 80, 70] },
- { label: 'Y', axis: [0, 1, 0], color: [90, 205, 90] },
- { label: 'Z', axis: [0, 0, 1], color: [90, 145, 245] },
-];
-
-/**
- * Stamp a small world-axis gnomon into a rasterized cell (bottom-left corner),
- * using the SAME camera basis as rasterizeView so the arrows are exact
- * (3DAxisPrompt: ticked/annotated axes measurably improve VLM 3D localization).
- * Axes nearly perpendicular to the image plane (projected length < 0.25) are
- * skipped — only in-plane axes disambiguate a view.
- */
-export function stampAxisGnomon(rgb: Uint8Array, size: number, viewDir: readonly number[]): void {
- // rasterizeView's basis, duplicated deliberately (raster.ts keeps it private).
- const zl = Math.hypot(viewDir[0]!, viewDir[1]!, viewDir[2]!) || 1;
- const z = [viewDir[0]! / zl, viewDir[1]! / zl, viewDir[2]! / zl] as const;
- const up = Math.abs(z[1]) > 0.99 ? ([0, 0, -1] as const) : ([0, 1, 0] as const);
- const cx = [
- up[1] * z[2] - up[2] * z[1],
- up[2] * z[0] - up[0] * z[2],
- up[0] * z[1] - up[1] * z[0],
- ];
- const xl = Math.hypot(cx[0]!, cx[1]!, cx[2]!) || 1;
- const bx = [cx[0]! / xl, cx[1]! / xl, cx[2]! / xl] as const;
- const by = [
- z[1] * bx[2] - z[2] * bx[1],
- z[2] * bx[0] - z[0] * bx[2],
- z[0] * bx[1] - z[1] * bx[0],
- ] as const;
-
- const len = Math.max(12, Math.round(size * 0.055));
- // Inset the origin by the arrow length so leftward/downward projections
- // (e.g. +Z in the Front view) aren't clipped at the cell edge.
- const ox = len + 10;
- const oy = size - len - 10;
- for (const { label, axis, color } of GNOMON_AXES) {
- const dx = axis[0] * bx[0] + axis[1] * bx[1] + axis[2] * bx[2];
- const dy = axis[0] * by[0] + axis[1] * by[1] + axis[2] * by[2];
- if (Math.hypot(dx, dy) < 0.25) continue;
- const ex = ox + dx * len;
- const ey = oy - dy * len; // screen y is flipped vs the camera's up
- const steps = Math.ceil(Math.hypot(ex - ox, ey - oy));
- for (let s = 0; s <= steps; s++) {
- const px = Math.round(ox + ((ex - ox) * s) / steps);
- const py = Math.round(oy + ((ey - oy) * s) / steps);
- for (let ty = 0; ty < 2; ty++) {
- for (let tx = 0; tx < 2; tx++) {
- const x = px + tx;
- const y = py + ty;
- if (x < 0 || y < 0 || x >= size || y >= size) continue;
- const p = (y * size + x) * 3;
- rgb[p] = color[0];
- rgb[p + 1] = color[1];
- rgb[p + 2] = color[2];
- }
- }
- }
- stampLabel(rgb, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);
- }
+ /** Model-chosen grid shape and cameras. Omit for the shipped 3x2 contact sheet.
+ * Ignored when `views` is passed explicitly (internal callers win). */
+ capture?: CaptureConfig;
+ /** Column count override. Defaults to the capture preset's columns. */
+ cols?: number;
}
/** Render a (possibly sandbox-created) Three.js scene root into the 3x2 grid. */
@@ -330,29 +297,64 @@ export async function renderViewGrid(
// swaps the 3/4 cell to the opposite-rear azimuth) so a bench arm can flip the
// grid per-process without any wire or tool-schema change. Explicit opts.views
// always wins; unset/unknown env keeps SIX_VIEWS.
- const views = opts.views ?? resolveGridViews(process.env['KILN_GRID_VARIANT']);
+ //
+ // T3.2: `capture` lets the model pick the grid shape and per-cell cameras.
+ // The env variant and an explicit `views` both still win, in that order of
+ // specificity, so no internal caller changes behavior. With `capture`
+ // omitted this resolves to SIX_VIEWS at 3 columns — the previous constants.
+ const resolved = resolveGridCapture(opts.capture, process.env['KILN_GRID_VARIANT']);
+ const views = opts.views ?? resolved.views;
+ const cols = opts.cols ?? resolved.cols;
if (opts.snapPalette?.length) snapSceneToPalette(root, opts.snapPalette);
- const labelScale = Math.max(2, Math.round(size / 96));
+ // Per-cell zoom needs a shared frame box; measuring is only worth it when a
+ // zoom was actually requested. Passing frameBounds unconditionally would
+ // route every render through a different framing path than before and break
+ // the byte-identity guarantee for the default grid.
+ const wantsZoom = resolved.zooms.some((z) => z !== undefined);
+ const sceneBounds = wantsZoom ? measureBounds(root) : undefined;
+
const cells: Uint8Array[] = [];
for (let vi = 0; vi < views.length; vi++) {
- const cell = rasterizeView(root, views[vi]!.dir, { size, backfaceCull: opts.backfaceCull });
- // H-30: stamp the view name + axis gnomon into the cell (small, corner-
- // anchored, away from the centered silhouette — SeeAct caveat).
- stampLabel(cell, size, size, labelScale, labelScale, views[vi]!.name, labelScale);
- stampAxisGnomon(cell, size, views[vi]!.dir);
+ const zoom = resolved.zooms[vi];
+ const cell = rasterizeView(root, views[vi]!.dir, {
+ size,
+ backfaceCull: opts.backfaceCull,
+ ...(sceneBounds && zoom !== undefined
+ ? { frameBounds: expandFrameBounds(sceneBounds, zoom) }
+ : {}),
+ });
+ // H-30: view name + axis gnomon, via the annotator the GPU port shares.
+ annotateViewCell(cell, size, views[vi]!);
cells.push(cell);
}
- const { rgb, width, height } = compositeCellGrid(cells, size);
+ const { rgb, width, height } = compositeCellGrid(cells, size, cols);
return {
png: encodePng(rgb, width, height),
width,
height,
views: views.map((v) => v.name),
+ capture: { preset: resolved.preset, cols, cells: views.length },
};
}
+/** Grow a bounds box about its center — the per-cell `zoom` padding. */
+function expandFrameBounds(
+ b: { min: [number, number, number]; max: [number, number, number] },
+ factor: number,
+): { min: [number, number, number]; max: [number, number, number] } {
+ const min: [number, number, number] = [0, 0, 0];
+ const max: [number, number, number] = [0, 0, 0];
+ for (let a = 0; a < 3; a++) {
+ const center = (b.min[a]! + b.max[a]!) / 2;
+ const half = ((b.max[a]! - b.min[a]!) / 2) * factor;
+ min[a] = center - half;
+ max[a] = center + half;
+ }
+ return { min, max };
+}
+
/** Execute a Kiln program and render its scene into the 3x2 grid. */
export async function renderCodeViewGrid(
code: string,
diff --git a/src/views/inspect.ts b/src/views/inspect.ts
index 5865cafa..974d6750 100644
--- a/src/views/inspect.ts
+++ b/src/views/inspect.ts
@@ -13,7 +13,7 @@
* and hides everything outside the part so nothing can block the view.
*/
-import { rasterizeView, measureBounds } from './raster';
+import { measureBounds, orbitAnglesOf, orbitDir, rasterizeView } from './raster';
import { encodePng } from './png';
/** Square close-up size in pixels — one big view, not a grid cell. */
@@ -48,8 +48,16 @@ export interface InspectViewOptions {
* Omit to frame the whole asset. */
part?: string;
/** Camera angle: front, right, back, left, top, or three-quarter (default).
- * Unknown names fall back to three-quarter. */
+ * Unknown names fall back to three-quarter. Ignored when `azimuthDeg` or
+ * `elevationDeg` is supplied. */
view?: string;
+ /** Object-relative orbit azimuth in degrees: 0 = front, 90 = right,
+ * 180 = back, 270 = left. Wraps. Supplying either orbit angle switches the
+ * camera off the named presets. */
+ azimuthDeg?: number;
+ /** Object-relative orbit elevation in degrees: 0 = eye level, positive looks
+ * down from above. Clamped to -89..89. */
+ elevationDeg?: number;
/** Padding multiplier around the framed bounds, clamped to 1..4. Default 1.2. */
zoom?: number;
/** Square output size in pixels. Default {@link INSPECT_SIZE}. */
@@ -65,8 +73,13 @@ export type InspectViewResult =
ok: true;
/** Resolved node name that was framed (absent when the whole asset was framed). */
part?: string;
- /** Resolved camera name. */
+ /** Resolved camera name, or `'orbit'` when orbit angles were supplied. */
view: string;
+ /** Effective orbit angles actually rendered — present for BOTH named and
+ * orbit cameras, so the model always learns where the camera was and can
+ * nudge from there. Elevation reflects the clamp. */
+ azimuthDeg: number;
+ elevationDeg: number;
/** Effective (clamped) padding multiplier. */
zoom: number;
/** Whether everything outside the framed part was actually hidden. False
@@ -161,8 +174,19 @@ function isolateSubtree(root: unknown, keep: DuckNamedNode): void {
*/
export function renderInspectView(root: unknown, opts: InspectViewOptions = {}): InspectViewResult {
const size = opts.size ?? INSPECT_SIZE;
+
+ // Orbit angles win over the named presets, but ONLY when at least one is
+ // supplied — omitting both must reproduce the previous behavior exactly, so
+ // the named direction vectors stay authoritative rather than being
+ // regenerated from angles (`top` is [0, 1, 0.0001], which is not orbitDir's
+ // 89-degree elevation, and re-deriving it would silently move that camera).
+ const hasOrbit = opts.azimuthDeg !== undefined || opts.elevationDeg !== undefined;
const viewKey = (opts.view ?? 'three-quarter').trim().toLowerCase();
- const view = viewKey in INSPECT_CAMERAS ? viewKey : 'three-quarter';
+ const view = hasOrbit ? 'orbit' : viewKey in INSPECT_CAMERAS ? viewKey : 'three-quarter';
+ const namedDir = INSPECT_CAMERAS[view in INSPECT_CAMERAS ? view : 'three-quarter']!;
+ const dir = hasOrbit ? orbitDir(opts.azimuthDeg ?? 0, opts.elevationDeg ?? 0) : namedDir;
+ const angles = orbitAnglesOf(dir);
+
const zoom = Math.min(
INSPECT_MAX_ZOOM,
Math.max(INSPECT_MIN_ZOOM, opts.zoom ?? INSPECT_DEFAULT_ZOOM),
@@ -209,7 +233,7 @@ export function renderInspectView(root: unknown, opts: InspectViewOptions = {}):
bounds = measureBounds(root);
}
- const rgb = rasterizeView(root, INSPECT_CAMERAS[view]!, {
+ const rgb = rasterizeView(root, dir, {
size,
frameBounds: expandBounds(bounds, zoom),
});
@@ -217,6 +241,7 @@ export function renderInspectView(root: unknown, opts: InspectViewOptions = {}):
ok: true,
...(part ? { part } : {}),
view,
+ ...angles,
zoom,
isolated,
width: size,
diff --git a/src/views/raster.ts b/src/views/raster.ts
index cee1c092..2b85519f 100644
--- a/src/views/raster.ts
+++ b/src/views/raster.ts
@@ -20,6 +20,8 @@
* the offline audit grid) so inverted winding shows up as missing faces.
*/
+import { GRID_BACKGROUND_RGB } from './background';
+
export interface ViewSpec {
name: string;
/** Direction from model center toward the camera (kiln frame: +X fwd, +Y up, +Z right). */
@@ -46,6 +48,52 @@ export const SIX_VIEWS_REAR_QUARTER: ViewSpec[] = [
{ name: '3/4 Rear', dir: [-0.7, 0.5, -0.7] },
];
+/**
+ * Elevation clamp for orbit cameras. The rasterizer already swaps its up-hint
+ * past |y| > 0.99 so a true pole does not degenerate, but an exactly-vertical
+ * camera makes the framing basis spin freely with azimuth — two calls that
+ * differ only in azimuth would return differently-rotated top views. Clamping
+ * short of the pole keeps azimuth meaningful all the way up.
+ */
+export const MIN_ELEVATION_DEG = -89;
+export const MAX_ELEVATION_DEG = 89;
+
+/**
+ * Object-relative orbit angles to a camera direction in the kiln frame
+ * (+X forward, +Y up, +Z right).
+ *
+ * Azimuth sweeps from the front (+X) toward the right (+Z), so it reproduces
+ * the named grid cameras exactly: 0 = Front, 90 = Right, 180 = Back,
+ * 270 = Left, and (45, 26.79) is the shipped 3/4 direction. Azimuth wraps
+ * naturally; elevation is clamped to {@link MIN_ELEVATION_DEG}..{@link MAX_ELEVATION_DEG}.
+ */
+export function orbitDir(azimuthDeg: number, elevationDeg: number): [number, number, number] {
+ const el =
+ (Math.min(MAX_ELEVATION_DEG, Math.max(MIN_ELEVATION_DEG, elevationDeg)) * Math.PI) / 180;
+ const az = (azimuthDeg * Math.PI) / 180;
+ const cosEl = Math.cos(el);
+ return [cosEl * Math.cos(az), Math.sin(el), cosEl * Math.sin(az)];
+}
+
+/**
+ * Exact inverse of {@link orbitDir}: recover orbit angles from a direction.
+ *
+ * Used so the named cameras can report where they are in the same coordinates
+ * the model steers with, without a second hand-maintained table that could
+ * drift from the direction vectors above. Azimuth comes back in [0, 360).
+ */
+export function orbitAnglesOf(dir: [number, number, number]): {
+ azimuthDeg: number;
+ elevationDeg: number;
+} {
+ const [x, y, z] = normalize(dir);
+ const azimuthDeg = ((((Math.atan2(z, x) * 180) / Math.PI) % 360) + 360) % 360;
+ return {
+ azimuthDeg: +azimuthDeg.toFixed(2),
+ elevationDeg: +((Math.asin(Math.min(1, Math.max(-1, y))) * 180) / Math.PI).toFixed(2),
+ };
+}
+
/** Named six-view grid variants (H-33). 'default' keeps the shipped front-quarter grid. */
export type ViewGridVariant = 'default' | 'rear-quarter';
@@ -73,7 +121,8 @@ export interface RasterOptions {
frameBounds?: { min: [number, number, number]; max: [number, number, number] };
}
-const BG: [number, number, number] = [26, 26, 26]; // #1a1a1a, matches audit grid
+// Shared with the GPU render port so both producers paint the same backdrop.
+const BG = GRID_BACKGROUND_RGB;
const AMBIENT = 0.25;
const KEY_INTENSITY = 1.1;
const KEY_DIR = normalize([1.5, 2, 1]);