Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

feat(geometry): simplifyGeometry derives lower-detail LOD tiers (#243)

Matt Kissingere447a5694845
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 13ff855e..0dc178aa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -62,6 +62,16 @@ does not publish a package.
with mulberry32, the generator scene layout and material presets already used. Builds
that use it stay cacheable; `Math.random` still bypasses build reuse. Discovery finds it
for "seeded random".
+- Add `simplifyGeometry` to derive a lower-detail copy of a part for an LOD tier
+ ([#243](https://github.com/instruktlabs/kiln/issues/243)).
+ `await simplifyGeometry(geometry, { ratio })` (or `{ targetTriangles }`, with optional
+ `maxError` and `lockBorder`) uses the pinned meshoptimizer simplifier and returns new
+ geometry without changing the input. Material groups are simplified separately with
+ their boundaries locked, UV and normal seams and open borders hold, and surviving
+ vertices keep their exact attributes. `userData.kilnSimplify` records the triangle
+ counts, achieved ratio and the simplifier's error; a missed target is a
+ `SIMPLIFY_TARGET_NOT_REACHED` build note. It never runs implicitly or to meet a budget.
+ The `defineLod` contract no longer says Kiln simplifies no geometry and points to it.
## 1.4.0 (2026-10-23)
diff --git a/docs/geometry.md b/docs/geometry.md
index ef0e72af..da7ec9fd 100644
--- a/docs/geometry.md
+++ b/docs/geometry.md
@@ -493,6 +493,32 @@ hosts: `KILN_INDEX_POLICY=asBuilt`) keeps helper buffers as built and requires
optimization off. The receipt's `indexBuffers` reports vertex, morph and index payload
bytes before and after this pass, not GLB file size.
+## Derive a lower-detail tier
+
+`defineLod` declares tiers you build; it never generates one. To derive a lower tier
+from a part, call `simplifyGeometry` on that part's geometry and place the result in
+the tier:
+
+```js
+const rock = sphereGeo(1, 32, 16);
+const far = await simplifyGeometry(rock, { ratio: 0.25 }); // or { targetTriangles: 240 }
+createPart('RockNear', rock, stone, { parent: nearTier });
+createPart('RockFar', far, stone, { parent: farTier });
+defineLod([nearTier, farTier], { screenCoverage: [0.05, 0.002] });
+```
+
+It is async, uses the pinned meshoptimizer simplifier and returns new geometry; the
+input is unchanged. Surviving vertices keep their exact attribute values. Each
+material group is simplified on its own with its boundary vertices locked, vertices
+are welded only where every attribute matches so UV and normal seams hold, and open
+borders stay locked unless `lockBorder: false`. `maxError` (a fraction of the mesh
+extent, default 1, no practical limit) can stop it short of the target.
+`userData.kilnSimplify` records `trianglesBefore`, `trianglesAfter`, the achieved
+`ratio` and the simplifier's `error` and `errorAbsolute`; a result more than 5% above
+the target adds a `SIMPLIFY_TARGET_NOT_REACHED` build note. It never runs implicitly
+or to meet a budget. Flat-shaded or heavily seamed meshes simplify less; inspect the
+lower tier through its `levelsOfDetail` path.
+
## Declare a triangle budget
`defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 })` records the asset's
diff --git a/skills/kiln-author-asset/references/geometry-recipes.md b/skills/kiln-author-asset/references/geometry-recipes.md
index 64233fbb..f8590f71 100644
--- a/skills/kiln-author-asset/references/geometry-recipes.md
+++ b/skills/kiln-author-asset/references/geometry-recipes.md
@@ -430,6 +430,11 @@ const tiers = [0, 1, 2].map((lod) => {
defineLod(tiers, { screenCoverage: [coverage(2.5, 60), coverage(2.5, 250), coverage(2.5, 1500)] });
```
+To derive a lower tier from a finished part instead, call
+`await simplifyGeometry(geometry, { ratio: 0.25 })` per part and place the result in
+the tier. It returns new geometry, keeps groups, seams and open borders, and records
+the achieved ratio and error on `userData.kilnSimplify`; it never runs on its own.
+
`screenCoverage[i]` is the smallest fraction of the screen, 0 to 1, at which level
`i` still draws; the values strictly decrease, the set is culled below the last
one, and a last value of 0 never culls. Compute each set's values from the bounding
diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
index adb9cbe2..4602df5f 100644
--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap
+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
@@ -67,7 +67,8 @@ defineLod(levels: Object3D[], opts: { screenCoverage: number[], impostor?: boole
// NOTE: Only when the brief asks for LOD tiers; otherwise build one tier. Tiers are sibling
// nodes named with one stem and consecutive LOD<n> tokens. screenCoverage has one value per
// level, strictly decreasing; below the last the asset is culled, and a last value of 0 never
- // culls. impostor: true marks the last level a card or billboard tier.
+ // culls. impostor: true marks the last level a card or billboard tier. Build lower tiers with
+ // less detail, or derive one per part with simplifyGeometry.
// e.g. const tiers = ['Body_LOD0', 'Body_LOD1', 'Body_LOD2'].map((name) => { const g = new
// THREE.Group(); g.name = name; root.add(g); return g; }); defineLod(tiers, { screenCoverage:
// [0.25, 0.06, 0.01] });
@@ -621,6 +622,21 @@ mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?
// e.g. const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true }); const rock =
// displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9),
// 0]);
+await simplifyGeometry(geometry: BufferGeometry, opts: { ratio?: number, targetTriangles?: number, maxError?: 1, lockBorder?: true })
+ // Derives a lower-detail copy of one geometry for an LOD tier with the meshoptimizer
+ // simplifier. Pass exactly one of ratio (0 < ratio <= 1) or targetTriangles. Material groups,
+ // UV and normal seams and open borders are kept; the input is never changed.
+ // userData.kilnSimplify records trianglesBefore, trianglesAfter, the achieved ratio and the
+ // error.
+ // NOTE: Async: await it inside async build(). Call it per part for a lower tier and pass the
+ // tiers to defineLod; it never runs on its own or to meet a budget. maxError, locked borders
+ // and seams can stop it short of the target: read userData.kilnSimplify.ratio, and
+ // SIMPLIFY_TARGET_NOT_REACHED is a build note.
+ // e.g. const rock = sphereGeo(1, 32, 16); const far = await simplifyGeometry(rock, { ratio:
+ // 0.25 }); const [near, farTier] = ['Rock_LOD0', 'Rock_LOD1'].map((name) => { const g = new
+ // THREE.Group(); g.name = name; root.add(g); return g; }); createPart('RockNear', rock,
+ // stone, { parent: near }); createPart('RockFar', far, stone, { parent: farTier });
+ // defineLod([near, farTier], { screenCoverage: [0.05, 0.002] });
// Curves
sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true | false | 'start' | 'end', creaseAngle?: 60, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })
diff --git a/src/__tests__/simplify-geometry.test.ts b/src/__tests__/simplify-geometry.test.ts
new file mode 100644
index 00000000..bdbf4b42
--- /dev/null
+++ b/src/__tests__/simplify-geometry.test.ts
@@ -0,0 +1,350 @@
+/**
+ * simplifyGeometry: an explicit, author-called lower-detail copy of one geometry (#243).
+ *
+ * The pinned meshoptimizer simplifier reduces triangles towards a ratio or count. Kiln wraps
+ * it so the input is never mutated, material groups stay separate, UV seams and open borders
+ * hold, and the achieved ratio and the simplifier's error are reported on the result. It feeds
+ * defineLod tiers; it never runs implicitly.
+ */
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import { listDiscoveryEntries } from '../discovery/catalog';
+import { createLexicalDiscoveryIndex } from '../discovery/lexical-index';
+import { createGltfIO } from '../gltf-io';
+import { summarizeLodChains } from '../lod-export';
+import { buildSandboxGlobals } from '../primitives';
+import { renderGLBInProcess } from '../render';
+import { type SimplifyReportV1, simplifyGeometry } from '../simplify';
+
+const triangles = (geometry: THREE.BufferGeometry) =>
+ (geometry.index ? geometry.index.count : geometry.getAttribute('position').count) / 3;
+
+function report(geometry: THREE.BufferGeometry): SimplifyReportV1 {
+ return geometry.userData.kilnSimplify as SimplifyReportV1;
+}
+
+function snapshot(geometry: THREE.BufferGeometry) {
+ return {
+ attributes: Object.fromEntries(
+ Object.entries(geometry.attributes).map(([name, attribute]) => [
+ name,
+ Array.from(attribute.array as ArrayLike<number>),
+ ]),
+ ),
+ index: geometry.index ? Array.from(geometry.index.array as ArrayLike<number>) : null,
+ groups: structuredClone(geometry.groups),
+ userData: structuredClone(geometry.userData),
+ };
+}
+
+function uvRange(geometry: THREE.BufferGeometry) {
+ const uv = geometry.getAttribute('uv');
+ const range = { minU: Infinity, maxU: -Infinity, minV: Infinity, maxV: -Infinity, nan: 0 };
+ for (let i = 0; i < uv.count; i++) {
+ const u = uv.getX(i);
+ const v = uv.getY(i);
+ if (!Number.isFinite(u) || !Number.isFinite(v)) range.nan++;
+ range.minU = Math.min(range.minU, u);
+ range.maxU = Math.max(range.maxU, u);
+ range.minV = Math.min(range.minV, v);
+ range.maxV = Math.max(range.maxV, v);
+ }
+ return range;
+}
+
+/** Edges, keyed by rounded positions, not shared by exactly two triangles: cracks or borders. */
+function openEdges(geometry: THREE.BufferGeometry): number {
+ const position = geometry.getAttribute('position');
+ const key = (i: number) =>
+ [position.getX(i), position.getY(i), position.getZ(i)].map((n) => n.toFixed(5)).join();
+ const corners = geometry.index ? geometry.index.count : position.count;
+ const at = (i: number) => (geometry.index ? geometry.index.getX(i) : i);
+ const edges = new Map<string, number>();
+ for (let t = 0; t < corners; t += 3) {
+ const keys = [key(at(t)), key(at(t + 1)), key(at(t + 2))];
+ if (new Set(keys).size < 3) continue;
+ for (let e = 0; e < 3; e++) {
+ const [a, b] = [keys[e]!, keys[(e + 1) % 3]!].sort();
+ edges.set(`${a}|${b}`, (edges.get(`${a}|${b}`) ?? 0) + 1);
+ }
+ }
+ return [...edges.values()].filter((count) => count !== 2).length;
+}
+
+describe('simplifyGeometry', () => {
+ test('reduces a sphere to near the requested ratio and reports the result', async () => {
+ const sphere = new THREE.SphereGeometry(1, 32, 16);
+ const before = triangles(sphere);
+ const far = await simplifyGeometry(sphere, { ratio: 0.25 });
+
+ expect(far).not.toBe(sphere);
+ expect(far.isBufferGeometry).toBe(true);
+ const after = triangles(far);
+ expect(after).toBeGreaterThanOrEqual(before * 0.25 * 0.9);
+ expect(after).toBeLessThanOrEqual(before * 0.25 * 1.1);
+ const r = report(far);
+ expect(r.schemaVersion).toBe(1);
+ expect(r.trianglesBefore).toBe(before);
+ expect(r.trianglesAfter).toBe(after);
+ expect(r.ratio).toBeCloseTo(after / before, 6);
+ expect(r.requested).toEqual({ ratio: 0.25 });
+ // The simplifier's error: relative to the mesh extent and in scene units.
+ expect(r.error).toBeGreaterThan(0);
+ expect(r.error).toBeLessThan(0.1);
+ expect(r.errorAbsolute).toBeGreaterThan(0);
+ expect(r.errorAbsolute).toBeCloseTo(r.error * r.scale, 6);
+ // Fewer vertices too: unused vertices are compacted away, normals stay unit length.
+ expect(far.getAttribute('position').count).toBeLessThan(sphere.getAttribute('position').count);
+ const normal = far.getAttribute('normal');
+ for (let i = 0; i < normal.count; i++)
+ expect(Math.hypot(normal.getX(i), normal.getY(i), normal.getZ(i))).toBeCloseTo(1, 4);
+ far.computeBoundingSphere();
+ expect(far.boundingSphere!.radius).toBeCloseTo(1, 1);
+ });
+
+ test('closed shapes stay closed: UV seams do not open into cracks', async () => {
+ for (const geometry of [
+ new THREE.SphereGeometry(1, 32, 16),
+ new THREE.TorusGeometry(1, 0.3, 24, 48),
+ ])
+ for (const lockBorder of [true, false]) {
+ const out = await simplifyGeometry(geometry, { ratio: 0.25, lockBorder });
+ expect(triangles(out)).toBeLessThanOrEqual(triangles(geometry) * 0.3);
+ expect(openEdges(out)).toBe(0);
+ }
+ });
+
+ test('a triangle target works like a ratio', async () => {
+ const sphere = new THREE.SphereGeometry(1, 32, 16);
+ const far = await simplifyGeometry(sphere, { targetTriangles: 300 });
+ expect(Math.abs(triangles(far) - 300)).toBeLessThanOrEqual(30);
+ expect(report(far).requested).toEqual({ targetTriangles: 300 });
+ });
+
+ test('never mutates the input geometry', async () => {
+ const box = new THREE.BoxGeometry(1, 1, 1, 6, 6, 6);
+ box.userData.note = 'kept';
+ const before = snapshot(box);
+ const out = await simplifyGeometry(box, { ratio: 0.3 });
+ expect(snapshot(box)).toEqual(before);
+ expect(out.userData.note).toBe('kept');
+ expect(box.userData.kilnSimplify).toBeUndefined();
+ for (const name of Object.keys(out.attributes))
+ expect(out.getAttribute(name).array).not.toBe(box.getAttribute(name).array);
+ });
+
+ test('keeps material groups separate and their boundaries in place', async () => {
+ // BoxGeometry has one group per face, materialIndex 0..5.
+ const box = new THREE.BoxGeometry(2, 2, 2, 8, 8, 8);
+ const axes = [
+ [0, 1],
+ [0, -1],
+ [1, 1],
+ [1, -1],
+ [2, 1],
+ [2, -1],
+ ] as const;
+ // Group boundaries hold even when open borders are free to move.
+ for (const lockBorder of [true, false]) {
+ const out = await simplifyGeometry(box, { ratio: 0.25, lockBorder });
+
+ expect(out.groups.map((group) => group.materialIndex)).toEqual([0, 1, 2, 3, 4, 5]);
+ let next = 0;
+ for (const group of out.groups) {
+ expect(group.start).toBe(next);
+ expect(group.count % 3).toBe(0);
+ expect(group.count).toBeGreaterThan(0);
+ next += group.count;
+ }
+ expect(next).toBe(out.index!.count);
+ expect(triangles(out)).toBeLessThan(triangles(box) * 0.5);
+ expect(report(out).runs).toBe(6);
+ expect(report(out).lockedVertices).toBeGreaterThan(0);
+
+ // Every triangle of a face group stays on that face's plane, and the faces still meet
+ // edge to edge: no group borrows another's vertices and no shared edge moved apart.
+ const position = out.getAttribute('position');
+ for (const group of out.groups) {
+ const [axis, sign] = axes[group.materialIndex!]!;
+ for (let i = group.start; i < group.start + group.count; i++)
+ expect(position.getComponent(out.index!.getX(i), axis)).toBeCloseTo(sign, 6);
+ }
+ expect(openEdges(out)).toBe(0);
+ out.computeBoundingBox();
+ expect(out.boundingBox!.min.toArray()).toEqual([-1, -1, -1]);
+ expect(out.boundingBox!.max.toArray()).toEqual([1, 1, 1]);
+ }
+ });
+
+ test('keeps UV seams and their range on a seamed cylinder, with no NaNs', async () => {
+ const cylinder = new THREE.CylinderGeometry(0.5, 0.5, 2, 48, 12);
+ const before = uvRange(cylinder);
+ const out = await simplifyGeometry(cylinder, { ratio: 0.3 });
+ const after = uvRange(out);
+
+ expect(triangles(out)).toBeLessThan(triangles(cylinder) * 0.5);
+ expect(after.nan).toBe(0);
+ expect(after.minU).toBeCloseTo(before.minU, 6);
+ expect(after.maxU).toBeCloseTo(before.maxU, 6);
+ expect(after.minV).toBeCloseTo(before.minV, 6);
+ expect(after.maxV).toBeCloseTo(before.maxV, 6);
+
+ // The side seam survives: some positions still carry both u = 0 and u = 1.
+ const position = out.getAttribute('position');
+ const uv = out.getAttribute('uv');
+ const us = new Map<string, Set<number>>();
+ for (let i = 0; i < position.count; i++) {
+ const key = [position.getX(i), position.getY(i), position.getZ(i)]
+ .map((n) => n.toFixed(5))
+ .join();
+ if (!us.has(key)) us.set(key, new Set());
+ us.get(key)!.add(Math.round(uv.getX(i) * 1e5) / 1e5);
+ }
+ expect([...us.values()].some((set) => set.has(0) && set.has(1))).toBe(true);
+ // Material groups of the cylinder (side, top cap, bottom cap) are kept too.
+ expect(out.groups.map((group) => group.materialIndex)).toEqual([0, 1, 2]);
+ });
+
+ test('locks open borders by default, and frees them on request', async () => {
+ const plane = new THREE.PlaneGeometry(2, 2, 16, 16);
+ const border = (geometry: THREE.BufferGeometry) => {
+ const position = geometry.getAttribute('position');
+ const points = new Set<string>();
+ for (let i = 0; i < position.count; i++) {
+ const [x, y] = [position.getX(i), position.getY(i)];
+ if (Math.abs(Math.abs(x) - 1) < 1e-6 || Math.abs(Math.abs(y) - 1) < 1e-6)
+ points.add(`${x.toFixed(5)},${y.toFixed(5)}`);
+ }
+ return points;
+ };
+ const locked = await simplifyGeometry(plane, { ratio: 0.1 });
+ expect(border(locked)).toEqual(border(plane));
+ expect(report(locked).lockBorder).toBe(true);
+
+ const free = await simplifyGeometry(plane, { ratio: 0.1, lockBorder: false });
+ expect(border(free).size).toBeLessThan(border(plane).size);
+ expect(triangles(free)).toBeLessThan(triangles(locked));
+ });
+
+ test('welds an unindexed copy before simplifying and keeps every attribute type', async () => {
+ const sphere = new THREE.SphereGeometry(1, 24, 12).toNonIndexed();
+ const colors = new Uint8Array(sphere.getAttribute('position').count * 4).fill(200);
+ sphere.setAttribute('color', new THREE.BufferAttribute(colors, 4, true));
+ const out = await simplifyGeometry(sphere, { ratio: 0.3 });
+ expect(out.index).not.toBeNull();
+ expect(triangles(out)).toBeLessThan(triangles(sphere) * 0.4);
+ const color = out.getAttribute('color') as THREE.BufferAttribute;
+ expect(color.array).toBeInstanceOf(Uint8Array);
+ expect(color.normalized).toBe(true);
+ expect(color.itemSize).toBe(4);
+ expect(Array.from(color.array as Uint8Array).every((value) => value === 200)).toBe(true);
+ });
+
+ test('reports when an error limit stops it short of the target', async () => {
+ const sphere = new THREE.SphereGeometry(1, 32, 16);
+ const out = await simplifyGeometry(sphere, { ratio: 0.1, maxError: 0.001 });
+ const r = report(out);
+ expect(r.trianglesAfter).toBeGreaterThan(r.trianglesBefore * 0.1 * 1.1);
+ expect(r.error).toBeLessThanOrEqual(0.001);
+ expect(r.maxError).toBe(0.001);
+ expect(out.userData.kilnGeometryWarnings).toEqual([
+ expect.objectContaining({ code: 'SIMPLIFY_TARGET_NOT_REACHED' }),
+ ]);
+ });
+
+ test('is deterministic', async () => {
+ const a = await simplifyGeometry(new THREE.TorusGeometry(1, 0.3, 24, 48), { ratio: 0.2 });
+ const b = await simplifyGeometry(new THREE.TorusGeometry(1, 0.3, 24, 48), { ratio: 0.2 });
+ expect(snapshot(a)).toEqual(snapshot(b));
+ });
+
+ test('rejects bad options with a sentence that names the fix', async () => {
+ const sphere = new THREE.SphereGeometry(1, 8, 6);
+ for (const [options, message] of [
+ [{ ratio: 0 }, 'ratio'],
+ [{ ratio: 1.5 }, 'ratio'],
+ [{ ratio: -0.2 }, 'ratio'],
+ [{ ratio: Number.NaN }, 'ratio'],
+ [{}, 'exactly one of ratio or targetTriangles'],
+ [{ ratio: 0.5, targetTriangles: 10 }, 'exactly one of ratio or targetTriangles'],
+ [{ targetTriangles: 0 }, 'targetTriangles'],
+ [{ targetTriangles: 2.5 }, 'targetTriangles'],
+ [{ ratio: 0.5, maxError: -1 }, 'maxError'],
+ [{ ratio: 0.5, lockBorder: 'yes' }, 'lockBorder'],
+ [{ ratio: 0.5, target: 10 }, 'unknown option "target"'],
+ ] as const)
+ await expect(simplifyGeometry(sphere, options as never)).rejects.toThrow(message);
+ await expect(simplifyGeometry(sphere, undefined as never)).rejects.toThrow(
+ 'exactly one of ratio or targetTriangles',
+ );
+ await expect(simplifyGeometry({} as never, { ratio: 0.5 })).rejects.toThrow('BufferGeometry');
+ });
+
+ test('is a sandbox global that feeds defineLod through a rendered Kiln program', async () => {
+ expect(typeof buildSandboxGlobals().simplifyGeometry).toBe('function');
+ const code = `const meta = { name: 'Simplified Rock' };
+async function build() {
+ const root = createRoot('Rock');
+ const stone = gameMaterial(0x777777);
+ const rock = sphereGeo(1, 32, 16);
+ const far = await simplifyGeometry(rock, { ratio: 0.25 });
+ const near = new THREE.Group(); near.name = 'Rock_LOD0'; near.position.y = 1; root.add(near);
+ const farTier = new THREE.Group(); farTier.name = 'Rock_LOD1'; farTier.position.y = 1; root.add(farTier);
+ createPart('RockNear', rock, stone, { parent: near });
+ createPart('RockFar', far, stone, { parent: farTier });
+ defineLod([near, farTier], { screenCoverage: [0.05, 0.001] });
+ return root;
+}`;
+ const result = await renderGLBInProcess(code);
+ // The sandbox's primitive range stamp follows the copy; no provenance or target notes.
+ expect(result.warnings.join(' ')).not.toContain('SIMPLIFY_');
+ const doc = await createGltfIO().readBinary(new Uint8Array(result.glb));
+ const [chain] = summarizeLodChains(doc);
+ expect(chain!.levels.map((level) => level.name)).toEqual(['Rock_LOD0', 'Rock_LOD1']);
+ const [near, far] = chain!.levels.map((level) => level.triangles);
+ expect(near).toBe(960);
+ expect(far).toBeGreaterThanOrEqual(216);
+ expect(far).toBeLessThanOrEqual(264);
+ });
+
+ test('keeps a whole-geometry source range stamp and drops per-face provenance it cannot map', async () => {
+ const stamped = new THREE.SphereGeometry(1, 32, 16);
+ stamped.userData.kilnRanges = [{ name: 'sphereGeo#1', start: 0, count: 960 }];
+ const kept = await simplifyGeometry(stamped, { ratio: 0.25 });
+ expect(kept.userData.kilnRanges).toEqual([
+ { name: 'sphereGeo#1', start: 0, count: triangles(kept) },
+ ]);
+ expect(kept.userData.kilnGeometryWarnings).toBeUndefined();
+
+ const csg = new THREE.SphereGeometry(1, 32, 16);
+ csg.userData.kilnCsgProvenance = { schemaVersion: 1, runs: [], faceIds: [] };
+ csg.userData.kilnRanges = [{ name: 'a', start: 0, count: 100 }];
+ const dropped = await simplifyGeometry(csg, { ratio: 0.25 });
+ expect(dropped.userData.kilnCsgProvenance).toBeUndefined();
+ expect(dropped.userData.kilnRanges).toBeUndefined();
+ expect(dropped.userData.kilnGeometryWarnings).toEqual([
+ expect.objectContaining({ code: 'SIMPLIFY_PROVENANCE_DROPPED' }),
+ ]);
+ });
+});
+
+describe('simplifyGeometry in Discovery', () => {
+ test('a search for lower detail finds it, and defineLod points to it', async () => {
+ const entries = listDiscoveryEntries();
+ const index = createLexicalDiscoveryIndex(entries);
+ const hits = await index.search('simplify decimate lower detail');
+ expect(hits[0]?.id).toBe('operation:simplifyGeometry');
+
+ const simplify = entries.find((entry) => entry.id === 'operation:simplifyGeometry')!;
+ expect(simplify.kind).toBe('operation');
+ if (simplify.kind !== 'operation') throw new Error('expected an operation');
+ expect(simplify.contract.execution).toBe('async');
+ expect(simplify.contract.example).toContain('simplifyGeometry(');
+ expect(simplify.contract.example).toContain('defineLod(');
+
+ const lod = entries.find((entry) => entry.id === 'operation:defineLod')!;
+ expect(lod.limitations.join(' ')).not.toContain('Kiln simplifies no geometry');
+ expect(lod.limitations.join(' ')).toContain('simplifyGeometry');
+ expect(lod.related.map((related) => related.id)).toContain('operation:simplifyGeometry');
+ });
+});
diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.ts
index 6e56387a..cd7421b2 100644
--- a/src/discovery/helper-contracts.ts
+++ b/src/discovery/helper-contracts.ts
@@ -887,10 +887,13 @@ define(
summary:
'Declares LOD tiers (sibling nodes named Body_LOD0, Body_LOD1, ...) and their screen-coverage thresholds. Use only when the brief asks for LOD tiers.',
limitations: [
- 'Tiers are authored, not generated: Kiln simplifies no geometry.',
+ 'Tiers are authored: defineLod generates and simplifies nothing. Build each lower tier with less detail, or derive it explicitly per part with simplifyGeometry and place the result in the tier.',
'Sets cannot nest inside another tier; material LOD chains are not created.',
],
- related: [{ name: 'createPart', relation: 'companion' }],
+ related: [
+ { name: 'createPart', relation: 'companion' },
+ { name: 'simplifyGeometry', relation: 'companion' },
+ ],
},
);
const deliveryMetadata = {
@@ -2409,6 +2412,57 @@ define(
],
},
);
+define(
+ 'simplifyGeometry',
+ {
+ ...ownedGeometry,
+ execution: 'async',
+ axes: 'Preserves source axes and the authored origin.',
+ parameters: [
+ 'Exactly one of ratio (a number, 0 < ratio <= 1, the fraction of triangles to keep) or targetTriangles (a positive integer). A target at or above the input count returns a welded copy.',
+ 'maxError: a fraction of the mesh extent, at least 0; default 1, no practical limit, so the ratio or target decides. lockBorder defaults true. Any other option key is rejected.',
+ 'A triangle list with a finite three-component position attribute, per-vertex attributes and a draw range covering the whole geometry. Instanced attributes are rejected. At most 1,000,000 input triangles.',
+ ],
+ topology: [
+ 'Collapses edges with the meshoptimizer simplifier (attribute-aware: normal weight 0.5, UV0 weight 0.5 per unit of UV extent) and removes unused vertices. Not a remesh: it keeps a subset of the input vertices and does not repair defects.',
+ 'Each material group, and each run of triangles outside a group, is simplified on its own; vertices on a boundary between runs are locked.',
+ 'Vertices are welded only where every attribute matches, after positions within 2^-20 of the extent are snapped together, so UV and normal seams stay split and hold; open borders are locked unless lockBorder: false.',
+ ],
+ preservation: [
+ 'Surviving vertices keep their exact attribute values, storage types and normalized flags, including UVs, normals, tangents, colours, skin data and morph targets; nothing is interpolated. Normals are not recomputed; use creaseNormals for faceted shading.',
+ 'Keeps material groups in order with their materialIndex, the geometry name and JSON userData. Source face/range provenance is dropped with SIMPLIFY_PROVENANCE_DROPPED.',
+ ],
+ semantics: [
+ 'userData.kilnSimplify: { schemaVersion: 1, requested, trianglesBefore, trianglesAfter, ratio (achieved), error (fraction of scale), errorAbsolute (scene units), scale, maxError, lockBorder, runs, lockedVertices }.',
+ 'A result more than 5% above the target adds SIMPLIFY_TARGET_NOT_REACHED to userData.kilnGeometryWarnings, which becomes a build note.',
+ 'Explicit only: never runs implicitly or to meet a budget. Pass the result to a lower defineLod tier.',
+ noAssetSemantics,
+ ],
+ cost: 'Roughly linear in vertices and triangles plus WASM simplification; the simplifier loads once per process.',
+ },
+ {
+ references: ['src/simplify.ts'],
+ tags: ['mesh processing', 'lod', 'simplification', 'async'],
+ aliases: [
+ 'decimate',
+ 'decimation',
+ 'mesh simplification',
+ 'reduce triangles',
+ 'lower detail copy',
+ 'polygon reduction',
+ ],
+ intents: ['derive a lower-detail LOD tier from a part'],
+ limitations: [
+ "Error is meshoptimizer's estimate, including attribute deviation; inspect the lower tier as well.",
+ 'Flat-shaded or heavily seamed meshes simplify less, because every seam stays split. Hard edges, seams and group boundaries can stop it short of the target.',
+ ],
+ related: [
+ { name: 'defineLod', relation: 'companion' },
+ { name: 'creaseNormals', relation: 'companion' },
+ { name: 'subdivide', relation: 'alternative' },
+ ],
+ },
+);
const curveFacts: Facts = {
...ownedGeometry,
axes: 'Path points use XYZ; frames are chosen by the curve implementation.',
diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.ts
index 4d4d3303..b1ab908e 100644
--- a/src/discovery/helper-specs.ts
+++ b/src/discovery/helper-specs.ts
@@ -184,7 +184,7 @@ const PRIMITIVES: HelperSpec[] = [
example:
"const tiers = ['Body_LOD0', 'Body_LOD1', 'Body_LOD2'].map((name) => { const g = new THREE.Group(); g.name = name; root.add(g); return g; });\ndefineLod(tiers, { screenCoverage: [0.25, 0.06, 0.01] });",
promptNotes:
- 'Only when the brief asks for LOD tiers; otherwise build one tier. Tiers are sibling nodes named with one stem and consecutive LOD<n> tokens. screenCoverage has one value per level, strictly decreasing; below the last the asset is culled, and a last value of 0 never culls. impostor: true marks the last level a card or billboard tier.',
+ 'Only when the brief asks for LOD tiers; otherwise build one tier. Tiers are sibling nodes named with one stem and consecutive LOD<n> tokens. screenCoverage has one value per level, strictly decreasing; below the last the asset is culled, and a last value of 0 never culls. impostor: true marks the last level a card or billboard tier. Build lower tiers with less detail, or derive one per part with simplifyGeometry.',
},
{
name: 'markOpenShell',
@@ -1049,6 +1049,21 @@ const PRIMITIVES: HelperSpec[] = [
'const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });\nconst rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);',
},
+ {
+ name: 'simplifyGeometry',
+ signature:
+ 'await simplifyGeometry(geometry: BufferGeometry, opts: { ratio?: number, targetTriangles?: number, maxError?: 1, lockBorder?: true })',
+ returns:
+ 'Promise<THREE.BufferGeometry> (new geometry; userData.kilnSimplify reports the result)',
+ category: 'mesh-ops',
+ description:
+ 'Derives a lower-detail copy of one geometry for an LOD tier with the meshoptimizer simplifier. Pass exactly one of ratio (0 < ratio <= 1) or targetTriangles. Material groups, UV and normal seams and open borders are kept; the input is never changed. userData.kilnSimplify records trianglesBefore, trianglesAfter, the achieved ratio and the error.',
+ example:
+ "const rock = sphereGeo(1, 32, 16);\nconst far = await simplifyGeometry(rock, { ratio: 0.25 });\nconst [near, farTier] = ['Rock_LOD0', 'Rock_LOD1'].map((name) => { const g = new THREE.Group(); g.name = name; root.add(g); return g; });\ncreatePart('RockNear', rock, stone, { parent: near });\ncreatePart('RockFar', far, stone, { parent: farTier });\ndefineLod([near, farTier], { screenCoverage: [0.05, 0.002] });",
+ promptNotes:
+ 'Async: await it inside async build(). Call it per part for a lower tier and pass the tiers to defineLod; it never runs on its own or to meet a budget. maxError, locked borders and seams can stop it short of the target: read userData.kilnSimplify.ratio, and SIMPLIFY_TARGET_NOT_REACHED is a build note.',
+ },
+
// ---------------------------------------------------------------------------
// Curves (Wave 2B)
// ---------------------------------------------------------------------------
diff --git a/src/discovery/intents.ts b/src/discovery/intents.ts
index fb5f04b7..d2d33859 100644
--- a/src/discovery/intents.ts
+++ b/src/discovery/intents.ts
@@ -67,6 +67,12 @@ export const discoveryIntents: Readonly<Record<string, readonly string[]>> = {
boolIntersect: ['intersection of solids', 'overlapping volume'],
beamBetween: ['beam between points', 'bar connecting endpoints'],
autoUnwrap: ['unwrap texture coordinates', 'UV atlas', 'unfold mesh'],
+ simplifyGeometry: [
+ 'lower detail variant',
+ 'far LOD tier',
+ 'decimate a mesh',
+ 'reduce triangle count',
+ ],
foliageCardGeo: ['thin leaf cutout', 'foliage card', 'single leaflet card', 'fern leaf'],
foliageMaterial: ['leaf transparency', 'foliage cutout', 'alpha mask'],
};
diff --git a/src/geometry-budget.ts b/src/geometry-budget.ts
index b928d8dc..6e562434 100644
--- a/src/geometry-budget.ts
+++ b/src/geometry-budget.ts
@@ -7,6 +7,8 @@ export const GEOMETRY_ALLOCATION_LIMITS = Object.freeze({
repeatedMeshes: 10_000,
// repeatAlongCurve merge: vertices in the one merged geometry it returns.
curveRepeatVertices: 262_144,
+ // simplifyGeometry: input triangles per call.
+ simplifyTriangles: 1_000_000,
primitiveSegments: 4096,
primitiveGridVertices: 262_144,
// xatlasjs 0.2 returns Uint16 indices and source-vertex correspondence.
diff --git a/src/primitives.ts b/src/primitives.ts
index 8d499874..caa56389 100644
--- a/src/primitives.ts
+++ b/src/primitives.ts
@@ -61,6 +61,7 @@ import * as ops from './ops';
import * as geometry from './geometry';
import * as deform from './deform';
import * as sweep from './sweep';
+import { simplifyGeometry } from './simplify';
import { implicitSurface } from './implicit';
import { catmullRomPath, metaballSurface, smoothOrganic, spiralPath, taperedTube } from './organic';
import { smoothUnion, sphereInside } from './sdf';
@@ -323,7 +324,7 @@ function assertPartArgs(name: unknown, geometry: unknown, material: unknown): vo
'a function -- geometry helpers have to be CALLED, so boxGeo(1, 1, 1) rather than boxGeo';
} else if (geometry instanceof Promise) {
got =
- 'a Promise -- roundedBoxGeo, extrudeProfile and revolveProfile are async, ' +
+ 'a Promise -- roundedBoxGeo, extrudeProfile, revolveProfile and simplifyGeometry are async, ' +
'so await the helper and mark build() async';
} else {
got =
@@ -2423,6 +2424,8 @@ export function buildSandboxGlobals(
mirror: wrap('mirror', ops.mirror),
subdivide: wrap('subdivide', ops.subdivide),
mergeVertices: wrap('mergeVertices', ops.mergeVertices),
+ // Explicit lower-detail copy (async: meshoptimizer WASM). Never implicit.
+ simplifyGeometry: wrap('simplifyGeometry', simplifyGeometry),
curveToMesh: wrap('curveToMesh', ops.curveToMesh),
pipeAlongPath: wrap('pipeAlongPath', ops.pipeAlongPath),
lathe: wrap('lathe', ops.lathe),
diff --git a/src/simplify.ts b/src/simplify.ts
new file mode 100644
index 00000000..c783d4bd
--- /dev/null
+++ b/src/simplify.ts
@@ -0,0 +1,526 @@
+/**
+ * `simplifyGeometry`: an explicit lower-detail copy of one geometry, for authored LOD tiers.
+ *
+ * Backed by the pinned meshoptimizer simplifier (WASM, loaded lazily on the first call). The
+ * simplifier keeps a subset of the input vertices and rewrites only the index buffer, so every
+ * surviving vertex keeps its exact attribute values: UVs, normals, colours, skin data and morph
+ * targets are copied, never interpolated. Kiln adds what the raw call lacks:
+ *
+ * - the input is never mutated; the result owns new buffers;
+ * - vertices are welded only where every attribute is identical, so UV and normal seams stay
+ * split and the simplifier recognises them from the index data and keeps them;
+ * - each material group (and each run of triangles outside a group) is simplified on its own,
+ * with vertices on a boundary between runs locked, so groups keep their triangles and edges;
+ * - open borders are locked unless `lockBorder: false`;
+ * - the achieved ratio, triangle counts and the simplifier's error are recorded on
+ * `userData.kilnSimplify`, and a target the simplifier could not reach is a build note.
+ *
+ * It never runs implicitly and never runs to meet a budget: authors call it per part and pass
+ * the results to `defineLod` tiers.
+ */
+import * as THREE from 'three';
+import { GEOMETRY_ALLOCATION_LIMITS } from './geometry-budget';
+
+/** Options for {@link simplifyGeometry}. Exactly one of `ratio` or `targetTriangles`. */
+export interface SimplifyGeometryOptions {
+ /** Fraction of triangles to keep, greater than 0 and at most 1. */
+ ratio?: number;
+ /** Triangle count to aim for, a positive integer. */
+ targetTriangles?: number;
+ /**
+ * Largest error the simplifier may introduce, as a fraction of the mesh extent (meshoptimizer's
+ * relative metric). Default 1: no practical limit, so the ratio or target decides.
+ */
+ maxError?: number;
+ /** Keep vertices on open borders in place. Default true. */
+ lockBorder?: boolean;
+}
+
+/** `geometry.userData.kilnSimplify` on every {@link simplifyGeometry} result. */
+export interface SimplifyReportV1 {
+ schemaVersion: 1;
+ /** What the caller asked for. */
+ requested: { ratio: number } | { targetTriangles: number };
+ trianglesBefore: number;
+ trianglesAfter: number;
+ /** Achieved ratio, trianglesAfter / trianglesBefore. */
+ ratio: number;
+ /** The simplifier's error estimate as a fraction of the mesh extent (`scale`). */
+ error: number;
+ /** The same error in scene units: error x scale. */
+ errorAbsolute: number;
+ /** The mesh extent meshoptimizer measures errors against, in scene units. */
+ scale: number;
+ maxError: number;
+ lockBorder: boolean;
+ /** Runs simplified separately: one per material group, plus any ungrouped runs. */
+ runs: number;
+ /** Vertices locked because they sit on a boundary between runs. */
+ lockedVertices: number;
+}
+
+const OPTION_KEYS = new Set(['ratio', 'targetTriangles', 'maxError', 'lockBorder']);
+/**
+ * Attribute weights for attribute-aware simplification. Normals use meshoptimizer's suggested
+ * scale for unit vectors, halved so geometry still leads; UVs are divided by the geometry's UV
+ * extent so tiled (metric) and 0..1 UVs weigh the same.
+ */
+const NORMAL_WEIGHT = 0.5;
+const UV_WEIGHT = 0.5;
+/** Positions closer than this fraction of the extent are treated as one point. */
+const POSITION_SNAP = 2 ** -20;
+
+type Simplifier = typeof import('meshoptimizer/simplifier').MeshoptSimplifier;
+type SimplifierFlags = NonNullable<Parameters<Simplifier['simplifyWithAttributes']>[9]>;
+
+let simplifierReady: Promise<Simplifier> | undefined;
+function loadSimplifier(): Promise<Simplifier> {
+ simplifierReady ??= import('meshoptimizer/simplifier').then(async ({ MeshoptSimplifier }) => {
+ await MeshoptSimplifier.ready;
+ return MeshoptSimplifier;
+ });
+ return simplifierReady;
+}
+
+type AnyAttribute = THREE.BufferAttribute | THREE.InterleavedBufferAttribute;
+
+/** The stored (not denormalized) value, so a copy is bit-exact for every array type. */
+function raw(attribute: AnyAttribute, vertex: number, component: number): number {
+ if ((attribute as THREE.InterleavedBufferAttribute).isInterleavedBufferAttribute) {
+ const interleaved = attribute as THREE.InterleavedBufferAttribute;
+ return interleaved.data.array[
+ vertex * interleaved.data.stride + interleaved.offset + component
+ ] as number;
+ }
+ return (attribute as THREE.BufferAttribute).array[vertex * attribute.itemSize + component]!;
+}
+
+/** Copy the listed source vertices into a new attribute of the same storage type. */
+function gather(attribute: AnyAttribute, vertices: Uint32Array): THREE.BufferAttribute {
+ const source = (attribute as THREE.InterleavedBufferAttribute).isInterleavedBufferAttribute
+ ? (attribute as THREE.InterleavedBufferAttribute).data.array
+ : (attribute as THREE.BufferAttribute).array;
+ const Ctor = source.constructor as new (length: number) => THREE.TypedArray;
+ const values = new Ctor(vertices.length * attribute.itemSize);
+ for (let i = 0; i < vertices.length; i++)
+ for (let c = 0; c < attribute.itemSize; c++)
+ values[i * attribute.itemSize + c] = raw(attribute, vertices[i]!, c);
+ const out = new THREE.BufferAttribute(values, attribute.itemSize, attribute.normalized);
+ out.name = attribute.name;
+ return out;
+}
+
+function fail(message: string): never {
+ throw new TypeError(`simplifyGeometry: ${message}`);
+}
+
+function readOptions(options: unknown): {
+ requested: SimplifyReportV1['requested'];
+ maxError: number;
+ lockBorder: boolean;
+} {
+ if (options === null || typeof options !== 'object' || Array.isArray(options))
+ fail(
+ 'pass exactly one of ratio or targetTriangles, e.g. simplifyGeometry(geo, { ratio: 0.25 }).',
+ );
+ const record = options as Record<string, unknown>;
+ for (const key of Object.keys(record))
+ if (!OPTION_KEYS.has(key))
+ fail(`unknown option "${key}". Options are ratio, targetTriangles, maxError and lockBorder.`);
+ const hasRatio = record.ratio !== undefined;
+ const hasTarget = record.targetTriangles !== undefined;
+ if (hasRatio === hasTarget)
+ fail(
+ 'pass exactly one of ratio or targetTriangles, e.g. simplifyGeometry(geo, { ratio: 0.25 }).',
+ );
+ let requested: SimplifyReportV1['requested'];
+ if (hasRatio) {
+ const ratio = record.ratio;
+ if (typeof ratio !== 'number' || !Number.isFinite(ratio) || ratio <= 0 || ratio > 1)
+ fail(`ratio must be a number greater than 0 and at most 1, but got ${String(ratio)}.`);
+ requested = { ratio };
+ } else {
+ const target = record.targetTriangles;
+ if (typeof target !== 'number' || !Number.isSafeInteger(target) || target < 1)
+ fail(`targetTriangles must be a positive integer, but got ${String(target)}.`);
+ requested = { targetTriangles: target };
+ }
+ const maxError = record.maxError ?? 1;
+ if (typeof maxError !== 'number' || !Number.isFinite(maxError) || maxError < 0)
+ fail(
+ `maxError must be a finite number of at least 0 (a fraction of the mesh extent), but got ${String(maxError)}.`,
+ );
+ const lockBorder = record.lockBorder ?? true;
+ if (typeof lockBorder !== 'boolean')
+ fail(`lockBorder must be a boolean, but got ${String(lockBorder)}.`);
+ return { requested, maxError, lockBorder };
+}
+
+interface Run {
+ start: number;
+ count: number;
+ materialIndex?: number;
+}
+
+/** Group ranges plus the ungrouped gaps between them, in index order. */
+function readRuns(geometry: THREE.BufferGeometry, corners: number): Run[] {
+ if (!geometry.groups.length) return [{ start: 0, count: corners }];
+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
+ const runs: Run[] = [];
+ let next = 0;
+ for (const group of groups) {
+ const start = group.start;
+ const count = Math.min(group.count, corners - start);
+ if (
+ !Number.isSafeInteger(start) ||
+ start < next ||
+ start % 3 !== 0 ||
+ !Number.isFinite(count) ||
+ count < 0 ||
+ count % 3 !== 0
+ )
+ fail('material groups must start on a triangle, cover whole triangles and not overlap.');
+ if (start > next) runs.push({ start: next, count: start - next });
+ if (count > 0) runs.push({ start, count, materialIndex: group.materialIndex ?? 0 });
+ next = start + count;
+ }
+ if (next < corners) runs.push({ start: next, count: corners - next });
+ return runs;
+}
+
+function remapRanges(
+ value: unknown,
+ trianglesBefore: number,
+ runs: readonly Run[],
+ runOut: ReadonlyArray<{ start: number; count: number }>,
+): Record<string, unknown>[] | undefined {
+ if (!Array.isArray(value) || value.length === 0) return undefined;
+ const mapped: Record<string, unknown>[] = [];
+ const total = runOut.reduce((sum, run) => sum + run.count, 0) / 3;
+ for (const range of value) {
+ if (!range || typeof range !== 'object') return undefined;
+ const { start, count } = range as { start?: unknown; count?: unknown };
+ if (start === 0 && count === trianglesBefore) {
+ mapped.push({ ...range, start: 0, count: total });
+ continue;
+ }
+ const r = runs.findIndex(
+ (run) => run.start === Number(start) * 3 && run.count === Number(count) * 3,
+ );
+ if (r === -1) return undefined;
+ mapped.push({ ...range, start: runOut[r]!.start / 3, count: runOut[r]!.count / 3 });
+ }
+ return mapped;
+}
+
+/**
+ * Derive a lower-detail copy of `geometry`. Returns a new BufferGeometry and never mutates the
+ * input. See {@link SimplifyReportV1} for what `userData.kilnSimplify` records.
+ */
+export async function simplifyGeometry(
+ geometry: THREE.BufferGeometry,
+ options: SimplifyGeometryOptions,
+): Promise<THREE.BufferGeometry> {
+ if ((geometry as { isBufferGeometry?: boolean } | null)?.isBufferGeometry !== true)
+ fail('the first argument must be a BufferGeometry, such as sphereGeo(1, 32, 16).');
+ const { requested, maxError, lockBorder } = readOptions(options);
+
+ const position = geometry.getAttribute('position') as AnyAttribute | undefined;
+ if (position?.itemSize !== 3 || position.count === 0)
+ fail('the geometry needs a nonempty three-component position attribute.');
+ const vertexCount = position.count;
+ for (const [name, attribute] of Object.entries(geometry.attributes)) {
+ if ((attribute as THREE.InstancedBufferAttribute).isInstancedBufferAttribute)
+ fail(`${name} is per-instance data; simplify the base geometry before instancing.`);
+ if (attribute.count !== vertexCount)
+ fail(`${name} must have one value per vertex (${vertexCount}), but has ${attribute.count}.`);
+ }
+ for (const [name, targets] of Object.entries(geometry.morphAttributes))
+ for (const target of targets)
+ if (target.count !== vertexCount)
+ fail(`morph ${name} must have one value per vertex (${vertexCount}).`);
+ const { start: drawStart, count: drawCount } = geometry.drawRange;
+ if (
+ drawStart !== 0 ||
+ (Number.isFinite(drawCount) && drawCount < (geometry.index?.count ?? vertexCount))
+ )
+ fail('the draw range must cover the whole geometry; simplify the full mesh.');
+
+ const index = geometry.index;
+ const corners = index ? index.count : vertexCount;
+ if (corners % 3 !== 0) fail('the geometry must be a triangle list.');
+ const trianglesBefore = corners / 3;
+ if (trianglesBefore > GEOMETRY_ALLOCATION_LIMITS.simplifyTriangles)
+ throw new RangeError(
+ `simplifyGeometry: ${trianglesBefore} triangles exceed the limit of ${GEOMETRY_ALLOCATION_LIMITS.simplifyTriangles}. Split the mesh first.`,
+ );
+ const corner = (i: number): number => {
+ const vertex = index ? index.getX(i) : i;
+ if (!Number.isInteger(vertex) || vertex < 0 || vertex >= vertexCount)
+ fail(`index ${i} is outside the position attribute.`);
+ return vertex;
+ };
+
+ // Extent, for position snapping and the error scale.
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (let v = 0; v < vertexCount; v++)
+ for (let c = 0; c < 3; c++) {
+ const value = position.getComponent(v, c);
+ if (!Number.isFinite(value)) fail('positions must be finite.');
+ if (value < min[c]!) min[c] = value;
+ if (value > max[c]!) max[c] = value;
+ }
+ const extent = Math.max(max[0]! - min[0]!, max[1]! - min[1]!, max[2]! - min[2]!);
+ const cell = extent > 0 ? extent * POSITION_SNAP : 1;
+
+ // Snap near-identical positions to one representative, so seams the primitive generators
+ // leave a rounding error apart (sin(2 pi) is not 0) read as seams rather than open borders.
+ const positionKey = new Uint32Array(vertexCount);
+ const snapped: number[] = [];
+ {
+ const byKey = new Map<string, number>();
+ for (let v = 0; v < vertexCount; v++) {
+ const key = [0, 1, 2]
+ .map((c) => Math.round((position.getComponent(v, c) - min[c]!) / cell))
+ .join(',');
+ let id = byKey.get(key);
+ if (id === undefined) {
+ id = byKey.size;
+ byKey.set(key, id);
+ snapped.push(
+ position.getComponent(v, 0),
+ position.getComponent(v, 1),
+ position.getComponent(v, 2),
+ );
+ }
+ positionKey[v] = id;
+ }
+ }
+
+ // Weld vertices whose every attribute (after snapping) is identical. Seams stay split.
+ const others = Object.entries(geometry.attributes)
+ .filter(([name]) => name !== 'position')
+ .map(([, attribute]) => attribute as AnyAttribute);
+ for (const targets of Object.values(geometry.morphAttributes))
+ others.push(...(targets as AnyAttribute[]));
+ const weldOf = new Int32Array(vertexCount).fill(-1);
+ const representative: number[] = [];
+ {
+ const byKey = new Map<string, number>();
+ const parts: number[] = [];
+ for (let i = 0; i < corners; i++) {
+ const v = corner(i);
+ if (weldOf[v] !== -1) continue;
+ parts.length = 0;
+ parts.push(positionKey[v]!);
+ for (const attribute of others)
+ for (let c = 0; c < attribute.itemSize; c++) parts.push(raw(attribute, v, c));
+ const key = parts.join(',');
+ let id = byKey.get(key);
+ if (id === undefined) {
+ id = representative.length;
+ byKey.set(key, id);
+ representative.push(v);
+ }
+ weldOf[v] = id;
+ }
+ }
+ const weldedCount = representative.length;
+ const weldedIndex = new Uint32Array(corners);
+ for (let i = 0; i < corners; i++) weldedIndex[i] = weldOf[corner(i)]!;
+
+ const positions = new Float32Array(weldedCount * 3);
+ for (let w = 0; w < weldedCount; w++) {
+ const p = positionKey[representative[w]!]! * 3;
+ positions[w * 3] = snapped[p]!;
+ positions[w * 3 + 1] = snapped[p + 1]!;
+ positions[w * 3 + 2] = snapped[p + 2]!;
+ }
+
+ // Attribute-aware simplification: normals and UV0 steer collapses away from shading and
+ // texture distortion. Seams themselves are kept by topology, not by these weights.
+ const normal = geometry.getAttribute('normal') as AnyAttribute | undefined;
+ const uv = geometry.getAttribute('uv') as AnyAttribute | undefined;
+ const weights: number[] = [];
+ const channels: Array<(vertex: number) => number> = [];
+ if (normal?.itemSize === 3)
+ for (let c = 0; c < 3; c++) {
+ weights.push(NORMAL_WEIGHT);
+ channels.push((v) => normal.getComponent(v, c));
+ }
+ if (uv?.itemSize === 2) {
+ let uvExtent = 0;
+ for (let c = 0; c < 2; c++) {
+ let lo = Infinity;
+ let hi = -Infinity;
+ for (let v = 0; v < vertexCount; v++) {
+ const value = uv.getComponent(v, c);
+ if (!Number.isFinite(value)) fail('uv values must be finite.');
+ lo = Math.min(lo, value);
+ hi = Math.max(hi, value);
+ }
+ uvExtent = Math.max(uvExtent, hi - lo);
+ }
+ if (uvExtent > 0)
+ for (let c = 0; c < 2; c++) {
+ weights.push(UV_WEIGHT / uvExtent);
+ channels.push((v) => uv.getComponent(v, c));
+ }
+ }
+ const stride = weights.length;
+ const attributes = new Float32Array(weldedCount * stride);
+ for (let w = 0; w < weldedCount; w++)
+ for (let c = 0; c < stride; c++) {
+ const value = channels[c]!(representative[w]!);
+ if (!Number.isFinite(value)) fail('normal values must be finite.');
+ attributes[w * stride + c] = value;
+ }
+
+ // Runs and the vertices on their boundaries.
+ const runs = readRuns(geometry, corners);
+ const lock = new Uint8Array(weldedCount);
+ let lockedVertices = 0;
+ if (runs.length > 1) {
+ const firstRun = new Int32Array(snapped.length / 3).fill(-1);
+ const shared = new Uint8Array(snapped.length / 3);
+ runs.forEach((run, r) => {
+ for (let i = run.start; i < run.start + run.count; i++) {
+ const p = positionKey[representative[weldedIndex[i]!]!]!;
+ if (firstRun[p] === -1) firstRun[p] = r;
+ else if (firstRun[p] !== r) shared[p] = 1;
+ }
+ });
+ for (let w = 0; w < weldedCount; w++)
+ if (shared[positionKey[representative[w]!]!]) {
+ lock[w] = 1;
+ lockedVertices++;
+ }
+ }
+
+ const simplifier = await loadSimplifier();
+ const scale = simplifier.getScale(positions, 3);
+ const flags: SimplifierFlags = ['ErrorAbsolute'] as SimplifierFlags;
+ if (lockBorder) flags.push('LockBorder' as SimplifierFlags[number]);
+ if (runs.length > 1) flags.push('Sparse' as SimplifierFlags[number]);
+ const ratio =
+ 'ratio' in requested
+ ? requested.ratio
+ : Math.min(1, requested.targetTriangles / trianglesBefore);
+
+ const outIndex: number[] = [];
+ const outGroups: Run[] = [];
+ const runOut: Array<{ start: number; count: number }> = [];
+ let errorAbsolute = 0;
+ let targetTotal = 0;
+ for (const run of runs) {
+ const runIndex = weldedIndex.subarray(run.start, run.start + run.count);
+ const runTriangles = run.count / 3;
+ const target = Math.min(runTriangles, Math.max(1, Math.round(runTriangles * ratio)));
+ targetTotal += target;
+ let kept: Uint32Array = runIndex;
+ if (target < runTriangles) {
+ const [result, error] = simplifier.simplifyWithAttributes(
+ runIndex.slice(),
+ positions,
+ 3,
+ attributes,
+ stride,
+ weights,
+ lock,
+ target * 3,
+ maxError * scale,
+ flags,
+ );
+ kept = result;
+ errorAbsolute = Math.max(errorAbsolute, error);
+ }
+ runOut.push({ start: outIndex.length, count: kept.length });
+ if (run.materialIndex !== undefined)
+ outGroups.push({
+ start: outIndex.length,
+ count: kept.length,
+ materialIndex: run.materialIndex,
+ });
+ for (let i = 0; i < kept.length; i++) outIndex.push(kept[i]!);
+ }
+
+ // Compact: keep used vertices in first-use order and copy their original values.
+ const remap = new Int32Array(weldedCount).fill(-1);
+ const used: number[] = [];
+ const indexValues =
+ weldedCount > 65535 ? new Uint32Array(outIndex.length) : new Uint16Array(outIndex.length);
+ for (let i = 0; i < outIndex.length; i++) {
+ const w = outIndex[i]!;
+ if (remap[w] === -1) {
+ remap[w] = used.length;
+ used.push(w);
+ }
+ indexValues[i] = remap[w]!;
+ }
+ const sources = Uint32Array.from(used, (w) => representative[w]!);
+
+ const out = new THREE.BufferGeometry();
+ out.name = geometry.name;
+ const outPosition = new Float32Array(sources.length * 3);
+ for (let i = 0; i < used.length; i++)
+ outPosition.set(positions.subarray(used[i]! * 3, used[i]! * 3 + 3), i * 3);
+ for (const [name, attribute] of Object.entries(geometry.attributes)) {
+ if (name === 'position') {
+ const attr = new THREE.BufferAttribute(outPosition, 3);
+ attr.name = attribute.name;
+ out.setAttribute(name, attr);
+ } else out.setAttribute(name, gather(attribute as AnyAttribute, sources));
+ }
+ for (const [name, targets] of Object.entries(geometry.morphAttributes))
+ (out.morphAttributes as Record<string, THREE.BufferAttribute[]>)[name] = targets.map((target) =>
+ gather(target as AnyAttribute, sources),
+ );
+ out.morphTargetsRelative = geometry.morphTargetsRelative;
+ out.setIndex(new THREE.BufferAttribute(indexValues, 1));
+ for (const group of outGroups) out.addGroup(group.start, group.count, group.materialIndex);
+ out.computeBoundingBox();
+ out.computeBoundingSphere();
+
+ const trianglesAfter = outIndex.length / 3;
+ const userData = structuredClone(geometry.userData) as Record<string, unknown>;
+ const warnings: Array<{ code: string; message: string }> = [];
+ const previous = userData.kilnGeometryWarnings;
+ if (Array.isArray(previous)) warnings.push(...previous);
+ // Source ranges (in triangles) survive when each covers the whole geometry, as the sandbox
+ // stamps primitives, or exactly one simplified run. Per-face provenance cannot be remapped.
+ const ranges = remapRanges(userData.kilnRanges, trianglesBefore, runs, runOut);
+ if (ranges) userData.kilnRanges = ranges;
+ if (userData.kilnCsgProvenance || (userData.kilnRanges !== undefined && !ranges)) {
+ delete userData.kilnCsgProvenance;
+ delete userData.kilnRanges;
+ warnings.push({
+ code: 'SIMPLIFY_PROVENANCE_DROPPED',
+ message:
+ 'Simplification changed triangle topology. Source face/range provenance was discarded rather than guessed.',
+ });
+ }
+ if (trianglesAfter > Math.ceil(targetTotal * 1.05))
+ warnings.push({
+ code: 'SIMPLIFY_TARGET_NOT_REACHED',
+ message: `simplifyGeometry kept ${trianglesAfter} of ${trianglesBefore} triangles against a target of ${targetTotal}: maxError ${maxError}, locked borders, seams or group boundaries stopped it. Raise maxError, pass lockBorder: false, or accept the result.`,
+ });
+ if (warnings.length) userData.kilnGeometryWarnings = warnings;
+ const report: SimplifyReportV1 = {
+ schemaVersion: 1,
+ requested,
+ trianglesBefore,
+ trianglesAfter,
+ ratio: trianglesAfter / trianglesBefore,
+ error: scale > 0 ? errorAbsolute / scale : 0,
+ errorAbsolute,
+ scale,
+ maxError,
+ lockBorder,
+ runs: runs.length,
+ lockedVertices,
+ };
+ userData.kilnSimplify = report;
+ out.userData = userData;
+ return out;
+}