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(kiln): architecture category — enterable buildings as a core capability
Matt Kissingercc1d265aa31f
diff --git a/__tests__/__snapshots__/prompt-api.test.ts.snap b/__tests__/__snapshots__/prompt-api.test.ts.snapindex 1de4a467..b273f162 100644--- a/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -25,6 +25,30 @@ createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, runcreateWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })// Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft// wings and helicopter stub wings.+room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })+ // Builds a HOLLOW, enterable room: four thin walls + a floor, human-scaled (defaults: 2.8m+ // ceiling, a centered 1.1x2.1m front door so it is enterable by default). \`front\` faces +X;+ // the floor sits on the ground. The keystone of an architecture asset — add a roof with+ // createRoofPlanes and fixtures as separate parts.+ // NOTE: Use for any building the player enters. Do NOT model a building as a solid block —+ // room() guarantees real interior space and a doorway gap. Pass openings to add windows /+ // side doors.+wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, parent? })+ // A single wall panel with an optional real door/window cut, composed from solid box segments+ // (side panels + lintel + window sill) — no CSG. Base at local Y=0, centered on the run axis.+ // Use to compose custom building layouts or interior dividing walls beyond the default+ // room().+createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })+ // A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite+ // tilts — never mirrored the same way), footprint-matched with an eave overhang. Eave at+ // local Y=0, ridge at Y=height, so position the group at Y=wallHeight. Returns a named group+ // (e.g. \`Roof\`) the engine can lift to reveal the interior.+ // NOTE: The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does+ // this for you. Drop it onto the walls (position.y = wall height).+createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })+ // A straight flight of stairs: box treads (with optional risers) climbing totalRise over+ // totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in+ // a multi-storey building.// Geometry (returns BufferGeometry)boxGeo(width: number, height: number, depth: number) // 6-face box. 12 tris regardless of size. Cheapest geometry.@@ -271,6 +295,38 @@ createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thick// wings and helicopter stub wings.// e.g. createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4,// rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });+room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })+ // Builds a HOLLOW, enterable room: four thin walls + a floor, human-scaled (defaults: 2.8m+ // ceiling, a centered 1.1x2.1m front door so it is enterable by default). \`front\` faces +X;+ // the floor sits on the ground. The keystone of an architecture asset — add a roof with+ // createRoofPlanes and fixtures as separate parts.+ // NOTE: Use for any building the player enters. Do NOT model a building as a solid block —+ // room() guarantees real interior space and a doorway gap. Pass openings to add windows /+ // side doors.+ // e.g. const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings:+ // [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });+wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, parent? })+ // A single wall panel with an optional real door/window cut, composed from solid box segments+ // (side panels + lintel + window sill) — no CSG. Base at local Y=0, centered on the run axis.+ // Use to compose custom building layouts or interior dividing walls beyond the default+ // room().+ // e.g. wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis:+ // 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });+createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })+ // A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite+ // tilts — never mirrored the same way), footprint-matched with an eave overhang. Eave at+ // local Y=0, ridge at Y=height, so position the group at Y=wallHeight. Returns a named group+ // (e.g. \`Roof\`) the engine can lift to reveal the interior.+ // NOTE: The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does+ // this for you. Drop it onto the walls (position.y = wall height).+ // e.g. const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height:+ // 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root }); roof.position.y = 2.8;+createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })+ // A straight flight of stairs: box treads (with optional risers) climbing totalRise over+ // totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in+ // a multi-storey building.+ // e.g. createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4,+ // axis: 'x', parent: root });// Geometry (returns BufferGeometry)boxGeo(width: number, height: number, depth: number) // 6-face box. 12 tris regardless of size. Cheapest geometry.diff --git a/__tests__/primitives.test.ts b/__tests__/primitives.test.tsindex e48ba2c5..1cc28cbb 100644--- a/__tests__/primitives.test.ts+++ b/__tests__/primitives.test.ts@@ -26,6 +26,10 @@ import {beamBetween,createLadder,createWingPair,+ room,+ wallWithOpening,+ createRoofPlanes,+ createStairs,// geometriesboxGeo,sphereGeo,@@ -220,6 +224,127 @@ describe('attachment helpers', () => {});});+describe('building helpers', () => {+ test('wallWithOpening: solid wall is one panel', () => {+ const wall = wallWithOpening('S', gameMaterial(0x808080), {+ length: 4,+ height: 2.8,+ thickness: 0.15,+ });+ expect(wall.name).toBe('S');+ expect(wall.children.length).toBe(1);+ expect(wall.children[0]!.name).toBe('Mesh_S');+ });++ test('wallWithOpening: a door cuts a real gap (two jambs + a lintel, no sill)', () => {+ const wall = wallWithOpening('W', gameMaterial(0x808080), {+ length: 4,+ height: 2.8,+ thickness: 0.15,+ opening: { kind: 'door' },+ });+ expect(wall.children.map((c) => c.name).sort()).toEqual(['Mesh_W_L', 'Mesh_W_Lintel', 'Mesh_W_R']);+ });++ test('wallWithOpening: a window adds a sill apron under the gap', () => {+ const wall = wallWithOpening('Win', gameMaterial(0x808080), {+ length: 4,+ height: 2.8,+ thickness: 0.15,+ opening: { kind: 'window' },+ });+ expect(wall.children.map((c) => c.name).sort()).toEqual([+ 'Mesh_Win_L',+ 'Mesh_Win_Lintel',+ 'Mesh_Win_R',+ 'Mesh_Win_Sill',+ ]);+ });++ test('room: hollow shell of four walls + a floor, enterable by default', () => {+ const root = createRoot('R');+ const { root: hut, walls, floor } = room('Hut', gameMaterial(0x8b6f3d), {+ width: 5,+ depth: 4,+ parent: root,+ });+ expect(hut.parent).toBe(root);+ // 4 wall containers + 1 floor.+ expect(hut.children.length).toBe(5);+ expect(floor).not.toBeNull();+ expect(floor!.name).toBe('Mesh_Hut_Floor');+ expect(walls.front.name).toBe('Hut_WallFront');+ // Default = a door on the front wall, so the front wall is NOT a solid slab.+ expect(walls.front.children.length).toBe(3); // L, R, Lintel+ // The other walls have no opening — a single solid panel each.+ expect(walls.back.children.length).toBe(1);+ expect(walls.left.children.length).toBe(1);+ expect(walls.right.children.length).toBe(1);+ // Front faces +X; left/right sit at -/+ width/2 on Z.+ expect(walls.front.position.x).toBeCloseTo(2); // depth/2+ expect(walls.left.position.z).toBeCloseTo(-2.5); // -width/2+ expect(walls.right.position.z).toBeCloseTo(2.5);+ });++ test('room: openings can be placed on any wall', () => {+ const { walls } = room('Hut', gameMaterial(0x8b6f3d), {+ openings: [+ { wall: 'front', kind: 'door' },+ { wall: 'right', kind: 'window' },+ ],+ });+ expect(walls.front.children.length).toBe(3); // door+ expect(walls.right.children.length).toBe(4); // window (+ sill)+ expect(walls.back.children.length).toBe(1); // solid+ });++ test('createRoofPlanes: two slopes fall AWAY from each other from one ridge', () => {+ const { root, slopes } = createRoofPlanes('Roof', gameMaterial(0x6b4f2a), {+ width: 5,+ depth: 4,+ height: 1.6,+ ridgeAxis: 'x',+ });+ expect(root.name).toBe('Roof');+ expect(slopes[0].name).toBe('Mesh_RoofA');+ expect(slopes[1].name).toBe('Mesh_RoofB');+ // Opposite tilt (NOT mirrored the same way) — the anti-defect invariant.+ expect(slopes[0].rotation.x).not.toBeCloseTo(0);+ expect(slopes[0].rotation.x).toBeCloseTo(-slopes[1].rotation.x);+ // Slopes drop toward opposite Z sides; ridge centered above the eaves.+ expect(Math.sign(slopes[0].position.z)).toBe(1);+ expect(Math.sign(slopes[1].position.z)).toBe(-1);+ expect(slopes[0].position.y).toBeCloseTo(0.8); // height/2+ });++ test('createStairs: named treads climb up and along; risers included', () => {+ const { root, steps } = createStairs('Porch', gameMaterial(0x888888), {+ steps: 4,+ totalRise: 1.0,+ totalRun: 2.0,+ width: 1.2,+ axis: 'x',+ });+ expect(steps.map((s) => s.name)).toEqual([+ 'Mesh_PorchStep1',+ 'Mesh_PorchStep2',+ 'Mesh_PorchStep3',+ 'Mesh_PorchStep4',+ ]);+ expect(steps[3]!.position.y).toBeGreaterThan(steps[0]!.position.y);+ expect(steps[3]!.position.x).toBeGreaterThan(steps[0]!.position.x);+ expect(root.children.length).toBe(8); // 4 treads + 4 risers+ });++ test('createStairs: rejects no steps and a degenerate flight', () => {+ const mat = gameMaterial(0x888888);+ expect(() => createStairs('Bad', mat, { steps: 0, totalRise: 1, totalRun: 1, width: 1 })).toThrow(+ 'steps must be >= 1',+ );+ expect(() => createStairs('Bad', mat, { totalRise: 0, totalRun: 1, width: 1 })).toThrow('must be non-zero');+ });+});+// =============================================================================// Geometry primitives// =============================================================================diff --git a/__tests__/prompt.test.ts b/__tests__/prompt.test.tsindex 46ba6a5c..1a4b4235 100644--- a/__tests__/prompt.test.ts+++ b/__tests__/prompt.test.ts@@ -17,6 +17,7 @@ import {KILN_TSL_SYSTEM_PROMPT,KILN_BOTH_SYSTEM_PROMPT,KILN_REFINE_DIRECTIVE,+ ARCHITECTURE_CONTEXT,KILN_API_SECTION,KILN_API_SECTION_UNIFIED,KILN_VISUAL_QA_UNIFIED,@@ -102,6 +103,34 @@ describe('buildUserPrompt', () => {expect(prompt).toContain('Create a prop: red barrel');});+ test('appends the architecture directive on a fresh architecture generation', () => {+ const prompt = buildUserPrompt({+ prompt: 'a stone watchtower',+ mode: 'glb',+ category: 'architecture',+ });+ expect(prompt).toContain('Create a architecture: a stone watchtower');+ expect(prompt).toContain(ARCHITECTURE_CONTEXT);+ // Guidance comes after the task line.+ expect(prompt.indexOf('## Task')).toBeLessThan(prompt.indexOf(ARCHITECTURE_CONTEXT));+ });++ test('does not append the architecture directive for other categories', () => {+ const prompt = buildUserPrompt({ prompt: 'a barrel', mode: 'glb', category: 'prop' });+ expect(prompt).not.toContain(ARCHITECTURE_CONTEXT);+ });++ test('does not append the architecture directive when refining (existingCode set)', () => {+ const prompt = buildUserPrompt({+ prompt: 'add a second floor',+ mode: 'glb',+ category: 'architecture',+ existingCode: 'function build() { return createRoot("Tower"); }',+ });+ expect(prompt).not.toContain(ARCHITECTURE_CONTEXT);+ expect(prompt).toContain('## Edit Request');+ });+test('prepends an Original Request section (intent -> code -> edit order) when refining', () => {const prompt = buildUserPrompt({prompt: 'make the barrel taller',diff --git a/agent/index.ts b/agent/index.tsindex 82995c94..d94de969 100644--- a/agent/index.ts+++ b/agent/index.ts@@ -36,7 +36,7 @@ export {KilnEditBuffer,KILN_SUBMIT_TOOL_NAME,} from './tools';-export type { SubmitSink, EditSink, UnifiedSink, EditRecord, EditResult } from './tools';+export type { SubmitSink, EditSink, UnifiedSink, EditRecord, EditResult, KilnRenderCandidate } from './tools';export { unifiedDiff } from './diff';export type { UnifiedDiffOptions } from './diff';diff --git a/agent/run.ts b/agent/run.tsindex 93b0750b..99454bd8 100644--- a/agent/run.ts+++ b/agent/run.ts@@ -28,7 +28,7 @@ import {KILN_EDIT_DIRECTIVE_UNIFIED,} from '../prompt';import type { AssetCategory, AssetStyle } from '../prompt';-import type { SubmitSink, EditSink, UnifiedSink, EditRecord } from './tools';+import type { SubmitSink, EditSink, UnifiedSink, EditRecord, KilnRenderCandidate } from './tools';import {resolveToolSurface,buildAgentTools,@@ -108,6 +108,11 @@ export interface RunKilnAgentOptions {/** Live agent-loop events (tool calls / model calls) for progress UIs.* Best-effort: sink errors are swallowed and never fail the run. */onEvent?: (event: KilnAgentEvent) => void;+ /** Live render-candidate sink (one per successful kiln_render on the unified+ * surface): the working buffer + its six-view image. Lets the host stream a+ * filmstrip of intermediate renders and let the user pick a version. Best-effort;+ * ignored on the current/edit surfaces. */+ onCandidate?: (c: KilnRenderCandidate) => void;/** A complete Kiln program used as a style anchor for FRESH generation —* rendered as "## Reference Asset" in the user prompt (ignored when* existingCode is set). ~5-15k input tokens/run; cached on most providers. */diff --git a/agent/surface.ts b/agent/surface.tsindex d41062f9..b1f9aa32 100644--- a/agent/surface.ts+++ b/agent/surface.ts@@ -14,6 +14,7 @@ import {type SubmitSink,type EditSink,type UnifiedSink,+ type KilnRenderCandidate,} from './tools';/** Which agent tool surface drives the loop. 'current' = today's@@ -28,6 +29,9 @@ export type RefineMode = 'rewrite' | 'edit';export interface ToolBuildOptions {existingCode?: string;refineMode?: RefineMode;+ /** Live render-candidate sink, wired into the unified surface's kiln_render.+ * Only the unified surface emits candidates (current/edit surfaces ignore it). */+ onCandidate?: (c: KilnRenderCandidate) => void;}/** Per-run sinks for the three tool factories (only one is read, by surface). */@@ -61,6 +65,7 @@ export function buildAgentTools(return makeKilnUnifiedTools({...(opts.existingCode ? { seedCode: opts.existingCode } : {}),sink: sinks.unifiedSink,+ ...(opts.onCandidate ? { onCandidate: opts.onCandidate } : {}),});}const editMode = Boolean(opts.existingCode) && opts.refineMode === 'edit';diff --git a/agent/tools-unified.test.ts b/agent/tools-unified.test.tsindex cba60e2d..e2fb275a 100644--- a/agent/tools-unified.test.ts+++ b/agent/tools-unified.test.ts@@ -141,6 +141,25 @@ describe('makeKilnUnifiedTools', () => {expect(out.error).toBeDefined();});+ test('kiln_render emits a render candidate (buffer code + six-view png) via onCandidate', async () => {+ const sink: UnifiedSink = { edits: [] };+ const got: Array<{ code: string; pngBase64: string; tris?: number }> = [];+ const tools = makeKilnUnifiedTools({ seedCode: BOX_CODE, sink, onCandidate: (c) => got.push(c) });+ await findTool(tools, 'kiln_render').invoke({});+ expect(got).toHaveLength(1);+ expect(got[0]!.code).toBe(BOX_CODE); // the exact working buffer+ expect(got[0]!.pngBase64.length).toBeGreaterThan(0); // the same image the agent saw+ expect(got[0]!.tris).toBeGreaterThan(0);+ });++ test('kiln_render on a broken buffer does NOT emit a candidate (image-free build)', async () => {+ const sink: UnifiedSink = { edits: [] };+ const got: unknown[] = [];+ const tools = makeKilnUnifiedTools({ seedCode: 'not a kiln program (', sink, onCandidate: (c) => got.push(c) });+ await findTool(tools, 'kiln_render').invoke({});+ expect(got).toHaveLength(0); // a failed render has no image → no candidate+ });+test('kiln_finalize captures the buffer and marks finalized', async () => {const sink: UnifiedSink = { edits: [] };const tools = makeKilnUnifiedTools({ sink });diff --git a/agent/tools.ts b/agent/tools.tsindex 1a72f5cb..0c5977b0 100644--- a/agent/tools.ts+++ b/agent/tools.ts@@ -434,6 +434,22 @@ export interface UnifiedSink {finalized?: boolean;}+/**+ * A live render candidate surfaced out-of-band from the unified `kiln_render`+ * tool: the working-buffer code at this render plus its six-view grid PNG+ * (base64). Emitted in addition to — never instead of — what the agent sees.+ * Consumers (the runtime/web tier) shape it into a streamed thumbnail and a+ * rebakeable version so the user can watch the build and "pick a version".+ */+export interface KilnRenderCandidate {+ /** The exact program in the working buffer at this render. */+ code: string;+ /** The six-view grid PNG, base64 (the same image the agent inspected). */+ pngBase64: string;+ /** Triangle count at this render, when known. */+ tris?: number;+}+const draftInput = z.object({code: z.string()@@ -447,7 +463,14 @@ const draftInput = z.object({* every draft/edit (so an un-finalized run still captures the work). `kiln_edit`* failures point at `kiln_draft` as the always-reliable rewrite escape hatch.*/-export function makeKilnUnifiedTools(opts: { seedCode?: string; sink: UnifiedSink }): Tool[] {+export function makeKilnUnifiedTools(opts: {+ seedCode?: string;+ sink: UnifiedSink;+ /** Best-effort sink for live render candidates (one per successful kiln_render).+ * Lets the host surface a filmstrip of intermediate renders + pick a version.+ * Never affects the agent's view; sink errors are swallowed. */+ onCandidate?: (c: KilnRenderCandidate) => void;+}): Tool[] {const buffer = new KilnDraftBuffer(opts.seedCode ?? '');opts.sink.edits = buffer.edits; // share the live trace@@ -512,8 +535,23 @@ export function makeKilnUnifiedTools(opts: { seedCode?: string; sink: UnifiedSinname: 'kiln_render',description: kilnRenderViewsDef.description + ' Operates on your current working buffer (no argument).',inputSchema: viewInput,- callback: async () =>- toCallbackResult(kilnRenderViewsDef, await kilnRenderViewsDef.run({ code: buffer.code })),+ callback: async () => {+ const out = await kilnRenderViewsDef.run({ code: buffer.code });+ // Out-of-band: surface a SUCCESSFUL render as a live candidate (the working+ // buffer + the six-view image the agent just saw). Best-effort; a build+ // failure is image-free and not a candidate. Never changes the agent's view.+ if (opts.onCandidate) {+ const o = out as { ok?: boolean; pngBase64?: string; tris?: number };+ if (o.ok && o.pngBase64) {+ try {+ opts.onCandidate({ code: buffer.code, pngBase64: o.pngBase64, ...(o.tris != null ? { tris: o.tris } : {}) });+ } catch {+ // candidate sink is best-effort+ }+ }+ }+ return toCallbackResult(kilnRenderViewsDef, out);+ },});// Buffer-aware motion view: after drafting/editing an animated character, SEE adiff --git a/index.ts b/index.tsindex 2ceda15d..3caa39da 100644--- a/index.ts+++ b/index.ts@@ -95,6 +95,10 @@ export {beamBetween,createLadder,snapTo,+ room,+ wallWithOpening,+ createRoofPlanes,+ createStairs,foliageCardGeo,crossedQuadsGeo,octaGridPlane,@@ -284,7 +288,7 @@ export {export interface KilnGenerateOptions {/** Spike supports glb only. Ignored if set otherwise. */mode?: 'glb';- category?: 'character' | 'prop' | 'vfx' | 'environment';+ category?: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture';style?: 'low-poly' | 'stylized' | 'voxel' | 'detailed' | 'realistic';referenceImageUrl?: string;/**diff --git a/list-primitives.ts b/list-primitives.tsindex 4bd292ec..a288c02f 100644--- a/list-primitives.ts+++ b/list-primitives.ts@@ -121,6 +121,54 @@ const PRIMITIVES: PrimitiveSpec[] = [example:"createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4, rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });",},+ {+ name: 'room',+ signature:+ "room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",+ returns: '{ root: Object3D, walls: { front, back, left, right }, floor: Object3D | null }',+ category: 'structure',+ description:+ 'Builds a HOLLOW, enterable room: four thin walls + a floor, human-scaled (defaults: 2.8m ceiling, a centered 1.1x2.1m front door so it is enterable by default). `front` faces +X; the floor sits on the ground. The keystone of an architecture asset — add a roof with createRoofPlanes and fixtures as separate parts.',+ example:+ "const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings: [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });",+ promptNotes:+ 'Use for any building the player enters. Do NOT model a building as a solid block — room() guarantees real interior space and a doorway gap. Pass openings to add windows / side doors.',+ },+ {+ name: 'wallWithOpening',+ signature:+ "wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, parent? })",+ returns: 'THREE.Object3D (wall container)',+ category: 'structure',+ description:+ 'A single wall panel with an optional real door/window cut, composed from solid box segments (side panels + lintel + window sill) — no CSG. Base at local Y=0, centered on the run axis. Use to compose custom building layouts or interior dividing walls beyond the default room().',+ example:+ "wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis: 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });",+ },+ {+ name: 'createRoofPlanes',+ signature:+ "createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",+ returns: '{ root: Object3D, slopes: [Object3D, Object3D] }',+ category: 'structure',+ description:+ 'A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite tilts — never mirrored the same way), footprint-matched with an eave overhang. Eave at local Y=0, ridge at Y=height, so position the group at Y=wallHeight. Returns a named group (e.g. `Roof`) the engine can lift to reveal the interior.',+ example:+ "const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height: 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root });\nroof.position.y = 2.8;",+ promptNotes:+ 'The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Drop it onto the walls (position.y = wall height).',+ },+ {+ name: 'createStairs',+ signature:+ "createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })",+ returns: '{ root: Object3D, steps: Object3D[] }',+ category: 'structure',+ description:+ 'A straight flight of stairs: box treads (with optional risers) climbing totalRise over totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in a multi-storey building.',+ example:+ "createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4, axis: 'x', parent: root });",+ },// ---------------------------------------------------------------------------// Geometrydiff --git a/primitives.ts b/primitives.tsindex ebfb5f3c..3d2aa09d 100644--- a/primitives.ts+++ b/primitives.ts@@ -743,6 +743,331 @@ export function createLadder(return { leftRail, rightRail, rungs };}+// =============================================================================+// Building / architecture helpers+// =============================================================================+//+// Enterable buildings are HOLLOW shells: thin walls around real interior space,+// real doorway gaps, a separable roof. These helpers make that correct-by-+// construction so the agent cannot accidentally fill the volume, forget the+// doorway, or mirror the roof slopes the wrong way. Openings are composed from+// box segments (jambs + lintel + sill), never CSG — solid opaque overlaps are+// robust where thin boolean cutters are fragile.++export interface WallOpening {+ /** 'door' reaches the floor; 'window' is inset at `sill` height. */+ kind?: 'door' | 'window';+ /** Center of the opening along the wall length axis (0 = centered). */+ offset?: number;+ /** Opening width along the wall length axis. */+ width?: number;+ /** Opening height. */+ height?: number;+ /** Window sill height above the wall base (ignored for doors). */+ sill?: number;+}++export interface WallWithOpeningOptions {+ /** Wall length along its run axis. */+ length: number;+ /** Wall height (Y). Base sits at local Y=0. */+ height: number;+ /** Wall thickness along the perpendicular horizontal axis. */+ thickness: number;+ /** Which horizontal axis the wall runs along. Default 'z'. */+ axis?: 'x' | 'z';+ /** A single door/window cut. Omit for a solid wall. */+ opening?: WallOpening;+ parent?: THREE.Object3D;+}++/**+ * A single wall panel — optionally with one rectangular door/window cut —+ * composed from solid box segments (two side panels + a lintel, plus a sill+ * apron for a window). Runs along `axis`, base at local Y=0, centered on the+ * length axis. Returns the wall container so the caller can position it.+ */+export function wallWithOpening(+ name: string,+ material: THREE.Material,+ options: WallWithOpeningOptions,+): THREE.Object3D {+ const { length, height, thickness, axis = 'z', opening, parent } = options;+ const group = new THREE.Object3D();+ group.name = name;+ const overlap = 0.02;++ const panel = (+ suffix: string,+ lenStart: number,+ lenEnd: number,+ yLo: number,+ yHi: number,+ ): void => {+ const segLen = lenEnd - lenStart;+ const segH = yHi - yLo;+ if (segLen <= 1e-4 || segH <= 1e-4) return;+ const lenC = (lenStart + lenEnd) / 2;+ const yC = (yLo + yHi) / 2;+ const geo = axis === 'z' ? boxGeo(thickness, segH, segLen) : boxGeo(segLen, segH, thickness);+ const pos: [number, number, number] = axis === 'z' ? [0, yC, lenC] : [lenC, yC, 0];+ createPart(`${name}${suffix}`, geo, material, { position: pos, parent: group });+ };++ if (!opening) {+ panel('', -length / 2, length / 2, 0, height);+ } else {+ const ow = opening.width ?? (opening.kind === 'window' ? 1.0 : 1.1);+ const oh = opening.height ?? (opening.kind === 'window' ? 1.0 : 2.1);+ const off = opening.offset ?? 0;+ const left = off - ow / 2;+ const right = off + ow / 2;+ const sill = opening.kind === 'window' ? Math.max(opening.sill ?? 1.0, 0) : 0;+ const top = Math.min(sill + oh, height);+ panel('_L', -length / 2, left, 0, height); // full-height side panels+ panel('_R', right, length / 2, 0, height);+ panel('_Lintel', left - overlap, right + overlap, top, height); // above the gap+ if (sill > 0) panel('_Sill', left - overlap, right + overlap, 0, sill); // below a window+ }++ if (parent) parent.add(group);+ return group;+}++export interface RoomOpening extends WallOpening {+ /** Which wall the opening cuts. `front` faces +X. */+ wall: 'front' | 'back' | 'left' | 'right';+}++export interface RoomOptions {+ /** Side-to-side extent along Z. */+ width?: number;+ /** Front-to-back extent along X (front faces +X). */+ depth?: number;+ /** Wall height (Y). */+ height?: number;+ wallThickness?: number;+ /** Lay a floor slab. Default true. */+ floor?: boolean;+ floorThickness?: number;+ /** Per-wall openings. Defaults to a centered door on the front wall, so the+ * room is ENTERABLE by default. */+ openings?: RoomOpening[];+ parent?: THREE.Object3D;+}++/**+ * A hollow, enterable room: four thin walls + a floor, sized so a humanoid fits+ * (defaults: 2.8m ceiling, a centered 1.1×2.1m front door). The keystone of an+ * architecture asset — the agent builds onto/around it (roof via+ * {@link createRoofPlanes}, fixtures as separate parts) but cannot ship a solid+ * block or a sealed box. `front` faces +X; the floor top sits at the ground.+ */+export function room(+ name: string,+ material: THREE.Material,+ options: RoomOptions = {},+): { root: THREE.Object3D; walls: Record<'front' | 'back' | 'left' | 'right', THREE.Object3D>; floor: THREE.Object3D | null } {+ const {+ width = 4,+ depth = 4,+ height = 2.8,+ wallThickness = 0.15,+ floor = true,+ floorThickness = 0.1,+ parent,+ } = options;+ const openings = options.openings ?? [{ wall: 'front', kind: 'door' }];+ const root = new THREE.Object3D();+ root.name = name;++ const openingFor = (wall: RoomOpening['wall']): WallOpening | undefined => {+ const found = openings.find((op) => op.wall === wall);+ if (!found) return undefined;+ const { wall: _wall, ...rest } = found;+ return rest;+ };++ const wall = (+ suffix: string,+ len: number,+ axis: 'x' | 'z',+ pos: [number, number, number],+ which: RoomOpening['wall'],+ ): THREE.Object3D => {+ const op = openingFor(which);+ const w = wallWithOpening(`${name}_Wall${suffix}`, material, {+ length: len,+ height,+ thickness: wallThickness,+ axis,+ ...(op ? { opening: op } : {}),+ parent: root,+ });+ w.position.set(...pos);+ return w;+ };++ const walls = {+ front: wall('Front', width, 'z', [depth / 2, 0, 0], 'front'),+ back: wall('Back', width, 'z', [-depth / 2, 0, 0], 'back'),+ left: wall('Left', depth, 'x', [0, 0, -width / 2], 'left'),+ right: wall('Right', depth, 'x', [0, 0, width / 2], 'right'),+ };++ let floorObj: THREE.Object3D | null = null;+ if (floor) {+ floorObj = createPart(`${name}_Floor`, boxGeo(depth, floorThickness, width), material, {+ position: [0, floorThickness / 2, 0],+ parent: root,+ });+ }++ if (parent) parent.add(root);+ return { root, walls, floor: floorObj };+}++export interface RoofPlanesOptions {+ /** Footprint extent along Z. */+ width: number;+ /** Footprint extent along X. */+ depth: number;+ /** Ridge height above the eave (local Y=0). */+ height: number;+ /** Eave overhang past the footprint on every side. Default 0.3. */+ overhang?: number;+ /** Axis the ridge line runs along; slopes fall toward the perpendicular+ * horizontal axis. Default 'x'. */+ ridgeAxis?: 'x' | 'z';+ /** Roof-plane thickness. Default 0.08. */+ thickness?: number;+ parent?: THREE.Object3D;+}++/**+ * A pitched roof: two thin sloped planes meeting at one ridge and falling+ * DOWN-AND-OUTWARD (opposite tilts — the cure for the recurring mirrored-slope+ * defect), footprint-matched with an eave overhang. Built with the eave at+ * local Y=0 and the ridge at Y=`height`, so the caller drops it onto the walls+ * at Y=wallHeight. Returns a named group (e.g. `Roof`) the engine can lift to+ * reveal the interior.+ */+export function createRoofPlanes(+ name: string,+ material: THREE.Material,+ options: RoofPlanesOptions,+): { root: THREE.Object3D; slopes: [THREE.Object3D, THREE.Object3D] } {+ const { width, depth, height, overhang = 0.3, ridgeAxis = 'x', thickness = 0.08, parent } = options;+ const group = new THREE.Object3D();+ group.name = name;++ // Half-span of the slope direction (perpendicular to the ridge) + overhang,+ // and the ridge-direction length.+ const halfSpan = (ridgeAxis === 'x' ? width : depth) / 2 + overhang;+ const ridgeLen = (ridgeAxis === 'x' ? depth : width) + overhang * 2;+ const rafterLen = Math.hypot(halfSpan, height);+ const angle = Math.atan2(height, halfSpan);++ const slopes: THREE.Object3D[] = [];+ for (const side of [1, -1] as const) {+ const geo =+ ridgeAxis === 'x' ? boxGeo(ridgeLen, thickness, rafterLen) : boxGeo(rafterLen, thickness, ridgeLen);+ const mesh = new THREE.Mesh(geo, material);+ mesh.name = `Mesh_${name}${side > 0 ? 'A' : 'B'}`;+ if (ridgeAxis === 'x') {+ // Ridge along X; slopes drop toward +Z (side=+1) / -Z (side=-1).+ mesh.position.set(0, height / 2, (side * halfSpan) / 2);+ mesh.rotation.x = side * angle;+ } else {+ // Ridge along Z; slopes drop toward +X (side=+1) / -X (side=-1).+ mesh.position.set((side * halfSpan) / 2, height / 2, 0);+ mesh.rotation.z = -side * angle;+ }+ group.add(mesh);+ slopes.push(mesh);+ }++ if (parent) parent.add(group);+ return { root: group, slopes: [slopes[0]!, slopes[1]!] };+}++export interface StairsOptions {+ /** Number of steps. Default 8. */+ steps?: number;+ /** Total vertical climb. */+ totalRise: number;+ /** Total horizontal run along `axis`. */+ totalRun: number;+ /** Tread width along the perpendicular horizontal axis. */+ width: number;+ /** Direction the flight climbs toward. Default 'x'. */+ axis?: 'x' | 'z';+ treadThickness?: number;+ /** Add a vertical riser face under each tread. Default true. */+ riser?: boolean;+ parent?: THREE.Object3D;+}++/**+ * A straight flight of stairs: box treads (with optional risers) climbing+ * `totalRise` over `totalRun` from local origin toward +`axis`. Connects storeys+ * (the multi-storey toggle) or makes porch/entry steps. Steps are named+ * `Step_1..N` for engine use.+ */+export function createStairs(+ name: string,+ material: THREE.Material,+ options: StairsOptions,+): { root: THREE.Object3D; steps: THREE.Object3D[] } {+ const {+ steps = 8,+ totalRise,+ totalRun,+ width,+ axis = 'x',+ treadThickness = 0.08,+ riser = true,+ parent,+ } = options;+ if (steps < 1) {+ throw new Error(`createStairs("${name}"): steps must be >= 1 (got ${steps}).`);+ }+ if (Math.abs(totalRise) < 1e-4 || Math.abs(totalRun) < 1e-4) {+ throw new Error(+ `createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`,+ );+ }+ const root = new THREE.Object3D();+ root.name = name;+ const stepRise = totalRise / steps;+ const stepRun = totalRun / steps;+ const stepList: THREE.Object3D[] = [];++ for (let i = 0; i < steps; i++) {+ const topY = (i + 1) * stepRise;+ const alongC = (i + 0.5) * stepRun;+ const treadGeo =+ axis === 'x' ? boxGeo(stepRun, treadThickness, width) : boxGeo(width, treadThickness, stepRun);+ const treadPos: [number, number, number] =+ axis === 'x' ? [alongC, topY - treadThickness / 2, 0] : [0, topY - treadThickness / 2, alongC];+ stepList.push(createPart(`${name}Step${i + 1}`, treadGeo, material, { position: treadPos, parent: root }));++ if (riser) {+ const front = i * stepRun;+ const riserGeo =+ axis === 'x' ? boxGeo(treadThickness, stepRise, width) : boxGeo(width, stepRise, treadThickness);+ const riserPos: [number, number, number] =+ axis === 'x'+ ? [front + treadThickness / 2, topY - stepRise / 2, 0]+ : [0, topY - stepRise / 2, front + treadThickness / 2];+ createPart(`${name}Riser${i + 1}`, riserGeo, material, { position: riserPos, parent: root });+ }+ }++ if (parent) parent.add(root);+ return { root, steps: stepList };+}+// =============================================================================// Materials// =============================================================================@@ -1079,7 +1404,7 @@ export function getJointNames(root: THREE.Object3D): string[] {*/export function validateAsset(root: THREE.Object3D,- category: 'character' | 'prop' | 'vfx' | 'environment'+ category: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture'): { valid: boolean; errors: string[]; warnings: string[] } {const errors: string[] = [];const warnings: string[] = [];@@ -1089,6 +1414,7 @@ export function validateAsset(prop: { suggestedTris: 3000, suggestedMats: 6 },vfx: { suggestedTris: 2000, suggestedMats: 4 },environment: { suggestedTris: 15000, suggestedMats: 12 },+ architecture: { suggestedTris: 15000, suggestedMats: 12 },};const limits = guidelines[category];@@ -1237,6 +1563,10 @@ export function buildSandboxGlobals(beamBetween: wrap('beamBetween', beamBetween),createLadder: wrap('createLadder', createLadder),snapTo: wrap('snapTo', snapTo),+ room: wrap('room', room),+ wallWithOpening: wrap('wallWithOpening', wallWithOpening),+ createRoofPlanes: wrap('createRoofPlanes', createRoofPlanes),+ createStairs: wrap('createStairs', createStairs),gameMaterial: wrap('gameMaterial', gameMaterial),basicMaterial: wrap('basicMaterial', basicMaterial),glassMaterial: wrap('glassMaterial', glassMaterial),diff --git a/prompt.ts b/prompt.tsindex 42430c77..e1164d9d 100644--- a/prompt.ts+++ b/prompt.ts@@ -19,7 +19,7 @@ import { listPrimitives } from './list-primitives';import { renderApiSection } from './prompt-api';export type RenderMode = 'glb' | 'tsl' | 'both';-export type AssetCategory = 'character' | 'prop' | 'vfx' | 'environment';+export type AssetCategory = 'character' | 'prop' | 'vfx' | 'environment' | 'architecture';export type AssetStyle = 'low-poly' | 'stylized' | 'voxel' | 'detailed' | 'realistic';// =============================================================================@@ -792,6 +792,47 @@ export interface KilnGenerateRequest {exemplarCode?: string;}+/**+ * Category-gated guidance appended to the user prompt on fresh generation.+ * Parallel to Kiln Studio's `composeAgentPrompt` (which carries `character`),+ * but core-owned so it reaches EVERY consumer — CLI, batch/TIJ, bench, editor,+ * AND the deployed agent runtime (category already crosses the AgentCore wire).+ * Keep the two maps disjoint by category so a directive is injected exactly+ * once: studio owns `character`; core owns `architecture`.+ */+export const ARCHITECTURE_CONTEXT =+ 'This is a BUILDING the player can go INSIDE. Build it HOLLOW: thin walls enclosing real ' ++ 'interior space with a floor — never a solid block. Its foundation rests flat on the ground, ' ++ 'and the main entrance faces forward so the front reads clearly.\n\n' ++ 'Give it true human architectural scale: a doorway tall and wide enough for a person to walk ' ++ 'through, windows at standing height, and a ceiling high enough to stand under with headroom. ' ++ "The building's mass should dwarf a single doorway.\n\n" ++ 'Cut REAL openings into the walls — a doorway is an actual gap you could pass through, not a ' ++ 'panel painted on a wall; windows are inset panes or holes flush with the wall surface. Never ' ++ 'float a pane in front of a wall or bury glass inside a solid block, and never seal the entrance.\n\n' ++ 'Walls meet squarely at the corners with no gaps; give large coplanar surfaces a hair of ' ++ 'separation so they do not flicker. Cap it with a roof that matches the footprint and overhangs ' ++ "slightly at the eaves; a pitched roof's two sides slope DOWN-AND-OUTWARD from one ridge line — " ++ 'they fall away from each other, never tilt the same way. Name the roof as its own part so the ' ++ 'engine can lift it to reveal the inside.\n\n' ++ 'Spend detail where a building reads: the roofline and eaves, a framed door, window sills or ' ++ 'mullions, a chimney, a porch or entry overhang, a foundation course, corner posts, trim — and ' ++ 'built-in fixtures (a hearth, a counter, shelving). Leave the floor space open for furniture to ' ++ 'be placed later.\n\n' ++ 'Use room(...) to build the hollow walled-and-floored shell with its doorway, wallWithOpening(...) ' ++ 'for extra doors or windows, and createRoofPlanes(...) for the pitched roof; createStairs(...) ' ++ 'makes porch steps or connects floors.';++/**+ * Per-category context appended to fresh-generation prompts by+ * {@link buildUserPrompt}. Intentionally sparse: only categories whose guidance+ * is owned by core live here (today just `architecture`, because its primitives+ * are core helpers). `character` deliberately stays studio-side.+ */+export const CATEGORY_CONTEXT: Partial<Record<AssetCategory, string>> = {+ architecture: ARCHITECTURE_CONTEXT,+};+export function buildUserPrompt(request: KilnGenerateRequest): string {const parts: string[] = [];@@ -833,6 +874,11 @@ export function buildUserPrompt(request: KilnGenerateRequest): string {parts.push(editSections.join('\n\n'));} else {parts.push(`## Task\n\nCreate a ${request.category}: ${request.prompt}`);+ // Category-gated guidance (fresh generation only). Studio injects character+ // context into the prompt string before the wire; core injects the rest here+ // so every consumer — including the deployed runtime — gets it once.+ const categoryContext = CATEGORY_CONTEXT[request.category];+ if (categoryContext) parts.push(`\n${categoryContext}`);}// Animation instructions — only for fresh generation. When editing existing code