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): Waves 1-3 primitives + visual-audit inspector v2

Matt Kissinger6d4400055c16
diff --git a/__tests__/companions.test.ts b/__tests__/companions.test.ts
index e71c9b26..daadfa69 100644
--- a/__tests__/companions.test.ts
+++ b/__tests__/companions.test.ts
@@ -151,7 +151,7 @@ function animate() {
])];
}
`;
- const { root, clips } = kiln.executeKilnCode(code);
+ const { root, clips } = await kiln.executeKilnCode(code);
const warnings = kiln.inspectGeneratedAnimation(root, clips);
expect(warnings.length).toBeGreaterThan(0);
expect(warnings.some((w) => w.includes('Joint_Missing'))).toBe(true);
@@ -172,7 +172,7 @@ function animate() {
])];
}
`;
- const { root, clips } = kiln.executeKilnCode(code);
+ const { root, clips } = await kiln.executeKilnCode(code);
const warnings = kiln.inspectGeneratedAnimation(root, clips);
expect(warnings).toEqual([]);
});
@@ -186,7 +186,7 @@ function build() {
return root;
}
`;
- const { root, clips } = kiln.executeKilnCode(code);
+ const { root, clips } = await kiln.executeKilnCode(code);
expect(clips).toEqual([]);
expect(kiln.inspectGeneratedAnimation(root, clips)).toEqual([]);
});
diff --git a/__tests__/csg-sandbox.test.ts b/__tests__/csg-sandbox.test.ts
new file mode 100644
index 00000000..61d0d4b8
--- /dev/null
+++ b/__tests__/csg-sandbox.test.ts
@@ -0,0 +1,57 @@
+/**
+ * Wave 2A: verifies CSG primitives work inside the sandbox via
+ * executeKilnCode — the real agent-authoring path.
+ */
+
+import { describe, it, expect } from 'bun:test';
+import { executeKilnCode, renderGLB } from '../render';
+
+describe('Wave 2A: CSG inside sandbox (agent authoring path)', () => {
+ it('async build() with boolDiff produces a gear', async () => {
+ const code = `
+const meta = { name: 'Gear', category: 'prop' };
+
+async function build() {
+ const root = createRoot('Gear');
+ const steel = gameMaterial(0xb0b0b0, { metalness: 0.7, roughness: 0.3 });
+ const body = new (Object.getPrototypeOf(createPart('X', boxGeo(0,0,0), steel)).constructor)(cylinderGeo(1, 1, 0.3, 32), steel);
+ // Use THREE.Mesh via createPart-less construction since the sandbox
+ // does expose a Three-compatible Mesh through createPart.
+ // Simpler: use createPart which returns a Mesh, grab it as an operand.
+ return root;
+}
+`;
+ // The above stub just verifies the async path works at all. A more
+ // realistic sandbox path would involve THREE.Mesh, but the sandbox
+ // doesn't expose THREE directly. See the follow-up scenario below.
+ const { root } = await executeKilnCode(code);
+ expect(root.name).toBe('Gear');
+ });
+
+ it('agent-style code using createPart siblings + boolDiff', async () => {
+ // This is what a kiln prompt would actually produce: build parts with
+ // createPart, then feed them through boolDiff. The parts become
+ // detached from root once fed to CSG (we replace them with the
+ // result).
+ const code = `
+const meta = { name: 'PiercedBox', category: 'prop' };
+
+async function build() {
+ const root = createRoot('PiercedBox');
+ const steel = gameMaterial(0x888888);
+
+ // Build operand meshes as standalone (no parent) so they don't end up
+ // in root before being consumed by CSG.
+ const body = createPart('Body', boxGeo(2, 2, 2), steel, {});
+ const hole = createPart('Hole', cylinderGeo(0.4, 0.4, 3, 16), gameMaterial(0x000000), {});
+
+ const pierced = await boolDiff('Pierced', body, hole);
+ root.add(pierced);
+ return root;
+}
+`;
+ const r = await renderGLB(code);
+ expect(r.glb.byteLength).toBeGreaterThan(1000);
+ expect(r.tris).toBeGreaterThan(12); // More than a bare box
+ });
+});
diff --git a/__tests__/deps-smoke.test.ts b/__tests__/deps-smoke.test.ts
new file mode 100644
index 00000000..debc30ac
--- /dev/null
+++ b/__tests__/deps-smoke.test.ts
@@ -0,0 +1,32 @@
+/**
+ * Wave 1C smoke test: verify the new WASM/module deps load cleanly in Node.
+ * If any of these fail to import, the downstream CSG/UV/subdivide primitives
+ * (Waves 2A / 2B / 3A) won't work.
+ */
+
+import { describe, it, expect } from 'bun:test';
+
+describe('Wave 1C: new dependency smoke tests', () => {
+ it('manifold-3d loads and initializes', async () => {
+ const module = (await import('manifold-3d')) as unknown as {
+ default: () => Promise<Record<string, unknown>>;
+ };
+ const init = module.default;
+ expect(typeof init).toBe('function');
+
+ const Manifold = (await init()) as Record<string, unknown>;
+ expect(Manifold).toBeDefined();
+ expect(typeof Manifold['Manifold']).toBe('function');
+ });
+
+ it('three-subdivide loads', async () => {
+ const mod = (await import('three-subdivide')) as Record<string, unknown>;
+ expect(mod).toBeDefined();
+ expect(typeof mod['LoopSubdivision']).toBe('function');
+ });
+
+ it('xatlas-three loads', async () => {
+ const mod = (await import('xatlas-three')) as Record<string, unknown>;
+ expect(mod).toBeDefined();
+ });
+});
diff --git a/__tests__/instancing.test.ts b/__tests__/instancing.test.ts
new file mode 100644
index 00000000..a0a2a692
--- /dev/null
+++ b/__tests__/instancing.test.ts
@@ -0,0 +1,124 @@
+/**
+ * Wave 1B: instancing primitives + gltf-transform dedup end-to-end.
+ *
+ * Verifies that a 4-wheel vehicle built with createInstance produces a
+ * meaningfully smaller GLB than the naive "4 separate createPart calls"
+ * version, confirming geometry + material reuse survives the export path.
+ */
+
+import { describe, it, expect } from 'bun:test';
+import * as THREE from 'three';
+import {
+ createRoot,
+ createPart,
+ createInstance,
+ cloneGeometry,
+ cloneMaterial,
+ cylinderGeo,
+ boxGeo,
+ gameMaterial,
+} from '../primitives';
+import { renderSceneToGLB } from '../render';
+
+describe('Wave 1B: instancing primitives', () => {
+ it('cloneGeometry and cloneMaterial return the same reference', () => {
+ const geo = boxGeo(1, 1, 1);
+ const mat = gameMaterial(0xff0000);
+ expect(cloneGeometry(geo)).toBe(geo);
+ expect(cloneMaterial(mat)).toBe(mat);
+ });
+
+ it('createInstance reuses geometry and material of source', () => {
+ const root = createRoot('Truck');
+ const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);
+ const rubber = gameMaterial(0x1a1a1a);
+ const fl = createPart('WheelFL', wheelGeo, rubber, {
+ position: [-0.8, 0.3, 1.2],
+ parent: root,
+ });
+ const fr = createInstance('WheelFR', fl, {
+ position: [0.8, 0.3, 1.2],
+ parent: root,
+ });
+
+ expect(fr).toBeInstanceOf(THREE.Mesh);
+ expect((fr as THREE.Mesh).geometry).toBe((fl as THREE.Mesh).geometry);
+ expect((fr as THREE.Mesh).material).toBe((fl as THREE.Mesh).material);
+ expect(fr.parent).toBe(root);
+ });
+
+ it('createInstance from a pivot reuses the first Mesh child', () => {
+ const root = createRoot('Scene');
+ const pivot = createPart('Head', boxGeo(0.5, 0.5, 0.5), gameMaterial(0xffcc66), {
+ pivot: true,
+ parent: root,
+ });
+ const copy = createInstance('Head2', pivot, { position: [2, 0, 0], parent: root });
+ const sourceMesh = pivot.children[0] as THREE.Mesh;
+ expect((copy as THREE.Mesh).geometry).toBe(sourceMesh.geometry);
+ });
+
+ it('createInstance throws when source has no Mesh', () => {
+ const empty = new THREE.Object3D();
+ expect(() => createInstance('Bad', empty)).toThrow(/no Mesh/);
+ });
+
+ // A 4-wheel vehicle built three ways:
+ // 1. instanced — one geometry shared via createInstance
+ // 2. independent — four fresh createPart calls with identical geo/mat
+ // 3. raw-indep — same as (2) but with dedup disabled on export
+ // Ref-sharing via createInstance produces an optimal GLB without needing
+ // dedup. dedup() catches agents who forget to use createInstance and
+ // reaches the same optimum post-hoc. Both confirm the instancing path
+ // beats naive authoring when dedup is off.
+ it('instancing + dedup cuts 4-wheel GLB to ~1/3.5 of naive', async () => {
+ const buildInstanced = () => {
+ const r = createRoot('Instanced');
+ const wg = cylinderGeo(0.4, 0.4, 0.2, 16);
+ const rm = gameMaterial(0x1a1a1a);
+ const fl = createPart('WheelFL', wg, rm, { position: [-0.8, 0.3, 1.2], parent: r });
+ createInstance('WheelFR', fl, { position: [0.8, 0.3, 1.2], parent: r });
+ createInstance('WheelRL', fl, { position: [-0.8, 0.3, -1.2], parent: r });
+ createInstance('WheelRR', fl, { position: [0.8, 0.3, -1.2], parent: r });
+ return r;
+ };
+ const buildIndependent = () => {
+ const r = createRoot('Independent');
+ const coords: Array<[number, number]> = [[-0.8, 1.2], [0.8, 1.2], [-0.8, -1.2], [0.8, -1.2]];
+ coords.forEach(([x, z], i) => {
+ createPart(`W${i}`, cylinderGeo(0.4, 0.4, 0.2, 16), gameMaterial(0x1a1a1a), {
+ position: [x, 0.3, z],
+ parent: r,
+ });
+ });
+ return r;
+ };
+
+ const instanced = await renderSceneToGLB(buildInstanced());
+ const rawIndep = await renderSceneToGLB(buildIndependent(), { dedup: false });
+ const dedupedIndep = await renderSceneToGLB(buildIndependent());
+
+ // Raw (no dedup, no instancing): ~4x the size.
+ expect(instanced.bytes.byteLength).toBeLessThan(rawIndep.bytes.byteLength * 0.5);
+ // Dedup catches the redundancy even without createInstance.
+ expect(dedupedIndep.bytes.byteLength).toBeLessThan(rawIndep.bytes.byteLength * 0.5);
+ });
+
+ it('dedup: false disables the transform', async () => {
+ const root = createRoot('R');
+ // Two *separate* box geos with same shape — dedup should merge them,
+ // dedup:false should preserve both.
+ createPart('A', boxGeo(1, 1, 1), gameMaterial(0xff0000), {
+ position: [0, 0, 0],
+ parent: root,
+ });
+ createPart('B', boxGeo(1, 1, 1), gameMaterial(0xff0000), {
+ position: [2, 0, 0],
+ parent: root,
+ });
+
+ const withDedup = await renderSceneToGLB(root);
+ const withoutDedup = await renderSceneToGLB(root, { dedup: false });
+ expect(withDedup.bytes.byteLength).toBeLessThan(withoutDedup.bytes.byteLength);
+ });
+});
diff --git a/__tests__/list-primitives.test.ts b/__tests__/list-primitives.test.ts
index e889bd1d..d5ca3120 100644
--- a/__tests__/list-primitives.test.ts
+++ b/__tests__/list-primitives.test.ts
@@ -22,9 +22,20 @@ describe('kiln.listPrimitives', () => {
expect(p.returns.length).toBeGreaterThan(0);
expect(p.description.length).toBeGreaterThan(0);
expect(p.example.length).toBeGreaterThan(0);
- expect(['geometry', 'material', 'structure', 'animation', 'utility']).toContain(
- p.category
- );
+ expect([
+ 'geometry',
+ 'material',
+ 'structure',
+ 'animation',
+ 'utility',
+ 'instancing',
+ 'csg',
+ 'arrays',
+ 'mesh-ops',
+ 'curves',
+ 'uv',
+ 'textures',
+ ]).toContain(p.category);
}
});
diff --git a/__tests__/render-edges.test.ts b/__tests__/render-edges.test.ts
index 94442231..32c9cc6b 100644
--- a/__tests__/render-edges.test.ts
+++ b/__tests__/render-edges.test.ts
@@ -22,43 +22,42 @@ import {
// =============================================================================
describe('executeKilnCode input validation', () => {
- test('throws on empty string', () => {
- expect(() => executeKilnCode('')).toThrow(/non-empty string/);
+ test('throws on empty string', async () => {
+ await expect(executeKilnCode('')).rejects.toThrow(/non-empty string/);
});
- test('throws when build is not defined at all', () => {
+ test('throws when build is not defined at all', async () => {
// The Function-constructor sandbox references `build` unconditionally
// in its return wrapper, so a missing declaration surfaces as a
// ReferenceError before the typeof check fires. Either failure
// mode is acceptable - the contract is "code without build() does
// not silently render".
- expect(() =>
+ await expect(
executeKilnCode(`const meta = { name: 'NoBuild' };`)
- ).toThrow(/build is not defined|did not define `build`/);
+ ).rejects.toThrow(/build is not defined|did not define `build`/);
});
- test('throws when build is defined but is not a function', () => {
- // This drives the explicit `typeof build !== 'function'` branch.
- expect(() =>
+ test('throws when build is defined but is not a function', async () => {
+ await expect(
executeKilnCode(`
const meta = { name: 'NotFn' };
const build = 'not a function';
`)
- ).toThrow(/did not define `build`/);
+ ).rejects.toThrow(/did not define `build`/);
});
- test('throws when build() does not return an Object3D', () => {
- expect(() =>
+ test('throws when build() does not return an Object3D', async () => {
+ await expect(
executeKilnCode(`
const meta = { name: 'BadReturn' };
function build() { return 42; }
`)
- ).toThrow(/did not return a THREE.Object3D/);
+ ).rejects.toThrow(/did not return a THREE.Object3D/);
});
- test('normalizes CRLF line endings', () => {
+ test('normalizes CRLF line endings', async () => {
const code = `\r\nconst meta = { name: 'CRLF' };\r\nfunction build() { return createRoot('CRLF'); }\r\n`;
- const { meta, root } = executeKilnCode(code);
+ const { meta, root } = await executeKilnCode(code);
expect(meta.name).toBe('CRLF');
expect(root.name).toBe('CRLF');
});
@@ -220,8 +219,8 @@ function animate() {
// =============================================================================
describe('inspectGeneratedAnimation track validation', () => {
- test('flags tracks whose name lacks a dot separator', () => {
- const { root, clips } = executeKilnCode(`
+ test('flags tracks whose name lacks a dot separator', async () => {
+ const { root, clips } = await executeKilnCode(`
const meta = { name: 'R' };
function build() { return createRoot('R'); }
function animate() {
@@ -235,8 +234,8 @@ function animate() {
expect(warnings.some((w) => w.includes('missing a node.property separator'))).toBe(true);
});
- test('flags tracks using unsupported properties', () => {
- const { root, clips } = executeKilnCode(`
+ test('flags tracks using unsupported properties', async () => {
+ const { root, clips } = await executeKilnCode(`
const meta = { name: 'R' };
function build() {
const root = createRoot('R');
diff --git a/__tests__/solids.test.ts b/__tests__/solids.test.ts
new file mode 100644
index 00000000..e22268f0
--- /dev/null
+++ b/__tests__/solids.test.ts
@@ -0,0 +1,102 @@
+/**
+ * Wave 2A: CSG primitives via manifold-3d.
+ *
+ * Smoke-tests boolUnion / boolDiff / boolIntersect / hull end-to-end:
+ * three.js geometry -> Manifold -> result -> three.js Mesh -> GLB bytes.
+ *
+ * These tests pay the ~100ms WASM init on the first manifold call. Keep
+ * them in a single describe block so init happens once.
+ */
+
+import { describe, it, expect } from 'bun:test';
+import * as THREE from 'three';
+import {
+ createRoot,
+ createPart,
+ boxGeo,
+ cylinderGeo,
+ sphereGeo,
+ gameMaterial,
+} from '../primitives';
+import { boolUnion, boolDiff, boolIntersect, hull } from '../solids';
+import { renderSceneToGLB } from '../render';
+
+describe('Wave 2A: CSG primitives (manifold-3d)', () => {
+ it('boolUnion merges two boxes into a watertight mesh', async () => {
+ const a = new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0xff0000));
+ const b = new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0xff0000));
+ b.position.set(0.5, 0, 0);
+
+ const merged = await boolUnion('Merged', a, b);
+ expect(merged).toBeInstanceOf(THREE.Mesh);
+ const posCount = (merged.geometry.getAttribute('position') as THREE.BufferAttribute)
+ .count;
+ expect(posCount).toBeGreaterThan(0);
+ });
+
+ it('boolDiff carves a hole (cylinder through box)', async () => {
+ const body = new THREE.Mesh(boxGeo(2, 2, 2), gameMaterial(0x888888));
+ const hole = new THREE.Mesh(cylinderGeo(0.4, 0.4, 3, 16), gameMaterial(0x000000));
+
+ const pierced = await boolDiff('Pierced', body, hole);
+ const piercedTris =
+ (pierced.geometry.getIndex()?.count ?? 0) / 3;
+ // A pierced box has more triangles than a plain box (12).
+ expect(piercedTris).toBeGreaterThan(12);
+ });
+
+ it('builds a gear: cylinder minus 8 radially-arrayed box cutters', async () => {
+ const root = createRoot('Gear');
+ const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), gameMaterial(0xaaaaaa));
+
+ // 8 cutters radially arrayed around the Y axis at radius 1.1
+ const cutters: THREE.Mesh[] = [];
+ for (let i = 0; i < 8; i++) {
+ const angle = (i / 8) * Math.PI * 2;
+ const c = new THREE.Mesh(boxGeo(0.4, 0.4, 0.4), gameMaterial(0x000000));
+ c.position.set(Math.cos(angle) * 1.1, 0, Math.sin(angle) * 1.1);
+ cutters.push(c);
+ }
+
+ const gear = await boolDiff('Gear', body, ...cutters);
+ root.add(gear);
+
+ const result = await renderSceneToGLB(root);
+ expect(result.bytes.byteLength).toBeGreaterThan(1000);
+ // Gear should have more tris than the plain cylinder (2*32 = 64).
+ expect(result.tris).toBeGreaterThan(64);
+ });
+
+ it('boolIntersect keeps overlap only', async () => {
+ const a = new THREE.Mesh(boxGeo(2, 2, 2), gameMaterial(0x00ff00));
+ const b = new THREE.Mesh(sphereGeo(1.2, 16, 12), gameMaterial(0x00ff00));
+
+ const lens = await boolIntersect('Lens', a, b);
+ expect(lens).toBeInstanceOf(THREE.Mesh);
+ const posCount = (lens.geometry.getAttribute('position') as THREE.BufferAttribute)
+ .count;
+ expect(posCount).toBeGreaterThan(0);
+ });
+
+ it('hull wraps a cluster of small boxes into one convex mesh', async () => {
+ const parts: THREE.Mesh[] = [];
+ for (let i = 0; i < 4; i++) {
+ const b = new THREE.Mesh(boxGeo(0.2, 0.2, 0.2), gameMaterial(0x6699cc));
+ b.position.set(Math.cos(i) * 0.8, Math.sin(i) * 0.8, 0);
+ parts.push(b);
+ }
+ const wrapped = await hull('Cluster', ...parts);
+ expect(wrapped).toBeInstanceOf(THREE.Mesh);
+
+ const tris = (wrapped.geometry.getIndex()?.count ?? 0) / 3;
+ // A convex hull of 4 small boxes has far fewer tris than 4*12=48.
+ expect(tris).toBeLessThan(48);
+ expect(tris).toBeGreaterThan(0);
+ });
+
+ it('errors clearly on invalid input', async () => {
+ await expect(
+ boolUnion('X', new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0xff0000)))
+ ).rejects.toThrow(/at least two/);
+ });
+});
diff --git a/__tests__/textures.test.ts b/__tests__/textures.test.ts
new file mode 100644
index 00000000..7b76ced4
--- /dev/null
+++ b/__tests__/textures.test.ts
@@ -0,0 +1,103 @@
+/**
+ * Wave 3B: PBR materials + texture round-trip through the GLB bridge.
+ */
+
+import { describe, it, expect } from 'bun:test';
+import * as THREE from 'three';
+import sharp from 'sharp';
+import { NodeIO } from '@gltf-transform/core';
+import {
+ createRoot,
+ boxGeo,
+ gameMaterial,
+} from '../primitives';
+import { loadTexture, pbrMaterial } from '../textures';
+import { autoUnwrap } from '../uv';
+import { renderSceneToGLB } from '../render';
+
+async function makeSolidPng(color: { r: number; g: number; b: number }): Promise<Buffer> {
+ return sharp({
+ create: {
+ width: 16,
+ height: 16,
+ channels: 4,
+ background: { ...color, alpha: 1 },
+ },
+ })
+ .png()
+ .toBuffer();
+}
+
+describe('Wave 3B: loadTexture + pbrMaterial', () => {
+ it('loadTexture decodes a PNG into a DataTexture with encoded bytes stashed', async () => {
+ const png = await makeSolidPng({ r: 255, g: 100, b: 50 });
+ const tex = await loadTexture(png);
+
+ expect(tex).toBeInstanceOf(THREE.DataTexture);
+ expect(tex.image.width).toBe(16);
+ expect(tex.image.height).toBe(16);
+ const encoded = (tex.userData as Record<string, unknown>)['encoded'] as {
+ mime: string;
+ bytes: Uint8Array;
+ };
+ expect(encoded).toBeDefined();
+ expect(encoded.mime).toBe('image/png');
+ expect(encoded.bytes.length).toBe(png.length);
+ });
+
+ it('pbrMaterial with scalar inputs produces a MeshStandardMaterial', () => {
+ const mat = pbrMaterial({ albedo: 0x886644, roughness: 0.9, metalness: 0 });
+ expect(mat).toBeInstanceOf(THREE.MeshStandardMaterial);
+ expect(mat.color.getHex()).toBe(0x886644);
+ expect(mat.roughness).toBeCloseTo(0.9);
+ expect(mat.metalness).toBe(0);
+ });
+
+ it('pbrMaterial with a Texture wires map + neutralizes color', async () => {
+ const png = await makeSolidPng({ r: 200, g: 150, b: 100 });
+ const tex = await loadTexture(png);
+ const mat = pbrMaterial({ albedo: tex });
+
+ expect(mat.map).toBe(tex);
+ expect(mat.color.getHex()).toBe(0xffffff);
+ });
+
+ it('texture survives round-trip through GLB export', async () => {
+ const png = await makeSolidPng({ r: 255, g: 0, b: 128 });
+ const tex = await loadTexture(png);
+ const mat = pbrMaterial({ albedo: tex, roughness: 0.7 });
+
+ const root = createRoot('TexCrate');
+ const geo = await autoUnwrap(boxGeo(1, 1, 1));
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.name = 'Mesh_TexCrate';
+ root.add(mesh);
+
+ const { bytes } = await renderSceneToGLB(root);
+ expect(bytes.byteLength).toBeGreaterThan(png.length); // contains the texture
+
+ // Re-parse the GLB and confirm the albedo texture is present.
+ const io = new NodeIO();
+ const doc = await io.readBinary(bytes);
+ const mats = doc.getRoot().listMaterials();
+ expect(mats.length).toBe(1);
+ const base = mats[0]!.getBaseColorTexture();
+ expect(base).not.toBeNull();
+ const img = base!.getImage();
+ expect(img).not.toBeNull();
+ expect(img!.byteLength).toBe(png.length);
+ });
+
+ it('untextured gameMaterial still exports without maps (regression)', async () => {
+ const root = createRoot('Plain');
+ const mesh = new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0xff0000));
+ mesh.name = 'Mesh_Plain';
+ root.add(mesh);
+ const { bytes } = await renderSceneToGLB(root);
+
+ const io = new NodeIO();
+ const doc = await io.readBinary(bytes);
+ const mats = doc.getRoot().listMaterials();
+ expect(mats[0]!.getBaseColorTexture()).toBeNull();
+ });
+});
diff --git a/__tests__/uv.test.ts b/__tests__/uv.test.ts
new file mode 100644
index 00000000..8c4f31d5
--- /dev/null
+++ b/__tests__/uv.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Wave 3A: UV auto-unwrap via xatlasjs (Node WASM).
+ *
+ * Verifies:
+ * - autoUnwrap produces UVs within [0, 1]
+ * - atlas metadata stamped on userData
+ * - post-unwrap geometry exports cleanly through the GLB bridge
+ * - survives through CSG output (boolDiff → autoUnwrap → GLB)
+ */
+
+import { describe, it, expect } from 'bun:test';
+import * as THREE from 'three';
+import {
+ createRoot,
+ boxGeo,
+ cylinderGeo,
+ sphereGeo,
+ gameMaterial,
+} from '../primitives';
+import { autoUnwrap } from '../uv';
+import { boolDiff } from '../solids';
+import { renderSceneToGLB } from '../render';
+
+describe('Wave 3A: autoUnwrap (xatlasjs)', () => {
+ it('produces a uv attribute on a simple box', async () => {
+ const unwrapped = await autoUnwrap(boxGeo(1, 1, 1), { resolution: 512 });
+ const uv = unwrapped.getAttribute('uv') as THREE.BufferAttribute | undefined;
+ expect(uv).toBeDefined();
+ expect(uv!.itemSize).toBe(2);
+ expect(uv!.count).toBeGreaterThan(0);
+
+ // All UV values should lie in [0, 1].
+ let min = Infinity;
+ let max = -Infinity;
+ for (let i = 0; i < uv!.array.length; i++) {
+ const v = uv!.array[i] as number;
+ if (v < min) min = v;
+ if (v > max) max = v;
+ }
+ expect(min).toBeGreaterThanOrEqual(0);
+ expect(max).toBeLessThanOrEqual(1);
+ });
+
+ it('stamps atlas metadata on userData', async () => {
+ const unwrapped = await autoUnwrap(sphereGeo(1, 16, 12), { resolution: 1024 });
+ const atlas = unwrapped.userData['atlas'] as
+ | { width: number; height: number; atlasCount: number }
+ | undefined;
+ expect(atlas).toBeDefined();
+ expect(atlas!.width).toBeGreaterThan(0);
+ expect(atlas!.height).toBeGreaterThan(0);
+ expect(atlas!.atlasCount).toBeGreaterThanOrEqual(1);
+ });
+
+ it('does not mutate the input geometry', async () => {
+ const input = boxGeo(1, 1, 1);
+ const beforeUv = input.getAttribute('uv');
+ const beforeVertCount = (input.getAttribute('position') as THREE.BufferAttribute).count;
+
+ await autoUnwrap(input);
+
+ const afterUv = input.getAttribute('uv');
+ const afterVertCount = (input.getAttribute('position') as THREE.BufferAttribute).count;
+ // xatlas may reindex and duplicate seam verts, but the input shouldn't change.
+ expect(afterVertCount).toBe(beforeVertCount);
+ expect(afterUv).toBe(beforeUv);
+ });
+
+ it('UVs survive GLB export end-to-end', async () => {
+ const root = createRoot('UvCube');
+ const unwrapped = await autoUnwrap(boxGeo(1, 1, 1));
+ const mat = gameMaterial(0x888888);
+ const mesh = new THREE.Mesh(unwrapped, mat);
+ mesh.name = 'Mesh_UvCube';
+ root.add(mesh);
+
+ const result = await renderSceneToGLB(root);
+ expect(result.bytes.byteLength).toBeGreaterThan(500);
+ // No UV-related warnings should surface.
+ expect(result.warnings.filter((w) => w.toLowerCase().includes('uv'))).toEqual([]);
+ });
+
+ it('works on CSG output (boolDiff → autoUnwrap)', async () => {
+ const body = new THREE.Mesh(boxGeo(2, 2, 2), gameMaterial(0x888888));
+ const hole = new THREE.Mesh(cylinderGeo(0.4, 0.4, 3, 16), gameMaterial(0x000000));
+ const pierced = await boolDiff('Pierced', body, hole);
+
+ const unwrapped = await autoUnwrap(pierced.geometry);
+ const uv = unwrapped.getAttribute('uv') as THREE.BufferAttribute | undefined;
+ expect(uv).toBeDefined();
+ expect(uv!.count).toBeGreaterThan(0);
+ });
+});
diff --git a/generate.ts b/generate.ts
index fe92bd75..a21772d3 100644
--- a/generate.ts
+++ b/generate.ts
@@ -298,6 +298,46 @@ Fix these issues before producing the refactored code.`;
return retried;
}
+/**
+ * Maps a single SDK message to a terminal KilnGenerateResult, or returns
+ * null if the message is not terminal and the caller should keep iterating.
+ *
+ * Shared between runRefactorQuery and runStructuredQuery to dedupe the
+ * three branches (success / error result / auth failure).
+ */
+function handleQueryMessage(
+ message: Record<string, any>,
+ fallbackErrorLabel: string
+): KilnGenerateResult | null {
+ if (message['type'] === 'result' && message['subtype'] === 'success') {
+ const sessionId = message['session_id'];
+ if (message['structured_output']) {
+ const output = message['structured_output'] as { code: string; effectCode?: string };
+ return {
+ success: true,
+ code: output.code,
+ effectCode: output.effectCode,
+ sessionId,
+ };
+ }
+ return parseResultText(message['result'], sessionId);
+ }
+ if (message['type'] === 'result' && message['subtype']?.startsWith('error')) {
+ const errs = message['errors'];
+ return {
+ success: false,
+ error: Array.isArray(errs) ? errs.join('; ') : fallbackErrorLabel,
+ };
+ }
+ if (message['type'] === 'auth_status' && message['error']) {
+ return {
+ success: false,
+ error: `Auth failed: ${message['error']}. Run "claude auth login".`,
+ };
+ }
+ return null;
+}
+
async function runRefactorQuery(
prompt: string,
systemPrompt: string,
@@ -324,38 +364,9 @@ async function runRefactorQuery(
},
});
- let sessionId: string | undefined;
-
for await (const message of q) {
- if (message.type === 'result' && message.subtype === 'success') {
- sessionId = message.session_id;
- if (message.structured_output) {
- const output = message.structured_output as {
- code: string;
- effectCode?: string;
- };
- return {
- success: true,
- code: output.code,
- effectCode: output.effectCode,
- sessionId,
- };
- }
- return parseResultText(message.result, sessionId);
- }
- if (message.type === 'result' && message.subtype?.startsWith('error')) {
- const errMsg = (message as Record<string, unknown>).errors;
- return {
- success: false,
- error: Array.isArray(errMsg) ? errMsg.join('; ') : 'Refactor failed',
- };
- }
- if (message.type === 'auth_status' && message.error) {
- return {
- success: false,
- error: `Auth failed: ${message.error}. Run "claude auth login".`,
- };
- }
+ const terminal = handleQueryMessage(message as Record<string, any>, 'Refactor failed');
+ if (terminal) return terminal;
}
return { success: false, error: 'No result received from refactor query' };
@@ -399,31 +410,8 @@ async function runStructuredQuery(
});
for await (const message of q) {
- if (message.type === 'result' && message.subtype === 'success') {
- if (message.structured_output) {
- const output = message.structured_output as { code: string; effectCode?: string };
- return {
- success: true,
- code: output.code,
- effectCode: output.effectCode,
- sessionId: message.session_id,
- };
- }
- return parseResultText(message.result, message.session_id);
- }
- if (message.type === 'result' && message.subtype?.startsWith('error')) {
- const errors = (message as Record<string, unknown>).errors;
- return {
- success: false,
- error: Array.isArray(errors) ? errors.join('; ') : 'Generation failed',
- };
- }
- if (message.type === 'auth_status' && message.error) {
- return {
- success: false,
- error: `Auth failed: ${message.error}. Run "claude auth login".`,
- };
- }
+ const terminal = handleQueryMessage(message as Record<string, any>, 'Generation failed');
+ if (terminal) return terminal;
}
return { success: false, error: 'No result received from query' };
diff --git a/index.ts b/index.ts
index 9517cf27..e907aa5b 100644
--- a/index.ts
+++ b/index.ts
@@ -88,7 +88,25 @@ export {
idleBreathing,
bobbingAnimation,
spinAnimation,
+ cloneGeometry,
+ cloneMaterial,
+ createInstance,
} from './primitives';
+export type { TrackInterpolation } from './primitives';
+export { boolUnion, boolDiff, boolIntersect, hull } from './solids';
+export {
+ arrayLinear,
+ arrayRadial,
+ mirror,
+ subdivide,
+ curveToMesh,
+ lathe,
+ bezierCurve,
+} from './ops';
+export { autoUnwrap } from './uv';
+export type { AutoUnwrapOptions } from './uv';
+export { loadTexture, pbrMaterial } from './textures';
+export type { PbrMaterialOptions, TextureSource, EncodedTextureData } from './textures';
// =============================================================================
// Top-level `generate()` - the full pipeline: prompt -> code -> GLB
diff --git a/inspect.ts b/inspect.ts
index f23f8ba2..8ff098ed 100644
--- a/inspect.ts
+++ b/inspect.ts
@@ -254,7 +254,7 @@ function collectAnimationTracks(
* {@link executeKilnCode}).
*/
export async function inspect(code: string): Promise<InspectResult> {
- const { meta, root, clips } = executeKilnCode(code);
+ const { meta, root, clips } = await executeKilnCode(code);
const primitivesUsed = detectPrimitivesUsed(code);
const namedParts = collectNamedParts(root);
diff --git a/list-primitives.ts b/list-primitives.ts
index 9915b829..15aaab29 100644
--- a/list-primitives.ts
+++ b/list-primitives.ts
@@ -24,7 +24,19 @@ export interface PrimitiveSpec {
/** Idiomatic usage snippet agents can splice directly into generated code. */
example: string;
/** High-level grouping for filtering in agent UIs. */
- category: 'geometry' | 'material' | 'structure' | 'animation' | 'utility';
+ category:
+ | 'geometry'
+ | 'material'
+ | 'structure'
+ | 'animation'
+ | 'utility'
+ | 'instancing'
+ | 'csg'
+ | 'arrays'
+ | 'mesh-ops'
+ | 'curves'
+ | 'uv'
+ | 'textures';
}
const PRIMITIVES: PrimitiveSpec[] = [
@@ -234,6 +246,208 @@ const PRIMITIVES: PrimitiveSpec[] = [
example: "return [spinAnimation('Joint_Rotor', 0.5, 'y')];",
},
+ // ---------------------------------------------------------------------------
+ // Instancing (Wave 1B) — reuse geometry + material across many parts
+ // ---------------------------------------------------------------------------
+ {
+ name: 'cloneGeometry',
+ signature: 'cloneGeometry(geo: BufferGeometry)',
+ returns: 'THREE.BufferGeometry (same ref)',
+ category: 'instancing',
+ description:
+ 'Returns the same geometry reference. Use it as a signal that you are intentionally sharing geometry across multiple parts; gltf-transform dedupes on export.',
+ example: 'const wheelGeo = cylinderGeo(0.4, 0.4, 0.2, 12);',
+ },
+ {
+ name: 'cloneMaterial',
+ signature: 'cloneMaterial(mat: Material)',
+ returns: 'THREE.Material (same ref)',
+ category: 'instancing',
+ description: 'Shared material reference. See cloneGeometry.',
+ example: 'const rubberMat = gameMaterial(0x1a1a1a, { roughness: 0.95 });',
+ },
+ {
+ name: 'createInstance',
+ signature:
+ 'createInstance(name, source, opts?: { position, rotation, scale, parent })',
+ returns: 'THREE.Object3D',
+ category: 'instancing',
+ description:
+ 'Creates a new mesh reusing an existing part\'s geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows.',
+ example:
+ "const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });\ncreateInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });\ncreateInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });\ncreateInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });",
+ },
+
+ // ---------------------------------------------------------------------------
+ // CSG / Boolean ops (Wave 2A) — async, backed by manifold-3d
+ // ---------------------------------------------------------------------------
+ // IMPORTANT: build() must be `async` and the call must use `await` because
+ // these ops are WASM-backed. The executor awaits build() transparently.
+ {
+ name: 'boolUnion',
+ signature: 'await boolUnion(name: string, ...parts: Object3D[])',
+ returns: 'Promise<THREE.Mesh>',
+ category: 'csg',
+ description:
+ 'Merges two or more parts into one watertight manifold mesh. Inherits material from the first operand.',
+ example:
+ "const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);\nconst turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);\nturret.position.y = 0.5;\nconst hull = await boolUnion('Hull', body, turret);",
+ },
+ {
+ name: 'boolDiff',
+ signature: 'await boolDiff(name: string, body: Object3D, ...cutters: Object3D[])',
+ returns: 'Promise<THREE.Mesh>',
+ category: 'csg',
+ description:
+ 'Subtracts one or more cutters from a body. Use to carve holes, button recesses, window slots, bolt mounts.',
+ example:
+ "const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);\nconst teeth = [...]; // 8 radially-arrayed box meshes\nconst gear = await boolDiff('Gear', body, ...teeth);",
+ },
+ {
+ name: 'boolIntersect',
+ signature: 'await boolIntersect(name: string, a: Object3D, b: Object3D)',
+ returns: 'Promise<THREE.Mesh>',
+ category: 'csg',
+ description:
+ 'Keeps only the volume where both operands overlap. Less common than union/diff but useful for lens shapes and trim cuts.',
+ example:
+ "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);",
+ },
+ {
+ name: 'hull',
+ signature: 'await hull(name: string, ...parts: Object3D[])',
+ returns: 'Promise<THREE.Mesh>',
+ category: 'csg',
+ description:
+ 'Tightest convex mesh enclosing all input points. Good for simplifying rocks, loose clusters, or collision volumes.',
+ example:
+ "const rockChunks = [...]; // scattered box meshes\nconst rock = await hull('Rock', ...rockChunks);",
+ },
+
+ // ---------------------------------------------------------------------------
+ // Arrays / mirror (Wave 2B) — replicate a source part with shared geo/mat
+ // ---------------------------------------------------------------------------
+ {
+ name: 'arrayLinear',
+ signature:
+ 'arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)',
+ returns: 'THREE.Object3D[]',
+ category: 'arrays',
+ description:
+ 'Places N copies of `source` along a constant offset vector. Copies share geometry + material via createInstance.',
+ example:
+ "const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });\narrayLinear('Post', post, 10, [0.5, 0, 0], root);",
+ },
+ {
+ name: 'arrayRadial',
+ signature:
+ "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
+ returns: 'THREE.Object3D[]',
+ category: 'arrays',
+ description:
+ "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.",
+ example:
+ "const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });\narrayRadial('Bolt', bolt, 8, 'y', root);",
+ },
+ {
+ name: 'mirror',
+ signature: "mirror(name, source, axis: 'x'|'y'|'z', parent?)",
+ returns: 'THREE.Object3D',
+ category: 'arrays',
+ description:
+ "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
+ example: "mirror('WingR', wingL, 'x', root);",
+ },
+
+ // ---------------------------------------------------------------------------
+ // Mesh ops (Wave 2B)
+ // ---------------------------------------------------------------------------
+ {
+ name: 'subdivide',
+ signature:
+ 'subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { split, uvSmooth, preserveEdges, flatOnly })',
+ returns: 'THREE.BufferGeometry',
+ category: 'mesh-ops',
+ description:
+ 'Loop subdivision. Each iteration ~4x the triangle count and smooths the surface. Use 1 for mild smoothing, 2 for organic shapes.',
+ example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);",
+ },
+
+ // ---------------------------------------------------------------------------
+ // Curves (Wave 2B)
+ // ---------------------------------------------------------------------------
+ {
+ name: 'curveToMesh',
+ signature:
+ 'curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)',
+ returns: 'THREE.BufferGeometry',
+ category: 'curves',
+ description:
+ "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.",
+ example:
+ "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);",
+ },
+ {
+ name: 'lathe',
+ signature: 'lathe(profile: [x,y][], segments?: 12)',
+ returns: 'THREE.BufferGeometry',
+ category: 'curves',
+ description:
+ 'Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.',
+ example:
+ "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);",
+ },
+ {
+ name: 'bezierCurve',
+ signature: 'bezierCurve(controlPoints: [x,y,z][], samples?: 32)',
+ returns: '[x,y,z][]',
+ category: 'curves',
+ description:
+ "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",
+ example:
+ "const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);\nconst geo = curveToMesh(path, 0.1);",
+ },
+
+ // ---------------------------------------------------------------------------
+ // UV (Wave 3A) — async, WASM-backed via xatlasjs
+ // ---------------------------------------------------------------------------
+ {
+ name: 'autoUnwrap',
+ signature:
+ 'await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })',
+ returns: 'Promise<THREE.BufferGeometry>',
+ category: 'uv',
+ description:
+ "Auto-generates a UV atlas for any BufferGeometry using xatlas. Required before applying textures or projection-baking. Input not mutated; output geometry has fresh uv attribute in [0,1] and atlas metadata on userData.atlas.",
+ example:
+ "const unwrapped = await autoUnwrap(boxGeo(1, 2, 1), { resolution: 1024 });\nconst crate = new THREE.Mesh(unwrapped, woodPBR);",
+ },
+
+ // ---------------------------------------------------------------------------
+ // Textures + PBR (Wave 3B)
+ // ---------------------------------------------------------------------------
+ {
+ name: 'loadTexture',
+ signature: 'await loadTexture(source: string | Buffer | Uint8Array)',
+ returns: 'Promise<THREE.DataTexture>',
+ category: 'textures',
+ description:
+ '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');",
+ },
+ {
+ name: 'pbrMaterial',
+ signature:
+ 'pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? })',
+ returns: 'THREE.MeshStandardMaterial',
+ category: 'material',
+ description:
+ 'Full PBR material. Each slot can be a hex color/scalar or a Texture loaded via loadTexture. Exports as glTF pbrMetallicRoughness.',
+ example:
+ "const wood = await loadTexture('./oak.png');\nconst crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });",
+ },
+
// ---------------------------------------------------------------------------
// Utility
// ---------------------------------------------------------------------------
diff --git a/ops.ts b/ops.ts
new file mode 100644
index 00000000..9893cec8
--- /dev/null
+++ b/ops.ts
@@ -0,0 +1,219 @@
+/**
+ * Kiln higher-level ops — Wave 2B
+ *
+ * Array/mirror/subdivide/curve helpers that wrap the base primitives.
+ * These expand the catalog toward Blender Geometry Nodes parity without
+ * bloating primitives.ts.
+ *
+ * - `arrayLinear` / `arrayRadial` / `mirror` use createInstance under the
+ * hood so the GLB exports as true glTF mesh instances (single geometry,
+ * many transforms).
+ * - `subdivide` runs Loop subdivision on a BufferGeometry.
+ * - `curveToMesh` / `lathe` wrap Three.js TubeGeometry/LatheGeometry for
+ * curves-as-primitives.
+ */
+
+import * as THREE from 'three';
+import { LoopSubdivision } from 'three-subdivide';
+import { createInstance } from './primitives';
+
+// =============================================================================
+// Array ops
+// =============================================================================
+
+/**
+ * Linear array: place `count` copies of `source` along a constant offset.
+ * Uses createInstance so all copies share geometry + material.
+ *
+ * @example
+ * const postGeo = cylinderGeo(0.05, 0.05, 1.5, 6);
+ * const postMat = gameMaterial(0x8b6f3d);
+ * const first = createPart('Post0', postGeo, postMat, { position: [0, 0.75, 0], parent: root });
+ * arrayLinear('Post', first, 10, [0.5, 0, 0], root); // 10 posts, 0.5 apart on X
+ */
+export function arrayLinear(
+ namePrefix: string,
+ source: THREE.Object3D,
+ count: number,
+ offset: [number, number, number],
+ parent?: THREE.Object3D
+): THREE.Object3D[] {
+ const out: THREE.Object3D[] = [];
+ // Source is already at some position; clones start at offset 1.
+ const base = source.position.toArray() as [number, number, number];
+ for (let i = 1; i < count; i++) {
+ const pos: [number, number, number] = [
+ base[0] + offset[0] * i,
+ base[1] + offset[1] * i,
+ base[2] + offset[2] * i,
+ ];
+ out.push(createInstance(`${namePrefix}${i}`, source, { position: pos, parent }));
+ }
+ return out;
+}
+
+/**
+ * Radial array: place `count` copies of `source` around an axis at radius.
+ * Source stays put; clones orbit around the origin on the given axis.
+ *
+ * @example
+ * const bolt = createPart('Bolt', cylinderGeo(0.02, 0.02, 0.1, 6), steel,
+ * { position: [1, 0, 0], parent: root });
+ * arrayRadial('Bolt', bolt, 8, 'y', root); // 8 bolts around Y axis
+ */
+export function arrayRadial(
+ namePrefix: string,
+ source: THREE.Object3D,
+ count: number,
+ axis: 'x' | 'y' | 'z' = 'y',
+ parent?: THREE.Object3D
+): THREE.Object3D[] {
+ const out: THREE.Object3D[] = [];
+ const basePos = source.position.clone();
+ const axisVec =
+ axis === 'x'
+ ? new THREE.Vector3(1, 0, 0)
+ : axis === 'z'
+ ? new THREE.Vector3(0, 0, 1)
+ : new THREE.Vector3(0, 1, 0);
+
+ for (let i = 1; i < count; i++) {
+ const angle = (i / count) * Math.PI * 2;
+ const m = new THREE.Matrix4().makeRotationAxis(axisVec, angle);
+ const rotated = basePos.clone().applyMatrix4(m);
+ // Rotate local frame too so the copy faces outward consistently.
+ const eulerDeg: [number, number, number] =
+ axis === 'y'
+ ? [0, (angle * 180) / Math.PI, 0]
+ : axis === 'x'
+ ? [(angle * 180) / Math.PI, 0, 0]
+ : [0, 0, (angle * 180) / Math.PI];
+ out.push(
+ createInstance(`${namePrefix}${i}`, source, {
+ position: [rotated.x, rotated.y, rotated.z],
+ rotation: eulerDeg,
+ parent,
+ })
+ );
+ }
+ return out;
+}
+
+/**
+ * Mirror: create one mirrored instance of `source` across the given plane.
+ * Plane is identified by its normal axis ('x' = mirror across YZ plane).
+ *
+ * Uses a negative scale on the mirror axis. Note: negative scale flips
+ * triangle winding — the bridge still exports correctly but lighting on
+ * the mirrored copy may invert until GLB viewers apply the TRS properly.
+ */
+export function mirror(
+ name: string,
+ source: THREE.Object3D,
+ axis: 'x' | 'y' | 'z',
+ parent?: THREE.Object3D
+): THREE.Object3D {
+ const sourcePos = source.position.toArray() as [number, number, number];
+ const pos: [number, number, number] = [
+ axis === 'x' ? -sourcePos[0] : sourcePos[0],
+ axis === 'y' ? -sourcePos[1] : sourcePos[1],
+ axis === 'z' ? -sourcePos[2] : sourcePos[2],
+ ];
+ const scale: [number, number, number] = [
+ axis === 'x' ? -1 : 1,
+ axis === 'y' ? -1 : 1,
+ axis === 'z' ? -1 : 1,
+ ];
+ return createInstance(name, source, { position: pos, scale, parent });
+}
+
+// =============================================================================
+// Mesh ops
+// =============================================================================
+
+/**
+ * Subdivide a geometry using Loop subdivision (via three-subdivide).
+ * Returns a new BufferGeometry; the input is not mutated.
+ *
+ * Higher `iterations` = smoother but exponentially more triangles.
+ * 1 iteration ~= 4x triangle count, 2 ~= 16x. Budget accordingly.
+ *
+ * @example
+ * const smoothRock = subdivide(boxGeo(1, 1, 1), 2);
+ */
+export function subdivide(
+ geometry: THREE.BufferGeometry,
+ iterations = 1,
+ opts: { split?: boolean; uvSmooth?: boolean; preserveEdges?: boolean; flatOnly?: boolean } = {}
+): THREE.BufferGeometry {
+ return LoopSubdivision.modify(geometry, iterations, opts);
+}
+
+// =============================================================================
+// Curve ops
+// =============================================================================
+
+/**
+ * Sweep a circular profile along a path of points to produce a tube mesh.
+ * The simplest "curve to mesh" — matches Blender's Curve to Mesh node when
+ * the profile is a circle.
+ *
+ * @param points — array of [x, y, z] waypoints defining the path
+ * @param radius — tube radius
+ * @param tubularSegments — segments along the path (default 32)
+ * @param radialSegments — segments around the tube (default 8)
+ * @param closed — loop the path back to start (default false)
+ *
+ * @example
+ * const pipeGeo = curveToMesh([[0,0,0], [0,1,0], [1,1,0], [1,2,0]], 0.1);
+ */
+export function curveToMesh(
+ points: Array<[number, number, number]>,
+ radius: number,
+ tubularSegments = 32,
+ radialSegments = 8,
+ closed = false
+): THREE.BufferGeometry {
+ const vectors = points.map((p) => new THREE.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE.CatmullRomCurve3(vectors, closed);
+ return new THREE.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+}
+
+/**
+ * Construct a lathe (surface of revolution) by spinning a 2D profile
+ * around the Y axis. Classic for bottles, vases, wheels, turned wood.
+ *
+ * @param profile — array of [x, y] points; x is radial distance, y is height
+ * @param segments — radial segments (default 12)
+ */
+export function lathe(
+ profile: Array<[number, number]>,
+ segments = 12
+): THREE.BufferGeometry {
+ const points2d = profile.map((p) => new THREE.Vector2(p[0], p[1]));
+ return new THREE.LatheGeometry(points2d, segments);
+}
+
+/**
+ * Quadratic or cubic Bézier curve sampled into a point list for curveToMesh.
+ * 3 points = quadratic, 4 points = cubic.
+ *
+ * @example
+ * const path = bezierCurve([[0,0,0], [1,2,0], [3,2,0], [4,0,0]], 24);
+ * const geo = curveToMesh(path, 0.1);
+ */
+export function bezierCurve(
+ controlPoints: Array<[number, number, number]>,
+ samples = 32
+): Array<[number, number, number]> {
+ const vecs = controlPoints.map((p) => new THREE.Vector3(p[0], p[1], p[2]));
+ let curve: THREE.Curve<THREE.Vector3>;
+ if (vecs.length === 3) {
+ curve = new THREE.QuadraticBezierCurve3(vecs[0]!, vecs[1]!, vecs[2]!);
+ } else if (vecs.length === 4) {
+ curve = new THREE.CubicBezierCurve3(vecs[0]!, vecs[1]!, vecs[2]!, vecs[3]!);
+ } else {
+ throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);
+ }
+ return curve.getPoints(samples).map((v) => [v.x, v.y, v.z] as [number, number, number]);
+}
diff --git a/primitives.ts b/primitives.ts
index c15b7799..ea2992d4 100644
--- a/primitives.ts
+++ b/primitives.ts
@@ -211,9 +211,21 @@ export function lambertMaterial(
// Animation Helpers
// =============================================================================
+/**
+ * Keyframe interpolation mode.
+ * - LINEAR: default, smooth transitions between keyframes.
+ * - STEP: discrete, hold value until next keyframe (good for robotic/mechanical motion).
+ */
+export type TrackInterpolation = 'LINEAR' | 'STEP';
+
+function threeInterpolation(mode?: TrackInterpolation): THREE.InterpolationModes {
+ return mode === 'STEP' ? THREE.InterpolateDiscrete : THREE.InterpolateLinear;
+}
+
export function rotationTrack(
jointName: string,
- keyframes: Array<{ time: number; rotation: [number, number, number] }>
+ keyframes: Array<{ time: number; rotation: [number, number, number] }>,
+ interpolation?: TrackInterpolation
): THREE.QuaternionKeyframeTrack {
const times: number[] = [];
const values: number[] = [];
@@ -234,13 +246,15 @@ export function rotationTrack(
return new THREE.QuaternionKeyframeTrack(
`${jointName}.quaternion`,
times,
- values
+ values,
+ threeInterpolation(interpolation)
);
}
export function positionTrack(
jointName: string,
- keyframes: Array<{ time: number; position: [number, number, number] }>
+ keyframes: Array<{ time: number; position: [number, number, number] }>,
+ interpolation?: TrackInterpolation
): THREE.VectorKeyframeTrack {
const times: number[] = [];
const values: number[] = [];
@@ -253,13 +267,15 @@ export function positionTrack(
return new THREE.VectorKeyframeTrack(
`${jointName}.position`,
times,
- values
+ values,
+ threeInterpolation(interpolation)
);
}
export function scaleTrack(
jointName: string,
- keyframes: Array<{ time: number; scale: [number, number, number] }>
+ keyframes: Array<{ time: number; scale: [number, number, number] }>,
+ interpolation?: TrackInterpolation
): THREE.VectorKeyframeTrack {
const times: number[] = [];
const values: number[] = [];
@@ -269,7 +285,12 @@ export function scaleTrack(
values.push(...kf.scale);
}
- return new THREE.VectorKeyframeTrack(`${jointName}.scale`, times, values);
+ return new THREE.VectorKeyframeTrack(
+ `${jointName}.scale`,
+ times,
+ values,
+ threeInterpolation(interpolation)
+ );
}
export function createClip(
@@ -336,6 +357,81 @@ export function spinAnimation(
// Utilities
// =============================================================================
+// =============================================================================
+// Instancing / Reuse (Wave 1B)
+// =============================================================================
+
+/**
+ * Returns the same BufferGeometry reference — explicit no-op clone that
+ * signals intent to reuse geometry across multiple parts. gltf-transform
+ * will dedupe on export, but authoring with the shared ref keeps memory
+ * low at render time too.
+ *
+ * For 4 wheels on a truck: build one `cylinderGeo(...)`, pass it through
+ * `cloneGeometry` to each `createPart` call. Four meshes, one geometry.
+ */
+export function cloneGeometry(geo: THREE.BufferGeometry): THREE.BufferGeometry {
+ return geo;
+}
+
+/**
+ * Shared material reference. See `cloneGeometry` for the pattern.
+ */
+export function cloneMaterial(mat: THREE.Material): THREE.Material {
+ return mat;
+}
+
+/**
+ * Creates a new Object3D that reuses an existing part's geometry+material
+ * at a new transform. The cheapest way to replicate a part (wheel, bolt,
+ * window, fence-post) without duplicating GPU-side data.
+ *
+ * If `source` is a pivot (from `createPivot` or `createPart` with
+ * `pivot: true`), the instance replicates the first Mesh child's geometry.
+ *
+ * Automatically adds to `parent` when provided (mirrors createPart).
+ */
+export function createInstance(
+ name: string,
+ source: THREE.Object3D,
+ options: {
+ position?: [number, number, number];
+ rotation?: [number, number, number];
+ scale?: [number, number, number];
+ parent?: THREE.Object3D;
+ } = {}
+): THREE.Object3D {
+ const sourceMesh =
+ source instanceof THREE.Mesh
+ ? source
+ : (source.children.find((c) => c instanceof THREE.Mesh) as THREE.Mesh | undefined);
+
+ if (!sourceMesh) {
+ throw new Error(
+ `createInstance("${name}"): source "${source.name}" has no Mesh to clone from`
+ );
+ }
+
+ const mesh = new THREE.Mesh(sourceMesh.geometry, sourceMesh.material);
+ mesh.name = `Mesh_${name}`;
+
+ if (options.position) mesh.position.set(...options.position);
+ if (options.rotation)
+ mesh.rotation.set(
+ THREE.MathUtils.degToRad(options.rotation[0]),
+ THREE.MathUtils.degToRad(options.rotation[1]),
+ THREE.MathUtils.degToRad(options.rotation[2])
+ );
+ if (options.scale) mesh.scale.set(...options.scale);
+
+ if (options.parent) options.parent.add(mesh);
+ return mesh;
+}
+
+// =============================================================================
+// Introspection
+// =============================================================================
+
export function countTriangles(root: THREE.Object3D): number {
let count = 0;
root.traverse((child) => {
@@ -415,13 +511,50 @@ export function validateAsset(
* the LLM expects.
*/
export function buildSandboxGlobals(): Record<string, unknown> {
+ // CSG ops are async — the executor awaits build() so agents can
+ // `await boolDiff(...)` inside build().
+ //
+ // Lazy-required at call-time so the Three.js-only path doesn't pay the
+ // manifold WASM init unless an agent actually uses CSG.
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const solids = require('./solids') as typeof import('./solids');
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const ops = require('./ops') as typeof import('./ops');
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const uv = require('./uv') as typeof import('./uv');
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const textures = require('./textures') as typeof import('./textures');
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const THREE = require('three') as typeof import('three');
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,
+ // CSG (async)
+ boolUnion: solids.boolUnion,
+ boolDiff: solids.boolDiff,
+ boolIntersect: solids.boolIntersect,
+ hull: solids.hull,
+ // Array/mirror/subdivide/curve ops
+ arrayLinear: ops.arrayLinear,
+ arrayRadial: ops.arrayRadial,
+ mirror: ops.mirror,
+ subdivide: ops.subdivide,
+ curveToMesh: ops.curveToMesh,
+ lathe: ops.lathe,
+ bezierCurve: ops.bezierCurve,
+ // UV (async)
+ autoUnwrap: uv.autoUnwrap,
+ // Textures + PBR (loadTexture is async)
+ loadTexture: textures.loadTexture,
+ pbrMaterial: textures.pbrMaterial,
countTriangles, countMaterials, getJointNames, 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,
Math, console,
};
}
diff --git a/prompt.ts b/prompt.ts
index e8b73667..23ccc9e5 100644
--- a/prompt.ts
+++ b/prompt.ts
@@ -73,14 +73,24 @@ CRITICAL: NO import/export statements. Code runs in a sandbox with primitives as
<file-format>
const meta = { name: "AssetName", category: "prop" };
-function build() {
+// build() may be sync OR async. Mark it async if you use any CSG op
+// (boolUnion / boolDiff / boolIntersect / hull) because those await WASM.
+function build() { // simple, no CSG
const root = createRoot("AssetName");
- // Build scene graph with pivots and meshes
return root;
}
-function animate(root) {
- // Return animation clips (optional)
+// OR when using CSG:
+async function build() { // use this form when any await is needed
+ const root = createRoot("AssetName");
+ const body = new THREE.Mesh(boxGeo(1,1,1), steel);
+ const hole = new THREE.Mesh(cylinderGeo(0.2, 0.2, 2, 16), steel);
+ const pierced = await boolDiff("Pierced", body, hole);
+ root.add(pierced);
+ return root;
+}
+
+function animate(root) { // optional
return [clip1, clip2];
}
</file-format>
@@ -89,14 +99,14 @@ function animate(root) {
// Scene (no imports needed - globals)
createRoot(name: string): Object3D
createPivot(name: string, position: [x,y,z], parent: Object3D): Object3D
-createPart(name, geo, mat, opts): void // AUTO-ADDS to parent! Do NOT call .add() on it
+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
+// Geometry (returns BufferGeometry)
boxGeo(width, height, depth)
sphereGeo(radius, widthSegs=8, heightSegs=6)
cylinderGeo(radiusTop, radiusBot, height, segments=8)
@@ -109,10 +119,52 @@ planeGeo(width, height, widthSegs=1, heightSegs=1)
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):
+// 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()\`)
+await boolUnion(name, ...parts) // merge into one watertight mesh
+await boolDiff(name, body, ...cutters) // subtract cutters from body (holes, recesses)
+await boolIntersect(name, a, b) // keep overlapping volume only
+await hull(name, ...parts) // tightest convex hull
+
+// Mesh ops
+subdivide(geometry, iterations=1) // Loop subdivision, returns new BufferGeometry
+
+// Curves
+curveToMesh(points: [x,y,z][], radius, tubularSegs=32, radialSegs=8, closed=false) // returns BufferGeometry (tube)
+lathe(profile: [x,y][], segments=12) // surface of revolution (vase, wheel, bottle)
+bezierCurve(ctrlPts: [x,y,z][], samples=32) // returns [x,y,z][] — feed into curveToMesh
+
+// UV + Textures (both async, require \`async function build()\`)
+await autoUnwrap(geometry, { resolution?: 1024, padding?: 2 }) // returns BufferGeometry with uv attribute
+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
+
+// 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.
// Animation - IMPORTANT: keyframes use "rotation" or "position" keys, NOT "value"
-rotationTrack(jointName: string, keyframes: [{time, rotation: [x,y,z]}]) // rotation in DEGREES
-positionTrack(jointName: string, keyframes: [{time, position: [x,y,z]}])
+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
@@ -159,7 +211,7 @@ RIGHT: { time: 0, rotation: [0,0,0] } for rotationTrack (degrees)
RIGHT: { time: 0, position: [0,0,0] } for positionTrack
</critical-animation-format>
-<example>
+<example name="animated-chest">
const meta = { name: "Chest", category: "prop" };
function build() {
@@ -191,6 +243,83 @@ function animate(root) {
])
])];
}
+</example>
+
+<example name="gear-with-csg">
+// Gear = cylinder body - 8 radially-arrayed cutter boxes - center hole.
+// NOTE: build() is async because boolDiff awaits WASM.
+const meta = { name: "Gear", category: "prop" };
+
+async function build() {
+ const root = createRoot("Gear");
+ const steel = gameMaterial(0xb0b0b0, { metalness: 0.8, roughness: 0.3 });
+
+ // Body disc (not added to root — will be consumed by boolDiff)
+ const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);
+
+ // 8 teeth cutters around the rim, detached from scene
+ const cutters = [];
+ for (let i = 0; i < 8; i++) {
+ const a = (i / 8) * Math.PI * 2;
+ const c = new THREE.Mesh(boxGeo(0.4, 0.4, 0.4), steel);
+ c.position.set(Math.cos(a) * 1.1, 0, Math.sin(a) * 1.1);
+ cutters.push(c);
+ }
+
+ // Center shaft hole
+ const hole = new THREE.Mesh(cylinderGeo(0.25, 0.25, 0.5, 16), steel);
+
+ const gear = await boolDiff("Gear", body, ...cutters, hole);
+ root.add(gear);
+ return root;
+}
+</example>
+
+<example name="textured-crate">
+// A unit-cube crate with a wood albedo texture.
+// autoUnwrap adds UVs so the texture maps cleanly; pbrMaterial wraps the
+// texture into a MeshStandardMaterial that exports as glTF PBR.
+const meta = { name: "Crate", category: "prop" };
+
+async function build() {
+ const root = createRoot("Crate");
+ const wood = await loadTexture('./war-assets/textures/wood-planks.png');
+ const mat = pbrMaterial({ albedo: wood, roughness: 0.88, metalness: 0 });
+ const geo = await autoUnwrap(boxGeo(1, 1, 1), { resolution: 1024 });
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.name = "Mesh_Crate";
+ root.add(mesh);
+ return root;
+}
+</example>
+
+<example name="fence-with-array">
+// Linear + radial arrays share geometry across many instances.
+const meta = { name: "Fence", category: "environment" };
+
+function build() {
+ const root = createRoot("Fence");
+ const wood = gameMaterial(0x8b6f3d, { roughness: 0.9 });
+
+ // One post, then 9 instances along +X (10 posts total, 0.5 apart)
+ const post0 = createPart("Post0", cylinderGeo(0.05, 0.05, 1.2, 6), wood, {
+ position: [0, 0.6, 0],
+ parent: root
+ });
+ arrayLinear("Post", post0, 10, [0.5, 0, 0], root);
+
+ // Two horizontal rails across the length
+ createPart("RailTop", boxGeo(4.6, 0.08, 0.06), wood, {
+ position: [2.25, 0.95, 0],
+ parent: root
+ });
+ createPart("RailBot", boxGeo(4.6, 0.08, 0.06), wood, {
+ position: [2.25, 0.35, 0],
+ parent: root
+ });
+
+ return root;
+}
</example>`;
export const KILN_TSL_SYSTEM_PROMPT = `You are an expert shader artist. Create stunning real-time visual effects using Three.js TSL.
diff --git a/render.ts b/render.ts
index a3b2f505..ccec71bd 100644
--- a/render.ts
+++ b/render.ts
@@ -12,6 +12,7 @@
import * as THREE from 'three';
import { Document, WebIO } from '@gltf-transform/core';
+import { dedup } from '@gltf-transform/functions';
import {
buildSandboxGlobals,
@@ -29,6 +30,7 @@ type GtNode = import('@gltf-transform/core').Node;
type GtMesh = import('@gltf-transform/core').Mesh;
type GtMaterial = import('@gltf-transform/core').Material;
type GtBuffer = import('@gltf-transform/core').Buffer;
+type GtTexture = import('@gltf-transform/core').Texture;
// Accessor.Type is typed as Record<string, AccessorType> which runs afoul of
// noUncheckedIndexedAccess. Use the literal strings directly - same values,
@@ -61,7 +63,15 @@ export interface ExecutedKilnCode {
* Three.js scene plus animation clips. Throws on any runtime error in the
* generated code.
*/
-export function executeKilnCode(code: string): ExecutedKilnCode {
+/**
+ * Execute generated Kiln code and return the built scene + clips.
+ *
+ * Async because CSG primitives (boolUnion, boolDiff, etc.) are WASM-backed
+ * and async. Sync `build()` functions are supported transparently — if the
+ * return value is a Promise it is awaited, otherwise it is used as-is.
+ * Same for `animate()`.
+ */
+export async function executeKilnCode(code: string): Promise<ExecutedKilnCode> {
if (!code || typeof code !== 'string') {
throw new Error('executeKilnCode: code must be a non-empty string');
}
@@ -81,20 +91,25 @@ export function executeKilnCode(code: string): ExecutedKilnCode {
const { meta, build, animate } = fn(...globalValues) as {
meta: KilnCodeMeta;
- build: () => THREE.Object3D;
- animate: ((root: THREE.Object3D) => THREE.AnimationClip[] | undefined) | null;
+ build: () => THREE.Object3D | Promise<THREE.Object3D>;
+ animate:
+ | ((root: THREE.Object3D) =>
+ | THREE.AnimationClip[]
+ | undefined
+ | Promise<THREE.AnimationClip[] | undefined>)
+ | null;
};
if (typeof build !== 'function') {
throw new Error('executeKilnCode: generated code did not define `build`');
}
- const root = build();
+ const root = await build();
if (!(root instanceof THREE.Object3D)) {
throw new Error('executeKilnCode: build() did not return a THREE.Object3D');
}
- const clips = animate ? (animate(root) ?? []) : [];
+ const clips = animate ? ((await animate(root)) ?? []) : [];
return { meta: meta ?? {}, root, clips };
}
@@ -106,7 +121,8 @@ export function executeKilnCode(code: string): ExecutedKilnCode {
function bridgeMaterial(
doc: Document,
threeMat: THREE.Material,
- cache: Map<THREE.Material, GtMaterial>
+ cache: Map<THREE.Material, GtMaterial>,
+ textureCache: Map<THREE.Texture, GtTexture>
): GtMaterial {
const cached = cache.get(threeMat);
if (cached) return cached;
@@ -126,6 +142,32 @@ function bridgeMaterial(
if (threeMat.side === THREE.DoubleSide) {
mat.setDoubleSided(true);
}
+ // PBR texture slots (Wave 3B)
+ if (threeMat.map) {
+ const t = bridgeTexture(doc, threeMat.map, textureCache);
+ if (t) mat.setBaseColorTexture(t);
+ }
+ if (threeMat.normalMap) {
+ const t = bridgeTexture(doc, threeMat.normalMap, textureCache);
+ if (t) mat.setNormalTexture(t);
+ }
+ // metallic + roughness live in one glTF texture (R=unused, G=rough, B=metal).
+ // If the agent used separate Three.js maps we emit the roughness one as
+ // the combined channel — the common case is a single combined map anyway.
+ const mrSource = threeMat.roughnessMap ?? threeMat.metalnessMap;
+ if (mrSource) {
+ const t = bridgeTexture(doc, mrSource, textureCache);
+ if (t) mat.setMetallicRoughnessTexture(t);
+ }
+ if (threeMat.emissiveMap) {
+ const t = bridgeTexture(doc, threeMat.emissiveMap, textureCache);
+ if (t) mat.setEmissiveTexture(t);
+ }
+ if (threeMat.aoMap) {
+ const t = bridgeTexture(doc, threeMat.aoMap, textureCache);
+ if (t) mat.setOcclusionTexture(t);
+ mat.setOcclusionStrength(threeMat.aoMapIntensity ?? 1);
+ }
} else if (threeMat instanceof THREE.MeshLambertMaterial) {
mat.setBaseColorFactor([threeMat.color.r, threeMat.color.g, threeMat.color.b, threeMat.opacity]);
mat.setRoughnessFactor(1.0);
@@ -143,6 +185,34 @@ function bridgeMaterial(
return mat;
}
+/**
+ * Bridge a Three.js Texture to a gltf-transform Texture.
+ *
+ * Prefers `userData.encoded` (raw PNG/JPG bytes from loadTexture) so we
+ * don't re-encode. Falls back to null if nothing is encoded — procedural
+ * DataTextures without encoded bytes aren't exportable yet (requires
+ * runtime PNG encoding, which we'll wire in Wave 3D via sharp).
+ */
+function bridgeTexture(
+ doc: Document,
+ threeTex: THREE.Texture,
+ cache: Map<THREE.Texture, GtTexture>
+): GtTexture | null {
+ const cached = cache.get(threeTex);
+ if (cached) return cached;
+
+ const encoded = (threeTex.userData as Record<string, unknown>)['encoded'] as
+ | { mime: string; bytes: Uint8Array }
+ | undefined;
+ if (!encoded) return null;
+
+ const t = doc.createTexture(threeTex.name || 'texture');
+ t.setMimeType(encoded.mime);
+ t.setImage(encoded.bytes);
+ cache.set(threeTex, t);
+ return t;
+}
+
function bridgeGeometry(
doc: Document,
buf: GtBuffer,
@@ -207,7 +277,9 @@ function bridgeNode(
buf: GtBuffer,
threeObj: THREE.Object3D,
matCache: Map<THREE.Material, GtMaterial>,
- nodeMap: Map<string, GtNode>
+ nodeMap: Map<string, GtNode>,
+ meshCache: Map<string, GtMesh>,
+ texCache: Map<THREE.Texture, GtTexture>
): GtNode {
const gtNode = doc.createNode(threeObj.name || undefined);
@@ -222,8 +294,18 @@ function bridgeNode(
if (threeObj instanceof THREE.Mesh) {
const threeMat = threeObj.material as THREE.Material;
- const gtMat = bridgeMaterial(doc, threeMat, matCache);
- const gtMesh = bridgeGeometry(doc, buf, threeObj.geometry, gtMat, threeObj.name || 'mesh');
+ const gtMat = bridgeMaterial(doc, threeMat, matCache, texCache);
+
+ // Key the mesh cache by (geometry ref, material ref) so createInstance
+ // (same geo + mat as source) produces a GLB-level mesh instance: a
+ // single Mesh referenced by multiple Nodes. Cuts duplicated accessors
+ // for wheels, bolts, fence posts, etc.
+ const cacheKey = `${(threeObj.geometry as any).uuid}__${(threeMat as any).uuid}`;
+ let gtMesh = meshCache.get(cacheKey);
+ if (!gtMesh) {
+ gtMesh = bridgeGeometry(doc, buf, threeObj.geometry, gtMat, threeObj.name || 'mesh');
+ meshCache.set(cacheKey, gtMesh);
+ }
gtNode.setMesh(gtMesh);
}
@@ -232,7 +314,7 @@ function bridgeNode(
}
for (const child of threeObj.children) {
- const childNode = bridgeNode(doc, buf, child, matCache, nodeMap);
+ const childNode = bridgeNode(doc, buf, child, matCache, nodeMap, meshCache, texCache);
gtNode.addChild(childNode);
}
@@ -325,6 +407,11 @@ export interface RenderSceneOptions {
sceneName?: string;
/** Animation clips to bridge into the document. */
clips?: THREE.AnimationClip[];
+ /**
+ * Run gltf-transform dedup() before serializing. Default true. Set false
+ * to inspect raw bridge output for debugging.
+ */
+ dedup?: boolean;
}
/**
@@ -361,15 +448,28 @@ export async function renderSceneToGLB(
const doc = new Document();
const buf = doc.createBuffer();
const matCache = new Map<THREE.Material, GtMaterial>();
+ const meshCache = new Map<string, GtMesh>();
+ const texCache = new Map<THREE.Texture, GtTexture>();
const nodeMap = new Map<string, GtNode>();
- const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap);
+ const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
doc.createScene(opts.sceneName ?? 'Scene').addChild(rootNode);
if (clips.length > 0) {
bridgeAnimations(doc, buf, clips, nodeMap, warnings);
}
+ // Dedupe accessors/materials/meshes so instanced parts (4 wheels, 10 posts,
+ // 12 windows) share a single underlying resource in the GLB. Cuts file
+ // size on instancing-heavy assets; no-op on unique-geometry scenes.
+ if (opts.dedup !== false) {
+ try {
+ await doc.transform(dedup());
+ } catch (err) {
+ warnings.push(`dedup transform failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+
const io = new WebIO();
const bytes = await io.writeBinary(doc);
@@ -386,7 +486,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 } = executeKilnCode(code);
+ const { meta, root, clips } = await executeKilnCode(code);
const scene = await renderSceneToGLB(root, {
sceneName: meta.name || 'Scene',
clips,
diff --git a/solids.ts b/solids.ts
new file mode 100644
index 00000000..fc82249f
--- /dev/null
+++ b/solids.ts
@@ -0,0 +1,234 @@
+/**
+ * Kiln CSG primitives — manifold-3d wrapper
+ *
+ * Boolean operations (union / diff / intersect) and convex hull for the
+ * Kiln primitive set, backed by Google's manifold-3d WASM library. The
+ * library guarantees topologically-manifold output which matters for GLB
+ * integrity (non-manifold geometry breaks many downstream tools).
+ *
+ * These primitives bridge Three.js BufferGeometry <-> Manifold Mesh.
+ * Operations are synchronous once the WASM module is loaded (first call
+ * pays the ~100ms init cost; subsequent calls are fast).
+ *
+ * Agents use these to:
+ * - carve holes: boolDiff(body, cutter)
+ * - merge parts: boolUnion(a, b, c)
+ * - keep overlap: boolIntersect(a, b)
+ * - wrap loosely: hull(parts)
+ *
+ * Limitations:
+ * - Input geometry should be watertight / manifold. sphereGeo's polar
+ * singularity can produce degenerate triangles that manifold trims.
+ * - Only position data survives — normals and UVs are regenerated.
+ * - Material is inherited from the first operand.
+ */
+
+import * as THREE from 'three';
+
+// eslint-disable-next-line @typescript-eslint/consistent-type-imports
+import type { ManifoldToplevel, Manifold, Mesh } from 'manifold-3d';
+
+// Lazy-init singleton. First call to any CSG op awaits init; subsequent
+// calls are O(bridge cost) only.
+let _module: ManifoldToplevel | null = null;
+let _initPromise: Promise<ManifoldToplevel> | null = null;
+
+async function getManifoldModule(): Promise<ManifoldToplevel> {
+ if (_module) return _module;
+ if (_initPromise) return _initPromise;
+
+ _initPromise = (async () => {
+ const mod = (await import('manifold-3d')) as unknown as {
+ default: (opts?: Record<string, unknown>) => Promise<ManifoldToplevel>;
+ };
+ const m = await mod.default();
+ m.setup();
+ _module = m;
+ return m;
+ })();
+
+ return _initPromise;
+}
+
+/**
+ * Convert a Three.js Mesh/Object3D to a Manifold Mesh (world-space).
+ * Flattens any scene subtree into a single merged manifold.
+ */
+function threeToManifold(src: THREE.Object3D, ManifoldCls: typeof Manifold, MeshCls: typeof Mesh): Manifold {
+ src.updateMatrixWorld(true);
+
+ const positions: number[] = [];
+ const indices: number[] = [];
+
+ const tmpVec = new THREE.Vector3();
+ let vertexOffset = 0;
+
+ src.traverse((child) => {
+ if (!(child instanceof THREE.Mesh)) return;
+ const geo = child.geometry as THREE.BufferGeometry;
+ const posAttr = geo.getAttribute('position') as THREE.BufferAttribute | undefined;
+ if (!posAttr) return;
+
+ const matrix = child.matrixWorld;
+
+ for (let i = 0; i < posAttr.count; i++) {
+ tmpVec.fromBufferAttribute(posAttr, i).applyMatrix4(matrix);
+ positions.push(tmpVec.x, tmpVec.y, tmpVec.z);
+ }
+
+ const idx = geo.getIndex();
+ if (idx) {
+ for (let i = 0; i < idx.count; i++) {
+ indices.push((idx.getX(i) as number) + vertexOffset);
+ }
+ } else {
+ // Non-indexed: generate sequential triangles
+ for (let i = 0; i < posAttr.count; i++) {
+ indices.push(i + vertexOffset);
+ }
+ }
+
+ vertexOffset += posAttr.count;
+ });
+
+ const mesh = new MeshCls({
+ numProp: 3,
+ vertProperties: new Float32Array(positions),
+ triVerts: new Uint32Array(indices),
+ });
+ mesh.merge();
+
+ return ManifoldCls.ofMesh(mesh);
+}
+
+/**
+ * Convert a Manifold result back to a Three.js Mesh with the given material.
+ * Regenerates vertex normals (flat shading by default).
+ */
+function manifoldToThree(m: Manifold, material: THREE.Material, name: string): THREE.Mesh {
+ const mesh = m.getMesh();
+ const numProp = mesh.numProp;
+ const verts = mesh.vertProperties;
+ const tris = mesh.triVerts;
+
+ // Extract xyz from interleaved vertProperties
+ const positions = new Float32Array((verts.length / numProp) * 3);
+ for (let i = 0, o = 0; i < verts.length; i += numProp, o += 3) {
+ positions[o] = verts[i] as number;
+ positions[o + 1] = verts[i + 1] as number;
+ positions[o + 2] = verts[i + 2] as number;
+ }
+
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
+ geo.setIndex(new THREE.BufferAttribute(new Uint32Array(tris), 1));
+ geo.computeVertexNormals();
+
+ const out = new THREE.Mesh(geo, material);
+ out.name = name;
+ return out;
+}
+
+function materialOf(src: THREE.Object3D, fallback: THREE.Material): THREE.Material {
+ if (src instanceof THREE.Mesh) return src.material as THREE.Material;
+ let found: THREE.Material | null = null;
+ src.traverse((c) => {
+ if (!found && c instanceof THREE.Mesh) found = c.material as THREE.Material;
+ });
+ return found ?? fallback;
+}
+
+// =============================================================================
+// Public primitives
+// =============================================================================
+
+/**
+ * Boolean union: combine two or more parts into one watertight mesh.
+ * Inherits material from the first operand.
+ *
+ * @example
+ * const merged = await boolUnion('Hull', body, turret, barrel);
+ */
+export async function boolUnion(name: string, ...parts: THREE.Object3D[]): Promise<THREE.Mesh> {
+ if (parts.length < 2) {
+ throw new Error('boolUnion requires at least two parts');
+ }
+ const mod = await getManifoldModule();
+ const manifolds = parts.map((p) => threeToManifold(p, mod.Manifold, mod.Mesh));
+ const result = mod.Manifold.union(manifolds);
+ const mat = materialOf(parts[0]!, new THREE.MeshStandardMaterial());
+ const mesh = manifoldToThree(result, mat, `Mesh_${name}`);
+ manifolds.forEach((m) => m.delete());
+ result.delete();
+ return mesh;
+}
+
+/**
+ * Boolean difference: subtract `cutter` parts from `body`.
+ * Use to carve windows, buttons, grip panels, bolt holes.
+ *
+ * @example
+ * const gear = await boolDiff('Gear', cylinder, ...teethCutters);
+ */
+export async function boolDiff(
+ name: string,
+ body: THREE.Object3D,
+ ...cutters: THREE.Object3D[]
+): Promise<THREE.Mesh> {
+ if (cutters.length < 1) {
+ throw new Error('boolDiff requires at least one cutter');
+ }
+ const mod = await getManifoldModule();
+ const bodyM = threeToManifold(body, mod.Manifold, mod.Mesh);
+ const cutterM = cutters.map((c) => threeToManifold(c, mod.Manifold, mod.Mesh));
+ const cutterUnion =
+ cutterM.length === 1 ? (cutterM[0] as Manifold) : mod.Manifold.union(cutterM);
+ const result = bodyM.subtract(cutterUnion);
+ const mat = materialOf(body, new THREE.MeshStandardMaterial());
+ const mesh = manifoldToThree(result, mat, `Mesh_${name}`);
+ bodyM.delete();
+ cutterM.forEach((m) => m.delete());
+ if (cutterM.length > 1) cutterUnion.delete();
+ result.delete();
+ return mesh;
+}
+
+/**
+ * Boolean intersection: keep only the overlapping volume.
+ * Less commonly used in game assets, but handy for complex trim cuts.
+ */
+export async function boolIntersect(
+ name: string,
+ a: THREE.Object3D,
+ b: THREE.Object3D
+): Promise<THREE.Mesh> {
+ const mod = await getManifoldModule();
+ const aM = threeToManifold(a, mod.Manifold, mod.Mesh);
+ const bM = threeToManifold(b, mod.Manifold, mod.Mesh);
+ const result = aM.intersect(bM);
+ const mat = materialOf(a, new THREE.MeshStandardMaterial());
+ const mesh = manifoldToThree(result, mat, `Mesh_${name}`);
+ aM.delete();
+ bM.delete();
+ result.delete();
+ return mesh;
+}
+
+/**
+ * Convex hull: tightest convex mesh enclosing all points of the inputs.
+ * Good for simplifying collision volumes or wrapping a cluster of parts.
+ */
+export async function hull(name: string, ...parts: THREE.Object3D[]): Promise<THREE.Mesh> {
+ if (parts.length < 1) {
+ throw new Error('hull requires at least one part');
+ }
+ const mod = await getManifoldModule();
+ const manifolds = parts.map((p) => threeToManifold(p, mod.Manifold, mod.Mesh));
+ const result =
+ manifolds.length === 1 ? (manifolds[0] as Manifold).hull() : mod.Manifold.hull(manifolds);
+ const mat = materialOf(parts[0]!, new THREE.MeshStandardMaterial());
+ const mesh = manifoldToThree(result, mat, `Mesh_${name}`);
+ manifolds.forEach((m) => m.delete());
+ if (manifolds.length > 1) result.delete();
+ return mesh;
+}
diff --git a/textures.ts b/textures.ts
new file mode 100644
index 00000000..8a03c637
--- /dev/null
+++ b/textures.ts
@@ -0,0 +1,184 @@
+/**
+ * Kiln texture loading + PBR material — Wave 3B
+ *
+ * Loads image files (PNG/JPG/WebP) into Three.js Textures suitable for
+ * MeshStandardMaterial slots (albedo / normal / roughness / metalness /
+ * emissive). Works in Node via sharp (already a dep); the original
+ * encoded bytes are stashed on `texture.userData.encoded` so the GLB
+ * bridge can re-serialize without re-encoding.
+ */
+
+import * as THREE from 'three';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import sharp from 'sharp';
+
+export type TextureSource = string | Buffer | Uint8Array;
+
+export interface EncodedTextureData {
+ mime: 'image/png' | 'image/jpeg' | 'image/webp';
+ bytes: Uint8Array;
+}
+
+/**
+ * Load an image into a Three.js Texture. Accepts a file path, a Buffer,
+ * or a Uint8Array of encoded bytes.
+ *
+ * The returned texture has:
+ * - a decoded RGBA DataTexture (for runtime preview in the editor)
+ * - `userData.encoded = { mime, bytes }` — original encoded bytes, used
+ * by the GLB bridge so we don't re-encode PNG on every export.
+ *
+ * @example
+ * const wood = await loadTexture('./textures/oak-albedo.png');
+ * const barrel = new THREE.Mesh(unwrapped, pbrMaterial({ albedo: wood }));
+ */
+export async function loadTexture(source: TextureSource): Promise<THREE.DataTexture> {
+ let bytes: Uint8Array;
+ if (typeof source === 'string') {
+ const abs = path.isAbsolute(source) ? source : path.resolve(source);
+ bytes = new Uint8Array(readFileSync(abs));
+ } else if (Buffer.isBuffer(source)) {
+ bytes = new Uint8Array(source);
+ } else {
+ bytes = source;
+ }
+
+ const mime = sniffMime(bytes);
+
+ // Decode to RGBA via sharp so we have a live Texture for editor preview
+ // and for any client-side work (projection baking, normal-map inspect).
+ const img = sharp(bytes);
+ const meta = await img.metadata();
+ const { data } = await img
+ .ensureAlpha()
+ .raw({ depth: 'uchar' })
+ .toBuffer({ resolveWithObject: true });
+
+ if (!meta.width || !meta.height) {
+ throw new Error('loadTexture: could not read image dimensions');
+ }
+
+ const tex = new THREE.DataTexture(
+ new Uint8Array(data),
+ meta.width,
+ meta.height,
+ THREE.RGBAFormat,
+ THREE.UnsignedByteType
+ );
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.needsUpdate = true;
+ tex.wrapS = THREE.RepeatWrapping;
+ tex.wrapT = THREE.RepeatWrapping;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.generateMipmaps = true;
+
+ (tex.userData as Record<string, unknown>)['encoded'] = {
+ mime,
+ bytes,
+ } satisfies EncodedTextureData;
+
+ return tex;
+}
+
+function sniffMime(bytes: Uint8Array): EncodedTextureData['mime'] {
+ // PNG magic: 89 50 4E 47
+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {
+ return 'image/png';
+ }
+ // JPEG magic: FF D8 FF
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
+ return 'image/jpeg';
+ }
+ // WebP magic: "RIFF????WEBP"
+ if (
+ bytes[0] === 0x52 &&
+ bytes[1] === 0x49 &&
+ bytes[2] === 0x46 &&
+ bytes[3] === 0x46 &&
+ bytes[8] === 0x57 &&
+ bytes[9] === 0x45 &&
+ bytes[10] === 0x42 &&
+ bytes[11] === 0x50
+ ) {
+ return 'image/webp';
+ }
+ // Default to PNG — safe for sharp to re-encode if ever needed.
+ return 'image/png';
+}
+
+// =============================================================================
+// PBR material primitive
+// =============================================================================
+
+export interface PbrMaterialOptions {
+ /** Base color — either a hex color or a Texture (albedo map). */
+ albedo?: number | string | THREE.Texture;
+ /** Normal map Texture. */
+ normal?: THREE.Texture;
+ /** Roughness: scalar [0,1] or Texture (R channel). */
+ roughness?: number | THREE.Texture;
+ /** Metalness: scalar [0,1] or Texture (R channel). */
+ metalness?: number | THREE.Texture;
+ /** Emissive: hex color or Texture. */
+ emissive?: number | string | THREE.Texture;
+ /** Emissive intensity multiplier. */
+ emissiveIntensity?: number;
+ /** Ambient occlusion map Texture (R channel). */
+ aoMap?: THREE.Texture;
+ /** AO intensity [0,1]. Default 1. */
+ aoMapIntensity?: number;
+}
+
+/**
+ * Full PBR material. Any of the slots can be a Texture or a scalar/color.
+ * Maps to MeshStandardMaterial and exports as glTF pbrMetallicRoughness.
+ *
+ * @example
+ * const wood = await loadTexture('./textures/oak-albedo.png');
+ * const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });
+ */
+export function pbrMaterial(opts: PbrMaterialOptions = {}): THREE.MeshStandardMaterial {
+ const mat = new THREE.MeshStandardMaterial();
+
+ if (opts.albedo instanceof THREE.Texture) {
+ mat.map = opts.albedo;
+ mat.color = new THREE.Color(0xffffff);
+ } else if (opts.albedo !== undefined) {
+ mat.color = new THREE.Color(opts.albedo);
+ }
+
+ if (opts.normal) mat.normalMap = opts.normal;
+
+ if (opts.roughness instanceof THREE.Texture) {
+ mat.roughnessMap = opts.roughness;
+ mat.roughness = 1;
+ } else if (opts.roughness !== undefined) {
+ mat.roughness = opts.roughness;
+ } else {
+ mat.roughness = 0.8;
+ }
+
+ if (opts.metalness instanceof THREE.Texture) {
+ mat.metalnessMap = opts.metalness;
+ mat.metalness = 1;
+ } else if (opts.metalness !== undefined) {
+ mat.metalness = opts.metalness;
+ }
+
+ if (opts.emissive instanceof THREE.Texture) {
+ mat.emissiveMap = opts.emissive;
+ mat.emissive = new THREE.Color(0xffffff);
+ } else if (opts.emissive !== undefined) {
+ mat.emissive = new THREE.Color(opts.emissive);
+ }
+ if (opts.emissiveIntensity !== undefined) {
+ mat.emissiveIntensity = opts.emissiveIntensity;
+ }
+
+ if (opts.aoMap) mat.aoMap = opts.aoMap;
+ if (opts.aoMapIntensity !== undefined) mat.aoMapIntensity = opts.aoMapIntensity;
+
+ return mat;
+}
diff --git a/uv.ts b/uv.ts
new file mode 100644
index 00000000..aa79d139
--- /dev/null
+++ b/uv.ts
@@ -0,0 +1,204 @@
+/// <reference path="./xatlasjs-shims.d.ts" />
+/**
+ * Kiln UV unwrapping — Wave 3A
+ *
+ * Auto-generates UV coordinates for an arbitrary BufferGeometry using
+ * xatlas (Witness engine alum, C++ → WASM via xatlasjs). Output is a new
+ * BufferGeometry — the input is not mutated.
+ *
+ * Why UVs matter for Kiln: once we support textures (Wave 3B+) and
+ * projection painting (Wave 3D), every mesh needs a well-packed UV atlas
+ * or projected textures will overlap / stretch. `autoUnwrap` is the step
+ * that makes our CSG / subdivide / curveToMesh outputs texture-ready.
+ *
+ * Runs headlessly in Node via `xatlasjs/dist/node`. Lazy init so the
+ * WASM isn't paid for in scenes that don't use textures.
+ */
+
+import * as THREE from 'three';
+
+// Lazy xatlas init — pays ~100-200ms on first call, then free.
+let _xatlasReady: Promise<unknown> | null = null;
+
+type XatlasApi = {
+ loaded: boolean;
+ createAtlas(): void;
+ addMesh(
+ indexes: Uint16Array | Uint32Array,
+ vertices: Float32Array,
+ normals: Float32Array | null,
+ coords: Float32Array | null,
+ meshObj: string,
+ useNormals: boolean,
+ useCoords: boolean,
+ scale: number
+ ): { meshId: number } | null;
+ generateAtlas(
+ chartOptions: Record<string, unknown>,
+ packOptions: Record<string, unknown>,
+ destroyMesh: boolean
+ ): {
+ width: number;
+ height: number;
+ atlasCount: number;
+ meshCount: number;
+ meshes: Array<{
+ mesh: string;
+ vertex: {
+ vertices: Float32Array | number[];
+ normals?: Float32Array | number[];
+ coords?: Float32Array | number[];
+ coords1?: Float32Array | number[];
+ };
+ index?: Uint32Array | number[];
+ oldIndexes: Uint32Array | number[];
+ }>;
+ };
+ destroyAtlas(): void;
+};
+
+async function getXatlas(): Promise<XatlasApi> {
+ if (!_xatlasReady) {
+ _xatlasReady = (async () => {
+ // xatlasjs publishes a Node-friendly emscripten build under dist/node.
+ const apiMod = (await import('xatlasjs/dist/node/api.mjs')) as unknown as {
+ Api: (createModule: unknown) => new (
+ onLoad: () => void,
+ locateFile: unknown,
+ onProgress: unknown
+ ) => XatlasApi;
+ };
+ const xatlasMod = (await import('xatlasjs/dist/node/xatlas.js')) as unknown as {
+ default?: unknown;
+ };
+ const create = xatlasMod.default ?? xatlasMod;
+ const ApiCtor = apiMod.Api(create);
+ return new Promise<XatlasApi>((resolve) => {
+ const xa = new ApiCtor(() => resolve(xa), null as never, null as never);
+ });
+ })();
+ }
+ return _xatlasReady as Promise<XatlasApi>;
+}
+
+export interface AutoUnwrapOptions {
+ /** Atlas texture resolution (power-of-2). Default 1024. */
+ resolution?: number;
+ /** Padding between charts in texels. Default 2. */
+ padding?: number;
+ /** Bake surface normals when determining seams. Default false (faster). */
+ useNormals?: boolean;
+}
+
+/**
+ * Generate a UV atlas for a BufferGeometry.
+ *
+ * The output geometry has a fresh `uv` attribute ready for texture
+ * sampling, and (usually) a different vertex count than the input: xatlas
+ * duplicates vertices along UV seams so each shell gets its own chart.
+ *
+ * Returns a *new* BufferGeometry; the input is left untouched.
+ *
+ * @example
+ * const raw = boxGeo(1, 2, 1);
+ * const unwrapped = await autoUnwrap(raw, { resolution: 1024, padding: 2 });
+ * const crate = new THREE.Mesh(unwrapped, woodPBR);
+ */
+export async function autoUnwrap(
+ geometry: THREE.BufferGeometry,
+ opts: AutoUnwrapOptions = {}
+): Promise<THREE.BufferGeometry> {
+ const xa = await getXatlas();
+
+ // xatlas needs an indexed BufferGeometry. Convert if necessary.
+ const src = geometry.index ? geometry : toIndexed(geometry);
+ const posAttr = src.getAttribute('position') as THREE.BufferAttribute | undefined;
+ const normAttr = src.getAttribute('normal') as THREE.BufferAttribute | undefined;
+ const idxAttr = src.getIndex();
+ if (!posAttr || !idxAttr) {
+ throw new Error('autoUnwrap: geometry requires position attribute and an index');
+ }
+
+ xa.createAtlas();
+
+ const useNormals = Boolean(opts.useNormals && normAttr);
+ const indexArray =
+ idxAttr.array instanceof Uint32Array
+ ? idxAttr.array
+ : new Uint32Array(idxAttr.array as ArrayLike<number>);
+
+ const addRes = xa.addMesh(
+ indexArray,
+ new Float32Array(posAttr.array),
+ useNormals && normAttr ? new Float32Array(normAttr.array) : null,
+ null,
+ 'kiln-mesh',
+ useNormals,
+ false,
+ 1
+ );
+ if (!addRes) {
+ xa.destroyAtlas();
+ throw new Error('autoUnwrap: xatlas.addMesh failed (non-manifold or degenerate geometry?)');
+ }
+
+ const result = xa.generateAtlas(
+ {},
+ { resolution: opts.resolution ?? 1024, padding: opts.padding ?? 2 },
+ true
+ );
+
+ const mesh = result.meshes[0];
+ if (!mesh) {
+ xa.destroyAtlas();
+ throw new Error('autoUnwrap: xatlas returned no meshes');
+ }
+
+ const out = new THREE.BufferGeometry();
+ out.setAttribute(
+ 'position',
+ new THREE.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3)
+ );
+ if (mesh.vertex.normals) {
+ out.setAttribute(
+ 'normal',
+ new THREE.BufferAttribute(new Float32Array(mesh.vertex.normals), 3)
+ );
+ }
+ if (mesh.vertex.coords1) {
+ out.setAttribute(
+ 'uv',
+ new THREE.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2)
+ );
+ }
+ if (mesh.index) {
+ out.setIndex(new THREE.BufferAttribute(new Uint32Array(mesh.index), 1));
+ }
+
+ // Atlas metadata lives on userData so downstream tools (texture baking,
+ // projection painting) can sample the atlas resolution.
+ out.userData['atlas'] = {
+ width: result.width,
+ height: result.height,
+ atlasCount: result.atlasCount,
+ };
+
+ if (!out.getAttribute('normal')) out.computeVertexNormals();
+
+ xa.destroyAtlas();
+ return out;
+}
+
+/**
+ * Convert a non-indexed BufferGeometry to an indexed one via naive
+ * sequential indexing. Sufficient for xatlas input (it re-indexes anyway
+ * during chart generation).
+ */
+function toIndexed(geo: THREE.BufferGeometry): THREE.BufferGeometry {
+ const posAttr = geo.getAttribute('position') as THREE.BufferAttribute;
+ const indices = new Uint32Array(posAttr.count);
+ for (let i = 0; i < posAttr.count; i++) indices[i] = i;
+ const out = geo.clone();
+ out.setIndex(new THREE.BufferAttribute(indices, 1));
+ return out;
+}
diff --git a/xatlasjs-shims.d.ts b/xatlasjs-shims.d.ts
new file mode 100644
index 00000000..e513f4f0
--- /dev/null
+++ b/xatlasjs-shims.d.ts
@@ -0,0 +1,14 @@
+// Ambient module shims for xatlasjs's Node build — the package ships JS
+// only, so we declare the surface we actually touch in uv.ts.
+declare module 'xatlasjs/dist/node/api.mjs' {
+ export const Api: (createModule: unknown) => new (
+ onLoad: () => void,
+ locateFile: unknown,
+ onProgress: unknown
+ ) => unknown;
+}
+
+declare module 'xatlasjs/dist/node/xatlas.js' {
+ const createXAtlasModule: unknown;
+ export default createXAtlasModule;
+}