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(kiln): vision loop, registry unification, geometry gains, fork retirement

Matt Kissinger6023a2ae1378
diff --git a/__tests__/__snapshots__/prompt-api.test.ts.snap b/__tests__/__snapshots__/prompt-api.test.ts.snap
new file mode 100644
index 00000000..5c77a463
--- /dev/null
+++ b/__tests__/__snapshots__/prompt-api.test.ts.snap
@@ -0,0 +1,231 @@
+// Bun Snapshot v1, https://bun.sh/docs/test/snapshots
+
+exports[`system prompt embeds the generated catalog api section snapshot (review prompt changes in this diff) 1`] = `
+"// Scene & structure (globals — no imports needed)
+createRoot(name: string) // Creates the root Object3D for an asset. Call first in build().
+createPivot(name: string, position?: [x, y, z], parent?: Object3D)
+ // Creates an empty pivot node for skeletal animation. Name is auto-prefixed with \`Joint_\`.
+createPart(name, geometry, material, opts?: { position, rotation, scale, pivot, parent })
+ // Creates a mesh, optionally wrapped in a pivot, and attaches it to \`opts.parent\`.
+ // NOTE: AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent }
+ // instead.
+beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })
+ // Creates a cylindrical rail/strut exactly between two endpoints. Use for braces, gun
+ // barrels, skid struts, cables, and scaffolding.
+snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })
+ // Translates \`part\` by the minimal vector that brings its bounding box into contact with
+ // \`host\` (plus a small overlap). The direct cure for a "Floating parts" warning — attach the
+ // part instead of eyeballing a corrective offset. No-op if they already touch.
+createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })
+ // Builds two continuous rails plus evenly-spaced rungs. Use this instead of loose boxes for
+ // ladders.
+createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })
+ // Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft
+ // wings and helicopter stub wings.
+
+// Geometry (returns BufferGeometry)
+boxGeo(width: number, height: number, depth: number) // 6-face box. 12 tris regardless of size. Cheapest geometry.
+sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)
+ // UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.
+cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)
+ // Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.
+cylinderYGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)
+ // Alias for cylinderGeo — a Y-axis cylinder. Provided because the sandbox exposes
+ // cylinderXGeo / cylinderZGeo and the symmetric Y form is commonly reached for.
+cylinderXGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)
+ // Cylinder pre-rotated to run along +X/-X. Use for fuselages, cannons, barrels, axles, and
+ // forward-facing tubes.
+cylinderZGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)
+ // Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars,
+ // and pipes.
+cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })
+ // Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when
+ // the cylinder needs to point along a non-cardinal direction (struts inside CSG operands,
+ // antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo /
+ // cylinderYGeo / cylinderZGeo helpers.
+capsuleGeo(radius: number, height: number, segments?: 6)
+ // Stadium shape (cylinder with hemispherical caps). Good for limbs.
+capsuleYGeo(radius: number, height: number, segments?: 6)
+ // Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo /
+ // capsuleZGeo.
+capsuleXGeo(radius: number, length: number, segments?: 6)
+ // Capsule pre-rotated to run along +X/-X. Use for aircraft bodies, rounded vehicle hulls, and
+ // missiles.
+capsuleZGeo(radius: number, length: number, segments?: 6)
+ // Capsule pre-rotated to run along +Z/-Z. Use for lateral pods, floats, and side tanks.
+coneGeo(radius: number, height: number, segments?: 8)
+ // Y-axis cone (pointed up). Use for spikes, roofs, projectiles.
+coneYGeo(radius: number, height: number, segments?: 8)
+ // Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo /
+ // coneZGeo.
+coneXGeo(radius: number, length: number, segments?: 8)
+ // Cone pre-rotated so its point faces +X. Use for noses, rockets, shells, and forward-facing
+ // tips.
+coneZGeo(radius: number, length: number, segments?: 8)
+ // Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.
+taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)
+ // Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo,
+ // radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades,
+ // anything tapered that does not come to a point. axis selects orientation (default Y).
+torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)
+ // Donut shape. For rings, tyres, barrel ribs.
+planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)
+ // Flat quad for TEXTURED surfaces (ground, signs, walls with albedo maps). For solid-color
+ // decals like red stars, hull numbers, stamps, or window cutouts on no-texture assets use
+ // decalBox — a bare planeGeo without a texture will render as a disconnected 2-tri square and
+ // get flagged as a stray plane.
+decalBox(width: number, height: number, depth?: 0.01)
+ // Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture
+ // windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must
+ // be placed on a surface with position + rotation.
+ // NOTE: Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull
+ // has faces at z=±0.4, so place the decal at z=±0.41).
+foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })
+ // Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the
+ // ground. Pair with an alpha-tested material and a leaf/plant sprite.
+crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })
+ // Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a
+ // dense plant from any angle, cheaper than real geometry.
+octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })
+ // Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas;
+ // the consumer shader adds per-instance tile offsets at draw time.
+wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })
+ // Trapezoid wing panel. Local root edge is at Z=0, span extends toward +Z, positive sweep
+ // moves the tip aft along -X.
+gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })
+ // Parametric gear: disc with N additive teeth around the rim and a center bore. Flat-shaded
+ // hard edges. Built directly (no CSG), so cheap.
+bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })
+ // Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0
+ // pinches the cross-section toward a diamond ridge.
+
+// Materials
+gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })
+ // Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.
+basicMaterial(color, opts?: { transparent, opacity })
+ // Unlit flat material. For UI / effects where lighting is baked in.
+glassMaterial(color, opts?: { opacity, roughness, metalness })
+ // Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.
+lambertMaterial(color, opts?: { flatShading, emissive })
+ // Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.
+pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? })
+ // Full PBR material. Each slot can be a hex color/scalar or a Texture loaded via loadTexture.
+ // Exports as glTF pbrMetallicRoughness.
+
+// Instancing (share geometry+material; smaller GLBs)
+cloneGeometry(geo: BufferGeometry)
+ // Returns the same geometry reference. Use it as a signal that you are intentionally sharing
+ // geometry across multiple parts; gltf-transform dedupes on export.
+cloneMaterial(mat: Material) // Shared material reference. See cloneGeometry.
+createInstance(name, source, opts?: { position, rotation, scale, parent })
+ // Creates a new mesh reusing an existing part's geometry + material at a new transform.
+ // Cheapest way to replicate wheels / bolts / fence posts / windows.
+
+// Arrays (replicate a source part)
+arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)
+ // Places N copies of \`source\` along a constant offset vector. Copies share geometry +
+ // material via createInstance.
+arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)
+ // Places N copies of \`source\` around the given axis. Source's local rotation is oriented
+ // outward. Perfect for gear teeth, radial bolts, circle of columns.
+mirror(name, source, axis: 'x'|'y'|'z', parent?)
+ // Reflects source across the plane whose normal is \`axis\`. Uses negative scale (winding flip
+ // handled by viewers).
+
+// CSG / Boolean (async — using any of these requires \`async function build()\`)
+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.
+await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false })
+ // Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading
+ // for sharp mechanical edges.
+await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })
+ // Keeps only the volume where both operands overlap. Default flat shading.
+await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })
+ // Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision
+ // volumes). Pass { smooth: false } for a faceted look.
+
+// Mesh ops
+subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { split, uvSmooth, preserveEdges, flatOnly, weld })
+ // Loop subdivision. Each iteration ~4x the triangle count and smooths the surface.
+ // Non-indexed input is auto-welded via mergeVertices (weld: false to skip). Use 1 for mild
+ // smoothing, 2 for organic shapes.
+mergeVertices(geometry: BufferGeometry, tolerance?: 1e-4)
+ // Welds coincident vertices into shared, indexed ones. Three's primitives emit disconnected
+ // per-face strips — call this before subdividing, deforming, or smooth-shading so shared
+ // corners move once.
+
+// Curves
+curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)
+ // Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a
+ // circle profile. Use for pipes, cables, tubular frames.
+pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })
+ // Path-driven swept circle with optional bend smoothing. Generalises beamBetween
+ // (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts
+ // interpolated waypoints near interior corners so the spline reads as a rounded turn instead
+ // of pinching to the control point.
+lathe(profile: [x,y][], segments?: 12)
+ // Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels,
+ // turned wood parts.
+revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })
+ // Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you
+ // need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile
+ // convention is identical to lathe: x = radial distance, y = position along the axis.
+bezierCurve(controlPoints: [x,y,z][], samples?: 32)
+ // Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can
+ // feed into curveToMesh.
+
+// UV unwrapping
+await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })
+ // xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a
+ // packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For
+ // directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware
+ // unwraps below.
+boxUnwrap(geometry: BufferGeometry)
+ // Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent
+ // orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.
+cylinderUnwrap(geometry: BufferGeometry)
+ // Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture
+ // features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM
+ // cost.
+planeUnwrap(geometry: BufferGeometry)
+ // Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE
+ // readable texture and no edge-face bleeding. Sync.
+panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)
+ // Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture.
+ // Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify
+ // on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the
+ // geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and
+ // v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample
+ // only the clean strip.
+
+// Textures (loadTexture is async)
+await loadTexture(source: string | Buffer | Uint8Array)
+ // Loads a PNG/JPG/WebP image into a Three.js Texture. Stashes the encoded bytes on
+ // userData.encoded so GLB export is lossless.
+ // 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.
+
+// Animation — keyframes use "rotation"/"position"/"scale" keys, NOT "value"
+rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')
+ // Rotation track in degrees, auto-converted to quaternions. Joint name must include \`Joint_\`
+ // prefix.
+positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')
+ // Position track in world units. Always use \`position:\` not \`value:\` in keyframes.
+scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')
+ // Uniform or per-axis scale track.
+createClip(name: string, duration: number, tracks: KeyframeTrack[])
+ // Collects tracks into a named clip. Returned from animate().
+idleBreathing(bodyJoint: string, duration?: 2, amount?: 0.02) // Gentle Y-axis bob. For NPC idle states.
+bobbingAnimation(rootName: string, duration?: 2, height?: 0.1) // Floating / bobbing loop for pickups and effects.
+spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')
+ // 360° rotation over \`duration\` around \`axis\`.
+
+// Inspection utilities
+countTriangles(root: Object3D) // Sums triangle count across every mesh in the subtree.
+countMaterials(root: Object3D) // Unique material count (by reference) across the subtree.
+getJointNames(root: Object3D) // All node names beginning with \`Joint_\`. Use to sanity-check animation targets.
+validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment')
+ // Warns on category-appropriate triangle / material budgets."
+`;
diff --git a/__tests__/companions.test.ts b/__tests__/companions.test.ts
index daadfa69..28d58dea 100644
--- a/__tests__/companions.test.ts
+++ b/__tests__/companions.test.ts
@@ -12,6 +12,11 @@
import { describe, expect, test, mock, beforeEach } from 'bun:test';
+// These companions test the SINGLE-SHOT machinery (mocked claude-agent-sdk).
+// The codegen default is now the Strands agent loop — pin this file's runs to
+// the mocked path before the module under test is imported.
+process.env['KILN_CODEGEN'] = 'single-shot';
+
// Mocks must be declared before importing the module under test.
let queryImpl = async function* (_args: unknown): AsyncGenerator<unknown> {
yield { type: 'result', subtype: 'success', result: '', session_id: 'test' };
diff --git a/__tests__/geometry-gains.test.ts b/__tests__/geometry-gains.test.ts
new file mode 100644
index 00000000..0ce854ab
--- /dev/null
+++ b/__tests__/geometry-gains.test.ts
@@ -0,0 +1,154 @@
+/**
+ * Phase 5.1 geometry gains: snapTo contact resolution, gap-vector fix hints on
+ * floating-part warnings, the category orientation advisory, settleContacts,
+ * and the upgraded static tri estimates (loops, gearGeo, subdivide).
+ */
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import { buildSandboxGlobals, snapTo } from '../primitives';
+import { executeKilnCode, inspectSceneStructure, settleContacts } from '../render';
+import { validate } from '../validation';
+
+const FLOATER_CODE = `
+const meta = { name: 'floaty', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Base', boxGeo(1, 1, 1), gameMaterial('#888888'), { parent: root, position: [0, 0.5, 0] });
+ // float bottom at 1.14-0.1=1.04 vs base top at 1.0 → a 4cm gap (settleable)
+ createPart('Mesh_Float', boxGeo(0.2, 0.2, 0.2), gameMaterial('#ff0000'), { parent: root, position: [0, 1.14, 0] });
+ return root;
+}
+`;
+
+describe('snapTo', () => {
+ test('translates a floating part into contact with its host', () => {
+ const g = buildSandboxGlobals();
+ void g; // sandbox registration sanity is covered by the parity test
+ const host = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());
+ host.position.set(0, 0.5, 0);
+ const part = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.2, 0.2), new THREE.MeshStandardMaterial());
+ part.position.set(0, 1.8, 0); // 0.7 above the host top
+ const scene = new THREE.Object3D();
+ scene.add(host, part);
+
+ snapTo(part, host);
+ const a = new THREE.Box3().setFromObject(part);
+ const b = new THREE.Box3().setFromObject(host);
+ expect(a.intersectsBox(b)).toBe(true);
+ });
+
+ test('is a no-op when already in contact', () => {
+ const host = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1));
+ const part = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.4, 0.4));
+ part.position.set(0, 0.6, 0); // overlapping
+ const scene = new THREE.Object3D();
+ scene.add(host, part);
+ const before = part.position.clone();
+ snapTo(part, host);
+ expect(part.position.distanceTo(before)).toBe(0);
+ });
+});
+
+describe('floating-part fix hints', () => {
+ test('warning carries the minimal gap vector and the snapTo suggestion', async () => {
+ const { root } = await executeKilnCode(FLOATER_CODE);
+ const warnings = inspectSceneStructure(root);
+ const floatWarning = warnings.find((w) => w.includes('Floating parts'));
+ expect(floatWarning).toBeDefined();
+ expect(floatWarning).toContain('Mesh_Float');
+ expect(floatWarning).toContain('shift');
+ expect(floatWarning).toContain('snapTo');
+ // 4cm downward gap → the hint vector's Y component is -0.040.
+ expect(floatWarning).toContain('-0.040');
+ });
+});
+
+describe('orientation advisory', () => {
+ test('flags a sideways vehicle (Z-dominant), passes an X-forward one', async () => {
+ const sideways = await executeKilnCode(`
+ const meta = { name: 'sideways' };
+ function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Hull', boxGeo(0.8, 0.5, 3.0), gameMaterial('#445544'), { parent: root, position: [0, 0.25, 0] });
+ return root;
+ }
+ `);
+ const w1 = inspectSceneStructure(sideways.root, { category: 'vehicle' });
+ expect(w1.some((w) => w.includes('Orientation'))).toBe(true);
+
+ const forward = await executeKilnCode(`
+ const meta = { name: 'forward' };
+ function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Hull', boxGeo(3.0, 0.5, 0.8), gameMaterial('#445544'), { parent: root, position: [0, 0.25, 0] });
+ return root;
+ }
+ `);
+ const w2 = inspectSceneStructure(forward.root, { category: 'vehicle' });
+ expect(w2.some((w) => w.includes('Orientation'))).toBe(false);
+ // No category → no orientation check at all.
+ expect(inspectSceneStructure(sideways.root).some((w) => w.includes('Orientation'))).toBe(false);
+ });
+});
+
+describe('settleContacts', () => {
+ test('closes a small gap and reports the moved part; leaves big gaps alone', async () => {
+ const { root } = await executeKilnCode(FLOATER_CODE); // 4cm gap
+ const settled = settleContacts(root, { maxGap: 0.05 });
+ expect(settled).toEqual(['Mesh_Mesh_Float']);
+ expect(inspectSceneStructure(root).some((w) => w.includes('Floating parts'))).toBe(false);
+
+ const far = await executeKilnCode(`
+ const meta = { name: 'far' };
+ function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Base', boxGeo(1, 1, 1), gameMaterial('#888888'), { parent: root, position: [0, 0.5, 0] });
+ createPart('Mesh_Far', boxGeo(0.2, 0.2, 0.2), gameMaterial('#ff0000'), { parent: root, position: [0, 3, 0] });
+ return root;
+ }
+ `);
+ expect(settleContacts(far.root, { maxGap: 0.05 })).toEqual([]);
+ });
+});
+
+describe('tri estimate upgrades', () => {
+ const wrap = (body: string) => `
+ const meta = { name: 'est', category: 'prop' };
+ function build() {
+ const root = createRoot('Root');
+ ${body}
+ return root;
+ }
+ `;
+
+ test('for-loop literal bounds multiply the estimate', () => {
+ // 8 cylinders at 16 segs = 8 * 64 = 512 estimated tris (vs 64 unscaled).
+ const r = validate(
+ wrap(`for (let i = 0; i < 8; i++) {
+ createPart('P' + i, cylinderGeo(0.1, 0.1, 1, 16), gameMaterial('#999999'), { parent: root });
+ }`),
+ { category: 'vfx' }, // 2000 budget — single counting stays silent
+ );
+ expect(r.valid).toBe(true);
+ // 30 spheres at 32x16 → 30 * 1024 = 30720 >> any budget → advisory fires.
+ const heavy = validate(
+ wrap(`for (let i = 0; i < 30; i++) {
+ createPart('S' + i, sphereGeo(0.5, 32, 16), gameMaterial('#999999'), { parent: root });
+ }`),
+ { category: 'prop' },
+ );
+ expect(heavy.warnings.some((w) => w.message.includes('tris'))).toBe(true);
+ });
+
+ test('gearGeo and subdivide contribute estimates', () => {
+ const r = validate(
+ wrap(`
+ createPart('Gear', gearGeo({ teeth: 64 }), gameMaterial('#999999'), { parent: root }); // ~2048
+ const blob = subdivide(sphereGeo(1, 16, 12), 2); // 384 base + 384*15 growth
+ createPart('Blob', blob, gameMaterial('#999999'), { parent: root });
+ `),
+ { category: 'vfx' }, // budget 2000 → combined ~8200 trips the advisory
+ );
+ expect(r.warnings.some((w) => w.message.includes('tris'))).toBe(true);
+ });
+});
diff --git a/__tests__/prompt-api.test.ts b/__tests__/prompt-api.test.ts
new file mode 100644
index 00000000..791b25b3
--- /dev/null
+++ b/__tests__/prompt-api.test.ts
@@ -0,0 +1,148 @@
+/**
+ * Registry-unification gates (Phase 1.3):
+ *
+ * 1. Arity parity — every catalog signature's required-parameter count agrees
+ * with the real sandbox function's `Function.length` (named exceptions for
+ * rest/options/destructured signatures where JS arity can't see the truth).
+ * 2. Prompt composition — the system prompt embeds the generated <api>
+ * enumeration, so EVERY cataloged primitive is teachable; a snapshot makes
+ * prompt changes reviewable in diffs.
+ * 3. Skill drift gate — the on-disk kiln-glb skill files match the in-memory
+ * render; regenerate with `bun run kiln:gen-skill` when this fails.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { listPrimitives } from '../list-primitives';
+import {
+ renderApiSection,
+ renderPrimitivesMarkdown,
+ renderSkillQuickReference,
+} from '../prompt-api';
+import {
+ KILN_SYSTEM_PROMPT,
+ KILN_SYSTEM_PROMPT_SECTIONS,
+ KILN_API_SECTION,
+} from '../prompt';
+import { buildSandboxGlobals } from '../primitives';
+
+const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../../..');
+const SKILL_DIR = resolve(REPO_ROOT, '.claude/skills/kiln-glb');
+
+// =============================================================================
+// (1) Arity parity
+// =============================================================================
+
+/**
+ * Signatures whose JS `Function.length` legitimately exceeds the documented
+ * param count (e.g. internal-only trailing params). Currently empty — add a
+ * name here ONLY with a comment explaining why the drift is not model-facing.
+ */
+const ARITY_EXCEPTIONS = new Set<string>([]);
+
+/** Count ALL documented top-level params (required + optional, incl. rest). */
+function documentedParamCount(signature: string): number {
+ const open = signature.indexOf('(');
+ const close = signature.lastIndexOf(')');
+ if (open === -1 || close === -1) return 0;
+ const inner = signature.slice(open + 1, close).trim();
+ if (!inner) return 0;
+
+ let depth = 0;
+ let count = 1;
+ for (const ch of inner) {
+ if (ch === '(' || ch === '[' || ch === '{' || ch === '<') depth++;
+ else if (ch === ')' || ch === ']' || ch === '}' || ch === '>') depth--;
+ else if (ch === ',' && depth === 0) count++;
+ }
+ return count;
+}
+
+describe('catalog arity parity', () => {
+ // Direction matters: an impl that takes FEWER declared params than documented
+ // is just defensive defaults (harmless), but an impl whose Function.length
+ // EXCEEDS the documented param count means the catalog omits a real
+ // parameter — a model following the catalog can never discover it. That is
+ // exactly how the interp param of rotation/position/scaleTrack went missing.
+ test('the catalog documents at least as many params as the impl declares', () => {
+ const globals = buildSandboxGlobals();
+ const mismatches: string[] = [];
+ for (const p of listPrimitives()) {
+ if (ARITY_EXCEPTIONS.has(p.name)) continue;
+ const fn = globals[p.name] as ((...args: unknown[]) => unknown) | undefined;
+ if (typeof fn !== 'function') continue; // covered by the existing parity test
+ const documented = documentedParamCount(p.signature.replace(/^await\s+/, ''));
+ if (fn.length > documented) {
+ mismatches.push(
+ `${p.name}: impl declares ${fn.length} params but the signature documents only ${documented}`,
+ );
+ }
+ }
+ expect(mismatches).toEqual([]);
+ });
+});
+
+// =============================================================================
+// (2) Prompt composition
+// =============================================================================
+
+describe('system prompt embeds the generated catalog', () => {
+ test('every cataloged primitive name appears in the system prompt', () => {
+ const missing = listPrimitives()
+ .map((p) => p.name)
+ .filter((name) => !KILN_SYSTEM_PROMPT.includes(name));
+ expect(missing).toEqual([]);
+ });
+
+ test('the sections compose to the full prompt in canonical order', () => {
+ expect(KILN_SYSTEM_PROMPT).toBe(KILN_SYSTEM_PROMPT_SECTIONS.map(([, s]) => s).join('\n\n'));
+ expect(KILN_SYSTEM_PROMPT_SECTIONS.map(([name]) => name)).toEqual([
+ 'header',
+ 'file-format',
+ 'coordinate-contract',
+ 'api',
+ 'architecture',
+ 'quality',
+ 'attachment-rules',
+ 'rules',
+ 'animation-format',
+ 'visual-qa',
+ 'examples',
+ ]);
+ });
+
+ test('api section keeps the load-bearing hand idioms', () => {
+ expect(KILN_API_SECTION).toContain('WRONG: parent.add(createPart(...))');
+ expect(KILN_API_SECTION).toContain('createInstance("WheelFR"');
+ expect(KILN_API_SECTION).toContain('autoUnwrap');
+ expect(KILN_API_SECTION).toContain('THREE namespace is exposed');
+ });
+
+ test('api section snapshot (review prompt changes in this diff)', () => {
+ expect(renderApiSection(listPrimitives())).toMatchSnapshot();
+ });
+});
+
+// =============================================================================
+// (3) Skill drift gate
+// =============================================================================
+
+describe('kiln-glb skill files match the catalog render', () => {
+ test('references/primitives.md is up to date (bun run kiln:gen-skill)', () => {
+ const onDisk = readFileSync(resolve(SKILL_DIR, 'references/primitives.md'), 'utf-8');
+ expect(onDisk.replace(/\r\n/g, '\n')).toBe(renderPrimitivesMarkdown(listPrimitives()));
+ });
+
+ test('SKILL.md generated block is up to date (bun run kiln:gen-skill)', () => {
+ const skill = readFileSync(resolve(SKILL_DIR, 'SKILL.md'), 'utf-8').replace(/\r\n/g, '\n');
+ const begin = skill.indexOf('<!-- BEGIN GENERATED PRIMITIVES -->');
+ const end = skill.indexOf('<!-- END GENERATED PRIMITIVES -->');
+ expect(begin).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(begin);
+ const block = skill.slice(begin, end);
+ expect(block).toContain(renderSkillQuickReference(listPrimitives()));
+ });
+});
diff --git a/agent/generate.ts b/agent/generate.ts
index 02d0d3e6..6e4978a5 100644
--- a/agent/generate.ts
+++ b/agent/generate.ts
@@ -58,6 +58,13 @@ export interface GenerateKilnAssetOptions {
refineMode?: RefineMode;
/** Agent name (for tracing). */
agentName?: string;
+ /** 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;
+ /** Style anchor: a complete Kiln program rendered as "## Reference Asset" for
+ * FRESH generation (ignored on refine). ~5-15k input tokens/run, mostly
+ * absorbed by prompt caching when reused across a batch. */
+ exemplarCode?: string;
}
export interface GenerateKilnAssetResult {
@@ -83,6 +90,66 @@ export interface GenerateKilnAssetResult {
edits?: EditRecord[];
/** Edit-mode refine: a unified diff from the parent code to the final buffer. */
diff?: string;
+ /** Six-view grid PNG of the final asset (only when `captureViews` was set and the render succeeded). */
+ views?: Buffer;
+}
+
+/**
+ * CODE-ONLY agent generation — the agent tool loop without the final GLB
+ * render. The retirement bridge for the legacy `generateKilnCode` fork:
+ * `kiln/generate.ts` lazy-imports this when the codegen mode is 'agent', so
+ * the editor server route and `editKilnCode` ride the Strands loop with zero
+ * route changes (they render separately, exactly as they did with the
+ * single-shot emitter). Returns the same success/error shape that path expects.
+ */
+export async function generateKilnCodeAgent(opts: {
+ prompt: string;
+ category?: AssetCategory;
+ style?: AssetStyle;
+ includeAnimation?: boolean;
+ existingCode?: string;
+ originalPrompt?: string;
+ /** Strands model id; defaults like {@link generateKilnAsset}. */
+ model?: string;
+}): Promise<{
+ success: boolean;
+ code?: string;
+ usage?: { inputTokens: number; outputTokens: number };
+ error?: string;
+ provider?: KilnAgentProvider;
+ model?: string;
+}> {
+ const modelId =
+ opts.model ??
+ process.env['KILN_MODEL'] ??
+ process.env['PIXEL_FORGE_MODEL'] ??
+ DEFAULT_KILN_AGENT_MODEL;
+ const desc = resolveKilnAgentModel(modelId);
+ const model = makeKilnModel(desc);
+
+ const agent = await runKilnAgent({
+ model,
+ prompt: opts.prompt,
+ category: opts.category ?? 'prop',
+ includeAnimation: opts.includeAnimation ?? false,
+ ...(opts.style ? { style: opts.style } : {}),
+ ...(opts.existingCode ? { existingCode: opts.existingCode } : {}),
+ ...(opts.originalPrompt ? { originalPrompt: opts.originalPrompt } : {}),
+ });
+
+ if (agent.error || !agent.code) {
+ return { success: false, error: agent.error ?? 'agent produced no code' };
+ }
+ return {
+ success: true,
+ code: agent.code,
+ usage: {
+ inputTokens: agent.usage?.inputTokens ?? 0,
+ outputTokens: agent.usage?.outputTokens ?? 0,
+ },
+ provider: desc.provider,
+ model: desc.model,
+ };
}
/**
@@ -113,6 +180,7 @@ export async function generateKilnAsset(
...(opts.originalPrompt ? { originalPrompt: opts.originalPrompt } : {}),
...(opts.existingCode && opts.refineMode ? { refineMode: opts.refineMode } : {}),
...(opts.agentName ? { agentName: opts.agentName } : {}),
+ ...(opts.exemplarCode ? { exemplarCode: opts.exemplarCode } : {}),
});
if (agent.error || !agent.code) {
@@ -121,6 +189,18 @@ export async function generateKilnAsset(
const render = await renderGLB(agent.code);
+ // 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;
+ if (opts.captureViews) {
+ try {
+ const { renderCodeViewGrid } = await import('../views');
+ views = (await renderCodeViewGrid(agent.code)).png;
+ } catch {
+ views = undefined;
+ }
+ }
+
return {
code: agent.code,
glb: render.glb,
@@ -133,5 +213,6 @@ export async function generateKilnAsset(
model: desc.model,
...(agent.edits ? { edits: agent.edits } : {}),
...(agent.diff ? { diff: agent.diff } : {}),
+ ...(views ? { views } : {}),
};
}
diff --git a/agent/hooks.ts b/agent/hooks.ts
index 36609a2a..d2986d2a 100644
--- a/agent/hooks.ts
+++ b/agent/hooks.ts
@@ -19,6 +19,11 @@ export interface AgentUsage {
outputTokens?: number;
}
+/** A live agent-loop event, emitted as the loop runs (for progress UIs). */
+export type KilnAgentEvent =
+ | { type: 'tool'; tool: string; step: number }
+ | { type: 'model_call'; step: number };
+
/** The agent-loop-derived metrics this collector produces. */
export interface CollectedMetrics {
toolCalls: string[];
@@ -32,13 +37,31 @@ export class MetricsCollector {
private usage: AgentUsage | undefined;
private cleanups: Array<() => void> = [];
+ /**
+ * @param onEvent - Optional live sink, fired as the loop runs (tool calls,
+ * model calls). Errors thrown by the sink are swallowed — a broken progress
+ * listener must never fail a generation.
+ */
+ constructor(private readonly onEvent?: (event: KilnAgentEvent) => void) {}
+
+ private emit(event: KilnAgentEvent): void {
+ if (!this.onEvent) return;
+ try {
+ this.onEvent(event);
+ } catch {
+ // progress sinks are best-effort
+ }
+ }
+
/** Attach hooks; returns a cleanup function (also tracked for `detach()`). */
attach(agent: Agent): () => void {
const offTool = agent.addHook(BeforeToolCallEvent, (event) => {
this.toolCalls.push(event.toolUse.name);
+ this.emit({ type: 'tool', tool: event.toolUse.name, step: this.steps });
});
const offModel = agent.addHook(AfterModelCallEvent, () => {
this.steps += 1;
+ this.emit({ type: 'model_call', step: this.steps });
});
this.cleanups.push(offTool, offModel);
return () => this.detach();
diff --git a/agent/index.ts b/agent/index.ts
index f1086938..988d21e6 100644
--- a/agent/index.ts
+++ b/agent/index.ts
@@ -21,7 +21,7 @@
export { runKilnAgent } from './run';
export type { RunKilnAgentOptions, RunKilnAgentResult, KilnKnowhow, RefineMode } from './run';
-export { generateKilnAsset, DEFAULT_KILN_AGENT_MODEL } from './generate';
+export { generateKilnAsset, generateKilnCodeAgent, DEFAULT_KILN_AGENT_MODEL } from './generate';
export type { GenerateKilnAssetOptions, GenerateKilnAssetResult } from './generate';
export { makeKilnTools, makeKilnEditTools, KilnEditBuffer, KILN_SUBMIT_TOOL_NAME } from './tools';
@@ -32,7 +32,7 @@ export type { UnifiedDiffOptions } from './diff';
export { ensureStreamStart } from './stream-start';
-export { makeOpenRouterModel, makeKilnModel, resolveKilnAgentModel } from './providers';
+export { makeOpenRouterModel, makeKilnModel, resolveKilnAgentModel, harnessIdToAgentModelId } from './providers';
export type {
OpenRouterModelOptions,
KilnAgentProvider,
@@ -41,4 +41,4 @@ export type {
} from './providers';
export { MetricsCollector } from './hooks';
-export type { CollectedMetrics, AgentUsage } from './hooks';
+export type { CollectedMetrics, AgentUsage, KilnAgentEvent } from './hooks';
diff --git a/agent/providers.ts b/agent/providers.ts
index 062a9559..cf03e1e9 100644
--- a/agent/providers.ts
+++ b/agent/providers.ts
@@ -151,3 +151,29 @@ export function resolveKilnAgentModel(modelId: string): KilnModelDescriptor {
// Default: Anthropic (claude-*).
return { provider: 'anthropic', model: id };
}
+
+/**
+ * Translate a HARNESS model id (the `llm.resolveKilnModelRoute` vocabulary the
+ * single-shot path takes via `KILN_MODEL` / `--model`) into a Strands agent
+ * model id, or null when the id has no agent-path equivalent.
+ *
+ * This explicit bridge exists because the two resolvers use different provider
+ * vocabularies (harness `gemini` vs Strands `google`; harness routes via the
+ * AI-SDK, Strands via native providers) — DO NOT merge the resolvers: feeding
+ * a Strands id like `google:gemini-3.5-flash` through the harness resolver (or
+ * vice versa) misroutes silently. A null return means "no agent route — let
+ * the single-shot fallback handle this id".
+ */
+export function harnessIdToAgentModelId(id: string): string | null {
+ const trimmed = id.trim();
+ if (!trimmed) return null;
+ // Already a Strands-form id (provider:model) — pass through untouched.
+ if (/^(anthropic|openai|google|bedrock|openrouter):/.test(trimmed)) return trimmed;
+ // OpenRouter `vendor/model` slashes route the same on both paths.
+ if (trimmed.includes('/')) return `openrouter:${trimmed}`;
+ if (trimmed.startsWith('claude-')) return `anthropic:${trimmed}`;
+ if (trimmed.startsWith('gemini-')) return `google:${trimmed}`;
+ if (trimmed.startsWith('gpt-') || /^o[34]/.test(trimmed)) return `openai:${trimmed}`;
+ // Unknown family (imagen, embeddings, harness-only aliases): no agent route.
+ return null;
+}
diff --git a/agent/run.ts b/agent/run.ts
index 517325b4..d9668c28 100644
--- a/agent/run.ts
+++ b/agent/run.ts
@@ -23,7 +23,7 @@ import { getSystemPrompt, buildUserPrompt, KILN_REFINE_DIRECTIVE, KILN_EDIT_DIRE
import type { AssetCategory, AssetStyle } from '../prompt';
import { makeKilnTools, makeKilnEditTools, type SubmitSink, type EditSink, type EditRecord } from './tools';
import { unifiedDiff } from './diff';
-import { MetricsCollector, type AgentUsage } from './hooks';
+import { MetricsCollector, type AgentUsage, type KilnAgentEvent } from './hooks';
/** How the agent learns Kiln conventions. */
export type KilnKnowhow = 'inline' | 'skill';
@@ -42,6 +42,10 @@ export interface RunKilnAgentOptions {
style?: AssetStyle;
/** Know-how source: inline system prompt (default) or the kiln-glb skill. */
knowhow?: KilnKnowhow;
+ /** Inline-knowhow only: 'full' (default) embeds the whole primitive
+ * enumeration in the system prompt; 'trimmed' sends a ~15-line stub and
+ * relies on the kiln_list_primitives tool. The bench prompt-ablation axis. */
+ apiSurface?: 'full' | 'trimmed';
/** Absolute path to a SKILL.md dir, required when knowhow='skill'. */
skillDir?: string;
/** Extra tools to expose (e.g. a Strands McpClient for the MCP transport). */
@@ -62,6 +66,13 @@ export interface RunKilnAgentOptions {
refineMode?: RefineMode;
/** Agent name (for tracing). Default 'kiln-agent'. */
agentName?: string;
+ /** Live agent-loop events (tool calls / model calls) for progress UIs.
+ * Best-effort: sink errors are swallowed and never fail the run. */
+ onEvent?: (event: KilnAgentEvent) => void;
+ /** A complete Kiln program used as a style anchor for FRESH generation —
+ * rendered as "## Reference Asset" in the user prompt (ignored when
+ * existingCode is set). ~5-15k input tokens/run; cached on most providers. */
+ exemplarCode?: string;
}
export interface RunKilnAgentResult {
@@ -101,7 +112,7 @@ function lastMessageText(message: Message | undefined): string | undefined {
* on `result.error` with whatever metrics were collected beforehand.
*/
export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAgentResult> {
- const metrics = new MetricsCollector();
+ const metrics = new MetricsCollector(opts.onEvent);
// Edit mode only engages when refining (existingCode set) AND explicitly chosen.
const editMode = Boolean(opts.existingCode) && opts.refineMode === 'edit';
const sink: SubmitSink = {};
@@ -123,7 +134,7 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg
'validate and render it with the kiln tools, then call kiln_submit with the ' +
'final code.';
} else {
- systemPrompt = getSystemPrompt('glb');
+ systemPrompt = getSystemPrompt('glb', opts.apiSurface ? { apiSurface: opts.apiSurface } : {});
}
// Refine framing: edit an existing asset on top of the unchanged conventions.
@@ -151,9 +162,13 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg
...(opts.style ? { style: opts.style } : {}),
...(opts.existingCode ? { existingCode: opts.existingCode } : {}),
...(opts.originalPrompt ? { originalPrompt: opts.originalPrompt } : {}),
+ ...(opts.exemplarCode ? { exemplarCode: opts.exemplarCode } : {}),
}) +
- '\n\nWhen finished, call the kiln_submit tool exactly once with your final, ' +
- 'complete Kiln program.';
+ '\n\nBefore submitting, call kiln_screenshot once on your final code and check ' +
+ 'the six views: correct facing in Front, a clean silhouette in Right, symmetry in ' +
+ 'Top, and no floating or detached parts in the 3/4 view. Fix anything that looks ' +
+ 'wrong, then call the kiln_submit tool exactly once with your final, complete ' +
+ 'Kiln program.';
const result = await agent.invoke(userPrompt);
metrics.recordResultUsage(result.metrics?.latestAgentInvocation?.usage);
diff --git a/agent/tools-edit.test.ts b/agent/tools-edit.test.ts
index 1a5c618f..e23738dd 100644
--- a/agent/tools-edit.test.ts
+++ b/agent/tools-edit.test.ts
@@ -2,7 +2,7 @@
* Unit tests for the surgical edit-tool skin (KilnEditBuffer + makeKilnEditTools).
*
* The buffer is the whole edit contract - pure string ops, no Strands / THREE -
- * so it is tested directly. The tool factory is checked for its wiring (the six
+ * so it is tested directly. The tool factory is checked for its wiring (the seven
* tools and their names, plus the shared edit trace). The run-level gating (edit
* mode only when refining) is exercised by the studio mock-adapter tests.
*/
@@ -89,7 +89,7 @@ test('view returns the raw buffer and a line count that tracks edits', () => {
expect(buf.view().lines).toBe(buf.code.split('\n').length);
});
-test('makeKilnEditTools exposes the six edit-mode tools and wires the edit trace', () => {
+test('makeKilnEditTools exposes the seven edit-mode tools and wires the edit trace', () => {
const sink: EditSink = { edits: [] };
const tools = makeKilnEditTools({ seedCode: SEED, sink });
expect(tools.map((t) => t.name)).toEqual([
@@ -98,6 +98,7 @@ test('makeKilnEditTools exposes the six edit-mode tools and wires the edit trace
'kiln_edit',
'kiln_validate',
'kiln_render',
+ 'kiln_screenshot',
'kiln_submit',
]);
// The sink's edit trace is the buffer's live array (shared reference).
diff --git a/agent/tools-media.test.ts b/agent/tools-media.test.ts
new file mode 100644
index 00000000..172abeef
--- /dev/null
+++ b/agent/tools-media.test.ts
@@ -0,0 +1,88 @@
+/**
+ * Strands tool skin: kiln_screenshot returns [ImageBlock, JsonBlock] so the
+ * model literally sees the rendered views; plain tools keep their JSON output.
+ */
+import { describe, expect, test } from 'bun:test';
+import { ImageBlock, JsonBlock } from '@strands-agents/sdk';
+
+import { makeKilnTools, makeKilnEditTools, type SubmitSink, type EditSink } from './tools';
+
+const BOX_CODE = `
+const meta = { name: 'test-box', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Box', boxGeo(1, 1, 1), gameMaterial('#ff0000'), { parent: root, position: [0, 0.5, 0] });
+ return root;
+}
+`;
+
+function findTool(tools: ReturnType<typeof makeKilnTools>, name: string) {
+ const t = tools.find((x) => x.name === name) as
+ | { invoke(input: unknown): Promise<unknown> }
+ | undefined;
+ if (!t) throw new Error(`tool ${name} not found`);
+ return t;
+}
+
+describe('makeKilnTools media handling', () => {
+ test('exposes the four registry tools plus kiln_submit', () => {
+ const sink: SubmitSink = {};
+ const tools = makeKilnTools(sink);
+ expect(tools.map((t) => t.name)).toEqual([
+ 'kiln_list_primitives',
+ 'kiln_validate',
+ 'kiln_render',
+ 'kiln_screenshot',
+ 'kiln_submit',
+ ]);
+ });
+
+ test('kiln_screenshot returns [ImageBlock, JsonBlock] with the base64 stripped', async () => {
+ const tools = makeKilnTools({});
+ const out = (await findTool(tools, 'kiln_screenshot').invoke({ code: BOX_CODE })) as unknown[];
+ expect(Array.isArray(out)).toBe(true);
+ expect(out).toHaveLength(2);
+ expect(out[0]).toBeInstanceOf(ImageBlock);
+ expect((out[0] as ImageBlock).format).toBe('png');
+ expect(out[1]).toBeInstanceOf(JsonBlock);
+ const json = (out[1] as JsonBlock).json as Record<string, unknown>;
+ expect(json['ok']).toBe(true);
+ expect('pngBase64' in json).toBe(false);
+ });
+
+ test('kiln_screenshot on broken code falls back to the plain JSON error output', async () => {
+ const tools = makeKilnTools({});
+ const out = (await findTool(tools, 'kiln_screenshot').invoke({ code: 'nope(' })) as {
+ ok: boolean;
+ error?: string;
+ };
+ expect(Array.isArray(out)).toBe(false);
+ expect(out.ok).toBe(false);
+ expect(out.error).toBeDefined();
+ });
+
+ test('kiln_render keeps its plain JSON output (no media wrapping)', async () => {
+ const tools = makeKilnTools({});
+ const out = (await findTool(tools, 'kiln_render').invoke({ code: BOX_CODE })) as {
+ ok: boolean;
+ tris?: number;
+ };
+ expect(Array.isArray(out)).toBe(false);
+ expect(out.ok).toBe(true);
+ expect(out.tris).toBeGreaterThan(0);
+ });
+});
+
+describe('makeKilnEditTools kiln_screenshot', () => {
+ test('defaults to the working buffer and returns image blocks', async () => {
+ const sink: EditSink = { edits: [] };
+ const tools = makeKilnEditTools({ seedCode: BOX_CODE, sink });
+ const out = (await findTool(
+ tools as ReturnType<typeof makeKilnTools>,
+ 'kiln_screenshot',
+ ).invoke({})) as unknown[];
+ expect(Array.isArray(out)).toBe(true);
+ expect(out[0]).toBeInstanceOf(ImageBlock);
+ expect(out[1]).toBeInstanceOf(JsonBlock);
+ });
+});
diff --git a/agent/tools.ts b/agent/tools.ts
index cc280a8d..0f47e75b 100644
--- a/agent/tools.ts
+++ b/agent/tools.ts
@@ -11,7 +11,7 @@
* latter's coexistence with a full tool set is provider-dependent; a submit tool
* is unambiguous and works across every provider.
*/
-import { tool, type Tool, type JSONValue } from '@strands-agents/sdk';
+import { tool, ImageBlock, JsonBlock, type Tool, type JSONValue } from '@strands-agents/sdk';
import { z } from 'zod';
import { kilnToolRegistry } from '../tools/registry';
@@ -36,18 +36,38 @@ const submitInput = z.object({
),
});
+/**
+ * Convert a registry `run()` output into the tool-callback return value. Defs
+ * with a `media` extractor (kiln_screenshot) return [ImageBlock, JsonBlock] so
+ * the model literally sees the rendered views; everything else passes the JSON
+ * output through unchanged. The array of content blocks is a valid (if untyped)
+ * Strands callback return — the SDK's tool-result coercion passes block arrays
+ * through as-is — so it is cast past JSONValue.
+ */
+function toCallbackResult(def: (typeof kilnToolRegistry)[number], output: unknown): JSONValue {
+ const media = def.media?.(output);
+ if (media) {
+ return [
+ new ImageBlock({ format: 'png', source: { bytes: media.png } }),
+ new JsonBlock({ json: media.json as JSONValue }),
+ ] as unknown as JSONValue;
+ }
+ return output as JSONValue;
+}
+
function toStrandsTool(def: (typeof kilnToolRegistry)[number]): Tool {
return tool({
name: def.name,
description: def.description,
inputSchema: def.inputSchema as z.ZodType,
- callback: async (input) => (await def.run(input)) as JSONValue,
+ callback: async (input) => toCallbackResult(def, await def.run(input)),
});
}
/**
* Build the in-process tool list for an agent: the kiln registry tools
- * (list_primitives / validate / render) plus the terminal `kiln_submit` tool.
+ * (list_primitives / validate / render / screenshot) plus the terminal
+ * `kiln_submit` tool.
*
* @param sink - Receives the submitted final code. Read `sink.code` after invoke.
*/
@@ -213,8 +233,8 @@ const submitEditInput = z.object({
/**
* Build the edit-mode tool list for a refine run: list_primitives (as-is),
* `kiln_view` + `kiln_edit` over a working buffer seeded with `seedCode`, plus
- * `kiln_validate` / `kiln_render` / `kiln_submit` that default to the buffer
- * when their `code` arg is omitted. The buffer's live edit trace is shared into
+ * `kiln_validate` / `kiln_render` / `kiln_screenshot` / `kiln_submit` that
+ * default to the buffer when their `code` arg is omitted. The buffer's live edit trace is shared into
* `sink.edits`; `sink.code` tracks the latest buffer (so an un-submitted run
* still captures the edits).
*/
@@ -229,6 +249,7 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
};
const validateDef = find('kiln_validate');
const renderDef = find('kiln_render');
+ const screenshotDef = find('kiln_screenshot');
const listTool = toStrandsTool(find('kiln_list_primitives'));
@@ -272,6 +293,17 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
(await renderDef.run({ code: (input as { code?: string }).code ?? buffer.code })) as JSONValue,
});
+ const screenshotTool: Tool = tool({
+ name: 'kiln_screenshot',
+ description: `${screenshotDef.description} Omit code to screenshot the current working buffer.`,
+ inputSchema: bufferCodeInput,
+ callback: async (input) =>
+ toCallbackResult(
+ screenshotDef,
+ await screenshotDef.run({ code: (input as { code?: string }).code ?? buffer.code }),
+ ),
+ });
+
const submitTool: Tool = tool({
name: KILN_SUBMIT_TOOL_NAME,
description:
@@ -286,5 +318,5 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
},
});
- return [listTool, viewTool, editTool, validateTool, renderTool, submitTool];
+ return [listTool, viewTool, editTool, validateTool, renderTool, screenshotTool, submitTool];
}
diff --git a/generate.ts b/generate.ts
index 8c8c9aa5..827c59cf 100644
--- a/generate.ts
+++ b/generate.ts
@@ -128,6 +128,19 @@ function stripClaudeCodeNestingMarkers(): void {
delete process.env['CLAUDE_CODE_ENTRYPOINT'];
}
+/**
+ * Resolve the codegen mechanism: `KILN_CODEGEN` env > 'agent' default. Shared
+ * by `kiln.generate()` (index.ts) and `generateKilnCode` (this file) so both
+ * forks flip together.
+ */
+export function resolveCodegenMode(explicit?: 'agent' | 'single-shot'): 'agent' | 'single-shot' {
+ if (explicit) return explicit;
+ const env = process.env['KILN_CODEGEN']?.trim().toLowerCase();
+ if (env === 'single-shot' || env === 'singleshot' || env === 'single') return 'single-shot';
+ return 'agent';
+}
+
+
// =============================================================================
// Public API
// =============================================================================
@@ -143,6 +156,40 @@ export async function generateKilnCode(
stripClaudeCodeNestingMarkers();
try {
+ // DEFAULT: the Strands agent tool loop (code-only — callers render
+ // separately, exactly as with the single-shot emitter). This retires the
+ // last fork: the editor server route + editKilnCode now ride the same
+ // engine as the CLI/MCP/batch/studio. Falls through to single-shot for
+ // tsl/both modes, reference-image requests, KILN_CODEGEN=single-shot, or
+ // a model id the agent path can't translate.
+ if (resolveCodegenMode() === 'agent' && request.mode === 'glb' && !request.referenceImageUrl) {
+ // Lazy imports keep @strands-agents/sdk out of the non-agent module
+ // graph (browser/editor bundle safety) — same pattern as kiln.generate.
+ const { harnessIdToAgentModelId } = await import('./agent/providers');
+ const agentModel = opts.model ? harnessIdToAgentModelId(opts.model) : undefined;
+ if (!opts.model || agentModel) {
+ const { generateKilnCodeAgent } = await import('./agent/generate');
+ const result = await generateKilnCodeAgent({
+ prompt: request.prompt,
+ category: request.category,
+ ...(request.style ? { style: request.style } : {}),
+ includeAnimation: request.includeAnimation ?? false,
+ ...(request.existingCode ? { existingCode: request.existingCode } : {}),
+ ...(request.originalPrompt ? { originalPrompt: request.originalPrompt } : {}),
+ ...(agentModel ? { model: agentModel } : {}),
+ });
+ if (!result.success) return { success: false, error: result.error };
+ if (result.code) {
+ const validation = validate(result.code);
+ if (!validation.valid) {
+ return retryWithFeedback(request, result.code, validation.errors, opts);
+ }
+ }
+ return { success: true, code: result.code, usage: result.usage };
+ }
+ // opts.model had no agent translation — single-shot owns that id.
+ }
+
if (shouldUseModelHarness(opts.model)) {
const result = await runHarnessGenerate(request, opts);
if (!result.success) return result;
diff --git a/index.ts b/index.ts
index 43ed6e91..2ceda15d 100644
--- a/index.ts
+++ b/index.ts
@@ -10,7 +10,7 @@
import type { KilnCodeMeta } from './render';
import { renderGLB } from './render';
-import { generateKilnCode } from './generate';
+import { generateKilnCode, resolveCodegenMode } from './generate';
export { renderGLB, renderSceneToGLB, inspectGeneratedAnimation } from './render';
export {
@@ -39,6 +39,11 @@ export type {
} from './inspect';
export { listPrimitives } from './list-primitives';
export type { PrimitiveSpec } from './list-primitives';
+export {
+ renderApiSection,
+ renderPrimitivesMarkdown,
+ renderSkillQuickReference,
+} from './prompt-api';
export {
buildUserPrompt,
getSystemPrompt,
@@ -89,6 +94,7 @@ export {
createWingPair,
beamBetween,
createLadder,
+ snapTo,
foliageCardGeo,
crossedQuadsGeo,
octaGridPlane,
@@ -305,6 +311,14 @@ export interface KilnGenerateOptions {
* path. Falls back to the `KILN_CODEGEN` env var, then 'agent'.
*/
codegen?: 'agent' | 'single-shot';
+ /**
+ * Also rasterize the final asset into the six-view grid PNG (`output.views`)
+ * for sidecars / review UIs. Best-effort; agent codegen path only.
+ */
+ captureViews?: boolean;
+ /** Style anchor: a complete Kiln program rendered as "## Reference Asset"
+ * (fresh generation only). ~5-15k input tokens/run; mostly prompt-cached. */
+ exemplarCode?: string;
}
export interface KilnGenerateOutput {
@@ -324,15 +338,10 @@ export interface KilnGenerateOutput {
toolCalls?: string[];
/** Number of agent-loop iterations (agent path only). */
steps?: number;
+ /** Six-view grid PNG (only when `captureViews` was set; agent path only). */
+ views?: Buffer;
}
-/** Resolve the codegen mechanism: explicit opt > `KILN_CODEGEN` env > 'agent'. */
-function resolveCodegenMode(explicit?: 'agent' | 'single-shot'): 'agent' | 'single-shot' {
- if (explicit) return explicit;
- const env = process.env['KILN_CODEGEN']?.trim().toLowerCase();
- if (env === 'single-shot' || env === 'singleshot' || env === 'single') return 'single-shot';
- return 'agent';
-}
/**
* End-to-end Kiln generation: prompt -> code -> rendered GLB.
@@ -358,6 +367,8 @@ export async function generate(
includeAnimation: opts.includeAnimation ?? true,
...(opts.style ? { style: opts.style } : {}),
...(opts.model ? { model: opts.model } : {}),
+ ...(opts.captureViews ? { captureViews: true } : {}),
+ ...(opts.exemplarCode ? { exemplarCode: opts.exemplarCode } : {}),
});
return {
code: r.code,
@@ -368,6 +379,7 @@ export async function generate(
model: r.model,
toolCalls: r.toolCalls,
steps: r.steps,
+ ...(r.views ? { views: r.views } : {}),
};
}
diff --git a/inspect.ts b/inspect.ts
index 42563b4f..93f5cd60 100644
--- a/inspect.ts
+++ b/inspect.ts
@@ -19,6 +19,7 @@
import * as THREE from 'three';
import { executeKilnCode, inspectGeneratedAnimation } from './render';
+import { listPrimitives } from './list-primitives';
// =============================================================================
// Types
@@ -76,51 +77,12 @@ export interface InspectResult {
// =============================================================================
/**
- * Names of every primitive helper exposed in the Kiln sandbox. Kept in sync
- * with `buildSandboxGlobals` by hand — the catalog is tiny and any drift
- * surfaces immediately in `listPrimitives()` tests.
+ * Names of every primitive helper exposed in the Kiln sandbox, derived from
+ * the canonical catalog (list-primitives.ts) so this detector can never drift
+ * from the real surface — the catalog itself is parity-tested against
+ * `buildSandboxGlobals` in `__tests__/list-primitives.test.ts`.
*/
-const KNOWN_PRIMITIVE_NAMES = [
- 'createRoot',
- 'createPivot',
- 'createPart',
- 'capsuleGeo',
- 'capsuleXGeo',
- 'capsuleYGeo',
- 'capsuleZGeo',
- 'cylinderGeo',
- 'cylinderXGeo',
- 'cylinderYGeo',
- 'cylinderZGeo',
- 'boxGeo',
- 'sphereGeo',
- 'coneGeo',
- 'coneXGeo',
- 'coneYGeo',
- 'coneZGeo',
- 'torusGeo',
- 'planeGeo',
- 'decalBox',
- 'wingGeo',
- 'createWingPair',
- 'beamBetween',
- 'createLadder',
- 'gameMaterial',
- 'basicMaterial',
- 'glassMaterial',
- 'lambertMaterial',
- 'rotationTrack',
- 'positionTrack',
- 'scaleTrack',
- 'createClip',
- 'idleBreathing',
- 'bobbingAnimation',
- 'spinAnimation',
- 'countTriangles',
- 'countMaterials',
- 'getJointNames',
- 'validateAsset',
-] as const;
+const KNOWN_PRIMITIVE_NAMES: readonly string[] = listPrimitives().map((p) => p.name);
function detectPrimitivesUsed(code: string): string[] {
const seen = new Set<string>();
diff --git a/list-primitives.ts b/list-primitives.ts
index 8345d552..3b8c5df3 100644
--- a/list-primitives.ts
+++ b/list-primitives.ts
@@ -23,6 +23,12 @@ export interface PrimitiveSpec {
description: string;
/** Idiomatic usage snippet agents can splice directly into generated code. */
example: string;
+ /**
+ * Extra imperative guidance surfaced verbatim in model-facing renderings of
+ * the catalog (system prompt API section, skill reference). Use for footguns
+ * the description alone does not make actionable.
+ */
+ promptNotes?: string;
/** High-level grouping for filtering in agent UIs. */
category:
| 'geometry'
@@ -70,6 +76,8 @@ const PRIMITIVES: PrimitiveSpec[] = [
'Creates a mesh, optionally wrapped in a pivot, and attaches it to `opts.parent`.',
example:
"createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], parent: root });",
+ promptNotes:
+ 'AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead.',
},
{
name: 'beamBetween',
@@ -82,6 +90,15 @@ const PRIMITIVES: PrimitiveSpec[] = [
example:
"beamBetween('SkidBraceA', [0.8, 0.3, 0.7], [0.8, 1.0, 0.45], 0.025, black, { parent: root });",
},
+ {
+ name: 'snapTo',
+ signature: "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
+ returns: 'THREE.Object3D (the part, for chaining)',
+ category: 'structure',
+ description:
+ 'Translates `part` by the minimal vector that brings its bounding box into contact with `host` (plus a small overlap). The direct cure for a "Floating parts" warning — attach the part instead of eyeballing a corrective offset. No-op if they already touch.',
+ example: "const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });\nsnapTo(scope, receiver);",
+ },
{
name: 'createLadder',
signature:
@@ -282,6 +299,8 @@ const PRIMITIVES: PrimitiveSpec[] = [
'Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must be placed on a surface with position + rotation.',
example:
"const star = decalBox(0.18, 0.18, 0.01);\ncreatePart('Mesh_StarPort', star, gameMaterial(0xc61f2a), { position: [0.4, 0.6, 0.41], parent: fuselage });",
+ promptNotes:
+ 'Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull has faces at z=±0.4, so place the decal at z=±0.41).',
},
{
name: 'foliageCardGeo',
@@ -391,7 +410,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
{
name: 'rotationTrack',
signature:
- 'rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>)',
+ "rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP')",
returns: 'THREE.QuaternionKeyframeTrack',
category: 'animation',
description:
@@ -402,7 +421,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
{
name: 'positionTrack',
signature:
- 'positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>)',
+ "positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
returns: 'THREE.VectorKeyframeTrack',
category: 'animation',
description: 'Position track in world units. Always use `position:` not `value:` in keyframes.',
@@ -412,7 +431,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
{
name: 'scaleTrack',
signature:
- 'scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>)',
+ "scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP')",
returns: 'THREE.VectorKeyframeTrack',
category: 'animation',
description: 'Uniform or per-axis scale track.',
@@ -717,6 +736,8 @@ const PRIMITIVES: PrimitiveSpec[] = [
'Loads a PNG/JPG/WebP image into a Three.js Texture. Stashes the encoded bytes on userData.encoded so GLB export is lossless.',
example:
"const wood = await loadTexture('./textures/oak-albedo.png');",
+ 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: 'pbrMaterial',
diff --git a/primitives.ts b/primitives.ts
index f420b184..ebfb5f3c 100644
--- a/primitives.ts
+++ b/primitives.ts
@@ -609,6 +609,62 @@ export function beamBetween(
return mesh;
}
+/**
+ * Snap a part into contact with a host: translate `part` by the minimal
+ * world-space vector that closes the gap between its bounding box and the
+ * host's, plus a small `overlap` along the dominant gap axis (or the forced
+ * `axis`). The cure for "Floating parts" warnings — instead of eyeballing a
+ * corrective offset, attach the part and let the geometry resolve contact.
+ *
+ * If the boxes already touch or overlap, the part is left in place.
+ * Returns `part` for chaining.
+ */
+export function snapTo(
+ part: THREE.Object3D,
+ host: THREE.Object3D,
+ options: { axis?: 'x' | 'y' | 'z'; overlap?: number } = {},
+): THREE.Object3D {
+ const overlap = options.overlap ?? 0.02;
+ // Boxes in world space (works mid-build; matrices may be stale otherwise).
+ part.updateMatrixWorld(true);
+ host.updateMatrixWorld(true);
+ const a = new THREE.Box3().setFromObject(part);
+ const b = new THREE.Box3().setFromObject(host);
+ if (a.isEmpty() || b.isEmpty()) return part;
+
+ const delta = new THREE.Vector3();
+ for (const axis of ['x', 'y', 'z'] as const) {
+ if (a.min[axis] > b.max[axis]) delta[axis] = b.max[axis] - a.min[axis];
+ else if (a.max[axis] < b.min[axis]) delta[axis] = b.min[axis] - a.max[axis];
+ }
+ if (delta.lengthSq() === 0) return part; // already in contact
+
+ const dominant =
+ options.axis ??
+ (['x', 'y', 'z'] as const).reduce<'x' | 'y' | 'z'>(
+ (d, axis) => (Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d),
+ 'x',
+ );
+ if (delta[dominant] !== 0) delta[dominant] += Math.sign(delta[dominant]) * overlap;
+ else delta[dominant] = -overlap; // forced axis had no gap — bias into the host
+
+ // Convert the world delta into the part's parent space (handles rotated or
+ // scaled ancestors) by mapping two world points.
+ const parent = part.parent;
+ if (parent) {
+ const p0 = new THREE.Vector3();
+ part.getWorldPosition(p0);
+ const p1 = p0.clone().add(delta);
+ const l0 = parent.worldToLocal(p0.clone());
+ const l1 = parent.worldToLocal(p1.clone());
+ part.position.add(l1.sub(l0));
+ } else {
+ part.position.add(delta);
+ }
+ part.updateMatrixWorld(true);
+ return part;
+}
+
export interface LadderOptions {
bottom: Vec3Tuple;
top: Vec3Tuple;
@@ -1180,6 +1236,7 @@ export function buildSandboxGlobals(
createWingPair: wrap('createWingPair', createWingPair),
beamBetween: wrap('beamBetween', beamBetween),
createLadder: wrap('createLadder', createLadder),
+ snapTo: wrap('snapTo', snapTo),
gameMaterial: wrap('gameMaterial', gameMaterial),
basicMaterial: wrap('basicMaterial', basicMaterial),
glassMaterial: wrap('glassMaterial', glassMaterial),
diff --git a/prompt-api.ts b/prompt-api.ts
new file mode 100644
index 00000000..2a2c8031
--- /dev/null
+++ b/prompt-api.ts
@@ -0,0 +1,198 @@
+/**
+ * Model-facing renderings of the Kiln primitive catalog.
+ *
+ * `list-primitives.ts` is the single source of truth for what the sandbox
+ * exposes; this module turns that catalog into the three places models read
+ * it: the system prompt's <api> section, the kiln-glb skill's primitives
+ * reference, and the SKILL.md quick-reference block. All three are generated
+ * at load time (core has no build step; rendering is ~1ms and deterministic),
+ * so adding a primitive to the catalog automatically updates every surface.
+ *
+ * Hand-written pedagogy (usage idioms, attachment rules, worked examples)
+ * stays hand-authored in prompt.ts AROUND the generated enumeration — this
+ * module only renders what the catalog knows.
+ */
+
+import type { PrimitiveSpec } from './list-primitives';
+
+/** Display order + comment header for each catalog category in the prompt. */
+const CATEGORY_HEADERS: Array<[PrimitiveSpec['category'], string]> = [
+ ['structure', '// Scene & structure (globals — no imports needed)'],
+ ['geometry', '// Geometry (returns BufferGeometry)'],
+ ['material', '// Materials'],
+ ['instancing', '// Instancing (share geometry+material; smaller GLBs)'],
+ ['arrays', '// Arrays (replicate a source part)'],
+ [
+ 'csg',
+ '// CSG / Boolean (async — using any of these requires `async function build()`)',
+ ],
+ ['mesh-ops', '// Mesh ops'],
+ ['curves', '// Curves'],
+ ['uv', '// UV unwrapping'],
+ ['textures', '// Textures (loadTexture is async)'],
+ ['animation', '// Animation — keyframes use "rotation"/"position"/"scale" keys, NOT "value"'],
+ ['utility', '// Inspection utilities'],
+];
+
+const WRAP = 96;
+
+/** Wrap text into `// `-prefixed comment lines at ~WRAP columns. */
+function wrapComment(text: string, indent: string): string[] {
+ const words = text.split(/\s+/);
+ const lines: string[] = [];
+ let line = '';
+ for (const w of words) {
+ if (line && (indent + '// ' + line + ' ' + w).length > WRAP) {
+ lines.push(`${indent}// ${line}`);
+ line = w;
+ } else {
+ line = line ? `${line} ${w}` : w;
+ }
+ }
+ if (line) lines.push(`${indent}// ${line}`);
+ return lines;
+}
+
+function renderPrimitiveLines(p: PrimitiveSpec): string[] {
+ const oneLiner = `${p.signature} // ${p.description}`;
+ const lines: string[] = [];
+ if (oneLiner.length <= WRAP + 20 && !p.description.includes('\n')) {
+ lines.push(oneLiner);
+ } else {
+ lines.push(p.signature);
+ lines.push(...wrapComment(p.description, ' '));
+ }
+ if (p.promptNotes) {
+ lines.push(...wrapComment(`NOTE: ${p.promptNotes}`, ' '));
+ }
+ return lines;
+}
+
+/**
+ * Render the catalog enumeration that fills the system prompt's <api> section:
+ * category comment headers followed by one entry per primitive (signature plus
+ * a wrapped description comment and any promptNotes). Order is the canonical
+ * category order, primitives in catalog order within each category.
+ */
+export function renderApiSection(primitives: PrimitiveSpec[]): string {
+ const byCategory = new Map<string, PrimitiveSpec[]>();
+ for (const p of primitives) {
+ const list = byCategory.get(p.category) ?? [];
+ list.push(p);
+ byCategory.set(p.category, list);
+ }
+
+ const blocks: string[] = [];
+ for (const [category, header] of CATEGORY_HEADERS) {
+ const list = byCategory.get(category);
+ if (!list || list.length === 0) continue;
+ const lines = [header];
+ for (const p of list) lines.push(...renderPrimitiveLines(p));
+ blocks.push(lines.join('\n'));
+ }
+
+ // Catch categories the header table does not know yet — never drop entries.
+ const known = new Set(CATEGORY_HEADERS.map(([c]) => c));
+ for (const [category, list] of byCategory) {
+ if (known.has(category as PrimitiveSpec['category'])) continue;
+ const lines = [`// ${category}`];
+ for (const p of list) lines.push(...renderPrimitiveLines(p));
+ blocks.push(lines.join('\n'));
+ }
+
+ return blocks.join('\n\n');
+}
+
+/**
+ * Render the full markdown primitives reference for the kiln-glb skill
+ * (`references/primitives.md`). One section per category, one subsection per
+ * primitive with signature, returns, description, notes, and example.
+ */
+export function renderPrimitivesMarkdown(primitives: PrimitiveSpec[]): string {
+ const byCategory = new Map<string, PrimitiveSpec[]>();
+ for (const p of primitives) {
+ const list = byCategory.get(p.category) ?? [];
+ list.push(p);
+ byCategory.set(p.category, list);
+ }
+
+ const titles: Record<string, string> = {
+ structure: 'Scene & Structure',
+ geometry: 'Geometry',
+ material: 'Materials',
+ instancing: 'Instancing',
+ arrays: 'Arrays',
+ csg: 'CSG / Boolean (async)',
+ 'mesh-ops': 'Mesh Ops',
+ curves: 'Curves',
+ uv: 'UV Unwrapping',
+ textures: 'Textures',
+ animation: 'Animation',
+ utility: 'Inspection Utilities',
+ };
+
+ const parts: string[] = [
+ '# Kiln Primitives Reference',
+ '',
+ '<!-- GENERATED FILE — do not edit by hand. -->',
+ '<!-- Source: packages/core/src/kiln/list-primitives.ts -->',
+ '<!-- Regenerate: bun run kiln:gen-skill -->',
+ '',
+ `Every helper the Kiln sandbox exposes to generated code (${primitives.length} primitives). No imports needed — all are globals inside build()/animate().`,
+ ];
+
+ const order = [...CATEGORY_HEADERS.map(([c]) => c)];
+ for (const [category] of byCategory) {
+ if (!order.includes(category as PrimitiveSpec['category'])) {
+ order.push(category as PrimitiveSpec['category']);
+ }
+ }
+
+ for (const category of order) {
+ const list = byCategory.get(category);
+ if (!list || list.length === 0) continue;
+ parts.push('', `## ${titles[category] ?? category}`);
+ for (const p of list) {
+ parts.push('', `### ${p.name}`, '', '```typescript', p.signature, '```', '');
+ parts.push(`Returns: ${p.returns}`, '', p.description);
+ if (p.promptNotes) parts.push('', `**Note:** ${p.promptNotes}`);
+ parts.push('', '```javascript', p.example, '```');
+ }
+ }
+
+ parts.push('');
+ return parts.join('\n');
+}
+
+/**
+ * Render the compact quick-reference block for SKILL.md (spliced between the
+ * BEGIN/END GENERATED PRIMITIVES markers): per-category signature lists only,
+ * pointing at references/primitives.md for detail.
+ */
+export function renderSkillQuickReference(primitives: PrimitiveSpec[]): string {
+ const byCategory = new Map<string, PrimitiveSpec[]>();
+ for (const p of primitives) {
+ const list = byCategory.get(p.category) ?? [];
+ list.push(p);
+ byCategory.set(p.category, list);
+ }
+
+ const lines: string[] = [
+ `All ${primitives.length} sandbox primitives, grouped (full signatures, descriptions, and examples in \`references/primitives.md\`):`,
+ '',
+ '```typescript',
+ ];
+ for (const [category, header] of CATEGORY_HEADERS) {
+ const list = byCategory.get(category);
+ if (!list || list.length === 0) continue;
+ lines.push(header);
+ for (const p of list) {
+ lines.push(p.signature);
+ if (p.promptNotes) lines.push(...wrapComment(`NOTE: ${p.promptNotes}`, ' '));
+ }
+ lines.push('');
+ }
+ while (lines[lines.length - 1] === '') lines.pop();
+ lines.push('```');
+ return lines.join('\n');
+}
diff --git a/prompt.ts b/prompt.ts
index ff7e8760..a0b27847 100644
--- a/prompt.ts
+++ b/prompt.ts
@@ -5,8 +5,19 @@
* `packages/shared/kiln-prompts.ts`; that file has been retired in favor of
* this one. Server imports via `@pixel-forge/core/kiln` (the route wrapper
* re-exports through `services/claude`).
+ *
+ * The GLB system prompt is decomposed into named sections so each piece can
+ * be reviewed, tested, and reused independently. The <api> enumeration is
+ * GENERATED at load time from the primitive catalog (list-primitives.ts via
+ * prompt-api.ts) — adding a primitive to the catalog updates the prompt, the
+ * kiln_list_primitives tool, and the skill reference together. Hand-written
+ * pedagogy (idioms, attachment rules, worked examples) stays hand-authored
+ * around that enumeration.
*/
+import { listPrimitives } from './list-primitives';
+import { renderApiSection } from './prompt-api';
+
export type RenderMode = 'glb' | 'tsl' | 'both';
export type AssetCategory = 'character' | 'prop' | 'vfx' | 'environment';
export type AssetStyle = 'low-poly' | 'stylized' | 'voxel' | 'detailed' | 'realistic';
@@ -63,14 +74,14 @@ Generate assets with realistic proportions and detail:
};
// =============================================================================
-// System Prompts
+// GLB System Prompt — named sections
// =============================================================================
-export const KILN_SYSTEM_PROMPT = `You are an expert procedural 3D asset generator. Create game-ready models with character and style.
+export const KILN_PROMPT_HEADER = `You are an expert procedural 3D asset generator. Create game-ready models with character and style.
-CRITICAL: NO import/export statements. Code runs in a sandbox with primitives as globals.
+CRITICAL: NO import/export statements. Code runs in a sandbox with primitives as globals.`;
-<file-format>
+export const KILN_FILE_FORMAT = `<file-format>
const meta = { name: "AssetName", category: "prop" };
// build() may be sync OR async. Mark it async if you use any CSG op
@@ -93,9 +104,9 @@ async function build() { // use this form when any await is needed
function animate(root) { // optional
return [clip1, clip2];
}
-</file-format>
+</file-format>`;
-<coordinate-contract>
+export const KILN_COORDINATE_CONTRACT = `<coordinate-contract>
World coordinates are strict:
- +X = forward / nose / muzzle direction
- +Y = up
@@ -105,118 +116,42 @@ World coordinates are strict:
Vehicles, aircraft, weapons, boats, and buildings must follow this frame. If a
part points forward, build it along +X. If a part spans left/right, build it
along Z. Do not make each asset invent its own forward axis.
-</coordinate-contract>
+</coordinate-contract>`;
-<api>
-// Scene (no imports needed - globals)
-createRoot(name: string): Object3D
-createPivot(name: string, position: [x,y,z], parent: Object3D): Object3D
-createPart(name, geo, mat, opts): Object3D // AUTO-ADDS to opts.parent! Do NOT call .add() on result
-
-// createPart usage - it automatically adds to parent:
-createPart("Name", geometry, material, { position: [x,y,z], parent: parentObj });
-// WRONG: parent.add(createPart(...)) // DO NOT DO THIS
-// RIGHT: createPart("Name", geo, mat, { parent: parentObj }); // auto-adds
-
-// Geometry (returns BufferGeometry)
-boxGeo(width, height, depth)
-sphereGeo(radius, widthSegs=8, heightSegs=6)
-cylinderGeo(radiusTop, radiusBot, height, segments=8) // Y-axis (preferred)
-cylinderXGeo(radiusTop, radiusBot, length, segments=8) // X-axis
-cylinderYGeo(radiusTop, radiusBot, length, segments=8) // alias for cylinderGeo (Y-axis)
-cylinderZGeo(radiusTop, radiusBot, length, segments=8) // Z-axis
-cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom, height, opts?: { radiusTop?, segments? }) // arbitrary axis — use only when not cardinal
-coneGeo(radius, height, segments=8) // Y-axis, point +Y (preferred)
-coneXGeo(radius, length, segments=8) // point +X
-coneYGeo(radius, length, segments=8) // alias for coneGeo (point +Y)
-coneZGeo(radius, length, segments=8) // point +Z
-taperConeGeo(radiusBottom, radiusTop, height, axis?='y', segments?=8) // truncated cone / frustum — use for soda cans, pylon caps, lampshades
-capsuleGeo(radius, height, segments=6) // Y-axis (preferred)
-capsuleXGeo(radius, length, segments=6) // X-axis
-capsuleYGeo(radius, length, segments=6) // alias for capsuleGeo (Y-axis)
-capsuleZGeo(radius, length, segments=6) // Z-axis
-torusGeo(radius, tube, radialSegs=8, tubularSegs=12)
-planeGeo(width, height, widthSegs=1, heightSegs=1) // texture-only; for solid-color decals use decalBox
-decalBox(width, height, depth=0.01) // flat box for solid-color decals: red stars, hull numbers, stamps, windows on no-texture assets. MUST be placed on a surface via position + rotation.
-wingGeo({ span, rootChord, tipChord, sweep, thickness, dihedral }) // root at Z=0, span extends +Z
-gearGeo({ teeth=12, rootRadius=0.8, tipRadius=1.0, boreRadius=0.2, height=0.3, toothWidthFrac=0.5 }) // parametric gear, flat-shaded
-bladeGeo({ length=1.5, baseWidth=0.1, thickness=0.015, tipLength=0.25, edgeBevel=0 }) // tapered sword blade with pointed tip
-
-// Attachment helpers
-beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, { segments?, parent? })
-createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })
-createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })
-
-// Materials
-gameMaterial(0xcolor, {metalness?, roughness?, emissive?, flatShading?})
-lambertMaterial(0xcolor, {flatShading?, emissive?})
-glassMaterial(0xcolor, {opacity?, roughness?, metalness?}) // transparent, DoubleSide - cockpits, windows
-basicMaterial(0xcolor, {transparent?, opacity?})
-
-// Instancing (share geometry+material; smaller GLBs)
-createInstance(name, sourceObj, { position?, rotation?, scale?, parent? })
-// Pattern for repeated parts (4 wheels, 10 posts, 12 bolts):
+/**
+ * Hand-authored usage idioms that close out the <api> section — the patterns
+ * the enumeration alone cannot teach (multi-step pipelines, WRONG/RIGHT pairs).
+ */
+export const KILN_API_IDIOMS = `// Usage idioms:
+// createPart auto-adds to its parent:
+// WRONG: parent.add(createPart(...)) // DO NOT DO THIS
+// RIGHT: createPart("Name", geo, mat, { parent: parentObj }); // auto-adds
+// Repeated parts (4 wheels, 10 posts, 12 bolts) — build one, instance the rest:
// const wheelFL = createPart("WheelFL", wheelGeo, rubberMat, { position: [...], parent: root });
// createInstance("WheelFR", wheelFL, { position: [...], parent: root });
-// GLB exports these as true mesh instances — one geometry, many nodes.
-
-// Arrays (replicate a source part)
-arrayLinear(namePrefix, source, count, [x,y,z], parent?) // returns Object3D[]
-arrayRadial(namePrefix, source, count, 'x'|'y'|'z', parent?) // returns Object3D[]
-mirror(name, source, 'x'|'y'|'z', parent?) // returns Object3D
-
-// CSG / Boolean (async - requires \`async function build()\`)
-// Default: flat shading (hard mechanical edges). Pass { smooth: true }
-// as the LAST arg for averaged normals on organic/blended merges.
-await boolUnion(name, ...parts, opts?) // merge into one watertight mesh
-await boolDiff(name, body, ...cutters, opts?) // subtract cutters from body (holes, recesses)
-await boolIntersect(name, a, b, opts?) // keep overlapping volume only
-await hull(name, ...parts, opts?) // tightest convex hull (defaults to smooth)
-
-// Mesh ops
-subdivide(geometry, iterations=1) // Loop subdivision, returns new BufferGeometry (auto-welds non-indexed input)
-mergeVertices(geometry, tolerance=1e-4) // weld coincident verts; call before deforming/subdividing box/sphere/cylinder
-
-// Curves
-curveToMesh(points: [x,y,z][], radius, tubularSegs=32, radialSegs=8, closed=false) // returns BufferGeometry (tube)
-pipeAlongPath(points: [x,y,z][], radius, opts?: { bendRadius?, closed?, tubularSegments?, radialSegments? }) // path-driven swept circle with corner smoothing — use for cables, hoses, tubing, rigging
-lathe(profile: [x,y][], segments=12) // surface of revolution around Y axis (vase, wheel, bottle)
-revolveGeo(profile: [x,y][], opts?: { angle?=2π, axis?=[0,1,0], segments?=12 }) // partial sweep / non-Y axis (half-domes, 90° wedges, fan blades around +X)
-bezierCurve(ctrlPts: [x,y,z][], samples=32) // returns [x,y,z][] — feed into curveToMesh
-
-// UV + Textures (loadTexture is async; shape-aware unwraps are sync)
-await autoUnwrap(geometry, { resolution?: 1024, padding?: 2 }) // xatlas atlas — for CSG/subdivided/deformed meshes
-boxUnwrap(boxGeo(...)) // preserves per-face [0,1] UVs — crates, blocks
-cylinderUnwrap(cylinderGeo(...)) // u around axis, v up — barrels, pipes (texture bands ring the mesh)
-planeUnwrap(planeGeo(...)) // xy-extent → [0,1] — signs, decals, posters
-panelRemapV(geo, vScale=0.30) // rescale UV.y so a SMALL part samples a sub-region of a SHARED texture (e.g. clean v=0..0.30 panel zone)
-await loadTexture(path) // returns THREE.DataTexture with encoded bytes stashed for GLB export
-pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? }) // Any slot = color/scalar OR Texture
-// Do NOT clone a loaded texture (texture.clone() corrupts userData via JSON.stringify, breaking GLB export).
-// Use panelRemapV on the SMALL mesh's geometry instead, sharing the same Texture object across materials.
-
+// GLB exports these as true mesh instances — one geometry, many nodes.
// Textured asset pipeline:
// 1. Build a geometry (boxGeo / CSG / subdivide / curveToMesh / etc)
// 2. \`await autoUnwrap(geo)\` → adds a uv attribute
// 3. \`await loadTexture(path)\` → load albedo/normal/etc PNG
// 4. \`pbrMaterial({ albedo: tex, ... })\` → build PBR material
// 5. new THREE.Mesh(unwrappedGeo, mat) → attach to scene
-
// THREE namespace is exposed — use \`new THREE.Mesh(geo, mat)\` when an op needs a
// Mesh input (like CSG operands) without attaching it to the scene.
+// animate() must return an ARRAY of clips:
+// function animate(root) { return [clip1, clip2]; }`;
-// Animation - IMPORTANT: keyframes use "rotation" or "position" keys, NOT "value"
-rotationTrack(jointName: string, keyframes: [{time, rotation: [x,y,z]}], interp?: 'LINEAR'|'STEP')
-positionTrack(jointName: string, keyframes: [{time, position: [x,y,z]}], interp?: 'LINEAR'|'STEP')
-createClip(name: string, duration: number, tracks: Track[])
-spinAnimation(jointName, duration, axis: 'x'|'y'|'z') // returns a clip
-bobbingAnimation(rootName, duration, height) // returns a clip
+/**
+ * The <api> section: the generated catalog enumeration (single source of
+ * truth: list-primitives.ts) followed by the hand-authored idioms.
+ */
+export const KILN_API_SECTION = `<api>
+${renderApiSection(listPrimitives())}
-// animate() must return an ARRAY of clips
-function animate(root) { return [clip1, clip2]; }
-</api>
+${KILN_API_IDIOMS}
+</api>`;
-<architecture>
+export const KILN_ARCHITECTURE = `<architecture>
Use Pivot+Mesh pattern for animated parts:
- Joint_* = pivot node (animate this) - created by createPivot or createPart with pivot:true
- Mesh_* = geometry node (child of pivot)
@@ -224,17 +159,17 @@ Use Pivot+Mesh pattern for animated parts:
For animations, track names must use "Joint_" prefix:
- createPivot("Body", ...) creates "Joint_Body" - animate with rotationTrack("Joint_Body", ...)
- createPart("Wheel", ..., {pivot: true}) creates "Joint_Wheel" - animate it
-</architecture>
+</architecture>`;
-<quality>
+export const KILN_QUALITY = `<quality>
- Give your asset personality and character
- Use appropriate level of detail for the category
- Colors should be cohesive and intentional
- Animations should feel natural and loop seamlessly
- Name parts descriptively (Body, LeftArm, Wheel)
-</quality>
+</quality>`;
-<attachment-rules>
+export const KILN_ATTACHMENT_RULES = `<attachment-rules>
- Use cylinderXGeo / capsuleXGeo / coneXGeo for forward-facing bodies, barrels,
aircraft fuselages, missiles, and weapon muzzles. Do not hand-rotate Y-axis
cylinders unless you have a specific reason.
@@ -263,9 +198,9 @@ For animations, track names must use "Joint_" prefix:
units. Floating parts are invalid even if the named-parts check passes.
- Low triangle count is not the goal by itself. Spend triangles where silhouette
matters: cockpits, wheels, rotors, wings, organic rocks, and curved aircraft.
-</attachment-rules>
+</attachment-rules>`;
-<rules>
+export const KILN_RULES = `<rules>
- Colors as hex: 0xff0000
- Coordinates: +X forward, +Y up, +Z right, ground at Y=0
- Animate pivots only (Joint_* names)
@@ -277,15 +212,33 @@ For animations, track names must use "Joint_" prefix:
- Output ONLY valid JavaScript code (no TypeScript types)
- NEVER call .add() on createPart result - it auto-adds to parent
- Z-FIGHTING PREVENTION: No two mesh faces may be coplanar or near-coplanar. All decorative geometry (decals, markings, edge strips, reinforcements, trim) must be fully outside the parent mesh - never intersecting or flush. Offset at least 0.01 from the nearest surface. If a box is 0.6 wide (edges at x=+-0.3), place edge trim at x=+-0.31, NOT x=+-0.29. Minimum 0.01 thickness for flat parts.
-</rules>
+</rules>`;
-<critical-animation-format>
+export const KILN_ANIMATION_FORMAT = `<critical-animation-format>
WRONG: { time: 0, value: [0,0,0] }
RIGHT: { time: 0, rotation: [0,0,0] } for rotationTrack (degrees)
RIGHT: { time: 0, position: [0,0,0] } for positionTrack
-</critical-animation-format>
+</critical-animation-format>`;
-<example name="animated-chest">
+/**
+ * What to verify in the kiln_screenshot grid before submitting — ties the
+ * vision loop to concrete, per-view checks instead of "look at it".
+ */
+export const KILN_VISUAL_QA = `<visual-qa>
+Before kiln_submit, call kiln_screenshot and check each view deliberately:
+- Front (camera on +X): the nose/muzzle/face should point AT you. If you see
+ a side profile here, the asset is built sideways — rebuild along +X.
+- Right (+Z): the long profile. Check silhouette: proportions, ground contact
+ at the bottom edge, nothing important missing.
+- Back / Left: symmetry with their opposites; no missing or one-sided parts.
+- Top (+Y): left/right symmetry; wings/axles/rails centered on the body.
+- 3/4: part CONTACT. Look for gaps where parts should touch (struts, ladder
+ rails, wing roots, attachments). A visible gap means a floating part — fix
+ the position or call snapTo(part, host), then screenshot again.
+If any view looks wrong, fix the code and re-screenshot before submitting.
+</visual-qa>`;
+
+export const KILN_EXAMPLES = `<example name="animated-chest">
const meta = { name: "Chest", category: "prop" };
function build() {
@@ -394,8 +347,60 @@ function build() {
return root;
}
+</example>
+
+<example name="attached-watchtower-leg-braces">
+// Attachment discipline: beamBetween for braces whose ENDPOINTS lie on the
+// parts they connect; snapTo to resolve contact instead of eyeballing offsets.
+const meta = { name: "TowerBase", category: "environment" };
+
+function build() {
+ const root = createRoot("TowerBase");
+ const wood = gameMaterial(0x7a5a38, { roughness: 0.9 });
+
+ // Platform 2.0 up; four legs from the ground to the platform underside.
+ const platform = createPart("Platform", boxGeo(1.6, 0.12, 1.6), wood, {
+ position: [0, 2.0, 0], parent: root
+ });
+ for (const [x, z] of [[0.7, 0.7], [0.7, -0.7], [-0.7, 0.7], [-0.7, -0.7]]) {
+ createPart("Leg", cylinderGeo(0.07, 0.09, 2.0, 6), wood, {
+ position: [x, 1.0, z], parent: root
+ });
+ }
+
+ // Cross braces: endpoints ON the leg surfaces, so they visibly connect.
+ const dark = gameMaterial(0x5a4128, { roughness: 0.9 });
+ beamBetween("BraceA", [0.7, 0.3, 0.7], [-0.7, 1.5, 0.7], 0.035, dark, { parent: root });
+ beamBetween("BraceB", [-0.7, 0.3, 0.7], [0.7, 1.5, 0.7], 0.035, dark, { parent: root });
+
+ // A lamp that must TOUCH the platform underside: place it close, then let
+ // snapTo close the remaining gap (no z-fighting math by hand).
+ const lamp = createPart("Lamp", sphereGeo(0.09, 8, 6), gameMaterial(0xffc864, { emissive: 0xa86a1e }), {
+ position: [0.5, 1.78, 0.5], parent: root
+ });
+ snapTo(lamp, platform);
+
+ return root;
+}
</example>`;
+/** Ordered sections of the GLB system prompt (exported for tests/ablation). */
+export const KILN_SYSTEM_PROMPT_SECTIONS: ReadonlyArray<readonly [string, string]> = [
+ ['header', KILN_PROMPT_HEADER],
+ ['file-format', KILN_FILE_FORMAT],
+ ['coordinate-contract', KILN_COORDINATE_CONTRACT],
+ ['api', KILN_API_SECTION],
+ ['architecture', KILN_ARCHITECTURE],
+ ['quality', KILN_QUALITY],
+ ['attachment-rules', KILN_ATTACHMENT_RULES],
+ ['rules', KILN_RULES],
+ ['animation-format', KILN_ANIMATION_FORMAT],
+ ['visual-qa', KILN_VISUAL_QA],
+ ['examples', KILN_EXAMPLES],
+];
+
+export const KILN_SYSTEM_PROMPT = KILN_SYSTEM_PROMPT_SECTIONS.map(([, s]) => s).join('\n\n');
+
export const KILN_TSL_SYSTEM_PROMPT = `You are an expert shader artist. Create stunning real-time visual effects using Three.js TSL.
<file-format>
@@ -583,9 +588,51 @@ RULES:
// Prompt Helpers
// =============================================================================
-export function getSystemPrompt(mode: RenderMode): string {
+/**
+ * The trimmed <api> stub: instead of the full generated enumeration, a ~15
+ * line category map plus an explicit instruction to discover signatures via
+ * the kiln_list_primitives tool. The ablation arm for measuring whether the
+ * full enumeration earns its tokens (kiln-bench prompt axis).
+ */
+export const KILN_API_SECTION_TRIMMED = `<api>
+The sandbox exposes ~70 primitive helpers as globals (no imports), grouped:
+- Scene & structure: createRoot, createPivot, createPart (AUTO-ADDS to parent —
+ never call parent.add on its result), beamBetween, createLadder,
+ createWingPair, snapTo
+- Geometry: boxGeo, sphereGeo, cylinder/capsule/cone in Y (default) + X + Z
+ axis variants, taperConeGeo, torusGeo, planeGeo (textured only), decalBox,
+ wingGeo, gearGeo, bladeGeo, billboard cards
+- Materials: gameMaterial, glassMaterial, lambertMaterial, basicMaterial, pbrMaterial
+- Repetition: createInstance, arrayLinear, arrayRadial, mirror
+- CSG (async build() required): boolUnion, boolDiff, boolIntersect, hull
+- Mesh ops & curves: subdivide, mergeVertices, curveToMesh, pipeAlongPath, lathe, revolveGeo
+- UV + textures: autoUnwrap, boxUnwrap, cylinderUnwrap, planeUnwrap, panelRemapV, loadTexture
+- Animation: rotationTrack/positionTrack/scaleTrack (keys are "rotation"/"position"/"scale",
+ NOT "value"), createClip, spinAnimation, bobbingAnimation, idleBreathing
+
+IMPORTANT: call the kiln_list_primitives tool BEFORE writing any code to get
+exact signatures, defaults, and idiomatic examples for the helpers you plan to
+use. THREE is also exposed (new THREE.Mesh(geo, mat) for CSG operands).
+</api>`;
+
+export interface GetSystemPromptOptions {
+ /**
+ * How much of the primitive catalog rides in the system prompt:
+ * 'full' (default) embeds the complete generated enumeration; 'trimmed'
+ * sends the ~15-line stub above and relies on the kiln_list_primitives
+ * tool for discovery. Bench-measured via the prompt axis.
+ */
+ apiSurface?: 'full' | 'trimmed';
+}
+
+export function getSystemPrompt(mode: RenderMode, opts: GetSystemPromptOptions = {}): string {
if (mode === 'tsl') return KILN_TSL_SYSTEM_PROMPT;
if (mode === 'both') return KILN_BOTH_SYSTEM_PROMPT;
+ if (opts.apiSurface === 'trimmed') {
+ return KILN_SYSTEM_PROMPT_SECTIONS.map(([name, s]) =>
+ name === 'api' ? KILN_API_SECTION_TRIMMED : s,
+ ).join('\n\n');
+ }
return KILN_SYSTEM_PROMPT;
}
@@ -626,6 +673,17 @@ export interface KilnGenerateRequest {
* knows the asset's intent, not just its source. Ignored for fresh generation. */
originalPrompt?: string;
referenceImageUrl?: string;
+ /**
+ * A complete Kiln program rendered as a "## Reference Asset (style anchor)"
+ * section — the model studies its idioms (proportions, segment counts,
+ * attachment patterns, palette discipline) and builds the NEW asset in the
+ * same style. Fresh generation only: suppressed when `existingCode` is set
+ * (a refine already anchors on the parent's source).
+ *
+ * Token cost: a typical canonical program adds ~5-15k input tokens per run;
+ * prompt caching absorbs most of it on repeated batch use.
+ */
+ exemplarCode?: string;
}
export function buildUserPrompt(request: KilnGenerateRequest): string {
@@ -649,6 +707,14 @@ export function buildUserPrompt(request: KilnGenerateRequest): string {
parts.push('');
}
+ // Style anchor (fresh generation only — a refine anchors on the parent).
+ if (request.exemplarCode && !request.existingCode) {
+ parts.push(
+ `## Reference Asset (style anchor)\n\nStudy this finished Kiln program: its proportions, segment counts, attachment patterns, naming, and palette discipline define the style to match. Build the NEW asset requested below in the same style — do NOT copy or reproduce the reference asset itself.\n\n\`\`\`javascript\n${request.exemplarCode}\n\`\`\``,
+ );
+ parts.push('');
+ }
+
// Main request
if (request.existingCode) {
// Refine framing: Original Request (intent) -> Current Code (source) -> Edit Request.
diff --git a/render.ts b/render.ts
index 3bd51044..f3eacbfd 100644
--- a/render.ts
+++ b/render.ts
@@ -643,12 +643,61 @@ function collectMeshStats(root: THREE.Object3D): MeshStats[] {
* Emits strings compatible with the existing `warnings` channel on
* `RenderResult`. `_direct-generate.ts` threshold-checks these to trigger
* a single corrective retry.
+ *
+ * Floating-part warnings carry an actionable fix: the minimal world-space
+ * shift that brings the floater into contact with its nearest sibling (or the
+ * `snapTo(part, host)` call that applies it).
+ *
+ * Pass `opts.category` (vehicle / weapon / boat / aircraft) to additionally
+ * run the orientation advisory: kiln assets face +X, so a vehicle whose Z
+ * extent dominates its X extent was probably built sideways. Aircraft skip
+ * the Z check (wingspan legitimately dominates) and check Y instead.
*/
-export function inspectSceneStructure(root: THREE.Object3D): string[] {
+export interface InspectStructureOptions {
+ /** Asset kind for the orientation advisory. Omit to skip it. */
+ category?: 'vehicle' | 'weapon' | 'boat' | 'aircraft' | (string & {});
+}
+
+/** Minimal world-space translation that closes the gap between two boxes
+ * (zero on axes that already overlap). */
+function minimalGapVector(a: THREE.Box3, b: THREE.Box3): THREE.Vector3 {
+ const v = new THREE.Vector3();
+ for (const axis of ['x', 'y', 'z'] as const) {
+ if (a.min[axis] > b.max[axis]) v[axis] = b.max[axis] - a.min[axis];
+ else if (a.max[axis] < b.min[axis]) v[axis] = b.min[axis] - a.max[axis];
+ else v[axis] = 0;
+ }
+ return v;
+}
+
+export function inspectSceneStructure(
+ root: THREE.Object3D,
+ opts: InspectStructureOptions = {},
+): string[] {
const warnings: string[] = [];
const meshes = collectMeshStats(root);
if (meshes.length === 0) return warnings;
+ // Orientation advisory (category-aware; runs even for single-mesh scenes).
+ const cat = opts.category?.toLowerCase();
+ if (cat === 'vehicle' || cat === 'weapon' || cat === 'boat' || cat === 'aircraft') {
+ const all = new THREE.Box3();
+ for (const m of meshes) all.union(m.box);
+ const size = new THREE.Vector3();
+ all.getSize(size);
+ if (cat === 'aircraft') {
+ if (size.y > size.x * 1.2) {
+ warnings.push(
+ `Orientation: this aircraft is ${size.y.toFixed(2)} tall but only ${size.x.toFixed(2)} long along +X (the nose axis). Kiln aircraft fly nose-first along +X — it may be built vertically or sideways.`,
+ );
+ }
+ } else if (size.z > size.x * 1.3) {
+ warnings.push(
+ `Orientation: this ${cat} spans ${size.z.toFixed(2)} along Z but only ${size.x.toFixed(2)} along +X. Kiln ${cat}s face +X (forward/muzzle/bow) — it looks built sideways; rebuild the long axis along X.`,
+ );
+ }
+ }
+
const STRAY_CENTROID_TOL = 0.02;
const FLOATING_EXPAND = 0.02;
const DECAL_EXTENT_MAX = 0.5; // anything smaller than 50cm fits decal profile
@@ -678,14 +727,104 @@ export function inspectSceneStructure(root: THREE.Object3D): string[] {
break;
}
}
- if (!overlapsAny) floaters.push(a.name);
+ if (overlapsAny) continue;
+
+ // Actionable fix: the minimal shift to the NEAREST sibling, plus the
+ // snapTo call that applies it.
+ let nearest: MeshStats | undefined;
+ let nearestGap: THREE.Vector3 | undefined;
+ for (let j = 0; j < meshes.length; j++) {
+ if (i === j) continue;
+ const gap = minimalGapVector(a.box, meshes[j]!.box);
+ if (!nearestGap || gap.length() < nearestGap.length()) {
+ nearest = meshes[j]!;
+ nearestGap = gap;
+ }
+ }
+ const fix =
+ nearest && nearestGap
+ ? ` Fix: shift "${a.name}" by [${nearestGap.x.toFixed(3)}, ${nearestGap.y.toFixed(3)}, ${nearestGap.z.toFixed(3)}] toward "${nearest.name}", or call snapTo(part, hostPart) to do it automatically.`
+ : '';
+ floaters.push(`${a.name}${fix ? ' —' + fix : ''}`);
}
if (floaters.length > 0) {
warnings.push(
- `Floating parts (no mesh overlap with any sibling, 2cm tol): ${floaters.join(', ')}. Move these so their bbox contacts a parent/surface mesh.`,
+ `Floating parts (no mesh overlap with any sibling, 2cm tol): ${floaters.join(' | ')}`,
);
}
}
return warnings;
}
+
+/**
+ * OPT-IN geometry settle: translate each floating mesh into contact with its
+ * nearest sibling, but only when the gap is small (≤ `maxGap`). Deliberately
+ * NOT applied inside kiln_render or renderGLB — silently mutating geometry
+ * would desync the code from the artifact and poison refine loops. The batch
+ * harness uses it after a soft-retry still warns, and records the settled part
+ * names in provenance so the mutation is visible.
+ *
+ * Returns the names of the parts that were moved.
+ */
+export function settleContacts(
+ root: THREE.Object3D,
+ opts: { maxGap?: number; overlap?: number } = {},
+): string[] {
+ const maxGap = opts.maxGap ?? 0.05;
+ const overlap = opts.overlap ?? 0.01;
+ const settled: string[] = [];
+
+ // One move per pass, then re-collect: moving a part changes every other
+ // part's floating status (with two meshes BOTH read as floaters — moving
+ // either resolves both). Among the settleable floaters, move the smallest
+ // (it's the attachment, not the hull).
+ for (let pass = 0; pass < 8; pass++) {
+ const meshes = collectMeshStats(root);
+ if (meshes.length < 2) return settled;
+
+ let pick: { stats: MeshStats; gap: THREE.Vector3; volume: number } | undefined;
+ for (let i = 0; i < meshes.length; i++) {
+ const a = meshes[i]!;
+ const ax = a.box.clone().expandByScalar(0.02);
+ if (meshes.some((b, j) => j !== i && ax.intersectsBox(b.box))) continue;
+
+ let nearestGap: THREE.Vector3 | undefined;
+ for (let j = 0; j < meshes.length; j++) {
+ if (i === j) continue;
+ const gap = minimalGapVector(a.box, meshes[j]!.box);
+ if (!nearestGap || gap.length() < nearestGap.length()) nearestGap = gap;
+ }
+ if (!nearestGap || nearestGap.length() === 0 || nearestGap.length() > maxGap) continue;
+
+ const volume = a.size.x * a.size.y * a.size.z;
+ if (!pick || volume < pick.volume) pick = { stats: a, gap: nearestGap, volume };
+ }
+ if (!pick) break;
+
+ // Close the gap plus a small overlap along the dominant gap axis.
+ const delta = pick.gap.clone();
+ const dominant = (['x', 'y', 'z'] as const).reduce((d, axis) =>
+ Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d,
+ 'x' as 'x' | 'y' | 'z');
+ delta[dominant] += Math.sign(delta[dominant]) * overlap;
+
+ // Find the named object and move it, converting the world delta into the
+ // parent's local space (handles rotated/scaled ancestors).
+ let target: THREE.Object3D | undefined;
+ root.traverse((obj) => {
+ if (!target && obj.name === pick!.stats.name && (obj as { isMesh?: boolean }).isMesh) target = obj;
+ });
+ if (!target) break;
+ const parent = target.parent ?? root;
+ const p0 = new THREE.Vector3();
+ target.getWorldPosition(p0);
+ const p1 = p0.clone().add(delta);
+ const l0 = parent.worldToLocal(p0.clone());
+ const l1 = parent.worldToLocal(p1.clone());
+ target.position.add(l1.sub(l0));
+ target.updateMatrixWorld(true);
+ settled.push(pick.stats.name);
+ }
+ return settled;
+}
diff --git a/tools/__tests__/registry-screenshot.test.ts b/tools/__tests__/registry-screenshot.test.ts
new file mode 100644
index 00000000..a9256d4c
--- /dev/null
+++ b/tools/__tests__/registry-screenshot.test.ts
@@ -0,0 +1,61 @@
+/**
+ * kiln_screenshot registry tool: six-view grid output + the `media` contract
+ * transports use to attach the PNG as a real image block.
+ */
+import { describe, expect, test } from 'bun:test';
+import { kilnToolRegistry, type KilnScreenshotResult } from '../registry';
+
+const BOX_CODE = `
+const meta = { name: 'test-box', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Box', boxGeo(1, 1, 1), gameMaterial('#ff0000'), { parent: root, position: [0, 0.5, 0] });
+ return root;
+}
+`;
+
+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+
+function screenshotDef() {
+ const def = kilnToolRegistry.find((d) => d.name === 'kiln_screenshot');
+ if (!def) throw new Error('kiln_screenshot missing from registry');
+ return def;
+}
+
+describe('kiln_screenshot', () => {
+ test('renders valid code to a six-view grid PNG', async () => {
+ const out = (await screenshotDef().run({ code: BOX_CODE })) as KilnScreenshotResult;
+ expect(out.ok).toBe(true);
+ expect(out.views).toEqual(['Front', 'Right', 'Back', 'Left', 'Top', '3/4']);
+ expect(out.width).toBeGreaterThan(0);
+ expect(out.height).toBeGreaterThan(0);
+ expect(out.warnings).toEqual([]);
+ const png = Buffer.from(out.pngBase64!, 'base64');
+ expect(png.subarray(0, 8).equals(PNG_SIGNATURE)).toBe(true);
+ });
+
+ test('returns ok:false with the error message instead of throwing', async () => {
+ const out = (await screenshotDef().run({ code: 'not a kiln program (' })) as KilnScreenshotResult;
+ expect(out.ok).toBe(false);
+ expect(out.error).toBeDefined();
+ expect(out.pngBase64).toBeUndefined();
+ });
+
+ test('media() extracts the PNG bytes and strips the base64 from the JSON payload', async () => {
+ const def = screenshotDef();
+ const out = await def.run({ code: BOX_CODE });
+ const media = def.media!(out);
+ expect(media).toBeDefined();
+ expect(Buffer.from(media!.png.subarray(0, 8)).equals(PNG_SIGNATURE)).toBe(true);
+ const json = media!.json as Record<string, unknown>;
+ expect(json['ok']).toBe(true);
+ expect(json['views']).toEqual(['Front', 'Right', 'Back', 'Left', 'Top', '3/4']);
+ expect('pngBase64' in json).toBe(false);
+ });
+
+ test('media() returns undefined for a failed run (no image to attach)', async () => {
+ const def = screenshotDef();
+ const out = await def.run({ code: 'throw new Error("boom")' });
+ expect(def.media!(out)).toBeUndefined();
+ });
+});
diff --git a/tools/registry.ts b/tools/registry.ts
index 7dfba0d0..261181a6 100644
--- a/tools/registry.ts
+++ b/tools/registry.ts
@@ -30,6 +30,14 @@ export interface KilnToolDef {
inputSchema: z.ZodType;
/** Execute the tool. Returns JSON-serializable output. */
run(input: unknown): Promise<unknown>;
+ /**
+ * Extract media from a `run()` output, for transports that can show the
+ * model images (Strands ImageBlock tool results, MCP image content). Returns
+ * the PNG bytes plus the JSON payload to send alongside them (the output
+ * with any embedded base64 stripped, so the image is never double-encoded).
+ * Transports without image support just use the raw `run()` output.
+ */
+ media?(output: unknown): { png: Uint8Array; json: unknown } | undefined;
}
// =============================================================================
@@ -53,6 +61,10 @@ const renderInput = z.object({
code: z.string().describe('Kiln source code to execute and render to an in-memory GLB.'),
});
+const screenshotInput = z.object({
+ code: z.string().describe('Kiln source code to execute and render to a six-view image grid.'),
+});
+
// =============================================================================
// kiln_list_primitives
// =============================================================================
@@ -169,6 +181,59 @@ async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRender
}
}
+// =============================================================================
+// kiln_screenshot
+// =============================================================================
+
+export interface KilnScreenshotResult {
+ ok: boolean;
+ /** View names in grid order (row-major): Front, Right, Back, Left, Top, 3/4. */
+ views?: string[];
+ width?: number;
+ height?: number;
+ /** The 3x2 grid PNG, base64-encoded (transports with image support strip this and attach the bytes). */
+ pngBase64?: string;
+ warnings: string[];
+ error?: string;
+}
+
+/**
+ * Execute Kiln code and rasterize it into the 3x2 six-view grid (pure CPU —
+ * no browser, no GPU). Never throws — failures come back as { ok:false, error }.
+ * The renderer is imported lazily so the views module (node:zlib) never enters
+ * the browser bundle graph.
+ */
+async function runScreenshot(input: z.infer<typeof screenshotInput>): Promise<KilnScreenshotResult> {
+ try {
+ const { renderViewGrid } = await import('../views');
+ const { root } = await executeKilnCode(input.code);
+ const warnings = inspectSceneStructure(root);
+ const grid = await renderViewGrid(root);
+ return {
+ ok: true,
+ views: grid.views,
+ width: grid.width,
+ height: grid.height,
+ pngBase64: grid.png.toString('base64'),
+ warnings,
+ };
+ } catch (err) {
+ return {
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ warnings: [],
+ };
+ }
+}
+
+/** Shared media extractor for screenshot-shaped outputs (pngBase64 -> bytes + stripped JSON). */
+function screenshotMedia(output: unknown): { png: Uint8Array; json: unknown } | undefined {
+ const o = output as KilnScreenshotResult | undefined;
+ if (!o || typeof o.pngBase64 !== 'string' || o.pngBase64.length === 0) return undefined;
+ const { pngBase64: _png, ...json } = o;
+ return { png: new Uint8Array(Buffer.from(o.pngBase64, 'base64')), json };
+}
+
// =============================================================================
// Registry
// =============================================================================
@@ -195,4 +260,16 @@ export const kilnToolRegistry: KilnToolDef[] = [
inputSchema: renderInput,
run: async (input) => runRender(renderInput.parse(input)),
},
+ {
+ name: 'kiln_screenshot',
+ description:
+ 'Render Kiln code to a six-view image grid so you can SEE the asset: ' +
+ '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 verify orientation (+X forward), attachment (no floating parts), and silhouette before submitting. ' +
+ 'If a view looks wrong, fix the code and screenshot again. Flat-shaded CPU render; does not write files.',
+ inputSchema: screenshotInput,
+ run: async (input) => runScreenshot(screenshotInput.parse(input)),
+ media: screenshotMedia,
+ },
];
diff --git a/validation.ts b/validation.ts
index b39b3d84..c9785343 100644
--- a/validation.ts
+++ b/validation.ts
@@ -81,28 +81,58 @@ function estimateGeometryTris(
return null;
}
+ /** Numeric property off an options-object literal arg (e.g. gearGeo({ teeth: 16 })). */
+ function asObjNum(node: acorn.Expression | undefined, prop: string): number | null {
+ if (!node || node.type !== 'ObjectExpression') return null;
+ for (const p of node.properties) {
+ if (
+ p.type === 'Property' &&
+ !p.computed &&
+ ((p.key.type === 'Identifier' && p.key.name === prop) ||
+ (p.key.type === 'Literal' && p.key.value === prop))
+ ) {
+ return asNum(p.value as acorn.Expression);
+ }
+ }
+ return null;
+ }
+
switch (name) {
case 'boxGeo':
+ case 'decalBox':
return 12; // 6 faces x 2 tris
case 'planeGeo': {
const ws = asNum(args[2]) ?? 1;
const hs = asNum(args[3]) ?? 1;
return Math.max(1, ws * hs) * 2;
}
- case 'coneGeo': {
+ case 'coneGeo':
+ case 'coneXGeo':
+ case 'coneYGeo':
+ case 'coneZGeo': {
const segs = asNum(args[2]) ?? 8;
return segs * 2; // cap + sides
}
- case 'cylinderGeo': {
+ case 'cylinderGeo':
+ case 'cylinderXGeo':
+ case 'cylinderYGeo':
+ case 'cylinderZGeo': {
const segs = asNum(args[3]) ?? 8;
return segs * 4; // side + 2 caps
}
+ case 'taperConeGeo': {
+ const segs = asNum(args[4]) ?? 8;
+ return segs * 4; // open frustum ≈ cylinder budget
+ }
case 'sphereGeo': {
const w = asNum(args[1]) ?? 8;
const h = asNum(args[2]) ?? 6;
return w * h * 2;
}
- case 'capsuleGeo': {
+ case 'capsuleGeo':
+ case 'capsuleXGeo':
+ case 'capsuleYGeo':
+ case 'capsuleZGeo': {
const segs = asNum(args[2]) ?? 6;
return segs * 8; // rough: body + caps
}
@@ -111,6 +141,16 @@ function estimateGeometryTris(
const tub = asNum(args[3]) ?? 12;
return rad * tub * 2;
}
+ case 'gearGeo': {
+ // Calibrated against countTriangles on the parametric gear builder:
+ // each tooth contributes ~32 tris (tooth walls + rim segments + caps).
+ const teeth = asObjNum(args[0], 'teeth') ?? 12;
+ return teeth * 32;
+ }
+ case 'bladeGeo':
+ return 36; // tapered prism + tip
+ case 'wingGeo':
+ return 24; // closed trapezoid slab
default:
return null;
}
@@ -402,10 +442,36 @@ function analyzeBody(ast: acorn.Program): BodyAnalysis {
recursiveBuild ??= node.loc?.start.line;
}
- // Tri estimate — count geometry primitive calls at any depth.
+ // Tri estimate — count geometry primitive calls at any depth, scaled by
+ // any enclosing literal-bound for-loops (the dominant undercount in real
+ // failures: radial arrays and CSG cutter loops that build N geometries).
if (node.callee.type === 'Identifier') {
- const est = estimateGeometryTris(node.callee.name, node.arguments as acorn.Expression[]);
- if (est !== null) estimatedTris += est;
+ let est = estimateGeometryTris(node.callee.name, node.arguments as acorn.Expression[]);
+
+ // subdivide(geo, n): Loop subdivision quadruples tris per iteration.
+ // When the input is an inline estimable call its base count is already
+ // accumulated by this walker, so add only the growth (e * (4^n - 1)).
+ if (est === null && node.callee.name === 'subdivide') {
+ const inner = node.arguments[0];
+ if (inner && inner.type === 'CallExpression' && inner.callee.type === 'Identifier') {
+ const base = estimateGeometryTris(
+ inner.callee.name,
+ inner.arguments as acorn.Expression[],
+ );
+ if (base !== null) {
+ const nArg = node.arguments[1];
+ const n = Math.min(
+ 4, // cap: beyond 4 iterations the estimate is noise anyway
+ (nArg && nArg.type === 'Literal' && typeof nArg.value === 'number' ? nArg.value : 1),
+ );
+ est = base * (Math.pow(4, Math.max(0, n)) - 1);
+ }
+ }
+ }
+
+ if (est !== null) {
+ estimatedTris += est * loopMultiplier(ancestors);
+ }
}
},
});
@@ -413,6 +479,27 @@ function analyzeBody(ast: acorn.Program): BodyAnalysis {
return { infiniteLoops, recursiveBuild, estimatedTris };
}
+/**
+ * Product of the literal iteration counts of every enclosing for-loop of the
+ * shape `for (let i = 0; i < N; i++)` (or `<=`). Unknown bounds contribute 1
+ * (no scaling) so the estimate only ever moves toward the truth. Capped so a
+ * pathological literal can't produce a nonsense advisory.
+ */
+function loopMultiplier(ancestors: readonly acorn.Node[]): number {
+ let mult = 1;
+ for (const node of ancestors) {
+ if (node.type !== 'ForStatement') continue;
+ const f = node as acorn.ForStatement;
+ if (!f.test || f.test.type !== 'BinaryExpression') continue;
+ const { operator, right } = f.test;
+ if (operator !== '<' && operator !== '<=') continue;
+ if (right.type !== 'Literal' || typeof right.value !== 'number') continue;
+ const n = operator === '<' ? right.value : right.value + 1;
+ if (n > 1 && Number.isFinite(n)) mult *= Math.min(n, 256);
+ }
+ return Math.min(mult, 4096);
+}
+
function insideFunctionNamed(
ancestors: readonly acorn.AnyNode[],
name: string
diff --git a/views/__tests__/views.test.ts b/views/__tests__/views.test.ts
new file mode 100644
index 00000000..f3d9361f
--- /dev/null
+++ b/views/__tests__/views.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, test } from 'bun:test';
+import sharp from 'sharp';
+import { coverage, rasterizeView, renderViewGrid, renderCodeViewGrid, SIX_VIEWS } from '../index';
+import { encodePng } from '../png';
+import { executeKilnCode } from '../../render';
+
+const BOX_CODE = `
+const meta = { name: 'test-box', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Box', boxGeo(1, 1, 1), gameMaterial('#ff0000'), { parent: root, position: [0, 0.5, 0] });
+ return root;
+}
+`;
+
+// Elongated along +X (correct kiln frame for a "forward" asset).
+const LONG_X_CODE = `
+const meta = { name: 'long-x', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Body', boxGeo(4, 0.5, 0.5), gameMaterial('#00ff00'), { parent: root, position: [0, 0.25, 0] });
+ return root;
+}
+`;
+
+// Same shape elongated along +Z (the classic wrong-axis failure).
+const LONG_Z_CODE = `
+const meta = { name: 'long-z', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ createPart('Mesh_Body', boxGeo(0.5, 0.5, 4), gameMaterial('#00ff00'), { parent: root, position: [0, 0.25, 0] });
+ return root;
+}
+`;
+
+describe('rasterizeView', () => {
+ test('renders a centered box with substantial coverage from every view', async () => {
+ const { root } = await executeKilnCode(BOX_CODE);
+ for (const view of SIX_VIEWS) {
+ const rgb = rasterizeView(root, view.dir, { size: 128 });
+ const cov = coverage(rgb, 128);
+ // The box is framed at ~90% of the cell; a cube face should fill a lot of it.
+ expect(cov).toBeGreaterThan(0.3);
+ expect(cov).toBeLessThan(1);
+ }
+ });
+
+ test('is deterministic', async () => {
+ const { root } = await executeKilnCode(BOX_CODE);
+ const a = rasterizeView(root, [0.7, 0.5, 0.7], { size: 64 });
+ const b = rasterizeView(root, [0.7, 0.5, 0.7], { size: 64 });
+ expect(Buffer.from(a).equals(Buffer.from(b))).toBe(true);
+ });
+
+ test('lighting differentiates faces (flat lambert, not silhouette fill)', async () => {
+ const { root } = await executeKilnCode(BOX_CODE);
+ // 3/4 view sees three faces of the cube with different lambert terms.
+ const rgb = rasterizeView(root, [0.7, 0.5, 0.7], { size: 128 });
+ const reds = new Set<number>();
+ for (let i = 0; i < 128 * 128; i++) {
+ const r = rgb[i * 3]!;
+ if (r !== 26) reds.add(r); // skip background
+ }
+ expect(reds.size).toBeGreaterThanOrEqual(2);
+ });
+
+ test('orientation is distinguishable: +X vs +Z elongation swap Front/Right profiles', async () => {
+ // For the X-elongated asset, the Front view (camera on +X) sees the small
+ // square end; the Right view (camera on +Z) sees the long profile.
+ // The Z-elongated asset swaps them. Framing is per-view extent-fit, so the
+ // long profile fills the frame width while the end-on view leaves the
+ // cell mostly square — compare aspect by occupied-row/col extents.
+ const occupiedAspect = (rgb: Uint8Array, size: number): number => {
+ let minX = size, maxX = -1, minY = size, maxY = -1;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const i = (y * size + x) * 3;
+ if (rgb[i] !== 26 || rgb[i + 1] !== 26 || rgb[i + 2] !== 26) {
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ }
+ }
+ }
+ return (maxX - minX + 1) / (maxY - minY + 1);
+ };
+
+ const { root: rx } = await executeKilnCode(LONG_X_CODE);
+ const { root: rz } = await executeKilnCode(LONG_Z_CODE);
+ const front = SIX_VIEWS[0]!.dir;
+ const right = SIX_VIEWS[1]!.dir;
+
+ // X-long: front view is end-on (aspect ~1), right view is wide (aspect >> 1).
+ expect(occupiedAspect(rasterizeView(rx, front, { size: 128 }), 128)).toBeLessThan(2);
+ expect(occupiedAspect(rasterizeView(rx, right, { size: 128 }), 128)).toBeGreaterThan(3);
+ // Z-long: swapped.
+ expect(occupiedAspect(rasterizeView(rz, front, { size: 128 }), 128)).toBeGreaterThan(3);
+ expect(occupiedAspect(rasterizeView(rz, right, { size: 128 }), 128)).toBeLessThan(2);
+ });
+
+ test('empty scene renders pure background', async () => {
+ const { root } = await executeKilnCode(`
+ const meta = { name: 'empty' };
+ function build() { return createRoot('Root'); }
+ `);
+ const rgb = rasterizeView(root, [1, 0, 0], { size: 32 });
+ expect(coverage(rgb, 32)).toBe(0);
+ });
+});
+
+describe('encodePng', () => {
+ test('round-trips through a real decoder', async () => {
+ const size = 16;
+ const rgb = new Uint8Array(size * size * 3);
+ for (let i = 0; i < size * size; i++) {
+ rgb[i * 3] = i % 256;
+ rgb[i * 3 + 1] = (i * 7) % 256;
+ rgb[i * 3 + 2] = (i * 13) % 256;
+ }
+ const png = encodePng(rgb, size, size);
+ const decoded = await sharp(png).raw().toBuffer({ resolveWithObject: true });
+ expect(decoded.info.width).toBe(size);
+ expect(decoded.info.height).toBe(size);
+ expect(decoded.info.channels).toBe(3);
+ expect(Buffer.from(rgb).equals(decoded.data)).toBe(true);
+ });
+
+ test('rejects wrong buffer size', () => {
+ expect(() => encodePng(new Uint8Array(10), 4, 4)).toThrow();
+ });
+});
+
+describe('renderViewGrid / renderCodeViewGrid', () => {
+ test('produces a valid 3x2 grid PNG with all six views', async () => {
+ const result = await renderCodeViewGrid(BOX_CODE, { size: 64 });
+ expect(result.views).toEqual(['Front', 'Right', 'Back', 'Left', 'Top', '3/4']);
+ expect(result.width).toBe(3 * 64 + 4 * 4);
+ expect(result.height).toBe(2 * 64 + 3 * 4);
+ const meta = await sharp(result.png).metadata();
+ expect(meta.width).toBe(result.width);
+ expect(meta.height).toBe(result.height);
+ expect(meta.format).toBe('png');
+ });
+
+ test('renderViewGrid accepts a pre-built sandbox scene root', async () => {
+ const { root } = await executeKilnCode(BOX_CODE);
+ const result = await renderViewGrid(root, { size: 32 });
+ expect(result.png.length).toBeGreaterThan(100);
+ });
+});
diff --git a/views/index.ts b/views/index.ts
new file mode 100644
index 00000000..14d8ead5
--- /dev/null
+++ b/views/index.ts
@@ -0,0 +1,84 @@
+/**
+ * Six-view grid rendering for the Kiln vision loop.
+ *
+ * Renders a scene (or a Kiln program) to a 3x2 grid PNG of orthographic
+ * views — Front / Right / Back / Left | Top / 3-4 — using the pure-CPU
+ * rasterizer in ./raster.ts. This is what the agent sees via the
+ * kiln_screenshot tool and what ships as the views.png artifact.
+ *
+ * Grid order (stated in tool text instead of baked-in labels):
+ * row 1: Front, Right, Back
+ * row 2: Left, Top, 3/4
+ */
+
+import { rasterizeView, SIX_VIEWS, type RasterOptions, type ViewSpec } from './raster';
+import { encodePng } from './png';
+
+export { rasterizeView, SIX_VIEWS, coverage } from './raster';
+export type { RasterOptions, ViewSpec } from './raster';
+export { encodePng } from './png';
+
+const PAD = 4;
+const PAD_COLOR: [number, number, number] = [10, 11, 13];
+
+export interface ViewGridResult {
+ png: Buffer;
+ width: number;
+ height: number;
+ /** View names in grid order (row-major). */
+ views: string[];
+}
+
+export interface ViewGridOptions extends RasterOptions {
+ views?: ViewSpec[];
+}
+
+/** Render a (possibly sandbox-created) Three.js scene root into the 3x2 grid. */
+export async function renderViewGrid(
+ root: unknown,
+ opts: ViewGridOptions = {}
+): Promise<ViewGridResult> {
+ const size = opts.size ?? 256;
+ const views = opts.views ?? SIX_VIEWS;
+ const cols = 3;
+ const rows = Math.ceil(views.length / cols);
+ const width = cols * size + (cols + 1) * PAD;
+ const height = rows * size + (rows + 1) * PAD;
+
+ const grid = new Uint8Array(width * height * 3);
+ for (let i = 0; i < width * height; i++) {
+ grid[i * 3] = PAD_COLOR[0];
+ grid[i * 3 + 1] = PAD_COLOR[1];
+ grid[i * 3 + 2] = PAD_COLOR[2];
+ }
+
+ for (let vi = 0; vi < views.length; vi++) {
+ const cell = rasterizeView(root, views[vi]!.dir, { size, backfaceCull: opts.backfaceCull });
+ const col = vi % cols;
+ const row = Math.floor(vi / cols);
+ const x0 = PAD + col * (size + PAD);
+ const y0 = PAD + row * (size + PAD);
+ for (let y = 0; y < size; y++) {
+ const src = y * size * 3;
+ const dst = ((y0 + y) * width + x0) * 3;
+ grid.set(cell.subarray(src, src + size * 3), dst);
+ }
+ }
+
+ return {
+ png: encodePng(grid, width, height),
+ width,
+ height,
+ views: views.map((v) => v.name),
+ };
+}
+
+/** Execute a Kiln program and render its scene into the 3x2 grid. */
+export async function renderCodeViewGrid(
+ code: string,
+ opts: ViewGridOptions = {}
+): Promise<ViewGridResult> {
+ const { executeKilnCode } = await import('../render');
+ const { root } = await executeKilnCode(code);
+ return renderViewGrid(root, opts);
+}
diff --git a/views/png.ts b/views/png.ts
new file mode 100644
index 00000000..c395d111
--- /dev/null
+++ b/views/png.ts
@@ -0,0 +1,70 @@
+/**
+ * Minimal PNG encoder (8-bit RGB, no interlace) over node:zlib.
+ *
+ * Deliberately dependency-free: this module must load inside the kiln-studio
+ * agent-runtime container and under Bun without native modules (sharp is NOT
+ * acceptable here). ~70 lines is cheaper than a dependency.
+ */
+
+import { deflateSync } from 'node:zlib';
+
+const CRC_TABLE = (() => {
+ const table = new Uint32Array(256);
+ for (let n = 0; n < 256; n++) {
+ let c = n;
+ for (let k = 0; k < 8; k++) {
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ }
+ table[n] = c >>> 0;
+ }
+ return table;
+})();
+
+function crc32(buf: Uint8Array): number {
+ let c = 0xffffffff;
+ for (let i = 0; i < buf.length; i++) {
+ c = CRC_TABLE[(c ^ buf[i]!) & 0xff]! ^ (c >>> 8);
+ }
+ return (c ^ 0xffffffff) >>> 0;
+}
+
+function chunk(type: string, data: Uint8Array): Buffer {
+ const out = Buffer.alloc(8 + data.length + 4);
+ out.writeUInt32BE(data.length, 0);
+ out.write(type, 4, 'ascii');
+ out.set(data, 8);
+ const crcInput = out.subarray(4, 8 + data.length);
+ out.writeUInt32BE(crc32(crcInput), 8 + data.length);
+ return out;
+}
+
+/** Encode a row-major RGB buffer (width*height*3 bytes) as a PNG. */
+export function encodePng(rgb: Uint8Array, width: number, height: number): Buffer {
+ if (rgb.length !== width * height * 3) {
+ throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb.length}`);
+ }
+
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8; // bit depth
+ ihdr[9] = 2; // color type: truecolor RGB
+ ihdr[10] = 0; // compression
+ ihdr[11] = 0; // filter
+ ihdr[12] = 0; // interlace
+
+ // Filter byte 0 (None) per scanline.
+ const raw = Buffer.alloc(height * (1 + width * 3));
+ for (let y = 0; y < height; y++) {
+ const rowStart = y * (1 + width * 3);
+ raw[rowStart] = 0;
+ raw.set(rgb.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);
+ }
+
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk('IHDR', ihdr),
+ chunk('IDAT', deflateSync(raw)),
+ chunk('IEND', new Uint8Array(0)),
+ ]);
+}
diff --git a/views/raster.ts b/views/raster.ts
new file mode 100644
index 00000000..b73618fe
--- /dev/null
+++ b/views/raster.ts
@@ -0,0 +1,321 @@
+/**
+ * Pure-CPU orthographic rasterizer for Kiln scene graphs.
+ *
+ * Why this exists: the agent loop needs to SEE its asset (kiln_screenshot)
+ * but no GPU/browser renderer is available everywhere the loop runs — the
+ * kiln-studio agent-runtime container ships without a browser
+ * (PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1) and Playwright is unsupported under
+ * Bun on Windows (see imposter/bake.ts). headless-gl is WebGL1-only while
+ * three >= r163 requires WebGL2. So: a dependency-free scanline z-buffer
+ * rasterizer over the executed scene. Flat lambert, base color only — enough
+ * fidelity for silhouette / proportion / orientation / contact QA, which is
+ * what the vision loop checks.
+ *
+ * Scene access is strictly duck-typed (`.isMesh`, `matrixWorld.elements`,
+ * position attribute arrays) because sandbox-created objects live in a
+ * different module realm — see executeKilnCode in ../render.ts.
+ *
+ * Lighting matches scripts/visual-audit.ts: key directional light from
+ * [1.5, 2, 1] at 1.1 plus 0.25 ambient. Back-face culling is strict (like
+ * the offline audit grid) so inverted winding shows up as missing faces.
+ */
+
+export interface ViewSpec {
+ name: string;
+ /** Direction from model center toward the camera (kiln frame: +X fwd, +Y up, +Z right). */
+ dir: [number, number, number];
+}
+
+/** Same six views as the offline audit grid (scripts/visual-audit.ts). */
+export const SIX_VIEWS: ViewSpec[] = [
+ { name: 'Front', dir: [1, 0, 0] },
+ { name: 'Right', dir: [0, 0, 1] },
+ { name: 'Back', dir: [-1, 0, 0] },
+ { name: 'Left', dir: [0, 0, -1] },
+ { name: 'Top', dir: [0, 1, 0.0001] },
+ { name: '3/4', dir: [0.7, 0.5, 0.7] },
+];
+
+export interface RasterOptions {
+ /** Square output size in pixels per view. Default 256. */
+ size?: number;
+ /** Cull triangles facing away from the camera. Default true (reveals winding bugs). */
+ backfaceCull?: boolean;
+}
+
+const BG: [number, number, number] = [26, 26, 26]; // #1a1a1a, matches audit grid
+const AMBIENT = 0.25;
+const KEY_INTENSITY = 1.1;
+const KEY_DIR = normalize([1.5, 2, 1]);
+
+type Vec3 = [number, number, number];
+
+function normalize(v: number[]): Vec3 {
+ const len = Math.hypot(v[0]!, v[1]!, v[2]!) || 1;
+ return [v[0]! / len, v[1]! / len, v[2]! / len];
+}
+
+function cross(a: Vec3, b: Vec3): Vec3 {
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+}
+
+function dot(a: Vec3, b: Vec3): number {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+
+/** Minimal duck-typed views of the Three.js objects we read. */
+interface DuckAttribute {
+ array: ArrayLike<number>;
+ itemSize: number;
+ count: number;
+}
+interface DuckGeometry {
+ getAttribute(name: string): DuckAttribute | undefined;
+ index: DuckAttribute | null;
+}
+interface DuckMaterial {
+ color?: { r: number; g: number; b: number };
+ visible?: boolean;
+}
+interface DuckMesh {
+ isMesh?: boolean;
+ visible?: boolean;
+ geometry?: DuckGeometry;
+ material?: DuckMaterial | DuckMaterial[];
+ matrixWorld?: { elements: ArrayLike<number> };
+}
+interface DuckObject3D {
+ visible?: boolean;
+ updateMatrixWorld?(force?: boolean): void;
+ traverse?(cb: (obj: unknown) => void): void;
+}
+
+interface Tri {
+ // World-space vertices, flattened [x0,y0,z0, x1,y1,z1, x2,y2,z2]
+ v: Float64Array;
+ color: [number, number, number];
+}
+
+/** Collect world-space triangles + base colors from a (possibly cross-realm) scene. */
+function collectTriangles(root: DuckObject3D): { tris: Tri[]; bbox: { min: Vec3; max: Vec3 } } {
+ root.updateMatrixWorld?.(true);
+
+ const tris: Tri[] = [];
+ const min: Vec3 = [Infinity, Infinity, Infinity];
+ const max: Vec3 = [-Infinity, -Infinity, -Infinity];
+
+ root.traverse?.((obj) => {
+ const mesh = obj as DuckMesh;
+ if (!mesh.isMesh || mesh.visible === false) return;
+ const geo = mesh.geometry;
+ const pos = geo?.getAttribute?.('position');
+ if (!geo || !pos || pos.itemSize !== 3) return;
+
+ const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
+ // Multi-material groups are rare in kiln output; first material's color is
+ // a sufficient approximation for QA views.
+ const c = mats[0]?.color;
+ const color: [number, number, number] = c
+ ? [clamp01(c.r), clamp01(c.g), clamp01(c.b)]
+ : [0.7, 0.7, 0.7];
+
+ const m = mesh.matrixWorld?.elements;
+ if (!m) return;
+
+ const arr = pos.array;
+ const world = new Float64Array(pos.count * 3);
+ for (let i = 0; i < pos.count; i++) {
+ const x = arr[i * 3]!;
+ const y = arr[i * 3 + 1]!;
+ const z = arr[i * 3 + 2]!;
+ const wx = m[0]! * x + m[4]! * y + m[8]! * z + m[12]!;
+ const wy = m[1]! * x + m[5]! * y + m[9]! * z + m[13]!;
+ const wz = m[2]! * x + m[6]! * y + m[10]! * z + m[14]!;
+ world[i * 3] = wx;
+ world[i * 3 + 1] = wy;
+ world[i * 3 + 2] = wz;
+ if (wx < min[0]) min[0] = wx;
+ if (wy < min[1]) min[1] = wy;
+ if (wz < min[2]) min[2] = wz;
+ if (wx > max[0]) max[0] = wx;
+ if (wy > max[1]) max[1] = wy;
+ if (wz > max[2]) max[2] = wz;
+ }
+
+ const pushTri = (a: number, b: number, c2: number) => {
+ const v = new Float64Array(9);
+ v[0] = world[a * 3]!;
+ v[1] = world[a * 3 + 1]!;
+ v[2] = world[a * 3 + 2]!;
+ v[3] = world[b * 3]!;
+ v[4] = world[b * 3 + 1]!;
+ v[5] = world[b * 3 + 2]!;
+ v[6] = world[c2 * 3]!;
+ v[7] = world[c2 * 3 + 1]!;
+ v[8] = world[c2 * 3 + 2]!;
+ tris.push({ v, color });
+ };
+
+ const index = geo.index;
+ if (index) {
+ const ia = index.array;
+ for (let i = 0; i + 2 < index.count; i += 3) {
+ pushTri(ia[i]!, ia[i + 1]!, ia[i + 2]!);
+ }
+ } else {
+ for (let i = 0; i + 2 < pos.count; i += 3) {
+ pushTri(i, i + 1, i + 2);
+ }
+ }
+ });
+
+ if (!Number.isFinite(min[0])) {
+ return { tris, bbox: { min: [0, 0, 0], max: [0, 0, 0] } };
+ }
+ return { tris, bbox: { min, max } };
+}
+
+function clamp01(n: number): number {
+ return n < 0 ? 0 : n > 1 ? 1 : n;
+}
+
+/**
+ * Linear -> sRGB encode (the renderer's output transform). Material colors read
+ * off the scene are linear-sRGB (Three.js color management converts hex strings
+ * on construction), and lighting math happens in linear space — without this
+ * encode the views come out far darker than the Three.js-rendered audit grids.
+ */
+function linearToSrgb(c: number): number {
+ const v = clamp01(c);
+ return v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055;
+}
+
+/**
+ * Render one orthographic view of the scene to an RGB pixel buffer
+ * (size*size*3 bytes, row-major from the top-left).
+ */
+export function rasterizeView(
+ root: unknown,
+ dir: [number, number, number],
+ opts: RasterOptions = {}
+): Uint8Array {
+ const size = opts.size ?? 256;
+ const cull = opts.backfaceCull ?? true;
+ const { tris, bbox } = collectTriangles(root as DuckObject3D);
+
+ const out = new Uint8Array(size * size * 3);
+ for (let i = 0; i < size * size; i++) {
+ out[i * 3] = BG[0];
+ out[i * 3 + 1] = BG[1];
+ out[i * 3 + 2] = BG[2];
+ }
+ if (tris.length === 0) return out;
+
+ // Camera basis: z points from target toward the camera (three.js convention).
+ const z = normalize(dir);
+ const upHint: Vec3 = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];
+ const x = normalize(cross(upHint, z));
+ const y = cross(z, x);
+
+ const center: Vec3 = [
+ (bbox.min[0] + bbox.max[0]) / 2,
+ (bbox.min[1] + bbox.max[1]) / 2,
+ (bbox.min[2] + bbox.max[2]) / 2,
+ ];
+
+ // Project the 8 bbox corners to find the framing extent for this view.
+ let ext = 1e-6;
+ for (let ci = 0; ci < 8; ci++) {
+ const px = (ci & 1 ? bbox.max[0] : bbox.min[0]) - center[0];
+ const py = (ci & 2 ? bbox.max[1] : bbox.min[1]) - center[1];
+ const pz = (ci & 4 ? bbox.max[2] : bbox.min[2]) - center[2];
+ const p: Vec3 = [px, py, pz];
+ ext = Math.max(ext, Math.abs(dot(p, x)), Math.abs(dot(p, y)));
+ }
+ const scale = (size * 0.45) / ext; // 90% of the half-size — small margin
+ const half = size / 2;
+
+ const zbuf = new Float64Array(size * size).fill(-Infinity);
+
+ const sx = new Float64Array(3);
+ const sy = new Float64Array(3);
+ const sz = new Float64Array(3);
+
+ for (const tri of tris) {
+ // World-space face normal (flat shading; robust under non-uniform scale).
+ const e1: Vec3 = [tri.v[3]! - tri.v[0]!, tri.v[4]! - tri.v[1]!, tri.v[5]! - tri.v[2]!];
+ const e2: Vec3 = [tri.v[6]! - tri.v[0]!, tri.v[7]! - tri.v[1]!, tri.v[8]! - tri.v[2]!];
+ const n = cross(e1, e2);
+ const nLen = Math.hypot(n[0], n[1], n[2]);
+ if (nLen < 1e-12) continue;
+ const N: Vec3 = [n[0] / nLen, n[1] / nLen, n[2] / nLen];
+
+ const facing = dot(N, z);
+ if (cull && facing <= 0) continue;
+
+ // Project to screen space.
+ for (let i = 0; i < 3; i++) {
+ const px = tri.v[i * 3]! - center[0];
+ const py = tri.v[i * 3 + 1]! - center[1];
+ const pz = tri.v[i * 3 + 2]! - center[2];
+ const p: Vec3 = [px, py, pz];
+ sx[i] = half + dot(p, x) * scale;
+ sy[i] = half - dot(p, y) * scale;
+ sz[i] = dot(p, z);
+ }
+
+ // Flat lambert with the audit-grid light rig, in linear space, then the
+ // sRGB output transform (matching what a Three.js renderer would write).
+ const lambert = Math.max(0, dot(N, KEY_DIR));
+ const lit = Math.min(1, AMBIENT + KEY_INTENSITY * lambert);
+ const r = Math.round(linearToSrgb(tri.color[0] * lit) * 255);
+ const g = Math.round(linearToSrgb(tri.color[1] * lit) * 255);
+ const b = Math.round(linearToSrgb(tri.color[2] * lit) * 255);
+
+ // Rasterize via edge functions.
+ const minX = Math.max(0, Math.floor(Math.min(sx[0]!, sx[1]!, sx[2]!)));
+ const maxX = Math.min(size - 1, Math.ceil(Math.max(sx[0]!, sx[1]!, sx[2]!)));
+ const minY = Math.max(0, Math.floor(Math.min(sy[0]!, sy[1]!, sy[2]!)));
+ const maxY = Math.min(size - 1, Math.ceil(Math.max(sy[0]!, sy[1]!, sy[2]!)));
+ if (minX > maxX || minY > maxY) continue;
+
+ const ax = sx[0]!, ay = sy[0]!, bx2 = sx[1]!, by = sy[1]!, cx = sx[2]!, cy = sy[2]!;
+ const area = (bx2 - ax) * (cy - ay) - (by - ay) * (cx - ax);
+ if (Math.abs(area) < 1e-9) continue;
+ const invArea = 1 / area;
+
+ for (let py = minY; py <= maxY; py++) {
+ for (let px = minX; px <= maxX; px++) {
+ const cxp = px + 0.5;
+ const cyp = py + 0.5;
+ const w0 = ((bx2 - ax) * (cyp - ay) - (by - ay) * (cxp - ax)) * invArea;
+ const w1 = ((cx - bx2) * (cyp - by) - (cy - by) * (cxp - bx2)) * invArea;
+ const w2 = 1 - w0 - w1;
+ // Accept either winding on screen (back-face culling already happened
+ // in world space) — check all barycentrics share the area's sign space.
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;
+ // Barycentric weights map: w0 → vertex C, w1 → vertex A, w2 → vertex B
+ // for this edge-function arrangement; depth interpolation just needs a
+ // consistent convex combination, so order doesn't matter for QA views.
+ const depth = w1 * sz[0]! + w2 * sz[1]! + w0 * sz[2]!;
+ const pi = py * size + px;
+ if (depth <= zbuf[pi]!) continue;
+ zbuf[pi] = depth;
+ out[pi * 3] = r;
+ out[pi * 3 + 1] = g;
+ out[pi * 3 + 2] = b;
+ }
+ }
+ }
+
+ return out;
+}
+
+/** Fraction of non-background pixels — used by tests and occupancy checks. */
+export function coverage(rgb: Uint8Array, size: number): number {
+ let filled = 0;
+ for (let i = 0; i < size * size; i++) {
+ if (rgb[i * 3] !== BG[0] || rgb[i * 3 + 1] !== BG[1] || rgb[i * 3 + 2] !== BG[2]) filled++;
+ }
+ return filled / (size * size);
+}