Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Keep GPU instancing faithful to mirrored and normal-mapped copies, and add a minimal-draws runtime export (#342)
Matthew Kissinger048eecf64a6f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b7ece4fc..2bdefc8e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,24 @@ does not publish a package.## Unreleased+- GPU instancing now draws what the copies drew as separate nodes, in both `KILN_BAKE_INSTANCE` and the+ three runtime target's `repeatInstances`. A mirrored copy no longer shares a batch with unmirrored ones,+ where it drew inside out: single-sided surfaces vanished. Mirrored copies form their own batch on a node+ scaled `[-1, 1, 1]`, with no second copy of the geometry. three r186's WebGPU renderer does not transform+ instance tangents, which shaded a quarter-turned normal-mapped copy black. The bake pass now batches+ tangent-bearing copies by the rotation they share and puts it on the batch node, and the runtime target+ keeps a turned, stretched or mirrored tangent-bearing child separate. The bake pass also keeps a sheared+ copy separate, because instance transforms cannot state shear. `EXT_mesh_gpu_instancing` is now required+ wherever Kiln batches, so a viewer without it refuses the file instead of drawing one copy. Batches and+ draws change on affected assets, including `role: 'fill'` assets under the default `auto`. A saved+ revision built with instancing on can now rebuild with `matchesSavedArtifact: false`; the saved GLB is+ unchanged.+- `kiln export ... --profile runtime --draws minimal [--draw-cell M]` (and `draws: 'minimal'` in+ `exportAssetGlb`) derives a file with fewer draw calls. Every repeated mesh becomes a batch, and parts+ with a single-user mesh merge per material within cells of `M` metres (default 15). It runs no+ `palette()` or `weld()`, and the saved revision is unchanged. The sidecar's `drawReduction` reports the+ result. On the 1,834-draw cathedral revision it gives 283 draws, with the same triangles and 1% fewer+ bytes. `mergeRigidGroups` gains opt-in `cellSize` and `positionTolerance`; `optimize: 'full'` is unchanged.- Three repeated costs on large assets are paid once. Measured on the 2,635,224-triangle cathedral, whose1,707 meshes share 184 geometries:- The open-surface penetration rule measures each shared geometry's topology once per pass. Thediff --git a/docs/delivery-contract.md b/docs/delivery-contract.mdindex 0ff0e8ab..6a9afc90 100644--- a/docs/delivery-contract.md+++ b/docs/delivery-contract.md@@ -33,7 +33,10 @@ Hidden nodes are excluded from triangle counts, bounds and QA.`repeatInstances(parent)` marks a parent (`extras.kilnRepeatInstances`) whoseidentical leaf children the three.js runtime target turns into one-`EXT_mesh_gpu_instancing` node. The editable GLB keeps every child.+`EXT_mesh_gpu_instancing` node. The editable GLB keeps every child. Mirrored children+form a second batch on a node scaled `[-1, 1, 1]`, because a node states the winding for+all its copies. A turned, stretched or mirrored child of a mesh with `TANGENT` stays a+separate node; see [the runtime notes](runtime.md).## Baked vertex attributesdiff --git a/docs/export-profiles.md b/docs/export-profiles.mdindex 41f987d9..695050de 100644--- a/docs/export-profiles.md+++ b/docs/export-profiles.md@@ -203,6 +203,37 @@ scene list; their GLB can grow slightly. This is not geometry optimization, compmesh merging, texture compression, or an FPS improvement. Measure actual delivery sizeand target-scene performance separately.+## Fewer draw calls++`--draws minimal` (runtime profile only; `draws: 'minimal'` in `exportAssetGlb`) derives a+file with as few draws as the saved revision allows, and composes with `--target three`. The+saved revision does not change.++1. Every mesh used by two or more nodes becomes an `EXT_mesh_gpu_instancing` batch, within the+ limits in [the runtime notes](runtime.md): one handedness per batch, no shear, and tangent-bearing+ copies batched by the rotation they share.+2. Parts whose mesh has a single user merge per material, vertex layout and tangent handedness,+ within cubes `--draw-cell` metres wide (default 15), so a viewer can still cull a large asset by+ region. Blended and transmissive parts, and nodes a consumer reads by name (`Joint_*` pivots,+ semantic roles, extras, visibility, LOD), are never merged. A part keeps its node name; its+ geometry can move to another node of its cell.++Unlike `optimize: 'full'`, it runs no `palette()`, which rewrites materials, and no `weld()`,+which splits accessors that parts share. On a 16 MB cathedral, `weld()` alone added 10 MB. The+sidecar's `drawReduction` reports draws before and after, batches, merges, and what stayed+separate and why.++Measured on copies of the 1,834-draw cathedral revision:++| Export | Draws | Triangles | Bytes | Time |+| --- | --- | --- | --- | --- |+| Saved revision | 1,834 | 3,979,304 | 15,993,092 | |+| `--draws minimal` | 283 | 3,979,304 | 15,851,728 | 1.5 s |+| `--draws minimal --target three` | 283 | 3,979,304 | 6,839,500 | 1.9 s |++Batches cost a renderer more per draw than plain meshes do, so measure frame time in the target+scene, not only the draw count.+## three.js runtime target`--target three` (runtime profile only) derives a GLB for a three.js application:@@ -226,7 +257,10 @@ What it does, in order:1. Identical accessors are merged. Under each node marked by `repeatInstances(parent)`,direct children with the same mesh content (accessors, material, mode) and nochildren, roles, extras, skin, morph weights or hidden flag become one node- `<parent>_Instances` with `EXT_mesh_gpu_instancing`.+ `<parent>_Instances` with `EXT_mesh_gpu_instancing`. Mirrored children form their own+ batch on a node scaled `[-1, 1, 1]`, named `<parent>_Instances_<n>` like any further+ batch under that parent. A turned, stretched or mirrored child of a mesh with `TANGENT`+ stays separate.2. Each collider's proxy mesh moves to a child `<collider>_Proxy`, so the collider nodekeeps its authored transform (its scale is the collider size).3. Vertices are reordered for compression, then quantized with `KHR_mesh_quantization`diff --git a/docs/runtime.md b/docs/runtime.mdindex 3cda9cd9..a2d2105e 100644--- a/docs/runtime.md+++ b/docs/runtime.md@@ -169,6 +169,17 @@ see the [migration notes](migration.md#changes-in-10).The MCP and CLI tools pin `optimize: 'off'` for every render, inspection and save, so `KILN_BAKE_OPTIMIZE` does not change a tool's GLB; they leave `instance` to the host, so `KILN_BAKE_INSTANCE` does. Library calls that omit `optimize` take the variable: `renderGLB` in process, `renderSceneToGLB` (including the review copies some tool views are rendered from), `renderCodeViewGrid` and `rasterizeComposedScene`. The library's own subprocess mode does not pass either variable to its worker. `node kiln.mjs asset ASSET_ID REVISION --rebuild --out rebuilt.glb` replays the `optimize` and `instance` the saved manifest recorded, whatever the variables say. Both variables are part of the local build-cache key.+A batch draws what its copies drew as separate nodes, within these limits:++- **One handedness per batch.** glTF and three.js take a triangle's winding from the node's global transform and have no per-instance winding, so a mirrored copy (negative determinant) in a right-handed batch would draw inside out. Mirrored copies form their own batch on a node scaled `[-1, 1, 1]`, which needs no second copy of the geometry. The five-node threshold counts each hand separately, so fewer than five mirrored copies of a mesh stay separate nodes. A batch of mirrored copies costs one draw per primitive like any other.+- **No shear.** A copy whose world matrix has shear, such as a rotated child of a non-uniformly scaled parent, stays a separate node, because an instance's translation, rotation and scale cannot state it.+- **Tangents stay correct.** three r186's WebGPU renderer transforms an instance's positions and normals but not its tangents, so a turned copy of a mesh with `TANGENT` would light its normal map wrongly and a quarter-turned one would shade black. Copies of such a mesh batch only with copies that share their rotation and stretch, which the batch node carries; the instances keep only translation and uniform scale. A rotation with fewer than five copies stays separate.+- **Required.** Batches mark `EXT_mesh_gpu_instancing` as required, so a viewer without it refuses the file instead of drawing one copy per batch.++CPU views expand every instance to its own matrix and draw these cases correctly either way, so they cannot confirm how a batch draws on the GPU.++The bake default stays as it is: `auto` batches only `role: 'fill'` assets, because a batch folds named mesh nodes into one. On the published cathedral, batching at bake folds 1,403 of its 1,707 named mesh nodes, which inspection, live review and exact rebuilds read. To cut draws for delivery without changing the saved revision, derive a runtime export with `--draws minimal`; see [export profiles](export-profiles.md#fewer-draw-calls).+Full mode's rigid-merge pass retains every node name, parent and transform. Geometry on a protectedboundary stays there; other named mesh nodes can become empty or hold their group'smerged geometry. Consumers that require geometry attached to each ordinary nameddiff --git a/src/__tests__/draw-reduction.test.ts b/src/__tests__/draw-reduction.test.tsnew file mode 100644index 00000000..de40d44f--- /dev/null+++ b/src/__tests__/draw-reduction.test.ts@@ -0,0 +1,203 @@+/**+ * The runtime derivative that minimizes draw calls: every repeat becomes a batch, the remaining+ * one-off parts merge per material within spatial cells, and the saved revision never changes.+ */+import { describe, expect, it } from 'bun:test';+import { createHash } from 'node:crypto';+import * as THREE from 'three';+import { exportAssetGlb } from '../asset-export';+import type { AssetRecord } from '../assets';+import { reduceDrawCalls } from '../draw-reduction';+import { createGltfIO } from '../gltf-io';+import { collectGlbMetrics } from '../metrics';+import {+ boxGeo,+ coneGeo,+ createInstance,+ createPart,+ createRoot,+ gameMaterial,+ planeGeo,+} from '../primitives';+import { renderSceneToGLB } from '../render';+import {+ REVIEW_DIRECTIONS,+ drawnFaces,+ facesDifference,+ loadThreeScene,+ wronglyWoundInstances,+} from './helpers/three-winding';++/** Two copies of a pane, a mirrored pair, three nearby one-offs, one far away, one blended. */+function buildingScene(): THREE.Object3D {+ const root = createRoot('Building');+ const stone = gameMaterial(0xc8c0a8);+ const pane = createPart('Pane0', planeGeo(1, 2), gameMaterial(0x803030), {+ position: [0, 1, 4],+ parent: root,+ });+ createInstance('Pane1', pane, { position: [3, 1, 4], parent: root });+ createInstance('MirrorPane0', pane, {+ position: [0, 1, 7],+ rotation: [0, 180, 0],+ scale: [1, 1, -1],+ parent: root,+ });+ createInstance('MirrorPane1', pane, {+ position: [3, 1, 7],+ rotation: [0, 180, 0],+ scale: [1, 1, -1],+ parent: root,+ });+ createPart('Wall', boxGeo(4, 3, 0.4), stone, { position: [0, 1.5, 0], parent: root });+ createPart('Pier', boxGeo(0.5, 3, 0.5), stone, { position: [3, 1.5, 0], parent: root });+ createPart('Spire', coneGeo(0.5, 2, 6), stone, {+ position: [6, 1, 0],+ scale: [1, 1, -1],+ parent: root,+ });+ createPart('FarPier', boxGeo(0.5, 3, 0.7), stone, { position: [100, 1.5, 0], parent: root });+ const decal = gameMaterial(0x202020);+ decal.transparent = true;+ decal.opacity = 0.5;+ createPart('Decal', planeGeo(1, 1), decal, { position: [0, 1, 0.3], parent: root });+ return root;+}++const sha = (bytes: Uint8Array) =>+ `sha256:${createHash('sha256').update(bytes).digest('hex')}` as `sha256:${string}`;++function record(bytes: Uint8Array): AssetRecord {+ return {+ manifest: {+ version: 'kiln.asset.v1',+ assetId: 'a_draws',+ revisionId: 'r_draws',+ name: 'Draw Probe',+ tags: [],+ createdAt: '2026-11-07T00:00:00.000Z',+ editable: false,+ files: { 'asset.glb': { bytes: bytes.length, sha256: sha(bytes) } },+ },+ files: { 'asset.glb': bytes },+ };+}++async function expectSameFaces(before: Uint8Array, after: Uint8Array, tolerance?: number) {+ const a = await loadThreeScene(before);+ const b = await loadThreeScene(after);+ expect(wronglyWoundInstances(b)).toBe(0);+ let compared = 0;+ for (const direction of REVIEW_DIRECTIONS) {+ const expected = drawnFaces(a, direction);+ compared += expected.length;+ expect(facesDifference(drawnFaces(b, direction), expected, tolerance)).toEqual({+ extra: 0,+ missing: 0,+ });+ }+ expect(compared).toBeGreaterThan(0);+}++describe('reduceDrawCalls', () => {+ it('batches every repeat, merges one-offs per cell and material, and draws the same', async () => {+ const { bytes } = await renderSceneToGLB(buildingScene(), { instance: 'off' });+ const io = createGltfIO();+ const doc = await io.readBinary(bytes);+ const before = collectGlbMetrics(doc);+ const summary = await reduceDrawCalls(doc, { cellSize: 15 });+ const after = collectGlbMetrics(doc);++ // Pane pair, mirrored pane pair, near stone cell, far stone part, the blended decal.+ expect(after.drawCalls).toBe(5);+ expect(after.triangles).toBe(before.triangles);+ expect(summary).toMatchObject({+ drawsBefore: before.drawCalls,+ drawsAfter: 5,+ batches: 2,+ instances: 4,+ cellSize: 15,+ });+ expect(summary.rejected).toEqual([]);+ await expectSameFaces(bytes, await io.writeBinary(doc));+ });++ it('never splits accessors that parts already share', async () => {+ const root = createRoot('Shared');+ const geo = boxGeo(1, 1, 1);+ const stone = gameMaterial(0x999999);+ for (let i = 0; i < 4; i++)+ createPart(`Part${i}`, geo, stone, {+ position: [i * 2, 0.5, 0],+ rotation: [0, i * 30, 0],+ parent: root,+ });+ const { bytes } = await renderSceneToGLB(root, { instance: 'off' });+ const doc = await createGltfIO().readBinary(bytes);+ const accessors = doc.getRoot().listAccessors().length;+ await reduceDrawCalls(doc);+ const geometry = doc+ .getRoot()+ .listAccessors()+ .filter((accessor) => accessor.listParents().some((p) => p.propertyType === 'Primitive'));+ expect(geometry.length).toBeLessThanOrEqual(accessors);+ expect(collectGlbMetrics(doc).drawCalls).toBe(1);+ });++ it('leaves a part a consumer addresses alone', async () => {+ const root = createRoot('Rigged');+ const stone = gameMaterial(0x999999);+ createPart('Wall', boxGeo(4, 3, 0.4), stone, { parent: root });+ createPart('Pier', boxGeo(0.5, 3, 0.5), stone, { position: [3, 0, 0], parent: root });+ const joint = new THREE.Group();+ joint.name = 'Joint_Door';+ root.add(joint);+ createPart('Door', boxGeo(1, 2, 0.1), stone, { parent: joint });+ const { bytes } = await renderSceneToGLB(root, { instance: 'off' });+ const doc = await createGltfIO().readBinary(bytes);+ const summary = await reduceDrawCalls(doc);+ expect(summary.batches).toBe(0);+ const door = doc+ .getRoot()+ .listNodes()+ .find((node) => node.getName() === 'Mesh_Door');+ expect(door?.getMesh()).not.toBeNull();+ });+});++describe('--draws minimal runtime export', () => {+ it('derives a reduced GLB with a receipt and leaves the saved revision alone', async () => {+ const { bytes } = await renderSceneToGLB(buildingScene(), { instance: 'off' });+ const saved = Uint8Array.from(bytes);+ const asset = record(saved);+ const output = await exportAssetGlb(asset, { profile: 'runtime', draws: 'minimal' });+ if (output.profile !== 'runtime') throw new Error('expected runtime');+ expect(asset.files['asset.glb']).toEqual(bytes);++ const metadata = JSON.parse(new TextDecoder().decode(output.metadata.bytes));+ expect(metadata.source.glbSha256).toBe(sha(saved));+ expect(metadata.drawReduction).toMatchObject({ drawsAfter: 5, batches: 2 });+ const doc = await createGltfIO().readBinary(output.glb);+ expect(collectGlbMetrics(doc).drawCalls).toBe(5);+ await expectSameFaces(bytes, output.glb);+ });++ it('composes with the three target', async () => {+ const { bytes } = await renderSceneToGLB(buildingScene(), { instance: 'off' });+ const output = await exportAssetGlb(record(Uint8Array.from(bytes)), {+ profile: 'runtime',+ target: 'three',+ draws: 'minimal',+ });+ if (output.profile !== 'runtime') throw new Error('expected runtime');+ await expectSameFaces(bytes, output.glb, 5e-3);+ });++ it('needs the runtime profile and a positive cell', async () => {+ const asset = record((await renderSceneToGLB(buildingScene(), { instance: 'off' })).bytes);+ await expect(exportAssetGlb(asset, { draws: 'minimal' })).rejects.toThrow(/runtime profile/);+ await expect(+ exportAssetGlb(asset, { profile: 'runtime', draws: 'minimal', drawCellSize: 0 }),+ ).rejects.toThrow(/positive/);+ });+});diff --git a/src/__tests__/helpers/three-winding.ts b/src/__tests__/helpers/three-winding.tsnew file mode 100644index 00000000..76e97311--- /dev/null+++ b/src/__tests__/helpers/three-winding.ts@@ -0,0 +1,101 @@+/**+ * What three.js draws for a GLB, without a GPU. CPU rasterization expands every instance to its+ * own matrix, so it cannot show three's per-object winding choice; this helper applies that+ * choice (`WebGLRenderer.renderBufferDirect`, `WebGPUPipelineUtils`: the winding comes from+ * `object.matrixWorld`, never from `instanceMatrix`) to what GLTFLoader actually loads.+ */+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';++type Face = [THREE.Vector3, THREE.Vector3, THREE.Vector3];++/** Load a GLB the way a three.js application does and resolve its world matrices. */+export async function loadThreeScene(bytes: Uint8Array): Promise<THREE.Object3D> {+ await MeshoptDecoder.ready;+ const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);+ const { scene } = await loader.parseAsync(Uint8Array.from(bytes).buffer, '');+ scene.updateMatrixWorld(true);+ return scene;+}++function instanceMatrices(mesh: THREE.Mesh): THREE.Matrix4[] {+ if (!(mesh as THREE.InstancedMesh).isInstancedMesh) return [new THREE.Matrix4()];+ const instanced = mesh as THREE.InstancedMesh;+ return Array.from({ length: instanced.count }, (_, index) => {+ const matrix = new THREE.Matrix4();+ instanced.getMatrixAt(index, matrix);+ return matrix;+ });+}++/** World triangles of the faces three.js keeps when the camera lies along `toCamera`. */+export function drawnFaces(scene: THREE.Object3D, toCamera: THREE.Vector3Like): Face[] {+ const camera = new THREE.Vector3().copy(toCamera);+ const faces: Face[] = [];+ scene.traverse((object) => {+ const mesh = object as THREE.Mesh;+ if (!mesh.isMesh) return;+ const material = mesh.material as THREE.Material;+ const frontFaceCW = mesh.matrixWorld.determinant() < 0;+ const positions = mesh.geometry.getAttribute('position');+ const index = mesh.geometry.getIndex();+ const count = index ? index.count : positions.count;+ for (const instance of instanceMatrices(mesh)) {+ const world = mesh.matrixWorld.clone().multiply(instance);+ for (let start = 0; start + 2 < count; start += 3) {+ const corner = (offset: number) =>+ new THREE.Vector3()+ .fromBufferAttribute(positions, index ? index.getX(start + offset) : start + offset)+ .applyMatrix4(world);+ const face: Face = [corner(0), corner(1), corner(2)];+ const towardCamera =+ new THREE.Vector3()+ .subVectors(face[1], face[0])+ .cross(new THREE.Vector3().subVectors(face[2], face[0]))+ .dot(camera) > 0;+ const front = towardCamera !== frontFaceCW;+ if (material.side === THREE.DoubleSide || front === (material.side === THREE.FrontSide))+ faces.push(face);+ }+ }+ });+ return faces;+}++/** Faces of `actual` with no counterpart in `expected`, and the reverse, within `tolerance`. */+export function facesDifference(+ actual: readonly Face[],+ expected: readonly Face[],+ tolerance = 1e-3,+): { extra: number; missing: number } {+ const sameCorner = (a: THREE.Vector3, b: THREE.Vector3) => a.distanceTo(b) <= tolerance;+ const sameFace = (a: Face, b: Face) => a.every((p) => b.some((q) => sameCorner(p, q)));+ const unmatched = [...expected];+ let extra = 0;+ for (const face of actual) {+ const match = unmatched.findIndex((candidate) => sameFace(face, candidate));+ if (match < 0) extra += 1;+ else unmatched.splice(match, 1);+ }+ return { extra, missing: unmatched.length };+}++/** Directions that see both sides of an axis-aligned face on all three axes. */+export const REVIEW_DIRECTIONS: readonly THREE.Vector3Like[] = [+ { x: 0.3, y: 0.5, z: 1 },+ { x: -0.3, y: -0.5, z: -1 },+ { x: 1, y: 0.2, z: -0.4 },+ { x: -1, y: -0.2, z: 0.4 },+];++/** The copies an `EXT_mesh_gpu_instancing` InstancedMesh draws wrong-way-round under three. */+export function wronglyWoundInstances(scene: THREE.Object3D): number {+ let wrong = 0;+ scene.traverse((object) => {+ const mesh = object as THREE.InstancedMesh;+ if (!mesh.isInstancedMesh) return;+ for (const instance of instanceMatrices(mesh)) if (instance.determinant() < 0) wrong += 1;+ });+ return wrong;+}diff --git a/src/__tests__/instancing.test.ts b/src/__tests__/instancing.test.tsindex 38260268..2eea03c7 100644--- a/src/__tests__/instancing.test.ts+++ b/src/__tests__/instancing.test.ts@@ -7,6 +7,7 @@*/import { describe, it, expect } from 'bun:test';+import type { InstancedMesh } from '@gltf-transform/extensions';import * as THREE from 'three';import {createRoot,@@ -15,8 +16,17 @@ import {cylinderGeo,boxGeo,gameMaterial,+ planeGeo,} from '../primitives';+import { createGltfIO } from '../gltf-io';import { gradeGlbBytes, optimizeGlbBytes, renderSceneToGLB } from '../render';+import {+ REVIEW_DIRECTIONS,+ drawnFaces,+ facesDifference,+ loadThreeScene,+ wronglyWoundInstances,+} from './helpers/three-winding';describe('Wave 1B: instancing primitives', () => {it('direct references share geometry and material between parts', () => {@@ -237,3 +247,176 @@ describe('M1c: GPU-instancing pass (instance option)', () => {).toBeUndefined();});});++// three.js picks the winding per object from matrixWorld, so one batch cannot hold both hands.+describe('M1c: mirrored copies under the GPU-instancing pass', () => {+ /** Single-sided panes: rotated, non-uniformly scaled, half of them mirrored on Z. */+ function paneScene(plain: number, mirrored: number): THREE.Object3D {+ const r = createRoot('Panes');+ const pane = createPart('Pane0', planeGeo(1, 2), gameMaterial(0x445566), {+ position: [0, 0, 0],+ parent: r,+ });+ for (let i = 1; i < plain; i++)+ createInstance(`Pane${i}`, pane, {+ position: [i * 2, 0, 0],+ rotation: [0, i * 20, 0],+ parent: r,+ });+ for (let i = 0; i < mirrored; i++)+ createInstance(`Mirror${i}`, pane, {+ position: [i * 2, 5, 1],+ rotation: [0, 180 + i * 15, i * 10],+ scale: [1.5, 0.75, -1],+ parent: r,+ });+ return r;+ }++ async function expectDrawnLikeUninstanced(build: () => THREE.Object3D) {+ const plain = await renderSceneToGLB(build(), { instance: 'off' });+ const inst = await renderSceneToGLB(build(), { instance: 'on' });+ expect(inst.instancing).toBeDefined();+ const plainScene = await loadThreeScene(plain.bytes);+ const instScene = await loadThreeScene(inst.bytes);+ expect(wronglyWoundInstances(instScene)).toBe(0);+ let compared = 0;+ for (const direction of REVIEW_DIRECTIONS) {+ const expected = drawnFaces(plainScene, direction);+ compared += expected.length;+ expect(facesDifference(drawnFaces(instScene, direction), expected)).toEqual({+ extra: 0,+ missing: 0,+ });+ }+ expect(compared).toBeGreaterThan(0);+ return inst;+ }++ it('a mirrored single-sided copy draws the same faces with instancing on and off', async () => {+ await expectDrawnLikeUninstanced(() => paneScene(6, 6));+ });++ it('too few mirrored copies to batch still draw the same', async () => {+ const inst = await expectDrawnLikeUninstanced(() => paneScene(6, 2));+ expect(inst.instancing!.instances).toBe(6);+ });++ it('handedness counts the whole world matrix, not the node scale alone', async () => {+ const build = () => {+ const r = paneScene(6, 0);+ const pane = r.children[0]!;+ const flipped = new THREE.Group();+ flipped.name = 'Flipped';+ flipped.scale.set(-1, 1, 1);+ flipped.position.set(0, 10, 0);+ r.add(flipped);+ // Mirrored through the parent alone, and mirrored twice back to right-handed.+ for (let i = 0; i < 6; i++)+ createInstance(`Parent${i}`, pane, { position: [i * 2, 0, 0], parent: flipped });+ for (let i = 0; i < 6; i++)+ createInstance(`Twice${i}`, pane, {+ position: [i * 2, 4, 0],+ scale: [1, 1, -1],+ parent: flipped,+ });+ return r;+ };+ await expectDrawnLikeUninstanced(build);+ });++ it('a copy that TRS cannot represent stays a plain node', async () => {+ const build = () => {+ const r = paneScene(6, 0);+ const pane = r.children[0]!;+ const stretched = new THREE.Group();+ stretched.name = 'Stretched';+ stretched.scale.set(1, 3, 1);+ stretched.position.set(0, 10, 0);+ r.add(stretched);+ // A rotated child under a non-uniform parent shears: instance TRS would straighten it.+ createInstance('Sheared', pane, { rotation: [0, 0, 40], parent: stretched });+ return r;+ };+ const inst = await expectDrawnLikeUninstanced(build);+ expect(inst.instancing!.instances).toBe(6);+ });++ // three r186's WebGPU instance node moves positions and normals but not TANGENT, so a turned+ // copy keeps its source tangent. At 90 degrees that lies along the normal and shades black.+ // A batch node's transform does reach the tangent, so it carries what the copies share.+ it('tangent-bearing copies batch per shared rotation, with the rotation on the node', async () => {+ const build = () => {+ const r = createRoot('Tangents');+ const geo = planeGeo(1, 2);+ geo.computeTangents();+ const source = createPart('Moved0', geo, gameMaterial(0x667788), { parent: r });+ for (let i = 1; i < 6; i++)+ createInstance(`Moved${i}`, source, {+ position: [i * 2, 0, 0],+ scale: i % 2 ? [2, 2, 2] : [1, 1, 1],+ parent: r,+ });+ for (let i = 0; i < 6; i++)+ createInstance(`Turned${i}`, source, {+ position: [i * 2, 4, 3],+ rotation: [0, 90, 0],+ scale: i % 2 ? [2, 2, 2] : [1, 1, 1],+ parent: r,+ });+ for (let i = 0; i < 6; i++)+ createInstance(`Stretched${i}`, source, {+ position: [i * 2, 8, 0],+ scale: [3, 1, 1],+ parent: r,+ });+ for (let i = 0; i < 6; i++)+ createInstance(`Mirrored${i}`, source, {+ position: [i * 2, 12, 0],+ rotation: [0, 30, 0],+ scale: [1, 1, -1],+ parent: r,+ });+ for (let i = 0; i < 4; i++)+ createInstance(`Varied${i}`, source, {+ position: [i * 2, 16, 0],+ rotation: [0, i * 40 + 15, 0],+ parent: r,+ });+ return r;+ };+ const inst = await expectDrawnLikeUninstanced(build);+ expect(inst.instancing).toMatchObject({ batches: 4, instances: 24 });+ const doc = await createGltfIO().readBinary(inst.bytes);+ for (const node of doc.getRoot().listNodes()) {+ const batch = node.getExtension<InstancedMesh>('EXT_mesh_gpu_instancing');+ if (!batch) continue;+ expect(batch.getAttribute('ROTATION')).toBeNull();+ const scale = batch.getAttribute('SCALE');+ for (let i = 0; i < (scale?.getCount() ?? 0); i++) {+ const [x, y, z] = scale!.getElement(i, [0, 0, 0]);+ expect(y).toBeCloseTo(x!, 5);+ expect(z).toBeCloseTo(x!, 5);+ }+ }+ });++ it('requires the extension, so a viewer without it refuses rather than drawing one copy', async () => {+ const inst = await renderSceneToGLB(paneScene(6, 6), { instance: 'on' });+ const json = glbJson(inst.bytes) as { extensionsRequired?: string[] };+ expect(json.extensionsRequired).toContain('EXT_mesh_gpu_instancing');+ });++ it('an optimizeGlbBytes pass honours handedness too', async () => {+ const plain = await renderSceneToGLB(paneScene(6, 6));+ const out = await optimizeGlbBytes(plain.bytes, { mode: 'off', instance: 'on' });+ const before = await loadThreeScene(plain.bytes);+ const after = await loadThreeScene(out!.bytes);+ expect(wronglyWoundInstances(after)).toBe(0);+ for (const direction of REVIEW_DIRECTIONS)+ expect(facesDifference(drawnFaces(after, direction), drawnFaces(before, direction))).toEqual({+ extra: 0,+ missing: 0,+ });+ });+});diff --git a/src/__tests__/rigid-merge.test.ts b/src/__tests__/rigid-merge.test.tsindex 8b8d9047..970198cb 100644--- a/src/__tests__/rigid-merge.test.ts+++ b/src/__tests__/rigid-merge.test.ts@@ -1193,3 +1193,49 @@ describe('mergeRigidGroups: release policies', () => {expect(prim.getIndices()!.getArray()).toBeInstanceOf(Uint16Array);});});++describe('mergeRigidGroups cellSize', () => {+ function spread() {+ const doc = new Document();+ const buffer = doc.createBuffer();+ const material = doc.createMaterial('Stone');+ const scene = doc.createScene('Scene');+ const positions = (x: number) =>+ new Float32Array([x + 0.123, 0.456, 0.789, x + 1.321, 0.654, 0.987, x + 0.111, 1.222, 0.333]);+ const part = (name: string, x: number) => {+ const position = doc+ .createAccessor()+ .setType('VEC3')+ .setArray(positions(x))+ .setBuffer(buffer);+ const prim = doc.createPrimitive().setAttribute('POSITION', position).setMaterial(material);+ scene.addChild(doc.createNode(name).setMesh(doc.createMesh(name).addPrimitive(prim)));+ };+ part('NearA', 0);+ part('NearB', 3);+ part('FarA', 40);+ part('FarB', 43);+ return doc;+ }++ test('merges only within a cell and keeps every triangle', () => {+ const whole = spread();+ expect(mergeRigidGroups(whole).primitivesAfter).toBe(1);++ const celled = spread();+ const summary = mergeRigidGroups(celled, { cellSize: 15 });+ expect(summary.primitivesAfter).toBe(2);+ expect(collectGlbMetrics(celled).triangles).toBe(4);+ });++ test('a loosened position tolerance is opt-in', () => {+ const far = () => {+ const doc = spread();+ for (const node of doc.getRoot().listNodes())+ node.setTranslation([node.getName() === 'NearA' ? 1000 : 0, 0, 0]);+ return doc;+ };+ expect(mergeRigidGroups(far()).rejected.length).toBeGreaterThan(0);+ expect(mergeRigidGroups(far(), { positionTolerance: 1e-3 }).rejected).toEqual([]);+ });+});diff --git a/src/__tests__/runtime-three-export.test.ts b/src/__tests__/runtime-three-export.test.tsindex b8a3d513..cc0c2c80 100644--- a/src/__tests__/runtime-three-export.test.ts+++ b/src/__tests__/runtime-three-export.test.ts@@ -23,6 +23,13 @@ import { renderGLBInProcess, renderSceneToGLB } from '../render';import { validateAtlasDocumentProvenance } from '../atlas-provenance';import { createGltfIO } from '../gltf-io';import { encodePng } from '../views/png';+import {+ REVIEW_DIRECTIONS,+ drawnFaces,+ facesDifference,+ loadThreeScene,+ wronglyWoundInstances,+} from './helpers/three-winding';const BUNKER = readFileSync(resolve('src/__tests__/fixtures/bunker-door-frame.kiln.js'), 'utf8');@@ -92,6 +99,55 @@ describe('repeatInstances', () => {});describe('three runtime target', () => {+ test('repeatInstances keeps mirrored copies drawn the right way round', async () => {+ const program = `const meta={name:'Mirrored Panes'};+function build(){+ const root=createRoot('Root');+ const pane=gameMaterial('#556677');+ const panes=new THREE.Group(); panes.name='Panes'; root.add(panes);+ const geo=planeGeo(1,2);+ for(let i=0;i<3;i++) createPart('Plain_'+i,geo,pane,{parent:panes,position:[i*2,0,0],rotation:[0,i*20,0]});+ for(let i=0;i<3;i++) createPart('Mirror_'+i,geo,pane,{parent:panes,position:[i*2,4,1],rotation:[0,180+i*15,i*10],scale:[1.5,0.75,-1]});+ repeatInstances(panes);+ return root;+}`;+ const rendered = await renderGLBInProcess(program);+ const source = new Uint8Array(rendered.glb);+ const delivered = await deliverThreeRuntimeGlb(source);+ const before = await loadThreeScene(source);+ const after = await loadThreeScene(delivered.glb);+ expect(wronglyWoundInstances(after)).toBe(0);+ let compared = 0;+ for (const direction of REVIEW_DIRECTIONS) {+ const expected = drawnFaces(before, direction);+ compared += expected.length;+ expect(facesDifference(drawnFaces(after, direction), expected, 2e-3)).toEqual({+ extra: 0,+ missing: 0,+ });+ }+ expect(compared).toBeGreaterThan(0);+ });++ test('repeatInstances batches a tangent-bearing mesh only where three can keep its tangents', async () => {+ const program = `const meta={name:'Tangent Panes'};+function build(){+ const root=createRoot('Root');+ const pane=gameMaterial('#556677');+ const panes=new THREE.Group(); panes.name='Panes'; root.add(panes);+ const geo=planeGeo(1,2); geo.computeTangents();+ for(let i=0;i<3;i++) createPart('Moved_'+i,geo,pane,{parent:panes,position:[i*2,0,0]});+ for(let i=0;i<3;i++) createPart('Turned_'+i,geo,pane,{parent:panes,position:[i*2,4,0],rotation:[0,90,0]});+ repeatInstances(panes);+ return root;+}`;+ const rendered = await renderGLBInProcess(program);+ const { delivery } = await deliverThreeRuntimeGlb(new Uint8Array(rendered.glb));+ expect(delivery.instancing.map((entry) => entry.instances)).toEqual([+ ['Mesh_Moved_0', 'Mesh_Moved_1', 'Mesh_Moved_2'],+ ]);+ });+for (const gltfExporter of ['legacy', 'three'] as const)test(`${gltfExporter} converter output qualifies through GLTFLoader`, async () => {const rendered = await renderGLBInProcess(RUNTIME_PROGRAM, { gltfExporter });diff --git a/src/asset-cli.test.ts b/src/asset-cli.test.tsindex 25158833..847aa56e 100644--- a/src/asset-cli.test.ts+++ b/src/asset-cli.test.ts@@ -262,7 +262,31 @@ test('CLI saves, exports, imports, and restores a revision across independent stJSON.parse(await readFile(join(root, 'float.kiln-metadata.json'), 'utf8')).delivery.quantization,).toMatchObject({ bits: { position: 'float32' }, maxPositionStep: 0 });+ // --draws minimal derives the reduced runtime file and states what it did.+ const drawsRun = run('first', [+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ join(root, 'draws.glb'),+ '--profile',+ 'runtime',+ '--draws',+ 'minimal',+ '--draw-cell',+ '30',+ '--json',+ ]);+ expect(drawsRun.status, drawsRun.stderr).toBe(0);+ expect(JSON.parse(drawsRun.stdout)).toMatchObject({ draws: 'minimal', drawCellSize: 30 });+ expect(+ JSON.parse(await readFile(join(root, 'draws.kiln-metadata.json'), 'utf8')).drawReduction,+ ).toMatchObject({ cellSize: 30 });for (const flags of [+ ['--draws', 'minimal'],+ ['--profile', 'runtime', '--draws', 'max'],+ ['--profile', 'runtime', '--draw-cell', '15'],+ ['--profile', 'runtime', '--draws', 'minimal', '--draw-cell', '0'],['--profile', 'runtime', '--position-bits', '16'],['--profile', 'runtime', '--target', 'three', '--position-bits', '7'],['--profile', 'runtime', '--target', 'three', '--position-bits', '17'],diff --git a/src/asset-cli.ts b/src/asset-cli.tsindex c8daf701..28a46d9a 100644--- a/src/asset-cli.ts+++ b/src/asset-cli.ts@@ -64,6 +64,9 @@ ${SAVE_LINES}(default 14) or float positions; the sidecar reports the grid step[--ktx2] with --target three: KTX2 through the optional [email protected] peer(npm install [email protected]), ETC1S colour, UASTC data maps+ [--draws minimal] runtime only: batch every repeated mesh and merge one-off parts+ per material; the saved revision is unchanged, the sidecar reports it+ [--draw-cell M] with --draws minimal: merge cell size in metres (default 15)[--textures manifest] runtime only: the sidecar names each image's exact bytes[--textures external] with --target three and --out x.gltf: x.gltf, x.bin andshared textures/<sha256>.<ext> files that are never replaced@@ -113,6 +116,8 @@ export async function assetMain(argv: readonly string[]): Promise<number> {'compression','max-lod','position-bits',+ 'draws',+ 'draw-cell','textures','port','render',@@ -428,6 +433,16 @@ export async function assetMain(argv: readonly string[]): Promise<number> {throw new Error('--position-bits requires --target three');const positionBits =bitsFlag === undefined || bitsFlag === 'float' ? bitsFlag : Number(bitsFlag);+ const draws = flags.draws;+ if (draws !== undefined && draws !== 'minimal') throw new Error('--draws must be minimal');+ if (draws !== undefined && profile !== 'runtime')+ throw new Error('--draws requires --profile runtime');+ const drawCellFlag = flags['draw-cell'];+ if (drawCellFlag !== undefined && draws === undefined)+ throw new Error('--draw-cell requires --draws minimal');+ const drawCellSize = drawCellFlag === undefined ? undefined : Number(drawCellFlag);+ if (drawCellSize !== undefined && !(drawCellSize > 0))+ throw new Error('--draw-cell must be a positive number of metres');const textures = flags.textures;if (textures !== undefined && textures !== 'manifest' && textures !== 'external')throw new Error('Unknown --textures value; use manifest or external');@@ -467,6 +482,8 @@ export async function assetMain(argv: readonly string[]): Promise<number> {...(compression ? { compression } : {}),...(maxLod !== undefined ? { maxLod } : {}),...(positionBits !== undefined ? { positionBits } : {}),+ ...(draws ? { draws } : {}),+ ...(drawCellSize !== undefined ? { drawCellSize } : {}),...(textures ? { textures } : {}),...(gltfLayout ? { gltfFileName: basename(destination) } : {}),...(flags.ktx2 ? { ktx2Encoder: await createKtx2Encoder() } : {}),@@ -539,6 +556,8 @@ export async function assetMain(argv: readonly string[]): Promise<number> {...(compression ? { compression } : {}),...(maxLod !== undefined ? { maxLod } : {}),...(positionBits !== undefined ? { positionBits } : {}),+ ...(draws ? { draws } : {}),+ ...(drawCellSize !== undefined ? { drawCellSize } : {}),format,...(ktx2Receipt ? { ktx2: ktx2Receipt } : {}),...(format !== 'source'diff --git a/src/asset-export.ts b/src/asset-export.tsindex b57ee86f..fe6e6f8b 100644--- a/src/asset-export.ts+++ b/src/asset-export.ts@@ -2,6 +2,7 @@* Saved-asset delivery profiles. No renderer, filesystem, or network dependencies; the* three.js runtime target loads its glTF passes and the meshopt encoder lazily.*/+import type { DrawReductionV1 } from './draw-reduction';import {ASSET_LIMIT,assetMaterialRootManifests,@@ -54,6 +55,10 @@ export interface AssetGlbExportOptions extends RuntimeThreeOptionsV1 {textures?: AssetExportTextures;/** External textures only: a portable sibling `*.gltf` filename. */gltfFileName?: string;+ /** Runtime only, opt-in: batch every repeat and merge one-off parts (see docs/export-profiles.md). */+ draws?: 'minimal';+ /** `draws` only: metres per merge cell; a viewer can cull one cell at a time. */+ drawCellSize?: number;}export type AssetGlbExport =| { profile: 'editable'; glb: Uint8Array }@@ -92,6 +97,8 @@ export interface RuntimeMetadataV1 {delivery?: RuntimeThreeDeliveryV1;/** Opt-in texture manifest: each delivered image's exact identity, by image index. */textures?: RuntimeTextureManifestEntryV1[];+ /** Present when `draws: 'minimal'` derived this file: what the reduction did. */+ drawReduction?: DrawReductionV1;}const encoder = new TextEncoder();@@ -253,6 +260,14 @@ export async function exportAssetGlb(throw new Error('Runtime maxLod requires the three runtime target');if (options.positionBits !== undefined && options.target !== 'three')throw new Error('Runtime positionBits requires the three runtime target');+ if (options.draws !== undefined && options.draws !== 'minimal')+ throw new Error('Unknown runtime draws option');+ if (options.draws !== undefined && profile !== 'runtime')+ throw new Error('A draw reduction requires the runtime profile');+ if (options.drawCellSize !== undefined && options.draws === undefined)+ throw new Error('A draw cell size requires the minimal draws option');+ if (options.drawCellSize !== undefined && !(options.drawCellSize > 0))+ throw new Error('The draw cell size must be a positive number of metres');const textures = options.textures;if (textures !== undefined && textures !== 'manifest' && textures !== 'external')throw new Error('Unknown runtime texture option');@@ -263,7 +278,7 @@ export async function exportAssetGlb(const gltfName = options.gltfFileName ?? 'runtime.gltf';if (textures === 'external') validateGltfFileName(gltfName);validateRecordShape(record);- const bytes = record.files['asset.glb']!;+ let bytes = record.files['asset.glb']!;if (profile === 'editable') return { profile, glb: bytes };const name = options.metadataFileName ?? 'runtime.kiln-metadata.json';validateMetadataFileName(name);@@ -272,6 +287,17 @@ export async function exportAssetGlb(throw new Error(`Asset integrity mismatch: ${file}`);}+ let drawReduction: DrawReductionV1 | undefined;+ if (options.draws) {+ const { reduceGlbDrawCalls } = await import('./draw-reduction');+ const reduced = await reduceGlbDrawCalls(bytes, {+ ...(options.drawCellSize !== undefined ? { cellSize: options.drawCellSize } : {}),+ });+ if (reduced.glb.byteLength > ASSET_LIMIT) throw new Error('Runtime export exceeds 64 MiB');+ bytes = reduced.glb;+ drawReduction = reduced.summary;+ }+const { json, jsonEnd } = readGlbJson(bytes);const asset = json.asset as Record<string, unknown>;if (owns(asset, 'extras') && !object(asset.extras))@@ -309,6 +335,7 @@ export async function exportAssetGlb(: {}),},scenes,+ ...(drawReduction ? { drawReduction } : {}),};// The three target derives from the review-free GLB; provenance is stamped on its result.let base = bytes,diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.tsindex e1e2a63c..98a61fa8 100644--- a/src/discovery/helper-contracts.ts+++ b/src/discovery/helper-contracts.ts@@ -1022,7 +1022,8 @@ define(parameters: ['parent: a scene node whose direct children repeat one mesh.'],semantics: ['The three.js runtime target groups direct children by mesh content (accessors, material, mode) and turns each group of two or more into one node named <parent>_Instances with EXT_mesh_gpu_instancing TRANSLATION/ROTATION/SCALE; the sidecar lists the instance names in order.',- 'Children with their own children, roles, extras, skins, morph weights or hidden flags stay separate nodes. Other export profiles ignore the mark.',+ 'Mirrored children form their own batch on a node scaled [-1, 1, 1], because a node states the winding for all its copies; the batch keeps the same mesh.',+ 'Children with their own children, roles, extras, skins, morph weights or hidden flags stay separate nodes, as does a turned, non-uniformly scaled or mirrored child of a mesh with TANGENT, whose tangents three.js WebGPU instancing would not transform. Other export profiles ignore the mark.',],cost: 'Metadata on one node.',},diff --git a/src/draw-reduction.ts b/src/draw-reduction.tsnew file mode 100644index 00000000..b5901de0--- /dev/null+++ b/src/draw-reduction.ts@@ -0,0 +1,114 @@+/**+ * A delivery derivative with as few draw calls as the asset allows. Every repeated mesh becomes a+ * GPU batch, then the one-off parts left over merge per material within spatial cells, so a viewer+ * can still cull a large asset by region.+ *+ * Unlike `optimize: 'full'` this runs no `palette()`, which rewrites materials, and no `weld()`,+ * which splits the accessors shared parts rely on: on a 16 MB cathedral `weld()` alone added 10 MB.+ * Saved revisions are never rewritten by this pass; `exportAssetGlb` derives from them.+ */+import { type Document, Logger } from '@gltf-transform/core';+import { prune } from '@gltf-transform/functions';+import {+ refreshAtlasDocumentProvenance,+ validateAtlasDocumentProvenance,+} from './atlas-provenance';+import { createGltfIO } from './gltf-io';+import {+ countInstanceBatches,+ instanceByHandedness,+ instancingBlocker,+} from './instance-handedness';+import { collectGlbMetrics } from './metrics';+import { assertFinalGlbValid } from './qa/gltf';+import { mergeRigidGroups, type RigidMergeSummary } from './rigid-merge';++/** Metres. Near the size a viewer's culling can use; set per export with `drawCellSize`. */+export const DEFAULT_DRAW_CELL_SIZE = 15;++/** Two copies already save a draw. The bake pass's higher threshold protects node names. */+const REPEAT_MIN = 2;++/**+ * Metres a merged vertex may move through float32 rounding in its destination frame. The strict+ * default rejects a metre-sized part baked 100 m from its destination, which rounds by about+ * 8 micrometres. 0.1 mm stays far below a pixel at any distance the part is visible from.+ */+const POSITION_TOLERANCE = 1e-4;++export interface DrawReductionV1 {+ drawsBefore: number;+ drawsAfter: number;+ batches: number;+ instances: number;+ /** Why no copy was batched, when something in the asset rules batching out. */+ batchingSkipped?: string;+ merges: number;+ cellSize: number;+ /** Primitives the merge left alone, by reason. */+ locked: Record<string, number>;+ /** Buckets left as authored because building or checking the join failed. */+ rejected: RigidMergeSummary['rejected'];+}++export function assertDrawCellSize(cellSize: number): void {+ if (!Number.isFinite(cellSize) || cellSize <= 0)+ throw new Error('The draw cell size must be a positive number of metres');+}++/** Reduce a finished document's draw calls in place. */+export async function reduceDrawCalls(+ doc: Document,+ options: { cellSize?: number } = {},+): Promise<DrawReductionV1> {+ const cellSize = options.cellSize ?? DEFAULT_DRAW_CELL_SIZE;+ assertDrawCellSize(cellSize);+ // Transform progress must not corrupt CLI JSON on stdout.+ doc.setLogger(new Logger(Logger.Verbosity.WARN));+ const drawsBefore = collectGlbMetrics(doc).drawCalls;++ const batchingSkipped = instancingBlocker(doc);+ if (!batchingSkipped) await instanceByHandedness(doc, REPEAT_MIN);+ const { batches, instances } = countInstanceBatches(doc);++ // Repeats are batches now. A copy left over shares its mesh with a batch, and baking it would+ // duplicate geometry; mixed into a bucket it can also push the join past the vertex limit,+ // which strands the true one-offs beside it. Only meshes with a single user merge.+ const merge = mergeRigidGroups(doc, {+ cellSize,+ positionTolerance: POSITION_TOLERANCE,+ expandSharedMeshes: false,+ });+ await doc.transform(prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));++ const locked: Record<string, number> = {};+ for (const { reason, primitives } of merge.locked)+ locked[reason] = (locked[reason] ?? 0) + primitives;+ return {+ drawsBefore,+ drawsAfter: collectGlbMetrics(doc).drawCalls,+ batches,+ instances,+ ...(batchingSkipped ? { batchingSkipped } : {}),+ merges: merge.merges,+ cellSize,+ locked,+ rejected: merge.rejected,+ };+}++/** {@link reduceDrawCalls} over GLB bytes, validated before they are handed back. */+export async function reduceGlbDrawCalls(+ bytes: Uint8Array,+ options: { cellSize?: number } = {},+): Promise<{ glb: Uint8Array; summary: DrawReductionV1 }> {+ const io = createGltfIO();+ const doc = await io.readBinary(bytes);+ await validateAtlasDocumentProvenance(doc);+ const summary = await reduceDrawCalls(doc, options);+ await refreshAtlasDocumentProvenance(doc);+ await validateAtlasDocumentProvenance(doc);+ const glb = await io.writeBinary(doc);+ await assertFinalGlbValid(glb);+ return { glb, summary };+}diff --git a/src/instance-handedness.ts b/src/instance-handedness.tsnew file mode 100644index 00000000..4a58c42f--- /dev/null+++ b/src/instance-handedness.ts@@ -0,0 +1,251 @@+/**+ * Keeps GPU instancing faithful to what the copies looked like as separate nodes.+ *+ * glTF takes a triangle's winding from the determinant of the node's global transform and has+ * no per-instance winding, and three.js reads it from `matrixWorld` alone. A negative-determinant+ * instance on a right-handed node therefore draws inside out: a single-sided surface culls its+ * front and a closed one shows its inner faces.+ *+ * A batch holds one handedness. Mirrored copies get their own batch on a reflected node, so the+ * node's determinant states the winding for all of them and no geometry is copied.+ *+ * three r186's WebGPU instance node (`nodes/accessors/Instance.js`) transforms positions and+ * normals but not `tangentLocal`, unlike its batch and skinning nodes and the WebGL shader. A+ * turned, stretched or mirrored instance of a tangent-bearing mesh keeps its source tangent, which+ * lights its normal map wrongly, and a quarter turn lays the tangent along the normal and shades+ * black. A node's own transform does reach the tangent, so such copies batch by the rotation and+ * stretch they share, carried on the batch node, leaving only translation and uniform scale on the+ * instances.+ */+import type { Accessor, Document, Mesh, Node, mat4, vec3, vec4 } from '@gltf-transform/core';+import { instance } from '@gltf-transform/functions';+import type { InstancedMesh } from '@gltf-transform/extensions';+import * as THREE from 'three';+import { MSFT_LOD } from './gltf-io';++/** The reflection a mirrored batch's node carries. */+const BATCH_REFLECTION: vec3 = [-1, 1, 1];++/** Columns further from perpendicular than this are shear that TRS cannot state. */+const SHEAR_COSINE_LIMIT = 1e-4;++/** Rotation axis components and relative scale spread below this count as no change. */+const LINEAR_TOLERANCE = 1e-4;++const dot = (a: readonly number[], b: readonly number[]) =>+ a[0]! * b[0]! + a[1]! * b[1]! + a[2]! * b[2]!;++/** A TRS scale reflects when an odd number of its axes are negative. */+export function isMirroredScale(scale: readonly number[]): boolean {+ return scale[0]! * scale[1]! * scale[2]! < 0;+}++/** The sign of the upper 3x3 determinant, which decides winding. */+function isMirroredMatrix(m: mat4): boolean {+ const determinant =+ m[0] * (m[5] * m[10] - m[6] * m[9]) -+ m[4] * (m[1] * m[10] - m[2] * m[9]) ++ m[8] * (m[1] * m[6] - m[2] * m[5]);+ return determinant < 0;+}++/** True when the axes are non-zero and perpendicular, so translation, rotation and scale state it. */+function hasExactTrs(m: mat4): boolean {+ const axes = [m.slice(0, 3), m.slice(4, 7), m.slice(8, 11)];+ if (axes.some((axis) => dot(axis, axis) === 0)) return false;+ return [+ [0, 1],+ [0, 2],+ [1, 2],+ ].every(([i, j]) => {+ const a = axes[i!]!;+ const b = axes[j!]!;+ return Math.abs(dot(a, b)) <= SHEAR_COSINE_LIMIT * Math.sqrt(dot(a, a) * dot(b, b));+ });+}++const hasTangents = (mesh: Mesh) =>+ mesh.listPrimitives().some((primitive) => primitive.getAttribute('TANGENT'));++/** The world matrix's rotation and stretch with uniform scale divided out, as a grouping key. */+function sharedLinearKey(m: mat4): string {+ const largest = Math.sqrt(+ Math.max(+ dot(m.slice(0, 3), m.slice(0, 3)),+ dot(m.slice(4, 7), m.slice(4, 7)),+ dot(m.slice(8, 11), m.slice(8, 11)),+ ),+ );+ return [0, 1, 2, 4, 5, 6, 8, 9, 10].map((i) => Math.round((m[i]! / largest) * 1e5)).join(',');+}++/** True when an instance's own rotation or stretch would not reach a tangent-bearing mesh's tangents. */+export function instancingLosesTangents(mesh: Mesh, rotation: vec4, scale: vec3): boolean {+ if (!hasTangents(mesh)) return false;+ const turned = rotation.slice(0, 3).some((axis) => Math.abs(axis) > LINEAR_TOLERANCE);+ const largest = Math.max(...scale);+ const uniform = Math.min(...scale) >= largest * (1 - LINEAR_TOLERANCE) && largest > 0;+ return turned || !uniform;+}++function negateComponents(accessor: Accessor | null, stride: number, components: number[]): void {+ const array = accessor?.getArray();+ if (!array) return;+ for (let start = 0; start < array.length; start += stride)+ for (const component of components) array[start + component] = -array[start + component]!;+}++/**+ * Rewrite a batch of mirrored transforms for a node that carries {@link BATCH_REFLECTION}: with+ * M that reflection, `M * T(t) R(q) S(s)` equals `T(Mt) R(MqM) S(Ms)`, each a sign flip. An+ * absent channel is the identity, which the reflection leaves alone.+ */+export function reflectInstanceBatch(node: Node, batch: InstancedMesh): void {+ negateComponents(batch.getAttribute('TRANSLATION'), 3, [0]);+ negateComponents(batch.getAttribute('ROTATION'), 4, [1, 2]);+ negateComponents(batch.getAttribute('SCALE'), 3, [0]);+ node.setScale(BATCH_REFLECTION);+}++interface SharedLinear {+ rotation: vec4;+ scale: vec3;+}++/** Move a batch's shared rotation and stretch to its node, leaving translation and uniform scale. */+function carrySharedLinear(doc: Document, node: Node, batch: InstancedMesh, shared: SharedLinear) {+ const translations = batch.getAttribute('TRANSLATION');+ const rotations = batch.getAttribute('ROTATION');+ const scales = batch.getAttribute('SCALE');+ const first = (translations ?? rotations ?? scales)!;+ const count = first.getCount();+ const inverse = new THREE.Quaternion(...shared.rotation).invert();+ const moved = new Float32Array(count * 3);+ const uniform = new Float32Array(count * 3);+ const point = new THREE.Vector3();+ for (let i = 0; i < count; i++) {+ if (translations) point.fromArray(translations.getElement(i, []));+ else point.set(0, 0, 0);+ point.applyQuaternion(inverse);+ moved.set(+ [point.x / shared.scale[0], point.y / shared.scale[1], point.z / shared.scale[2]],+ i * 3,+ );+ const k = scales ? Math.max(...scales.getElement(i, []).map(Math.abs)) : 1;+ uniform.set([k, k, k], i * 3);+ }+ const buffer = first.getBuffer();+ const accessor = (array: Float32Array<ArrayBuffer>) =>+ doc.createAccessor().setType('VEC3').setArray(array).setBuffer(buffer);+ batch.setAttribute('TRANSLATION', accessor(moved));+ batch.setAttribute('ROTATION', null);+ batch.setAttribute('SCALE', uniform.every((value) => value === 1) ? null : accessor(uniform));+ for (const old of [translations, rotations, scales]) old?.dispose();+ node.setRotation(shared.rotation).setScale(shared.scale);+}++/**+ * `instance()` groups by Mesh identity and flattens each node's world matrix to TRS, so it mixes+ * hands, straightens shear and rotates tangent-bearing copies. Stand-in meshes steer that grouping:+ * mirrored nodes share one per mesh and become their own batch, tangent-bearing nodes share one per+ * mesh and shared rotation, and a node no batch can draw faithfully gets its own and stays below+ * `min`. Every node and batch gets its real mesh back.+ */+export async function instanceByHandedness(doc: Document, min: number): Promise<void> {+ const root = doc.getRoot();+ const originals = new Map<Mesh, Mesh>();+ const standIn = (mesh: Mesh) => {+ const copy = doc.createMesh(mesh.getName());+ for (const primitive of mesh.listPrimitives()) copy.addPrimitive(primitive);+ originals.set(copy, mesh);+ return copy;+ };++ const mirrored = new Map<Mesh, Mesh>();+ const byLinear = new Map<Mesh, Map<string, Mesh>>();+ const sharedLinear = new Map<Mesh, SharedLinear>();+ for (const node of root.listNodes()) {+ const mesh = node.getMesh();+ if (!mesh) continue;+ const world = node.getWorldMatrix();+ if (!hasExactTrs(world)) {+ node.setMesh(standIn(mesh));+ } else if (hasTangents(mesh)) {+ const groups = byLinear.get(mesh) ?? new Map<string, Mesh>();+ byLinear.set(mesh, groups);+ const key = sharedLinearKey(world);+ let group = groups.get(key);+ if (!group) {+ group = standIn(mesh);+ groups.set(key, group);+ const scale = node.getWorldScale();+ const largest = Math.max(...scale.map(Math.abs));+ sharedLinear.set(group, {+ rotation: node.getWorldRotation(),+ scale: [scale[0] / largest, scale[1] / largest, scale[2] / largest],+ });+ }+ node.setMesh(group);+ } else if (isMirroredMatrix(world)) {+ if (!mirrored.has(mesh)) mirrored.set(mesh, standIn(mesh));+ node.setMesh(mirrored.get(mesh)!);+ }+ }++ await doc.transform(instance({ min }));++ const mirroredStandIns = new Set(mirrored.values());+ for (const node of root.listNodes()) {+ const mesh = node.getMesh();+ const original = mesh && originals.get(mesh);+ if (!original) continue;+ const batch = node.getExtension<InstancedMesh>('EXT_mesh_gpu_instancing');+ const shared = sharedLinear.get(mesh);+ if (batch && shared) carrySharedLinear(doc, node, batch, shared);+ else if (batch && mirroredStandIns.has(mesh)) reflectInstanceBatch(node, batch);+ node.setMesh(original);+ }+ for (const copy of originals.keys()) copy.dispose();+ // A viewer without the extension would silently draw one copy per batch: make it refuse instead.+ for (const extension of root.listExtensionsUsed())+ if (extension.extensionName === 'EXT_mesh_gpu_instancing') extension.setRequired(true);+}++/** Why this document cannot be batched at all, or undefined when it can. */+export function instancingBlocker(doc: Document): string | undefined {+ const root = doc.getRoot();+ if (root.listAnimations().length > 0) return 'animations';+ if (root.listSkins().length > 0) return 'skins';+ const nodes = root.listNodes();+ // Kiln City runtimes target pivots by name, and a batch drops per-node names.+ if (nodes.some((node) => /^joint[_-]/i.test(node.getName()))) return 'joint pivots';+ // An MSFT_lod chain's levels stand in for a node a batch would fold away.+ if (nodes.some((node) => node.getExtension(MSFT_LOD) !== null)) return 'levels of detail';+ // These transforms cannot preserve per-node state when they remove or reparent nodes.+ if (+ nodes.some(+ (node) =>+ node.getExtension('KHR_node_visibility') !== null ||+ Object.keys(node.getExtras()).length > 0,+ )+ )+ return 'node extras or visibility';+ return undefined;+}++export function countInstanceBatches(doc: Document): { batches: number; instances: number } {+ let batches = 0;+ let instances = 0;+ for (const node of doc.getRoot().listNodes()) {+ const batch = node.getExtension<InstancedMesh>('EXT_mesh_gpu_instancing');+ if (!batch) continue;+ batches += 1;+ instances +=+ (+ batch.getAttribute('TRANSLATION') ??+ batch.getAttribute('ROTATION') ??+ batch.getAttribute('SCALE')+ )?.getCount() ?? 0;+ }+ return { batches, instances };+}diff --git a/src/render.ts b/src/render.tsindex 9a667478..4abbd959 100644--- a/src/render.ts+++ b/src/render.ts@@ -29,7 +29,7 @@ import { AuthoringDiagnosticError, rethrowAuthoringError } from './evaluator/aut*/import * as THREE from 'three';-import { createGltfIO, MSFT_LOD } from './gltf-io';+import { createGltfIO } from './gltf-io';import { collectLodSets } from './lod';import { applyLodChains, summarizeLodChains } from './lod-export';import { applyNodeVisibility, drawnSceneBounds, summarizeHiddenNodes } from './node-visibility';@@ -69,7 +69,12 @@ import {import { createHash } from 'node:crypto';import { Document, Logger, type TextureInfo } from '@gltf-transform/core';import { KHRMaterialsEmissiveStrength } from '@gltf-transform/extensions';-import { dedup, instance, palette, weld, prune, mergeDocuments } from '@gltf-transform/functions';+import { dedup, palette, weld, prune, mergeDocuments } from '@gltf-transform/functions';+import {+ countInstanceBatches,+ instanceByHandedness,+ instancingBlocker,+} from './instance-handedness';import {buildSlotIndex,@@ -1574,39 +1579,6 @@ function resolveInstance(opt?: InstanceMode): InstanceMode {return env === 'off' || env === 'auto' || env === 'on' ? env : 'auto';}-/** True when any node carries a `Joint*` name — the Kiln City runtime targets- * those pivots by NAME (wheel spin/steer rigs), and instance() drops per-node- * names when it folds nodes into a batch. Such assets are never instanced. */-function hasJointPivots(doc: Document): boolean {- return doc- .getRoot()- .listNodes()- .some((n) => /^joint[_-]/i.test(n.getName()));-}--/** True when any node carries an `MSFT_lod` chain. Its lower levels sit outside the- * scene and stand in for that node under the same parent, so a pass that moves the node- * (flatten), merges it into a sibling (join) or folds it into an instance batch would- * leave the levels describing geometry that is no longer there. */-function hasNodeLevelsOfDetail(doc: Document): boolean {- return doc- .getRoot()- .listNodes()- .some((n) => n.getExtension(MSFT_LOD) !== null);-}--/** These transforms cannot preserve per-node state when they remove or reparent nodes. */-function hasPreservedNodeState(doc: Document): boolean {- return doc- .getRoot()- .listNodes()- .some(- (node) =>- node.getExtension('KHR_node_visibility') !== null ||- Object.keys(node.getExtras()).length > 0,- );-}-/*** Run the opt-in GPU-instancing pass (M1c) on a baked Document, in place.*@@ -1616,7 +1588,8 @@ function hasPreservedNodeState(doc: Document): boolean {* grade keys on material count and does not move.** Runs after dedup (which* links duplicate meshes so sharing is detectable) and before palette()* (the upstream-canonical dedup → instance → palette order; join() skips- * instanced nodes by design so `full` stays safe).+ * instanced nodes by design so `full` stays safe). {@link instanceByHandedness} keeps mirrored,+ * sheared and tangent-bearing copies drawing as they did as separate nodes.** Skipped (returns undefined) when:* - mode is `off`, or `auto` and the role is not `'fill'`;@@ -1633,29 +1606,12 @@ async function applyGpuInstancing(): Promise<InstancingSummary | undefined> {if (mode === 'off') return undefined;if (mode === 'auto' && role !== 'fill') return undefined;- const root = doc.getRoot();- if (root.listAnimations().length > 0 || root.listSkins().length > 0) return undefined;- if (hasJointPivots(doc) || hasNodeLevelsOfDetail(doc) || hasPreservedNodeState(doc))- return undefined;+ if (instancingBlocker(doc)) return undefined;const before = collectGlbMetrics(doc);- await doc.transform(instance({ min: INSTANCE_MIN }));+ await instanceByHandedness(doc, INSTANCE_MIN);- let batches = 0;- let instances = 0;- for (const node of root.listNodes()) {- const ext = node.getExtension('EXT_mesh_gpu_instancing') as {- getAttribute?: (name: string) => { getCount(): number } | null;- } | null;- if (!ext) continue;- batches += 1;- // Identity channels are disposed by the library, so read whichever survives.- instances +=- ext.getAttribute?.('TRANSLATION')?.getCount() ??- ext.getAttribute?.('ROTATION')?.getCount() ??- ext.getAttribute?.('SCALE')?.getCount() ??- 0;- }+ const { batches, instances } = countInstanceBatches(doc);if (batches === 0) return undefined;const after = collectGlbMetrics(doc);diff --git a/src/rigid-merge.ts b/src/rigid-merge.tsindex af2fa590..3d7267e6 100644--- a/src/rigid-merge.ts+++ b/src/rigid-merge.ts@@ -95,6 +95,10 @@ export interface RigidMergeOptions {* False locks every user as `shared-mesh`.*/expandSharedMeshes?: boolean;+ /** Join only parts whose bounds centres share a cube this many world units wide. */+ cellSize?: number;+ /** World units a vertex may move to float32 rounding in its destination frame, beyond the strict default. */+ positionTolerance?: number;}export interface RigidMergeSummary {@@ -232,6 +236,7 @@ function bucketKey(prim: Primitive,materials: ReadonlyMap<Material | null, number>,handedness: number | null,+ cell: string,): string {const layout = prim.listSemantics()@@ -242,7 +247,18 @@ function bucketKey(}).join('+');const hand = handedness !== null && prim.getAttribute('TANGENT') ? `|${handedness}` : '';- return `${materials.get(prim.getMaterial()) ?? -1}|${prim.getMode()}|${!!prim.getIndices()}|${layout}${hand}`;+ return `${materials.get(prim.getMaterial()) ?? -1}|${prim.getMode()}|${!!prim.getIndices()}|${layout}${hand}${cell}`;+}++/** The spatial cell of a primitive's world-space bounds centre. */+function cellOf(prim: Primitive, world: THREE.Matrix4, size: number): string {+ const position = prim.getAttribute('POSITION')!;+ const centre = new THREE.Vector3()+ .fromArray(position.getMinNormalized([]))+ .add(new THREE.Vector3().fromArray(position.getMaxNormalized([])))+ .multiplyScalar(0.5)+ .applyMatrix4(world);+ return `|${Math.floor(centre.x / size)},${Math.floor(centre.y / size)},${Math.floor(centre.z / size)}`;}function reverseWinding(prim: Primitive): void {@@ -322,6 +338,7 @@ function checkPositionPrecision(sourceWorld: THREE.Matrix4,destinationWorld: THREE.Matrix4,reversed: boolean,+ minimumTolerance: number,): void {const expected = new THREE.Vector3();const actual = new THREE.Vector3();@@ -341,6 +358,7 @@ function checkPositionPrecision(bounds.getSize(expected).length() * 1e-6,magnitude * Number.EPSILON * 32,Number.EPSILON,+ minimumTolerance,);if (error > tolerance) throw new Error('rigid merge: destination frame loses position precision');}@@ -401,7 +419,12 @@ function splitVertices(prim: Primitive, created: Property[]): Primitive[] {}/** Join one bucket into detached, checked primitives without touching the originals. */-function prepare(entries: Entry[], dst: Node, created: Property[]): Primitive[] {+function prepare(+ entries: Entry[],+ dst: Node,+ created: Property[],+ positionTolerance: number,+): Primitive[] {const destinationWorld = worldOf(dst);const inverse = destinationWorld.clone().invert();const copies = entries.map(({ node, prim }) => {@@ -432,6 +455,7 @@ function prepare(entries: Entry[], dst: Node, created: Property[]): Primitive[]sourceWorld,destinationWorld,reversed,+ positionTolerance,);}return copy;@@ -574,7 +598,8 @@ export function mergeRigidGroups(const primReason = primLock(prim, options.mergeTransparent === true);if (primReason) lock(node, primReason, 1);else {- const key = bucketKey(prim, materials, handedness);+ const cell = options.cellSize ? cellOf(prim, world, options.cellSize) : '';+ const key = bucketKey(prim, materials, handedness, cell);const list = group.get(key);if (list) list.push({ node, prim });else group.set(key, [{ node, prim }]);@@ -603,7 +628,7 @@ export function mergeRigidGroups(doc.getGraph().addEventListener('node:create', track);try {const destination = destinationOf(entries);- const merged = prepare(entries, destination, created);+ const merged = prepare(entries, destination, created, options.positionTolerance ?? 0);const savedDraws = entries.length - merged.length;const shared = entries.filter((entry) => removableBytes([entry]) < primitiveBytes([entry.prim]),diff --git a/src/runtime-three.ts b/src/runtime-three.tsindex 0923212e..703b333d 100644--- a/src/runtime-three.ts+++ b/src/runtime-three.ts@@ -40,6 +40,11 @@ import { KILN_SEMANTIC_ROLES, readSemanticMetadataV1FromExtras } from './contracimport { createGltfIO, type Lod, MSFT_LOD } from './gltf-io';import { deliveryNodePaths } from './delivery-inspect';import { KILN_REPEAT_INSTANCES_KEY } from './delivery';+import {+ instancingLosesTangents,+ isMirroredScale,+ reflectInstanceBatch,+} from './instance-handedness';import { collectGlbMetrics, isHiddenGltfNode } from './metrics';import { isKtx2, sha256Hex } from './runtime-textures';import { trimLodChains, type TrimmedLodChain } from './lod-export';@@ -261,10 +266,13 @@ function applyScopedInstancing(doc: Document): InstancingRecord[] {isHiddenGltfNode(child) ||rolesOf(child).length ||Object.keys(child.getExtras()).length ||- child.getWeights().length+ child.getWeights().length ||+ instancingLosesTangents(mesh, child.getRotation(), child.getScale()))continue;- const signature = meshSignature(mesh, ids);+ // One batch holds one handedness, because a node states the winding for all its copies.+ const hand = isMirroredScale(child.getScale()) ? 'mirrored' : 'plain';+ const signature = `${hand}/${meshSignature(mesh, ids)}`;groups.set(signature, [...(groups.get(signature) ?? []), child]);}let batchIndex = 0;@@ -298,6 +306,7 @@ function applyScopedInstancing(doc: Document): InstancingRecord[] {.createNode(name).setMesh(mesh).setExtension('EXT_mesh_gpu_instancing', batch);+ if (isMirroredScale(nodes[0]!.getScale())) reflectInstanceBatch(batchNode, batch);parent.addChild(batchNode);report.push({node: batchNode,