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
Fix the occlusion UV set after packing, drop a dead citation, document the bake environment variables (#132)
Matthew Kissingerac8456ce1cc8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 08c95324..0be625de 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,26 @@Changes to `@kiln/engine`. Source releases and installable package publication areseparate milestones. The package is not published on the npm registry.+## Unreleased++On `main` after the 0.10.0 release; the package version stays 0.10.0 until the next one.++- The kit pass (`applyKitContract`, `packKitGlb`) no longer folds an occlusion map into the+ metallic-roughness image when the two are read through different UV sets or+ `KHR_texture_transform` values. It used to point the occlusion slot at the+ metallic-roughness UV set as well, so a baked AO map on `TEXCOORD_1` was sampled through+ `TEXCOORD_0`. Such a material keeps its separate occlusion image and UV set, and the+ summary's new `ormSkipped` names the material and the reason; a matching pair packs as+ before, and packing no longer rewrites the occlusion slot's UV set.+- `src/render.ts` and `src/__tests__/optimize.test.ts` no longer cite+ `docs/kiln-material-consolidation-cycle.md`, which exists on no branch; the `OptimizeMode`+ comment states the rule in place.+- `docs/runtime.md` documents `KILN_BAKE_OPTIMIZE` and `KILN_BAKE_INSTANCE`: their values,+ that they only set the default for a render that omits `optimize` or `instance`, that the+ MCP and CLI tools pin `optimize: 'off'` (so only `KILN_BAKE_INSTANCE` reaches their GLBs),+ which library renders take the variables, and that a saved revision rebuilds with the+ options its manifest recorded. No behaviour changes.+## 0.10.0**Protocol revision 2026-07-28, and a server that answers before it loads.** The v1diff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex b8a024eb..6f4c4ce8 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -26126,7 +26126,11 @@ var init_validation = __esm(() => {// src/kit.tsimport { execFile } from "node:child_process";import { promisify } from "node:util";-import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";+import {+ KHRMaterialsVariants,+ KHRTextureBasisu,+ KHRTextureTransform+} from "@gltf-transform/extensions";var run, KTX_ENCODER_CANDIDATES;var init_kit = __esm(() => {run = promisify(execFile);diff --git a/dist/build.json b/dist/build.jsonindex 8d48ff02..d1816b92 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:fdf269f53a7c012595be3dc58bf8683487f155d05b2d4fccb8f8ade33122d8c8",+ "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71","engineVersion": "0.10.0","toolchain": "[email protected]",- "sourceHash": "ae0f3033c91c1291a1d939411d006cf2fb1896816549ed48f07387827c50b460",+ "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229","rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442","dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9","dependencies": {@@ -34,13 +34,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:f786c2b8086fd3c1118231ec1fb367d200edb7009e1cbf7b2d904efae7a3920f"+ "bundleHash": "sha256:2b59a716045f271f1b4d1588d10e6021bf7b61d2f487de738f47cf20fe64472f"},"agent-run": {- "identity": "sha256:fdf269f53a7c012595be3dc58bf8683487f155d05b2d4fccb8f8ade33122d8c8",+ "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71","engineVersion": "0.10.0","toolchain": "[email protected]",- "sourceHash": "ae0f3033c91c1291a1d939411d006cf2fb1896816549ed48f07387827c50b460",+ "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229","rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442","dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9","dependencies": {@@ -69,13 +69,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:0c3949cb6de4a6a8fd0404ab91ea1e059ce7f37d8f65908a02d81d456b292b3c"+ "bundleHash": "sha256:7b458dd2b0156445ac01721bd977532f12ba6c7ef7f12298fa717f9aa1474709"},"agent-providers": {- "identity": "sha256:fdf269f53a7c012595be3dc58bf8683487f155d05b2d4fccb8f8ade33122d8c8",+ "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71","engineVersion": "0.10.0","toolchain": "[email protected]",- "sourceHash": "ae0f3033c91c1291a1d939411d006cf2fb1896816549ed48f07387827c50b460",+ "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229","rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442","dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9","dependencies": {@@ -107,10 +107,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:fdf269f53a7c012595be3dc58bf8683487f155d05b2d4fccb8f8ade33122d8c8",+ "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71","engineVersion": "0.10.0","toolchain": "[email protected]",- "sourceHash": "ae0f3033c91c1291a1d939411d006cf2fb1896816549ed48f07387827c50b460",+ "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229","rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442","dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9","dependencies": {@@ -142,10 +142,10 @@"bundleHash": "sha256:aff8b03e5146a9e7bc32f0fcb7dea5e46d1e47634046b1df09b86f4cdc73b772"},"cli": {- "identity": "sha256:fdf269f53a7c012595be3dc58bf8683487f155d05b2d4fccb8f8ade33122d8c8",+ "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71","engineVersion": "0.10.0","toolchain": "[email protected]",- "sourceHash": "ae0f3033c91c1291a1d939411d006cf2fb1896816549ed48f07387827c50b460",+ "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229","rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442","dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9","dependencies": {@@ -174,13 +174,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:fe51598f7eb10c64665c1ec4dbe5cddc18ac3a32d92cc1a498f94a6645fee147"+ "bundleHash": "sha256:8f7369895732aaf38879b8ea3f5003625f0b0fe114ec1f7e010c83c5fab15908"},"engine": {- "identity": "sha256:fdf269f53a7c012595be3dc58bf8683487f155d05b2d4fccb8f8ade33122d8c8",+ "identity": "sha256:e998e55ac15e0ff3dd98484975724258c08932bf4a050199f3f1f490917c7a71","engineVersion": "0.10.0","toolchain": "[email protected]",- "sourceHash": "ae0f3033c91c1291a1d939411d006cf2fb1896816549ed48f07387827c50b460",+ "sourceHash": "1cdf0d9097fc093acbd552c0d14a7106a19987fc12d7b4c5ea3f98f017a73229","rendererSourceHash": "27a01f842fffb183ce0da5044a100c172109bf791b0701da1cf56b6bc74db442","dependencyHash": "da9e9142ff49f835d5438b770d065358aba655fb38e9dd453220d31b65ec17e9","dependencies": {@@ -209,7 +209,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:e7e14a009a845bcad45693218f1559459c7a45f187d8baa958fbe6e6338586e5"+ "bundleHash": "sha256:76df0fd371e5b1da8f3f94f087791a043738e3169364cc2653f6df25359d00fc"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex 348cc5e1..0d77244e 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -25118,7 +25118,11 @@ var init_validation = __esm(() => {// src/kit.tsimport { execFile } from "node:child_process";import { promisify } from "node:util";-import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";+import {+ KHRMaterialsVariants,+ KHRTextureBasisu,+ KHRTextureTransform+} from "@gltf-transform/extensions";var run, KTX_ENCODER_CANDIDATES;var init_kit = __esm(() => {run = promisify(execFile);diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex 0c5830e5..5acc1140 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -22207,7 +22207,11 @@ var init_validation = __esm(() => {// src/kit.tsimport { execFile } from "node:child_process";import { promisify } from "node:util";-import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";+import {+ KHRMaterialsVariants,+ KHRTextureBasisu,+ KHRTextureTransform+} from "@gltf-transform/extensions";var run, KTX_ENCODER_CANDIDATES;var init_kit = __esm(() => {run = promisify(execFile);diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex 9c24452a..e7eb79e0 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -24324,7 +24324,11 @@ var init_validation = __esm(() => {// src/kit.tsimport { execFile } from "node:child_process";import { promisify } from "node:util";-import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";+import {+ KHRMaterialsVariants,+ KHRTextureBasisu,+ KHRTextureTransform+} from "@gltf-transform/extensions";var run, KTX_ENCODER_CANDIDATES;var init_kit = __esm(() => {run = promisify(execFile);diff --git a/docs/plans/2026-10-02-cycle-close.md b/docs/plans/2026-10-02-cycle-close.mdnew file mode 100644index 00000000..e1b5d64b--- /dev/null+++ b/docs/plans/2026-10-02-cycle-close.md@@ -0,0 +1,74 @@+# Cycle close before the trip: plan of record (2 October 2026)++Written 14:05 -04:00, revised 14:40 after the owner's direction ("finish what can be committed, pushed, merged and deployed before the trip; clear-cut engine defects confirmed by the adversarial review go in; tricky or undetermined work waits for the hub and is documented") and after the engine module review.++Owners: **F** = the engine session (orchestration, merges, releases, hub sync), **O1** = Opus agent landing the scenes work (PR 1), **O2** = Opus agent fixing the clear-cut engine defects (PR 3), **Owner** = Matt, who continues on the hub (his Linux laptop) after the trip.++## 1. Verdict on the draw-optimization branch++**What it is.** 25 local commits on `c734e2a`: 18 scenes, 2 compose-scene skill, 4 records, 1 engine (`e72b610`). Runtime-only scene optimizations (merge by material within anchors, cached sun shadow with stand-ins, MSAA discard, count probe, A/B timing runner); no GLB, pack, site, `dist/` or `src/` change apart from `e72b610`, which nothing imports. Scenes gates on the tip: typecheck and lint clean, 533 pass / 22 skip / 0 fail. No file overlaps 0.10.0; a trial merge onto `main` is clean.++**What is proven vs reported.** Every draw, frame-time and byte figure is the author's: the evidence (5.6 GB) is in ignored folders, none of it committed or re-derivable on this PC. Counts came from committed tooling and are deterministic; timing came from the quiet hub and the tablet under the owner's rules. The committed numbers are the AFTER baselines only (Farm `x02-baseline.json`, Foundry `count-baseline.json`, Golden Gate `PERFORMANCE.md`). The headline table (Farm landing 583 → 283 draws settled; Golden Gate arrival 432 → 103; Foundry campus pipelines 21 → 10) is author-reported. The Farm is the only scene the site ships from source, so the site's Farm build check and the deployed look are the real acceptance.++**Disagreements with the agent's plan as written.**+1. Its 12-item "landing" goal is mostly new work (reversed depth with three renderer adaptations and two-backend parity; reflection content; a banks flag; the trailer exemption; thin-line budgets; timing-runner columns; four tooling items; profile cleanup) plus two hours of hub timing and two paid dogfood sessions. The hub is the laptop; none of that runs before the trip. Split: land what exists now, do the new work after.+2. The committed records still carry the six errors the agent itself listed (D30), four private links, stale counts and `tmp/` citations that read as committed. PR 1's records commit fixes them.+3. D8 (trailer shadows at economy) was answered yes but not implemented; it needs captures and a re-baseline, so it is recorded as adopted-deferred.+4. Wiring `optimize: 'full'` is not "unreachable by tools": `KILN_BAKE_OPTIMIZE` is the evaluator default for every render that omits `optimize`, two view paths (`renderCodeViewGrid`, `rasterizeComposedScene`) render bare, and the rebuild CLI replays a manifest's recorded `optimize`. A revision saved under `full` would rebuild to different bytes after the wiring. This, not the draw savings, is the risk to users.+5. The handoff's owner-only questions were never asked (Kiln Studio's `optimizeGlbBytes` mode; placement wrappers as boundaries; the named-node contract). They stay open for the hub.+6. The batch timestamps were estimated, then corrected from the transcript; the committed times now agree with the commit times. Process note.+7. Golden Gate's gzip headroom after this branch is 6.3 KB; the next Golden Gate change hits the bundle ceiling. Known cost of the post-trip work.+8. The compose-scene skill (+69 lines) ships without a dogfood run; accepted, dogfood after the trip.++**Engine modules, adversarial review (14:35).** `src/rigid-merge.ts` and `src/extension-compat.ts` are sound: 28 of 28 tests pass; baking of positions, normals and tangents (inverse-transpose, `w *= sign(det)`, winding reversal) verified by probes; deterministic output (two builds byte-identical); boundaries, locks, shared meshes, partial-mesh merges and animation targets behave as specified; the wiring patch ports mechanically onto `main`. **Not landable as one engine PR until** six items are done, each needing design or a decision:+- D2 "copy a shared mesh at most 4 KB per saved draw" is not implementable as drafted: the variant only widens `expandSharedMeshes` to a predicate that runs before buckets exist, so the saved draw is unknowable; a usable definition is `bakedBytes(mesh) ≤ 4096` (float32 POSITION/NORMAL/TANGENT plus index bytes) decided in `nodeLock` and reported on the lock entry, then re-measured.+- `MSFT_lod` referenced levels are not boundaries (only the node carrying the extension is): an in-scene lower level absorbed a wall's triangles in a probe. Kiln-written chains are safe because the exporter moves levels off-scene; `optimizeGlbBytes(…, 'full')` on an imported GLB is not.+- The wiring drops the merge summary: a rejected bucket yields `mode: 'full'` with unchanged draws and no warning. `OptimizeSummary` needs a `merge` block and `renderGLB` the warnings.+- The bake frame is the first contributing node with no conditioning check (a `[1, 1e-6, 1]` scale passes `isSingular` and bakes the bucket at ×1e6); choose the best-conditioned world matrix deterministically.+- D3 (split at 65,534 vertices) exists in the variant as an opt-in option, is not passed by the patch, and has no test; the rule is vertex count, not largest index.+- The rebuild and env consequences (item 4 above) need a recorded pipeline version in `rebuildOptions` and a Breaking CHANGELOG entry.+Plus missing tests (D2/D3 cases, in-scene LOD levels, partial-mesh and cross-group shared meshes, determinism through `consolidateMaterials`, UV/COLOR/texture-transform layouts, quantized primitives, a full `renderSceneToGLB` geometry assertion, a pre-wiring `full` manifest). Notes for later: lock reports keyed by node name are ambiguous; the apply phase is outside the per-bucket try/catch; `extension-compat`'s malformed-JSON path throws a raw `SyntaxError`, `unverified` profiles can never say `blocked`, and the Godot/Unity/Bevy allowlists rest on citations the tests merely pin.++**Clear-cut defects in the current engine (fixed now, PR 3):** the D34 hazards, which exist on `main` today. (1) `src/kit.ts` packs occlusion into the metallic-roughness image and points the occlusion texture at the metallic-roughness UV set without checking that the two sets match, so a baked AO map on UV1 would be sampled with UV0. (2) `src/render.ts` and `src/__tests__/optimize.test.ts` cite `docs/kiln-material-consolidation-cycle.md`, which exists on no branch. (3) `KILN_BAKE_OPTIMIZE` and `KILN_BAKE_INSTANCE` are read in `local-runtime.ts`, `render.ts` and the registry and documented nowhere; the two bare view renders inherit the env default while tool renders pin `off`.++## 2. Phase 0 (F): done+- PR #129 (Kiln 0.10.0) merged as `9375d04`; tag `v0.10.0` and the GitHub release with the CI tarball, six receipts and `SHA256SUMS.txt`.+- PR #130 (install guide, README and site copy for the download) merged as `a396612`.++## 3. Phase 1 (O1, then F): PR 1, the scenes landing+- 1.1 New worktree `kiln-draw-landing`, branch `draw-optimization-landing` from `origin/main`; cherry-pick the 24 non-engine commits.+- 1.2 Records commit: D30's six errors, private links replaced, stale counts, `tmp/` citations labelled ignored, `scenes/DECISIONS.md` D-65 onward with the owner's answers and "adopted; implementation after the trip" where the code is not in this PR, a dated log row in the landing plan.+- 1.3 D24 compose-scene corrections; `check:skills`.+- 1.4 Gates: check:skills, root typecheck and lint, `bun test scripts`; scenes typecheck, lint, test; `dist/` byte-identical to main.+- 1.5 Push, open PR 1 (no merge). F reads CI (the Website job builds the Farm from this source) and squash-merges.++## 4. Phase 2 (O2, then F): PR 3, the clear-cut engine fixes+- 3.1 Branch `engine-d34-fixes` from `origin/main` in a new worktree `kiln-engine-fixes`.+- 3.2 Test first: `src/kit.ts` occlusion packing checks the UV sets; when they differ the material keeps its separate occlusion texture and the summary says so.+- 3.3 Remove the two citations of the missing doc.+- 3.4 Document `KILN_BAKE_OPTIMIZE` and `KILN_BAKE_INSTANCE` where the runtime environment is documented, including that tool renders pin `optimize: 'off'`, that a render which omits `optimize` takes the env default, and that a saved revision rebuilds with the `optimize` its manifest recorded.+- 3.5 CHANGELOG: an "Unreleased" section above 0.10.0 with the three entries. No version bump: the package stays 0.10.0 and `main` is ahead of the release, as the install guide allows.+- 3.6 `node scripts/build-runtime.mjs all`; gates: typecheck, lint, test, test:render-service, check:skills (coverage runs in CI); the plan file `docs/plans/2026-10-02-cycle-close.md` (this document) committed in the same PR.+- 3.7 PR 3; F merges after PR 1.++## 5. Phase 3 (F; the deploy on the owner's word): the site+- 3.1 Launch-mode `bun run build` from clean `main` (after PR 1 and PR 3), the site's validation, `site/scripts/deploy.ps1 -DryRun`.+- 3.2 Deploy (ships the 0.10 download instructions and the optimized Farm); verify `build-info.json`, home, install and the Farm scene live.+- 3.3 No new tag: the package is still 0.10.0 (`e1ce85d7…`).++## 6. Phase 4 (F): hub sync+- 4.1 Done: `~/X/kiln` on `main` at the merged docs commit; the raw `draw-optimization` branch pushed over SSH into `~/X/kiln` (never to GitHub: its records carry the private links until PR 1 fixes them) and checked out as the worktree `~/X/kiln-draw-optimization` at `4a1d238`; its ignored evidence copied by tar over ssh (18,195 files: `tmp/drawcalls`, `scenes/evidence`, `scenes/.tmp/build-src/{draw-base,flicker-revz2}`; counts verified both sides).+- 4.2 After the merges: `~/X/kiln` to the final `main`; `bun install --frozen-lockfile` at the root and in `scenes/`; the landing branch fetched.+- 4.3 The private evidence repository (`~/X/kiln-dogfood/v1-readiness-2026-10`) pulled; this PC's `tmp/harness-probe` committed into it.+- 4.4 The Troy workspace repaired to the hub's runtime (`create-workspace.mjs … --repair`, `kiln.mjs init --check`).+- 4.5 `~/X/START-HERE.md` on the hub: every folder, what is where, the next steps (this plan's section 7).+- 4.6 A cleanup list for the owner (worktrees and branches on this PC; decision 34).++## 7. After the trip, on the hub+- **Engine PR (0.11.0):** `e72b610` plus the six review items above, the wiring, D2 and D3 with tests, the three "falls back to palette" texts, a Breaking CHANGELOG entry, a pipeline version in `rebuildOptions`, one `dist/` rebuild, the full gate and a fresh clone; then D23's output-only draw signals, the authoring and QA skill proposals, and dogfood in Agy and OpenCode. Open questions first: Q1 does anything outside the repository call `optimize: 'full'` (Kiln Studio's `optimizeGlbBytes`); Q2 placement wrappers as boundaries (recommended: one `keep` at the `composeSceneGLB` call site); Q3 keep the named-node contract rather than plumbing `keep` through `RenderSceneOptions` (recommended: keep).+- **Scenes PR 1b:** D15 reversed depth with D5 and D6 (watch the Golden Gate gzip ceiling), D8, D16, D18, D19, D32; the hub timing (D21) on the quiet laptop; the compose-scene dogfood (D31). Then D20 tooling, the D22 stalls, D26 correctness, D27 run-time layout, the D29 reseal of Golden Gate and Foundry Floor with an approved upload, the D33 GPU cycle.+- **Troy:** the asset revisions the owner listed, the real battle scene under `scenes/packages/`, the gallery (needs pinned-material support in the site build), the pack's move into the scenes workspace. The handoff is `packs/troy/HANDOFF.md`.++## 8. Decisions+- A (the split), B (no 0.11.0 now; clear-cut fixes land without a bump) and C (one site deploy after the merges, on the owner's word): taken by the owner's direction of 2 October, 14:00 to 14:20.+- Q1 to Q3: open, for the hub.diff --git a/docs/runtime.md b/docs/runtime.mdindex b684df18..6cc0fd17 100644--- a/docs/runtime.md+++ b/docs/runtime.md@@ -131,6 +131,17 @@ Use `kiln_discover({ capabilities: true })` or `node kiln.mjs discover --capabilAdvanced geometry callbacks also have operation-specific input limits. Those checks do not replace the process deadline: a callback that never returns cannot check its own evaluation counter. Capture pixels and PNG payloads have independent host limits described in [cameras](cameras.md).+### Bake defaults++`KILN_BAKE_OPTIMIZE` and `KILN_BAKE_INSTANCE` choose the bake passes for a render that does not pass `optimize` or `instance`; a value the call passes always wins.++| Environment variable | Supported values |+| --- | --- |+| `KILN_BAKE_OPTIMIZE` | `off` (default), `auto`, `palette` or `full`; any other value means `off`. `palette` merges flat-colour materials into one palette material and texture, `auto` does so only for an asset with at least four distinct materials, and `full` also flattens and joins meshes to cut draw calls, falling back to `palette` for an asset that is animated, skinned or LOD-chained or has nodes that carry extras or visibility |+| `KILN_BAKE_INSTANCE` | `auto` (default), `off` or `on`; any other value means `auto`. `on` batches a mesh shared by five or more nodes with `EXT_mesh_gpu_instancing` and `auto` does so only for `role: 'fill'` assets; neither batches an animated or skinned asset, or one with `Joint_` pivots, LOD chains, or nodes that carry extras or visibility |++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.+## What a build identity coversTwo hashes identify a local Kiln and they answer different questions. The **builddiff --git a/src/__tests__/kit.test.ts b/src/__tests__/kit.test.tsindex 82d50897..531ebeb1 100644--- a/src/__tests__/kit.test.ts+++ b/src/__tests__/kit.test.ts@@ -8,16 +8,23 @@*/import { describe, expect, test } from 'bun:test';-import { WebIO } from '@gltf-transform/core';+import { Document, WebIO } from '@gltf-transform/core';import {KHRMaterialsEmissiveStrength,KHRMaterialsVariants,KHRTextureBasisu,+ KHRTextureTransform,} from '@gltf-transform/extensions';-import { findKtxEncoder, resetKtxEncoderProbe, type KitVariantSpec } from '../kit';+import {+ applyKitContract,+ findKtxEncoder,+ resetKtxEncoderProbe,+ type KitVariantSpec,+} from '../kit';import { hexToLinearRgb } from '../palette-snap';import { packKitGlb, renderGLB } from '../render';+import { encodePng } from '../views/png';const io = (): WebIO => new WebIO().registerExtensions([KHRMaterialsVariants, KHRTextureBasisu]);@@ -126,6 +133,27 @@ async function glbOf(code: string): Promise<Uint8Array> {return (await renderGLB(code, {})).glb;}+/** One material whose occlusion and metallic-roughness maps are distinct PNGs of the+ * same size, each read through the UV set given — so all a case varies is how the+ * two maps are sampled. */+function occlusionBesideMetallicRoughness(occlusionUv: number, metallicRoughnessUv: number) {+ const doc = new Document();+ const png = (value: number): Uint8Array =>+ Uint8Array.from(encodePng(new Uint8Array(4 * 4 * 3).fill(value), 4, 4));+ const occlusion = doc.createTexture('Occlusion').setMimeType('image/png').setImage(png(200));+ const metallicRoughness = doc+ .createTexture('MetallicRoughness')+ .setMimeType('image/png')+ .setImage(png(90));+ const material = doc+ .createMaterial('Panel')+ .setOcclusionTexture(occlusion)+ .setMetallicRoughnessTexture(metallicRoughness);+ material.getOcclusionTextureInfo()!.setTexCoord(occlusionUv);+ material.getMetallicRoughnessTextureInfo()!.setTexCoord(metallicRoughnessUv);+ return { doc, material, occlusion, metallicRoughness };+}+describe('ORM channel packing', () => {test('the occlusion image is folded in AND removed from the file', async () => {const original = await glbOf(ORM);@@ -163,6 +191,75 @@ describe('ORM channel packing', () => {expect(packed).toBeUndefined();});++ test('an occlusion map on another UV set keeps its own image and UV set', async () => {+ // A baked AO map usually lives on TEXCOORD_1 while metallic-roughness uses+ // TEXCOORD_0. Their pixels describe different layouts, so folding the AO into+ // the metallic-roughness image would sample it through the wrong UV set.+ const { doc, material, occlusion, metallicRoughness } = occlusionBesideMetallicRoughness(1, 0);+ const occlusionBytes = occlusion.getImage();+ const metallicRoughnessBytes = metallicRoughness.getImage();++ const summary = await applyKitContract(doc, { ktx2: false });++ expect(material.getOcclusionTexture()).toBe(occlusion);+ expect(material.getOcclusionTextureInfo()?.getTexCoord()).toBe(1);+ expect(occlusion.getImage()).toEqual(occlusionBytes);+ expect(metallicRoughness.getImage()).toEqual(metallicRoughnessBytes);+ expect(doc.getRoot().listTextures()).toHaveLength(2);+ expect(summary.ormPacked).toBe(0);+ expect(summary.ormSkipped).toHaveLength(1);+ expect(summary.ormSkipped?.[0]).toMatch(/"Panel".*TEXCOORD_1.*TEXCOORD_0/);+ });++ test('an occlusion map under a different texture transform keeps its own image', async () => {+ // Same UV set, but KHR_texture_transform tiles metallic-roughness four times, so+ // the two images still map different pixels to the same point on the surface.+ const { doc, material, occlusion } = occlusionBesideMetallicRoughness(0, 0);+ const transforms = doc.createExtension(KHRTextureTransform);+ material+ .getMetallicRoughnessTextureInfo()!+ .setExtension('KHR_texture_transform', transforms.createTransform().setScale([4, 4]));++ const summary = await applyKitContract(doc, { ktx2: false });++ expect(material.getOcclusionTexture()).toBe(occlusion);+ expect(summary.ormPacked).toBe(0);+ expect(summary.ormSkipped).toHaveLength(1);+ expect(summary.ormSkipped?.[0]).toMatch(/"Panel".*KHR_texture_transform/);+ });++ test('an occlusion map on the same UV set as metallic-roughness still packs', async () => {+ // Both on UV set 1: packing names one image for both slots and leaves the+ // occlusion reading the UV set it was authored for.+ const { doc, material, metallicRoughness } = occlusionBesideMetallicRoughness(1, 1);++ const summary = await applyKitContract(doc, { ktx2: false });++ expect(summary.ormPacked).toBe(1);+ expect(summary.ormSkipped).toBeUndefined();+ expect(material.getOcclusionTexture()).toBe(metallicRoughness);+ expect(material.getOcclusionTextureInfo()?.getTexCoord()).toBe(1);+ expect(doc.getRoot().listTextures()).toHaveLength(1);+ });++ test('equal texture transforms held in separate objects still pack', async () => {+ // The pass compares the transforms' values, not their identity.+ const { doc, material, metallicRoughness } = occlusionBesideMetallicRoughness(0, 0);+ const transforms = doc.createExtension(KHRTextureTransform);+ for (const info of [+ material.getOcclusionTextureInfo()!,+ material.getMetallicRoughnessTextureInfo()!,+ ]) {+ info.setExtension('KHR_texture_transform', transforms.createTransform().setScale([2, 2]));+ }++ const summary = await applyKitContract(doc, { ktx2: false });++ expect(summary.ormPacked).toBe(1);+ expect(summary.ormSkipped).toBeUndefined();+ expect(material.getOcclusionTexture()).toBe(metallicRoughness);+ });});describe('palette colourways as KHR_materials_variants', () => {diff --git a/src/__tests__/optimize.test.ts b/src/__tests__/optimize.test.tsindex 3fef2992..8e74d1af 100644--- a/src/__tests__/optimize.test.ts+++ b/src/__tests__/optimize.test.ts@@ -1,7 +1,7 @@/*** Move 1 — bake-time material consolidation (the opt-in `optimize` pass).*- * Covers the load-bearing guarantees from docs/kiln-material-consolidation-cycle.md:+ * Covers the pass's load-bearing guarantees:* - palette collapses many distinct flat materials -> ~1 and lifts the grade* - the grade is recomputed on the OPTIMIZED document* - `full` auto-degrades to `palette` when the asset is animated (rig-safe)diff --git a/src/kit.ts b/src/kit.tsindex e8cf5056..40f1babf 100644--- a/src/kit.ts+++ b/src/kit.ts@@ -34,8 +34,13 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { promisify } from 'node:util';-import type { Document, Material, Texture } from '@gltf-transform/core';-import { KHRMaterialsVariants, KHRTextureBasisu } from '@gltf-transform/extensions';+import type { Document, Material, Texture, TextureInfo } from '@gltf-transform/core';+import {+ KHRMaterialsVariants,+ KHRTextureBasisu,+ KHRTextureTransform,+ type Transform,+} from '@gltf-transform/extensions';import { buildSlotIndex, chooseSlot, hexToLinearRgb, type SnapPaletteSlot } from './palette-snap';@@ -91,6 +96,11 @@ export const KTX2_SIZE_ACCEPT_RATIO = 0.9;export interface KitPackSummary {ormPacked: number;+ /**+ * Present when a material kept a separate occlusion image because the two maps+ * are read through different UV sets or texture transforms: why, one per material.+ */+ ormSkipped?: readonly string[];variantsAdded: readonly string[];variantMaterialsCreated: number;ktx2: KitKtx2Summary;@@ -142,22 +152,71 @@ function disposeIfOrphaned(texture: Texture): void {if (!stillUsed) texture.dispose();}+/** The UV set a slot reads (after any `KHR_texture_transform` override) and the+ * transform it applies, as offset, rotation and scale; identity when absent. */+function uvMapping(info: TextureInfo): { texCoord: number; transform: number[] } {+ const transform = info.getExtension<Transform>(KHRTextureTransform.EXTENSION_NAME);+ return {+ texCoord: transform?.getTexCoord() ?? info.getTexCoord(),+ transform: [+ ...(transform?.getOffset() ?? [0, 0]),+ transform?.getRotation() ?? 0,+ ...(transform?.getScale() ?? [1, 1]),+ ],+ };+}++/**+ * Why this material's occlusion map cannot share the metallic-roughness image, or+ * undefined when it can.+ *+ * Packing copies occlusion into R pixel for pixel, so both slots must read the image+ * the same way. A baked AO map usually sits on its own UV set (TEXCOORD_1); folded+ * into an image read through TEXCOORD_0, its shadows would land in the wrong places.+ */+function uvMappingMismatch(material: Material, index: number): string | undefined {+ const occlusionInfo = material.getOcclusionTextureInfo();+ const metallicRoughnessInfo = material.getMetallicRoughnessTextureInfo();+ if (!occlusionInfo || !metallicRoughnessInfo) return undefined;+ const occlusion = uvMapping(occlusionInfo);+ const metallicRoughness = uvMapping(metallicRoughnessInfo);+ const name = material.getName()+ ? `material ${JSON.stringify(material.getName())}`+ : `material ${index}`;+ if (occlusion.texCoord !== metallicRoughness.texCoord) {+ return `${name}: occlusion reads TEXCOORD_${occlusion.texCoord} and metallic-roughness TEXCOORD_${metallicRoughness.texCoord}; kept separate images`;+ }+ if (occlusion.transform.some((value, i) => value !== metallicRoughness.transform[i])) {+ return `${name}: occlusion and metallic-roughness use different KHR_texture_transform values; kept separate images`;+ }+ return undefined;+}+/*** Fold occlusion into metallic-roughness R.*- * Only when the two are genuinely distinct images of identical size — a- * mismatched pair would need resampling, and silently resampling an author's- * occlusion map is a bigger change than leaving one extra image in the file.+ * Only when the two are genuinely distinct images of identical size, read through+ * the same UV set and texture transform — a mismatched pair would need resampling,+ * and silently resampling an author's occlusion map is a bigger change than leaving+ * one extra image in the file. A UV mismatch is reported in `skipped`.*/-async function packOcclusionIntoMetallicRoughness(doc: Document): Promise<number> {+async function packOcclusionIntoMetallicRoughness(+ doc: Document,+): Promise<{ packed: number; skipped: string[] }> {const sharp = (await import('sharp')).default;let packed = 0;+ const skipped: string[] = [];- for (const material of doc.getRoot().listMaterials()) {+ for (const [index, material] of doc.getRoot().listMaterials().entries()) {const occlusion = material.getOcclusionTexture();const metallicRoughness = material.getMetallicRoughnessTexture();if (!occlusion || !metallicRoughness || occlusion === metallicRoughness) continue;if (!isPng(occlusion) || !isPng(metallicRoughness)) continue;+ const mismatch = uvMappingMismatch(material, index);+ if (mismatch) {+ skipped.push(mismatch);+ continue;+ }const occlusionBytes = occlusion.getImage();const mrBytes = metallicRoughness.getImage();@@ -198,10 +257,9 @@ async function packOcclusionIntoMetallicRoughness(doc: Document): Promise<number.toBuffer();metallicRoughness.setImage(new Uint8Array(png));+ // Only the image changes: the occlusion slot keeps its own UV set and transform,+ // which the mismatch check above found equal to the metallic-roughness slot's.material.setOcclusionTexture(metallicRoughness);- const info = material.getOcclusionTextureInfo();- const mrInfo = material.getMetallicRoughnessTextureInfo();- if (info && mrInfo) info.setTexCoord(mrInfo.getTexCoord());disposeIfOrphaned(occlusion);packed += 1;} catch {@@ -209,7 +267,7 @@ async function packOcclusionIntoMetallicRoughness(doc: Document): Promise<number}}- return packed;+ return { packed, skipped };}/** A palette-snapped clone of one material, or undefined when the palette does not cover it. */@@ -392,7 +450,10 @@ export async function applyKitContract(doc: Document,options: KitPackOptions = {},): Promise<KitPackSummary> {- const ormPacked = options.packOrm === false ? 0 : await packOcclusionIntoMetallicRoughness(doc);+ const orm =+ options.packOrm === false+ ? { packed: 0, skipped: [] }+ : await packOcclusionIntoMetallicRoughness(doc);const specs = options.variants ?? [];const { names, materialsCreated } = specs.length@@ -450,5 +511,11 @@ export async function applyKitContract(}}- return { ormPacked, variantsAdded: names, variantMaterialsCreated: materialsCreated, ktx2 };+ return {+ ormPacked: orm.packed,+ ...(orm.skipped.length > 0 ? { ormSkipped: orm.skipped } : {}),+ variantsAdded: names,+ variantMaterialsCreated: materialsCreated,+ ktx2,+ };}diff --git a/src/render.ts b/src/render.tsindex 5e60ca3e..17f12dc2 100644--- a/src/render.ts+++ b/src/render.ts@@ -1100,7 +1100,8 @@ export interface RenderResult {* - `full` — `palette` plus `flatten → join` to also cut draw calls. STATIC* assets only: auto-degrades to `palette` when the Document has* animations or skins (flatten/join must not disturb a rig).- * See docs/kiln-material-consolidation-cycle.md (Move 1).+ * A render that omits the mode takes `KILN_BAKE_OPTIMIZE` (else `off`); what every+ * pass keeps intact is listed on {@link consolidateMaterials}.*/export type OptimizeMode = 'off' | 'auto' | 'palette' | 'full';