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.

chore: adopt Biome 2.5.1 (format + lint baseline)

Matt Kissingerea0a4023daa4
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..ad1bbc84
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,5 @@
+# Normalize line endings to LF for all text; let Git detect text vs binary.
+* text=auto eol=lf
+bun.lock -diff linguist-generated=true
+*.png binary
+*.glb binary
diff --git a/CHANGELOG.md b/CHANGELOG.md
index afa99cda..8548cbb3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,14 +29,28 @@ Initial extraction of the Kiln 3D engine from `pixel-forge/packages/core/src/kil
- `xatlasjs` — UV atlas in `autoUnwrap` (`await import('xatlasjs/dist/node/...')`).
### Tests
-- 38 source test files ported. Live agent tests gated behind `KILN_SPIKE_LIVE=1`
- (off in CI). Dropped: the 6 OUT-module test suites, `deps-smoke` (old dep set), and
- `spike`/`top-level-generate` (tested the deleted barrel `generate()` wrapper).
+- 36 source test files ported (382 pass / 2 skip / 0 fail offline). Live agent tests
+ gated behind `KILN_SPIKE_LIVE=1` (off in CI). Dropped: the 6 OUT-module test suites,
+ `deps-smoke` (old dep set), `spike`/`top-level-generate` (tested the deleted barrel
+ `generate()` wrapper), and `companions`/`refactor-validation` (tested the legacy
+ `generate.ts` companion aliases `kiln.editCode`/`kiln.refactor`, also pruned).
+- Provider SDKs (`@anthropic-ai/sdk`, `@google/genai`, `openai`, `ai`,
+ `@aws-sdk/client-bedrock-runtime`) are **devDependencies only** — needed to exercise
+ the multi-provider `makeKilnModel` factory in `providers.test.ts`; they never enter
+ runtime `dependencies`. The kiln-glb skill-drift gate is `skipIf`-guarded (the skill
+ lives outside the engine repo).
+
+### Tooling
+- **Biome 2.5.1** adopted (lint + format). Source formatted to Biome style (single
+ quotes, 2-space, 100-col); `bun run lint` is green. A baseline of 19 stylistic
+ warnings (`noExplicitAny`/`useTemplate`/`useOptionalChain`/`noGlobalIsFinite`/…) is
+ left visible for a hardening pass; `noNonNullAssertion`/`useLiteralKeys` are off and
+ `useIterableCallbackReturn` is warn (all idiomatic in the extracted code).
### Follow-ups (deliberately deferred from WS0 — see ../plan/03-standards-harness.md)
+- Burn down the 19 Biome warnings + re-promote `useIterableCallbackReturn` to error.
- Tighten `tsconfig` (`exactOptionalPropertyTypes`); currently mirrors pixel-forge core
for a zero-drift green typecheck.
-- Add Biome lint config.
- Consider `tsup` `dist` build + Vitest golden-image render harness (engine ships TS
source today for drop-in parity with how Studio consumes core).
- Rename the live-test gate `KILN_SPIKE_LIVE` → `KILN_LIVE`.
diff --git a/biome.json b/biome.json
new file mode 100644
index 00000000..fba75b7c
--- /dev/null
+++ b/biome.json
@@ -0,0 +1,28 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.5.1/schema.json",
+ "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
+ "files": { "includes": ["src/**/*.ts"] },
+ "formatter": {
+ "enabled": true,
+ "indentStyle": "space",
+ "indentWidth": 2,
+ "lineWidth": 100
+ },
+ "javascript": {
+ "formatter": {
+ "quoteStyle": "single",
+ "semicolons": "always",
+ "trailingCommas": "all"
+ }
+ },
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true,
+ "style": { "noNonNullAssertion": "off" },
+ "complexity": { "useLiteralKeys": "off" },
+ "suspicious": { "useIterableCallbackReturn": "warn" }
+ }
+ },
+ "assist": { "enabled": false }
+}
diff --git a/bun.lock b/bun.lock
index dc80ec47..7a523a98 100644
--- a/bun.lock
+++ b/bun.lock
@@ -22,6 +22,7 @@
"@ai-sdk/provider": "^3.0.10",
"@anthropic-ai/sdk": "^0.104.1",
"@aws-sdk/client-bedrock-runtime": "^3.1075.0",
+ "@biomejs/biome": "^2.5.1",
"@google/genai": "^2.8.0",
"@strands-agents/sdk": "^1.4.0",
"@types/bun": "^1.3.14",
@@ -100,6 +101,24 @@
"@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],
+ "@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.1", "@biomejs/cli-darwin-x64": "2.5.1", "@biomejs/cli-linux-arm64": "2.5.1", "@biomejs/cli-linux-arm64-musl": "2.5.1", "@biomejs/cli-linux-x64": "2.5.1", "@biomejs/cli-linux-x64-musl": "2.5.1", "@biomejs/cli-win32-arm64": "2.5.1", "@biomejs/cli-win32-x64": "2.5.1" }, "bin": { "biome": "bin/biome" } }, "sha512-IXWLCxKmae+rI7LOHS1B3EbVisQ6GRAWbhN9msa6KjNCyFWrvKZWR4oUdinaNssrV852OrSHuSPa95h1GPJc7Q=="],
+
+ "@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-npqDzvqv7vFaWRiNN1Te71siRgPaqS9MpqgYCdP/CrUbkJ7ApezaeaKjueKHRN/JH/6lRjJQAHi8acQDCAz22w=="],
+
+ "@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-RgwTqPAM8g2tn1j+b5oRjF/DbSBX8a4gwojtuG9XuhfK7GgomvZ9+T+tqjXiVbjLEeGJOoL6VEk8mvRTVeSybw=="],
+
+ "@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-yhV35CzZh38VyMvTEXi3JTjxZBs++oCKK9KG8vB6VI5+uvQvZNR3BFWEKKzuOmx9DJJj7sQpZ4LQJcmbGTs3+Q=="],
+
+ "@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-WMcvMLgByyTqVxGlq918NBBYliq9FRR9GAQVETHb+VjGVqXCZFfHlZHC1FX4ibuYY/Hg6TJE3rHU0xVrdJXNRw=="],
+
+ "@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-J/7uHSX7NfoYDI7HijAkd8lnQIOrRb2W7j3X+tw4R+N5ExvXGsyXFiGdQcfcxfOmNQmZVSQOCDk757fwpzqQcg=="],
+
+ "@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-ANTowtlLmPYm5yeMckWY8Xzb9Ix+JJP3tgHR/n6xRj1VWyIzzWtfRfih9hv9VmClwadpBvZduISZIbBsIlYG3A=="],
+
+ "@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-zgXnKNgWPC4iPF7Y1lR3STUeCUuZRpD6IiOrC7TZTlh0Lx6FiVUT05myuMQHQ9D+1cc7uyMldi4forE6lp0ivQ=="],
+
+ "@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-6uxpR9hvaglANkZemeSiN/FhYgkGasrEGn267eXIWvjrjJ2LhDlk251IhjVJq6MXzkV2/bcXwLwSroLyPtqRZg=="],
+
"@dimforge/rapier3d-compat": ["@dimforge/[email protected]", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],
"@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="],
diff --git a/package.json b/package.json
index e7bd6f12..ac0c8a8f 100644
--- a/package.json
+++ b/package.json
@@ -65,6 +65,7 @@
"@ai-sdk/provider": "^3.0.10",
"@anthropic-ai/sdk": "^0.104.1",
"@aws-sdk/client-bedrock-runtime": "^3.1075.0",
+ "@biomejs/biome": "^2.5.1",
"@google/genai": "^2.8.0",
"@strands-agents/sdk": "^1.4.0",
"@types/bun": "^1.3.14",
diff --git a/src/__tests__/billboard-primitives.test.ts b/src/__tests__/billboard-primitives.test.ts
index 6e92e1ad..326dd7a1 100644
--- a/src/__tests__/billboard-primitives.test.ts
+++ b/src/__tests__/billboard-primitives.test.ts
@@ -3,13 +3,9 @@
*/
import { describe, expect, test } from 'bun:test';
-import * as THREE from 'three';
+import type * as THREE from 'three';
-import {
- crossedQuadsGeo,
- foliageCardGeo,
- octaGridPlane,
-} from '../primitives';
+import { crossedQuadsGeo, foliageCardGeo, octaGridPlane } from '../primitives';
function bbox(g: THREE.BufferGeometry): { min: THREE.Vector3; max: THREE.Vector3 } {
g.computeBoundingBox();
@@ -43,13 +39,13 @@ describe('foliageCardGeo', () => {
describe('crossedQuadsGeo', () => {
test('planes=2 yields 2 planes × 2 tris = 4 triangles', () => {
const g = crossedQuadsGeo({ width: 1, height: 1, planes: 2 });
- const tris = (g.index!.count / 3);
+ const tris = g.index!.count / 3;
expect(tris).toBe(4);
});
test('planes=3 yields 6 triangles', () => {
const g = crossedQuadsGeo({ width: 1, height: 1, planes: 3 });
- const tris = (g.index!.count / 3);
+ const tris = g.index!.count / 3;
expect(tris).toBe(6);
});
diff --git a/src/__tests__/fixtures.ts b/src/__tests__/fixtures.ts
index 80630329..f197feca 100644
--- a/src/__tests__/fixtures.ts
+++ b/src/__tests__/fixtures.ts
@@ -29,8 +29,8 @@ const worktreeRoot = path.resolve(here, '../../../../..');
// From worktree root: .claude/worktrees/<id>/ -> main repo root is three up.
const mainRepoRoot = path.resolve(worktreeRoot, '../../..');
-export const WAR_ASSETS_DIR = process.env['WAR_ASSETS_DIR']
- ?? path.join(mainRepoRoot, 'war-assets');
+export const WAR_ASSETS_DIR =
+ process.env['WAR_ASSETS_DIR'] ?? path.join(mainRepoRoot, 'war-assets');
export interface GlbFixture {
label: 'trivial' | 'medium' | 'compound';
diff --git a/src/__tests__/gears.test.ts b/src/__tests__/gears.test.ts
index e62eb5aa..f88c503a 100644
--- a/src/__tests__/gears.test.ts
+++ b/src/__tests__/gears.test.ts
@@ -3,7 +3,7 @@
*/
import { describe, it, expect } from 'bun:test';
-import * as THREE from 'three';
+import type * as THREE from 'three';
import { gearGeo, bladeGeo } from '../gears';
function bbox(geo: THREE.BufferGeometry) {
diff --git a/src/__tests__/geometry-gains.test.ts b/src/__tests__/geometry-gains.test.ts
index f6e10bb6..4703b0bb 100644
--- a/src/__tests__/geometry-gains.test.ts
+++ b/src/__tests__/geometry-gains.test.ts
@@ -26,7 +26,10 @@ describe('snapTo', () => {
void g; // sandbox registration sanity is covered by the parity test
const host = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());
host.position.set(0, 0.5, 0);
- const part = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.2, 0.2), new THREE.MeshStandardMaterial());
+ const part = new THREE.Mesh(
+ new THREE.BoxGeometry(0.2, 0.2, 0.2),
+ new THREE.MeshStandardMaterial(),
+ );
part.position.set(0, 1.8, 0); // 0.7 above the host top
const scene = new THREE.Object3D();
scene.add(host, part);
diff --git a/src/__tests__/instancing.test.ts b/src/__tests__/instancing.test.ts
index a0a2a692..357e2656 100644
--- a/src/__tests__/instancing.test.ts
+++ b/src/__tests__/instancing.test.ts
@@ -84,7 +84,12 @@ describe('Wave 1B: instancing primitives', () => {
};
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]];
+ 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],
diff --git a/src/__tests__/ops.test.ts b/src/__tests__/ops.test.ts
index 1010c8c7..44ba2026 100644
--- a/src/__tests__/ops.test.ts
+++ b/src/__tests__/ops.test.ts
@@ -198,8 +198,8 @@ describe('revolveGeo', () => {
[1, 0],
[1, 1],
],
- { axis: [0, 0, 0] }
- )
+ { axis: [0, 0, 0] },
+ ),
).toThrow('axis must be a non-zero vector');
});
});
@@ -220,7 +220,7 @@ describe('pipeAlongPath', () => {
[0, 0, 0],
[0, 1, 0],
],
- 0.05
+ 0.05,
);
const b = bbox(pipe);
expect(b.y).toBeCloseTo(1, 1);
@@ -236,7 +236,7 @@ describe('pipeAlongPath', () => {
[1, 0, 0],
[1, 1, 0],
],
- 0.05
+ 0.05,
);
const b = bbox(pipe);
expect(b.x).toBeGreaterThan(0.9);
diff --git a/src/__tests__/optimize.test.ts b/src/__tests__/optimize.test.ts
index da5d6ff5..2f287ea8 100644
--- a/src/__tests__/optimize.test.ts
+++ b/src/__tests__/optimize.test.ts
@@ -32,14 +32,23 @@ const hue = (i: number, n: number): number => new THREE.Color().setHSL(i / n, 0.
function manyColorScene(n: number): THREE.Object3D {
const root = createRoot('Palette');
for (let i = 0; i < n; i++) {
- createPart(`Box${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, n)), { position: [i * 1.5, 0, 0], parent: root });
+ createPart(`Box${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, n)), {
+ position: [i * 1.5, 0, 0],
+ parent: root,
+ });
}
return root;
}
async function nodeNamesOf(bytes: Uint8Array): Promise<Set<string>> {
const doc = await new WebIO().readBinary(bytes);
- return new Set(doc.getRoot().listNodes().map((nd) => nd.getName()).filter(Boolean));
+ return new Set(
+ doc
+ .getRoot()
+ .listNodes()
+ .map((nd) => nd.getName())
+ .filter(Boolean),
+ );
}
describe('optimize=off (byte-stable)', () => {
@@ -71,7 +80,10 @@ describe('optimize=palette (material collapse)', () => {
it('keeps transparency separate — glass is never merged into opaque', async () => {
const root = createRoot('Glassy');
for (let i = 0; i < 8; i++) {
- createPart(`Wall${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 8)), { position: [i * 1.5, 0, 0], parent: root });
+ createPart(`Wall${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 8)), {
+ position: [i * 1.5, 0, 0],
+ parent: root,
+ });
}
createPart('Window', boxGeo(1, 1, 0.05), glassMaterial(0x88ccff, { opacity: 0.4 }), {
position: [0, 2, 0],
@@ -87,12 +99,18 @@ describe('optimize=palette (material collapse)', () => {
const root = createRoot('Rig');
// A named pivot carrying a moving part (the realistic Kiln City case)...
const lid = createPivot('Lid', [0, 1, 0], root);
- createPart('LidPanel', boxGeo(0.9, 0.1, 0.9), gameMaterial(0x886644), { position: [0, 0.2, 0], parent: lid });
+ createPart('LidPanel', boxGeo(0.9, 0.1, 0.9), gameMaterial(0x886644), {
+ position: [0, 0.2, 0],
+ parent: lid,
+ });
// ...and a named empty pivot (a leaf the behavior could still reference).
createPivot('Marker', [0, 2, 0], root);
// Pad with distinct materials so palette actually runs.
for (let i = 0; i < 8; i++) {
- createPart(`Body${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 8)), { position: [i * 1.5, -2, 0], parent: root });
+ createPart(`Body${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 8)), {
+ position: [i * 1.5, -2, 0],
+ parent: root,
+ });
}
const after = await renderSceneToGLB(root, { optimize: 'palette' });
@@ -107,7 +125,10 @@ describe('optimize=full (static-only; auto-degrade on animation)', () => {
const root = createRoot('Spinner');
const hub = createPivot('Spin', [0, 1, 0], root);
for (let i = 0; i < 8; i++) {
- createPart(`Blade${i}`, boxGeo(0.2, 0.05, 1.2), gameMaterial(hue(i, 8)), { position: [0, 0, 0], parent: hub });
+ createPart(`Blade${i}`, boxGeo(0.2, 0.05, 1.2), gameMaterial(hue(i, 8)), {
+ position: [0, 0, 0],
+ parent: hub,
+ });
}
const track = new THREE.QuaternionKeyframeTrack(
'Joint_Spin.quaternion',
@@ -145,8 +166,12 @@ describe('optimizeGlbBytes (web-side path)', () => {
it('an instanced scene keeps shared geometry through consolidation', async () => {
const root = createRoot('Fence');
- const post = createPart('Post0', boxGeo(0.1, 1, 0.1), gameMaterial(0x8a5a2b), { position: [0, 0.5, 0], parent: root });
- for (let i = 1; i < 10; i++) createInstance(`Post${i}`, post, { position: [i * 0.5, 0.5, 0], parent: root });
+ const post = createPart('Post0', boxGeo(0.1, 1, 0.1), gameMaterial(0x8a5a2b), {
+ position: [0, 0.5, 0],
+ parent: root,
+ });
+ for (let i = 1; i < 10; i++)
+ createInstance(`Post${i}`, post, { position: [i * 0.5, 0.5, 0], parent: root });
const baked = await renderSceneToGLB(root);
expect(baked.instanceability!.metrics.uniqueGeometries).toBe(1);
const opt = await optimizeGlbBytes(baked.bytes, { mode: 'palette' });
diff --git a/src/__tests__/primitives.test.ts b/src/__tests__/primitives.test.ts
index 1cc28cbb..36e61f40 100644
--- a/src/__tests__/primitives.test.ts
+++ b/src/__tests__/primitives.test.ts
@@ -156,14 +156,10 @@ describe('createRoot / createPivot / createPart', () => {
describe('attachment helpers', () => {
test('beamBetween creates a named cylinder centered between endpoints', () => {
const root = createRoot('R');
- const beam = beamBetween(
- 'Brace',
- [1, 0, 0],
- [1, 2, 0],
- 0.05,
- gameMaterial(0x333333),
- { parent: root, segments: 6 }
- ) as THREE.Mesh;
+ const beam = beamBetween('Brace', [1, 0, 0], [1, 2, 0], 0.05, gameMaterial(0x333333), {
+ parent: root,
+ segments: 6,
+ }) as THREE.Mesh;
expect(beam.name).toBe('Mesh_Brace');
expect(beam.parent).toBe(root);
@@ -174,9 +170,9 @@ describe('attachment helpers', () => {
});
test('beamBetween rejects zero-length beams', () => {
- expect(() =>
- beamBetween('Bad', [0, 0, 0], [0, 0, 0], 0.05, gameMaterial(0x333333))
- ).toThrow('start and end must be different points');
+ expect(() => beamBetween('Bad', [0, 0, 0], [0, 0, 0], 0.05, gameMaterial(0x333333))).toThrow(
+ 'start and end must be different points',
+ );
});
test('createLadder creates two continuous rails and evenly named rungs', () => {
@@ -243,7 +239,11 @@ describe('building helpers', () => {
thickness: 0.15,
opening: { kind: 'door' },
});
- expect(wall.children.map((c) => c.name).sort()).toEqual(['Mesh_W_L', 'Mesh_W_Lintel', 'Mesh_W_R']);
+ expect(wall.children.map((c) => c.name).sort()).toEqual([
+ 'Mesh_W_L',
+ 'Mesh_W_Lintel',
+ 'Mesh_W_R',
+ ]);
});
test('wallWithOpening: a window adds a sill apron under the gap', () => {
@@ -263,7 +263,11 @@ describe('building helpers', () => {
test('room: hollow shell of four walls + a floor, enterable by default', () => {
const root = createRoot('R');
- const { root: hut, walls, floor } = room('Hut', gameMaterial(0x8b6f3d), {
+ const {
+ root: hut,
+ walls,
+ floor,
+ } = room('Hut', gameMaterial(0x8b6f3d), {
width: 5,
depth: 4,
parent: root,
@@ -338,10 +342,12 @@ describe('building helpers', () => {
test('createStairs: rejects no steps and a degenerate flight', () => {
const mat = gameMaterial(0x888888);
- expect(() => createStairs('Bad', mat, { steps: 0, totalRise: 1, totalRun: 1, width: 1 })).toThrow(
- 'steps must be >= 1',
+ expect(() =>
+ createStairs('Bad', mat, { steps: 0, totalRise: 1, totalRun: 1, width: 1 }),
+ ).toThrow('steps must be >= 1');
+ expect(() => createStairs('Bad', mat, { totalRise: 0, totalRun: 1, width: 1 })).toThrow(
+ 'must be non-zero',
);
- expect(() => createStairs('Bad', mat, { totalRise: 0, totalRun: 1, width: 1 })).toThrow('must be non-zero');
});
});
@@ -427,7 +433,7 @@ describe('geometry primitives produce real Three.js geometries', () => {
test('cylinderOnAxis rejects zero-length normal', () => {
expect(() => cylinderOnAxis([0, 0, 0], [0, 0, 0], 0.1, 1)).toThrow(
- 'normal must be a non-zero vector'
+ 'normal must be a non-zero vector',
);
});
@@ -800,7 +806,7 @@ describe('countTriangles / countMaterials / getJointNames', () => {
// A single triangle (3 verts, 9 floats), no index.
geo.setAttribute(
'position',
- new THREE.BufferAttribute(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), 3)
+ new THREE.BufferAttribute(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), 3),
);
root.add(new THREE.Mesh(geo, gameMaterial(0x0)));
expect(countTriangles(root)).toBe(1);
@@ -813,10 +819,7 @@ describe('countTriangles / countMaterials / getJointNames', () => {
test('countMaterials handles arrays of materials per mesh', () => {
const root = createRoot('R');
- const mesh = new THREE.Mesh(
- boxGeo(1, 1, 1),
- [gameMaterial(0xff0000), gameMaterial(0x00ff00)]
- );
+ const mesh = new THREE.Mesh(boxGeo(1, 1, 1), [gameMaterial(0xff0000), gameMaterial(0x00ff00)]);
root.add(mesh);
expect(countMaterials(root)).toBe(2);
});
@@ -883,17 +886,43 @@ describe('buildSandboxGlobals', () => {
test('exposes every primitive the LLM is told it can use', () => {
const globals = buildSandboxGlobals();
const expected = [
- 'createRoot', 'createPivot', 'createPart',
- 'beamBetween', 'createLadder', 'createWingPair',
- 'capsuleGeo', 'capsuleXGeo', 'capsuleZGeo',
- 'cylinderGeo', 'cylinderXGeo', 'cylinderZGeo',
- 'boxGeo', 'sphereGeo', 'coneGeo', 'coneXGeo', 'coneZGeo',
- 'torusGeo', 'planeGeo', 'wingGeo',
- 'gameMaterial', 'basicMaterial', 'glassMaterial', 'lambertMaterial',
- 'rotationTrack', 'positionTrack', 'scaleTrack', 'createClip',
- 'spinAnimation', 'bobbingAnimation', 'idleBreathing',
- 'countTriangles', 'countMaterials', 'getJointNames', 'validateAsset',
- 'Math', 'console',
+ 'createRoot',
+ 'createPivot',
+ 'createPart',
+ 'beamBetween',
+ 'createLadder',
+ 'createWingPair',
+ 'capsuleGeo',
+ 'capsuleXGeo',
+ 'capsuleZGeo',
+ 'cylinderGeo',
+ 'cylinderXGeo',
+ 'cylinderZGeo',
+ 'boxGeo',
+ 'sphereGeo',
+ 'coneGeo',
+ 'coneXGeo',
+ 'coneZGeo',
+ 'torusGeo',
+ 'planeGeo',
+ 'wingGeo',
+ 'gameMaterial',
+ 'basicMaterial',
+ 'glassMaterial',
+ 'lambertMaterial',
+ 'rotationTrack',
+ 'positionTrack',
+ 'scaleTrack',
+ 'createClip',
+ 'spinAnimation',
+ 'bobbingAnimation',
+ 'idleBreathing',
+ 'countTriangles',
+ 'countMaterials',
+ 'getJointNames',
+ 'validateAsset',
+ 'Math',
+ 'console',
];
for (const name of expected) {
expect(globals[name]).toBeDefined();
@@ -902,10 +931,7 @@ describe('buildSandboxGlobals', () => {
test('when given a usage map, tallies primitive invocations', () => {
const usage: Record<string, number> = {};
- const globals = buildSandboxGlobals(usage) as Record<
- string,
- (...a: unknown[]) => unknown
- >;
+ const globals = buildSandboxGlobals(usage) as Record<string, (...a: unknown[]) => unknown>;
// Call a spread of primitives with varying counts.
globals.createRoot!('R');
diff --git a/src/__tests__/prompt-api.test.ts b/src/__tests__/prompt-api.test.ts
index d01db837..8cb52381 100644
--- a/src/__tests__/prompt-api.test.ts
+++ b/src/__tests__/prompt-api.test.ts
@@ -22,11 +22,7 @@ import {
renderPrimitivesMarkdown,
renderSkillQuickReference,
} from '../prompt-api';
-import {
- KILN_SYSTEM_PROMPT,
- KILN_SYSTEM_PROMPT_SECTIONS,
- KILN_API_SECTION,
-} from '../prompt';
+import { KILN_SYSTEM_PROMPT, KILN_SYSTEM_PROMPT_SECTIONS, KILN_API_SECTION } from '../prompt';
import { buildSandboxGlobals } from '../primitives';
const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../../..');
diff --git a/src/__tests__/render-edges.test.ts b/src/__tests__/render-edges.test.ts
index 9d343440..4d7486fc 100644
--- a/src/__tests__/render-edges.test.ts
+++ b/src/__tests__/render-edges.test.ts
@@ -11,11 +11,7 @@
import { describe, expect, test } from 'bun:test';
import { NodeIO } from '@gltf-transform/core';
-import {
- executeKilnCode,
- renderGLB,
- inspectGeneratedAnimation,
-} from '../render';
+import { executeKilnCode, renderGLB, inspectGeneratedAnimation } from '../render';
// =============================================================================
// executeKilnCode guard clauses
@@ -32,9 +28,9 @@ describe('executeKilnCode input validation', () => {
// ReferenceError before the typeof check fires. Either failure
// mode is acceptable - the contract is "code without build() does
// not silently render".
- await expect(
- executeKilnCode(`const meta = { name: 'NoBuild' };`)
- ).rejects.toThrow(/build is not defined|did not define `build`/);
+ await expect(executeKilnCode(`const meta = { name: 'NoBuild' };`)).rejects.toThrow(
+ /build is not defined|did not define `build`/,
+ );
});
test('throws when build is defined but is not a function', async () => {
@@ -42,7 +38,7 @@ describe('executeKilnCode input validation', () => {
executeKilnCode(`
const meta = { name: 'NotFn' };
const build = 'not a function';
-`)
+`),
).rejects.toThrow(/did not define `build`/);
});
@@ -51,7 +47,7 @@ const build = 'not a function';
executeKilnCode(`
const meta = { name: 'BadReturn' };
function build() { return 42; }
-`)
+`),
).rejects.toThrow(/did not return a THREE.Object3D/);
});
diff --git a/src/__tests__/scene-palette.test.ts b/src/__tests__/scene-palette.test.ts
index 48472bb6..ac0eb456 100644
--- a/src/__tests__/scene-palette.test.ts
+++ b/src/__tests__/scene-palette.test.ts
@@ -13,13 +13,7 @@
import { describe, it, expect } from 'bun:test';
import * as THREE from 'three';
import { WebIO } from '@gltf-transform/core';
-import {
- createRoot,
- createPart,
- boxGeo,
- gameMaterial,
- glassMaterial,
-} from '../primitives';
+import { createRoot, createPart, boxGeo, gameMaterial, glassMaterial } from '../primitives';
import {
renderSceneToGLB,
snapGlbToPalette,
@@ -35,7 +29,10 @@ const hue = (i: number, n: number): number => new THREE.Color().setHSL(i / n, 0.
function manyColorScene(n: number): THREE.Object3D {
const root = createRoot('Palette');
for (let i = 0; i < n; i++) {
- createPart(`Box${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, n)), { position: [i * 1.5, 0, 0], parent: root });
+ createPart(`Box${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, n)), {
+ position: [i * 1.5, 0, 0],
+ parent: root,
+ });
}
return root;
}
@@ -81,7 +78,9 @@ describe('palette-snap (pure)', () => {
{ color: '#aacbe0', kind: 'glass' },
{ color: '#ffd9a0', kind: 'glow' },
]);
- expect(chooseSlot(idx, { baseLinear: [0.1, 0.1, 0.1], emissiveLinear: [0.8, 0.6, 0.3] })).toBe(2);
+ expect(chooseSlot(idx, { baseLinear: [0.1, 0.1, 0.1], emissiveLinear: [0.8, 0.6, 0.3] })).toBe(
+ 2,
+ );
expect(chooseSlot(idx, { baseLinear: [0.5, 0.6, 0.7], transparent: true })).toBe(1);
expect(chooseSlot(idx, { baseLinear: [0.05, 0.05, 0.05] })).toBe(0); // opaque fallback
});
@@ -110,11 +109,20 @@ describe('snapGlbToPalette', () => {
it('snaps a transparent material to the glass slot (transparency preserved)', async () => {
const root = createRoot('Glassy');
for (let i = 0; i < 6; i++) {
- createPart(`Wall${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 6)), { position: [i * 1.5, 0, 0], parent: root });
+ createPart(`Wall${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 6)), {
+ position: [i * 1.5, 0, 0],
+ parent: root,
+ });
}
- createPart('Window', boxGeo(1, 1, 0.05), glassMaterial(0x88ccff, { opacity: 0.4 }), { position: [0, 2, 0], parent: root });
+ createPart('Window', boxGeo(1, 1, 0.05), glassMaterial(0x88ccff, { opacity: 0.4 }), {
+ position: [0, 2, 0],
+ parent: root,
+ });
const baked = await renderSceneToGLB(root);
- const palWithGlass: SnapPaletteSlot[] = [...PAL, { color: '#aacbe0', kind: 'glass', opacity: 0.4 }];
+ const palWithGlass: SnapPaletteSlot[] = [
+ ...PAL,
+ { color: '#aacbe0', kind: 'glass', opacity: 0.4 },
+ ];
const out = await snapGlbToPalette(baked.bytes, palWithGlass);
expect(out!.report!.metrics.transparentMaterials).toBeGreaterThanOrEqual(1);
});
@@ -133,12 +141,26 @@ describe('composeSceneGLB', () => {
it('merges parts, applies transforms, and sums triangles', async () => {
const a = await glbOf(manyColorScene(3));
- const b = await glbOf((() => { const r = createRoot('B'); createPart('BBox', boxGeo(2, 2, 2), gameMaterial(0x4444ff), { parent: r }); return r; })());
+ const b = await glbOf(
+ (() => {
+ const r = createRoot('B');
+ createPart('BBox', boxGeo(2, 2, 2), gameMaterial(0x4444ff), { parent: r });
+ return r;
+ })(),
+ );
const aTris = (await renderSceneToGLB(manyColorScene(3))).tris;
const out = await composeSceneGLB([
- { bytes: a, transform: { pos: [0, 0, 0], rotDeg: [0, 0, 0], scale: [1, 1, 1] }, name: 'PLACE_A' },
- { bytes: b, transform: { pos: [10, 0, 0], rotDeg: [0, 90, 0], scale: [1, 1, 1] }, name: 'PLACE_B' },
+ {
+ bytes: a,
+ transform: { pos: [0, 0, 0], rotDeg: [0, 0, 0], scale: [1, 1, 1] },
+ name: 'PLACE_A',
+ },
+ {
+ bytes: b,
+ transform: { pos: [10, 0, 0], rotDeg: [0, 90, 0], scale: [1, 1, 1] },
+ name: 'PLACE_B',
+ },
]);
expect(out.tris).toBe(aTris + 12); // a 2×2×2 box = 12 tris
expect(out.draws).toBeGreaterThan(0);
@@ -146,7 +168,10 @@ describe('composeSceneGLB', () => {
// The wrapper node carries the placement transform (pos + a 90° Y quaternion). Use a
// unique name so it can't collide with a source GLB's own root node.
const doc = await new WebIO().readBinary(out.bytes);
- const bNode = doc.getRoot().listNodes().find((nd) => nd.getName() === 'PLACE_B');
+ const bNode = doc
+ .getRoot()
+ .listNodes()
+ .find((nd) => nd.getName() === 'PLACE_B');
expect(bNode).toBeDefined();
const t = bNode!.getTranslation();
expect(t[0]).toBeCloseTo(10, 4);
@@ -156,7 +181,13 @@ describe('composeSceneGLB', () => {
});
it('dedup collapses a repeated blueprint (same GLB placed twice shares geometry)', async () => {
- const a = await glbOf((() => { const r = createRoot('One'); createPart('Box', boxGeo(1, 1, 1), gameMaterial(0x808080), { parent: r }); return r; })());
+ const a = await glbOf(
+ (() => {
+ const r = createRoot('One');
+ createPart('Box', boxGeo(1, 1, 1), gameMaterial(0x808080), { parent: r });
+ return r;
+ })(),
+ );
const out = await composeSceneGLB([
{ bytes: a, transform: { pos: [0, 0, 0], rotDeg: [0, 0, 0], scale: [1, 1, 1] } },
{ bytes: a, transform: { pos: [5, 0, 0], rotDeg: [0, 0, 0], scale: [1, 1, 1] } },
@@ -171,7 +202,14 @@ describe('renderPaletteDirective(slots)', () => {
it('defaults to the canonical palette and adapts to a custom one', () => {
expect(renderPaletteDirective()).toBe(renderPaletteDirective(OPTIMIZED_PALETTE));
const custom = renderPaletteDirective([
- { index: 0, name: 'siding-mint', color: '#9fc9a3', metalness: 0, roughness: 0.8, use: 'house siding' },
+ {
+ index: 0,
+ name: 'siding-mint',
+ color: '#9fc9a3',
+ metalness: 0,
+ roughness: 0.8,
+ use: 'house siding',
+ },
{ index: 1, name: 'asphalt', color: '#45454a', metalness: 0, roughness: 0.9, use: 'road' },
]);
expect(custom).toContain('siding-mint: house siding');
diff --git a/src/__tests__/solids.test.ts b/src/__tests__/solids.test.ts
index abdc4afa..891861f5 100644
--- a/src/__tests__/solids.test.ts
+++ b/src/__tests__/solids.test.ts
@@ -29,8 +29,7 @@ describe('Wave 2A: CSG primitives (manifold-3d)', () => {
const merged = await boolUnion('Merged', a, b);
expect(merged).toBeInstanceOf(THREE.Mesh);
- const posCount = (merged.geometry.getAttribute('position') as THREE.BufferAttribute)
- .count;
+ const posCount = (merged.geometry.getAttribute('position') as THREE.BufferAttribute).count;
expect(posCount).toBeGreaterThan(0);
});
@@ -41,9 +40,7 @@ describe('Wave 2A: CSG primitives (manifold-3d)', () => {
const pierced = await boolDiff('Pierced', body, hole);
// Default output is flat-shaded (non-indexed): count positions/3.
const posCount = (pierced.geometry.getAttribute('position') as THREE.BufferAttribute).count;
- const piercedTris = pierced.geometry.index
- ? pierced.geometry.index.count / 3
- : posCount / 3;
+ const piercedTris = pierced.geometry.index ? pierced.geometry.index.count / 3 : posCount / 3;
// A pierced box has more triangles than a plain box (12).
expect(piercedTris).toBeGreaterThan(12);
});
@@ -76,8 +73,7 @@ describe('Wave 2A: CSG primitives (manifold-3d)', () => {
const lens = await boolIntersect('Lens', a, b);
expect(lens).toBeInstanceOf(THREE.Mesh);
- const posCount = (lens.geometry.getAttribute('position') as THREE.BufferAttribute)
- .count;
+ const posCount = (lens.geometry.getAttribute('position') as THREE.BufferAttribute).count;
expect(posCount).toBeGreaterThan(0);
});
@@ -99,7 +95,7 @@ describe('Wave 2A: CSG primitives (manifold-3d)', () => {
it('errors clearly on invalid input', async () => {
await expect(
- boolUnion('X', new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0xff0000)))
+ boolUnion('X', new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0xff0000))),
).rejects.toThrow(/at least two/);
});
diff --git a/src/__tests__/textures.test.ts b/src/__tests__/textures.test.ts
index 7b76ced4..8f0369f5 100644
--- a/src/__tests__/textures.test.ts
+++ b/src/__tests__/textures.test.ts
@@ -6,11 +6,7 @@ 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 { createRoot, boxGeo, gameMaterial } from '../primitives';
import { loadTexture, pbrMaterial } from '../textures';
import { autoUnwrap } from '../uv';
import { renderSceneToGLB } from '../render';
diff --git a/src/__tests__/uv-shapes.test.ts b/src/__tests__/uv-shapes.test.ts
index ed9d6003..7bb0e40c 100644
--- a/src/__tests__/uv-shapes.test.ts
+++ b/src/__tests__/uv-shapes.test.ts
@@ -3,7 +3,7 @@
*/
import { describe, it, expect } from 'bun:test';
-import * as THREE from 'three';
+import type * as THREE from 'three';
import { boxGeo, cylinderGeo, planeGeo } from '../primitives';
import { boxUnwrap, cylinderUnwrap, planeUnwrap } from '../uv-shapes';
diff --git a/src/__tests__/uv.test.ts b/src/__tests__/uv.test.ts
index 8c4f31d5..2e73debe 100644
--- a/src/__tests__/uv.test.ts
+++ b/src/__tests__/uv.test.ts
@@ -10,13 +10,7 @@
import { describe, it, expect } from 'bun:test';
import * as THREE from 'three';
-import {
- createRoot,
- boxGeo,
- cylinderGeo,
- sphereGeo,
- gameMaterial,
-} from '../primitives';
+import { createRoot, boxGeo, cylinderGeo, sphereGeo, gameMaterial } from '../primitives';
import { autoUnwrap } from '../uv';
import { boolDiff } from '../solids';
import { renderSceneToGLB } from '../render';
diff --git a/src/__tests__/validation-hardened.test.ts b/src/__tests__/validation-hardened.test.ts
index 414ab88a..c201627f 100644
--- a/src/__tests__/validation-hardened.test.ts
+++ b/src/__tests__/validation-hardened.test.ts
@@ -221,7 +221,10 @@ describe('kiln validation — tri budget advisory', () => {
test('warns when a prop exceeds its tri budget', () => {
// 20x sphereGeo(1, 32, 32) -> 20 * 2048 = 40960 tris, dwarfs prop 3000.
const geo = Array.from({ length: 20 })
- .map(() => ' createPart(\'S\' + Math.random(), sphereGeo(1, 32, 32), gameMaterial(0xff0000), { parent: root });')
+ .map(
+ () =>
+ " createPart('S' + Math.random(), sphereGeo(1, 32, 32), gameMaterial(0xff0000), { parent: root });",
+ )
.join('\n');
const r = validate(
`
@@ -232,7 +235,7 @@ ${geo}
return root;
}
`,
- { category: 'prop' }
+ { category: 'prop' },
);
expect(r.valid).toBe(true);
expect(r.warnings.some((w) => w.code === 'TRI_BUDGET_EXCEEDED')).toBe(true);
@@ -276,19 +279,29 @@ function build() {
test('flags a numeric radian triple with the degree equivalent', () => {
const w = radianWarnings(
- wrap(`createPart('Grip', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: [0, 0, 0.785], parent: root });`)
+ wrap(
+ `createPart('Grip', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: [0, 0, 0.785], parent: root });`,
+ ),
);
expect(w.length).toBe(1);
expect(w[0]!.message).toContain('[0, 0, 0.785]');
expect(w[0]!.message).toContain('[0, 0, 45]');
expect(w[0]!.line).toBeDefined();
// Advisory only — the program is still valid.
- expect(validate(wrap(`createPart('G', boxGeo(1,1,1), gameMaterial(0x333333), { rotation: [0, 0, 0.785], parent: root });`)).valid).toBe(true);
+ expect(
+ validate(
+ wrap(
+ `createPart('G', boxGeo(1,1,1), gameMaterial(0x333333), { rotation: [0, 0, 0.785], parent: root });`,
+ ),
+ ).valid,
+ ).toBe(true);
});
test('flags Math.PI expressions (the -Math.PI/2 fin case)', () => {
const w = radianWarnings(
- wrap(`createPart('Fin', wingGeo({ span: 3 }), gameMaterial(0x445522), { rotation: [-Math.PI / 2, 0, 0], parent: root });`)
+ wrap(
+ `createPart('Fin', wingGeo({ span: 3 }), gameMaterial(0x445522), { rotation: [-Math.PI / 2, 0, 0], parent: root });`,
+ ),
);
expect(w.length).toBe(1);
expect(w[0]!.message).toContain('RADIANS');
@@ -297,16 +310,25 @@ function build() {
test('does NOT flag the rad-to-deg conversion idiom (a * 180 / Math.PI)', () => {
const w = radianWarnings(
wrap(`const a = 0.5;
- createPart('Blade', boxGeo(0.06, 1.7, 0.27), gameMaterial(0x111111), { rotation: [a * 180 / Math.PI, 0, 0], parent: root });`)
+ createPart('Blade', boxGeo(0.06, 1.7, 0.27), gameMaterial(0x111111), { rotation: [a * 180 / Math.PI, 0, 0], parent: root });`),
);
expect(w).toEqual([]);
});
test('does NOT flag degree-style values', () => {
- const cases = ['[0, 0, 90]', '[0, 0, -15]', '[0, 0, 28.6]', '[0, 45, 0.5]', '[0, 0, 0]', '[0, 0, 1]'];
+ const cases = [
+ '[0, 0, 90]',
+ '[0, 0, -15]',
+ '[0, 0, 28.6]',
+ '[0, 45, 0.5]',
+ '[0, 0, 0]',
+ '[0, 0, 1]',
+ ];
for (const rot of cases) {
const w = radianWarnings(
- wrap(`createPart('P', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: ${rot}, parent: root });`)
+ wrap(
+ `createPart('P', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: ${rot}, parent: root });`,
+ ),
);
expect(w).toEqual([]);
}
@@ -315,7 +337,7 @@ function build() {
test('stays quiet on dynamic expressions it cannot read', () => {
const w = radianWarnings(
wrap(`const tilt = 17;
- createPart('P', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: [0, 0, tilt], parent: root });`)
+ createPart('P', boxGeo(1, 1, 1), gameMaterial(0x333333), { rotation: [0, 0, tilt], parent: root });`),
);
expect(w).toEqual([]);
});
@@ -324,7 +346,7 @@ function build() {
const w = radianWarnings(
wrap(`const src = createPart('W', cylinderZGeo(0.5, 0.5, 0.3), gameMaterial(0x222222), { parent: root });
createInstance('W2', src, { position: [1, 0, 0], rotation: [0, 1.57, 0], parent: root });
- rotationTrack('Joint_X', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [0, 0, 0.5] }]);`)
+ rotationTrack('Joint_X', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [0, 0, 0.5] }]);`),
);
expect(w.length).toBe(1);
expect(w[0]!.message).toContain('createInstance');
diff --git a/src/agent/diff.ts b/src/agent/diff.ts
index bed9a00b..2ab06de6 100644
--- a/src/agent/diff.ts
+++ b/src/agent/diff.ts
@@ -37,7 +37,8 @@ function diffLines(a: string[], b: string[]): Array<{ tag: Tag; line: string }>
const lcs: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let j = m - 1; j >= 0; j--) {
- lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
+ lcs[i]![j] =
+ a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
}
}
diff --git a/src/agent/generate.test.ts b/src/agent/generate.test.ts
index d02381ea..03507d55 100644
--- a/src/agent/generate.test.ts
+++ b/src/agent/generate.test.ts
@@ -106,7 +106,11 @@ describe('generateKilnAsset', () => {
});
test('throws when the agent returns an error', async () => {
- runImpl = async () => ({ error: 'stream ended without completing a message', toolCalls: [], steps: 0 });
+ runImpl = async () => ({
+ error: 'stream ended without completing a message',
+ toolCalls: [],
+ steps: 0,
+ });
await expect(generateKilnAsset({ prompt: 'x' })).rejects.toThrow(/stream ended/);
});
diff --git a/src/agent/hooks.test.ts b/src/agent/hooks.test.ts
index cce757e4..1eecff6e 100644
--- a/src/agent/hooks.test.ts
+++ b/src/agent/hooks.test.ts
@@ -5,7 +5,11 @@
* exercises the loop without a live model.
*/
import { describe, expect, test } from 'bun:test';
-import { BeforeToolCallEvent, BeforeModelCallEvent, AfterModelCallEvent } from '@strands-agents/sdk';
+import {
+ BeforeToolCallEvent,
+ BeforeModelCallEvent,
+ AfterModelCallEvent,
+} from '@strands-agents/sdk';
import { MetricsCollector } from './hooks';
type Cb = (event: unknown) => void;
@@ -20,7 +24,10 @@ function fakeAgent() {
hooks.set(EventClass, arr);
return () => {
const cur = hooks.get(EventClass) ?? [];
- hooks.set(EventClass, cur.filter((c) => c !== cb));
+ hooks.set(
+ EventClass,
+ cur.filter((c) => c !== cb),
+ );
};
},
};
diff --git a/src/agent/hooks.ts b/src/agent/hooks.ts
index c9a0951e..e5090701 100644
--- a/src/agent/hooks.ts
+++ b/src/agent/hooks.ts
@@ -11,7 +11,12 @@
* `recordResultUsage(result.metrics?.latestAgentInvocation?.usage)`, read
* `readMetrics()`, then `detach()`.
*/
-import { type Agent, BeforeToolCallEvent, BeforeModelCallEvent, AfterModelCallEvent } from '@strands-agents/sdk';
+import {
+ type Agent,
+ BeforeToolCallEvent,
+ BeforeModelCallEvent,
+ AfterModelCallEvent,
+} from '@strands-agents/sdk';
/** Token-usage subset we surface. */
export interface AgentUsage {
@@ -75,14 +80,15 @@ export class MetricsCollector {
// Hard step cap: before a model call that would exceed maxSteps, cancel it.
// The SDK ends the loop with stopReason 'endTurn' (no exception) — `capped`
// lets the caller turn that bounded stop into a clear failed generation.
- const offCap = this.maxSteps && this.maxSteps > 0
- ? agent.addHook(BeforeModelCallEvent, (event) => {
- if (this.steps >= this.maxSteps!) {
- this.capped = true;
- event.cancel = `kiln: agent step cap reached (${this.maxSteps} model calls) — aborted to bound cost`;
- }
- })
- : undefined;
+ const offCap =
+ this.maxSteps && this.maxSteps > 0
+ ? agent.addHook(BeforeModelCallEvent, (event) => {
+ if (this.steps >= this.maxSteps!) {
+ this.capped = true;
+ event.cancel = `kiln: agent step cap reached (${this.maxSteps} model calls) — aborted to bound cost`;
+ }
+ })
+ : undefined;
this.cleanups.push(offTool, offModel);
if (offCap) this.cleanups.push(offCap);
return () => this.detach();
diff --git a/src/agent/index.ts b/src/agent/index.ts
index d94de969..485e3592 100644
--- a/src/agent/index.ts
+++ b/src/agent/index.ts
@@ -36,14 +36,26 @@ export {
KilnEditBuffer,
KILN_SUBMIT_TOOL_NAME,
} from './tools';
-export type { SubmitSink, EditSink, UnifiedSink, EditRecord, EditResult, KilnRenderCandidate } from './tools';
+export type {
+ SubmitSink,
+ EditSink,
+ UnifiedSink,
+ EditRecord,
+ EditResult,
+ KilnRenderCandidate,
+} from './tools';
export { unifiedDiff } from './diff';
export type { UnifiedDiffOptions } from './diff';
export { ensureStreamStart } from './stream-start';
-export { makeOpenRouterModel, makeKilnModel, resolveKilnAgentModel, harnessIdToAgentModelId } from './providers';
+export {
+ makeOpenRouterModel,
+ makeKilnModel,
+ resolveKilnAgentModel,
+ harnessIdToAgentModelId,
+} from './providers';
export type {
OpenRouterModelOptions,
KilnAgentProvider,
diff --git a/src/agent/providers.test.ts b/src/agent/providers.test.ts
index 875a98a6..9673a283 100644
--- a/src/agent/providers.test.ts
+++ b/src/agent/providers.test.ts
@@ -12,9 +12,18 @@ import { resolveKilnAgentModel, makeKilnModel } from './providers';
describe('resolveKilnAgentModel', () => {
test('explicit provider prefixes win and keep the model id intact', () => {
- expect(resolveKilnAgentModel('google:gemini-3.5-flash')).toEqual({ provider: 'google', model: 'gemini-3.5-flash' });
- expect(resolveKilnAgentModel('anthropic:claude-opus-4-8')).toEqual({ provider: 'anthropic', model: 'claude-opus-4-8' });
- expect(resolveKilnAgentModel('openai:gpt-5.5')).toEqual({ provider: 'openai', model: 'gpt-5.5' });
+ expect(resolveKilnAgentModel('google:gemini-3.5-flash')).toEqual({
+ provider: 'google',
+ model: 'gemini-3.5-flash',
+ });
+ expect(resolveKilnAgentModel('anthropic:claude-opus-4-8')).toEqual({
+ provider: 'anthropic',
+ model: 'claude-opus-4-8',
+ });
+ expect(resolveKilnAgentModel('openai:gpt-5.5')).toEqual({
+ provider: 'openai',
+ model: 'gpt-5.5',
+ });
expect(resolveKilnAgentModel('bedrock:global.anthropic.claude-opus-4-8')).toEqual({
provider: 'bedrock',
model: 'global.anthropic.claude-opus-4-8',
@@ -26,11 +35,17 @@ describe('resolveKilnAgentModel', () => {
});
test('a bare vendor/model slash id is OpenRouter', () => {
- expect(resolveKilnAgentModel('x-ai/grok-4.3')).toEqual({ provider: 'openrouter', model: 'x-ai/grok-4.3' });
+ expect(resolveKilnAgentModel('x-ai/grok-4.3')).toEqual({
+ provider: 'openrouter',
+ model: 'x-ai/grok-4.3',
+ });
});
test('bare gemini-* resolves to google (the regression the harness vocab gets wrong)', () => {
- expect(resolveKilnAgentModel('gemini-3.5-flash')).toEqual({ provider: 'google', model: 'gemini-3.5-flash' });
+ expect(resolveKilnAgentModel('gemini-3.5-flash')).toEqual({
+ provider: 'google',
+ model: 'gemini-3.5-flash',
+ });
expect(resolveKilnAgentModel('imagen-4')).toEqual({ provider: 'google', model: 'imagen-4' });
});
@@ -41,12 +56,18 @@ describe('resolveKilnAgentModel', () => {
});
test('bare claude-* and unknown ids default to anthropic', () => {
- expect(resolveKilnAgentModel('claude-opus-4-8')).toEqual({ provider: 'anthropic', model: 'claude-opus-4-8' });
+ expect(resolveKilnAgentModel('claude-opus-4-8')).toEqual({
+ provider: 'anthropic',
+ model: 'claude-opus-4-8',
+ });
expect(resolveKilnAgentModel('some-future-model').provider).toBe('anthropic');
});
test('trims surrounding whitespace', () => {
- expect(resolveKilnAgentModel(' google:gemini-3.5-flash ')).toEqual({ provider: 'google', model: 'gemini-3.5-flash' });
+ expect(resolveKilnAgentModel(' google:gemini-3.5-flash ')).toEqual({
+ provider: 'google',
+ model: 'gemini-3.5-flash',
+ });
});
});
@@ -68,15 +89,33 @@ describe('makeKilnModel', () => {
});
test('constructs the right Strands model class per provider', () => {
- expect(makeKilnModel({ provider: 'google', model: 'gemini-3.5-flash' }).constructor.name).toBe('GoogleModel');
- expect(makeKilnModel({ provider: 'anthropic', model: 'claude-opus-4-8', maxTokens: 16000 }).constructor.name).toBe('AnthropicModel');
- expect(makeKilnModel({ provider: 'openai', model: 'gpt-5.5', maxTokens: 16000 }).constructor.name).toBe('OpenAIModel');
- expect(makeKilnModel({ provider: 'bedrock', model: 'global.anthropic.claude-opus-4-8', maxTokens: 16000 }).constructor.name).toBe('BedrockModel');
- expect(makeKilnModel({ provider: 'openrouter', model: 'x-ai/grok-4.3' }).constructor.name).toBe('VercelModel');
+ expect(makeKilnModel({ provider: 'google', model: 'gemini-3.5-flash' }).constructor.name).toBe(
+ 'GoogleModel',
+ );
+ expect(
+ makeKilnModel({ provider: 'anthropic', model: 'claude-opus-4-8', maxTokens: 16000 })
+ .constructor.name,
+ ).toBe('AnthropicModel');
+ expect(
+ makeKilnModel({ provider: 'openai', model: 'gpt-5.5', maxTokens: 16000 }).constructor.name,
+ ).toBe('OpenAIModel');
+ expect(
+ makeKilnModel({
+ provider: 'bedrock',
+ model: 'global.anthropic.claude-opus-4-8',
+ maxTokens: 16000,
+ }).constructor.name,
+ ).toBe('BedrockModel');
+ expect(makeKilnModel({ provider: 'openrouter', model: 'x-ai/grok-4.3' }).constructor.name).toBe(
+ 'VercelModel',
+ );
});
test('accepts a BYOK apiKey override for the google path', () => {
- const m = makeKilnModel({ provider: 'google', model: 'gemini-3.5-flash' }, { apiKey: 'byok-override' });
+ const m = makeKilnModel(
+ { provider: 'google', model: 'gemini-3.5-flash' },
+ { apiKey: 'byok-override' },
+ );
expect(m).toBeTruthy();
});
@@ -94,7 +133,10 @@ describe('makeKilnModel', () => {
const cfg = getCfg(
makeKilnModel({ provider: 'anthropic', model: 'claude-fable-5', thinking: 'high' }),
);
- expect(cfg['params']).toEqual({ thinking: { type: 'adaptive' }, output_config: { effort: 'high' } });
+ expect(cfg['params']).toEqual({
+ thinking: { type: 'adaptive' },
+ output_config: { effort: 'high' },
+ });
expect(cfg['betas']).toBeUndefined();
});
@@ -111,13 +153,18 @@ describe('makeKilnModel', () => {
try {
process.env['KILN_THINKING'] = 'medium';
const adaptive = getCfg(makeKilnModel({ provider: 'anthropic', model: 'claude-fable-5' }));
- expect(adaptive['params']).toEqual({ thinking: { type: 'adaptive' }, output_config: { effort: 'medium' } });
+ expect(adaptive['params']).toEqual({
+ thinking: { type: 'adaptive' },
+ output_config: { effort: 'medium' },
+ });
process.env['KILN_THINKING'] = '512';
const floored = getCfg(makeKilnModel({ provider: 'anthropic', model: 'claude-opus-4-8' }));
expect(floored['params']).toEqual({ thinking: { type: 'enabled', budget_tokens: 1024 } });
- const off = getCfg(makeKilnModel({ provider: 'anthropic', model: 'claude-fable-5', thinking: 0 }));
+ const off = getCfg(
+ makeKilnModel({ provider: 'anthropic', model: 'claude-fable-5', thinking: 0 }),
+ );
expect(off['params']).toBeUndefined();
// Non-anthropic providers must not grow a thinking param from the env.
diff --git a/src/agent/providers.ts b/src/agent/providers.ts
index 66b36db2..d43001d5 100644
--- a/src/agent/providers.ts
+++ b/src/agent/providers.ts
@@ -106,7 +106,11 @@ function resolveAnthropicThinking(
const raw = fromDesc ?? trimmedEnv('KILN_THINKING');
if (raw == null || raw === '' || raw === 0) return undefined;
const asNum =
- typeof raw === 'number' ? raw : /^\d+$/.test(String(raw).trim()) ? Number.parseInt(String(raw).trim(), 10) : undefined;
+ typeof raw === 'number'
+ ? raw
+ : /^\d+$/.test(String(raw).trim())
+ ? Number.parseInt(String(raw).trim(), 10)
+ : undefined;
if (asNum !== undefined) {
if (!Number.isFinite(asNum) || asNum <= 0) return undefined;
return {
@@ -139,9 +143,16 @@ export function makeKilnModel(desc: KilnModelDescriptor, opts: MakeKilnModelOpti
});
}
case 'openai':
- return new OpenAIModel({ api: 'chat', modelId: desc.model, ...(maxTokens != null ? { maxTokens } : {}) });
+ return new OpenAIModel({
+ api: 'chat',
+ modelId: desc.model,
+ ...(maxTokens != null ? { maxTokens } : {}),
+ });
case 'google':
- return new GoogleModel({ modelId: desc.model, apiKey: opts.apiKey ?? trimmedEnv('GEMINI_API_KEY') });
+ return new GoogleModel({
+ modelId: desc.model,
+ apiKey: opts.apiKey ?? trimmedEnv('GEMINI_API_KEY'),
+ });
case 'bedrock':
return new BedrockModel({
modelId: desc.model,
@@ -196,8 +207,10 @@ export function resolveKilnAgentModel(modelId: string): KilnModelDescriptor {
}
// A slash with no explicit prefix is an OpenRouter `vendor/model` id.
if (id.includes('/')) return { provider: 'openrouter', model: id };
- if (id.startsWith('gemini-') || id.startsWith('imagen-')) return { provider: 'google', model: id };
- if (id.startsWith('gpt-') || id.startsWith('o3') || id.startsWith('o4')) return { provider: 'openai', model: id };
+ if (id.startsWith('gemini-') || id.startsWith('imagen-'))
+ return { provider: 'google', model: id };
+ if (id.startsWith('gpt-') || id.startsWith('o3') || id.startsWith('o4'))
+ return { provider: 'openai', model: id };
// Default: Anthropic (claude-*).
return { provider: 'anthropic', model: id };
}
diff --git a/src/agent/run-surface.test.ts b/src/agent/run-surface.test.ts
index 45f1db33..c364b206 100644
--- a/src/agent/run-surface.test.ts
+++ b/src/agent/run-surface.test.ts
@@ -9,11 +9,7 @@
*/
import { describe, expect, test } from 'bun:test';
-import {
- buildAgentTools,
- resolveToolSurface,
- type ToolBuildOptions,
-} from './surface';
+import { buildAgentTools, resolveToolSurface, type ToolBuildOptions } from './surface';
import type { SubmitSink, EditSink, UnifiedSink } from './tools';
function freshSinks() {
diff --git a/src/agent/run.ts b/src/agent/run.ts
index 5673a1dc..a3879adc 100644
--- a/src/agent/run.ts
+++ b/src/agent/run.ts
@@ -16,7 +16,14 @@
* caller constructs the `model` (see provider helpers) and owns any out-of-process
* resources (e.g. an MCP client passed via `extraTools`).
*/
-import { Agent, TextBlock, ImageBlock, type Plugin, type Tool, type Message } from '@strands-agents/sdk';
+import {
+ Agent,
+ TextBlock,
+ ImageBlock,
+ type Plugin,
+ type Tool,
+ type Message,
+} from '@strands-agents/sdk';
import { AgentSkills } from '@strands-agents/sdk/vended-plugins/skills';
import {
@@ -230,7 +237,10 @@ export async function runKilnAgent(opts: RunKilnAgentOptions): Promise<RunKilnAg
// An image-only request still needs a textual anchor for prompt framing.
const promptText =
- opts.prompt?.trim() || (opts.inputImage ? 'Build a 3D game asset that matches the attached reference image.' : opts.prompt);
+ opts.prompt?.trim() ||
+ (opts.inputImage
+ ? 'Build a 3D game asset that matches the attached reference image.'
+ : opts.prompt);
const reviewNote =
surface === 'unified'
diff --git a/src/agent/stream-start.test.ts b/src/agent/stream-start.test.ts
index fc30ecde..72e3b24a 100644
--- a/src/agent/stream-start.test.ts
+++ b/src/agent/stream-start.test.ts
@@ -29,7 +29,9 @@ function fakeModel(
} as never;
}
-async function drain(model: { doStream: (o: unknown) => Promise<{ stream: ReadableStream }> }): Promise<string[]> {
+async function drain(model: {
+ doStream: (o: unknown) => Promise<{ stream: ReadableStream }>;
+}): Promise<string[]> {
const { stream } = await model.doStream({});
const reader = stream.getReader();
const types: string[] = [];
@@ -52,7 +54,9 @@ test('injects a leading stream-start when the provider omits it (OpenRouter shap
});
test('is a no-op when the provider already emits stream-start', async () => {
- const wrapped = ensureStreamStart(fakeModel([{ type: 'stream-start', warnings: [] }, { type: 'finish' }]));
+ const wrapped = ensureStreamStart(
+ fakeModel([{ type: 'stream-start', warnings: [] }, { type: 'finish' }]),
+ );
expect(await drain(wrapped as never)).toEqual(['stream-start', 'finish']);
});
diff --git a/src/agent/stream-start.ts b/src/agent/stream-start.ts
index dc2069d5..80355721 100644
--- a/src/agent/stream-start.ts
+++ b/src/agent/stream-start.ts
@@ -40,7 +40,8 @@ export function ensureStreamStart(model: LanguageModelV3): LanguageModelV3 {
let injected = false;
const guard = new TransformStream<LanguageModelV3StreamPart, LanguageModelV3StreamPart>({
transform(chunk, ctrl) {
- if (!injected && chunk.type !== 'stream-start') ctrl.enqueue({ type: 'stream-start', warnings: [] });
+ if (!injected && chunk.type !== 'stream-start')
+ ctrl.enqueue({ type: 'stream-start', warnings: [] });
injected = true;
ctrl.enqueue(chunk);
},
diff --git a/src/agent/tools-edit.test.ts b/src/agent/tools-edit.test.ts
index ef0da633..f1ed3969 100644
--- a/src/agent/tools-edit.test.ts
+++ b/src/agent/tools-edit.test.ts
@@ -85,7 +85,10 @@ test('view returns the raw buffer and a line count that tracks edits', () => {
const v = buf.view();
expect(v.code).toBe(SEED);
expect(v.lines).toBe(SEED.split('\n').length);
- buf.apply({ oldString: ' return root;\n', newString: ' root.add(createPart("Lid", boxGeo(1,1,1)));\n return root;\n' });
+ buf.apply({
+ oldString: ' return root;\n',
+ newString: ' root.add(createPart("Lid", boxGeo(1,1,1)));\n return root;\n',
+ });
expect(buf.view().lines).toBe(buf.code.split('\n').length);
});
diff --git a/src/agent/tools-unified.test.ts b/src/agent/tools-unified.test.ts
index 939ea846..683a9e1a 100644
--- a/src/agent/tools-unified.test.ts
+++ b/src/agent/tools-unified.test.ts
@@ -8,12 +8,7 @@
import { describe, expect, test } from 'bun:test';
import { ImageBlock, JsonBlock } from '@strands-agents/sdk';
-import {
- KilnDraftBuffer,
- KilnEditBuffer,
- makeKilnUnifiedTools,
- type UnifiedSink,
-} from './tools';
+import { KilnDraftBuffer, KilnEditBuffer, makeKilnUnifiedTools, type UnifiedSink } from './tools';
const BOX_CODE = `
const meta = { name: 'test-box', category: 'prop' };
@@ -105,7 +100,10 @@ describe('makeKilnUnifiedTools', () => {
};
expect(drafted.ok).toBe(true);
expect(sink.code).toBe(BOX_CODE); // captured even before finalize
- const viewed = (await findTool(tools, 'kiln_view').invoke({})) as { code: string; lines: number };
+ const viewed = (await findTool(tools, 'kiln_view').invoke({})) as {
+ code: string;
+ lines: number;
+ };
expect(viewed.code).toBe(BOX_CODE);
});
@@ -150,7 +148,10 @@ describe('makeKilnUnifiedTools', () => {
test('kiln_render on a broken buffer is image-free (plain JSON error)', async () => {
const sink: UnifiedSink = { edits: [] };
const tools = makeKilnUnifiedTools({ seedCode: 'not a kiln program (', sink });
- const out = (await findTool(tools, 'kiln_render').invoke({})) as { ok: boolean; error?: string };
+ const out = (await findTool(tools, 'kiln_render').invoke({})) as {
+ ok: boolean;
+ error?: string;
+ };
expect(Array.isArray(out)).toBe(false);
expect(out.ok).toBe(false);
expect(out.error).toBeDefined();
@@ -159,7 +160,11 @@ describe('makeKilnUnifiedTools', () => {
test('kiln_render emits a render candidate (buffer code + six-view png) via onCandidate', async () => {
const sink: UnifiedSink = { edits: [] };
const got: Array<{ code: string; pngBase64: string; tris?: number }> = [];
- const tools = makeKilnUnifiedTools({ seedCode: BOX_CODE, sink, onCandidate: (c) => got.push(c) });
+ const tools = makeKilnUnifiedTools({
+ seedCode: BOX_CODE,
+ sink,
+ onCandidate: (c) => got.push(c),
+ });
await findTool(tools, 'kiln_render').invoke({});
expect(got).toHaveLength(1);
expect(got[0]!.code).toBe(BOX_CODE); // the exact working buffer
@@ -170,7 +175,11 @@ describe('makeKilnUnifiedTools', () => {
test('kiln_render on a broken buffer does NOT emit a candidate (image-free build)', async () => {
const sink: UnifiedSink = { edits: [] };
const got: unknown[] = [];
- const tools = makeKilnUnifiedTools({ seedCode: 'not a kiln program (', sink, onCandidate: (c) => got.push(c) });
+ const tools = makeKilnUnifiedTools({
+ seedCode: 'not a kiln program (',
+ sink,
+ onCandidate: (c) => got.push(c),
+ });
await findTool(tools, 'kiln_render').invoke({});
expect(got).toHaveLength(0); // a failed render has no image → no candidate
});
@@ -193,7 +202,10 @@ describe('makeKilnUnifiedTools', () => {
test('kiln_view_interior on a broken buffer is image-free (plain JSON error)', async () => {
const sink: UnifiedSink = { edits: [] };
const tools = makeKilnUnifiedTools({ seedCode: 'not a kiln program (', sink });
- const out = (await findTool(tools, 'kiln_view_interior').invoke({})) as { ok: boolean; error?: string };
+ const out = (await findTool(tools, 'kiln_view_interior').invoke({})) as {
+ ok: boolean;
+ error?: string;
+ };
expect(Array.isArray(out)).toBe(false);
expect(out.ok).toBe(false);
expect(out.error).toBeDefined();
diff --git a/src/agent/tools.ts b/src/agent/tools.ts
index e022081d..ad79446d 100644
--- a/src/agent/tools.ts
+++ b/src/agent/tools.ts
@@ -83,7 +83,10 @@ const animationBufferInput = z.object({
.string()
.optional()
.describe('Camera angle: right (default), front, back, left, top, or three-quarter.'),
- perFrame: z.boolean().optional().describe('Return separate high-res frames instead of one grid. Default false.'),
+ perFrame: z
+ .boolean()
+ .optional()
+ .describe('Return separate high-res frames instead of one grid. Default false.'),
});
/** Build a buffer-aware kiln_screenshot_animation tool that runs against `getCode()`
@@ -236,7 +239,10 @@ export class KilnDraftBuffer {
return { ok: false, error: 'oldString must not be empty.' };
}
if (oldString === newString) {
- return { ok: false, error: 'oldString and newString are identical - there is nothing to change.' };
+ return {
+ ok: false,
+ error: 'oldString and newString are identical - there is nothing to change.',
+ };
}
const occurrences = this.buf.split(oldString).length - 1;
@@ -361,7 +367,9 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
description: `${validateDef.description} Omit code to validate the current working buffer.`,
inputSchema: bufferCodeInput,
callback: async (input) =>
- (await validateDef.run({ code: (input as { code?: string }).code ?? buffer.code })) as JSONValue,
+ (await validateDef.run({
+ code: (input as { code?: string }).code ?? buffer.code,
+ })) as JSONValue,
});
const renderTool: Tool = tool({
@@ -369,7 +377,9 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
description: `${renderDef.description} Omit code to render the current working buffer.`,
inputSchema: bufferCodeInput,
callback: async (input) =>
- (await renderDef.run({ code: (input as { code?: string }).code ?? buffer.code })) as JSONValue,
+ (await renderDef.run({
+ code: (input as { code?: string }).code ?? buffer.code,
+ })) as JSONValue,
});
const screenshotTool: Tool = tool({
@@ -397,11 +407,25 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
callback: (input) => {
const code = (input as { code?: string }).code ?? buffer.code;
opts.sink.code = code;
- return { ok: true, recorded: true, bytes: code.length, edits: buffer.edits.length } as JSONValue;
+ return {
+ ok: true,
+ recorded: true,
+ bytes: code.length,
+ edits: buffer.edits.length,
+ } as JSONValue;
},
});
- return [listTool, viewTool, editTool, validateTool, renderTool, screenshotTool, animationTool, submitTool];
+ return [
+ listTool,
+ viewTool,
+ editTool,
+ validateTool,
+ renderTool,
+ screenshotTool,
+ animationTool,
+ submitTool,
+ ];
}
// =============================================================================
@@ -516,7 +540,9 @@ export function makeKilnUnifiedTools(opts: {
'{ ok, occurrences, newBytes } or { ok:false, error, hint }.',
inputSchema: editInput,
callback: (input) => {
- const r = buffer.apply(input as { oldString: string; newString: string; replaceAll?: boolean });
+ const r = buffer.apply(
+ input as { oldString: string; newString: string; replaceAll?: boolean },
+ );
if (r.ok) {
opts.sink.code = buffer.code; // capture the live buffer even if finalize is skipped
return r as JSONValue;
@@ -538,7 +564,8 @@ export function makeKilnUnifiedTools(opts: {
const renderTool: Tool = tool({
name: 'kiln_render',
- description: kilnRenderViewsDef.description + ' Operates on your current working buffer (no argument).',
+ description:
+ kilnRenderViewsDef.description + ' Operates on your current working buffer (no argument).',
inputSchema: viewInput,
callback: async () => {
const out = await kilnRenderViewsDef.run({ code: buffer.code });
@@ -549,7 +576,11 @@ export function makeKilnUnifiedTools(opts: {
const o = out as { ok?: boolean; pngBase64?: string; tris?: number };
if (o.ok && o.pngBase64) {
try {
- opts.onCandidate({ code: buffer.code, pngBase64: o.pngBase64, ...(o.tris != null ? { tris: o.tris } : {}) });
+ opts.onCandidate({
+ code: buffer.code,
+ pngBase64: o.pngBase64,
+ ...(o.tris != null ? { tris: o.tris } : {}),
+ });
} catch {
// candidate sink is best-effort
}
@@ -567,16 +598,17 @@ export function makeKilnUnifiedTools(opts: {
// (roof off — open floor, real doorway gap, fixtures grounded, nothing buried).
const interiorTool: Tool = tool({
name: 'kiln_view_interior',
- description: kilnViewInteriorDef.description + ' Operates on your current working buffer (omit code).',
+ description:
+ kilnViewInteriorDef.description + ' Operates on your current working buffer (omit code).',
inputSchema: z.object({
- nodeName: z
- .string()
- .optional()
- .describe('The roof part to lift, by name (default "Roof").'),
+ nodeName: z.string().optional().describe('The roof part to lift, by name (default "Roof").'),
}),
callback: async (input) => {
const n = (input as { nodeName?: string }).nodeName;
- const out = await kilnViewInteriorDef.run({ code: buffer.code, ...(n ? { nodeName: n } : {}) });
+ const out = await kilnViewInteriorDef.run({
+ code: buffer.code,
+ ...(n ? { nodeName: n } : {}),
+ });
return toCallbackResult(kilnViewInteriorDef, out);
},
});
@@ -591,9 +623,23 @@ export function makeKilnUnifiedTools(opts: {
callback: () => {
opts.sink.code = buffer.code;
opts.sink.finalized = true;
- return { ok: true, recorded: true, bytes: buffer.code.length, edits: buffer.edits.length } as JSONValue;
+ return {
+ ok: true,
+ recorded: true,
+ bytes: buffer.code.length,
+ edits: buffer.edits.length,
+ } as JSONValue;
},
});
- return [draftTool, viewTool, editTool, validateTool, renderTool, animationTool, interiorTool, finalizeTool];
+ return [
+ draftTool,
+ viewTool,
+ editTool,
+ validateTool,
+ renderTool,
+ animationTool,
+ interiorTool,
+ finalizeTool,
+ ];
}
diff --git a/src/arena/adaptive.ts b/src/arena/adaptive.ts
index ffc8cb64..1c954278 100644
--- a/src/arena/adaptive.ts
+++ b/src/arena/adaptive.ts
@@ -100,9 +100,7 @@ export function pickNextPair(
const uncertainty = (stdErrOf(a) + stdErrOf(b)) / stdErrScale;
const informativeness =
- closenessWeight * closeness +
- uncertaintyWeight * uncertainty -
- repeatPenalty * seen;
+ closenessWeight * closeness + uncertaintyWeight * uncertainty - repeatPenalty * seen;
// Tie-break deterministically: earlier (a,b) in sorted order wins.
if (informativeness > bestScore) {
diff --git a/src/arena/bradley-terry.ts b/src/arena/bradley-terry.ts
index 489c81c2..e7e66679 100644
--- a/src/arena/bradley-terry.ts
+++ b/src/arena/bradley-terry.ts
@@ -165,7 +165,7 @@ export function fitBradleyTerry(
});
// Strongest first; tie-break by id for determinism.
- items.sort((a, b) => (b.strength - a.strength) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
+ items.sort((a, b) => b.strength - a.strength || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
return { items, iterations, converged };
}
diff --git a/src/inspect.ts b/src/inspect.ts
index 93f5cd60..c8b7e73b 100644
--- a/src/inspect.ts
+++ b/src/inspect.ts
@@ -183,7 +183,7 @@ function computeBoundingBox(root: THREE.Object3D): InspectBoundingBox {
function collectAnimationTracks(
root: THREE.Object3D,
- clips: THREE.AnimationClip[]
+ clips: THREE.AnimationClip[],
): InspectAnimationTrack[] {
const tracks: InspectAnimationTrack[] = [];
if (clips.length === 0) return tracks;
diff --git a/src/list-primitives.ts b/src/list-primitives.ts
index a288c02f..801026fb 100644
--- a/src/list-primitives.ts
+++ b/src/list-primitives.ts
@@ -92,17 +92,19 @@ const PRIMITIVES: PrimitiveSpec[] = [
},
{
name: 'snapTo',
- signature: "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
+ signature:
+ "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",
returns: 'THREE.Object3D (the part, for chaining)',
category: 'structure',
description:
'Translates `part` by the minimal vector that brings its bounding box into contact with `host` (plus a small overlap). The direct cure for a "Floating parts" warning — attach the part instead of eyeballing a corrective offset. No-op if they already touch.',
- example: "const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });\nsnapTo(scope, receiver);",
+ example:
+ "const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });\nsnapTo(scope, receiver);",
},
{
name: 'createLadder',
signature:
- "createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })",
+ 'createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, widthAxis?, parent? })',
returns: '{ leftRail: Object3D, rightRail: Object3D, rungs: Object3D[] }',
category: 'structure',
description:
@@ -186,18 +188,15 @@ const PRIMITIVES: PrimitiveSpec[] = [
signature: 'sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)',
returns: 'THREE.SphereGeometry',
category: 'geometry',
- description:
- 'UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.',
+ description: 'UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.',
example: 'const geo = sphereGeo(0.5, 12, 8);',
},
{
name: 'cylinderGeo',
- signature:
- 'cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)',
+ signature: 'cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)',
returns: 'THREE.CylinderGeometry',
category: 'geometry',
- description:
- 'Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.',
+ description: 'Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.',
example: 'const geo = cylinderGeo(0.25, 0.25, 1, 12);',
},
{
@@ -238,8 +237,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
category: 'geometry',
description:
'Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.',
- example:
- "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);",
+ example: 'const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);',
},
{
name: 'capsuleGeo',
@@ -254,7 +252,8 @@ const PRIMITIVES: PrimitiveSpec[] = [
signature: 'capsuleYGeo(radius: number, height: number, segments?: 6)',
returns: 'THREE.CapsuleGeometry',
category: 'geometry',
- description: 'Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.',
+ description:
+ 'Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.',
example: 'const geo = capsuleYGeo(0.1, 0.5, 6);',
},
{
@@ -288,7 +287,8 @@ const PRIMITIVES: PrimitiveSpec[] = [
signature: 'coneYGeo(radius: number, height: number, segments?: 8)',
returns: 'THREE.ConeGeometry',
category: 'geometry',
- description: 'Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.',
+ description:
+ 'Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.',
example: 'const geo = coneYGeo(0.3, 0.8, 8);',
},
{
@@ -321,8 +321,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
},
{
name: 'torusGeo',
- signature:
- 'torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)',
+ signature: 'torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)',
returns: 'THREE.TorusGeometry',
category: 'geometry',
description: 'Donut shape. For rings, tyres, barrel ribs.',
@@ -330,8 +329,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
},
{
name: 'planeGeo',
- signature:
- 'planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)',
+ signature: 'planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)',
returns: 'THREE.PlaneGeometry',
category: 'geometry',
description:
@@ -377,13 +375,11 @@ const PRIMITIVES: PrimitiveSpec[] = [
category: 'geometry',
description:
'Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas; the consumer shader adds per-instance tile offsets at draw time.',
- example:
- "const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });",
+ example: 'const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });',
},
{
name: 'wingGeo',
- signature:
- 'wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })',
+ signature: 'wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })',
returns: 'THREE.BufferGeometry',
category: 'geometry',
description:
@@ -423,9 +419,8 @@ const PRIMITIVES: PrimitiveSpec[] = [
'gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })',
returns: 'THREE.MeshStandardMaterial',
category: 'material',
- description:
- 'Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.',
- example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });",
+ description: 'Flat-shaded PBR material. Default for game-ready low-poly. Use for 95% of parts.',
+ example: 'const mat = gameMaterial(0x8b7355, { roughness: 0.9 });',
},
{
name: 'basicMaterial',
@@ -433,14 +428,15 @@ const PRIMITIVES: PrimitiveSpec[] = [
returns: 'THREE.MeshBasicMaterial',
category: 'material',
description: 'Unlit flat material. For UI / effects where lighting is baked in.',
- example: "const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });",
+ example: 'const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });',
},
{
name: 'glassMaterial',
signature: 'glassMaterial(color, opts?: { opacity, roughness, metalness })',
returns: 'THREE.MeshStandardMaterial',
category: 'material',
- description: 'Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.',
+ description:
+ 'Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.',
example: 'const mat = glassMaterial(0x66ccff, { opacity: 0.3 });',
},
{
@@ -449,7 +445,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
returns: 'THREE.MeshLambertMaterial',
category: 'material',
description: 'Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.',
- example: "const mat = lambertMaterial(0x2a4d14, { flatShading: true });",
+ example: 'const mat = lambertMaterial(0x2a4d14, { flatShading: true });',
},
// ---------------------------------------------------------------------------
@@ -550,7 +546,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
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. `rotation` is in DEGREES, like createPart.',
+ "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",
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 });",
},
@@ -572,7 +568,8 @@ const PRIMITIVES: PrimitiveSpec[] = [
},
{
name: 'boolDiff',
- signature: 'await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false })',
+ signature:
+ 'await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false })',
returns: 'Promise<THREE.Mesh>',
category: 'csg',
description:
@@ -582,13 +579,12 @@ const PRIMITIVES: PrimitiveSpec[] = [
},
{
name: 'boolIntersect',
- signature: 'await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })',
+ signature:
+ 'await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })',
returns: 'Promise<THREE.Mesh>',
category: 'csg',
- description:
- 'Keeps only the volume where both operands overlap. Default flat shading.',
- example:
- "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);",
+ description: 'Keeps only the volume where both operands overlap. Default flat shading.',
+ example: "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);",
},
{
name: 'hull',
@@ -606,8 +602,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
// ---------------------------------------------------------------------------
{
name: 'arrayLinear',
- signature:
- 'arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)',
+ signature: 'arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)',
returns: 'THREE.Object3D[]',
category: 'arrays',
description:
@@ -617,8 +612,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
},
{
name: 'arrayRadial',
- signature:
- "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
+ signature: "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?)",
returns: 'THREE.Object3D[]',
category: 'arrays',
description:
@@ -632,7 +626,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
returns: 'THREE.Object3D',
category: 'arrays',
description:
- "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",
+ 'Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).',
example: "mirror('WingR', wingL, 'x', root);",
},
@@ -647,7 +641,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
category: 'mesh-ops',
description:
'Loop subdivision. Each iteration ~4x the triangle count and smooths the surface. Non-indexed input is auto-welded via mergeVertices (weld: false to skip). Use 1 for mild smoothing, 2 for organic shapes.',
- example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);",
+ example: 'const smoothRock = subdivide(boxGeo(1, 1, 1), 2);',
},
{
name: 'mergeVertices',
@@ -671,8 +665,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
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);",
+ example: 'const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);',
},
{
name: 'pipeAlongPath',
@@ -683,7 +676,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
description:
'Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.',
example:
- "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });",
+ 'const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });',
},
{
name: 'lathe',
@@ -692,8 +685,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
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);",
+ example: 'const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);',
},
{
name: 'revolveGeo',
@@ -704,7 +696,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
description:
'Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.',
example:
- "// Half-dome (180° sweep around +Y):\nconst quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });\nconst dome = revolveGeo(quarter, { angle: Math.PI });",
+ '// Half-dome (180° sweep around +Y):\nconst quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });\nconst dome = revolveGeo(quarter, { angle: Math.PI });',
},
{
name: 'bezierCurve',
@@ -712,9 +704,9 @@ const PRIMITIVES: PrimitiveSpec[] = [
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.",
+ '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);",
+ 'const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);\nconst geo = curveToMesh(path, 0.1);',
},
// ---------------------------------------------------------------------------
@@ -727,9 +719,9 @@ const PRIMITIVES: PrimitiveSpec[] = [
returns: 'Promise<THREE.BufferGeometry>',
category: 'uv',
description:
- "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",
+ 'xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.',
example:
- "const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });\nconst mesh = new THREE.Mesh(unwrapped, bakedPbr);",
+ 'const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });\nconst mesh = new THREE.Mesh(unwrapped, bakedPbr);',
},
{
name: 'boxUnwrap',
@@ -739,7 +731,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
description:
"Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",
example:
- "const crate = boxUnwrap(boxGeo(1, 1, 1));\nconst mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));",
+ 'const crate = boxUnwrap(boxGeo(1, 1, 1));\nconst mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));',
},
{
name: 'cylinderUnwrap',
@@ -749,7 +741,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
description:
"Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",
example:
- "const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));\nconst mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));",
+ 'const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));\nconst mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));',
},
{
name: 'planeUnwrap',
@@ -757,9 +749,9 @@ const PRIMITIVES: PrimitiveSpec[] = [
returns: 'THREE.BufferGeometry',
category: 'uv',
description:
- "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",
+ 'Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.',
example:
- "const sign = planeUnwrap(planeGeo(1, 0.6));\nconst mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));",
+ 'const sign = planeUnwrap(planeGeo(1, 0.6));\nconst mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));',
},
{
name: 'panelRemapV',
@@ -767,9 +759,9 @@ const PRIMITIVES: PrimitiveSpec[] = [
returns: 'THREE.BufferGeometry',
category: 'uv',
description:
- "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
+ 'Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.',
example:
- "const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);\nconst cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed",
+ 'const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);\nconst cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed',
},
// ---------------------------------------------------------------------------
@@ -782,15 +774,13 @@ const PRIMITIVES: PrimitiveSpec[] = [
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');",
+ example: "const wood = await loadTexture('./textures/oak-albedo.png');",
promptNotes:
'NEVER texture.clone() a loaded texture (clone() corrupts the encoded bytes and breaks GLB export). Share the same Texture object and remap UVs with panelRemapV on the smaller mesh instead.',
},
{
name: 'pbrMaterial',
- signature:
- 'pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? })',
+ signature: 'pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? })',
returns: 'THREE.MeshStandardMaterial',
category: 'material',
description:
@@ -808,7 +798,7 @@ const PRIMITIVES: PrimitiveSpec[] = [
returns: 'number',
category: 'utility',
description: 'Sums triangle count across every mesh in the subtree.',
- example: "meta.tris = countTriangles(root);",
+ example: 'meta.tris = countTriangles(root);',
},
{
name: 'countMaterials',
@@ -824,11 +814,12 @@ const PRIMITIVES: PrimitiveSpec[] = [
returns: 'string[]',
category: 'utility',
description: 'All node names beginning with `Joint_`. Use to sanity-check animation targets.',
- example: "const joints = getJointNames(root);",
+ example: 'const joints = getJointNames(root);',
},
{
name: 'validateAsset',
- signature: "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment')",
+ signature:
+ "validateAsset(root: Object3D, category: 'character' | 'prop' | 'vfx' | 'environment')",
returns: '{ valid, errors, warnings }',
category: 'utility',
description: 'Warns on category-appropriate triangle / material budgets.',
diff --git a/src/metrics.ts b/src/metrics.ts
index 9ba48b1a..28d9b08a 100644
--- a/src/metrics.ts
+++ b/src/metrics.ts
@@ -173,7 +173,9 @@ export function gradeInstanceability(
// Skinned: informational, NOT a grade penalty. Clone-rendered by design.
if (m.skinned) {
- reasons.push('skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts');
+ reasons.push(
+ 'skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts',
+ );
}
if (opts.category) reasons.push(`category: ${opts.category}`);
diff --git a/src/ops.ts b/src/ops.ts
index a2094bdf..f01c6ca5 100644
--- a/src/ops.ts
+++ b/src/ops.ts
@@ -37,7 +37,7 @@ export function arrayLinear(
source: THREE.Object3D,
count: number,
offset: [number, number, number],
- parent?: THREE.Object3D
+ parent?: THREE.Object3D,
): THREE.Object3D[] {
const out: THREE.Object3D[] = [];
// Source is already at some position; clones start at offset 1.
@@ -67,7 +67,7 @@ export function arrayRadial(
source: THREE.Object3D,
count: number,
axis: 'x' | 'y' | 'z' = 'y',
- parent?: THREE.Object3D
+ parent?: THREE.Object3D,
): THREE.Object3D[] {
const out: THREE.Object3D[] = [];
const basePos = source.position.clone();
@@ -94,7 +94,7 @@ export function arrayRadial(
position: [rotated.x, rotated.y, rotated.z],
rotation: eulerDeg,
parent,
- })
+ }),
);
}
return out;
@@ -112,7 +112,7 @@ export function mirror(
name: string,
source: THREE.Object3D,
axis: 'x' | 'y' | 'z',
- parent?: THREE.Object3D
+ parent?: THREE.Object3D,
): THREE.Object3D {
const sourcePos = source.position.toArray() as [number, number, number];
const pos: [number, number, number] = [
@@ -157,7 +157,7 @@ export function mirror(
*/
export function mergeVertices(
geometry: THREE.BufferGeometry,
- opts: { tolerance?: number; positionOnly?: boolean } | number = {}
+ opts: { tolerance?: number; positionOnly?: boolean } | number = {},
): THREE.BufferGeometry {
// Legacy numeric second-arg still works: mergeVertices(geo, 1e-4)
const { tolerance = 1e-4, positionOnly = false } =
@@ -171,7 +171,7 @@ export function mergeVertices(
if (!pos) return geometry;
stripped.setAttribute(
'position',
- new THREE.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized)
+ new THREE.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized),
);
if (geometry.index) {
stripped.setIndex(new THREE.BufferAttribute(new Uint32Array(geometry.index.array), 1));
@@ -202,7 +202,7 @@ export function subdivide(
preserveEdges?: boolean;
flatOnly?: boolean;
weld?: boolean;
- } = {}
+ } = {},
): THREE.BufferGeometry {
const { weld = true, ...subOpts } = opts;
// Subdivision wants position-only adjacency. Weld shared corners so
@@ -235,7 +235,7 @@ export function curveToMesh(
radius: number,
tubularSegments = 32,
radialSegments = 8,
- closed = false
+ 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);
@@ -249,10 +249,7 @@ export function curveToMesh(
* @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 {
+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);
}
@@ -289,7 +286,7 @@ export function revolveGeo(
angle?: number;
axis?: [number, number, number];
segments?: number;
- } = {}
+ } = {},
): THREE.BufferGeometry {
const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;
const points2d = profile.map((p) => new THREE.Vector2(p[0], p[1]));
@@ -340,19 +337,12 @@ export function pipeAlongPath(
closed?: boolean;
tubularSegments?: number;
radialSegments?: number;
- } = {}
+ } = {},
): THREE.BufferGeometry {
- const {
- bendRadius = 0,
- closed = false,
- tubularSegments = 32,
- radialSegments = 8,
- } = options;
+ const { bendRadius = 0, closed = false, tubularSegments = 32, radialSegments = 8 } = options;
if (points.length < 2) {
- throw new Error(
- `pipeAlongPath: need at least 2 points (got ${points.length}).`
- );
+ throw new Error(`pipeAlongPath: need at least 2 points (got ${points.length}).`);
}
let pathPoints = points;
@@ -400,7 +390,7 @@ export function pipeAlongPath(
*/
export function bezierCurve(
controlPoints: Array<[number, number, number]>,
- samples = 32
+ 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>;
diff --git a/src/palette-snap.ts b/src/palette-snap.ts
index 2ca0bfa4..c4d4008c 100644
--- a/src/palette-snap.ts
+++ b/src/palette-snap.ts
@@ -31,7 +31,7 @@ export type Vec3 = [number, number, number];
// ── sRGB → linear. Matches three's SRGBToLinear (the gamma transfer function),
// so a slot hex yields the same linear value the GLB's linear factors carry. ──
function srgbChannelToLinear(c: number): number {
- return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
}
/** Parse an sRGB hex (`#rrggbb` or `rrggbb`) to LINEAR RGB in [0..1]. */
@@ -51,7 +51,9 @@ export function linToOklab(r: number, g: number, b: number): Vec3 {
const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
- const l_ = Math.cbrt(l), m_ = Math.cbrt(m), s_ = Math.cbrt(s);
+ const l_ = Math.cbrt(l),
+ m_ = Math.cbrt(m),
+ s_ = Math.cbrt(s);
return [
0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,
1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,
@@ -60,7 +62,9 @@ export function linToOklab(r: number, g: number, b: number): Vec3 {
}
const dE2 = (a: Vec3, b: Vec3): number => {
- const dl = a[0] - b[0], da = a[1] - b[1], db = a[2] - b[2];
+ const dl = a[0] - b[0],
+ da = a[1] - b[1],
+ db = a[2] - b[2];
return dl * dl + da * da + db * db;
};
// CHROMATIC distance with lightness DOWN-WEIGHTED — full OKLab over-weights L, so a
@@ -68,7 +72,9 @@ const dE2 = (a: Vec3, b: Vec3): number => {
// GREEN. Weighting hue/chroma above L makes "what colour is it" win over "how bright".
const L_WEIGHT_CHROMA = 0.3;
const dE2Chroma = (a: Vec3, b: Vec3): number => {
- const dl = a[0] - b[0], da = a[1] - b[1], db = a[2] - b[2];
+ const dl = a[0] - b[0],
+ da = a[1] - b[1],
+ db = a[2] - b[2];
return L_WEIGHT_CHROMA * dl * dl + da * da + db * db;
};
const chroma = (lab: Vec3): number => Math.hypot(lab[1], lab[2]);
@@ -78,7 +84,10 @@ const chroma = (lab: Vec3): number => Math.hypot(lab[1], lab[2]);
const REL_CHROMA_GATE = 0.04;
const relChroma = (lab: Vec3): number => chroma(lab) / Math.max(lab[0], 0.25);
-interface SlotLab { i: number; lab: Vec3 }
+interface SlotLab {
+ i: number;
+ lab: Vec3;
+}
/** Precomputed OKLab partition of a palette — built once per snap, reused per material. */
export interface SlotIndex {
@@ -106,8 +115,14 @@ export function buildSlotIndex(slots: readonly SnapSlot[]): SlotIndex {
const kind = s.kind ?? 'opaque';
const [r, g, b] = hexToLinearRgb(s.color);
const lab = linToOklab(r, g, b);
- if (kind === 'glass') { glass.push(i); return; }
- if (kind === 'glow') { glow.push({ i, lab }); return; }
+ if (kind === 'glass') {
+ glass.push(i);
+ return;
+ }
+ if (kind === 'glow') {
+ glow.push({ i, lab });
+ return;
+ }
opaque.push({ i, lab });
if (relChroma(lab) >= REL_CHROMA_GATE) chromatic.push({ i, lab });
else neutral.push({ i, lab });
@@ -116,8 +131,15 @@ export function buildSlotIndex(slots: readonly SnapSlot[]): SlotIndex {
}
function nearestIn(cands: SlotLab[], lab: Vec3, dist: (a: Vec3, b: Vec3) => number): number {
- let best = cands[0]!.i, bd = Infinity;
- for (const c of cands) { const d = dist(c.lab, lab); if (d < bd) { bd = d; best = c.i; } }
+ let best = cands[0]!.i,
+ bd = Infinity;
+ for (const c of cands) {
+ const d = dist(c.lab, lab);
+ if (d < bd) {
+ bd = d;
+ best = c.i;
+ }
+ }
return best;
}
@@ -126,7 +148,9 @@ export function nearestOpaqueSlot(idx: SlotIndex, lin: Vec3): number | undefined
if (idx.opaque.length === 0) return undefined;
const lab = linToOklab(lin[0], lin[1], lin[2]);
if (relChroma(lab) >= REL_CHROMA_GATE) {
- return idx.chromatic.length ? nearestIn(idx.chromatic, lab, dE2Chroma) : nearestIn(idx.opaque, lab, dE2);
+ return idx.chromatic.length
+ ? nearestIn(idx.chromatic, lab, dE2Chroma)
+ : nearestIn(idx.opaque, lab, dE2);
}
return idx.neutral.length ? nearestIn(idx.neutral, lab, dE2) : nearestIn(idx.opaque, lab, dE2);
}
@@ -161,11 +185,15 @@ export function chooseSlot(idx: SlotIndex, m: MaterialColor): number | undefined
// Pick the glass slot nearest the source base color (palettes rarely have >1).
if (idx.glass.length === 1) return idx.glass[0];
const lab = linToOklab(m.baseLinear[0], m.baseLinear[1], m.baseLinear[2]);
- let best = idx.glass[0]!, bd = Infinity;
+ let best = idx.glass[0]!,
+ bd = Infinity;
for (const gi of idx.glass) {
const [r, g, b] = hexToLinearRgb(idx.slots[gi]!.color);
const d = dE2(linToOklab(r, g, b), lab);
- if (d < bd) { bd = d; best = gi; }
+ if (d < bd) {
+ bd = d;
+ best = gi;
+ }
}
return best;
}
diff --git a/src/palette.ts b/src/palette.ts
index 213daad5..a2a8f072 100644
--- a/src/palette.ts
+++ b/src/palette.ts
@@ -49,25 +49,161 @@ export interface PaletteSlot {
* simple (opaque everything + the one glass slot).
*/
export const OPTIMIZED_PALETTE: readonly PaletteSlot[] = [
- { index: 0, name: 'steel', color: '#8a8f99', metalness: 0.9, roughness: 0.5, use: 'bare metal, blades, machinery, hulls' },
- { index: 1, name: 'gunmetal', color: '#3a3f47', metalness: 0.9, roughness: 0.45, use: 'dark metal, weapons, iron fittings' },
- { index: 2, name: 'brass', color: '#c8a64b', metalness: 0.95, roughness: 0.4, use: 'gold/brass trim, horns, ornament' },
- { index: 3, name: 'copper', color: '#b06a3a', metalness: 0.9, roughness: 0.45, use: 'copper/bronze, worn metal' },
- { index: 4, name: 'wood', color: '#9a6a3c', metalness: 0.0, roughness: 0.8, use: 'planks, handles, crates, trunks' },
- { index: 5, name: 'dark-wood', color: '#5a3a22', metalness: 0.0, roughness: 0.8, use: 'aged timber, bark, framing' },
- { index: 6, name: 'stone', color: '#8d8a82', metalness: 0.0, roughness: 0.95, use: 'rock, masonry, boulders' },
- { index: 7, name: 'concrete', color: '#b8b4ad', metalness: 0.0, roughness: 0.95, use: 'concrete, plaster, pale walls' },
- { index: 8, name: 'brick', color: '#9e4b34', metalness: 0.0, roughness: 0.9, use: 'brick, terracotta, clay' },
- { index: 9, name: 'sand', color: '#cdb27a', metalness: 0.0, roughness: 1.0, use: 'sand, adobe, tan earth' },
- { index: 10, name: 'dirt', color: '#5b4632', metalness: 0.0, roughness: 1.0, use: 'soil, mud, dark ground' },
- { index: 11, name: 'foliage', color: '#4f8f3f', metalness: 0.0, roughness: 0.9, use: 'leaves, grass, plants' },
- { index: 12, name: 'glass', color: '#aacbe0', metalness: 0.0, roughness: 0.1, transparent: true, opacity: 0.35, use: 'windows, lenses — the ONE transparent slot' },
- { index: 13, name: 'white', color: '#e8e8e6', metalness: 0.0, roughness: 0.7, use: 'white paint, cloth, paper' },
- { index: 14, name: 'black', color: '#1a1c1f', metalness: 0.0, roughness: 0.6, use: 'black, rubber, charred, tires' },
- { index: 15, name: 'accent-warm', color: '#c0392b', metalness: 0.0, roughness: 0.7, use: 'red/orange paint, flags, signs' },
- { index: 16, name: 'accent-cool', color: '#2f6fd0', metalness: 0.0, roughness: 0.7, use: 'blue/teal paint, water, signs' },
- { index: 17, name: 'skin', color: '#c8946a', metalness: 0.0, roughness: 0.75, use: 'character skin / flesh' },
- { index: 18, name: 'glow', color: '#ffd9a0', metalness: 0.0, roughness: 1.0, emissive: true, use: 'lamps, neon, fire cores, vfx — the ONE emissive slot' },
+ {
+ index: 0,
+ name: 'steel',
+ color: '#8a8f99',
+ metalness: 0.9,
+ roughness: 0.5,
+ use: 'bare metal, blades, machinery, hulls',
+ },
+ {
+ index: 1,
+ name: 'gunmetal',
+ color: '#3a3f47',
+ metalness: 0.9,
+ roughness: 0.45,
+ use: 'dark metal, weapons, iron fittings',
+ },
+ {
+ index: 2,
+ name: 'brass',
+ color: '#c8a64b',
+ metalness: 0.95,
+ roughness: 0.4,
+ use: 'gold/brass trim, horns, ornament',
+ },
+ {
+ index: 3,
+ name: 'copper',
+ color: '#b06a3a',
+ metalness: 0.9,
+ roughness: 0.45,
+ use: 'copper/bronze, worn metal',
+ },
+ {
+ index: 4,
+ name: 'wood',
+ color: '#9a6a3c',
+ metalness: 0.0,
+ roughness: 0.8,
+ use: 'planks, handles, crates, trunks',
+ },
+ {
+ index: 5,
+ name: 'dark-wood',
+ color: '#5a3a22',
+ metalness: 0.0,
+ roughness: 0.8,
+ use: 'aged timber, bark, framing',
+ },
+ {
+ index: 6,
+ name: 'stone',
+ color: '#8d8a82',
+ metalness: 0.0,
+ roughness: 0.95,
+ use: 'rock, masonry, boulders',
+ },
+ {
+ index: 7,
+ name: 'concrete',
+ color: '#b8b4ad',
+ metalness: 0.0,
+ roughness: 0.95,
+ use: 'concrete, plaster, pale walls',
+ },
+ {
+ index: 8,
+ name: 'brick',
+ color: '#9e4b34',
+ metalness: 0.0,
+ roughness: 0.9,
+ use: 'brick, terracotta, clay',
+ },
+ {
+ index: 9,
+ name: 'sand',
+ color: '#cdb27a',
+ metalness: 0.0,
+ roughness: 1.0,
+ use: 'sand, adobe, tan earth',
+ },
+ {
+ index: 10,
+ name: 'dirt',
+ color: '#5b4632',
+ metalness: 0.0,
+ roughness: 1.0,
+ use: 'soil, mud, dark ground',
+ },
+ {
+ index: 11,
+ name: 'foliage',
+ color: '#4f8f3f',
+ metalness: 0.0,
+ roughness: 0.9,
+ use: 'leaves, grass, plants',
+ },
+ {
+ index: 12,
+ name: 'glass',
+ color: '#aacbe0',
+ metalness: 0.0,
+ roughness: 0.1,
+ transparent: true,
+ opacity: 0.35,
+ use: 'windows, lenses — the ONE transparent slot',
+ },
+ {
+ index: 13,
+ name: 'white',
+ color: '#e8e8e6',
+ metalness: 0.0,
+ roughness: 0.7,
+ use: 'white paint, cloth, paper',
+ },
+ {
+ index: 14,
+ name: 'black',
+ color: '#1a1c1f',
+ metalness: 0.0,
+ roughness: 0.6,
+ use: 'black, rubber, charred, tires',
+ },
+ {
+ index: 15,
+ name: 'accent-warm',
+ color: '#c0392b',
+ metalness: 0.0,
+ roughness: 0.7,
+ use: 'red/orange paint, flags, signs',
+ },
+ {
+ index: 16,
+ name: 'accent-cool',
+ color: '#2f6fd0',
+ metalness: 0.0,
+ roughness: 0.7,
+ use: 'blue/teal paint, water, signs',
+ },
+ {
+ index: 17,
+ name: 'skin',
+ color: '#c8946a',
+ metalness: 0.0,
+ roughness: 0.75,
+ use: 'character skin / flesh',
+ },
+ {
+ index: 18,
+ name: 'glow',
+ color: '#ffd9a0',
+ metalness: 0.0,
+ roughness: 1.0,
+ emissive: true,
+ use: 'lamps, neon, fire cores, vfx — the ONE emissive slot',
+ },
];
/**
diff --git a/src/primitives.ts b/src/primitives.ts
index 3d2aa09d..7f4ec519 100644
--- a/src/primitives.ts
+++ b/src/primitives.ts
@@ -43,7 +43,7 @@ export function createRoot(name: string): THREE.Object3D {
export function createPivot(
name: string,
position: [number, number, number] = [0, 0, 0],
- parent?: THREE.Object3D
+ parent?: THREE.Object3D,
): THREE.Object3D {
const pivot = new THREE.Object3D();
pivot.name = `Joint_${name}`;
@@ -69,17 +69,18 @@ export function createPart(
scale?: [number, number, number];
pivot?: boolean; // Wrap in pivot for animation
parent?: THREE.Object3D;
- } = {}
+ } = {},
): THREE.Object3D {
const mesh = new THREE.Mesh(geometry, 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.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.pivot) {
@@ -100,29 +101,17 @@ export function createPart(
// Common Shapes (game-ready low-poly)
// =============================================================================
-export function capsuleGeo(
- radius: number,
- height: number,
- segments = 6
-): THREE.CapsuleGeometry {
+export function capsuleGeo(radius: number, height: number, segments = 6): THREE.CapsuleGeometry {
return new THREE.CapsuleGeometry(radius, height, 2, segments);
}
-export function capsuleXGeo(
- radius: number,
- length: number,
- segments = 6
-): THREE.CapsuleGeometry {
+export function capsuleXGeo(radius: number, length: number, segments = 6): THREE.CapsuleGeometry {
const geo = capsuleGeo(radius, length, segments);
geo.rotateZ(-Math.PI / 2);
return geo;
}
-export function capsuleZGeo(
- radius: number,
- length: number,
- segments = 6
-): THREE.CapsuleGeometry {
+export function capsuleZGeo(radius: number, length: number, segments = 6): THREE.CapsuleGeometry {
const geo = capsuleGeo(radius, length, segments);
geo.rotateX(Math.PI / 2);
return geo;
@@ -132,7 +121,7 @@ export function cylinderGeo(
radiusTop: number,
radiusBottom: number,
height: number,
- segments = 8
+ segments = 8,
): THREE.CylinderGeometry {
return new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments);
}
@@ -141,7 +130,7 @@ export function cylinderXGeo(
radiusTop: number,
radiusBottom: number,
length: number,
- segments = 8
+ segments = 8,
): THREE.CylinderGeometry {
const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);
geo.rotateZ(-Math.PI / 2);
@@ -152,52 +141,36 @@ export function cylinderZGeo(
radiusTop: number,
radiusBottom: number,
length: number,
- segments = 8
+ segments = 8,
): THREE.CylinderGeometry {
const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);
geo.rotateX(Math.PI / 2);
return geo;
}
-export function boxGeo(
- width: number,
- height: number,
- depth: number
-): THREE.BoxGeometry {
+export function boxGeo(width: number, height: number, depth: number): THREE.BoxGeometry {
return new THREE.BoxGeometry(width, height, depth);
}
export function sphereGeo(
radius: number,
widthSegments = 8,
- heightSegments = 6
+ heightSegments = 6,
): THREE.SphereGeometry {
return new THREE.SphereGeometry(radius, widthSegments, heightSegments);
}
-export function coneGeo(
- radius: number,
- height: number,
- segments = 8
-): THREE.ConeGeometry {
+export function coneGeo(radius: number, height: number, segments = 8): THREE.ConeGeometry {
return new THREE.ConeGeometry(radius, height, segments);
}
-export function coneXGeo(
- radius: number,
- length: number,
- segments = 8
-): THREE.ConeGeometry {
+export function coneXGeo(radius: number, length: number, segments = 8): THREE.ConeGeometry {
const geo = coneGeo(radius, length, segments);
geo.rotateZ(-Math.PI / 2);
return geo;
}
-export function coneZGeo(
- radius: number,
- length: number,
- segments = 8
-): THREE.ConeGeometry {
+export function coneZGeo(radius: number, length: number, segments = 8): THREE.ConeGeometry {
const geo = coneGeo(radius, length, segments);
geo.rotateX(Math.PI / 2);
return geo;
@@ -230,7 +203,7 @@ export function cylinderOnAxis(
normal: Vec3Tuple,
radiusBottom: number,
height: number,
- options: { radiusTop?: number; segments?: number } = {}
+ options: { radiusTop?: number; segments?: number } = {},
): THREE.CylinderGeometry {
const radiusTop = options.radiusTop ?? radiusBottom;
const segments = options.segments ?? 8;
@@ -240,16 +213,13 @@ export function cylinderOnAxis(
const len = n.length();
if (len < 1e-6) {
throw new Error(
- `cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(',')}]).`
+ `cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(',')}]).`,
);
}
n.divideScalar(len);
// Quaternion from Y to normal.
- const q = new THREE.Quaternion().setFromUnitVectors(
- new THREE.Vector3(0, 1, 0),
- n
- );
+ const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
geo.translate(center[0], center[1], center[2]);
return geo;
@@ -272,7 +242,7 @@ export function taperConeGeo(
radiusTop: number,
height: number,
axis: 'x' | 'y' | 'z' = 'y',
- segments = 8
+ segments = 8,
): THREE.CylinderGeometry {
const geo = new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments);
if (axis === 'x') geo.rotateZ(-Math.PI / 2);
@@ -284,7 +254,7 @@ export function torusGeo(
radius: number,
tube: number,
radialSegments = 8,
- tubularSegments = 12
+ tubularSegments = 12,
): THREE.TorusGeometry {
return new THREE.TorusGeometry(radius, tube, radialSegments, tubularSegments);
}
@@ -293,7 +263,7 @@ export function planeGeo(
width: number,
height: number,
widthSegments = 1,
- heightSegments = 1
+ heightSegments = 1,
): THREE.PlaneGeometry {
return new THREE.PlaneGeometry(width, height, widthSegments, heightSegments);
}
@@ -319,11 +289,7 @@ export function planeGeo(
* });
* ```
*/
-export function decalBox(
- width: number,
- height: number,
- depth: number = 0.01,
-): THREE.BoxGeometry {
+export function decalBox(width: number, height: number, depth: number = 0.01): THREE.BoxGeometry {
const d = Math.max(depth, 0.002);
return new THREE.BoxGeometry(width, height, d);
}
@@ -392,10 +358,7 @@ export function crossedQuadsGeo(opts: CrossedQuadsOptions = {}): THREE.BufferGeo
// Merge into one BufferGeometry — deterministic + cheaper at draw time.
const out = new THREE.BufferGeometry();
- const posCount = geometries.reduce(
- (sum, g) => sum + (g.attributes.position?.count ?? 0),
- 0,
- );
+ const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);
const positions = new Float32Array(posCount * 3);
const normals = new Float32Array(posCount * 3);
const uvs = new Float32Array(posCount * 2);
@@ -513,23 +476,69 @@ export function wingGeo(options: WingGeometryOptions = {}): THREE.BufferGeometry
const halfThickness = thickness / 2;
const vertices = new Float32Array([
- rootLead, halfThickness, 0,
- rootTrail, halfThickness, 0,
- tipLead, dihedral + halfThickness, span,
- tipTrail, dihedral + halfThickness, span,
- rootLead, -halfThickness, 0,
- rootTrail, -halfThickness, 0,
- tipLead, dihedral - halfThickness, span,
- tipTrail, dihedral - halfThickness, span,
+ rootLead,
+ halfThickness,
+ 0,
+ rootTrail,
+ halfThickness,
+ 0,
+ tipLead,
+ dihedral + halfThickness,
+ span,
+ tipTrail,
+ dihedral + halfThickness,
+ span,
+ rootLead,
+ -halfThickness,
+ 0,
+ rootTrail,
+ -halfThickness,
+ 0,
+ tipLead,
+ dihedral - halfThickness,
+ span,
+ tipTrail,
+ dihedral - halfThickness,
+ span,
]);
const indices = [
- 0, 3, 2, 0, 1, 3, // top
- 4, 6, 7, 4, 7, 5, // bottom
- 0, 2, 6, 0, 6, 4, // leading edge
- 1, 5, 7, 1, 7, 3, // trailing edge
- 0, 4, 5, 0, 5, 1, // root cap
- 2, 3, 7, 2, 7, 6, // tip cap
+ 0,
+ 3,
+ 2,
+ 0,
+ 1,
+ 3, // top
+ 4,
+ 6,
+ 7,
+ 4,
+ 7,
+ 5, // bottom
+ 0,
+ 2,
+ 6,
+ 0,
+ 6,
+ 4, // leading edge
+ 1,
+ 5,
+ 7,
+ 1,
+ 7,
+ 3, // trailing edge
+ 0,
+ 4,
+ 5,
+ 0,
+ 5,
+ 1, // root cap
+ 2,
+ 3,
+ 7,
+ 2,
+ 7,
+ 6, // tip cap
];
const geo = new THREE.BufferGeometry();
@@ -550,7 +559,7 @@ export interface WingPairOptions extends WingGeometryOptions {
export function createWingPair(
name: string,
material: THREE.Material,
- options: WingPairOptions
+ options: WingPairOptions,
): { right: THREE.Object3D; left: THREE.Object3D } {
const { parent, rootX = 0, rootY = 0, rootZ, ...wingOptions } = options;
const rightGeo = wingGeo(wingOptions);
@@ -581,7 +590,7 @@ export function beamBetween(
end: Vec3Tuple,
radius: number,
material: THREE.Material,
- options: BeamBetweenOptions = {}
+ options: BeamBetweenOptions = {},
): THREE.Object3D {
const a = new THREE.Vector3(...start);
const b = new THREE.Vector3(...end);
@@ -594,16 +603,10 @@ export function beamBetween(
);
}
- const mesh = new THREE.Mesh(
- cylinderGeo(radius, radius, length, options.segments ?? 8),
- material
- );
+ const mesh = new THREE.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
mesh.name = `Mesh_${name}`;
mesh.position.copy(a.add(b).multiplyScalar(0.5));
- mesh.quaternion.setFromUnitVectors(
- new THREE.Vector3(0, 1, 0),
- direction.normalize()
- );
+ mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize());
if (options.parent) options.parent.add(mesh);
return mesh;
@@ -680,7 +683,7 @@ export interface LadderOptions {
export function createLadder(
name: string,
- options: LadderOptions
+ options: LadderOptions,
): { leftRail: THREE.Object3D; rightRail: THREE.Object3D; rungs: THREE.Object3D[] } {
const {
bottom,
@@ -698,9 +701,7 @@ export function createLadder(
const bottomVec = new THREE.Vector3(...bottom);
const topVec = new THREE.Vector3(...top);
const offset =
- widthAxis === 'x'
- ? new THREE.Vector3(width / 2, 0, 0)
- : new THREE.Vector3(0, 0, width / 2);
+ widthAxis === 'x' ? new THREE.Vector3(width / 2, 0, 0) : new THREE.Vector3(0, 0, width / 2);
const leftBottom = bottomVec.clone().sub(offset);
const leftTop = topVec.clone().sub(offset);
@@ -713,7 +714,7 @@ export function createLadder(
vectorToTuple(leftTop),
railRadius,
material,
- { parent, segments }
+ { parent, segments },
);
const rightRail = beamBetween(
`${name}RightRail`,
@@ -721,7 +722,7 @@ export function createLadder(
vectorToTuple(rightTop),
railRadius,
material,
- { parent, segments }
+ { parent, segments },
);
const rungs: THREE.Object3D[] = [];
@@ -735,8 +736,8 @@ export function createLadder(
vectorToTuple(center.clone().add(offset)),
rungRadius,
material,
- { parent, segments }
- )
+ { parent, segments },
+ ),
);
}
@@ -867,7 +868,11 @@ export function room(
name: string,
material: THREE.Material,
options: RoomOptions = {},
-): { root: THREE.Object3D; walls: Record<'front' | 'back' | 'left' | 'right', THREE.Object3D>; floor: THREE.Object3D | null } {
+): {
+ root: THREE.Object3D;
+ walls: Record<'front' | 'back' | 'left' | 'right', THREE.Object3D>;
+ floor: THREE.Object3D | null;
+} {
const {
width = 4,
depth = 4,
@@ -957,7 +962,15 @@ export function createRoofPlanes(
material: THREE.Material,
options: RoofPlanesOptions,
): { root: THREE.Object3D; slopes: [THREE.Object3D, THREE.Object3D] } {
- const { width, depth, height, overhang = 0.3, ridgeAxis = 'x', thickness = 0.08, parent } = options;
+ const {
+ width,
+ depth,
+ height,
+ overhang = 0.3,
+ ridgeAxis = 'x',
+ thickness = 0.08,
+ parent,
+ } = options;
const group = new THREE.Object3D();
group.name = name;
@@ -971,7 +984,9 @@ export function createRoofPlanes(
const slopes: THREE.Object3D[] = [];
for (const side of [1, -1] as const) {
const geo =
- ridgeAxis === 'x' ? boxGeo(ridgeLen, thickness, rafterLen) : boxGeo(rafterLen, thickness, ridgeLen);
+ ridgeAxis === 'x'
+ ? boxGeo(ridgeLen, thickness, rafterLen)
+ : boxGeo(rafterLen, thickness, ridgeLen);
const mesh = new THREE.Mesh(geo, material);
mesh.name = `Mesh_${name}${side > 0 ? 'A' : 'B'}`;
if (ridgeAxis === 'x') {
@@ -1047,15 +1062,23 @@ export function createStairs(
const topY = (i + 1) * stepRise;
const alongC = (i + 0.5) * stepRun;
const treadGeo =
- axis === 'x' ? boxGeo(stepRun, treadThickness, width) : boxGeo(width, treadThickness, stepRun);
+ axis === 'x'
+ ? boxGeo(stepRun, treadThickness, width)
+ : boxGeo(width, treadThickness, stepRun);
const treadPos: [number, number, number] =
- axis === 'x' ? [alongC, topY - treadThickness / 2, 0] : [0, topY - treadThickness / 2, alongC];
- stepList.push(createPart(`${name}Step${i + 1}`, treadGeo, material, { position: treadPos, parent: root }));
+ axis === 'x'
+ ? [alongC, topY - treadThickness / 2, 0]
+ : [0, topY - treadThickness / 2, alongC];
+ stepList.push(
+ createPart(`${name}Step${i + 1}`, treadGeo, material, { position: treadPos, parent: root }),
+ );
if (riser) {
const front = i * stepRun;
const riserGeo =
- axis === 'x' ? boxGeo(treadThickness, stepRise, width) : boxGeo(width, stepRise, treadThickness);
+ axis === 'x'
+ ? boxGeo(treadThickness, stepRise, width)
+ : boxGeo(width, stepRise, treadThickness);
const riserPos: [number, number, number] =
axis === 'x'
? [front + treadThickness / 2, topY - stepRise / 2, 0]
@@ -1080,7 +1103,7 @@ export function gameMaterial(
emissive?: number | string;
emissiveIntensity?: number;
flatShading?: boolean;
- } = {}
+ } = {},
): THREE.MeshStandardMaterial {
return new THREE.MeshStandardMaterial({
color,
@@ -1094,7 +1117,7 @@ export function gameMaterial(
export function basicMaterial(
color: number | string,
- options: { transparent?: boolean; opacity?: number } = {}
+ options: { transparent?: boolean; opacity?: number } = {},
): THREE.MeshBasicMaterial {
return new THREE.MeshBasicMaterial({
color,
@@ -1105,7 +1128,7 @@ export function basicMaterial(
export function glassMaterial(
color: number | string,
- options: { opacity?: number; roughness?: number; metalness?: number } = {}
+ options: { opacity?: number; roughness?: number; metalness?: number } = {},
): THREE.MeshStandardMaterial {
return new THREE.MeshStandardMaterial({
color,
@@ -1119,7 +1142,7 @@ export function glassMaterial(
export function lambertMaterial(
color: number | string,
- options: { flatShading?: boolean; emissive?: number | string } = {}
+ options: { flatShading?: boolean; emissive?: number | string } = {},
): THREE.MeshLambertMaterial {
return new THREE.MeshLambertMaterial({
color,
@@ -1146,7 +1169,7 @@ function threeInterpolation(mode?: TrackInterpolation): THREE.InterpolationModes
export function rotationTrack(
jointName: string,
keyframes: Array<{ time: number; rotation: [number, number, number] }>,
- interpolation?: TrackInterpolation
+ interpolation?: TrackInterpolation,
): THREE.QuaternionKeyframeTrack {
const times: number[] = [];
const values: number[] = [];
@@ -1158,7 +1181,7 @@ export function rotationTrack(
euler.set(
THREE.MathUtils.degToRad(kf.rotation[0]),
THREE.MathUtils.degToRad(kf.rotation[1]),
- THREE.MathUtils.degToRad(kf.rotation[2])
+ THREE.MathUtils.degToRad(kf.rotation[2]),
);
quat.setFromEuler(euler);
values.push(quat.x, quat.y, quat.z, quat.w);
@@ -1168,14 +1191,14 @@ export function rotationTrack(
`${jointName}.quaternion`,
times,
values,
- threeInterpolation(interpolation)
+ threeInterpolation(interpolation),
);
}
export function positionTrack(
jointName: string,
keyframes: Array<{ time: number; position: [number, number, number] }>,
- interpolation?: TrackInterpolation
+ interpolation?: TrackInterpolation,
): THREE.VectorKeyframeTrack {
const times: number[] = [];
const values: number[] = [];
@@ -1189,14 +1212,14 @@ export function positionTrack(
`${jointName}.position`,
times,
values,
- threeInterpolation(interpolation)
+ threeInterpolation(interpolation),
);
}
export function scaleTrack(
jointName: string,
keyframes: Array<{ time: number; scale: [number, number, number] }>,
- interpolation?: TrackInterpolation
+ interpolation?: TrackInterpolation,
): THREE.VectorKeyframeTrack {
const times: number[] = [];
const values: number[] = [];
@@ -1210,14 +1233,14 @@ export function scaleTrack(
`${jointName}.scale`,
times,
values,
- threeInterpolation(interpolation)
+ threeInterpolation(interpolation),
);
}
export function createClip(
name: string,
duration: number,
- tracks: THREE.KeyframeTrack[]
+ tracks: THREE.KeyframeTrack[],
): THREE.AnimationClip {
return new THREE.AnimationClip(name, duration, tracks);
}
@@ -1226,11 +1249,7 @@ export function createClip(
// Common Animation Patterns
// =============================================================================
-export function idleBreathing(
- bodyJoint: string,
- duration = 2,
- amount = 0.02
-): THREE.AnimationClip {
+export function idleBreathing(bodyJoint: string, duration = 2, amount = 0.02): THREE.AnimationClip {
const y = 0;
return createClip('Idle', duration, [
positionTrack(bodyJoint, [
@@ -1244,7 +1263,7 @@ export function idleBreathing(
export function bobbingAnimation(
rootName: string,
duration = 2,
- height = 0.1
+ height = 0.1,
): THREE.AnimationClip {
return createClip('Bob', duration, [
positionTrack(rootName, [
@@ -1258,12 +1277,11 @@ export function bobbingAnimation(
export function spinAnimation(
jointName: string,
duration = 2,
- axis: 'x' | 'y' | 'z' = 'y'
+ axis: 'x' | 'y' | 'z' = 'y',
): THREE.AnimationClip {
const rotation: [number, number, number] = [0, 0, 0];
const idx = axis === 'x' ? 0 : axis === 'y' ? 1 : 2;
- const rotations: Array<{ time: number; rotation: [number, number, number] }> =
- [];
+ const rotations: Array<{ time: number; rotation: [number, number, number] }> = [];
for (let i = 0; i <= 4; i++) {
const r: [number, number, number] = [...rotation];
@@ -1320,7 +1338,7 @@ export function createInstance(
rotation?: [number, number, number];
scale?: [number, number, number];
parent?: THREE.Object3D;
- } = {}
+ } = {},
): THREE.Object3D {
// Duck-typed `.isMesh` — sandbox-created meshes belong to a different
// module realm than this file's THREE import. See render.ts comment.
@@ -1331,9 +1349,7 @@ export function createInstance(
: (source.children.find(isMesh) as THREE.Mesh | undefined);
if (!sourceMesh) {
- throw new Error(
- `createInstance("${name}"): source "${source.name}" has no Mesh to clone from`
- );
+ throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);
}
const mesh = new THREE.Mesh(sourceMesh.geometry, sourceMesh.material);
@@ -1344,7 +1360,7 @@ export function createInstance(
mesh.rotation.set(
THREE.MathUtils.degToRad(options.rotation[0]),
THREE.MathUtils.degToRad(options.rotation[1]),
- THREE.MathUtils.degToRad(options.rotation[2])
+ THREE.MathUtils.degToRad(options.rotation[2]),
);
if (options.scale) mesh.scale.set(...options.scale);
@@ -1404,7 +1420,7 @@ export function getJointNames(root: THREE.Object3D): string[] {
*/
export function validateAsset(
root: THREE.Object3D,
- category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture'
+ category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture',
): { valid: boolean; errors: string[]; warnings: string[] } {
const errors: string[] = [];
const warnings: string[] = [];
@@ -1442,9 +1458,7 @@ export function validateAsset(
* so render.ts can stash it into `render.meta.primitiveUsage` for
* downstream analysis. When omitted, wrapping is skipped (zero overhead).
*/
-export function buildSandboxGlobals(
- usage?: Record<string, number>
-): Record<string, unknown> {
+export function buildSandboxGlobals(usage?: Record<string, number>): Record<string, unknown> {
// CSG ops remain lazy at their own call sites, so importing the wrapper here
// is safe for Node ESM builds and still avoids manifold WASM init unless used.
@@ -1482,9 +1496,7 @@ export function buildSandboxGlobals(
let _kilnCallSeq = 0;
const stampKilnRange = (name: string, geo: THREE.BufferGeometry) => {
const idx = geo.getIndex();
- const triCount = idx
- ? idx.count / 3
- : (geo.getAttribute('position')?.count ?? 0) / 3;
+ const triCount = idx ? idx.count / 3 : (geo.getAttribute('position')?.count ?? 0) / 3;
const callId = ++_kilnCallSeq;
geo.userData = {
...(geo.userData ?? {}),
@@ -1498,10 +1510,7 @@ export function buildSandboxGlobals(
};
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- const cacheGeo = <F extends (...args: any[]) => THREE.BufferGeometry>(
- name: string,
- fn: F
- ): F => {
+ const cacheGeo = <F extends (...args: any[]) => THREE.BufferGeometry>(name: string, fn: F): F => {
const memoFn = (...args: Parameters<F>): THREE.BufferGeometry => {
let key: string;
try {
@@ -1527,10 +1536,8 @@ export function buildSandboxGlobals(
// still ticks the usage counter so the telemetry reflects what the
// agent wrote, not what was recomputed.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- const wrapGeo = <F extends (...args: any[]) => THREE.BufferGeometry>(
- name: string,
- fn: F
- ): F => wrap(name, cacheGeo(name, fn));
+ const wrapGeo = <F extends (...args: any[]) => THREE.BufferGeometry>(name: string, fn: F): F =>
+ wrap(name, cacheGeo(name, fn));
return {
createRoot: wrap('createRoot', createRoot),
@@ -1617,6 +1624,7 @@ export function buildSandboxGlobals(
// 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,
+ Math,
+ console,
};
}
diff --git a/src/prompt-api.ts b/src/prompt-api.ts
index 7362964a..616b3c05 100644
--- a/src/prompt-api.ts
+++ b/src/prompt-api.ts
@@ -22,10 +22,7 @@ const CATEGORY_HEADERS: Array<[PrimitiveSpec['category'], string]> = [
['material', '// Materials'],
['instancing', '// Instancing (share geometry+material; smaller GLBs)'],
['arrays', '// Arrays (replicate a source part)'],
- [
- 'csg',
- '// CSG / Boolean (async — using any of these requires `async function build()`)',
- ],
+ ['csg', '// CSG / Boolean (async — using any of these requires `async function build()`)'],
['mesh-ops', '// Mesh ops'],
['curves', '// Curves'],
['uv', '// UV unwrapping'],
@@ -70,7 +67,10 @@ function renderPrimitiveLines(p: PrimitiveSpec, includeExamples = false): string
// kiln_list_primitives tool's only extra signal). Collapse internal newlines
// in multi-line examples (snapTo/createPart) to one logical line so the
// section stays scannable; wrapComment re-wraps long ones at WRAP columns.
- const collapsed = p.example.replace(/\s*\n\s*/g, ' ').replace(/\s{2,}/g, ' ').trim();
+ const collapsed = p.example
+ .replace(/\s*\n\s*/g, ' ')
+ .replace(/\s{2,}/g, ' ')
+ .trim();
lines.push(...wrapComment(`e.g. ${collapsed}`, ' '));
}
return lines;
diff --git a/src/prompt.ts b/src/prompt.ts
index a5c6b111..6d6f415e 100644
--- a/src/prompt.ts
+++ b/src/prompt.ts
@@ -36,7 +36,7 @@ Generate assets with a low-poly aesthetic:
- No small decorative elements
- Chunky proportions`,
- 'stylized': `## Style: Stylized Cartoon
+ stylized: `## Style: Stylized Cartoon
Generate assets with a stylized cartoon aesthetic:
- Use 12-16 segments for smoother curves
- Exaggerated proportions (big heads, small bodies for characters)
@@ -45,7 +45,7 @@ Generate assets with a stylized cartoon aesthetic:
- Can include small decorative details
- Playful, whimsical shapes`,
- 'voxel': `## Style: Voxel
+ voxel: `## Style: Voxel
Generate assets with a voxel/Minecraft-like aesthetic:
- Use ONLY box geometry (boxGeo)
- No spheres, cylinders, or curved shapes
@@ -54,7 +54,7 @@ Generate assets with a voxel/Minecraft-like aesthetic:
- Flat shading always
- Blocky proportions`,
- 'detailed': `## Style: Detailed
+ detailed: `## Style: Detailed
Generate assets with more geometric detail:
- Use 24-32 segments for smooth surfaces
- Include small decorative elements (buttons, rivets, trim)
@@ -63,14 +63,14 @@ Generate assets with more geometric detail:
- Can use metallic/roughness for PBR looks
- Realistic proportions`,
- 'realistic': `## Style: Realistic
+ realistic: `## Style: Realistic
Generate assets with realistic proportions and detail:
- Use 32-64 segments for very smooth surfaces
- Accurate real-world proportions
- Multiple materials with PBR properties (metalness, roughness)
- Include fine details (seams, edges, bevels)
- Subtle color gradients
-- Higher triangle budgets allowed`
+- Higher triangle budgets allowed`,
};
// =============================================================================
diff --git a/src/render.ts b/src/render.ts
index d4e7e658..1ded9c44 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -12,19 +12,19 @@
import * as THREE from 'three';
import { Document, WebIO } from '@gltf-transform/core';
-import { dedup, palette, flatten, join, weld, prune, mergeDocuments } from '@gltf-transform/functions';
-
-import {
- buildSlotIndex,
- chooseSlot,
- hexToLinearRgb,
- type SnapSlot,
-} from './palette-snap';
-
import {
- buildSandboxGlobals,
- countTriangles,
-} from './primitives';
+ dedup,
+ palette,
+ flatten,
+ join,
+ weld,
+ prune,
+ mergeDocuments,
+} from '@gltf-transform/functions';
+
+import { buildSlotIndex, chooseSlot, hexToLinearRgb, type SnapSlot } from './palette-snap';
+
+import { buildSandboxGlobals, countTriangles } from './primitives';
import {
collectGlbMetrics,
gradeInstanceability,
@@ -121,17 +121,16 @@ export async function executeKilnCode(code: string): Promise<ExecutedKilnCode> {
const fn = new Function(
...globalNames,
- `${normalized}\nreturn { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof animate !== 'undefined' ? animate : null };`
+ `${normalized}\nreturn { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof animate !== 'undefined' ? animate : null };`,
);
const { meta, build, animate } = fn(...globalValues) as {
meta: KilnCodeMeta;
build: () => THREE.Object3D | Promise<THREE.Object3D>;
animate:
- | ((root: THREE.Object3D) =>
- | THREE.AnimationClip[]
- | undefined
- | Promise<THREE.AnimationClip[] | undefined>)
+ | ((
+ root: THREE.Object3D,
+ ) => THREE.AnimationClip[] | undefined | Promise<THREE.AnimationClip[] | undefined>)
| null;
};
@@ -162,7 +161,7 @@ function bridgeMaterial(
doc: Document,
threeMat: THREE.Material,
cache: Map<THREE.Material, GtMaterial>,
- textureCache: Map<THREE.Texture, GtTexture>
+ textureCache: Map<THREE.Texture, GtTexture>,
): GtMaterial {
const cached = cache.get(threeMat);
if (cached) return cached;
@@ -227,7 +226,12 @@ function bridgeMaterial(
}
} else if (matFlags.isMeshBasicMaterial) {
const basicMat = threeMat as THREE.MeshBasicMaterial;
- mat.setBaseColorFactor([basicMat.color.r, basicMat.color.g, basicMat.color.b, basicMat.opacity]);
+ mat.setBaseColorFactor([
+ basicMat.color.r,
+ basicMat.color.g,
+ basicMat.color.b,
+ basicMat.opacity,
+ ]);
mat.setRoughnessFactor(1.0);
mat.setMetallicFactor(0.0);
}
@@ -247,7 +251,7 @@ function bridgeMaterial(
function bridgeTexture(
doc: Document,
threeTex: THREE.Texture,
- cache: Map<THREE.Texture, GtTexture>
+ cache: Map<THREE.Texture, GtTexture>,
): GtTexture | null {
const cached = cache.get(threeTex);
if (cached) return cached;
@@ -269,7 +273,7 @@ function bridgeGeometry(
buf: GtBuffer,
geometry: THREE.BufferGeometry,
material: GtMaterial,
- meshName: string
+ meshName: string,
): GtMesh {
if (!geometry.getAttribute('normal')) {
geometry.computeVertexNormals();
@@ -281,10 +285,11 @@ function bridgeGeometry(
if (posAttr) {
prim.setAttribute(
'POSITION',
- doc.createAccessor(meshName + '_pos')
+ doc
+ .createAccessor(meshName + '_pos')
.setArray(new Float32Array(posAttr.array))
.setType(TYPE_VEC3)
- .setBuffer(buf)
+ .setBuffer(buf),
);
}
@@ -292,10 +297,11 @@ function bridgeGeometry(
if (normAttr) {
prim.setAttribute(
'NORMAL',
- doc.createAccessor(meshName + '_norm')
+ doc
+ .createAccessor(meshName + '_norm')
.setArray(new Float32Array(normAttr.array))
.setType(TYPE_VEC3)
- .setBuffer(buf)
+ .setBuffer(buf),
);
}
@@ -303,20 +309,22 @@ function bridgeGeometry(
if (uvAttr) {
prim.setAttribute(
'TEXCOORD_0',
- doc.createAccessor(meshName + '_uv')
+ doc
+ .createAccessor(meshName + '_uv')
.setArray(new Float32Array(uvAttr.array))
.setType(TYPE_VEC2)
- .setBuffer(buf)
+ .setBuffer(buf),
);
}
const indexAttr = geometry.getIndex();
if (indexAttr) {
prim.setIndices(
- doc.createAccessor(meshName + '_idx')
+ doc
+ .createAccessor(meshName + '_idx')
.setArray(new Uint16Array(indexAttr.array))
.setType(TYPE_SCALAR)
- .setBuffer(buf)
+ .setBuffer(buf),
);
}
@@ -330,7 +338,7 @@ function bridgeNode(
matCache: Map<THREE.Material, GtMaterial>,
nodeMap: Map<string, GtNode>,
meshCache: Map<string, GtMesh>,
- texCache: Map<THREE.Texture, GtTexture>
+ texCache: Map<THREE.Texture, GtTexture>,
): GtNode {
const gtNode = doc.createNode(threeObj.name || undefined);
@@ -378,7 +386,7 @@ function bridgeAnimations(
buf: GtBuffer,
clips: THREE.AnimationClip[],
nodeMap: Map<string, GtNode>,
- warnings: string[]
+ warnings: string[],
): void {
for (const clip of clips) {
const anim = doc.createAnimation(clip.name);
@@ -410,22 +418,26 @@ function bridgeAnimations(
continue;
}
- const inputAcc = doc.createAccessor(clip.name + '_' + nodeName + '_input')
+ const inputAcc = doc
+ .createAccessor(clip.name + '_' + nodeName + '_input')
.setArray(new Float32Array(track.times))
.setType(TYPE_SCALAR)
.setBuffer(buf);
- const outputAcc = doc.createAccessor(clip.name + '_' + nodeName + '_output')
+ const outputAcc = doc
+ .createAccessor(clip.name + '_' + nodeName + '_output')
.setArray(new Float32Array(track.values))
.setType(valueType)
.setBuffer(buf);
- const sampler = doc.createAnimationSampler()
+ const sampler = doc
+ .createAnimationSampler()
.setInput(inputAcc)
.setOutput(outputAcc)
.setInterpolation('LINEAR');
- const channel = doc.createAnimationChannel()
+ const channel = doc
+ .createAnimationChannel()
.setTargetNode(targetNode)
.setTargetPath(targetPath)
.setSampler(sampler);
@@ -534,7 +546,10 @@ function resolveOptimize(opt?: OptimizeMode): OptimizeMode {
* Returns what it did; throws are the caller's to handle (the GLB is otherwise
* valid). Pure w.r.t. inputs other than the mutated Document.
*/
-async function consolidateMaterials(doc: Document, mode: 'palette' | 'full'): Promise<OptimizeSummary> {
+async function consolidateMaterials(
+ doc: Document,
+ mode: 'palette' | 'full',
+): Promise<OptimizeSummary> {
const before = collectGlbMetrics(doc);
const root = doc.getRoot();
const animatedOrSkinned = root.listAnimations().length > 0 || root.listSkins().length > 0;
@@ -576,7 +591,7 @@ async function consolidateMaterials(doc: Document, mode: 'palette' | 'full'): Pr
*/
export async function renderSceneToGLB(
root: THREE.Object3D,
- opts: RenderSceneOptions = {}
+ opts: RenderSceneOptions = {},
): Promise<RenderSceneResult> {
const clips = opts.clips ?? [];
const warnings: string[] = [];
@@ -626,7 +641,9 @@ export async function renderSceneToGLB(
try {
optimize = await consolidateMaterials(doc, optimizeMode);
} catch (err) {
- warnings.push(`optimize (${optimizeMode}) failed: ${err instanceof Error ? err.message : String(err)}`);
+ warnings.push(
+ `optimize (${optimizeMode}) failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
}
}
@@ -647,7 +664,14 @@ export async function renderSceneToGLB(
const io = new WebIO();
const bytes = await io.writeBinary(doc);
- return { bytes, tris, warnings, instanceability, metricsError, ...(optimize ? { optimize } : {}) };
+ return {
+ bytes,
+ tris,
+ warnings,
+ instanceability,
+ metricsError,
+ ...(optimize ? { optimize } : {}),
+ };
}
/**
@@ -659,7 +683,10 @@ export async function renderSceneToGLB(
*
* Pure function: no file I/O, no globals, no WebGL.
*/
-export async function renderGLB(code: string, opts: { optimize?: OptimizeMode } = {}): Promise<RenderResult> {
+export async function renderGLB(
+ code: string,
+ opts: { optimize?: OptimizeMode } = {},
+): Promise<RenderResult> {
const { meta, root, clips, primitiveUsage } = await executeKilnCode(code);
const scene = await renderSceneToGLB(root, {
sceneName: meta.name || 'Scene',
@@ -805,7 +832,10 @@ export async function snapGlbToPalette(
let skipped = 0;
for (const mat of doc.getRoot().listMaterials()) {
// Hero exception — never recolor a textured material (it carries its own color).
- if (mat.getBaseColorTexture()) { skipped++; continue; }
+ if (mat.getBaseColorTexture()) {
+ skipped++;
+ continue;
+ }
const base = mat.getBaseColorFactor();
const emissive = mat.getEmissiveFactor();
const transparent = mat.getAlphaMode() === 'BLEND' || mat.getAlpha() < 0.98;
@@ -814,7 +844,10 @@ export async function snapGlbToPalette(
emissiveLinear: [emissive[0], emissive[1], emissive[2]],
transparent,
});
- if (slotI === undefined) { skipped++; continue; }
+ if (slotI === undefined) {
+ skipped++;
+ continue;
+ }
const slot = slots[slotI]!;
const kind = slot.kind ?? 'opaque';
const [lr, lg, lb] = hexToLinearRgb(slot.color);
@@ -951,7 +984,9 @@ export async function composeSceneGLB(
masterScene.addChild(wrap);
composed++;
} catch (err) {
- warnings.push(`part ${i} (${part.name ?? ''}) skipped: ${err instanceof Error ? err.message : String(err)}`);
+ warnings.push(
+ `part ${i} (${part.name ?? ''}) skipped: ${err instanceof Error ? err.message : String(err)}`,
+ );
}
}
@@ -973,7 +1008,9 @@ export async function composeSceneGLB(
try {
await consolidateMaterials(master, optimizeMode);
} catch (err) {
- warnings.push(`optimize (${optimizeMode}) failed: ${err instanceof Error ? err.message : String(err)}`);
+ warnings.push(
+ `optimize (${optimizeMode}) failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
}
}
@@ -988,7 +1025,13 @@ export async function composeSceneGLB(
const metrics = collectGlbMetrics(master);
const bytes = await io.writeBinary(master);
- return { bytes, tris: metrics.triangles, draws: metrics.drawCalls, materials: metrics.uniqueMaterials, warnings };
+ return {
+ bytes,
+ tris: metrics.triangles,
+ draws: metrics.drawCalls,
+ materials: metrics.uniqueMaterials,
+ warnings,
+ };
}
// =============================================================================
@@ -1006,7 +1049,7 @@ export async function composeSceneGLB(
*/
export function inspectGeneratedAnimation(
root: THREE.Object3D,
- clips: THREE.AnimationClip[]
+ clips: THREE.AnimationClip[],
): string[] {
const warnings: string[] = [];
if (clips.length === 0) return warnings;
@@ -1028,13 +1071,13 @@ export function inspectGeneratedAnimation(
if (!nodeNames.has(nodeName)) {
warnings.push(
- `Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName}" — rename the pivot or fix the track`
+ `Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName}" — rename the pivot or fix the track`,
);
}
if (!['position', 'quaternion', 'scale'].includes(property)) {
warnings.push(
- `Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`
+ `Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`,
);
}
}
@@ -1265,16 +1308,18 @@ export function settleContacts(
// Close the gap plus a small overlap along the dominant gap axis.
const delta = pick.gap.clone();
- const dominant = (['x', 'y', 'z'] as const).reduce((d, axis) =>
- Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d,
- 'x' as 'x' | 'y' | 'z');
+ const dominant = (['x', 'y', 'z'] as const).reduce(
+ (d, axis) => (Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d),
+ 'x' as 'x' | 'y' | 'z',
+ );
delta[dominant] += Math.sign(delta[dominant]) * overlap;
// Find the named object and move it, converting the world delta into the
// parent's local space (handles rotated/scaled ancestors).
let target: THREE.Object3D | undefined;
root.traverse((obj) => {
- if (!target && obj.name === pick!.stats.name && (obj as { isMesh?: boolean }).isMesh) target = obj;
+ if (!target && obj.name === pick!.stats.name && (obj as { isMesh?: boolean }).isMesh)
+ target = obj;
});
if (!target) break;
const parent = target.parent ?? root;
diff --git a/src/solids.ts b/src/solids.ts
index 7a1b0696..b6cafdbf 100644
--- a/src/solids.ts
+++ b/src/solids.ts
@@ -52,7 +52,11 @@ async function getManifoldModule(): Promise<ManifoldToplevel> {
* Convert a Three.js Mesh/Object3D to a Manifold Mesh (world-space).
* Flattens any scene subtree into a single merged manifold.
*/
-function threeToManifold(src: THREE.Object3D, ManifoldCls: typeof Manifold, MeshCls: typeof Mesh): Manifold {
+function threeToManifold(
+ src: THREE.Object3D,
+ ManifoldCls: typeof Manifold,
+ MeshCls: typeof Mesh,
+): Manifold {
src.updateMatrixWorld(true);
const positions: number[] = [];
@@ -117,7 +121,7 @@ function manifoldToThree(
m: Manifold,
material: THREE.Material,
name: string,
- opts: { smooth?: boolean } = {}
+ opts: { smooth?: boolean } = {},
): THREE.Mesh {
const mesh = m.getMesh();
const numProp = mesh.numProp;
@@ -157,16 +161,17 @@ function manifoldToThree(
* Detects a plain object with `smooth` that's NOT an Object3D, so calls
* like `boolUnion('X', a, b, { smooth: true })` still type-check.
*/
-function splitPartsAndOpts(
- parts: Array<THREE.Object3D | { smooth?: boolean }>
-): { parts: THREE.Object3D[]; opts: { smooth?: boolean } } {
+function splitPartsAndOpts(parts: Array<THREE.Object3D | { smooth?: boolean }>): {
+ parts: THREE.Object3D[];
+ opts: { smooth?: boolean };
+} {
if (parts.length === 0) return { parts: [], opts: {} };
const last = parts[parts.length - 1];
if (
last &&
typeof last === 'object' &&
!(last as { isObject3D?: boolean }).isObject3D &&
- ('smooth' in last)
+ 'smooth' in last
) {
return {
parts: parts.slice(0, -1) as THREE.Object3D[],
@@ -206,10 +211,7 @@ interface KilnRange {
* The metadata is consumed by future click-to-inspect UI; the GLB exporter
* ignores it (gltf-transform doesn't serialise userData).
*/
-function combineRangesFromCsgInputs(
- parts: THREE.Object3D[],
- outputTris: number
-): KilnRange[] {
+function combineRangesFromCsgInputs(parts: THREE.Object3D[], outputTris: number): KilnRange[] {
const inputs: Array<{ name: string; weight: number }> = [];
for (const part of parts) {
part.traverse((child) => {
@@ -241,9 +243,7 @@ function combineRangesFromCsgInputs(
for (let i = 0; i < inputs.length; i++) {
const isLast = i === inputs.length - 1;
const weight = inputs[i]!.weight;
- const count = isLast
- ? outputTris - offset
- : Math.floor((weight / totalWeight) * outputTris);
+ const count = isLast ? outputTris - offset : Math.floor((weight / totalWeight) * outputTris);
out.push({ name: inputs[i]!.name, start: offset, count });
offset += count;
}
@@ -253,9 +253,7 @@ function combineRangesFromCsgInputs(
/** Stamp `kilnRanges` on the result mesh's geometry from its CSG inputs. */
function tagCsgOutput(result: THREE.Mesh, parts: THREE.Object3D[]): void {
const idx = result.geometry.getIndex();
- const tris = idx
- ? idx.count / 3
- : (result.geometry.getAttribute('position')?.count ?? 0) / 3;
+ const tris = idx ? idx.count / 3 : (result.geometry.getAttribute('position')?.count ?? 0) / 3;
const ranges = combineRangesFromCsgInputs(parts, Math.floor(tris));
result.geometry.userData = {
...(result.geometry.userData ?? {}),
@@ -319,8 +317,7 @@ export async function boolDiff(
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 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}`, opts);
@@ -342,7 +339,7 @@ export async function boolIntersect(
name: string,
a: THREE.Object3D,
b: THREE.Object3D,
- opts: { smooth?: boolean } = {}
+ opts: { smooth?: boolean } = {},
): Promise<THREE.Mesh> {
const mod = await getManifoldModule();
const aM = threeToManifold(a, mod.Manifold, mod.Mesh);
diff --git a/src/textures.ts b/src/textures.ts
index b8b5a9f2..b246b719 100644
--- a/src/textures.ts
+++ b/src/textures.ts
@@ -64,7 +64,7 @@ export async function loadTexture(source: TextureSource): Promise<THREE.DataText
meta.width,
meta.height,
THREE.RGBAFormat,
- THREE.UnsignedByteType
+ THREE.UnsignedByteType,
);
tex.colorSpace = THREE.SRGBColorSpace;
tex.needsUpdate = true;
diff --git a/src/tools/__tests__/registry-animation.test.ts b/src/tools/__tests__/registry-animation.test.ts
index d4adaa2c..b6784a80 100644
--- a/src/tools/__tests__/registry-animation.test.ts
+++ b/src/tools/__tests__/registry-animation.test.ts
@@ -33,7 +33,10 @@ function animate(root) {
describe('kilnScreenshotAnimationDef', () => {
test('grid mode: returns metrics + a base64 grid PNG', async () => {
- const out = (await kilnScreenshotAnimationDef.run({ code: WALKER, clip: 'walk' })) as KilnScreenshotAnimationResult;
+ const out = (await kilnScreenshotAnimationDef.run({
+ code: WALKER,
+ clip: 'walk',
+ })) as KilnScreenshotAnimationResult;
expect(out.ok).toBe(true);
expect(out.clip).toBe('walk');
expect(out.camera).toBe('Right'); // default camera
@@ -71,7 +74,10 @@ describe('kilnScreenshotAnimationDef', () => {
});
test('a build failure is image-free (ok:false, no png)', async () => {
- const out = (await kilnScreenshotAnimationDef.run({ code: 'not valid (', clip: 'walk' })) as KilnScreenshotAnimationResult;
+ const out = (await kilnScreenshotAnimationDef.run({
+ code: 'not valid (',
+ clip: 'walk',
+ })) as KilnScreenshotAnimationResult;
expect(out.ok).toBe(false);
expect(out.error).toBeDefined();
expect(out.pngBase64).toBeUndefined();
@@ -79,7 +85,10 @@ describe('kilnScreenshotAnimationDef', () => {
});
test('an unknown clip reports the available clips, no image', async () => {
- const out = (await kilnScreenshotAnimationDef.run({ code: WALKER, clip: 'jump' })) as KilnScreenshotAnimationResult;
+ const out = (await kilnScreenshotAnimationDef.run({
+ code: WALKER,
+ clip: 'jump',
+ })) as KilnScreenshotAnimationResult;
expect(out.ok).toBe(false);
expect(out.availableClips).toEqual(['walk']);
expect(out.pngBase64).toBeUndefined();
diff --git a/src/tools/__tests__/registry-render-views.test.ts b/src/tools/__tests__/registry-render-views.test.ts
index 49dd7aa4..d87c431b 100644
--- a/src/tools/__tests__/registry-render-views.test.ts
+++ b/src/tools/__tests__/registry-render-views.test.ts
@@ -49,7 +49,9 @@ describe('kilnRenderViewsDef (unified kiln_render)', () => {
});
test('build failure is image-free: ok:false, error set, no pngBase64', async () => {
- const out = (await kilnRenderViewsDef.run({ code: 'not a kiln program (' })) as KilnRenderViewsResult;
+ const out = (await kilnRenderViewsDef.run({
+ code: 'not a kiln program (',
+ })) as KilnRenderViewsResult;
expect(out.ok).toBe(false);
expect(out.error).toBeDefined();
expect(out.pngBase64).toBeUndefined();
diff --git a/src/tools/__tests__/registry-screenshot.test.ts b/src/tools/__tests__/registry-screenshot.test.ts
index a9256d4c..7f6f44bb 100644
--- a/src/tools/__tests__/registry-screenshot.test.ts
+++ b/src/tools/__tests__/registry-screenshot.test.ts
@@ -35,7 +35,9 @@ describe('kiln_screenshot', () => {
});
test('returns ok:false with the error message instead of throwing', async () => {
- const out = (await screenshotDef().run({ code: 'not a kiln program (' })) as KilnScreenshotResult;
+ const out = (await screenshotDef().run({
+ code: 'not a kiln program (',
+ })) as KilnScreenshotResult;
expect(out.ok).toBe(false);
expect(out.error).toBeDefined();
expect(out.pngBase64).toBeUndefined();
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 4d39186b..12a3ea16 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -63,7 +63,7 @@ const listPrimitivesInput = z.object({
.string()
.optional()
.describe(
- 'Optional category filter: geometry, material, structure, animation, utility, instancing, csg, arrays, mesh-ops, curves, uv, textures.'
+ 'Optional category filter: geometry, material, structure, animation, utility, instancing, csg, arrays, mesh-ops, curves, uv, textures.',
),
});
@@ -80,10 +80,14 @@ const screenshotInput = z.object({
});
const screenshotAnimationInput = z.object({
- code: z.string().describe('Kiln source code to execute; must define animate() returning the named clip.'),
+ code: z
+ .string()
+ .describe('Kiln source code to execute; must define animate() returning the named clip.'),
clip: z
.string()
- .describe('The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.'),
+ .describe(
+ 'The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.',
+ ),
camera: z
.string()
.optional()
@@ -94,7 +98,9 @@ const screenshotAnimationInput = z.object({
perFrame: z
.boolean()
.optional()
- .describe('Return the frames as separate high-res images instead of one composite grid. Default false.'),
+ .describe(
+ 'Return the frames as separate high-res images instead of one composite grid. Default false.',
+ ),
});
const viewInteriorInput = z.object({
@@ -102,7 +108,9 @@ const viewInteriorInput = z.object({
nodeName: z
.string()
.optional()
- .describe('The roof part to lift, by name (default "Roof"). Matches that node and its children.'),
+ .describe(
+ 'The roof part to lift, by name (default "Roof"). Matches that node and its children.',
+ ),
});
// =============================================================================
@@ -115,9 +123,7 @@ function runListPrimitives(input: z.infer<typeof listPrimitivesInput>): {
} {
const all = listPrimitives();
const category = input.category?.trim().toLowerCase();
- const primitives = category
- ? all.filter((p) => p.category.toLowerCase() === category)
- : all;
+ const primitives = category ? all.filter((p) => p.category.toLowerCase() === category) : all;
const text = primitives
.map((p) => `${p.signature} -> ${p.returns}\n ${p.description}\n e.g. ${p.example}`)
@@ -254,7 +260,12 @@ async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRender
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...(rendered.instanceability
- ? { instanceability: { grade: rendered.instanceability.grade, summary: rendered.instanceability.summary } }
+ ? {
+ instanceability: {
+ grade: rendered.instanceability.grade,
+ summary: rendered.instanceability.summary,
+ },
+ }
: {}),
warnings,
};
@@ -289,7 +300,9 @@ export interface KilnScreenshotResult {
* The renderer is imported lazily so the views module (node:zlib) never enters
* the browser bundle graph.
*/
-async function runScreenshot(input: z.infer<typeof screenshotInput>): Promise<KilnScreenshotResult> {
+async function runScreenshot(
+ input: z.infer<typeof screenshotInput>,
+): Promise<KilnScreenshotResult> {
try {
const { renderViewGrid } = await import('../views');
const { root } = await executeKilnCode(input.code);
@@ -377,7 +390,12 @@ async function runRenderViews(input: z.infer<typeof renderInput>): Promise<KilnR
bbox: metrics.bbox,
lowestPart: metrics.lowestPart,
...(rendered.instanceability
- ? { instanceability: { grade: rendered.instanceability.grade, summary: rendered.instanceability.summary } }
+ ? {
+ instanceability: {
+ grade: rendered.instanceability.grade,
+ summary: rendered.instanceability.summary,
+ },
+ }
: {}),
views: grid.views,
gridWidth: grid.width,
@@ -485,12 +503,19 @@ async function runScreenshotAnimation(
if (r.pngs) return { ...base, framesBase64: r.pngs.map((p) => p.toString('base64')) };
return { ...base, pngBase64: r.png!.toString('base64') };
} catch (err) {
- return { ok: false, frames: 0, error: err instanceof Error ? err.message : String(err), warnings: [] };
+ return {
+ ok: false,
+ frames: 0,
+ error: err instanceof Error ? err.message : String(err),
+ warnings: [],
+ };
}
}
/** Media extractor for the composite-grid result (pngBase64 → bytes + stripped JSON). */
-export function screenshotAnimationMedia(output: unknown): { png: Uint8Array; json: unknown } | undefined {
+export function screenshotAnimationMedia(
+ output: unknown,
+): { png: Uint8Array; json: unknown } | undefined {
const o = output as KilnScreenshotAnimationResult | undefined;
if (!o || typeof o.pngBase64 !== 'string' || o.pngBase64.length === 0) return undefined;
const { pngBase64: _png, framesBase64: _frames, ...json } = o;
@@ -566,7 +591,9 @@ export interface KilnViewInteriorResult {
* inspector (the agent already gets floating/stray warnings from kiln_render). The views
* module is imported lazily to keep node:zlib out of the browser bundle graph.
*/
-async function runViewInterior(input: z.infer<typeof viewInteriorInput>): Promise<KilnViewInteriorResult> {
+async function runViewInterior(
+ input: z.infer<typeof viewInteriorInput>,
+): Promise<KilnViewInteriorResult> {
try {
const { renderInteriorGrid } = await import('../views');
const { root } = await executeKilnCode(input.code);
diff --git a/src/uv-shapes.ts b/src/uv-shapes.ts
index 30fc4576..0ec5fbee 100644
--- a/src/uv-shapes.ts
+++ b/src/uv-shapes.ts
@@ -102,7 +102,7 @@ export function planeUnwrap(geo: THREE.BufferGeometry): THREE.BufferGeometry {
*/
export function panelRemapV(
geo: THREE.BufferGeometry,
- vScale = 0.30,
+ vScale = 0.3,
vOffset = 0,
uScale = 1,
uOffset = 0,
diff --git a/src/uv.ts b/src/uv.ts
index 9bc0f976..eac73422 100644
--- a/src/uv.ts
+++ b/src/uv.ts
@@ -30,12 +30,12 @@ type XatlasApi = {
meshObj: string,
useNormals: boolean,
useCoords: boolean,
- scale: number
+ scale: number,
): { meshId: number } | null;
generateAtlas(
chartOptions: Record<string, unknown>,
packOptions: Record<string, unknown>,
- destroyMesh: boolean
+ destroyMesh: boolean,
): {
width: number;
height: number;
@@ -63,10 +63,12 @@ async function getXatlas(): Promise<XatlasApi> {
const apiSpecifier = 'xatlasjs/dist/node/api.mjs';
const xatlasSpecifier = 'xatlasjs/dist/node/xatlas.js';
const apiMod = (await import(apiSpecifier)) as unknown as {
- Api: (createModule: unknown) => new (
+ Api: (
+ createModule: unknown,
+ ) => new (
onLoad: () => void,
locateFile: unknown,
- onProgress: unknown
+ onProgress: unknown,
) => XatlasApi;
};
const xatlasMod = (await import(xatlasSpecifier)) as unknown as {
@@ -107,7 +109,7 @@ export interface AutoUnwrapOptions {
*/
export async function autoUnwrap(
geometry: THREE.BufferGeometry,
- opts: AutoUnwrapOptions = {}
+ opts: AutoUnwrapOptions = {},
): Promise<THREE.BufferGeometry> {
const xa = await getXatlas();
@@ -136,7 +138,7 @@ export async function autoUnwrap(
'kiln-mesh',
useNormals,
false,
- 1
+ 1,
);
if (!addRes) {
xa.destroyAtlas();
@@ -146,7 +148,7 @@ export async function autoUnwrap(
const result = xa.generateAtlas(
{},
{ resolution: opts.resolution ?? 1024, padding: opts.padding ?? 2 },
- true
+ true,
);
const mesh = result.meshes[0];
@@ -158,19 +160,13 @@ export async function autoUnwrap(
const out = new THREE.BufferGeometry();
out.setAttribute(
'position',
- new THREE.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3)
+ 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)
- );
+ 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)
- );
+ 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));
diff --git a/src/validation.ts b/src/validation.ts
index 9ac4507a..9a75a614 100644
--- a/src/validation.ts
+++ b/src/validation.ts
@@ -67,10 +67,7 @@ export interface ValidationResult {
* "your asset is likely to blow the category budget" warning before a render
* is attempted. Exact numbers come from Three.js's own primitive builders.
*/
-function estimateGeometryTris(
- name: string,
- args: readonly acorn.Expression[]
-): number | null {
+function estimateGeometryTris(name: string, args: readonly acorn.Expression[]): number | null {
function asNum(node: acorn.Expression | undefined): number | null {
if (!node) return null;
if (node.type === 'Literal' && typeof node.value === 'number') return node.value;
@@ -187,10 +184,7 @@ const DEFAULT_TRI_BUDGET = 40000;
* @param code raw JS string as returned by the LLM
* @param opts optional hints the validator can use for richer checks
*/
-export function validate(
- code: string,
- opts: { category?: string } = {}
-): ValidationResult {
+export function validate(code: string, opts: { category?: string } = {}): ValidationResult {
const issues: ValidationIssue[] = [];
const warnings: ValidationIssue[] = [];
@@ -221,7 +215,8 @@ export function validate(
issues.push({
code: 'HAS_EXPORT',
message: 'Contains export statements — just define meta, build, animate',
- fixHint: 'Remove `export` keywords; the sandbox evaluator picks up `meta` and `build` by name.',
+ fixHint:
+ 'Remove `export` keywords; the sandbox evaluator picks up `meta` and `build` by name.',
line: findLineOf(normalized, /^\s*export\s+/m),
});
}
@@ -234,7 +229,8 @@ export function validate(
issues.push({
code: 'KEYFRAME_VALUE_KEY',
message: 'Uses `value:` in keyframes — must use `rotation:` or `position:` instead',
- fixHint: 'In every `{ time, value: [...] }` change `value:` to `rotation:` (degrees) or `position:`.',
+ fixHint:
+ 'In every `{ time, value: [...] }` change `value:` to `rotation:` (degrees) or `position:`.',
line: lineOfIndex(normalized, valueMatch.index),
});
}
@@ -325,7 +321,8 @@ export function validate(
warnings.push({
code: 'TRI_BUDGET_EXCEEDED',
message: `Estimated ${analysis.estimatedTris} tris (informational; "${opts.category}" assets typically land under ~${budget}). This is not a limit — keep the detail if the silhouette needs it.`,
- fixHint: 'Only if the asset feels over-dense: reduce segments on cylinderGeo/sphereGeo, or drop hidden interior parts.',
+ fixHint:
+ 'Only if the asset feels over-dense: reduce segments on cylinderGeo/sphereGeo, or drop hidden interior parts.',
});
}
}
@@ -353,10 +350,7 @@ export const validateKilnCode = validate;
// Internals
// =============================================================================
-function toResult(
- issues: ValidationIssue[],
- warnings: ValidationIssue[]
-): ValidationResult {
+function toResult(issues: ValidationIssue[], warnings: ValidationIssue[]): ValidationResult {
return {
valid: issues.length === 0,
errors: issues.map((i) => i.message),
@@ -432,7 +426,7 @@ function analyzeRotationUnits(ast: acorn.Program, source: string): RotationSmell
function classifyRotationArray(
arr: acorn.ArrayExpression,
fn: string,
- source: string
+ source: string,
): RotationSmell | null {
const rendered = () => {
const text = source.slice(arr.start, arr.end).replace(/\s+/g, ' ');
@@ -550,10 +544,7 @@ function analyzeTopLevel(ast: acorn.Program): TopLevelStructure {
};
for (const stmt of ast.body) {
- if (
- stmt.type === 'VariableDeclaration' &&
- (stmt.kind === 'const' || stmt.kind === 'let')
- ) {
+ if (stmt.type === 'VariableDeclaration' && (stmt.kind === 'const' || stmt.kind === 'let')) {
for (const decl of stmt.declarations) {
if (decl.id.type === 'Identifier' && decl.id.name === 'meta') {
out.hasMetaConst = true;
@@ -563,7 +554,7 @@ function analyzeTopLevel(ast: acorn.Program): TopLevelStructure {
p.type === 'Property' &&
!p.computed &&
((p.key.type === 'Identifier' && p.key.name === 'name') ||
- (p.key.type === 'Literal' && p.key.value === 'name'))
+ (p.key.type === 'Literal' && p.key.value === 'name')),
);
}
}
@@ -645,9 +636,9 @@ function analyzeBody(ast: acorn.Program): BodyAnalysis {
const nArg = node.arguments[1];
const n = Math.min(
4, // cap: beyond 4 iterations the estimate is noise anyway
- (nArg && nArg.type === 'Literal' && typeof nArg.value === 'number' ? nArg.value : 1),
+ nArg && nArg.type === 'Literal' && typeof nArg.value === 'number' ? nArg.value : 1,
);
- est = base * (Math.pow(4, Math.max(0, n)) - 1);
+ est = base * (4 ** Math.max(0, n) - 1);
}
}
}
@@ -683,10 +674,7 @@ function loopMultiplier(ancestors: readonly acorn.Node[]): number {
return Math.min(mult, 4096);
}
-function insideFunctionNamed(
- ancestors: readonly acorn.AnyNode[],
- name: string
-): boolean {
+function insideFunctionNamed(ancestors: readonly acorn.AnyNode[], name: string): boolean {
for (let i = ancestors.length - 1; i >= 0; i--) {
const node = ancestors[i];
if (!node) continue;
diff --git a/src/views/__tests__/animation.test.ts b/src/views/__tests__/animation.test.ts
index 0f8af1e2..f24243d7 100644
--- a/src/views/__tests__/animation.test.ts
+++ b/src/views/__tests__/animation.test.ts
@@ -74,7 +74,11 @@ describe('renderClipAnimation', () => {
test('posing actually moves the scene — frames differ from each other', async () => {
const { root, clips } = await executeKilnCode(WALKER);
- const r = await renderClipAnimation(root, clips, { clip: 'walk', camera: 'right', perFrame: true });
+ const r = await renderClipAnimation(root, clips, {
+ clip: 'walk',
+ camera: 'right',
+ perFrame: true,
+ });
expect(r.pngs).toHaveLength(6);
// Mid-stride (frame 2, ~40%) must look different from the start pose (frame 0).
expect(Buffer.compare(r.pngs![0]!, r.pngs![2]!)).not.toBe(0);
diff --git a/src/views/__tests__/views.test.ts b/src/views/__tests__/views.test.ts
index 8b8b7235..7c498cf3 100644
--- a/src/views/__tests__/views.test.ts
+++ b/src/views/__tests__/views.test.ts
@@ -79,7 +79,10 @@ describe('rasterizeView', () => {
// long profile fills the frame width while the end-on view leaves the
// cell mostly square — compare aspect by occupied-row/col extents.
const occupiedAspect = (rgb: Uint8Array, size: number): number => {
- let minX = size, maxX = -1, minY = size, maxY = -1;
+ let minX = size,
+ maxX = -1,
+ minY = size,
+ maxY = -1;
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const i = (y * size + x) * 3;
@@ -187,7 +190,9 @@ describe('hideNodeInScene', () => {
test('hides the matched node AND its descendant meshes (per-mesh cull)', async () => {
const { root } = await executeKilnCode(ROOF_ONLY_CODE);
const dir: [number, number, number] = [0.7, 0.5, 0.7];
- expect(coverage(rasterizeView(root, dir, { size: 64, backfaceCull: false }), 64)).toBeGreaterThan(0.1);
+ expect(
+ coverage(rasterizeView(root, dir, { size: 64, backfaceCull: false }), 64),
+ ).toBeGreaterThan(0.1);
const hidden = hideNodeInScene(root, 'Roof');
expect(hidden).toBeGreaterThanOrEqual(1);
// If only the group's .visible flipped (not its child meshes), coverage would stay > 0.
diff --git a/src/views/index.ts b/src/views/index.ts
index b02bb724..0c3ad864 100644
--- a/src/views/index.ts
+++ b/src/views/index.ts
@@ -11,7 +11,14 @@
* row 2: Left, Top, 3/4
*/
-import { rasterizeView, measureBounds, hideNodeInScene, SIX_VIEWS, type RasterOptions, type ViewSpec } from './raster';
+import {
+ rasterizeView,
+ measureBounds,
+ hideNodeInScene,
+ SIX_VIEWS,
+ type RasterOptions,
+ type ViewSpec,
+} from './raster';
import { encodePng } from './png';
import {
prepareClip,
@@ -54,7 +61,7 @@ export interface ViewGridOptions extends RasterOptions {
/** Render a (possibly sandbox-created) Three.js scene root into the 3x2 grid. */
export async function renderViewGrid(
root: unknown,
- opts: ViewGridOptions = {}
+ opts: ViewGridOptions = {},
): Promise<ViewGridResult> {
const size = opts.size ?? 256;
const views = opts.views ?? SIX_VIEWS;
@@ -94,7 +101,7 @@ export async function renderViewGrid(
/** Execute a Kiln program and render its scene into the 3x2 grid. */
export async function renderCodeViewGrid(
code: string,
- opts: ViewGridOptions = {}
+ opts: ViewGridOptions = {},
): Promise<ViewGridResult> {
const { executeKilnCode } = await import('../render');
const { root } = await executeKilnCode(code);
@@ -127,8 +134,13 @@ const ANIM_CAMERA_ALIASES: Record<string, string> = {
};
function resolveCamera(name?: string): ViewSpec {
- const key = (name ?? 'right').trim().toLowerCase().replace(/[_\s]+/g, '-');
- return ANIM_CAMERAS[key] ?? ANIM_CAMERAS[ANIM_CAMERA_ALIASES[key] ?? ''] ?? ANIM_CAMERAS['right']!;
+ const key = (name ?? 'right')
+ .trim()
+ .toLowerCase()
+ .replace(/[_\s]+/g, '-');
+ return (
+ ANIM_CAMERAS[key] ?? ANIM_CAMERAS[ANIM_CAMERA_ALIASES[key] ?? ''] ?? ANIM_CAMERAS['right']!
+ );
}
export interface AnimationViewOptions extends RasterOptions {
@@ -189,7 +201,13 @@ export async function renderClipAnimation(
const cam = resolveCamera(opts.camera);
if (!clips || clips.length === 0) {
- return { ok: false, frames: 0, frameTimes: [], error: 'this asset has no animation clips', availableClips: [] };
+ return {
+ ok: false,
+ frames: 0,
+ frameTimes: [],
+ error: 'this asset has no animation clips',
+ availableClips: [],
+ };
}
// Resolve the requested clip by name; default to the first when none is named.
const requested = opts.clip?.trim();
diff --git a/src/views/pose.ts b/src/views/pose.ts
index 4ba0915f..d52c7a2b 100644
--- a/src/views/pose.ts
+++ b/src/views/pose.ts
@@ -137,13 +137,25 @@ function slerpFlat(
o1: number,
t: number,
): void {
- const x0 = src0[o0]!, y0 = src0[o0 + 1]!, z0 = src0[o0 + 2]!, w0 = src0[o0 + 3]!;
- const x1 = src1[o1]!, y1 = src1[o1 + 1]!, z1 = src1[o1 + 2]!, w1 = src1[o1 + 3]!;
+ const x0 = src0[o0]!,
+ y0 = src0[o0 + 1]!,
+ z0 = src0[o0 + 2]!,
+ w0 = src0[o0 + 3]!;
+ const x1 = src1[o1]!,
+ y1 = src1[o1 + 1]!,
+ z1 = src1[o1 + 2]!,
+ w1 = src1[o1 + 3]!;
let cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
- let bx = x1, by = y1, bz = z1, bw = w1;
+ let bx = x1,
+ by = y1,
+ bz = z1,
+ bw = w1;
if (cos < 0) {
cos = -cos;
- bx = -x1; by = -y1; bz = -z1; bw = -w1;
+ bx = -x1;
+ by = -y1;
+ bz = -z1;
+ bw = -w1;
}
let s0: number, s1: number;
if (cos > 0.9995) {
@@ -198,7 +210,8 @@ function sampleTrack(track: PreparedTrack, t: number, out: number[]): void {
out[2] = quatTmp[2]!;
out[3] = quatTmp[3]!;
} else {
- for (let s = 0; s < stride; s++) out[s] = values[o0 + s]! + (values[o1 + s]! - values[o0 + s]!) * a;
+ for (let s = 0; s < stride; s++)
+ out[s] = values[o0 + s]! + (values[o1 + s]! - values[o0 + s]!) * a;
}
}
diff --git a/src/views/raster.ts b/src/views/raster.ts
index b63f44a5..62bb802b 100644
--- a/src/views/raster.ts
+++ b/src/views/raster.ts
@@ -195,7 +195,7 @@ function clamp01(n: number): number {
*/
function linearToSrgb(c: number): number {
const v = clamp01(c);
- return v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055;
+ return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
}
/**
@@ -205,7 +205,7 @@ function linearToSrgb(c: number): number {
export function rasterizeView(
root: unknown,
dir: [number, number, number],
- opts: RasterOptions = {}
+ opts: RasterOptions = {},
): Uint8Array {
const size = opts.size ?? 256;
const cull = opts.backfaceCull ?? true;
@@ -291,7 +291,12 @@ export function rasterizeView(
const maxY = Math.min(size - 1, Math.ceil(Math.max(sy[0]!, sy[1]!, sy[2]!)));
if (minX > maxX || minY > maxY) continue;
- const ax = sx[0]!, ay = sy[0]!, bx2 = sx[1]!, by = sy[1]!, cx = sx[2]!, cy = sy[2]!;
+ const ax = sx[0]!,
+ ay = sy[0]!,
+ bx2 = sx[1]!,
+ by = sy[1]!,
+ cx = sx[2]!,
+ cy = sy[2]!;
const area = (bx2 - ax) * (cy - ay) - (by - ay) * (cx - ax);
if (Math.abs(area) < 1e-9) continue;
const invArea = 1 / area;
@@ -327,7 +332,10 @@ export function rasterizeView(
* Reuses the rasterizer's own triangle collection so the box matches exactly what
* gets drawn. Empty scenes report a zero box. Used by the animation grid to union
* bounds across posed frames into one steady camera framing. */
-export function measureBounds(root: unknown): { min: [number, number, number]; max: [number, number, number] } {
+export function measureBounds(root: unknown): {
+ min: [number, number, number];
+ max: [number, number, number];
+} {
const { bbox } = collectTriangles(root as DuckObject3D);
return { min: [...bbox.min], max: [...bbox.max] };
}
@@ -354,7 +362,10 @@ export function coverage(rgb: Uint8Array, size: number): number {
* number of matched subtree roots hidden (0 → nothing matched; the caller decides
* whether to warn). Pure helper; mutates `.visible` on the passed scene.
*/
-export function hideNodeInScene(root: unknown, match: string | ((name: string) => boolean)): number {
+export function hideNodeInScene(
+ root: unknown,
+ match: string | ((name: string) => boolean),
+): number {
const test =
typeof match === 'function'
? match
diff --git a/src/xatlasjs-shims.d.ts b/src/xatlasjs-shims.d.ts
index e513f4f0..9511acec 100644
--- a/src/xatlasjs-shims.d.ts
+++ b/src/xatlasjs-shims.d.ts
@@ -1,10 +1,12 @@
// 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 (
+ export const Api: (
+ createModule: unknown,
+ ) => new (
onLoad: () => void,
locateFile: unknown,
- onProgress: unknown
+ onProgress: unknown,
) => unknown;
}