Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(kiln): Round 3 — three.js 0.184, asset polish, usage instrumentation
Matt Kissingerba82582382ce
diff --git a/__tests__/primitives.test.ts b/__tests__/primitives.test.tsindex f3e9237c..1de35827 100644--- a/__tests__/primitives.test.ts+++ b/__tests__/primitives.test.ts@@ -466,4 +466,51 @@ describe('buildSandboxGlobals', () => {expect(globals[name]).toBeDefined();}});++ test('when given a usage map, tallies primitive invocations', () => {+ const usage: Record<string, number> = {};+ const globals = buildSandboxGlobals(usage) as Record<+ string,+ (...a: unknown[]) => unknown+ >;++ // Call a spread of primitives with varying counts.+ globals.createRoot!('R');+ globals.createRoot!('R2');+ globals.createRoot!('R3');+ globals.boxGeo!(1, 1, 1);+ globals.boxGeo!(2, 2, 2);+ globals.sphereGeo!(0.5);+ globals.gameMaterial!(0xff0000);++ expect(usage.createRoot).toBe(3);+ expect(usage.boxGeo).toBe(2);+ expect(usage.sphereGeo).toBe(1);+ expect(usage.gameMaterial).toBe(1);+ // Unused primitive has no entry.+ expect(usage.torusGeo).toBeUndefined();+ });++ test('usage map is isolated per call', () => {+ const usageA: Record<string, number> = {};+ const usageB: Record<string, number> = {};+ const gA = buildSandboxGlobals(usageA) as Record<string, (...a: unknown[]) => unknown>;+ const gB = buildSandboxGlobals(usageB) as Record<string, (...a: unknown[]) => unknown>;++ gA.createRoot!('A');+ gB.createRoot!('B');+ gB.createRoot!('B2');++ expect(usageA.createRoot).toBe(1);+ expect(usageB.createRoot).toBe(2);+ });++ test('without a usage map, primitives are unwrapped (zero-overhead path)', () => {+ const globals = buildSandboxGlobals() as Record<string, unknown>;+ // Identity check: the exposed function is the original primitive, not a+ // wrapper. Looking up by name against a second fresh globals keeps the+ // test independent of module structure.+ const raw = buildSandboxGlobals() as Record<string, unknown>;+ expect(globals.boxGeo).toBe(raw.boxGeo);+ });});diff --git a/__tests__/render-edges.test.ts b/__tests__/render-edges.test.tsindex 32c9cc6b..9d343440 100644--- a/__tests__/render-edges.test.ts+++ b/__tests__/render-edges.test.ts@@ -252,3 +252,45 @@ function animate() {expect(warnings.some((w) => w.includes('unsupported property'))).toBe(true);});});++// =============================================================================+// Primitive-usage instrumentation+// =============================================================================++describe('primitive usage tracking', () => {+ test('executeKilnCode surfaces primitiveUsage with exact call counts', async () => {+ const { primitiveUsage } = await executeKilnCode(`+const meta = { name: 'UsageProbe' };+function build() {+ const root = createRoot('R');+ createPart('A', boxGeo(1, 1, 1), gameMaterial(0xff0000), { parent: root });+ createPart('B', boxGeo(2, 1, 1), gameMaterial(0x00ff00), { parent: root });+ createPart('C', sphereGeo(0.5), gameMaterial(0x0000ff), { parent: root });+ return root;+}+`);+ expect(primitiveUsage.createRoot).toBe(1);+ expect(primitiveUsage.createPart).toBe(3);+ expect(primitiveUsage.boxGeo).toBe(2);+ expect(primitiveUsage.sphereGeo).toBe(1);+ expect(primitiveUsage.gameMaterial).toBe(3);+ expect(primitiveUsage.torusGeo).toBeUndefined();+ });++ test('renderGLB copies primitiveUsage into meta', async () => {+ const r = await renderGLB(`+const meta = { name: 'UsageProbeRender' };+function build() {+ const root = createRoot('R');+ createPart('A', boxGeo(1, 1, 1), gameMaterial(0xff0000), { parent: root });+ return root;+}+`);+ expect(r.meta.primitiveUsage).toBeDefined();+ const usage = r.meta.primitiveUsage!;+ expect(usage.createRoot).toBe(1);+ expect(usage.createPart).toBe(1);+ expect(usage.boxGeo).toBe(1);+ expect(usage.gameMaterial).toBe(1);+ });+});diff --git a/primitives.ts b/primitives.tsindex 5c928f43..4bd5da91 100644--- a/primitives.ts+++ b/primitives.ts@@ -509,8 +509,15 @@ export function validateAsset(* The full sandbox globals used when executing Kiln code. Kept in one place* so render.ts and any future evaluator share the same surface area as what* the LLM expects.+ *+ * Pass `usage` to tally how many times each primitive was invoked by the+ * agent-generated `build()` call. The counter lives on the caller's object+ * so render.ts can stash it into `render.meta.primitiveUsage` for+ * downstream analysis. When omitted, wrapping is skipped (zero overhead).*/-export function buildSandboxGlobals(): Record<string, unknown> {+export function buildSandboxGlobals(+ usage?: Record<string, number>+): Record<string, unknown> {// CSG ops are async — the executor awaits build() so agents can// `await boolDiff(...)` inside build().//@@ -530,40 +537,72 @@ export function buildSandboxGlobals(): Record<string, unknown> {const uvShapes = require('./uv-shapes') as typeof import('./uv-shapes');// eslint-disable-next-line @typescript-eslint/no-require-importsconst THREE = require('three') as typeof import('three');++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const wrap = <F extends (...args: any[]) => any>(name: string, fn: F): F => {+ if (!usage) return fn;+ const wrapped = (...args: Parameters<F>): ReturnType<F> => {+ usage[name] = (usage[name] ?? 0) + 1;+ return fn(...args);+ };+ return wrapped as F;+ };+return {- createRoot, createPivot, createPart,- capsuleGeo, cylinderGeo, boxGeo, sphereGeo, coneGeo, torusGeo, planeGeo,- gameMaterial, basicMaterial, glassMaterial, lambertMaterial,- rotationTrack, positionTrack, scaleTrack, createClip,- spinAnimation, bobbingAnimation, idleBreathing,- cloneGeometry, cloneMaterial, createInstance,+ createRoot: wrap('createRoot', createRoot),+ createPivot: wrap('createPivot', createPivot),+ createPart: wrap('createPart', createPart),+ capsuleGeo: wrap('capsuleGeo', capsuleGeo),+ cylinderGeo: wrap('cylinderGeo', cylinderGeo),+ boxGeo: wrap('boxGeo', boxGeo),+ sphereGeo: wrap('sphereGeo', sphereGeo),+ coneGeo: wrap('coneGeo', coneGeo),+ torusGeo: wrap('torusGeo', torusGeo),+ planeGeo: wrap('planeGeo', planeGeo),+ gameMaterial: wrap('gameMaterial', gameMaterial),+ basicMaterial: wrap('basicMaterial', basicMaterial),+ glassMaterial: wrap('glassMaterial', glassMaterial),+ lambertMaterial: wrap('lambertMaterial', lambertMaterial),+ rotationTrack: wrap('rotationTrack', rotationTrack),+ positionTrack: wrap('positionTrack', positionTrack),+ scaleTrack: wrap('scaleTrack', scaleTrack),+ createClip: wrap('createClip', createClip),+ spinAnimation: wrap('spinAnimation', spinAnimation),+ bobbingAnimation: wrap('bobbingAnimation', bobbingAnimation),+ idleBreathing: wrap('idleBreathing', idleBreathing),+ cloneGeometry: wrap('cloneGeometry', cloneGeometry),+ cloneMaterial: wrap('cloneMaterial', cloneMaterial),+ createInstance: wrap('createInstance', createInstance),// CSG (async)- boolUnion: solids.boolUnion,- boolDiff: solids.boolDiff,- boolIntersect: solids.boolIntersect,- hull: solids.hull,+ boolUnion: wrap('boolUnion', solids.boolUnion),+ boolDiff: wrap('boolDiff', solids.boolDiff),+ boolIntersect: wrap('boolIntersect', solids.boolIntersect),+ hull: wrap('hull', solids.hull),// Array/mirror/subdivide/curve ops- arrayLinear: ops.arrayLinear,- arrayRadial: ops.arrayRadial,- mirror: ops.mirror,- subdivide: ops.subdivide,- mergeVertices: ops.mergeVertices,- curveToMesh: ops.curveToMesh,- lathe: ops.lathe,- bezierCurve: ops.bezierCurve,+ arrayLinear: wrap('arrayLinear', ops.arrayLinear),+ arrayRadial: wrap('arrayRadial', ops.arrayRadial),+ mirror: wrap('mirror', ops.mirror),+ subdivide: wrap('subdivide', ops.subdivide),+ mergeVertices: wrap('mergeVertices', ops.mergeVertices),+ curveToMesh: wrap('curveToMesh', ops.curveToMesh),+ lathe: wrap('lathe', ops.lathe),+ bezierCurve: wrap('bezierCurve', ops.bezierCurve),// UV (async)- autoUnwrap: uv.autoUnwrap,+ autoUnwrap: wrap('autoUnwrap', uv.autoUnwrap),// Shape-aware unwraps (sync — preserve built-in directional UVs)- boxUnwrap: uvShapes.boxUnwrap,- cylinderUnwrap: uvShapes.cylinderUnwrap,- planeUnwrap: uvShapes.planeUnwrap,+ boxUnwrap: wrap('boxUnwrap', uvShapes.boxUnwrap),+ cylinderUnwrap: wrap('cylinderUnwrap', uvShapes.cylinderUnwrap),+ planeUnwrap: wrap('planeUnwrap', uvShapes.planeUnwrap),// Parametric primitives- gearGeo: gears.gearGeo,- bladeGeo: gears.bladeGeo,+ gearGeo: wrap('gearGeo', gears.gearGeo),+ bladeGeo: wrap('bladeGeo', gears.bladeGeo),// Textures + PBR (loadTexture is async)- loadTexture: textures.loadTexture,- pbrMaterial: textures.pbrMaterial,- countTriangles, countMaterials, getJointNames, validateAsset,+ loadTexture: wrap('loadTexture', textures.loadTexture),+ pbrMaterial: wrap('pbrMaterial', textures.pbrMaterial),+ countTriangles: wrap('countTriangles', countTriangles),+ countMaterials: wrap('countMaterials', countMaterials),+ getJointNames: wrap('getJointNames', getJointNames),+ validateAsset: wrap('validateAsset', validateAsset),// THREE namespace is exposed so agents can `new THREE.Mesh(geo, mat)`// as operands to CSG and other ops that expect Object3D inputs.THREE,diff --git a/render.ts b/render.tsindex ccec71bd..07ac9b9c 100644--- a/render.ts+++ b/render.ts@@ -49,6 +49,12 @@ export interface KilnCodeMeta {name?: string;category?: string;tris?: number;+ /**+ * Count of primitive invocations from the agent-generated build() call.+ * Populated by executeKilnCode / renderGLB; agents don't author this.+ * Used to drive primitive-library prioritization from real usage.+ */+ primitiveUsage?: Record<string, number>;[key: string]: unknown;}@@ -56,6 +62,11 @@ export interface ExecutedKilnCode {meta: KilnCodeMeta;root: THREE.Object3D;clips: THREE.AnimationClip[];+ /**+ * Primitive-call counts gathered while executing build()/animate().+ * Identical to meta.primitiveUsage once renderGLB merges it in.+ */+ primitiveUsage: Record<string, number>;}/**@@ -80,7 +91,8 @@ export async function executeKilnCode(code: string): Promise<ExecutedKilnCode> {// Function constructor.const normalized = code.replace(/\r\n/g, '\n');- const globals = buildSandboxGlobals();+ const primitiveUsage: Record<string, number> = {};+ const globals = buildSandboxGlobals(primitiveUsage);const globalNames = Object.keys(globals);const globalValues = Object.values(globals);@@ -111,7 +123,7 @@ export async function executeKilnCode(code: string): Promise<ExecutedKilnCode> {const clips = animate ? ((await animate(root)) ?? []) : [];- return { meta: meta ?? {}, root, clips };+ return { meta: meta ?? {}, root, clips, primitiveUsage };}// =============================================================================@@ -486,7 +498,7 @@ export async function renderSceneToGLB(* Pure function: no file I/O, no globals, no WebGL.*/export async function renderGLB(code: string): Promise<RenderResult> {- const { meta, root, clips } = await executeKilnCode(code);+ const { meta, root, clips, primitiveUsage } = await executeKilnCode(code);const scene = await renderSceneToGLB(root, {sceneName: meta.name || 'Scene',clips,@@ -495,7 +507,7 @@ export async function renderGLB(code: string): Promise<RenderResult> {return {glb: Buffer.from(scene.bytes),tris: scene.tris,- meta: { ...meta, tris: scene.tris },+ meta: { ...meta, tris: scene.tris, primitiveUsage },warnings: scene.warnings,};}