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
Add the cactus recipe, definePalette and the delivery contract docs
Matt Kissinger42a3e74496cd
diff --git a/docs/delivery-contract.md b/docs/delivery-contract.mdnew file mode 100644index 00000000..111fdd10--- /dev/null+++ b/docs/delivery-contract.md@@ -0,0 +1,126 @@+# Game delivery contract++This page is the single reference for what a Kiln asset carries into a game engine:+semantic roles, baked vertex attributes, and the integration manifest fields that+describe them. Everything here is plain glTF: roles in node `extras`, underscore+custom attributes, and extensions Kiln already writes (`KHR_node_visibility`,+`MSFT_lod`). No engine-specific schema is required to read it.++Every diagnostic on this page is **advisory**. It appears as a build warning and in+the manifest, never as a QA disposition, unless a helper below says otherwise+(`requireSolid` fails the build; CLI `render --strict-budget` turns a failing budget+into an exit code).++## Roles++Roles live in `extras.kilnSemantic.roles` on the node (revision 2 of the role+vocabulary, `KILN_SEMANTIC_ROLES_REVISION`). Ids and kinds are single segments:+a letter or digit, then up to 63 letters, digits, `_` or `-`.++| Role | Helper | Node | Meaning |+| --- | --- | --- | --- |+| `collider.box.<id>` | `colliderBox(size, { id, parent?, position?, rotation? })` | `Collider_box_<id>`, hidden | Unit-box proxy; the node scale is the box size |+| `collider.capsule.<id>` | `colliderCapsule(radius, height, opts)` | `Collider_capsule_<id>`, hidden | Y-axis capsule; node scale `[2r, h, 2r]`, `h` is the total height including caps |+| `collider.hull.<id>` | `colliderHull(mesh, { id, parent? })` | `Collider_hull_<id>`, hidden | Convex hull of the mesh, in the mesh's own transform |+| `anchor.<kind>.<id>` | `anchor(kind, id, opts?)` | `Anchor_<kind>_<id>` | A leaf transform the consumer attaches behaviour to (door, light, spawn) |+| `kit.module` | `defineModule(root, spec)` | the root | One modular kit piece; `extras.kilnKit` holds `{ schemaVersion: 1, footprint: [w, d], height, snapAxis, origin }` |+| `kit.port.<id>` | `port(id, opts?)` | `Port_<id>` | A snap frame under a module |+| `lod.impostor` | `defineLod(tiers, { screenCoverage, impostor: true })` | last tier | The last LOD level is a card impostor |++Collider proxies are real meshes hidden with `KHR_node_visibility`, so a loader that+ignores the extension still sees them; their material is named `KilnColliderProxy`.+Hidden nodes are excluded from triangle counts, bounds and QA.++`repeatInstances(parent)` marks a parent (`extras.kilnRepeatInstances`) whose+identical leaf children the three.js runtime target turns into one+`EXT_mesh_gpu_instancing` node. The editable GLB keeps every child.++## Baked vertex attributes++`bakeSurfaceAttributes(target, { edge?, cavity? })` writes float attributes on every+visible mesh under `target`, exported by both converters:++| glTF name | three.js name | Range | Meaning |+| --- | --- | --- | --- |+| `_EDGE` | `_edge` | 0..1 | 1 on a chamfer, bevel or rim (convex dihedral or open boundary); 0 on a flat face. Drives paint wear. |+| `_CAVITY` | `_cavity` | 0..1 | 1 fully exposed; toward 0 deep in a recess. Ambient-occlusion input only. |++Edge weight is `smoothstep(t/2, t, dihedral)` on convex edges (default threshold+`t` 35 degrees), 1 on boundary or non-manifold edges, the maximum per welded vertex,+then one averaging ring by default. Cavity casts a fixed cosine-weighted Fibonacci+hemisphere of rays (default 32) against the occluders (default: the whole asset,+excluding other LOD tiers and hidden nodes). Both are deterministic. Parameters are+recorded in mesh `extras.kilnSurfaceBakeV1`. three's `GLTFLoader` lowercases custom+attribute names, so shaders read `_edge` and `_cavity`.++## Budgets, palette and solids++- `defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws? })` stores scene extras+ `kilnBudgetV1`. Tier n is measured as level `min(n, last)` of every `MSFT_lod`+ chain plus everything outside the chains; `draws` caps LOD0 draw calls.+- `definePalette(colors, { threshold? })` stores scene extras `kilnPaletteV1`. Each+ material drawn by a visible node is compared by its base colour factor in CIELAB+ (CIE 1976 delta E, default threshold 10). Off-palette materials become+ `PALETTE_OFF` warnings. Texture pixels are not judged.+- `requireSolid(part)` fails the build with `REQUIRE_SOLID` unless every visible mesh+ under `part` is closed, manifold and outward. `geometryDiagnostics(geometry).solid`+ reports the same facts and the signed volume.++## Integration manifest fields++`inspectGlbIntegration(bytes)`, render results and CLI `render --json` receipts add+these optional fields. Older readers ignore them; a field is absent when the asset+has nothing to report.++| Field | Shape |+| --- | --- |+| `colliders` | `[{ role, id, path, name, transform: { translation, rotation, scale }, shape }]`; `shape` is `{ kind: 'box', size }`, `{ kind: 'capsule', radius, height }` or `{ kind: 'hull', vertices }` |+| `anchors` | `[{ role, kind, id, path, name, transform }]` |+| `kit` | `{ role, path, name, transform, footprint, height, snapAxis, origin }` for the first module |+| `ports` | `[{ role, id, path, name, transform, module? }]` |+| `levelsOfDetail[].levels[].impostor` | `true` on an impostor level |+| `vertexAttributes` | `[{ name: '_EDGE' \| '_CAVITY' \| ..., meshes: [path], params? }]` |+| `budget` | `{ status: 'pass' \| 'fail', tiers: [{ tier, declared, measured, status }] }` |+| `palette` | `{ status: 'pass' \| 'warn', colors, threshold, checkedMaterials, offPalette: [{ material, color, nearest, deltaE, textured? }] }` |+| `deliveryDiagnostics` | `[{ code, path, message }]` |++Transforms are relative to the asset root (the default scene), rotation as an+`[x, y, z, w]` quaternion. Paths are `/<scene>[0]/<name>[occurrence]/...` with each+name URI-encoded.++Delivery diagnostic codes: `DELIVERY_COLLIDER_NOT_HIDDEN`,+`DELIVERY_COLLIDER_OUTSIDE_BOUNDS`, `DELIVERY_COLLIDER_NO_OVERLAP`,+`DELIVERY_COLLIDER_OVERLAP_UNMEASURED`, `DELIVERY_KIT_INVALID`,+`DELIVERY_KIT_MULTIPLE`, `DELIVERY_PORT_OUTSIDE_FOOTPRINT`,+`DELIVERY_PORT_WITHOUT_MODULE`, `DELIVERY_ANCHOR_NOT_LEAF`. A box or capsule wholly+inside a closed solid touches no triangle, so it reports `NO_OVERLAP`.++## Texture atlases++`textureAtlas` packs regions without a `content` rectangle when the atlas sets+`pack: { edge: 1024 | 2048, gutter?, algorithm?: 'maxrects' }`. See+[procedural surfaces](procedural-surfaces-v3.md#pack-regions-automatically).++## three.js runtime delivery++`kiln export ASSET REVISION --profile runtime --target three --out a.glb` (or+`exportAssetGlb(record, { profile: 'runtime', target: 'three' })`, or+`deliverThreeRuntimeGlb(glb)` for any Kiln GLB) writes a meshopt-compressed,+quantized GLB and a sidecar whose `delivery` block states the extensions used,+which nodes carry a dequantization scale, the custom attributes and the instancing+batches. See [export profiles](export-profiles.md#threejs-runtime-target).++Consumer rules that follow from it:++- **Read geometry through its node.** Quantized positions are normalized integers;+ the node's matrix restores metres. A bare geometry re-parented into your own mesh+ drops that scale. `delivery.nodeScale` lists every such node.+- **Collider transforms are exact.** A collider's proxy mesh moves to a child named+ `<collider>_Proxy`, so the collider node's scale is still its size.+- **Custom attributes stay float.** `_EDGE` and `_CAVITY` are never quantized.++## Out of scope++Not built in this cycle: a crash-damage or tearing helper, a kit snap solver or+cross-module validation, general self-intersection detection, and a palette lock+that fails builds.diff --git a/docs/export-profiles.md b/docs/export-profiles.mdindex 9f26f1e6..b380ec18 100644--- a/docs/export-profiles.md+++ b/docs/export-profiles.md@@ -42,7 +42,8 @@ opt in because moving review data changes its location and adds a companion fileThe Three.js converter is experimental because native installation requirements,unsupported UV transforms and destination feature support still need qualification.Neither setting automatically enables mesh merging, geometry simplification, Draco,-Meshopt or KTX2 compression. Those require separate choices and validation.+Meshopt or KTX2 compression. Those require separate choices and validation; the+opt-in [three.js runtime target](#threejs-runtime-target) is one such choice.## Material sidedness at export@@ -161,6 +162,71 @@ 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.+## three.js runtime target++`--target three` (runtime profile only) derives a GLB for a three.js application:++```sh+node kiln.mjs export ASSET_ID REVISION_ID --profile runtime --target three --out door.glb+# door.glb+# door.kiln-metadata.json (version kiln.runtime-metadata.v1, target "three", delivery {...})+```++```ts+import { deliverThreeRuntimeGlb, exportAssetGlb } from '@instruktlabs/kiln/asset-export';++const output = await exportAssetGlb(record, { profile: 'runtime', target: 'three' });+// Or derive from any Kiln GLB without a saved record:+const { glb, delivery } = await deliverThreeRuntimeGlb(bytes, { ktx2Encoder });+```++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 no+ children, roles, extras, skin, morph weights or hidden flag become one node+ `<parent>_Instances` with `EXT_mesh_gpu_instancing`.+2. Each collider's proxy mesh moves to a child `<collider>_Proxy`, so the collider node+ keeps its authored transform (its scale is the collider size).+3. Vertices are reordered for compression, then quantized with `KHR_mesh_quantization`+ per mesh: position 14 bits, normal 10, texcoord 12, colour 8, weights 8.+ Underscore attributes such as `_EDGE` and `_CAVITY` are **not** quantized and stay+ FLOAT. Buffers are written with `EXT_meshopt_compression` (required).+4. Textures become KTX2 (`KHR_texture_basisu`) only when the library caller passes a+ `ktx2Encoder`; Kiln ships none, so the CLI reports `ktx2: { status: 'skipped' }` and+ textures stay PNG or JPEG.++Roles and kit extras, hidden collider nodes (`KHR_node_visibility`), anchors, ports and+`MSFT_lod` chains are kept. The sidecar `delivery` block states what a consumer needs:++| Field | Meaning |+| --- | --- |+| `extensionsUsed`, `extensionsRequired` | The derived GLB's extension sets |+| `quantization` | Bits per attribute class; `customAttributes: 'float32'` |+| `nodeScale` | Every node whose matrix now carries a dequantization `{ scale, offset }`, its `localScale`, and whether the mesh moved to a child (`meshMovedToChild`, `authoredNode`) |+| `colliderProxies` | Collider node and proxy child paths |+| `customAttributes` | Each underscore attribute, its mesh count, `FLOAT`, not normalized |+| `instancing` | Each batch node, its mesh, count and instance names in order |+| `ktx2` | `encoded` or `skipped` with the texture count and reason |+| `preserved` | Counts of LOD chains, hidden nodes, colliders, anchors, ports and kit modules |++Quantization stores positions as normalized integers and moves the metre scale onto+the node: read geometry through the node's world matrix. A loader needs the meshopt+decoder; with three.js:++```ts+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';++await MeshoptDecoder.ready;+const gltf = await new GLTFLoader().setMeshoptDecoder(MeshoptDecoder).parseAsync(buffer, '');+```++three's `GLTFLoader` keeps unknown node extensions in `userData.gltfExtensions`+(`KHR_node_visibility`, `MSFT_lod`) and lowercases custom attributes (`_edge`).+Kiln's tests load the derived GLB from both converters this way. On a very small asset+the extension JSON can outweigh the saved geometry; compare real assets.+## Pointer and hash contractThe runtime GLB contains this record in `asset.extras.kilnProvenanceV1`:diff --git a/docs/geometry.md b/docs/geometry.mdindex bc2fa17a..efe19105 100644--- a/docs/geometry.md+++ b/docs/geometry.md@@ -385,6 +385,42 @@ allocation. Kiln reports the offending argument; it does not round, reduce detaior change the requested shape. These checks do not replace the evaluator boundaryfor raw Three.js or authored custom geometry.+## Require a closed solid++`geometryDiagnostics(geometry).solid` reports `closed` (no boundary edges),+`manifold` (no edge shared by three or more faces), `orientation` (`outward` or+`inward` from the sign of the signed volume, `mixed` on any winding conflict or a+zero volume) and `signedVolume` in cubic geometry units. To make the build depend on+it, mark the part:++```js+const hull = createPart('Hull', await extrudeProfile(outline, { depth: 2 }), steel, { parent: root });+requireSolid(hull); // or requireSolid(group) for every visible mesh under it+```++A marked mesh that is open, non-manifold or not outward fails the build with+`REQUIRE_SOLID`, naming the part and the failing facts. The check measures; it+repairs nothing, and it does not detect general self-intersection.++## Bake edge and cavity attributes++`bakeSurfaceAttributes(target, { edge?, cavity? })` writes two float vertex+attributes on each visible mesh under `target`, exported as glTF `_EDGE` and+`_CAVITY`: edge is 1 on chamfers, bevels and rims and 0 on flat faces (for paint+wear); cavity is 1 fully exposed and toward 0 in recesses (an ambient-occlusion+input). Call it after every occluding part is attached. Each mesh gets its own+geometry copy, because cavity depends on placement. The bake is deterministic and+bounded by `GEOMETRY_ALLOCATION_LIMITS`; see the [delivery contract](delivery-contract.md#baked-vertex-attributes)+for the formulas.++## Declare a triangle budget++`defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 })` records the asset's+budget. Receipts measure the written GLB: tier n is level `min(n, last)` of every+`MSFT_lod` chain plus everything outside the chains, and draws count LOD0. The result+is `budget: { status, tiers }` in render results, `kiln_render` and CLI receipts. It+is advisory; `kiln render --strict-budget` exits 1 when a tier fails.+## Joint discovery and resource counts`describeAssembly(root).joints` finds validated articulated joints, wheel-spin pivots,diff --git a/docs/plans/2026-10-15-game-delivery-contract.md b/docs/plans/2026-10-15-game-delivery-contract.mdindex be371d63..016a00c5 100644--- a/docs/plans/2026-10-15-game-delivery-contract.md+++ b/docs/plans/2026-10-15-game-delivery-contract.md@@ -292,3 +292,39 @@ from this scope and why. The owner's game session reads this log to monitor.source texels and encoded byte budgets stay at the v1.1 values; (e) a packed resourceregion needs `crop` or `expected` width and height, because its size must be known beforeany host load.+- 2026-10-15 item 6 (three.js runtime target) done. Files: new `src/runtime-three.ts`+ (`deliverRuntimeThreeGlb`: accessor dedup, scoped `EXT_mesh_gpu_instancing`, collider proxy+ split, meshopt `reorder`, `KHR_mesh_quantization` (position 14, normal 10, texcoord 12,+ colour 8, weight 8 bits, mesh volume), `EXT_meshopt_compression` (quantize method), KTX2+ through an injected `ktx2Encoder` or `skipped`; report of extensions, node scales, collider+ proxies, custom attributes, instancing, KTX2 and preserved roles), `src/asset-export.ts`+ (`target: 'three'`, `ktx2Encoder`, `deliverThreeRuntimeGlb(glb, options)` library helper,+ sidecar `target` + `delivery`, provenance `target`), `src/asset-cli.ts` (`export --profile+ runtime --target three`; receipt `target`), `src/delivery.ts` (`repeatInstances(parent)`,+ `kilnRepeatInstances` extras), `src/delivery-inspect.ts` (`deliveryNodePaths`),+ `src/render.ts` + `src/community-exporter.ts` (export the mark), `src/primitives.ts`,+ Discovery (`repeatInstances`), prompt-api snapshot, `src/asset-cli.test.ts` (CLI three+ target and its refusals). Test: new `src/__tests__/runtime-three-export.test.ts` (5,+ observed failing first). GLTFLoader qualification ran under `bun test`: three 0.186.1's+ `GLTFLoader` with `three/addons/libs/meshopt_decoder.module.js` loads the derived GLB from+ both converters and the test asserts roles and kit extras in `userData`, the hidden collider+ (`userData.gltfExtensions.KHR_node_visibility`) at its authored scale with its proxy child,+ float `_edge` attributes, one `InstancedMesh` of 4, and the `MSFT_lod` ids with the lower+ level node loading through `parser.getDependency`. No fallback was needed. Gate after+ `node scripts/build-runtime.mjs all` (exit 0): `bun run test:coverage` 3714 pass, 2 skip, 19+ fail (only the GNU-tar baseline); `bun scripts/check-coverage.mjs` passed, functions 95.45%+ (min 94.00%), lines 93.13% (min 92.10%); `bun run test:render-service` exit 0; `bun run+ check:skills` 6 conform, 2 copies identical; typecheck and lint pass. Deviations: (a)+ underscore attributes are excluded from quantization and stay FLOAT, unnormalized, so+ `aEdge`/`aCav` keep their exact 0..1 floats and a CPU reader sees a `Float32Array`; (b) a+ collider's proxy mesh moves to a child `<collider>_Proxy` before quantization so the+ collider node keeps its authored transform (its scale is the collider size); every other+ quantized mesh carries a dequantization scale and offset on its node, listed in the sidecar+ `nodeScale` (the meshes a quantizer moved to a new child are named `<node>_Mesh`); (c) the+ meshopt encoder is `meshoptimizer` 1.1.1, today a transitive dependency through+ `@types/three`, imported lazily; it was not added to `package.json` because that needs a+ lockfile update this offline session did not make (owner question); (d) Kiln ships no KTX2+ encoder, so without `ktx2Encoder` the report is `skipped` and textures stay PNG/JPEG; (e) a+ probe this small grows in total size because the extension JSON outweighs the saved+ geometry; the test asserts the binary chunk shrinks; (f) MCP `kiln_export` is unchanged+ (schemas are prompt-cached), so the three target is CLI and library only.diff --git a/docs/procedural-surfaces-v3.md b/docs/procedural-surfaces-v3.mdindex 1519e023..f3fcabf9 100644--- a/docs/procedural-surfaces-v3.md+++ b/docs/procedural-surfaces-v3.md@@ -219,7 +219,41 @@ Coordinates are integer pixels from the top-left. Each region has a stablelowercase `name`, a `content` rectangle, a `source`, and optional crop, gutter,and edge mode. Default gutters are two pixels; padded allocations must fitwithout overlap. Sources must already match the requested crop size: this-operation does not pack, resize, rotate, or resample images.+operation does not resize, rotate, or resample images. It packs only on request+(below).++### Pack regions automatically++Set `pack: { edge: 1024 | 2048, gutter?, algorithm?: 'maxrects' }` and omit `content`+on any region to have Kiln place it:++```js+const atlas = await textureAtlas({+ schemaVersion: 1,+ usage: 'albedo',+ pack: { edge: 1024, gutter: 4 },+ regions: [+ { name: 'plate', source: { kind: 'procedural', spec: plateRecipe } },+ { name: 'grime', source: { kind: 'procedural', spec: grimeRecipe } },+ { name: 'decal', content: { x: 4, y: 4, width: 64, height: 64 }, source: decalSource },+ ],+});+```++A packed atlas compiles as `kiln.texture-atlas.v1.2` with raised limits: edge up to+2048, 4,194,304 output texels, 32 distinct sources and 128 regions. Width and height+default to `pack.edge`; `pack.gutter` (default 2) is the default gutter of every region.+Placement is MaxRects best short side fit without rotation, in a fixed order+(allocation area descending, then name), around any explicit rectangles, so the same+spec always packs the same way. A packed region takes its source size: the procedural+recipe's size, its `crop`, or for a pinned resource `expected.width` and+`expected.height` (a resource without one of these is refused before any load).++The compiled spec keeps `pack` and records each placed region's resolved `content`+with `packed: true`; the manifest regions carry the same rectangles. A saved recipe+or provenance record therefore re-validates exactly without re-packing. Use+`remapUVToAtlas` with the region name as usual. Atlases without `pack` keep compiler+`kiln.texture-atlas.v1.1`, its limits and their existing identities.A source is either `{kind:'procedural',spec:<V3 recipe>}` or`{kind:'resource',resourceId:<exact map id>,pin:{resourceId:<material id>,diff --git a/skills/kiln-author-asset/references/geometry-recipes.md b/skills/kiln-author-asset/references/geometry-recipes.mdindex f97c982e..108ef7af 100644--- a/skills/kiln-author-asset/references/geometry-recipes.md+++ b/skills/kiln-author-asset/references/geometry-recipes.md@@ -426,6 +426,43 @@ subject, with `visibility: "isolate"` to see it alone; the shot draws the levelLOD0's place, and each chain's `drawn` says which level every view drew. An importedGLB's chains are kept through save and export.+## Game delivery: colliders, anchors, kits, bakes and budgets++Add these only when the brief asks for a game-ready asset. Each is plain glTF a+loader can read; the manifest lists them and its advisory warnings name problems.++```js+defineModule(root, { footprint: [4, 0.6], height: 3.2, snapAxis: 'x', origin: 'center' });+port('west', { parent: root, position: [-2, 0, 0], rotation: [0, 180, 0] });+port('east', { parent: root, position: [2, 0, 0] });+colliderBox([4, 3.2, 0.6], { id: 'frame', parent: root, position: [0, 1.6, 0] });+anchor('door', 'main', { parent: root, position: [0, 0, 0.3] });+anchor('light', 'lintel', { parent: root, position: [0, 3, 0.35] });+repeatInstances(boltGroup); // identical bolts become one instanced mesh in the three.js export+bakeSurfaceAttributes(root, { edge: { thresholdDegrees: 35 }, cavity: { rays: 32 } });+defineBudget({ triangles: { LOD0: 6000, LOD1: 1500 }, draws: 4 });+definePalette(['#5b6066', '#2e3135', '#8a4b2a']);+requireSolid(frame);+```++- Colliders are hidden proxies; the box size or capsule `[2r, h, 2r]` is the node+ scale. Keep each one inside the drawn bounds and touching what it stands for.+- An anchor is a leaf transform (door, light, spawn); never parent parts under it.+- Place ports inside the module footprint. One module per asset.+- Bake after every occluding part is attached. `_edge` is 1 on rims and chamfers,+ `_cavity` is 1 when exposed; both are 0..1 floats.+- Budgets and palettes are advisory. `requireSolid` fails the build unless the part+ is closed, manifold and outward; build it from solid helpers (`boxGeo`,+ `extrudeProfile`, `revolveProfile`, `roundedBoxGeo`) rather than open sheets.+- For a far tier drawn as a card, pass `impostor: true` to `defineLod`; the last+ level is the impostor.++A cactus (`vegetation.subtype: 'cactus'`): a ribbed trunk from a star outline with+6 to 12 rounded ribs through `extrudeProfile(..., { axis: 'y', taper, divisions })`,+arms swept with `pipeAlongPath` through an elbow (out, then up) and embedded in the+trunk, small spine cards on the rib crests, and explicit tiers: full LOD0, fewer+ribs and no spines at LOD1, and a `crossedQuadsGeo` impostor last.+## Implicit fields are experimental```jsdiff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snapindex dce2f7ff..a67a6208 100644--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -807,6 +807,12 @@ defineBudget(spec: { triangles: number | { LOD0, LOD1, ... }, draws?: number },// NOTE: Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching// defineLod levels.// e.g. defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 });+definePalette(colors: string[], opts?: { threshold?: 10 }, target?: Object3D)+ // Declares the asset palette (1..64 hex colours). Receipts list every drawn material whose+ // base colour is farther than threshold (CIE76 delta E, default 10) from the nearest entry as+ // PALETTE_OFF warnings and a manifest palette report. Advisory: never fails a build.+ // NOTE: Only when the brief names a palette or a set of exact colours. Call once.+ // e.g. definePalette(['#6b6f73', '#3a3d40', '#8a4b2a', '#c9a227']);requireSolid(part: Object3D)// Opt-in assertion: the build fails with REQUIRE_SOLID unless every visible mesh in part is// closed, manifold and outward (geometryDiagnostics(geometry).solid).diff --git a/src/__tests__/delivery-palette.test.ts b/src/__tests__/delivery-palette.test.tsnew file mode 100644index 00000000..3fa9064e--- /dev/null+++ b/src/__tests__/delivery-palette.test.ts@@ -0,0 +1,84 @@+/**+ * Advisory palette and the cactus recipe (delivery contract item 7).+ *+ * `definePalette([...hex])` makes every receipt list the drawn materials whose base colour is+ * farther than a CIE76 delta E threshold from the nearest palette entry, as warnings and a+ * manifest `palette` report. It never fails a build.+ */+import { describe, expect, test } from 'bun:test';+import { createAssetIntentV1, VEGETATION_SUBTYPES } from '../contracts';+import { AuthoringDiagnosticError } from '../evaluator/authoring-diagnostic';+import { definePalette, linearRgbToLab, normalizePalette } from '../palette-check';+import { buildSandboxGlobals } from '../primitives';+import { renderGLBInProcess } from '../render';+import { vegetationSubtypePromptContext } from '../vegetation-prompt';++const program = (palette: string) => `const meta={name:'Swatches'};+function build(){+ const root=createRoot('Root');+ createPart('Steel',boxGeo(1,1,1),gameMaterial('#6b6f73'),{parent:root});+ createPart('Rust',boxGeo(1,1,1),gameMaterial('#8a4b2a'),{parent:root,position:[2,0,0]});+ createPart('Alarm',boxGeo(1,1,1),gameMaterial('#ff00ff'),{parent:root,position:[4,0,0]});+ colliderBox([1,1,1],{id:'steel',parent:root});+ ${palette}+ return root;+}`;++describe('definePalette', () => {+ test('normalises hex entries and validates the threshold', () => {+ expect(normalizePalette(['#ABC', '6b6f73', '#abc'])).toEqual({+ schemaVersion: 1,+ colors: ['#aabbcc', '#6b6f73'],+ threshold: 10,+ });+ expect(definePalette(['#000000'], { threshold: 4 }).threshold).toBe(4);+ for (const bad of [[], ['red'], ['#12345']])+ expect(() => normalizePalette(bad)).toThrow(AuthoringDiagnosticError);+ expect(() => normalizePalette(['#000'], { threshold: 0 })).toThrow(/threshold/);+ expect(typeof buildSandboxGlobals().definePalette).toBe('function');+ // D65 white is L* 100, a* = b* = 0.+ const [l, a, b] = linearRgbToLab([1, 1, 1]);+ expect(l).toBeCloseTo(100, 3);+ expect(a).toBeCloseTo(0, 2);+ expect(b).toBeCloseTo(0, 2);+ });++ test('lists off-palette materials as advisory warnings and a manifest report', async () => {+ const result = await renderGLBInProcess(+ program(`definePalette(['#6b6f73','#8a4b2a'],{threshold:8});`),+ );+ const report = result.integrationManifest.palette!;+ expect(report.status).toBe('warn');+ expect(report.colors).toEqual(['#6b6f73', '#8a4b2a']);+ // The collider proxy material is not judged; steel and rust match exactly.+ expect(report.checkedMaterials).toBe(3);+ expect(report.offPalette).toHaveLength(1);+ expect(report.offPalette[0]).toMatchObject({ color: '#ff00ff', nearest: expect.any(String) });+ expect(report.offPalette[0]!.deltaE).toBeGreaterThan(8);+ expect(result.warnings.some((w) => w.startsWith('PALETTE_OFF') && w.includes('#ff00ff'))).toBe(+ true,+ );+ const clean = await renderGLBInProcess(+ program(`definePalette(['#6b6f73','#8a4b2a','#ff00ff']);`),+ );+ expect(clean.integrationManifest.palette).toMatchObject({ status: 'pass', offPalette: [] });+ const none = await renderGLBInProcess(program(''));+ expect(none.integrationManifest.palette).toBeUndefined();+ });+});++describe('cactus vegetation recipe', () => {+ test('is a subtype with its own recipe naming the delivery helpers', () => {+ expect(VEGETATION_SUBTYPES).toContain('cactus');+ const context = vegetationSubtypePromptContext(+ createAssetIntentV1({ category: 'vegetation', vegetation: { subtype: 'cactus' } }),+ );+ expect(context).toContain('RECIPE_CACTUS_V1');+ for (const word of ['extrudeProfile', 'pipeAlongPath', 'spine', 'defineLod', 'impostor'])+ expect(context).toContain(word);+ expect(+ createAssetIntentV1({ category: 'vegetation', subtype: 'saguaro cactus' }).vegetation+ ?.subtype,+ ).toBe('cactus');+ });+});diff --git a/src/cli.ts b/src/cli.tsindex d9d143c5..02d7a757 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -347,6 +347,7 @@ async function emit(? { vertexAttributes: result.integrationManifest.vertexAttributes }: {}),budget: result.integrationManifest.budget ?? { status: 'none', tiers: [] },+ ...(result.integrationManifest.palette ? { palette: result.integrationManifest.palette } : {}),artifactGlbSha256: result.artifactGlbSha256,glbBytes: result.glb.length,warnings: result.warnings,@@ -399,6 +400,12 @@ async function emit(.join('; ');log(` budget ${budget.status} ${tiers}`);}+ // A declared palette: advisory, off-palette materials farthest first.+ const palette = result.integrationManifest.palette;+ if (palette)+ log(+ ` palette ${palette.status} ${palette.checkedMaterials} material(s), ${palette.offPalette.length} off palette (delta E > ${palette.threshold})`,+ );// Custom vertex attributes the GLB preserves, such as baked _EDGE and _CAVITY.for (const attribute of result.integrationManifest.vertexAttributes ?? [])log(` attribute ${attribute.name} on ${attribute.meshes.length} mesh(es)`);diff --git a/src/contracts/asset.test.ts b/src/contracts/asset.test.tsindex 2ce2afa0..f8c8b460 100644--- a/src/contracts/asset.test.ts+++ b/src/contracts/asset.test.ts@@ -104,6 +104,7 @@ describe('asset contracts', () => {'vine','crop/flower','succulent',+ 'cactus','fungus','aquatic','bare/dead',diff --git a/src/contracts/asset.ts b/src/contracts/asset.tsindex f9953b71..b84398e6 100644--- a/src/contracts/asset.ts+++ b/src/contracts/asset.ts@@ -296,6 +296,7 @@ export const VEGETATION_SUBTYPES = ['vine','crop/flower','succulent',+ 'cactus','fungus','aquatic','bare/dead',@@ -1776,7 +1777,8 @@ function inferVegetationSubtype(value: string | undefined): VegetationSubtype {if (/(?:shrub|bush|hedge|topiary)/i.test(value)) return 'shrub';if (/(?:grass|reed|sedge)/i.test(value)) return 'grass';if (/(?:vine|ivy|liana)/i.test(value)) return 'vine';- if (/(?:succulent|cactus|agave)/i.test(value)) return 'succulent';+ if (/(?:cactus|cacti|saguaro|cholla|opuntia)/i.test(value)) return 'cactus';+ if (/(?:succulent|agave)/i.test(value)) return 'succulent';if (/(?:fungus|mushroom)/i.test(value)) return 'fungus';if (/(?:aquatic|lily|kelp|lotus)/i.test(value)) return 'aquatic';return 'custom';diff --git a/src/contracts/integration.ts b/src/contracts/integration.tsindex cc8e88d2..03004397 100644--- a/src/contracts/integration.ts+++ b/src/contracts/integration.ts@@ -148,6 +148,29 @@ export interface BudgetReportV1 {tiers: BudgetTierV1[];}+/** One drawn material whose base colour is off the declared palette. */+export interface PaletteFindingV1 {+ material: string;+ /** The material's base colour factor as sRGB `#rrggbb`. */+ color: string;+ /** The nearest palette entry. */+ nearest: string;+ /** CIE 1976 delta E in CIELAB, rounded to 0.01. */+ deltaE: number;+ /** The factor tints a base colour texture; the texture itself is not judged. */+ textured?: true;+}++/** A `definePalette` declaration against the bytes. Advisory: never QA acceptance. */+export interface PaletteReportV1 {+ status: 'pass' | 'warn';+ colors: string[];+ threshold: number;+ checkedMaterials: number;+ /** Farthest first. */+ offPalette: PaletteFindingV1[];+}+/** An advisory delivery finding. Never QA acceptance. */export interface DeliveryDiagnosticV1 {code: string;@@ -198,6 +221,8 @@ export interface IntegrationManifestV1 {ports?: DeliveryPortV1[];/** The declared budget measured against these bytes, when source declared one. */budget?: BudgetReportV1;+ /** The declared palette against the drawn materials, when source declared one. */+ palette?: PaletteReportV1;/** Custom vertex attributes (`_EDGE`, `_CAVITY`) grouped by name and parameters. */vertexAttributes?: DeliveryVertexAttributeV1[];/** Advisory delivery findings (colliders, anchors, ports), when there are any. */diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.tsindex 4c3198ff..8ded5976 100644--- a/src/discovery/helper-contracts.ts+++ b/src/discovery/helper-contracts.ts@@ -1029,6 +1029,40 @@ define(related: [{ name: 'defineLod', relation: 'companion' }],},);+define(+ 'definePalette',+ {+ units: 'Colours are sRGB hex; threshold is a CIE 1976 delta E in CIELAB (D65).',+ axes: 'Not a placement operation.',+ origin: 'Not a placement operation.',+ ownership:+ 'Records one declaration: on target when given, otherwise on the root build() returns. Export writes it as default-scene extras kilnPaletteV1.',+ coordinates: 'Not a placement operation.',+ parameters: [+ "colors: 1..64 hex strings ('#rgb' or '#rrggbb'); duplicates collapse.",+ 'opts.threshold: delta E in (0, 100], default 10.',+ 'target: optional scene node, normally the root.',+ ],+ topology: [noMesh],+ preservation: ['Changes no geometry, material or node.'],+ semantics: [+ 'Every material drawn by a visible scene node (collider proxies excluded) is compared by its base colour factor, converted from linear to sRGB to CIELAB; a factor that tints a texture is flagged textured.',+ 'The integration manifest and CLI receipt report palette: { status: pass | warn, colors, threshold, checkedMaterials, offPalette: [{ material, color, nearest, deltaE, textured? }] }; each off-palette material is also a PALETTE_OFF warning.',+ 'Advisory only: no build fails and QA acceptance is unchanged. Invalid input is a DELIVERY_CONTRACT build error.',+ ],+ cost: 'One colour conversion per drawn material at export.',+ },+ {+ references: ['src/palette-check.ts', 'docs/delivery-contract.md'],+ tags: ['delivery', 'palette', 'color', 'art direction'],+ aliases: ['color palette', 'palette lock', 'art palette', 'swatches'],+ intents: ['check materials against a declared colour palette'],+ summary:+ 'Declares a colour palette; receipts list drawn materials off it by delta E, advisory only.',+ limitations: ['Judges base colour factors, not texture pixels. Never fails a build.'],+ related: [{ name: 'gameMaterial', relation: 'companion' }],+ },+);define('requireSolid',{diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.tsindex cb57caef..ac974421 100644--- a/src/discovery/helper-specs.ts+++ b/src/discovery/helper-specs.ts@@ -300,6 +300,16 @@ const PRIMITIVES: HelperSpec[] = [promptNotes:'Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching defineLod levels.',},+ {+ name: 'definePalette',+ signature: 'definePalette(colors: string[], opts?: { threshold?: 10 }, target?: Object3D)',+ returns: '{ schemaVersion: 1, colors, threshold } (the normalised declaration)',+ category: 'utility',+ description:+ 'Declares the asset palette (1..64 hex colours). Receipts list every drawn material whose base colour is farther than threshold (CIE76 delta E, default 10) from the nearest entry as PALETTE_OFF warnings and a manifest palette report. Advisory: never fails a build.',+ example: "definePalette(['#6b6f73', '#3a3d40', '#8a4b2a', '#c9a227']);",+ promptNotes: 'Only when the brief names a palette or a set of exact colours. Call once.',+ },{name: 'requireSolid',signature: 'requireSolid(part: Object3D)',diff --git a/src/evaluator/authoring-diagnostic.ts b/src/evaluator/authoring-diagnostic.tsindex 268faedc..f3c32521 100644--- a/src/evaluator/authoring-diagnostic.ts+++ b/src/evaluator/authoring-diagnostic.ts@@ -76,7 +76,7 @@ export const LOD_SET_ADVICE =export const OPEN_SHELL_ADVICE ='markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].';export const DELIVERY_CONTRACT_ADVICE =- 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws? }) takes positive integers. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].';+ 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws? }) takes positive integers; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].';export const REQUIRE_SOLID_ADVICE ='REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].';/**diff --git a/src/palette-check.ts b/src/palette-check.tsnew file mode 100644index 00000000..ab845279--- /dev/null+++ b/src/palette-check.ts@@ -0,0 +1,181 @@+/**+ * Advisory palette check (delivery contract item 7).+ *+ * `definePalette(['#6b6f73', '#3a3d40', ...])` declares the asset's colour palette. Every+ * receipt then lists each drawn material whose base colour is farther than `threshold`+ * (CIE 1976 delta E in CIELAB, default 10) from the nearest palette entry. The check is+ * advisory: it adds warnings and a manifest `palette` report and never fails a build.+ */+import type { Document } from '@gltf-transform/core';+import type * as THREE from 'three';+import type { PaletteReportV1 } from './contracts/integration';+import { COLLIDER_PROXY_MATERIAL_NAME } from './delivery';+import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';+import { isHiddenGltfNode } from './metrics';++/** Where a declaration lives: root userData until export, then default-scene extras. */+export const KILN_PALETTE_KEY = 'kilnPaletteV1';+export const PALETTE_DEFAULT_THRESHOLD = 10;+export const PALETTE_MAX_COLORS = 64;++export interface PaletteOptionsV1 {+ /** CIE76 delta E above which a material is reported (default 10). */+ threshold?: number;+}+export interface PaletteDeclarationV1 {+ schemaVersion: 1;+ /** Lowercase `#rrggbb` sRGB entries in the declared order. */+ colors: string[];+ threshold: number;+}++const fail = (detail: string): never => {+ throw new AuthoringDiagnosticError(+ 'DELIVERY_CONTRACT',+ `definePalette(colors, opts?): ${detail}`,+ );+};++function hex(value: unknown, label: string): string {+ if (typeof value !== 'string' || !/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value))+ fail(`${label} must be a hex colour such as '#6b6f73', got ${JSON.stringify(value)}.`);+ const digits = (value as string).replace('#', '').toLowerCase();+ return `#${digits.length === 3 ? [...digits].map((d) => d + d).join('') : digits}`;+}++export function normalizePalette(colors: unknown, opts?: unknown): PaletteDeclarationV1 {+ if (!Array.isArray(colors) || colors.length === 0 || colors.length > PALETTE_MAX_COLORS)+ fail(`colors must be an array of 1..${PALETTE_MAX_COLORS} hex colours.`);+ const entries = (colors as unknown[]).map((value, i) => hex(value, `colors[${i}]`));+ let threshold = PALETTE_DEFAULT_THRESHOLD;+ if (opts !== undefined) {+ if (!opts || typeof opts !== 'object' || Array.isArray(opts))+ fail('opts must be { threshold? }.');+ for (const key of Object.keys(opts as object))+ if (key !== 'threshold') fail(`unknown option ${JSON.stringify(key)}.`);+ const t = (opts as { threshold?: unknown }).threshold;+ if (t !== undefined) {+ if (typeof t !== 'number' || !Number.isFinite(t) || t <= 0 || t > 100)+ fail(`threshold must be a delta E in (0, 100], got ${String(t)}.`);+ threshold = t as number;+ }+ }+ return { schemaVersion: 1, colors: [...new Set(entries)], threshold };+}++/** Declare the palette; with `target` (normally the root) it is stamped there. */+export function definePalette(+ colors: readonly string[],+ opts?: PaletteOptionsV1,+ target?: THREE.Object3D,+): PaletteDeclarationV1 {+ const declaration = normalizePalette(colors, opts);+ if (target !== undefined) {+ if ((target as { isObject3D?: boolean } | null)?.isObject3D !== true)+ fail('target must be a scene node, normally the root.');+ target.userData[KILN_PALETTE_KEY] = structuredClone(declaration);+ }+ return declaration;+}++export function readPaletteDeclaration(value: unknown): PaletteDeclarationV1 | undefined {+ if (value === undefined) return undefined;+ try {+ const record = value as { schemaVersion?: unknown; colors?: unknown; threshold?: unknown };+ if (record.schemaVersion !== 1) return undefined;+ return normalizePalette(record.colors, { threshold: record.threshold });+ } catch {+ return undefined;+ }+}++const srgbToLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);+const linearToSrgb = (c: number) =>+ c <= 0.0031308 ? c * 12.92 : 1.055 * Math.max(0, c) ** (1 / 2.4) - 0.055;++/** Linear RGB (0..1) to CIELAB under D65. */+export function linearRgbToLab([r, g, b]: readonly [number, number, number]): [+ number,+ number,+ number,+] {+ const x = (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047;+ const y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b;+ const z = (0.0193339 * r + 0.119192 * g + 0.9503041 * b) / 1.08883;+ const f = (t: number) => (t > 216 / 24389 ? Math.cbrt(t) : ((24389 / 27) * t + 16) / 116);+ const [fx, fy, fz] = [f(x), f(y), f(z)];+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];+}+const hexToLinear = (value: string): [number, number, number] => {+ const n = Number.parseInt(value.slice(1), 16);+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((c) => srgbToLinear(c / 255)) as [+ number,+ number,+ number,+ ];+};+const linearToHex = (rgb: readonly number[]) =>+ `#${rgb+ .map((c) =>+ Math.round(Math.min(1, Math.max(0, linearToSrgb(c))) * 255)+ .toString(16)+ .padStart(2, '0'),+ )+ .join('')}`;+const deltaE = (a: readonly number[], b: readonly number[]) =>+ Math.hypot(a[0]! - b[0]!, a[1]! - b[1]!, a[2]! - b[2]!);++/**+ * Compare every material drawn by a visible scene node (collider proxies excluded) with the+ * palette. glTF base colour factors are linear; they are compared in CIELAB after conversion.+ * A textured material is judged by its factor (which tints the texture) and says so.+ */+export function evaluatePalette(declaration: PaletteDeclarationV1, doc: Document): PaletteReportV1 {+ const palette = declaration.colors.map((color) => ({+ color,+ lab: linearRgbToLab(hexToLinear(color)),+ }));+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ const materials = new Set<import('@gltf-transform/core').Material>();+ const visit = (node: import('@gltf-transform/core').Node, hidden: boolean): void => {+ const nodeHidden = hidden || isHiddenGltfNode(node);+ if (!nodeHidden)+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const material = primitive.getMaterial();+ if (material && material.getName() !== COLLIDER_PROXY_MATERIAL_NAME)+ materials.add(material);+ }+ for (const child of node.listChildren()) visit(child, nodeHidden);+ };+ for (const node of scene?.listChildren() ?? []) visit(node, false);+ const offPalette: PaletteReportV1['offPalette'] = [];+ for (const material of materials) {+ const factor = material.getBaseColorFactor();+ const lab = linearRgbToLab([factor[0]!, factor[1]!, factor[2]!]);+ let nearest = palette[0]!;+ let distance = Number.POSITIVE_INFINITY;+ for (const entry of palette) {+ const d = deltaE(lab, entry.lab);+ if (d < distance) {+ distance = d;+ nearest = entry;+ }+ }+ if (distance > declaration.threshold)+ offPalette.push({+ material: material.getName(),+ color: linearToHex(factor.slice(0, 3)),+ nearest: nearest.color,+ deltaE: Math.round(distance * 100) / 100,+ ...(material.getBaseColorTexture() ? { textured: true as const } : {}),+ });+ }+ offPalette.sort((a, b) => b.deltaE - a.deltaE || (a.material < b.material ? -1 : 1));+ return {+ status: offPalette.length ? 'warn' : 'pass',+ colors: [...declaration.colors],+ threshold: declaration.threshold,+ checkedMaterials: materials.size,+ offPalette,+ };+}diff --git a/src/primitives.ts b/src/primitives.tsindex 81799dc5..cb582030 100644--- a/src/primitives.ts+++ b/src/primitives.ts@@ -35,6 +35,7 @@ import {} from './delivery';import { bakeSurfaceAttributes } from './surface-bake';import { requireSolid } from './require-solid';+import { definePalette, type PaletteDeclarationV1 } from './palette-check';import { type BudgetDeclarationV1, defineBudget } from './budget';import { useCubicSpline } from './animation-cubic';import {@@ -2151,6 +2152,7 @@ export type DiagnosticConsole = Pick<Console, 'log' | 'info' | 'debug' | 'warn'/** Declarations a program makes without a node; executeKilnCode stamps them on the root. */export interface SandboxDeclarations {budget?: BudgetDeclarationV1;+ palette?: PaletteDeclarationV1;}/** Symbol-keyed, so it never becomes a sandbox global. */export const SANDBOX_DECLARATIONS: unique symbol = Symbol('kiln.sandbox.declarations');@@ -2303,6 +2305,18 @@ export function buildSandboxGlobals(return declaration;},),+ definePalette: wrap(+ 'definePalette',+ (+ colors: Parameters<typeof definePalette>[0],+ opts?: Parameters<typeof definePalette>[1],+ target?: THREE.Object3D,+ ) => {+ const declaration = definePalette(colors, opts, target);+ declarations.palette = declaration;+ return declaration;+ },+ ),capsuleGeo: wrapGeo('capsuleGeo', capsuleGeo),capsuleXGeo: wrapGeo('capsuleXGeo', capsuleXGeo),capsuleYGeo: wrapGeo('capsuleYGeo', capsuleYGeo),diff --git a/src/qa/vegetation.ts b/src/qa/vegetation.tsindex 8368effe..3e23f309 100644--- a/src/qa/vegetation.ts+++ b/src/qa/vegetation.ts@@ -467,6 +467,11 @@ export const VEGETATION_GROWTH_BANDS_V1: Readonly<trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] },},+ // Columnar ribbed trunks and elbowed arms barely taper.+ cactus: {+ trunk: { taper: [0.45, 1.15], lengthRadius: [1.5, 45] },+ branch: { taper: [0.35, 1.15], lengthRadius: [1.5, 35] },+ },fungus: {trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] },diff --git a/src/render.ts b/src/render.tsindex 587418ca..ce516860 100644--- a/src/render.ts+++ b/src/render.ts@@ -83,6 +83,12 @@ import {type SandboxDeclarations,} from './primitives';import { evaluateBudget, KILN_BUDGET_KEY, normalizeBudget, readBudgetDeclaration } from './budget';+import {+ evaluatePalette,+ KILN_PALETTE_KEY,+ normalizePalette,+ readPaletteDeclaration,+} from './palette-check';import {collectGlbMetrics,gradeInstanceability,@@ -297,6 +303,10 @@ export async function inspectGlbIntegration(levelsOfDetail,): undefined;+ const paletteDeclaration = readPaletteDeclaration(+ (scene.getExtras() as Record<string, unknown>)[KILN_PALETTE_KEY],+ );+ const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {schemaVersion: 'kiln.integration-manifest.v1',@@ -341,6 +351,7 @@ export async function inspectGlbIntegration(...(delivery.kit ? { kit: delivery.kit } : {}),...(delivery.ports.length ? { ports: delivery.ports } : {}),...(budget ? { budget } : {}),+ ...(palette ? { palette } : {}),...(vertexAttributes.length ? { vertexAttributes } : {}),...(delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {}),structuralQa: {@@ -487,6 +498,8 @@ export async function executeKilnCode(];if (declared?.budget && root.userData[KILN_BUDGET_KEY] === undefined)root.userData[KILN_BUDGET_KEY] = declared.budget;+ if (declared?.palette && root.userData[KILN_PALETTE_KEY] === undefined)+ root.userData[KILN_PALETTE_KEY] = declared.palette;const clips = animate ? ((await animate(root)) ?? []) : [];@@ -1838,6 +1851,15 @@ export async function renderSceneToGLB([KILN_BUDGET_KEY]: normalizeBudget(root.userData[KILN_BUDGET_KEY]),});}+ // A declared palette travels the same way; the receipt judges the written materials.+ if (root.userData[KILN_PALETTE_KEY] !== undefined && opts.derivative !== true) {+ const declared = root.userData[KILN_PALETTE_KEY] as { colors?: unknown; threshold?: unknown };+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0]!;+ scene.setExtras({+ ...scene.getExtras(),+ [KILN_PALETTE_KEY]: normalizePalette(declared?.colors, { threshold: declared?.threshold }),+ });+ }// Visibility flags and LOD chains are written before any pass merges or prunes nodes, so// those passes see them and keep them; flags first, while every node is still in place.applySurfaceBakeExtras(root, doc);@@ -1965,6 +1987,11 @@ export async function renderSceneToGLB(// Delivery findings are advisory: each is a build warning, never a QA disposition.for (const finding of integrationManifest.deliveryDiagnostics ?? [])warnings.push(`${finding.code} ${finding.path}: ${finding.message}`);+ const palette = integrationManifest.palette;+ for (const finding of palette?.offPalette ?? [])+ warnings.push(+ `PALETTE_OFF material ${JSON.stringify(finding.material)} ${finding.color} is delta E ${finding.deltaE} from the nearest palette entry ${finding.nearest} (threshold ${palette!.threshold})${finding.textured ? '; the factor tints a texture that is not judged' : ''}.`,+ );const diagnosticViews: CapturedDiagnosticV1[] = [];const rig = requirements.requirements.requirements.rig;diff --git a/src/vegetation-prompt.ts b/src/vegetation-prompt.tsindex 8fba3038..16619614 100644--- a/src/vegetation-prompt.ts+++ b/src/vegetation-prompt.ts@@ -62,6 +62,11 @@ export const VEGETATION_SUBTYPE_RECIPES_V1: Readonly<guidance:'Compose thick leaves or pads from scaled sphereGeo, capsuleGeo, or rounded boxGeo parts around a grounded center. Vary vertical reach and azimuth modestly while keeping each pad visibly joined to the base.',},+ cactus: {+ marker: 'RECIPE_CACTUS_V1',+ guidance:+ 'Build the trunk as a ribbed star-profile loft: await extrudeProfile(starOutline, { axis: "y", depth, taper, divisions }) with 6 to 12 rounded ribs (alternate outer and inner radii), seated at Y=0. Sweep each arm with pipeAlongPath through an elbow (out from the trunk, then up; bendRadius about one arm radius), embedded into the trunk. Seat spine clusters as small foliageCardGeo or crossedQuadsGeo cards on the rib crests, a few per rib, and keep them subordinate to the silhouette. Deliver explicit LOD tiers with defineLod: LOD0 full ribs, arms and spines; LOD1 fewer ribs and no spines; a last crossedQuadsGeo card tier with impostor: true.',+ },fungus: {marker: 'RECIPE_FUNGUS_V1',guidance:@@ -104,6 +109,6 @@ export function vegetationSubtypePromptContext(intent: AssetIntentV1): string {recipe.guidance,state,material,- 'Use current executable APIs only. No branch, canopy, leaf-distribution, frond, procedural-map, or LOD helper has been promoted.',+ 'Use current executable APIs only. No branch, canopy, leaf-distribution, frond, procedural-map, or vegetation-specific LOD helper has been promoted; defineLod is the general LOD helper.',].join('\n');}