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
feat(budget): report an instanced draw estimate beside the draws cap (#200)
Matt Kissinger4f240223e888
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9b9f2951..90ae212d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,11 @@ does not publish a package.([#202](https://github.com/instruktlabs/kiln/issues/202)). `docs/programs.md` lists thesandbox globals and refused host capabilities, and `docs/geometry.md` states theexact-equality export weld that was documented only in the migration notes.+- Budget receipts state that `draws` caps unbatched LOD0 draws (unchanged) and add+ `measured.instancedDraws` on the LOD0 tier when a draws cap is declared: the draws the+ three runtime target leaves after batching each `repeatInstances` group. It is+ informational and never changes the tier's status+ ([#200](https://github.com/instruktlabs/kiln/issues/200)).## 1.4.0 (2026-10-23)diff --git a/docs/delivery-contract.md b/docs/delivery-contract.mdindex dbad5857..de75edb8 100644--- a/docs/delivery-contract.md+++ b/docs/delivery-contract.md@@ -57,7 +57,11 @@ attribute names, so shaders read `_edge` and `_cavity`.- `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.+ chain plus everything outside the chains; `draws` caps LOD0 draw calls as the GLB+ stores them, before any consumer batching, so each child of a `repeatInstances` group+ counts. Beside the measured `draws`, the LOD0 tier reports `instancedDraws`: the draws+ the three runtime target leaves after batching each group into one instanced draw.+ It is informational and never changes the tier's status.- `definePalette(colors, { threshold? })` stores scene extras `kilnPaletteV1`. Eachmaterial drawn by a visible node is compared by its base colour factor in CIELAB(CIE 1976 delta E, default threshold 10). Off-palette materials becomediff --git a/docs/geometry.md b/docs/geometry.mdindex b0864571..ef0e72af 100644--- a/docs/geometry.md+++ b/docs/geometry.md@@ -497,7 +497,11 @@ bytes before and after this pass, not GLB file size.`defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 })` records the asset'sbudget. 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+`MSFT_lod` chain plus everything outside the chains, and draws count LOD0 as stored,+before batching: each child of a `repeatInstances` group is a draw. The LOD0 tier also+reports `instancedDraws`, the count after the three runtime target batches those groups,+for information only. Do not merge repeated parts by hand to meet a draws cap that the+batched export would meet; raise the cap or note the difference instead. The resultis `budget: { status, tiers }` in render results, `kiln_render` and CLI receipts. Itis advisory; `kiln render --strict-budget` exits 1 when a tier fails.diff --git a/skills/kiln-author-asset/references/geometry-recipes.md b/skills/kiln-author-asset/references/geometry-recipes.mdindex e6623fb7..64233fbb 100644--- a/skills/kiln-author-asset/references/geometry-recipes.md+++ b/skills/kiln-author-asset/references/geometry-recipes.md@@ -477,6 +477,9 @@ requireSolid(frame);- 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.+- A `draws` cap counts each child of a `repeatInstances` group; the LOD0 tier's+ `instancedDraws` shows the count after the three.js export batches them. Do not merge+ repeated parts by hand only to meet the cap.- Budgets and palettes are advisory. `requireSolid` fails the build unless the partis closed, manifold and outward; build it from solid helpers (`boxGeo`,`extrudeProfile`, `revolveProfile`, `roundedBoxGeo`) rather than open sheets.diff --git a/src/__tests__/delivery-budget.test.ts b/src/__tests__/delivery-budget.test.tsindex 650fb65d..592b8ab3 100644--- a/src/__tests__/delivery-budget.test.ts+++ b/src/__tests__/delivery-budget.test.ts@@ -16,6 +16,10 @@ import { AuthoringDiagnosticError } from '../evaluator/authoring-diagnostic';import { buildSandboxGlobals } from '../primitives';import { renderGLBInProcess } from '../render';import { createKilnProgramToolRegistry } from '../tools/registry';+import { MeshoptDecoder } from 'meshoptimizer';+import { deliverThreeRuntimeGlb } from '../asset-export';+import { createGltfIO } from '../gltf-io';+import { collectGlbMetrics } from '../metrics';const tiered = (budget: string) => `const meta={name:'Budgeted'};function build(){@@ -68,7 +72,7 @@ describe('defineBudget', () => {{tier: 'LOD0',declared: { triangles: 400, draws: 2 },- measured: { triangles: 364, draws: 2 },+ measured: { triangles: 364, draws: 2, instancedDraws: 2 },status: 'pass',},{ tier: 'LOD1', declared: { triangles: 20 }, measured: { triangles: 24 }, status: 'fail' },@@ -94,6 +98,40 @@ describe('defineBudget', () => {const result = await renderGLBInProcess(tiered(''));expect(result.integrationManifest.budget).toBeUndefined();});++ // #200: draws caps unbatched LOD0 draws; the receipt adds what the three runtime+ // target would draw after batching each repeatInstances group, without judging it.+ test('draws counts unbatched draws and reports the instanced estimate beside them', async () => {+ const program = `const meta={name:'Stool'};+function build(){+ const root=createRoot('Root');+ const wood=gameMaterial('#8a6a4a');+ createPart('Seat',cylinderGeo(0.2,0.2,0.04,16),wood,{parent:root,position:[0,0.45,0]});+ const legs=new THREE.Group(); legs.name='Legs'; root.add(legs);+ const leg=boxGeo(0.03,0.43,0.03);+ for(let i=0;i<4;i++) createPart('Leg_'+i,leg,wood,{parent:legs,position:[i<2?-0.12:0.12,0.215,i%2?-0.12:0.12]});+ repeatInstances(legs);+ defineBudget({ triangles: 1000, draws: 2 });+ return root;+}`;+ const result = await renderGLBInProcess(program);+ const lod0 = result.integrationManifest.budget!.tiers[0]!;+ expect(lod0.declared.draws).toBe(2);+ // Seat plus four legs: the cap is judged on these five unbatched draws.+ expect(lod0.measured.draws).toBe(5);+ expect(lod0.status).toBe('fail');+ expect(lod0.measured.instancedDraws).toBe(2);+ // The estimate is what the three runtime target actually draws.+ const runtime = await deliverThreeRuntimeGlb(result.glb);+ const doc = await createGltfIO()+ .registerDependencies({ 'meshopt.decoder': MeshoptDecoder })+ .readBinary(runtime.glb);+ expect(collectGlbMetrics(doc).drawCalls).toBe(lod0.measured.instancedDraws!);+ // Without batching the estimate equals the measured draws.+ const plain = await renderGLBInProcess(program.replace('repeatInstances(legs);', ''));+ const plainLod0 = plain.integrationManifest.budget!.tiers[0]!;+ expect(plainLod0.measured).toMatchObject({ draws: 5, instancedDraws: 5 });+ });});describe('CLI budget receipt', () => {diff --git a/src/budget.ts b/src/budget.tsindex 3eb76e9a..71d69295 100644--- a/src/budget.ts+++ b/src/budget.ts@@ -105,9 +105,14 @@ export function readBudgetDeclaration(value: unknown): BudgetDeclarationV1 | und*/export function evaluateBudget(declaration: BudgetDeclarationV1,- measuredLod0: { triangles: number; draws: number },+ measuredLod0: { triangles: number; draws: number; instancedDraws?: number },chains: readonly LevelOfDetailChainV1[],): BudgetReportV1 {+ // Reported beside draws, never judged (#200).+ const instanced =+ measuredLod0.instancedDraws === undefined+ ? {}+ : { instancedDraws: measuredLod0.instancedDraws };const outside =measuredLod0.triangles - chains.reduce((sum, chain) => sum + chain.levels[0]!.triangles, 0);const tierTriangles = (level: number) =>@@ -130,7 +135,7 @@ export function evaluateBudget(},measured: {triangles,- ...(drawsDeclared === undefined ? {} : { draws: measuredLod0.draws }),+ ...(drawsDeclared === undefined ? {} : { draws: measuredLod0.draws, ...instanced }),},status: pass ? 'pass' : 'fail',};@@ -139,7 +144,7 @@ export function evaluateBudget(tiers.unshift({tier: 'LOD0',declared: { draws: declaration.draws },- measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws },+ measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws, ...instanced },status: measuredLod0.draws <= declaration.draws ? 'pass' : 'fail',});return { status: tiers.every((tier) => tier.status === 'pass') ? 'pass' : 'fail', tiers };diff --git a/src/contracts/integration.ts b/src/contracts/integration.tsindex 03004397..5806aeb1 100644--- a/src/contracts/integration.ts+++ b/src/contracts/integration.ts@@ -137,7 +137,12 @@ export interface BudgetTierV1 {/** `LOD0`, `LOD1`, ...: tier n draws level min(n, last) of every chain. */tier: string;declared: { triangles?: number; draws?: number };- measured: { triangles: number; draws?: number };+ /**+ * `draws` is the LOD0 draw calls in the GLB before any consumer batching; the cap is+ * judged on it. `instancedDraws` (beside `draws`) is informational: the draws after the+ * three runtime target batches each `repeatInstances` group, never judged.+ */+ measured: { triangles: number; draws?: number; instancedDraws?: number };status: 'pass' | 'fail';}diff --git a/src/render.ts b/src/render.tsindex ccc2605e..fc78e015 100644--- a/src/render.ts+++ b/src/render.ts@@ -302,10 +302,20 @@ export async function inspectGlbIntegration(const budgetDeclaration = readBudgetDeclaration((scene.getExtras() as Record<string, unknown>)[KILN_BUDGET_KEY],);+ // The instanced estimate runs the three target's batching on a copy, so it is loaded+ // only when a draws cap is declared.+ const instancedDraws =+ budgetDeclaration?.draws === undefined+ ? undefined+ : await (await import('./runtime-three')).instancedDrawEstimate(doc);const budget = budgetDeclaration? evaluateBudget(budgetDeclaration,- { triangles: metrics.triangles, draws: metrics.drawCalls },+ {+ triangles: metrics.triangles,+ draws: metrics.drawCalls,+ ...(instancedDraws === undefined ? {} : { instancedDraws }),+ },levelsOfDetail,): undefined;diff --git a/src/runtime-three.ts b/src/runtime-three.tsindex e60eec41..24217690 100644--- a/src/runtime-three.ts+++ b/src/runtime-three.ts@@ -30,14 +30,14 @@ import {EXTMeshoptCompression,KHRTextureBasisu,} from '@gltf-transform/extensions';-import { dedup, quantize, reorder } from '@gltf-transform/functions';+import { cloneDocument, dedup, quantize, reorder } from '@gltf-transform/functions';import type { Property } from '@gltf-transform/core';import * as THREE from 'three';import { KILN_SEMANTIC_ROLES, readSemanticMetadataV1FromExtras } from './contracts/semantic';import { createGltfIO, MSFT_LOD } from './gltf-io';import { deliveryNodePaths } from './delivery-inspect';import { KILN_REPEAT_INSTANCES_KEY } from './delivery';-import { isHiddenGltfNode } from './metrics';+import { collectGlbMetrics, isHiddenGltfNode } from './metrics';import { isKtx2, sha256Hex } from './runtime-textures';/** Bits per quantized attribute class; custom underscore attributes stay float32. */@@ -188,6 +188,17 @@ function meshSignature(mesh: Mesh, ids: Map<Property, number>): string {).join('|');}+/**+ * The draw calls this target leaves after batching `repeatInstances` groups (#200): the same+ * accessor merge and instancing pass, run on a copy, counted the way the budget counts draws.+ */+export async function instancedDrawEstimate(doc: Document): Promise<number> {+ const copy = cloneDocument(doc);+ copy.setLogger(new Logger(Logger.Verbosity.SILENT));+ await copy.transform(dedup({ propertyTypes: [PropertyType.ACCESSOR], keepUniqueNames: true }));+ applyScopedInstancing(copy);+ return collectGlbMetrics(copy).drawCalls;+}function applyScopedInstancing(doc: Document): InstancingRecord[] {const report: InstancingRecord[] = [];const ids = new Map<Property, number>();