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(composer): scene composer engine surface + verbatim placeExact import
Matt Kissinger53dcb3a49dfc
diff --git a/package.json b/package.jsonindex ac0c8a8f..3081c677 100644--- a/package.json+++ b/package.json@@ -18,7 +18,9 @@"./prompt-api": "./src/prompt-api.ts","./list-primitives": "./src/list-primitives.ts","./metrics": "./src/metrics.ts",- "./inspect": "./src/inspect.ts"+ "./inspect": "./src/inspect.ts",+ "./composer": "./src/composer/index.ts",+ "./composer/agent": "./src/composer/agent/index.ts"},"files": ["src/**/*.ts",diff --git a/src/__tests__/composer-agent-tools.test.ts b/src/__tests__/composer-agent-tools.test.tsnew file mode 100644index 00000000..68a613d3--- /dev/null+++ b/src/__tests__/composer-agent-tools.test.ts@@ -0,0 +1,267 @@+/**+ * Composer agent tools — the scene_* surface driven directly (no live model).+ *+ * Each Strands tool is an InvokableTool, so `.invoke(input)` runs its callback in+ * isolation. We assert the model mutates, the sink autosaves the serialized+ * program + evaluated scene, overlaps are surfaced (never dropped), and the two+ * image tools call the injected render port and return content blocks.+ */+import { describe, expect, test } from 'bun:test';+import type { Tool } from '@strands-agents/sdk';++import {+ type CatalogEntry,+ PlacementModel,+ type SceneRenderPort,+ type SceneRenderRequest,+} from '../composer';+import {+ type ComposerSink,+ makeSceneComposerTools,+ type SceneRenderCandidate,+} from '../composer/agent';++const asset = (id: string, w = 2, h = 3, d = 2): CatalogEntry => ({+ generationId: id,+ bbox: { min: [-w / 2, 0, -d / 2], max: [w / 2, h, d / 2] },+ name: id,+});++const PNG_B64 = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]).toString('base64');++function setup() {+ const model = new PlacementModel('Test', {+ seed: 7,+ catalog: [asset('well', 3, 4, 3), asset('crate', 1, 1, 1), asset('column', 1, 5, 1)],+ });+ const sink: ComposerSink = {};+ const candidates: SceneRenderCandidate[] = [];+ const calls: SceneRenderRequest[] = [];+ const render: SceneRenderPort = async (req) => {+ calls.push(req);+ return { ok: true, pngBase64: PNG_B64, tris: 123 };+ };+ const tools = makeSceneComposerTools({+ model,+ render,+ sink,+ onCandidate: (c) => candidates.push(c),+ });+ return { model, sink, candidates, calls, tools };+}++// biome-ignore lint/suspicious/noExplicitAny: tool returns are intentionally untyped here+type AnyResult = any;+interface Invokable {+ name: string;+ invoke: (input: unknown) => Promise<AnyResult>;+}+function call(tools: Tool[], name: string, input: unknown = {}): Promise<AnyResult> {+ const t = tools.find((x) => x.name === name) as unknown as Invokable | undefined;+ if (!t) throw new Error(`no tool "${name}"`);+ return t.invoke(input);+}++describe('surface', () => {+ test('exposes the 14 scene_* tools by name', () => {+ const { tools } = setup();+ const names = tools.map((t) => t.name).sort();+ expect(names).toEqual(+ [+ 'scene_list_assets',+ 'scene_view',+ 'scene_validate',+ 'scene_render',+ 'scene_screenshot_camera',+ 'scene_layout',+ 'scene_place',+ 'scene_cluster',+ 'scene_ring',+ 'scene_move',+ 'scene_face',+ 'scene_group',+ 'scene_remove',+ 'scene_finalize',+ ].sort(),+ );+ });+});++describe('read tools', () => {+ test('scene_list_assets returns the catalog with footprint sizes', async () => {+ const { tools } = setup();+ const r = await call(tools, 'scene_list_assets');+ expect(r.assets).toHaveLength(3);+ expect(r.assets.map((a: { generationId: string }) => a.generationId)).toContain('well');+ expect(r.assets[0].size).toHaveLength(3);+ });++ test('scene_view reflects the current program + counts', async () => {+ const { tools } = setup();+ await call(tools, 'scene_place', { asset: 'well', at: [0, 0], face: 'center', role: 'hero' });+ const r = await call(tools, 'scene_view');+ expect(r.program).toContain('s.place(');+ expect(r.placementCount).toBe(1);+ expect(r.overlapCount).toBe(0);+ expect(r.aliases).toContain('well');+ });+});++describe('place / cluster / ring mutate + autosave', () => {+ test('scene_place places one asset and autosaves the program', async () => {+ const { tools, sink } = setup();+ const r = await call(tools, 'scene_place', { asset: 'well', at: [10, -5], face: 'center' });+ expect(r.ok).toBe(true);+ expect(r.placements).toBe(1);+ expect(r.overlaps).toBe(0);+ expect(sink.program).toContain('s.place(');+ expect(sink.placements).toHaveLength(1);+ });++ test('scene_place with an unknown asset returns an in-band error + hint', async () => {+ const { tools } = setup();+ const r = await call(tools, 'scene_place', { asset: 'nope', at: [0, 0] });+ expect(r.ok).toBe(false);+ expect(r.hint).toContain('scene_list_assets');+ });++ test('scene_cluster scatters N overlap-free and serializes as one line', async () => {+ const { tools, sink } = setup();+ const r = await call(tools, 'scene_cluster', {+ asset: 'crate',+ around: [20, 0],+ count: 8,+ spread: 14,+ });+ expect(r.ok).toBe(true);+ expect(r.placements).toBe(8);+ expect(r.overlaps).toBe(0);+ expect(sink.program?.split('\n').filter((l) => l.includes('s.cluster('))).toHaveLength(1);+ });++ test('scene_ring places N on a circle, overlap-free', async () => {+ const { tools } = setup();+ const r = await call(tools, 'scene_ring', {+ asset: 'column',+ center: [0, 0],+ count: 8,+ radius: 16,+ faceOut: false,+ });+ expect(r.placements).toBe(8);+ expect(r.overlaps).toBe(0);+ });+});++describe('layout baseline', () => {+ test('scene_layout lays out the whole catalog overlap-free, returns aliases', async () => {+ const { tools } = setup();+ const r = await call(tools, 'scene_layout', { anchor: 'single' });+ expect(r.ok).toBe(true);+ expect(Array.isArray(r.alias)).toBe(true);+ expect(r.alias).toHaveLength(3);+ expect(r.overlaps).toBe(0);+ });+});++describe('edit ops + overlap surfacing', () => {+ test('an overlap is surfaced on mutation and via scene_validate, and scene_move resolves it', async () => {+ const { tools } = setup();+ await call(tools, 'scene_place', { asset: 'well', at: [0, 0], alias: 'w' });+ const collide = await call(tools, 'scene_place', { asset: 'crate', at: [0, 0], alias: 'c' });+ expect(collide.overlaps).toBeGreaterThan(0);+ expect(collide.hint).toContain('scene_validate');++ const v = await call(tools, 'scene_validate');+ expect(v.ok).toBe(false);+ expect(v.count).toBeGreaterThan(0);+ expect(v.overlaps[0].separation).toHaveLength(3);++ const moved = await call(tools, 'scene_move', { target: 'c', to: [60, 60] });+ expect(moved.ok).toBe(true);+ expect(moved.overlaps).toBe(0);+ });++ test('scene_face re-orients, scene_remove drops, scene_group binds + moves together', async () => {+ const { tools } = setup();+ await call(tools, 'scene_place', { asset: 'crate', at: [0, 0], alias: 'a' });+ await call(tools, 'scene_place', { asset: 'crate', at: [4, 0], alias: 'b' });++ const faced = await call(tools, 'scene_face', { target: 'a', face: 90 });+ expect(faced.ok).toBe(true);++ const grouped = await call(tools, 'scene_group', {+ targets: ['a', 'b'],+ name: 'pile',+ delta: [10, 0],+ });+ expect(grouped.ok).toBe(true);+ expect(grouped.members).toEqual(['a', 'b']);++ const removed = await call(tools, 'scene_remove', { target: 'b' });+ expect(removed.ok).toBe(true);+ expect(removed.placements).toBe(1);+ });++ test('an edit op on a missing target returns ok:false', async () => {+ const { tools } = setup();+ const r = await call(tools, 'scene_move', { target: 'ghost', delta: [1, 0] });+ expect(r.ok).toBe(false);+ });+});++describe('render tools call the port and return content blocks', () => {+ test('scene_render renders the whole scene, emits a candidate, returns [image, json]', async () => {+ const { tools, calls, candidates } = setup();+ await call(tools, 'scene_place', { asset: 'well', at: [0, 0] });+ const r = await call(tools, 'scene_render');+ expect(Array.isArray(r)).toBe(true);+ expect(r).toHaveLength(2); // 1 ImageBlock + 1 JsonBlock+ expect(calls).toHaveLength(1);+ expect(calls[0]!.placements).toHaveLength(1);+ expect(calls[0]!.cameras).toBeUndefined(); // 3 canonical angles = host default+ expect(candidates).toHaveLength(1);+ expect(candidates[0]!.pngBase64).toBe(PNG_B64);+ expect(candidates[0]!.program).toContain('s.place(');+ });++ test('scene_screenshot_camera passes the requested camera through', async () => {+ const { tools, calls } = setup();+ await call(tools, 'scene_place', { asset: 'well', at: [0, 0] });+ const r = await call(tools, 'scene_screenshot_camera', {+ position: [30, 20, 30],+ target: [0, 0, 0],+ fovDeg: 45,+ });+ expect(Array.isArray(r)).toBe(true);+ expect(calls[0]!.cameras).toHaveLength(1);+ expect(calls[0]!.cameras![0]).toEqual({+ position: [30, 20, 30],+ target: [0, 0, 0],+ fovDeg: 45,+ });+ });++ test('a render failure returns an in-band ok:false (no image)', async () => {+ const model = new PlacementModel('T', { catalog: [asset('well')] });+ const sink: ComposerSink = {};+ const render: SceneRenderPort = async () => ({ ok: false, error: 'boom' });+ const tools = makeSceneComposerTools({ model, render, sink });+ await call(tools, 'scene_place', { asset: 'well', at: [0, 0] });+ const r = await call(tools, 'scene_render');+ expect(Array.isArray(r)).toBe(false);+ expect(r.ok).toBe(false);+ expect(r.error).toBe('boom');+ });+});++describe('finalize', () => {+ test('scene_finalize flips the sink + returns the final program', async () => {+ const { tools, sink } = setup();+ await call(tools, 'scene_place', { asset: 'well', at: [0, 0], role: 'hero' });+ const r = await call(tools, 'scene_finalize');+ expect(r.ok).toBe(true);+ expect(r.program).toContain('export default s;');+ expect(sink.finalized).toBe(true);+ });+});diff --git a/src/__tests__/composer-dsl.test.ts b/src/__tests__/composer-dsl.test.tsnew file mode 100644index 00000000..5f2e91b6--- /dev/null+++ b/src/__tests__/composer-dsl.test.ts@@ -0,0 +1,76 @@+/**+ * Composer DSL tests — the scene() / asset() builder and serialize() projection.+ *+ * The builder composes the same model the tools drive; serialize() emits a clean,+ * deterministic, asset-by-generationId program where cluster/ring stay one line.+ */+import { describe, expect, test } from 'bun:test';++import { asset, scene } from '../composer';++describe('scene builder', () => {+ test('composes a model whose placements are correct and overlap-free', () => {+ const well = asset('stone_well', 'gen_e5', { min: [-1.5, 0, -1.5], max: [1.5, 4, 1.5] });+ const crate = asset('crate', 'gen_g7', { min: [-0.6, 0, -0.6], max: [0.6, 0.6, 0.6] });+ const r = scene('Market', { seed: 7 })+ .place(well, { at: [0, 0], face: 'center', role: 'hero' })+ .cluster(crate, { around: [15, -10], count: 8, spread: 12 })+ .placements();+ expect(r.placements).toHaveLength(9); // 1 hero + 8 scattered+ expect(r.overlaps).toHaveLength(0);+ });+});++describe('serialize', () => {+ test('emits a clean, deterministic program referencing assets by generationId', () => {+ const well = asset('stone_well', 'gen_e5', { min: [-1.5, 0, -1.5], max: [1.5, 4, 1.5] });+ const s = scene('Market', { seed: 7 }).place(well, {+ at: [0, 0],+ face: 'center',+ role: 'hero',+ alias: 'well',+ });+ const prog = s.serialize();+ expect(prog).toContain('const s = scene("Market", { ground: flat(), seed: 7 });');+ expect(prog).toContain(+ 'const stone_well = asset("stone_well", "gen_e5", { min: [-1.5, 0, -1.5], max: [1.5, 4, 1.5] });',+ );+ expect(prog).toContain('s.place(stone_well, {');+ expect(prog).toContain('face: "center"');+ expect(prog).toContain('role: "hero"');+ expect(prog).toContain('alias: "well"');+ expect(prog).toContain('export default s;');+ expect(s.serialize()).toBe(prog); // deterministic+ });++ test('cluster and ring each serialize as a single sugar line', () => {+ const lantern = asset('lantern', 'gen_c3', { min: [-0.3, 0, -0.3], max: [0.3, 0.9, 0.3] });+ const crate = asset('crate', 'gen_g7', { min: [-0.6, 0, -0.6], max: [0.6, 0.6, 0.6] });+ const prog = scene('S')+ .ring(lantern, { center: [0, 0], count: 8, radius: 18, faceOut: true })+ .cluster(crate, { around: [10, 0], count: 12, spread: 14 })+ .serialize();+ const lines = prog.split('\n');+ expect(lines.filter((l) => l.includes('s.ring('))).toHaveLength(1);+ expect(lines.filter((l) => l.includes('s.cluster('))).toHaveLength(1);+ expect(prog).toContain('faceOut: true');+ });++ test('placeExact serializes as a verbatim line that re-evaluates to the exact pose', () => {+ const crate = asset('crate', 'gen_g7', { min: [-0.6, 0, -0.6], max: [0.6, 0.6, 0.6] });+ const s = scene('Imported').placeExact(crate, {+ pos: [12.5, 0, -7.25],+ rotYDeg: 90,+ alias: 'crate_0',+ });+ const prog = s.serialize();+ expect(prog).toContain('s.placeExact(crate, {');+ expect(prog).toContain('pos: [12.5, 0, -7.25]');+ expect(prog).toContain('rotYDeg: 90');+ expect(prog).not.toContain('s.place(crate'); // NOT the grounded form+ // and the model evaluates it verbatim (look-preserving)+ const p = s.placements().placements[0]!;+ expect(p.pos).toEqual([12.5, 0, -7.25]);+ expect(p.rotYDeg).toBe(90);+ });+});diff --git a/src/__tests__/composer-helpers.test.ts b/src/__tests__/composer-helpers.test.tsnew file mode 100644index 00000000..80bc87ec--- /dev/null+++ b/src/__tests__/composer-helpers.test.ts@@ -0,0 +1,41 @@+/**+ * Composer Phase-0 helper exports — the primitives the scene DSL will wrap:+ * facingToRotY (intent -> Y-rotation) and groundedPos (recentre + ground).+ */+import { describe, expect, test } from 'bun:test';++import { facingToRotY, flatGround, groundedPos, heightmap } from '../composer';++describe('facingToRotY', () => {+ test("'center' turns an east asset back toward the scene centre (~180)", () => {+ expect(Math.abs(facingToRotY('center', [95, 0], [0, 0]))).toBeCloseTo(180, 0);+ });++ test("'out' faces away from the scene centre (~0 for an east asset)", () => {+ expect(Math.abs(facingToRotY('out', [95, 0], [0, 0]))).toBeCloseTo(0, 0);+ });++ test('a world point intent faces that point', () => {+ expect(facingToRotY([10, 0], [0, 0], [0, 0])).toBeCloseTo(0, 5); // +X+ });++ test('a number is taken as explicit degrees', () => {+ expect(facingToRotY(45, [10, 10], [0, 0])).toBe(45);+ });+});++describe('groundedPos', () => {+ test('recentres an off-centre bbox so its centre lands on the target', () => {+ // geometry spans [0..10] in XZ (centre at 5,5); place that centre at (20,30).+ const p = groundedPos([0, 0, 0], [10, 4, 10], 1, [20, 30], 0, flatGround(0));+ expect(p[0]).toBeCloseTo(15, 5); // origin = centre - offset(5,5)+ expect(p[2]).toBeCloseTo(25, 5);+ expect(p[1]).toBeCloseTo(0, 5); // base (minY 0) sits on ground 0+ });++ test('drops the base onto a heightmap sampler', () => {+ const g = heightmap({ heightAt: (x) => x * 0.5 });+ const p = groundedPos([-2, 1, -2], [2, 5, 2], 1, [10, 0], 0, g);+ expect(p[1]).toBeCloseTo(10 * 0.5 - 1, 5); // ground(10)=5, minus scaled minY 1+ });+});diff --git a/src/__tests__/composer-layout.test.ts b/src/__tests__/composer-layout.test.tsnew file mode 100644index 00000000..98065cd6--- /dev/null+++ b/src/__tests__/composer-layout.test.ts@@ -0,0 +1,131 @@+/**+ * Composer layout tests — pure geometry, no LLM, no network.+ *+ * Pins the properties that make the layout a flexible, intelligent foundation:+ * overlap-free by construction across anchors, hero centrepieces, intentional+ * facing, terrain grounding via the sampler seam (heightmap-ready), grouping,+ * and full determinism.+ */+import { describe, expect, test } from 'bun:test';++import {+ type GroundSampler,+ type LayoutItem,+ layoutScene,+ worldAabbFromLocal,+ zonedCenters,+} from '../composer';++/** Item centred on its XZ origin, base at y=0, footprint w x d, height h. */+const item = (+ id: string,+ w: number,+ h: number,+ d: number,+ extra: Partial<LayoutItem> = {},+): LayoutItem => ({+ id,+ localMin: [-w / 2, 0, -d / 2],+ localMax: [w / 2, h, d / 2],+ ...extra,+});++function worldCenter(+ localMin: [number, number, number],+ localMax: [number, number, number],+ pos: [number, number, number],+ rotYDeg: number,+ scale: number,+): [number, number, number] {+ const b = worldAabbFromLocal(localMin, localMax, pos, rotYDeg, scale);+ return [(b.min[0] + b.max[0]) / 2, (b.min[1] + b.max[1]) / 2, (b.min[2] + b.max[2]) / 2];+}++describe('layout is overlap-free across anchors', () => {+ test('a full 5-zone scene (heroes + support + fill) has zero overlaps', () => {+ const items: LayoutItem[] = [];+ for (const z of ['hub', 'north', 'east', 'south', 'west']) {+ items.push(item(`${z}-hero`, 12, 20, 12, { role: 'hero', zone: z }));+ for (let i = 0; i < 3; i++)+ items.push(item(`${z}-sup${i}`, 6, 8, 6, { role: 'support', zone: z }));+ for (let i = 0; i < 5; i++)+ items.push(item(`${z}-fill${i}`, 2, 2, 2, { role: 'fill', zone: z, group: `${z}-hero` }));+ }+ const res = layoutScene(items, { anchors: zonedCenters(95) });+ expect(res.placements).toHaveLength(items.length);+ expect(res.overlaps).toHaveLength(0);+ });++ test('with no anchors (single root) it still packs overlap-free', () => {+ const items = Array.from({ length: 24 }, (_, i) => item(`p${i}`, 3 + (i % 4), 5, 3 + (i % 3)));+ expect(layoutScene(items).overlaps).toHaveLength(0);+ });+});++describe('hierarchy + facing + grouping', () => {+ test("a zone's hero anchors its centre", () => {+ const items: LayoutItem[] = [+ item('east-hero', 12, 20, 12, { role: 'hero', zone: 'east' }),+ item('east-sup', 6, 8, 6, { role: 'support', zone: 'east' }),+ ];+ const res = layoutScene(items, { anchors: zonedCenters(95) });+ const hero = res.placements.find((p) => p.id === 'east-hero')!;+ const c = worldCenter([-6, 0, -6], [6, 20, 6], hero.pos, hero.rotYDeg, hero.scale);+ expect(c[0]).toBeCloseTo(95, 1); // east anchor at [95,0]+ expect(c[2]).toBeCloseTo(0, 1);+ });++ test("'scene-in' turns an east asset to face the scene centre (+X points -X ~180deg)", () => {+ const res = layoutScene([item('e', 8, 10, 8, { role: 'hero', zone: 'east' })], {+ anchors: zonedCenters(95),+ facing: 'scene-in',+ });+ expect(Math.abs(res.placements[0]!.rotYDeg)).toBeCloseTo(180, 0);+ });++ test('fill clusters around its group hero', () => {+ const items: LayoutItem[] = [+ item('mkt', 8, 10, 8, { role: 'hero', zone: 'east', group: 'market' }),+ ...Array.from({ length: 6 }, (_, i) =>+ item(`stall${i}`, 2, 2, 2, { role: 'fill', zone: 'east', group: 'market' }),+ ),+ ];+ const res = layoutScene(items, { anchors: zonedCenters(95) });+ const hero = res.placements.find((p) => p.id === 'mkt')!;+ for (const s of res.placements.filter((p) => p.id.startsWith('stall'))) {+ const d = Math.hypot(s.pos[0] - hero.pos[0], s.pos[2] - hero.pos[2]);+ expect(d).toBeLessThan(20); // hug the market, not scattered across the zone+ }+ });+});++describe('terrain seam (heightmap-ready) + grounding', () => {+ test('placements drop onto a custom ground sampler', () => {+ const slope: GroundSampler = { heightAt: (x) => x * 0.1 };+ const res = layoutScene([item('a', 4, 6, 4, { zone: 'east' })], {+ anchors: zonedCenters(95),+ ground: slope,+ });+ const p = res.placements[0]!;+ expect(p.pos[1]).toBeCloseTo(p.pos[0] * 0.1, 1); // base follows the terrain+ });++ test('an asset whose geometry starts above its origin is dropped to the ground', () => {+ const floaty: LayoutItem = { id: 'f', localMin: [-2, 2, -2], localMax: [2, 8, 2] }; // base 2u above origin+ const res = layoutScene([floaty]);+ expect(res.placements[0]!.pos[1]).toBeCloseTo(-2, 5); // origin sinks so base sits at y=0+ });+});++describe('determinism', () => {+ test('same seed reproduces the layout exactly; different seed differs', () => {+ const items = Array.from({ length: 16 }, (_, i) =>+ item(`p${i}`, 3, 5, 3, { zone: i % 2 ? 'east' : 'west' }),+ );+ const a = layoutScene(items, { anchors: zonedCenters(95), seed: 7 });+ const b = layoutScene(items, { anchors: zonedCenters(95), seed: 7 });+ const c = layoutScene(items, { anchors: zonedCenters(95), seed: 99 });+ expect(a.placements).toEqual(b.placements);+ expect(a.placements).not.toEqual(c.placements);+ });+});diff --git a/src/__tests__/composer-model.test.ts b/src/__tests__/composer-model.test.tsnew file mode 100644index 00000000..8834a74c--- /dev/null+++ b/src/__tests__/composer-model.test.ts@@ -0,0 +1,165 @@+/**+ * PlacementModel tests — the composer's structured source of truth.+ *+ * Pure: ops mutate the model, placements() evaluates to overlap-gated world+ * placements with provenance, and the JSON round-trip reproduces them exactly.+ */+import { describe, expect, test } from 'bun:test';++import { type CatalogEntry, PlacementModel } from '../composer';++const asset = (id: string, w = 2, h = 3, d = 2): CatalogEntry => ({+ generationId: id,+ bbox: { min: [-w / 2, 0, -d / 2], max: [w / 2, h, d / 2] },+ name: id,+});++function model(): PlacementModel {+ return new PlacementModel('Test', {+ seed: 7,+ catalog: [+ asset('well', 3, 4, 3),+ asset('stall', 4, 3, 3),+ asset('crate', 1.2, 1.2, 1.2),+ asset('lantern', 0.6, 0.9, 0.6),+ ],+ });+}++describe('place / move / face / remove', () => {+ test('place evaluates to a grounded placement facing the scene centre', () => {+ const m = model();+ const a = m.addPlace('stall', { at: [20, 0], face: 'center', role: 'hero' });+ expect(a).toBe('stall');+ const { placements, overlaps } = m.placements();+ expect(placements).toHaveLength(1);+ expect(placements[0]!.generationId).toBe('stall');+ expect(Math.abs(placements[0]!.rotYDeg)).toBeCloseTo(180, 0); // east → faces -x+ expect(placements[0]!.pos[1]).toBeCloseTo(0, 5); // grounded+ expect(overlaps).toHaveLength(0);+ });++ test('move shifts it, face re-orients it, remove drops it', () => {+ const m = model();+ const a = m.addPlace('well', { at: [0, 0] });+ const p0 = m.placements().placements[0]!.pos[0];+ expect(m.move(a, { delta: [5, 0] }).ok).toBe(true);+ expect(m.placements().placements[0]!.pos[0]).toBeCloseTo(p0 + 5, 5);+ m.face(a, 90);+ expect(m.placements().placements[0]!.rotYDeg).toBe(90);+ expect(m.remove(a).ok).toBe(true);+ expect(m.placements().placements).toHaveLength(0);+ });++ test('edit ops on a missing target return ok:false with a hint', () => {+ const r = model().move('ghost', { delta: [1, 0] });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.hint).toBeDefined();+ });+});++describe('placeExact (verbatim / look-preserving import)', () => {+ // An off-centre bbox (non-zero min, centre away from origin): a normal place would+ // recentre + ground it, so it's the sharpest probe that exact does NEITHER.+ const offset = (m: PlacementModel): void =>+ m.registerAsset({+ generationId: 'offset',+ bbox: { min: [1, 2, -3], max: [5, 6, 1] },+ name: 'offset',+ });++ test('places the asset ORIGIN exactly — no grounding, recentre, or rounding', () => {+ const m = model();+ offset(m);+ const pos: [number, number, number] = [12.34, 5.67, -8.9];+ const alias = m.addPlaceExact('offset', { pos, rotYDeg: 137 });+ const p = m.placements().placements.find((x) => x.instanceId === alias)!;+ expect(p.pos).toEqual(pos); // exact origin, untouched+ expect(p.rotYDeg).toBe(137); // exact rotation — no facing resolve, no integer rounding loss+ });++ test('a normal place at the same XZ shifts the origin; exact does not', () => {+ const m = model();+ offset(m);+ const normal = m.addPlace('offset', { at: [0, 0], face: 0 });+ const exact = m.addPlaceExact('offset', { pos: [0, 0, 0], rotYDeg: 0 });+ const ps = m.placements().placements;+ const pn = ps.find((x) => x.instanceId === normal)!;+ const pe = ps.find((x) => x.instanceId === exact)!;+ expect(pe.pos).toEqual([0, 0, 0]); // verbatim+ // normal recentres by the bbox centre (3, ·, -1) and grounds (min.y=2) → [-3, -2, 1]+ expect(pn.pos).toEqual([-3, -2, 1]);+ });++ test('JSON round-trips the exact placement bit-for-bit (the machine reload)', () => {+ const m = model();+ const pos: [number, number, number] = [3.333, 1.25, -7.7];+ m.addPlaceExact('crate', { pos, rotYDeg: -45.5, scale: 1.5, alias: 'crate_x' });+ const back = PlacementModel.fromJSON(m.toJSON());+ const p = back.placements().placements.find((x) => x.instanceId === 'crate_x')!;+ expect(p.pos).toEqual(pos);+ expect(p.rotYDeg).toBe(-45.5);+ expect(p.scale).toBe(1.5);+ });+});++describe('cluster / ring / layout stay overlap-free and addressable', () => {+ test('cluster scatters N overlap-free around a point', () => {+ const m = model();+ m.addCluster('crate', { around: [15, -10], count: 12, spread: 14 });+ const r = m.placements();+ expect(r.placements).toHaveLength(12);+ expect(r.overlaps).toHaveLength(0);+ });++ test('ring places N on a circle, overlap-free, addressable as alias#i', () => {+ const m = model();+ const alias = m.addRing('lantern', { center: [0, 0], count: 8, radius: 10, faceOut: true });+ const r = m.placements();+ expect(r.placements).toHaveLength(8);+ expect(r.overlaps).toHaveLength(0);+ expect(r.placements.map((p) => p.instanceId)).toContain(`${alias}#0`);+ });++ test('layout explodes into editable place statements, overlap-free', () => {+ const m = model();+ const aliases = m.layout(['well', 'stall', 'crate', 'lantern']);+ expect(aliases).toHaveLength(4);+ expect(m.placements().overlaps).toHaveLength(0);+ // each laid-out asset is independently movable+ m.move(aliases[0]!, { to: [300, 300] });+ const moved = m.placements().placements.find((p) => p.instanceId === aliases[0]);+ expect(moved!.pos[0]).toBeGreaterThan(200);+ });+});++describe('group + provenance + persistence', () => {+ test('group tags members and moves them together', () => {+ const m = model();+ const a = m.addPlace('crate', { at: [0, 0] });+ const b = m.addPlace('crate', { at: [5, 0] });+ const g = m.group([a, b], { name: 'pile', delta: [10, 0] });+ expect(g.ok).toBe(true);+ const ps = m.placements().placements;+ expect(ps.find((p) => p.instanceId === a)!.pos[0]).toBeCloseTo(10, 5); // crate is centred+ expect(ps.find((p) => p.instanceId === b)!.pos[0]).toBeCloseTo(15, 5);+ });++ test('every instance carries provenance back to its generationId + statement', () => {+ const m = model();+ m.addRing('lantern', { center: [0, 0], count: 3, radius: 8 });+ const r = m.placements();+ for (const p of r.placements) {+ expect(r.provenance[p.instanceId]!.generationId).toBe('lantern');+ expect(r.provenance[p.instanceId]!.stmtId).toBe(p.stmtId);+ }+ });++ test('toJSON / fromJSON reproduces the evaluated scene exactly', () => {+ const m = model();+ m.addPlace('well', { at: [0, 0], face: 'center', role: 'hero' });+ m.addCluster('crate', { around: [12, 0], count: 6, spread: 10 });+ const restored = PlacementModel.fromJSON(m.toJSON());+ expect(restored.placements().placements).toEqual(m.placements().placements);+ });+});diff --git a/src/__tests__/composer-overlap.test.ts b/src/__tests__/composer-overlap.test.tsnew file mode 100644index 00000000..85678f7f--- /dev/null+++ b/src/__tests__/composer-overlap.test.ts@@ -0,0 +1,98 @@+/**+ * Composer overlap-validation tests — pure geometry, no LLM, no network.+ *+ * Pins the two bugs that made scene assets collide: footprint underestimation+ * and (the big one) placing a non-centred mesh by its origin as if the origin+ * were its centre. `worldAabbFromLocal` + `findPlacementOverlaps` must catch it.+ */+import { describe, expect, test } from 'bun:test';++import {+ findOverlaps,+ findPlacementOverlaps,+ isOverlapFree,+ type PlacedAsset,+ type PlacedBox,+ summarizeOverlaps,+ worldAabbFromLocal,+} from '../composer';++const box = (+ id: string,+ min: [number, number, number],+ max: [number, number, number],+): PlacedBox => ({ id, min, max });++describe('aabb overlap detection', () => {+ test('face-touching boxes do not overlap (within tolerance)', () => {+ const a = box('a', [0, 0, 0], [1, 1, 1]);+ const b = box('b', [1, 0, 0], [2, 1, 1]); // shares the x=1 face+ expect(isOverlapFree([a, b])).toBe(true);+ expect(findOverlaps([a, b])).toHaveLength(0);+ });++ test('penetrating boxes report depth + the minimum-translation axis', () => {+ const a = box('a', [0, 0, 0], [2, 2, 2]);+ const b = box('b', [1.5, 0, 0], [3.5, 2, 2]); // x-overlap 0.5, z-overlap 2+ const v = findOverlaps([a, b]);+ expect(v).toHaveLength(1);+ expect(v[0]!.axis).toBe('x'); // x is the shallower (cheaper) axis+ expect(v[0]!.penetration[0]).toBeCloseTo(0.5, 5);+ expect(v[0]!.separation[0]).toBeCloseTo(0.5, 5); // push b +x by 0.5+ });++ test('footprint mode ignores vertical separation; volume mode respects it', () => {+ const a = box('a', [0, 0, 0], [2, 2, 2]);+ const b = box('b', [0, 5, 0], [2, 7, 2]); // same XZ, stacked 3u above+ expect(findOverlaps([a, b], { mode: 'footprint' })).toHaveLength(1);+ expect(findOverlaps([a, b], { mode: 'volume' })).toHaveLength(0);+ });+});++describe('worldAabbFromLocal — the centre-offset + rotation fix', () => {+ test('preserves an off-centre local bbox (mesh not centred on its origin)', () => {+ // Geometry spans [0..10] in X/Z — centre at (5,_,5) but origin at the corner.+ const w = worldAabbFromLocal([0, 0, 0], [10, 4, 10], [0, 0, 0], 0, 1);+ expect(w.min).toEqual([0, 0, 0]);+ expect(w.max).toEqual([10, 4, 10]); // NOT recentred on the origin+ });++ test('Y-rotation swaps the XZ footprint extents', () => {+ // 10 (x) x 1 (y) x 2 (z), centred, rotated 90 deg about Y.+ const w = worldAabbFromLocal([-5, -0.5, -1], [5, 0.5, 1], [0, 0, 0], 90, 1);+ expect(w.max[0]).toBeCloseTo(1, 4); // x half-extent becomes ~1+ expect(w.max[2]).toBeCloseTo(5, 4); // z half-extent becomes ~5+ });++ test('uniform scale grows extent and offset together', () => {+ const w = worldAabbFromLocal([0, 0, 0], [2, 2, 2], [10, 0, 0], 0, 3);+ // local centre (1,1,1) -> scaled (3,3,3) -> +pos (10,0,0) => (13,3,3); half 3+ expect(w.min).toEqual([10, 0, 0]);+ expect(w.max).toEqual([16, 6, 6]);+ });+});++describe('placement overlap — the packer bug it catches', () => {+ test('two off-centre assets placed as if centred still collide', () => {+ // Each mesh spans local [0..8] in XZ from a corner origin. A packer that+ // assumes the origin is the centre places the origins only 5u apart.+ const assets: PlacedAsset[] = [+ { id: 'left', localMin: [0, 0, 0], localMax: [8, 5, 8], pos: [0, 0, 0] }, // world x[0..8]+ { id: 'right', localMin: [0, 0, 0], localMax: [8, 5, 8], pos: [5, 0, 0] }, // world x[5..13]+ ];+ const v = findPlacementOverlaps(assets);+ expect(v).toHaveLength(1);+ expect(v[0]!.penetration[0]).toBeCloseTo(3, 5); // 8 - 5+ expect(summarizeOverlaps(v)).toContain('left');+ });++ test('a cleanly spaced layout is overlap-free', () => {+ const assets: PlacedAsset[] = [+ { id: 'a', localMin: [-2, 0, -2], localMax: [2, 4, 2], pos: [0, 0, 0] },+ { id: 'b', localMin: [-2, 0, -2], localMax: [2, 4, 2], pos: [10, 0, 0] },+ { id: 'c', localMin: [-2, 0, -2], localMax: [2, 4, 2], pos: [0, 0, 10] },+ ];+ expect(findPlacementOverlaps(assets)).toHaveLength(0);+ expect(summarizeOverlaps(findPlacementOverlaps(assets))).toBe('No overlapping placements.');+ });+});diff --git a/src/__tests__/composer-scene-raster.test.ts b/src/__tests__/composer-scene-raster.test.tsnew file mode 100644index 00000000..dce7fce3--- /dev/null+++ b/src/__tests__/composer-scene-raster.test.ts@@ -0,0 +1,59 @@+/**+ * Composed-scene rasterizer — the default SceneRenderPort implementation.+ *+ * Executes each unique Kiln program once, clones it per placement into one THREE+ * scene, and rasterizes a labelled grid. We assert a real PNG comes out for the+ * default 3 angles, for a single custom direction, and that duplicate codes are+ * executed once (the cache), without any GLB round-trip.+ */+import { describe, expect, test } from 'bun:test';++import { rasterizeComposedScene, SCENE_VIEWS } from '../views';++const BARREL = `function build() {+ const root = createRoot('Barrel');+ const steel = lambertMaterial(0xc8743a);+ createPart('Body', cylinderGeo(0.55, 0.55, 1.3, 16), steel, { parent: root, position: [0, 0.65, 0] });+ return root;+}`;++const TREE = `function build() {+ const root = createRoot('Tree');+ const bark = lambertMaterial(0x4a2a14);+ const leaf = lambertMaterial(0x4f7d5e);+ createPart('Trunk', cylinderGeo(0.12, 0.17, 1.0, 8), bark, { parent: root, position: [0, 0.5, 0] });+ createPart('Canopy', sphereGeo(0.55, 8, 6), leaf, { parent: root, position: [0, 1.2, 0] });+ return root;+}`;++const isPng = (b: Buffer): boolean =>+ b.length > 1000 && b[0] === 0x89 && b.subarray(1, 4).toString('latin1') === 'PNG';++describe('rasterizeComposedScene', () => {+ test('renders a multi-asset scene from the 3 default angles into one grid PNG', async () => {+ const r = await rasterizeComposedScene([+ { code: BARREL, pos: [0, 0, 0], rotYDeg: 0, scale: 1 },+ { code: BARREL, pos: [4, 0, 0], rotYDeg: 90, scale: 1 },+ { code: TREE, pos: [0, 0, 6], rotYDeg: 0, scale: 1.5 },+ ]);+ expect(isPng(r.png)).toBe(true);+ expect(r.views).toEqual(SCENE_VIEWS.map((v) => v.name));+ // 3 cells across one row → wider than tall.+ expect(r.width).toBeGreaterThan(r.height);+ });++ test('a single custom view direction yields a one-cell image', async () => {+ const r = await rasterizeComposedScene(+ [{ code: BARREL, pos: [0, 0, 0], rotYDeg: 0, scale: 1 }],+ { views: [{ name: 'cam', dir: [1, 0.6, 1] }], size: 256 },+ );+ expect(isPng(r.png)).toBe(true);+ expect(r.views).toEqual(['cam']);+ expect(r.width).toBe(256 + 2 * 4); // one cell + padding+ });++ test('an empty scene still produces a (blank) grid without throwing', async () => {+ const r = await rasterizeComposedScene([]);+ expect(isPng(r.png)).toBe(true);+ });+});diff --git a/src/composer/agent/index.ts b/src/composer/agent/index.tsnew file mode 100644index 00000000..365009a4--- /dev/null+++ b/src/composer/agent/index.ts@@ -0,0 +1,21 @@+/**+ * `@kiln/engine/composer/agent` — the Strands-driven scene-composition loop.+ *+ * The agent counterpart to the pure `@kiln/engine/composer` core: it exposes the+ * `scene_*` tool surface over a `PlacementModel` and drives any Strands `Model`+ * through it via {@link runKilnComposer}. Isolated on its own subpath so the+ * `@strands-agents/sdk` dependency does not leak into the composer core (which is+ * pure and THREE-free) — import from here only when you want the agent loop.+ *+ * - {@link runKilnComposer} — drive a Strands Model through the scene_* tool loop+ * - {@link makeSceneComposerTools} — the 14-tool scene_* skin over a model + render port+ * - {@link COMPOSER_SYSTEM_PROMPT} / {@link buildComposerUserPrompt} — the prompts+ */+export { runKilnComposer } from './run';+export type { RunKilnComposerOptions, RunKilnComposerResult } from './run';++export { makeSceneComposerTools } from './tools';+export type { ComposerSink, MakeComposerToolsOptions, SceneRenderCandidate } from './tools';++export { buildComposerUserPrompt, COMPOSER_SYSTEM_PROMPT } from './prompt';+export type { BuildComposerPromptOptions } from './prompt';diff --git a/src/composer/agent/prompt.ts b/src/composer/agent/prompt.tsnew file mode 100644index 00000000..5b66d505--- /dev/null+++ b/src/composer/agent/prompt.ts@@ -0,0 +1,86 @@+/**+ * Composer prompts — the system know-how + user-task framing for runKilnComposer.+ *+ * Mirrors the asset-gen prompt's job (teach the conventions, keep the task prompt+ * natural language) but for SCENES: the agent arranges already-generated assets+ * from a fixed catalog onto a ground plane through the `scene_*` tools. It never+ * writes code — the structured model IS the program, and the tools mutate it.+ */++/** The conventions + working loop the composer agent operates under. */+export const COMPOSER_SYSTEM_PROMPT = `You are Kiln's scene composer. You arrange a fixed set of already-built 3D assets into a single cohesive scene by calling tools — you do NOT write code. Each tool mutates one structured scene model; after every change the scene is saved and can be re-rendered.++## World conventions+- The ground is the XZ plane, +Y is up. The scene centre is the origin [0, 0]. Positions are [x, z] ground points in world units.+- Assets are authored facing +X. "Facing" turns an asset so its front points where you intend: "center" faces the origin, "out" faces away from it, [x, z] faces that point, or pass degrees.+- Every asset sits on the terrain automatically (its base is grounded) — you place it by its footprint centre, not its pivot.+- Footprint overlaps are tracked and must be resolved: a finished scene has zero overlaps. The placement primitives (layout / cluster / ring) are overlap-free by construction; hand placements can collide.++## The catalog is fixed+You may only place assets from this scene's catalog (call scene_list_assets to see every generationId, its name, and its footprint size). You cannot invent or generate new assets in this loop — compose with what you have, reusing an asset as many times as the scene needs.++## Composition principles (make it read as intentional, not scattered)+- Spacing is deliberate, not uniform. Give hero/landmark assets breathing room; let supporting and fill assets cluster and frame them. Open up sightlines and negative space.+- Facing carries meaning. Turn heroes toward the viewer or a focal point; turn rows and walls to frame a space; face a ring inward or outward on purpose.+- Group what belongs together. A market row, a courtyard, a camp, a motor-court — build it from a cluster/ring or a group so it moves and reads as one unit.+- Use roles: hero (anchors the scene), support (frames + structures it), fill (density + texture).+- Depth and rhythm beat symmetry. Vary distances; avoid a flat even grid unless the scene is literally a grid.++## Tools+- Plan: scene_list_assets (always first), scene_view (the current program + counts).+- Build: scene_layout (an overlap-free baseline you then refine), scene_place (one asset), scene_cluster (N scattered around a point), scene_ring (N on a circle).+- Refine: scene_move (reposition / use a separation vector / rescale), scene_face (re-orient), scene_group (bind + move together), scene_remove.+- See + check: scene_render (the whole scene from three angles — LOOK at it), scene_screenshot_camera (one vantage you choose), scene_validate (overlaps + the vector to separate each).+- Commit: scene_finalize (exactly once, at the end).++## Working loop+1. scene_list_assets, and read the scene prompt: decide the layout idea (what anchors the scene, what frames it, where the groupings go).+2. Lay it down — scene_layout for a quick baseline, or place/cluster/ring deliberately for a hand-composed scene.+3. scene_render and JUDGE it: spacing, facing, groupings, silhouette, overlaps. Use scene_screenshot_camera to check a key vantage (e.g. how it reads on approach).+4. Fix it: scene_validate for any overlaps (move by the mtv), then improve the composition (facing, spacing, grouping). Re-render.+5. When the scene reads as cohesive, overlap-free, and intentional, call scene_finalize once.`;++export interface BuildComposerPromptOptions {+ /** Natural-language description of the scene to compose. */+ prompt: string;+ /** Asset catalog summary lines (name + footprint), for at-a-glance framing. */+ catalogSummary?: string;+ /** When refining: the parent scene program, framed as the starting point. */+ existingProgram?: string;+ /** The scene's display name, if any. */+ sceneName?: string;+}++/** Frame the composition task: the scene prompt, the catalog at a glance, the+ * refine starting point (if any), and the always-render-before-finalize note. */+export function buildComposerUserPrompt(opts: BuildComposerPromptOptions): string {+ const parts: string[] = [];+ parts.push(+ opts.sceneName+ ? `## Scene: ${opts.sceneName}\n${opts.prompt.trim()}`+ : `## Scene to compose\n${opts.prompt.trim()}`,+ );++ if (opts.catalogSummary?.trim()) {+ parts.push(+ `## Catalog (the assets available to you)\n${opts.catalogSummary.trim()}\n\n` ++ 'Call scene_list_assets for the exact generationIds and footprint sizes.',+ );+ }++ if (opts.existingProgram?.trim()) {+ parts.push(+ '## Starting point\nThis scene already exists — refine it rather than starting over. Its current program:\n\n' ++ `\`\`\`\n${opts.existingProgram.trim()}\n\`\`\`\n\n` ++ 'Make the requested changes through the tools (move / face / place / remove / group); preserve what already works.',+ );+ }++ parts.push(+ 'Before you call scene_finalize, call scene_render at least once and look at all three angles: ' ++ 'deliberate spacing, correct facing, clean groupings, no overlapping or floating assets. ' ++ 'Fix anything that looks wrong, then finalize exactly once.',+ );++ return parts.join('\n\n');+}diff --git a/src/composer/agent/run.ts b/src/composer/agent/run.tsnew file mode 100644index 00000000..7e1bf98d--- /dev/null+++ b/src/composer/agent/run.ts@@ -0,0 +1,240 @@+/**+ * `runKilnComposer` — the scene-composition counterpart to `runKilnAgent`.+ *+ * Drives any Strands `Model` through the `scene_*` tool loop: the agent discovers+ * the fixed asset catalog, lays out / places / refines a structured scene model,+ * renders it through the host `SceneRenderPort` to SEE the result, and finalizes.+ * Reuses the asset-gen `MetricsCollector` (tool/step/usage + the runaway step cap)+ * and `unifiedDiff` (the refine patch artifact). The `@strands-agents/sdk`+ * dependency lives ONLY here on `@kiln/engine/composer/agent` — the composer core+ * (model / dsl / overlap / layout / render-port) never imports it.+ *+ * Never throws: failures come back on `result.error` with whatever the sink+ * captured beforehand (a step-capped or erroring run still returns its partial+ * program + placements).+ */+import { Agent, type Message, type Tool } from '@strands-agents/sdk';++import { unifiedDiff } from '../../agent/diff';+import { type AgentUsage, type KilnAgentEvent, MetricsCollector } from '../../agent/hooks';+import { serialize } from '../dsl';+import { flatGround, type GroundSampler } from '../ground';+import {+ type CatalogEntry,+ type Placement,+ PlacementModel,+ type PlacementProvenance,+ type SceneModelJSON,+} from '../model';+import type { OverlapViolation } from '../overlap';+import type { SceneRenderPort } from '../render-port';+import { buildComposerUserPrompt, COMPOSER_SYSTEM_PROMPT } from './prompt';+import { type ComposerSink, makeSceneComposerTools, type SceneRenderCandidate } from './tools';++export interface RunKilnComposerOptions {+ /** A constructed Strands `Model` instance (provider-agnostic). */+ model: unknown;+ /** Natural-language description of the scene to compose. */+ prompt: string;+ /** The selectable asset catalog (generationId + asset-local bbox). The agent may+ * ONLY place these. Optional when `seedScene` already carries a catalog. */+ catalog?: CatalogEntry[];+ /** Host renderer: placements (+ optional cameras) → PNG(s). Injected so the+ * composer core stays THREE-free; tests pass a stub returning a fixed PNG. */+ render: SceneRenderPort;+ /** Display name for the scene (used in framing + the serialized program). */+ sceneName?: string;+ /** Terrain sampler. Default flat ground at y=0; a heightmap drops in unchanged. */+ ground?: GroundSampler;+ /** Deterministic layout seed. Default 1. */+ seed?: number;+ /** Refine an existing scene: seed the model from this JSON and frame the run as+ * an edit (its serialized program is shown as the starting point, and the result+ * carries a unified diff from it). Extra `catalog` entries are merged in. */+ seedScene?: SceneModelJSON;+ /** Agent name (for tracing). Default 'kiln-composer'. */+ agentName?: string;+ /** Live agent-loop events (tool/model calls) for progress UIs. Best-effort. */+ onEvent?: (event: KilnAgentEvent) => void;+ /** Live render candidates (one per successful scene_render) for a filmstrip. */+ onCandidate?: (c: SceneRenderCandidate) => void;+ /** Extra tools to expose (e.g. a Strands McpClient). */+ extraTools?: unknown[];+}++export interface RunKilnComposerResult {+ /** The final serialized scene program (the diffable, version-controlled artifact). */+ program?: string;+ /** The structured scene model JSON (machine round-trip / persistence). */+ scene?: SceneModelJSON;+ /** The evaluated world placements the renderer/runtime consume. */+ placements?: Placement[];+ /** instanceId → provenance (generationId + statement + optional source prompt). */+ provenance?: Record<string, PlacementProvenance>;+ /** Any unresolved footprint overlaps at finalize (surfaced, never dropped). */+ overlaps?: OverlapViolation[];+ /** Whether the agent called scene_finalize. */+ finalized: boolean;+ /** Every tool the model called, in order. */+ toolCalls: string[];+ /** Number of model calls (agent-loop iterations). */+ steps: number;+ /** Best-effort token usage. */+ usage?: AgentUsage;+ /** The last assistant text (fallback / diagnostics). */+ lastText?: string;+ /** When refining (seedScene set): a unified diff from the parent program. */+ diff?: string;+ /** Error message if the run threw or was step-capped. */+ error?: string;+}++function lastMessageText(message: Message | undefined): string | undefined {+ if (!message) return undefined;+ const parts: string[] = [];+ for (const block of message.content) {+ if ((block as { type?: string }).type === 'textBlock') {+ const t = (block as { text?: string }).text;+ if (typeof t === 'string') parts.push(t);+ }+ }+ const joined = parts.join('\n').trim();+ return joined.length ? joined : undefined;+}++/** Build the model from a fresh catalog or a seeded scene (merging extra catalog). */+function buildModel(opts: RunKilnComposerOptions): PlacementModel {+ const ground = opts.ground ?? flatGround(0);+ if (opts.seedScene) {+ const m = PlacementModel.fromJSON(opts.seedScene, ground);+ for (const e of opts.catalog ?? []) m.registerAsset(e);+ return m;+ }+ return new PlacementModel(opts.sceneName ?? 'Scene', {+ ground,+ ...(opts.seed != null ? { seed: opts.seed } : {}),+ catalog: opts.catalog ?? [],+ });+}++/**+ * Run one scene-composition session end-to-end. Never throws — failures are+ * returned on `result.error` with whatever the sink captured beforehand.+ */+export async function runKilnComposer(+ opts: RunKilnComposerOptions,+): Promise<RunKilnComposerResult> {+ // Runaway backstop (NOT a throttle): a stuck model could loop place/render+ // forever, re-feeding a growing transcript. Default 60 — composition takes more+ // tool turns than a single asset (many placements + renders). Env-overridable+ // (0 disables); shares the asset-gen knob name for one place to tune.+ const maxSteps = Number(process.env['KILN_AGENT_MAX_STEPS'] ?? 60) || 0;+ const metrics = new MetricsCollector(opts.onEvent, maxSteps);+ const model = buildModel(opts);+ const parentProgram = opts.seedScene ? serialize(model) : undefined;+ const sink: ComposerSink = {};++ try {+ const tools: Tool[] = makeSceneComposerTools({+ model,+ render: opts.render,+ sink,+ ...(opts.onCandidate ? { onCandidate: opts.onCandidate } : {}),+ });+ const allTools: unknown[] = opts.extraTools ? [...tools, ...opts.extraTools] : tools;++ const agent = new Agent({+ model: opts.model as never,+ systemPrompt: COMPOSER_SYSTEM_PROMPT,+ tools: allTools as never,+ name: opts.agentName ?? 'kiln-composer',+ });+ metrics.attach(agent);++ const catalogLines = model+ .catalogList()+ .map((e) => `- ${e.name ?? e.generationId} — ${e.size[0]}×${e.size[1]}×${e.size[2]}`)+ .join('\n');++ const userPrompt = buildComposerUserPrompt({+ prompt: opts.prompt,+ ...(opts.sceneName ? { sceneName: opts.sceneName } : {}),+ ...(catalogLines ? { catalogSummary: catalogLines } : {}),+ ...(parentProgram ? { existingProgram: parentProgram } : {}),+ });++ const result = await agent.invoke(userPrompt as never);+ metrics.recordResultUsage(result.metrics?.latestAgentInvocation?.usage);+ const lastText = lastMessageText(result.lastMessage);++ // Halted by the step cap: surface a clear failure but still return the partial+ // scene the sink captured (continuous autosave), so the host can show progress.+ if (metrics.wasCapped()) {+ const collected = metrics.readMetrics();+ return {+ ...sceneFields(sink, model),+ finalized: sink.finalized ?? false,+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...(collected.usage ? { usage: collected.usage } : {}),+ ...(lastText ? { lastText } : {}),+ error: `kiln composer exceeded ${maxSteps} model calls (step cap) — aborted to bound cost`,+ };+ }++ const collected = metrics.readMetrics();+ const program = sink.program;+ const diff =+ parentProgram && program+ ? unifiedDiff(parentProgram, program, { fromLabel: 'parent', toLabel: 'refined' })+ : undefined;++ return {+ ...sceneFields(sink, model),+ finalized: sink.finalized ?? false,+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...(collected.usage ? { usage: collected.usage } : {}),+ ...(lastText ? { lastText } : {}),+ ...(diff ? { diff } : {}),+ };+ } catch (err) {+ const collected = metrics.readMetrics();+ return {+ ...sceneFields(sink, model),+ finalized: sink.finalized ?? false,+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...(collected.usage ? { usage: collected.usage } : {}),+ error: err instanceof Error ? err.message : String(err),+ };+ } finally {+ metrics.detach();+ }+}++/** The scene payload fields, from the sink when present (the agent built something)+ * else evaluated fresh from the model (so even a no-tool run returns a valid scene). */+function sceneFields(+ sink: ComposerSink,+ model: PlacementModel,+): Pick<RunKilnComposerResult, 'program' | 'scene' | 'placements' | 'provenance' | 'overlaps'> {+ const program = sink.program ?? serialize(model);+ if (sink.placements) {+ return {+ program,+ scene: model.toJSON(),+ placements: sink.placements,+ ...(sink.provenance ? { provenance: sink.provenance } : {}),+ ...(sink.overlaps ? { overlaps: sink.overlaps } : {}),+ };+ }+ const ev = model.placements();+ return {+ program,+ scene: model.toJSON(),+ placements: ev.placements,+ provenance: ev.provenance,+ overlaps: ev.overlaps,+ };+}diff --git a/src/composer/agent/tools.ts b/src/composer/agent/tools.tsnew file mode 100644index 00000000..93995041--- /dev/null+++ b/src/composer/agent/tools.ts@@ -0,0 +1,608 @@+/**+ * Scene-composer tool skin for the Strands agent loop — the `scene_*` surface.+ *+ * Sibling to the asset-gen `kiln_*` tools (../../agent/tools), but the unit of+ * work is a SCENE, not a single asset. Every tool mutates ONE structured+ * `PlacementModel` (the source of truth); after each successful mutation the+ * model is re-evaluated + re-serialized into a `ComposerSink` (continuous+ * autosave — a step-capped run still captures its work). The two image tools+ * (`scene_render` / `scene_screenshot_camera`) call the host `SceneRenderPort`+ * and return `[ImageBlock…, JsonBlock]` so the model literally SEES the scene.+ *+ * Pure orchestration over the composer core (model / dsl / overlap) + the SDK's+ * `tool()`. No THREE — rendering is the injected host port. Errors are in-band+ * `{ ok:false, error, hint }` (tools never throw at the model).+ *+ * Surface (14): read — scene_list_assets, scene_view, scene_validate,+ * scene_render, scene_screenshot_camera · mutate — scene_layout, scene_place,+ * scene_cluster, scene_ring, scene_move, scene_face, scene_group, scene_remove ·+ * commit — scene_finalize. (Extends the design doc's 12 with scene_cluster /+ * scene_ring so the agent can author the grouping primitives the program already+ * serializes.)+ */+import { ImageBlock, JsonBlock, type JSONValue, type Tool, tool } from '@strands-agents/sdk';+import { z } from 'zod';++import { serialize } from '../dsl';+import type { EvalResult, Placement, PlacementModel, PlacementProvenance } from '../model';+import type { OverlapViolation } from '../overlap';+import type { SceneRenderPort, SceneRenderResult } from '../render-port';++/**+ * A mutable sink the composer tools write into. Create one per run; after every+ * successful mutation it holds the latest serialized program + evaluated scene+ * (so an un-finalized / step-capped run still captures the work). `.finalized`+ * flips when `scene_finalize` fires.+ */+export interface ComposerSink {+ program?: string;+ placements?: Placement[];+ provenance?: Record<string, PlacementProvenance>;+ overlaps?: OverlapViolation[];+ finalized?: boolean;+}++/**+ * A live render candidate surfaced out-of-band from `scene_render`: the+ * serialized program at this render plus the grid PNG (base64) the agent saw.+ * Lets the host stream a filmstrip of intermediate scenes + "pick a version".+ * Emitted in addition to — never instead of — what the agent sees.+ */+export interface SceneRenderCandidate {+ program: string;+ pngBase64: string;+ tris?: number;+}++// ── shared zod fragments ──────────────────────────────────────────────────────++const vec2 = z.tuple([z.number(), z.number()]);+const vec3 = z.tuple([z.number(), z.number(), z.number()]);+const roleEnum = z.enum(['hero', 'support', 'fill']);+/** center (face the scene origin) · out (face away) · [x,z] (face a point) · degrees. */+const facing = z.union([z.literal('center'), z.literal('out'), vec2, z.number()]);+const empty = z.object({});++// ── render-result → content blocks ────────────────────────────────────────────++/** base64 PNG → the raw bytes an ImageBlock wants. */+const png = (b64: string): Uint8Array => new Uint8Array(Buffer.from(b64, 'base64'));++/** Turn a host render result into the tool-callback value: one ImageBlock per+ * returned view (perCamera grid or single frame) + a JsonBlock of metadata, or a+ * plain `{ok:false}` when the render failed. Block arrays are a valid (untyped)+ * Strands callback return — cast past JSONValue, same as the kiln_* tools. */+function renderToCallback(res: SceneRenderResult): JSONValue {+ if (!res.ok) {+ return { ok: false, error: res.error ?? 'render failed' } as JSONValue;+ }+ const frames = res.perCameraBase64?.length+ ? res.perCameraBase64+ : res.pngBase64+ ? [res.pngBase64]+ : [];+ const json = {+ ok: true,+ views: frames.length,+ ...(res.tris != null ? { tris: res.tris } : {}),+ };+ return [+ ...frames.map((b64) => new ImageBlock({ format: 'png', source: { bytes: png(b64) } })),+ new JsonBlock({ json: json as JSONValue }),+ ] as unknown as JSONValue;+}++// ── shared mutation plumbing ──────────────────────────────────────────────────++/** A compact mutation receipt the model reads after every edit. */+interface MutationEcho {+ ok: true;+ alias?: string | string[];+ placements: number;+ overlaps: number;+ hint?: string;+}++export interface MakeComposerToolsOptions {+ /** The scene model the tools mutate (seeded with the selected catalog). */+ model: PlacementModel;+ /** Host renderer: placements (+ optional cameras) → PNG(s). */+ render: SceneRenderPort;+ /** Receives the serialized program + evaluated scene after each mutation. */+ sink: ComposerSink;+ /** Best-effort live render candidates (one per successful scene_render). */+ onCandidate?: (c: SceneRenderCandidate) => void;+}++/**+ * Build the in-process `scene_*` tool list for a composer run. Every mutator+ * shares one `capture()` that re-serializes + re-evaluates the model into the+ * sink and returns a `{ placements, overlaps }` receipt; a non-zero overlap count+ * carries a hint pointing at scene_validate → scene_move.+ */+export function makeSceneComposerTools(opts: MakeComposerToolsOptions): Tool[] {+ const { model, render, sink } = opts;++ /** Re-serialize + re-evaluate into the sink; the single autosave point. */+ const capture = (): EvalResult => {+ const ev = model.placements();+ sink.program = serialize(model);+ sink.placements = ev.placements;+ sink.provenance = ev.provenance;+ sink.overlaps = ev.overlaps;+ return ev;+ };++ /** Standard mutation receipt: capture, then echo counts (+ overlap nudge). */+ const echo = (alias?: string | string[]): MutationEcho => {+ const ev = capture();+ const overlaps = ev.overlaps.length;+ return {+ ok: true,+ ...(alias !== undefined ? { alias } : {}),+ placements: ev.placements.length,+ overlaps,+ ...(overlaps+ ? {+ hint: `${overlaps} footprint overlap(s) — call scene_validate for separation vectors, then scene_move to resolve.`,+ }+ : {}),+ };+ };++ /** Wrap an add op (which throws on an unknown asset) into an in-band result. */+ const guarded = (fn: () => string | string[]): JSONValue => {+ try {+ return echo(fn()) as unknown as JSONValue;+ } catch (err) {+ return {+ ok: false,+ error: err instanceof Error ? err.message : String(err),+ hint: 'Call scene_list_assets to see the generationIds available in this scene.',+ } as JSONValue;+ }+ };++ // ── read tools ──────────────────────────────────────────────────────────────++ const listAssetsTool: Tool = tool({+ name: 'scene_list_assets',+ description:+ 'List the assets you can place in this scene — each generationId with its name, footprint ' ++ 'size [w,h,d], and tags. These are the ONLY assets available; place them by generationId. ' ++ 'Call this first to plan your composition.',+ inputSchema: empty,+ callback: () => ({ assets: model.catalogList() }) as JSONValue,+ });++ const viewTool: Tool = tool({+ name: 'scene_view',+ description:+ 'Read the current scene: the serialized scene program (the diffable source of truth), the ' ++ 'placement aliases, and the live placement / overlap counts. Use it to see what you have ' ++ 'built before deciding the next move.',+ inputSchema: empty,+ callback: () => {+ const ev = model.placements();+ return {+ program: serialize(model),+ placementCount: ev.placements.length,+ overlapCount: ev.overlaps.length,+ aliases: model.statements().map((s) => s.alias),+ } as JSONValue;+ },+ });++ const validateTool: Tool = tool({+ name: 'scene_validate',+ description:+ 'Check the scene for footprint overlaps. Returns each colliding pair (a, b) with a penetration ' ++ 'depth and a `separation` vector [x,y,z] — pass its x and z to scene_move as a delta on one of ' ++ 'the pair to push them apart. An empty list means the scene is clean.',+ inputSchema: empty,+ callback: () => {+ const { overlaps } = model.placements();+ return {+ ok: overlaps.length === 0,+ count: overlaps.length,+ overlaps,+ } as unknown as JSONValue;+ },+ });++ const renderTool: Tool = tool({+ name: 'scene_render',+ description:+ 'Render the WHOLE scene from three canonical angles (a labelled grid) so you can SEE the ' ++ 'composition: spacing, facing, groupings, silhouette, and any overlaps the numbers miss. ' ++ 'Call it after a batch of placements/edits, judge it, then refine. No argument.',+ inputSchema: empty,+ callback: async () => {+ const res = await render({ placements: model.placements().placements });+ if (res.ok && opts.onCandidate) {+ const b64 = res.pngBase64 ?? res.perCameraBase64?.[0];+ if (b64) {+ try {+ opts.onCandidate({+ program: serialize(model),+ pngBase64: b64,+ ...(res.tris != null ? { tris: res.tris } : {}),+ });+ } catch {+ // candidate sink is best-effort+ }+ }+ }+ return renderToCallback(res);+ },+ });++ const screenshotTool: Tool = tool({+ name: 'scene_screenshot_camera',+ description:+ 'Render the scene from ONE camera you specify — position [x,y,z] and the target [x,y,z] it ' ++ 'looks at (optional fovDeg). Use it to inspect a specific vantage: a player entry view, a ' ++ 'sightline down a row, or a close read of one cluster. Returns a single image.',+ inputSchema: z.object({+ position: vec3.describe('Camera position [x,y,z] in world units (+Y up).'),+ target: vec3.describe(+ 'The point [x,y,z] the camera looks at (e.g. the scene centre [0,0,0]).',+ ),+ fovDeg: z.number().optional().describe('Vertical field of view in degrees (default ~50).'),+ }),+ callback: async (input) => {+ const i = input as {+ position: [number, number, number];+ target: [number, number, number];+ fovDeg?: number;+ };+ const res = await render({+ placements: model.placements().placements,+ cameras: [+ {+ position: i.position,+ target: i.target,+ ...(i.fovDeg != null ? { fovDeg: i.fovDeg } : {}),+ },+ ],+ });+ return renderToCallback(res);+ },+ });++ // ── mutate tools ──────────────────────────────────────────────────────────────++ const layoutTool: Tool = tool({+ name: 'scene_layout',+ description:+ 'Lay out a set of assets into an overlap-free BASELINE, then refine by hand. Explodes into one ' ++ 'editable placement per asset (each independently movable). Good as a first pass; omit `assets` ' ++ 'to lay out the whole catalog. anchor "zonedCenters" spreads them across four districts + a ' ++ 'centre; "single" packs them around the origin.',+ inputSchema: z.object({+ assets: z+ .array(z.string())+ .optional()+ .describe('generationIds to lay out (default: all in the catalog).'),+ anchor: z+ .enum(['single', 'zonedCenters'])+ .optional()+ .describe('Layout anchoring (default single).'),+ spacing: z.number().optional().describe('District spacing for zonedCenters (default 95).'),+ facing: z+ .enum(['scene-in', 'scene-out', 'zone-in', 'random', 'none'])+ .optional()+ .describe(+ 'How laid-out assets face (default scene-in: toward the centre; zone-in: toward their ' ++ 'district; scene-out: away; random / none).',+ ),+ seed: z.number().optional().describe('Layout seed (deterministic; default the scene seed).'),+ scale: z+ .number()+ .optional()+ .describe('Uniform scale applied to every laid-out asset (default 1).'),+ role: roleEnum.optional().describe('Role for the laid-out assets (default support).'),+ }),+ callback: (input) => {+ const i = input as {+ assets?: string[];+ anchor?: 'single' | 'zonedCenters';+ spacing?: number;+ facing?: 'scene-in' | 'scene-out' | 'zone-in' | 'random' | 'none';+ seed?: number;+ scale?: number;+ role?: 'hero' | 'support' | 'fill';+ };+ const ids = i.assets ?? model.catalogList().map((e) => e.generationId);+ return guarded(() =>+ model.layout(ids, {+ ...(i.anchor ? { anchor: i.anchor } : {}),+ ...(i.spacing != null ? { spacing: i.spacing } : {}),+ ...(i.facing ? { facing: i.facing } : {}),+ ...(i.seed != null ? { seed: i.seed } : {}),+ ...(i.scale != null ? { scale: i.scale } : {}),+ ...(i.role ? { role: i.role } : {}),+ }),+ );+ },+ });++ const placeTool: Tool = tool({+ name: 'scene_place',+ description:+ 'Place ONE asset at a ground point [x,z] (the scene centre is [0,0]; assets are authored facing ' ++ '+X). Pick `face` deliberately: "center" to face the origin, "out" away from it, [x,z] to face a ' ++ 'point, or degrees. `role` (hero/support/fill) signals intent. Returns the placement alias to ' ++ 'address it later.',+ inputSchema: z.object({+ asset: z.string().describe('The generationId to place (from scene_list_assets).'),+ at: vec2.describe('Ground position [x,z] in world units.'),+ y: z+ .number()+ .optional()+ .describe('Explicit Y (default: grounded so the base sits on the terrain).'),+ face: facing.optional().describe('Facing intent (default "center").'),+ scale: z.number().optional().describe('Uniform scale (default 1).'),+ role: roleEnum.optional().describe('hero | support | fill (default support).'),+ group: z.string().optional().describe('Optional group name to bind this placement into.'),+ alias: z+ .string()+ .optional()+ .describe('A friendly alias to address this placement (default derived from the name).'),+ }),+ callback: (input) => {+ const i = input as {+ asset: string;+ at: [number, number];+ y?: number;+ face?: z.infer<typeof facing>;+ scale?: number;+ role?: 'hero' | 'support' | 'fill';+ group?: string;+ alias?: string;+ };+ return guarded(() =>+ model.addPlace(i.asset, {+ at: i.at,+ ...(i.y != null ? { y: i.y } : {}),+ ...(i.face !== undefined ? { face: i.face } : {}),+ ...(i.scale != null ? { scale: i.scale } : {}),+ ...(i.role ? { role: i.role } : {}),+ ...(i.group ? { group: i.group } : {}),+ ...(i.alias ? { alias: i.alias } : {}),+ }),+ );+ },+ });++ const clusterTool: Tool = tool({+ name: 'scene_cluster',+ description:+ 'Scatter N copies of an asset around a point — overlap-free by construction. Use it for organic ' ++ 'density: a cluster of crates, rocks, tents, debris. `spread` is the rough diameter. Serializes ' ++ 'as a single line and is addressable as one unit (alias) or per-instance (alias#i).',+ inputSchema: z.object({+ asset: z.string().describe('The generationId to scatter.'),+ around: vec2.describe('Centre point [x,z] of the cluster.'),+ count: z.number().int().min(1).describe('How many copies.'),+ spread: z.number().describe('Approximate cluster diameter in world units.'),+ face: facing.optional().describe('Facing intent for the copies (default "center").'),+ scale: z.number().optional().describe('Uniform scale (default 1).'),+ role: roleEnum.optional().describe('hero | support | fill (default fill).'),+ group: z.string().optional().describe('Optional group name.'),+ alias: z.string().optional().describe('Alias for the cluster (default <name>_cluster).'),+ }),+ callback: (input) => {+ const i = input as {+ asset: string;+ around: [number, number];+ count: number;+ spread: number;+ face?: z.infer<typeof facing>;+ scale?: number;+ role?: 'hero' | 'support' | 'fill';+ group?: string;+ alias?: string;+ };+ return guarded(() =>+ model.addCluster(i.asset, {+ around: i.around,+ count: i.count,+ spread: i.spread,+ ...(i.face !== undefined ? { face: i.face } : {}),+ ...(i.scale != null ? { scale: i.scale } : {}),+ ...(i.role ? { role: i.role } : {}),+ ...(i.group ? { group: i.group } : {}),+ ...(i.alias ? { alias: i.alias } : {}),+ }),+ );+ },+ });++ const ringTool: Tool = tool({+ name: 'scene_ring',+ description:+ 'Place N copies evenly on a circle of `radius` around a centre — overlap-free. Use it for ' ++ 'deliberate radial structure: columns around a plaza, lanterns around a well, stones in a ' ++ 'circle. `faceOut:true` turns the copies to face outward (default: face the centre).',+ inputSchema: z.object({+ asset: z.string().describe('The generationId to ring.'),+ center: vec2.describe('Centre point [x,z] of the ring.'),+ count: z.number().int().min(1).describe('How many copies on the circle.'),+ radius: z.number().describe('Ring radius in world units.'),+ faceOut: z+ .boolean()+ .optional()+ .describe('Face outward instead of toward the centre (default false).'),+ scale: z.number().optional().describe('Uniform scale (default 1).'),+ role: roleEnum.optional().describe('hero | support | fill (default support).'),+ group: z.string().optional().describe('Optional group name.'),+ alias: z.string().optional().describe('Alias for the ring (default <name>_ring).'),+ }),+ callback: (input) => {+ const i = input as {+ asset: string;+ center: [number, number];+ count: number;+ radius: number;+ faceOut?: boolean;+ scale?: number;+ role?: 'hero' | 'support' | 'fill';+ group?: string;+ alias?: string;+ };+ return guarded(() =>+ model.addRing(i.asset, {+ center: i.center,+ count: i.count,+ radius: i.radius,+ ...(i.faceOut != null ? { faceOut: i.faceOut } : {}),+ ...(i.scale != null ? { scale: i.scale } : {}),+ ...(i.role ? { role: i.role } : {}),+ ...(i.group ? { group: i.group } : {}),+ ...(i.alias ? { alias: i.alias } : {}),+ }),+ );+ },+ });++ const moveTool: Tool = tool({+ name: 'scene_move',+ description:+ 'Move a placement (by alias or stmtId): `to` sets an absolute ground point [x,z], `delta` nudges ' ++ 'it by [dx,dz] (pass scene_validate’s separation x,z here to resolve an overlap), and `scale` ' ++ 'resets its scale. Targets a cluster/ring by its alias to move the whole group.',+ inputSchema: z.object({+ target: z.string().describe('The placement alias (or stmtId) to move.'),+ to: vec2.optional().describe('Absolute ground position [x,z].'),+ delta: vec2.optional().describe('Relative nudge [dx,dz] (e.g. a separation vector).'),+ scale: z.number().optional().describe('New uniform scale.'),+ }),+ callback: (input) => {+ const i = input as {+ target: string;+ to?: [number, number];+ delta?: [number, number];+ scale?: number;+ };+ const r = model.move(i.target, {+ ...(i.to ? { to: i.to } : {}),+ ...(i.delta ? { delta: i.delta } : {}),+ ...(i.scale != null ? { scale: i.scale } : {}),+ });+ return (r.ok ? echo(r.alias) : r) as unknown as JSONValue;+ },+ });++ const faceTool: Tool = tool({+ name: 'scene_face',+ description:+ 'Re-orient a placement: "center" faces the scene origin, "out" faces away, [x,z] faces that ' ++ 'point, or pass degrees. For a ring, "out"/"center" flips faceOut. Facing is how a scene reads ' ++ 'as intentional — point heroes at the viewer, turn supporting rows to frame them.',+ inputSchema: z.object({+ target: z.string().describe('The placement alias (or stmtId) to re-orient.'),+ face: facing.describe('Facing intent: "center" | "out" | [x,z] | degrees.'),+ }),+ callback: (input) => {+ const i = input as { target: string; face: z.infer<typeof facing> };+ const r = model.face(i.target, i.face);+ return (r.ok ? echo(r.alias) : r) as unknown as JSONValue;+ },+ });++ const groupTool: Tool = tool({+ name: 'scene_group',+ description:+ 'Bind several placements into a named group, optionally nudging (`delta`) or relocating (`to`) ' ++ 'them together — so a courtyard, a market row, or a camp moves as one unit. Returns the group ' ++ 'name and its members.',+ inputSchema: z.object({+ targets: z.array(z.string()).min(1).describe('Placement aliases (or stmtIds) to group.'),+ name: z.string().optional().describe('Group name (default group_N).'),+ delta: vec2.optional().describe('Move the whole group by [dx,dz].'),+ to: vec2.optional().describe('Move every member to [x,z].'),+ }),+ callback: (input) => {+ const i = input as {+ targets: string[];+ name?: string;+ delta?: [number, number];+ to?: [number, number];+ };+ const r = model.group(i.targets, {+ ...(i.name ? { name: i.name } : {}),+ ...(i.delta ? { delta: i.delta } : {}),+ ...(i.to ? { to: i.to } : {}),+ });+ if (!r.ok) return r as JSONValue;+ const ev = capture();+ return {+ ok: true,+ group: r.group,+ members: r.members,+ placements: ev.placements.length,+ overlaps: ev.overlaps.length,+ } as JSONValue;+ },+ });++ const removeTool: Tool = tool({+ name: 'scene_remove',+ description:+ 'Remove a placement (by alias or stmtId) from the scene — for a cluster/ring this drops the ' ++ 'whole group. Use it to declutter or swap an asset out. Returns the remaining placement count.',+ inputSchema: z.object({+ target: z.string().describe('The placement alias (or stmtId) to remove.'),+ }),+ callback: (input) => {+ const i = input as { target: string };+ const r = model.remove(i.target);+ if (!r.ok) return r as JSONValue;+ const ev = capture();+ return {+ ok: true,+ removed: r.removed,+ placements: ev.placements.length,+ overlaps: ev.overlaps.length,+ } as JSONValue;+ },+ });++ const finalizeTool: Tool = tool({+ name: 'scene_finalize',+ description:+ 'Lock in the current scene as the FINAL composition. Call this exactly once, after scene_render ' ++ 'reads as a cohesive, overlap-free, intentional scene. No argument — it finalizes exactly what ' ++ 'you have placed. Returns the final program + placement/overlap counts.',+ inputSchema: empty,+ callback: () => {+ const ev = capture();+ sink.finalized = true;+ return {+ ok: true,+ recorded: true,+ placements: ev.placements.length,+ overlaps: ev.overlaps.length,+ program: sink.program,+ } as JSONValue;+ },+ });++ return [+ listAssetsTool,+ viewTool,+ validateTool,+ renderTool,+ screenshotTool,+ layoutTool,+ placeTool,+ clusterTool,+ ringTool,+ moveTool,+ faceTool,+ groupTool,+ removeTool,+ finalizeTool,+ ];+}diff --git a/src/composer/dsl.ts b/src/composer/dsl.tsnew file mode 100644index 00000000..60f17145--- /dev/null+++ b/src/composer/dsl.ts@@ -0,0 +1,196 @@+/**+ * Composer DSL — the clean, sugared scene-authoring surface.+ *+ * `serialize(model)` projects the structured PlacementModel to the diffable scene+ * PROGRAM (the version-controlled artifact). `scene()` / `asset()` / SceneBuilder+ * are the executable sugar that program is written in: assets are bound by+ * immutable generationId, hierarchy is visible, and a one-asset move is a one-line+ * diff. Pure — no THREE, no SDK. The agent mutates the model through tools; this+ * is the human-facing projection (and a real code-authoring API for scripts).+ */+import { flatGround, type GroundSampler } from './ground';+import { type Facing, facingToRotY, groundedPos, type Vec2 } from './layout';+import {+ type Bbox,+ type ClusterArgs,+ type LayoutArgs,+ type PlaceArgs,+ type PlaceExactArgs,+ PlacementModel,+ type RingArgs,+ type Statement,+} from './model';+import type { Vec3 } from './overlap';++// ── serialize: model → program text ──────────────────────────────────────────++const q = (s: string): string => JSON.stringify(s);+const n = (x: number): string => String(Math.round(x * 100) / 100);+const vec2 = (v: Vec2): string => `[${n(v[0])}, ${n(v[1])}]`;+const vec3 = (v: Vec3): string => `[${n(v[0])}, ${n(v[1])}, ${n(v[2])}]`;+const faceLit = (f: Facing): string =>+ typeof f === 'number' ? n(f) : Array.isArray(f) ? vec2(f) : q(f);++const opts = (parts: Array<[string, string | undefined]>): string =>+ parts+ .filter((p): p is [string, string] => p[1] !== undefined)+ .map(([k, v]) => `${k}: ${v}`)+ .join(', ');++/** A valid, unique JS identifier for an asset var, derived from its name/id. */+function ident(base: string, used: Set<string>): string {+ const root =+ base+ .toLowerCase()+ .replace(/[^a-z0-9_]/g, '_')+ .replace(/^[^a-z_]+/, '') || 'asset';+ let name = root;+ let i = 2;+ while (used.has(name)) name = `${root}_${i++}`;+ used.add(name);+ return name;+}++function stmtLine(st: Statement, v: string): string {+ const roleDefault: string = st.kind === 'cluster' ? 'fill' : 'support';+ const tail: Array<[string, string | undefined]> = [+ ['scale', st.scale !== 1 ? n(st.scale) : undefined],+ ['role', st.role !== roleDefault ? q(st.role) : undefined],+ ['alias', q(st.alias)],+ ['group', st.group ? q(st.group) : undefined],+ ];+ if (st.kind === 'place') {+ if (st.exact) {+ return `s.placeExact(${v}, { ${opts([['pos', vec3(st.exact.pos)], ['rotYDeg', n(st.exact.rotYDeg)], ...tail])} });`;+ }+ return `s.place(${v}, { ${opts([['at', vec2(st.at)], ['y', st.y != null ? n(st.y) : undefined], ['face', faceLit(st.face)], ...tail])} });`;+ }+ if (st.kind === 'cluster') {+ return `s.cluster(${v}, { ${opts([['around', vec2(st.around)], ['count', String(st.count)], ['spread', n(st.spread)], ['face', faceLit(st.face)], ...tail])} });`;+ }+ return `s.ring(${v}, { ${opts([['center', vec2(st.center)], ['count', String(st.count)], ['radius', n(st.radius)], ['faceOut', st.faceOut ? 'true' : undefined], ...tail])} });`;+}++/** Project a model to its scene PROGRAM — deterministic, diffable, executable. */+export function serialize(model: PlacementModel): string {+ const j = model.toJSON();+ const byGen = new Map(j.catalog.map((e) => [e.generationId, e]));+ const varOf = new Map<string, string>();+ const usedIdents = new Set<string>();+ const assetLines: string[] = [];+ for (const st of j.statements) {+ if (varOf.has(st.generationId)) continue;+ const e = byGen.get(st.generationId);+ if (!e) continue;+ const v = ident(e.name ?? st.generationId, usedIdents);+ varOf.set(st.generationId, v);+ assetLines.push(+ `const ${v} = asset(${q(v)}, ${q(st.generationId)}, { min: ${vec3(e.bbox.min)}, max: ${vec3(e.bbox.max)} });`,+ );+ }+ const stmtLines = j.statements.map((st) =>+ stmtLine(st, varOf.get(st.generationId) ?? '_unknown'),+ );+ return [+ `// === ${j.name} — composed scene program (serialized; edit via the composer) ===`,+ `const s = scene(${q(j.name)}, { ground: flat(), seed: ${j.seed} });`,+ '',+ ...assetLines,+ '',+ ...stmtLines,+ '',+ 'export default s;',+ ].join('\n');+}++// ── builder: the executable sugar (scene/asset/...) ──────────────────────────++export interface AssetRef {+ alias: string;+ generationId: string;+ bbox: Bbox;+}++/** Bind a friendly local alias to an immutable generationId + its bbox (the+ * provenance anchor every statement carries forward). */+export function asset(alias: string, generationId: string, bbox: Bbox): AssetRef {+ return { alias, generationId, bbox };+}++export interface SceneOpts {+ ground?: GroundSampler;+ seed?: number;+}++/** Fluent wrapper over a PlacementModel — the surface the serialized program is+ * written in, and a real code-authoring API. */+export class SceneBuilder {+ readonly model: PlacementModel;++ constructor(name: string, sopts: SceneOpts = {}) {+ this.model = new PlacementModel(name, sopts);+ }++ private bind(ref: AssetRef): void {+ this.model.registerAsset({ generationId: ref.generationId, bbox: ref.bbox, name: ref.alias });+ }++ place(ref: AssetRef, p: PlaceArgs): this {+ this.bind(ref);+ this.model.addPlace(ref.generationId, { ...p, alias: p.alias ?? ref.alias });+ return this;+ }++ /** Verbatim placement (exact origin pos + Y-rotation, no grounding/recentre) — the+ * look-preserving import surface. */+ placeExact(ref: AssetRef, p: PlaceExactArgs): this {+ this.bind(ref);+ this.model.addPlaceExact(ref.generationId, { ...p, alias: p.alias ?? ref.alias });+ return this;+ }++ cluster(ref: AssetRef, p: ClusterArgs): this {+ this.bind(ref);+ this.model.addCluster(ref.generationId, p);+ return this;+ }++ ring(ref: AssetRef, p: RingArgs): this {+ this.bind(ref);+ this.model.addRing(ref.generationId, p);+ return this;+ }++ layout(refs: AssetRef[], p?: LayoutArgs): this {+ for (const r of refs) this.bind(r);+ this.model.layout(+ refs.map((r) => r.generationId),+ p,+ );+ return this;+ }++ placements(): ReturnType<PlacementModel['placements']> {+ return this.model.placements();+ }++ serialize(): string {+ return serialize(this.model);+ }+}++export function scene(name: string, sopts: SceneOpts = {}): SceneBuilder {+ return new SceneBuilder(name, sopts);+}++// ── intent sugar (re-exported under DSL names) ───────────────────────────────++/** Flat ground at `y` (the program's `flat()`). */+export const flat = flatGround;+/** Resolve a facing intent to degrees (the program's `facing()`). */+export const facing = facingToRotY;+/** Ground an XZ point for an asset (no rotation) — the program's `grounded()`.+ * `heightmap()` itself comes from the same barrel (re-exported by ground). */+export function grounded(xz: Vec2, bbox: Bbox, ground: GroundSampler, scale = 1): Vec3 {+ return groundedPos(bbox.min, bbox.max, scale, xz, 0, ground);+}diff --git a/src/composer/ground.ts b/src/composer/ground.tsnew file mode 100644index 00000000..429f5a12--- /dev/null+++ b/src/composer/ground.ts@@ -0,0 +1,20 @@+/**+ * Ground sampler — the terrain seam that keeps layout heightmap-agnostic.+ *+ * Flat today; a heightmap / heightfield implements the same `heightAt` contract+ * tomorrow and every placement drops onto the terrain with zero layout changes.+ * This is the single abstraction that stops the composer being locked to a flat+ * disc.+ */+export interface GroundSampler {+ /** World-space terrain height at (x, z). */+ heightAt(x: number, z: number): number;+}++/** Constant-height ground (the default, y = 0). */+export const flatGround = (y = 0): GroundSampler => ({ heightAt: () => y });++/** Mark a sampler as terrain — the heightmap seam. Identity today (a heightfield+ * is just a `GroundSampler`); exists so a scene program reads `heightmap(fn)`+ * symmetrically with `flat()`, and gives one place to add caching later. */+export const heightmap = (sampler: GroundSampler): GroundSampler => sampler;diff --git a/src/composer/index.ts b/src/composer/index.tsnew file mode 100644index 00000000..30580a5e--- /dev/null+++ b/src/composer/index.ts@@ -0,0 +1,12 @@+/**+ * `@kiln/engine/composer` — scene-composition primitives: overlap validation,+ * a terrain-agnostic hierarchy-aware layout engine, and the ground seam they+ * sit on. Pure and deterministic; the composer tool surface and agent build on+ * top of these.+ */+export * from './dsl';+export * from './ground';+export * from './layout';+export * from './model';+export * from './overlap';+export * from './render-port';diff --git a/src/composer/layout.ts b/src/composer/layout.tsnew file mode 100644index 00000000..0ba9a522--- /dev/null+++ b/src/composer/layout.ts@@ -0,0 +1,357 @@+/**+ * Composer layout — a terrain-agnostic, hierarchy-aware placement engine.+ *+ * Replaces the old per-district `packRings` (mechanical concentric rings,+ * footprint underestimate, no facing, flat-ground only). The substrate here is+ * deliberately NOT rigid — it is the foundation scenes grow on:+ *+ * - **Ground is a sampler** (`GroundSampler.heightAt`), not a hardcoded y=0.+ * Flat today; a heightmap implements the same seam tomorrow and every+ * placement drops onto the terrain with no layout change.+ * - **Anchors, not districts.** "4 zones + a centrepiece" is just one way to+ * build anchors (`zonedCenters`); pass any anchors, or one — rings, organic+ * clusters, street grids all sit on the same core.+ * - **Hierarchy-aware organic spacing.** Items pack big-first onto a golden-+ * angle (sunflower) lattice with circumradius min-distance — provably+ * overlap-free, but natural, not even concentric rings. Heroes claim the+ * centre and get extra breathing room; fill settles on the outskirts.+ * - **Intentional facing.** Each asset is turned to face a focal (scene centre+ * by default — kiln assets front along +X), so landmarks address the viewer+ * instead of pointing at random; fill gets a little jitter so clusters read+ * natural.+ * - **Grouping.** Items sharing a `group` cluster around that group's hero.+ *+ * Fully deterministic (seeded). The composer agent refines this baseline through+ * the tool surface; the overlap validator gates every result (`overlaps` is+ * empty by construction — global min-distance covers inter-anchor clearance).+ */+import { flatGround, type GroundSampler } from './ground';+import {+ findPlacementOverlaps,+ type OverlapViolation,+ type PlacedAsset,+ type Vec3,+} from './overlap';++export type Vec2 = [number, number];+export type ItemRole = 'hero' | 'support' | 'fill';+export type FacingPolicy = 'scene-in' | 'scene-out' | 'zone-in' | 'random' | 'none';++export interface LayoutItem {+ id: string;+ /** Asset-local bbox (e.g. generation metrics.bbox.min/max), unscaled. */+ localMin: Vec3;+ localMax: Vec3;+ /** Uniform scale applied to the placement. Default 1. */+ scale?: number;+ /** Importance tier: heroes anchor + get breathing room, fill scatters out. Default 'support'. */+ role?: ItemRole;+ /** Anchor id this item belongs to. Default: the first/only anchor. */+ zone?: string;+ /** Finer affinity — items with the same group cluster around that group's hero. */+ group?: string;+ /** Explicit facing focus (world point); overrides the policy. */+ faceTarget?: Vec2;+ /** Explicit Y rotation (degrees); skips facing entirely. */+ rotYDeg?: number;+}++export interface Anchor {+ id: string;+ center: Vec2;+ /** Facing focus for 'zone-in' items; defaults to `center`. */+ focus?: Vec2;+}++export interface LayoutOptions {+ /** Placement anchors. Default: a single anchor at the origin. */+ anchors?: Anchor[];+ /** Terrain sampler. Default: flat ground at y=0. */+ ground?: GroundSampler;+ /** Global focal point for 'scene-in' / 'scene-out' facing. Default [0,0]. */+ sceneCenter?: Vec2;+ /** Minimum clearance between footprints (world units). Default 2. */+ gap?: number;+ /** Extra breathing room when either item in a pair is a hero. Default 6. */+ heroClearance?: number;+ /** Facing policy for items without an explicit `faceTarget`/`rotYDeg`. Default 'scene-in'. */+ facing?: FacingPolicy;+ /** Deterministic seed. Default 1. */+ seed?: number;+}++export interface Placed {+ id: string;+ pos: Vec3;+ /** The XZ the asset's bbox CENTRE was placed at (the origin `pos` differs by the+ * centre offset). Lets the composer turn an auto-layout into editable per-asset+ * placements whose `at` is the centre and whose facing is the resolved angle. */+ centerXZ: Vec2;+ rotYDeg: number;+ scale: number;+}++export interface LayoutResult {+ placements: Placed[];+ /** Empty by construction; a non-empty result signals a degenerate input. */+ overlaps: OverlapViolation[];+ /** Outermost placed radius per anchor (useful for sizing the ground / camera). */+ spreadByAnchor: Record<string, number>;+}++const GOLDEN = Math.PI * (3 - Math.sqrt(5));+const TO_DEG = 180 / Math.PI;+const TO_RAD = Math.PI / 180;+const ROLE_RANK: Record<ItemRole, number> = { hero: 0, support: 1, fill: 2 };+const round1 = (n: number): number => Math.round(n * 10) / 10;++/** Deterministic PRNG (mulberry32) — no Math.random, so scenes are reproducible. */+function makeRng(seed: number): () => number {+ let s = seed >>> 0;+ return () => {+ s = (s + 0x6d2b79f5) >>> 0;+ let t = Math.imul(s ^ (s >>> 15), 1 | s);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++interface Prepared {+ item: LayoutItem;+ scale: number;+ role: ItemRole;+ /** Scaled footprint circumradius — half the XZ diagonal. Bounds the footprint+ * under any Y-rotation, so circle min-distance ⇒ AABB non-overlap. */+ footR: number;+}++function prepare(item: LayoutItem): Prepared {+ const s = item.scale ?? 1;+ const sx = Math.abs(item.localMax[0] - item.localMin[0]) * s;+ const sz = Math.abs(item.localMax[2] - item.localMin[2]) * s;+ return { item, scale: s, role: item.role ?? 'support', footR: Math.hypot(sx, sz) / 2 };+}++interface PlacedCenter {+ cx: number;+ cz: number;+ footR: number;+ hero: boolean;+}++interface PackCfg {+ spacingBase: number;+ gap: number;+ heroClearance: number;+}++/** Does a candidate centre clear every already-placed footprint circle? */+function clears(+ cx: number,+ cz: number,+ p: Prepared,+ placed: PlacedCenter[],+ cfg: PackCfg,+): boolean {+ for (const q of placed) {+ const heroRoom = p.role === 'hero' || q.hero ? cfg.heroClearance : 0;+ const need = p.footR + q.footR + cfg.gap + heroRoom;+ if (Math.hypot(cx - q.cx, cz - q.cz) < need) return false;+ }+ return true;+}++/** First open spot on a golden-angle spiral around `spiral` — organic, big-first+ * packing that is overlap-free by construction (checks ALL placed centres, so+ * it also keeps neighbouring anchors from colliding). */+function findOpenCenter(+ spiral: Vec2,+ phase: number,+ p: Prepared,+ placed: PlacedCenter[],+ cfg: PackCfg,+): Vec2 {+ const MAX_K = 4000;+ for (let k = 0; k < MAX_K; k++) {+ const r = cfg.spacingBase * Math.sqrt(k);+ const a = phase + k * GOLDEN;+ const cx = spiral[0] + r * Math.cos(a);+ const cz = spiral[1] + r * Math.sin(a);+ if (clears(cx, cz, p, placed, cfg)) return [cx, cz];+ }+ return [spiral[0] + cfg.spacingBase * Math.sqrt(MAX_K), spiral[1]];+}++interface FacingCtx {+ facing: FacingPolicy;+ sceneCenter: Vec2;+ anchor: Anchor;+ rng: () => number;+}++/** A per-asset facing INTENT (the composer DSL surface): face the scene centre,+ * face away, face a world [x,z] point, or an explicit Y-rotation in degrees. */+export type Facing = 'center' | 'out' | [number, number] | number;++/** Y-rotation (deg) so an asset's +X front points from `from` toward `target`. */+function faceAngleToward(from: Vec2, target: Vec2): number {+ const dx = target[0] - from[0];+ const dz = target[1] - from[1];+ if (Math.hypot(dx, dz) < 1e-6) return 0;+ // kiln assets face +X; local +X under Y-rotation θ points to (cosθ, -sinθ).+ return Math.atan2(-dz, dx) * TO_DEG;+}++/** Resolve a facing INTENT to a Y-rotation (deg). The composer DSL's `facing()`+ * sugar; prefer 'center'/'out' over hand-computed degrees. */+export function facingToRotY(intent: Facing, fromXZ: Vec2, sceneCenter: Vec2): number {+ if (typeof intent === 'number') return intent;+ if (Array.isArray(intent)) return faceAngleToward(fromXZ, intent);+ if (intent === 'out') {+ return faceAngleToward(fromXZ, [+ 2 * fromXZ[0] - sceneCenter[0],+ 2 * fromXZ[1] - sceneCenter[1],+ ]);+ }+ return faceAngleToward(fromXZ, sceneCenter); // 'center'+}++/** World position placing an asset's bbox CENTRE at `centerXZ` with its base on the+ * terrain — folds scale, the bbox-centre offset (so a non-centred mesh can't drift),+ * and Y-rotation. Shared by the layout engine and the composer DSL so a manual+ * placement lands exactly where auto-layout would put it. */+export function groundedPos(+ localMin: Vec3,+ localMax: Vec3,+ scale: number,+ centerXZ: Vec2,+ rotYDeg: number,+ ground: GroundSampler,+): Vec3 {+ const cx = ((localMin[0] + localMax[0]) / 2) * scale;+ const cz = ((localMin[2] + localMax[2]) / 2) * scale;+ const minY = localMin[1] * scale;+ const th = rotYDeg * TO_RAD;+ const cos = Math.cos(th);+ const sin = Math.sin(th);+ const rcx = cx * cos + cz * sin;+ const rcz = -cx * sin + cz * cos;+ return [centerXZ[0] - rcx, ground.heightAt(centerXZ[0], centerXZ[1]) - minY, centerXZ[1] - rcz];+}++/** Degrees of Y-rotation so the asset's +X front points at its focal point. */+function resolveFacing(p: Prepared, center: Vec2, ctx: FacingCtx): number {+ if (p.item.rotYDeg !== undefined) return p.item.rotYDeg;++ let target: Vec2 | null = p.item.faceTarget ?? null;+ if (!target) {+ switch (ctx.facing) {+ case 'scene-in':+ target = ctx.sceneCenter;+ break;+ case 'scene-out':+ target = [2 * center[0] - ctx.sceneCenter[0], 2 * center[1] - ctx.sceneCenter[1]];+ break;+ case 'zone-in':+ target = ctx.anchor.focus ?? ctx.anchor.center;+ break;+ case 'random':+ return ctx.rng() * 360;+ default:+ return 0;+ }+ }++ const deg = faceAngleToward(center, target);+ const jitter = p.role === 'fill' ? (ctx.rng() - 0.5) * 14 : 0; // natural, deterministic+ return deg + jitter;+}++/** Lay a set of items out across anchors: organic hierarchy-aware spacing,+ * intentional facing, group clustering, terrain-grounded, overlap-validated. */+export function layoutScene(items: LayoutItem[], opts: LayoutOptions = {}): LayoutResult {+ const ground = opts.ground ?? flatGround(0);+ const sceneCenter: Vec2 = opts.sceneCenter ?? [0, 0];+ const facing = opts.facing ?? 'scene-in';+ const rng = makeRng(opts.seed ?? 1);+ const anchors: Anchor[] = opts.anchors?.length+ ? opts.anchors+ : [{ id: '__root', center: [0, 0] }];+ const anchorById = new Map(anchors.map((a) => [a.id, a]));+ const defaultAnchor = anchors[0]!;++ const prepared = items.map(prepare);+ // Place big-first within role tiers: heroes, then support, then fill.+ const order = [...prepared].sort(+ (a, b) => ROLE_RANK[a.role] - ROLE_RANK[b.role] || b.footR - a.footR,+ );++ // Lattice density tracks the median footprint — keeps the candidate scan cheap+ // even for the largest heroes.+ const radii = prepared.map((p) => p.footR).sort((a, b) => a - b);+ const medianR = radii.length ? radii[Math.floor(radii.length / 2)]! : 2;+ const cfg: PackCfg = {+ spacingBase: Math.max(2, medianR),+ gap: opts.gap ?? 2,+ heroClearance: opts.heroClearance ?? 6,+ };++ const placedCenters: PlacedCenter[] = [];+ const groupCenter = new Map<string, Vec2>();+ const placements: Placed[] = [];+ const placedAssets: PlacedAsset[] = [];+ const spreadByAnchor: Record<string, number> = {};++ for (const p of order) {+ const anchor = (p.item.zone ? anchorById.get(p.item.zone) : undefined) ?? defaultAnchor;+ // Cluster around the group's hero if one is already down, else the anchor.+ const spiral: Vec2 =+ (p.item.group ? groupCenter.get(p.item.group) : undefined) ?? anchor.center;+ const phase = rng() * Math.PI * 2;++ const center = findOpenCenter(spiral, phase, p, placedCenters, cfg);+ placedCenters.push({ cx: center[0], cz: center[1], footR: p.footR, hero: p.role === 'hero' });+ if (p.role === 'hero') {+ const key = p.item.group ?? p.item.id;+ if (!groupCenter.has(key)) groupCenter.set(key, center);+ }++ const rotYDeg = resolveFacing(p, center, { facing, sceneCenter, anchor, rng });+ // Recentre + ground: bbox CENTRE at `center`, base on the terrain (shared helper).+ const raw = groundedPos(p.item.localMin, p.item.localMax, p.scale, center, rotYDeg, ground);+ const pos: Vec3 = [round1(raw[0]), round1(raw[1]), round1(raw[2])];++ placements.push({+ id: p.item.id,+ pos,+ centerXZ: [round1(center[0]), round1(center[1])],+ rotYDeg: Math.round(rotYDeg),+ scale: p.scale,+ });+ placedAssets.push({+ id: p.item.id,+ localMin: p.item.localMin,+ localMax: p.item.localMax,+ pos,+ rotYDeg: Math.round(rotYDeg),+ scale: p.scale,+ });++ const d = Math.hypot(center[0] - anchor.center[0], center[1] - anchor.center[1]);+ spreadByAnchor[anchor.id] = Math.max(spreadByAnchor[anchor.id] ?? 0, d);+ }++ return { placements, overlaps: findPlacementOverlaps(placedAssets), spreadByAnchor };+}++/** The default "hub + 4 satellites" anchor set — one preset on the agnostic core,+ * not a baked-in rule. `distance` is the satellite offset from the hub. */+export function zonedCenters(distance = 95): Anchor[] {+ return [+ { id: 'hub', center: [0, 0] },+ { id: 'north', center: [0, -distance] },+ { id: 'east', center: [distance, 0] },+ { id: 'south', center: [0, distance] },+ { id: 'west', center: [-distance, 0] },+ ];+}diff --git a/src/composer/model.ts b/src/composer/model.tsnew file mode 100644index 00000000..246e086f--- /dev/null+++ b/src/composer/model.ts@@ -0,0 +1,552 @@+/**+ * PlacementModel — the composer's structured source of truth.+ *+ * An ordered list of typed placement statements (place / cluster / ring) over a+ * catalog of selected assets. The agent's tools and a future in-viewport drag+ * mutate this ONE model through typed ops; `placements()` evaluates it to the+ * `Placement[]` the renderer/runtime consume, gated by `findPlacementOverlaps`;+ * `serialize()` (in dsl.ts) projects it to the clean, diffable scene program.+ *+ * Statements are addressable by a stable `alias` (or `stmtId`). `place` is one+ * asset; `cluster`/`ring` are atomic sugar that expand to N overlap-free+ * placements and serialize as a single line; `layout` is a baseline op that+ * EXPLODES into individual `place` statements so each is independently editable.+ *+ * Pure — no THREE, no @strands-agents/sdk. Wraps the engine layout primitives+ * (layoutScene / groundedPos / facingToRotY / findPlacementOverlaps). Terrain is+ * a GroundSampler, so a heightmap drops in with no model change.+ */+import { flatGround, type GroundSampler } from './ground';+import {+ type Facing,+ facingToRotY,+ type FacingPolicy,+ groundedPos,+ type LayoutItem,+ layoutScene,+ type Vec2,+ zonedCenters,+} from './layout';+import { findPlacementOverlaps, type OverlapViolation, type Vec3 } from './overlap';++export interface Bbox {+ min: Vec3;+ max: Vec3;+}++export interface CatalogEntry {+ generationId: string;+ bbox: Bbox;+ name?: string;+ tags?: string[];+}++export type Role = 'hero' | 'support' | 'fill';++/** One evaluated instance: a generation placed in the world, linked to its statement. */+export interface Placement {+ instanceId: string;+ generationId: string;+ pos: Vec3;+ rotYDeg: number;+ scale: number;+ stmtId: string;+}++export interface PlacementProvenance {+ generationId: string;+ stmtId: string;+ sourcePrompt?: string;+ parentGenerationId?: string;+}++export interface EvalResult {+ placements: Placement[];+ /** instanceId -> provenance (generationId + statement + optional source prompt). */+ provenance: Record<string, PlacementProvenance>;+ /** Empty when the scene is clean; non-empty pairs are surfaced, never dropped. */+ overlaps: OverlapViolation[];+}++interface Prov {+ sourcePrompt?: string;+ parentGenerationId?: string;+}++interface CommonStmt {+ stmtId: string;+ alias: string;+ generationId: string;+ role: Role;+ scale: number;+ group?: string;+ provenance?: Prov;+}+interface PlaceStmt extends CommonStmt {+ kind: 'place';+ at: Vec2;+ y?: number;+ face: Facing;+ /** Verbatim / origin-anchored override. When set, evaluation places the asset+ * ORIGIN at exactly `pos` with exactly `rotYDeg` — it SKIPS grounding, facing,+ * and the bbox-centre recentre that a normal `place` applies. This is what a+ * look-preserving import (a legacy `Placement[]` → model) uses so a hand- or+ * city-authored scene round-trips pixel-identically. `at`/`face` mirror it (the+ * XZ + angle) so a normal reader still sees a sensible position. */+ exact?: { pos: Vec3; rotYDeg: number };+}+interface ClusterStmt extends CommonStmt {+ kind: 'cluster';+ around: Vec2;+ count: number;+ spread: number;+ face: Facing;+}+interface RingStmt extends CommonStmt {+ kind: 'ring';+ center: Vec2;+ count: number;+ radius: number;+ faceOut: boolean;+}+export type Statement = PlaceStmt | ClusterStmt | RingStmt;++export type OpResult = { ok: true; alias: string } | { ok: false; error: string; hint?: string };++export interface SceneModelJSON {+ name: string;+ seed: number;+ catalog: CatalogEntry[];+ statements: Statement[];+}++export interface PlaceArgs {+ at: Vec2;+ y?: number;+ face?: Facing;+ scale?: number;+ role?: Role;+ group?: string;+ alias?: string;+ provenance?: Prov;+}+export interface PlaceExactArgs {+ /** Exact asset-ORIGIN world position (no grounding / recentre applied). */+ pos: Vec3;+ /** Exact Y rotation in degrees (no facing resolution applied). */+ rotYDeg: number;+ scale?: number;+ role?: Role;+ group?: string;+ alias?: string;+ provenance?: Prov;+}+export interface ClusterArgs {+ around: Vec2;+ count: number;+ spread: number;+ face?: Facing;+ scale?: number;+ role?: Role;+ group?: string;+ alias?: string;+}+export interface RingArgs {+ center: Vec2;+ count: number;+ radius: number;+ faceOut?: boolean;+ scale?: number;+ role?: Role;+ group?: string;+ alias?: string;+}+export interface LayoutArgs {+ anchor?: 'single' | 'zonedCenters';+ spacing?: number;+ facing?: FacingPolicy;+ seed?: number;+ scale?: number;+ role?: Role;+}++const SCENE_CENTER: Vec2 = [0, 0];+const r1 = (n: number): number => Math.round(n * 10) / 10;+const round3 = (v: Vec3): Vec3 => [r1(v[0]), r1(v[1]), r1(v[2])];++/** Deterministic FNV-1a hash → per-statement seed (so two clusters scatter differently). */+function stableHash(s: string): number {+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}++const notFound = (t: string): OpResult => ({+ ok: false,+ error: `no placement "${t}"`,+ hint: 'list the current placements to see their aliases',+});++export class PlacementModel {+ readonly name: string;+ readonly seed: number;+ private readonly ground: GroundSampler;+ private readonly catalog = new Map<string, CatalogEntry>();+ private readonly stmts: Statement[] = [];+ private readonly byAlias = new Map<string, Statement>();+ private seq = 0;+ private groupSeq = 0;++ constructor(+ name: string,+ opts: { ground?: GroundSampler; seed?: number; catalog?: CatalogEntry[] } = {},+ ) {+ this.name = name;+ this.seed = opts.seed ?? 1;+ this.ground = opts.ground ?? flatGround(0);+ for (const e of opts.catalog ?? []) this.registerAsset(e);+ }++ /** Bind an asset (generationId + its asset-local bbox) into the catalog. */+ registerAsset(entry: CatalogEntry): void {+ this.catalog.set(entry.generationId, entry);+ }++ /** The selectable catalog (id, name, footprint, tags). */+ catalogList(): Array<{ generationId: string; name?: string; size: Vec3; tags?: string[] }> {+ return [...this.catalog.values()].map((e) => ({+ generationId: e.generationId,+ ...(e.name ? { name: e.name } : {}),+ size: [+ r1(e.bbox.max[0] - e.bbox.min[0]),+ r1(e.bbox.max[1] - e.bbox.min[1]),+ r1(e.bbox.max[2] - e.bbox.min[2]),+ ],+ ...(e.tags ? { tags: e.tags } : {}),+ }));+ }++ private requireAsset(generationId: string): CatalogEntry {+ const e = this.catalog.get(generationId);+ if (!e) throw new Error(`unknown asset "${generationId}" — register it in the catalog first`);+ return e;+ }++ private nextStmtId(): string {+ return `s${++this.seq}`;+ }++ private baseAlias(generationId: string): string {+ return this.catalog.get(generationId)?.name ?? generationId;+ }++ private makeAlias(base: string): string {+ const slug =+ base+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '') || 'asset';+ if (!this.byAlias.has(slug)) return slug;+ let n = 2;+ while (this.byAlias.has(`${slug}_${n}`)) n++;+ return `${slug}_${n}`;+ }++ private push(st: Statement): void {+ this.stmts.push(st);+ this.byAlias.set(st.alias, st);+ }++ private resolve(target: string): Statement | undefined {+ return this.byAlias.get(target) ?? this.stmts.find((s) => s.stmtId === target);+ }++ // ── add ops (return the new alias; throw on unknown asset) ──────────────────++ addPlace(generationId: string, a: PlaceArgs): string {+ this.requireAsset(generationId);+ const alias = this.makeAlias(a.alias ?? this.baseAlias(generationId));+ this.push({+ kind: 'place',+ stmtId: this.nextStmtId(),+ alias,+ generationId,+ role: a.role ?? 'support',+ scale: a.scale ?? 1,+ at: [a.at[0], a.at[1]],+ face: a.face ?? 'center',+ ...(a.y != null ? { y: a.y } : {}),+ ...(a.group ? { group: a.group } : {}),+ ...(a.provenance ? { provenance: a.provenance } : {}),+ });+ return alias;+ }++ /** Place an asset VERBATIM at an exact origin pos + Y-rotation (no grounding,+ * facing, or bbox-centre recentre). The look-preserving import path. */+ addPlaceExact(generationId: string, a: PlaceExactArgs): string {+ this.requireAsset(generationId);+ const alias = this.makeAlias(a.alias ?? this.baseAlias(generationId));+ this.push({+ kind: 'place',+ stmtId: this.nextStmtId(),+ alias,+ generationId,+ role: a.role ?? 'support',+ scale: a.scale ?? 1,+ at: [a.pos[0], a.pos[2]],+ face: a.rotYDeg,+ exact: { pos: [a.pos[0], a.pos[1], a.pos[2]], rotYDeg: a.rotYDeg },+ ...(a.group ? { group: a.group } : {}),+ ...(a.provenance ? { provenance: a.provenance } : {}),+ });+ return alias;+ }++ addCluster(generationId: string, a: ClusterArgs): string {+ this.requireAsset(generationId);+ const alias = this.makeAlias(a.alias ?? `${this.baseAlias(generationId)}_cluster`);+ this.push({+ kind: 'cluster',+ stmtId: this.nextStmtId(),+ alias,+ generationId,+ role: a.role ?? 'fill',+ scale: a.scale ?? 1,+ around: [a.around[0], a.around[1]],+ count: Math.max(1, Math.floor(a.count)),+ spread: a.spread,+ face: a.face ?? 'center',+ ...(a.group ? { group: a.group } : {}),+ });+ return alias;+ }++ addRing(generationId: string, a: RingArgs): string {+ this.requireAsset(generationId);+ const alias = this.makeAlias(a.alias ?? `${this.baseAlias(generationId)}_ring`);+ this.push({+ kind: 'ring',+ stmtId: this.nextStmtId(),+ alias,+ generationId,+ role: a.role ?? 'support',+ scale: a.scale ?? 1,+ center: [a.center[0], a.center[1]],+ count: Math.max(1, Math.floor(a.count)),+ radius: a.radius,+ faceOut: a.faceOut ?? false,+ ...(a.group ? { group: a.group } : {}),+ });+ return alias;+ }++ /** Lay the given assets out into an overlap-free baseline, EXPLODED into one+ * editable `place` statement each (at its centre, with its resolved facing). */+ layout(generationIds: string[], a: LayoutArgs = {}): string[] {+ const zones = zonedCenters(a.spacing ?? 95);+ const items: LayoutItem[] = generationIds.map((g, i) => {+ const e = this.requireAsset(g);+ return {+ id: `${g}::${i}`,+ localMin: e.bbox.min,+ localMax: e.bbox.max,+ scale: a.scale ?? 1,+ role: a.role ?? 'support',+ ...(a.anchor === 'zonedCenters' ? { zone: zones[i % zones.length]!.id } : {}),+ };+ });+ const res = layoutScene(items, {+ ...(a.anchor === 'zonedCenters' ? { anchors: zones } : {}),+ ground: this.ground,+ facing: a.facing ?? 'scene-in',+ seed: a.seed ?? this.seed,+ });+ return res.placements.map((p) => {+ const gen = p.id.slice(0, p.id.lastIndexOf('::'));+ return this.addPlace(gen, {+ at: p.centerXZ,+ face: p.rotYDeg,+ scale: p.scale,+ role: a.role ?? 'support',+ });+ });+ }++ // ── edit ops (return ok/error; target by alias or stmtId) ───────────────────++ move(target: string, m: { to?: Vec2; delta?: Vec2; scale?: number }): OpResult {+ const st = this.resolve(target);+ if (!st) return notFound(target);+ if (m.scale != null) st.scale = m.scale;+ const apply = (cur: Vec2): Vec2 =>+ m.to ? [m.to[0], m.to[1]] : m.delta ? [cur[0] + m.delta[0], cur[1] + m.delta[1]] : cur;+ if (st.kind === 'place') st.at = apply(st.at);+ else if (st.kind === 'cluster') st.around = apply(st.around);+ else st.center = apply(st.center);+ return { ok: true, alias: st.alias };+ }++ face(target: string, intent: Facing): OpResult {+ const st = this.resolve(target);+ if (!st) return notFound(target);+ if (st.kind === 'ring') st.faceOut = intent === 'out';+ else if (st.kind === 'cluster') st.face = intent === 'out' ? 'out' : 'center';+ else st.face = intent;+ return { ok: true, alias: st.alias };+ }++ /** Bind statements into a movable group, optionally nudging them together. */+ group(+ targets: string[],+ opts: { name?: string; delta?: Vec2; to?: Vec2 } = {},+ ): { ok: true; group: string; members: string[] } | { ok: false; error: string } {+ const sts = targets.map((t) => this.resolve(t)).filter((s): s is Statement => !!s);+ if (!sts.length) return { ok: false, error: 'no targets resolved' };+ const name = opts.name ?? `group_${++this.groupSeq}`;+ for (const st of sts) st.group = name;+ if (opts.delta || opts.to) {+ for (const st of sts)+ this.move(st.alias, {+ ...(opts.to ? { to: opts.to } : {}),+ ...(opts.delta ? { delta: opts.delta } : {}),+ });+ }+ return { ok: true, group: name, members: sts.map((s) => s.alias) };+ }++ remove(+ target: string,+ ): { ok: true; removed: string; remaining: number } | { ok: false; error: string } {+ const st = this.resolve(target);+ if (!st) return { ok: false, error: `no placement "${target}"` };+ this.stmts.splice(this.stmts.indexOf(st), 1);+ this.byAlias.delete(st.alias);+ return { ok: true, removed: st.alias, remaining: this.stmts.length };+ }++ statements(): readonly Statement[] {+ return this.stmts;+ }++ // ── evaluate ────────────────────────────────────────────────────────────────++ /** Expand every statement to world placements, then gate on footprint overlap. */+ placements(): EvalResult {+ const placements: Placement[] = [];+ const provenance: Record<string, PlacementProvenance> = {};+ const add = (st: Statement, instanceId: string, pos: Vec3, rotYDeg: number): void => {+ placements.push({+ instanceId,+ generationId: st.generationId,+ pos,+ rotYDeg,+ scale: st.scale,+ stmtId: st.stmtId,+ });+ provenance[instanceId] = {+ generationId: st.generationId,+ stmtId: st.stmtId,+ ...(st.provenance ?? {}),+ };+ };++ for (const st of this.stmts) {+ const e = this.catalog.get(st.generationId);+ if (!e) continue;+ const { min, max } = e.bbox;++ if (st.kind === 'place') {+ if (st.exact) {+ // Verbatim: origin + rotation exactly as imported (no grounding / recentre /+ // rounding — preserve the source look bit-for-bit).+ add(st, st.alias, [st.exact.pos[0], st.exact.pos[1], st.exact.pos[2]], st.exact.rotYDeg);+ } else {+ const rotY = Math.round(facingToRotY(st.face, st.at, SCENE_CENTER));+ const pos = round3(groundedPos(min, max, st.scale, st.at, rotY, this.ground));+ if (st.y != null) pos[1] = r1(st.y);+ add(st, st.alias, pos, rotY);+ }+ } else if (st.kind === 'ring') {+ for (let i = 0; i < st.count; i++) {+ const ang = (i / st.count) * Math.PI * 2;+ const cx = st.center[0] + st.radius * Math.cos(ang);+ const cz = st.center[1] + st.radius * Math.sin(ang);+ const target: Vec2 = st.faceOut+ ? [2 * cx - st.center[0], 2 * cz - st.center[1]]+ : st.center;+ const rotY = Math.round(facingToRotY(target, [cx, cz], SCENE_CENTER));+ add(+ st,+ `${st.alias}#${i}`,+ round3(groundedPos(min, max, st.scale, [cx, cz], rotY, this.ground)),+ rotY,+ );+ }+ } else {+ const items: LayoutItem[] = Array.from({ length: st.count }, (_, i) => ({+ id: `${st.alias}#${i}`,+ localMin: min,+ localMax: max,+ scale: st.scale,+ role: st.role,+ }));+ const res = layoutScene(items, {+ anchors: [{ id: st.alias, center: st.around }],+ ground: this.ground,+ facing: st.face === 'out' ? 'scene-out' : 'scene-in',+ gap: Math.max(1, st.spread / Math.max(2, st.count)),+ seed: this.seed + stableHash(st.stmtId),+ });+ for (const p of res.placements) add(st, p.id, p.pos, p.rotYDeg);+ }+ }++ const overlaps = findPlacementOverlaps(+ placements.map((p) => {+ const b = this.catalog.get(p.generationId)!.bbox;+ return {+ id: p.instanceId,+ localMin: b.min,+ localMax: b.max,+ pos: p.pos,+ rotYDeg: p.rotYDeg,+ scale: p.scale,+ };+ }),+ );+ return { placements, provenance, overlaps };+ }++ // ── persistence (structured machine round-trip; serialize() is the human view) ─++ toJSON(): SceneModelJSON {+ return JSON.parse(+ JSON.stringify({+ name: this.name,+ seed: this.seed,+ catalog: [...this.catalog.values()],+ statements: this.stmts,+ }),+ );+ }++ static fromJSON(j: SceneModelJSON, ground?: GroundSampler): PlacementModel {+ const m = new PlacementModel(j.name, {+ seed: j.seed,+ catalog: j.catalog,+ ...(ground ? { ground } : {}),+ });+ let maxSeq = 0;+ for (const st of j.statements) {+ m.push(st);+ const n = Number(st.stmtId.replace(/^s/, ''));+ if (Number.isFinite(n)) maxSeq = Math.max(maxSeq, n);+ }+ m.seq = maxSeq;+ return m;+ }+}diff --git a/src/composer/overlap.ts b/src/composer/overlap.tsnew file mode 100644index 00000000..65e7ce3b--- /dev/null+++ b/src/composer/overlap.ts@@ -0,0 +1,220 @@+/**+ * Composer overlap validation — pure AABB geometry, no THREE, no I/O.+ *+ * Scenes place generated GLBs on the ground as placements (a generation id + a+ * transform: position, Y-rotation, uniform scale). The deterministic packer+ * *claims* to be overlap-free but underestimates each asset's footprint and+ * ignores the fact that a generated mesh is rarely centred on its own origin —+ * so buildings collide. This module is the ground truth that catches it:+ *+ * - `worldAabbFromLocal` folds an asset's LOCAL bbox (which carries the centre+ * offset) through uniform scale + Y-rotation + translation into a+ * world-space axis-aligned box. This is the fix for "the mesh lands offset+ * from where the packer reasoned".+ * - `findOverlaps` / `findPlacementOverlaps` report every colliding pair with a+ * penetration depth, the limiting axis, and the minimal translation vector+ * that separates them — directly consumable by a composer tool that nudges+ * things apart, and by a Bun test that fails on any overlap.+ *+ * `mode: 'footprint'` (default) ignores Y: everything sits on the same ground+ * plane, so two assets whose XZ footprints overlap visually intersect no matter+ * their heights — that is the failure the user sees. `mode: 'volume'` is the+ * full 3D check for stacked / interior composition.+ *+ * O(n^2) over placements; scenes cap at 200, so ~20k cheap pair tests — fine. A+ * uniform-grid broadphase is the obvious upgrade if a scene ever needs it.+ */++export type Vec3 = [number, number, number];++export interface Aabb {+ min: Vec3;+ max: Vec3;+}++export interface PlacedBox extends Aabb {+ /** Stable id for reporting (instanceId or asset id). */+ id: string;+}++/** A scene placement in the terms Studio already has: a local (asset-space)+ * bounding box plus the transform applied to drop it into the world. */+export interface PlacedAsset {+ id: string;+ /** Asset-local bbox (e.g. GenerationRecord.metrics.bbox.min/max), unscaled. */+ localMin: Vec3;+ localMax: Vec3;+ /** World position the asset origin is placed at. */+ pos: Vec3;+ /** Y rotation in DEGREES (kiln transforms are degrees). Default 0. */+ rotYDeg?: number;+ /** Uniform scale. Default 1. */+ scale?: number;+}++export type OverlapMode = 'footprint' | 'volume';++export interface OverlapOptions {+ /** Penetration at or below this (world units) counts as "just touching", not+ * overlapping. Default 0.01 (1cm). */+ tolerance?: number;+ /** 'footprint' ignores Y (ground-plane scenes, the default); 'volume' is full 3D. */+ mode?: OverlapMode;+}++export interface OverlapViolation {+ a: string;+ b: string;+ /** Penetration depth per axis (>=0). In 'footprint' mode the Y entry is 0. */+ penetration: Vec3;+ /** Axis of least penetration — the cheapest way to separate the pair. */+ axis: 'x' | 'y' | 'z';+ /** Minimal world translation to apply to `b` to separate it from `a` (apply+ * the negation to `a` instead). Lies along `axis`. */+ separation: Vec3;+ /** Overlap measure for ranking: footprint area (xz) or volume (xyz). */+ severity: number;+}++const DEG = Math.PI / 180;+const AXIS_NAME = ['x', 'y', 'z'] as const;+const axisIndex = (ax: 'x' | 'y' | 'z'): 0 | 1 | 2 => (ax === 'x' ? 0 : ax === 'y' ? 1 : 2);++function center(b: Aabb): Vec3 {+ return [(b.min[0] + b.max[0]) / 2, (b.min[1] + b.max[1]) / 2, (b.min[2] + b.max[2]) / 2];+}++/** Per-axis penetration depth of two AABBs: min(aMax,bMax) - max(aMin,bMin).+ * Positive ⇒ overlap on that axis; <=0 ⇒ a gap (a separating axis). */+function penetrationPerAxis(a: Aabb, b: Aabb): Vec3 {+ return [+ Math.min(a.max[0], b.max[0]) - Math.max(a.min[0], b.min[0]),+ Math.min(a.max[1], b.max[1]) - Math.max(a.min[1], b.min[1]),+ Math.min(a.max[2], b.max[2]) - Math.max(a.min[2], b.min[2]),+ ];+}++/** Test a single pair. Returns the violation (with the minimum-translation+ * separation) or null when the boxes are clear of each other. */+export function aabbOverlap(+ a: PlacedBox,+ b: PlacedBox,+ opts: OverlapOptions = {},+): OverlapViolation | null {+ const tol = opts.tolerance ?? 0.01;+ const mode = opts.mode ?? 'footprint';+ const pen = penetrationPerAxis(a, b);+ const tested: ReadonlyArray<0 | 1 | 2> = mode === 'footprint' ? [0, 2] : [0, 1, 2];++ for (const i of tested) {+ if (pen[i] <= tol) return null; // a separating axis ⇒ no overlap+ }+ // Minimum-penetration axis among the tested axes ⇒ cheapest separation (MTV).+ let mtv: 0 | 1 | 2 = 0; // x is always tested+ for (const i of tested) {+ if (pen[i] < pen[mtv]) mtv = i;+ }++ const dir = center(b)[mtv] >= center(a)[mtv] ? 1 : -1; // push b away from a+ const separation: Vec3 = [0, 0, 0];+ separation[mtv] = dir * pen[mtv];++ return {+ a: a.id,+ b: b.id,+ penetration: [pen[0], mode === 'footprint' ? 0 : pen[1], pen[2]],+ axis: AXIS_NAME[mtv],+ separation,+ severity: mode === 'footprint' ? pen[0] * pen[2] : pen[0] * pen[1] * pen[2],+ };+}++/** Every overlapping pair among `boxes`, worst (deepest) first. */+export function findOverlaps(boxes: PlacedBox[], opts: OverlapOptions = {}): OverlapViolation[] {+ const out: OverlapViolation[] = [];+ for (let i = 0; i < boxes.length; i++) {+ for (let j = i + 1; j < boxes.length; j++) {+ const v = aabbOverlap(boxes[i]!, boxes[j]!, opts);+ if (v) out.push(v);+ }+ }+ out.sort((p, q) => q.severity - p.severity);+ return out;+}++/** Cheap boolean: does any pair overlap? Short-circuits on the first hit. */+export function isOverlapFree(boxes: PlacedBox[], opts: OverlapOptions = {}): boolean {+ for (let i = 0; i < boxes.length; i++) {+ for (let j = i + 1; j < boxes.length; j++) {+ if (aabbOverlap(boxes[i]!, boxes[j]!, opts)) return false;+ }+ }+ return true;+}++/** Fold an asset's LOCAL bbox through uniform scale, Y-rotation (about the asset+ * origin — NOT the bbox centre, since generated meshes are rarely centred), and+ * translation into a world-space AABB. Captures both the centre offset and the+ * footprint growth a Y-rotation produces. */+export function worldAabbFromLocal(+ localMin: Vec3,+ localMax: Vec3,+ pos: Vec3,+ rotYDeg = 0,+ scale = 1,+): Aabb {+ // Scaled local centre + half-extents.+ const cx = ((localMin[0] + localMax[0]) / 2) * scale;+ const cy = ((localMin[1] + localMax[1]) / 2) * scale;+ const cz = ((localMin[2] + localMax[2]) / 2) * scale;+ const ex = (Math.abs(localMax[0] - localMin[0]) / 2) * scale;+ const ey = (Math.abs(localMax[1] - localMin[1]) / 2) * scale;+ const ez = (Math.abs(localMax[2] - localMin[2]) / 2) * scale;++ const th = rotYDeg * DEG;+ const cos = Math.cos(th);+ const sin = Math.sin(th);++ // Rotate the centre about the origin (three.js Y-rotation of a vector), and+ // grow the axis-aligned XZ half-extents to bound the rotated box. Y unchanged.+ const rcx = cx * cos + cz * sin;+ const rcz = -cx * sin + cz * cos;+ const rex = ex * Math.abs(cos) + ez * Math.abs(sin);+ const rez = ex * Math.abs(sin) + ez * Math.abs(cos);++ const wx = pos[0] + rcx;+ const wy = pos[1] + cy;+ const wz = pos[2] + rcz;+ return { min: [wx - rex, wy - ey, wz - rez], max: [wx + rex, wy + ey, wz + rez] };+}++/** World AABB for one placement (its local bbox through its transform). */+export function placedAssetToBox(a: PlacedAsset): PlacedBox {+ const { min, max } = worldAabbFromLocal(+ a.localMin,+ a.localMax,+ a.pos,+ a.rotYDeg ?? 0,+ a.scale ?? 1,+ );+ return { id: a.id, min, max };+}++/** Overlaps among placements expressed as local-bbox + transform. The ergonomic+ * entry for Studio's compose step and the composer's check tool. */+export function findPlacementOverlaps(+ assets: PlacedAsset[],+ opts: OverlapOptions = {},+): OverlapViolation[] {+ return findOverlaps(assets.map(placedAssetToBox), opts);+}++/** One-line-per-pair human summary for tool output / failing-test messages. */+export function summarizeOverlaps(violations: OverlapViolation[]): string {+ if (violations.length === 0) return 'No overlapping placements.';+ const lines = violations.map((v) => {+ const mag = Math.abs(v.separation[axisIndex(v.axis)]);+ return ` "${v.a}" overlaps "${v.b}" — separate by ${mag.toFixed(2)}u along ${v.axis}`;+ });+ return `${violations.length} overlapping pair(s):\n${lines.join('\n')}`;+}diff --git a/src/composer/render-port.ts b/src/composer/render-port.tsnew file mode 100644index 00000000..f300da59--- /dev/null+++ b/src/composer/render-port.ts@@ -0,0 +1,37 @@+/**+ * SceneRenderPort — the host-supplied seam that lets the composer SEE the scene+ * without the engine importing THREE. The engine defines this interface and the+ * agent tools call it; Studio implements it with real GLBs (composeSceneGLB ++ * the rasterizer). Bun tests inject a stub returning a fixed PNG.+ */+import type { Placement } from './model';++export interface SceneCamera {+ position: [number, number, number];+ target: [number, number, number];+ /** Vertical FOV in degrees. Default ~50. */+ fovDeg?: number;+}++export interface SceneRenderRequest {+ /** The evaluated scene (generationId + transform per instance). */+ placements: Placement[];+ /** Omit for the standard 3-angle grid; pass one camera for a custom shot. */+ cameras?: SceneCamera[];+ width?: number;+ height?: number;+}++export interface SceneRenderResult {+ ok: boolean;+ /** The composited grid, or the single custom-camera frame (base64 PNG). */+ pngBase64?: string;+ /** One PNG per requested camera, when more than one was passed. */+ perCameraBase64?: string[];+ tris?: number;+ error?: string;+}++/** Inject this at `runKilnComposer` call time. A build/render failure returns+ * `{ ok:false, error }` (no image) so the agent gets a fixable error. */+export type SceneRenderPort = (req: SceneRenderRequest) => Promise<SceneRenderResult>;diff --git a/src/views/index.ts b/src/views/index.tsindex 0c3ad864..4e94ec05 100644--- a/src/views/index.ts+++ b/src/views/index.ts@@ -33,6 +33,8 @@ import {export { rasterizeView, measureBounds, hideNodeInScene, SIX_VIEWS, coverage } from './raster';export type { RasterOptions, ViewSpec } from './raster';export { encodePng } from './png';+export { rasterizeComposedScene, SCENE_VIEWS } from './scene-raster';+export type { ComposedPart, ComposedSceneRasterResult } from './scene-raster';export {prepareClip,poseSceneAtTime,diff --git a/src/views/scene-raster.ts b/src/views/scene-raster.tsnew file mode 100644index 00000000..fb244d3e--- /dev/null+++ b/src/views/scene-raster.ts@@ -0,0 +1,108 @@+/**+ * Composed-scene rasterizer — the default implementation behind the composer's+ * host `SceneRenderPort` (which the engine defines in `composer/render-port.ts`+ * but does NOT implement, to stay decoupled from asset storage).+ *+ * Given a set of placed assets as { Kiln code, position, Y-rotation, scale }, it+ * executes each UNIQUE program once (cached), clones it per placement into a+ * single THREE scene, and rasterizes that scene from one or more view directions+ * into a labelled grid — the same CPU rasterizer the asset-gen six-view uses, so+ * the composer agent SEES exactly what the engine renders. No GLB round-trip and+ * no GLTFLoader (the rasterizer is duck-typed on THREE objects).+ *+ * The host wires it up: resolve each placement's generationId to its stored code,+ * then call this. Studio's `makeSceneRenderPort` is that wiring.+ */+import * as THREE from 'three';++import { executeKilnCode } from '../render';+import { encodePng } from './png';+import { rasterizeView, type ViewSpec } from './raster';++const DEG = Math.PI / 180;+const PAD = 4;+const PAD_COLOR: readonly [number, number, number] = [10, 11, 13];++/** One placed asset: its Kiln program + the world transform to instance it at. */+export interface ComposedPart {+ /** The asset's Kiln source (defines `meta` + `build()`). */+ code: string;+ /** World position [x, y, z] (kiln frame: +X forward, +Y up, +Z right). */+ pos: [number, number, number];+ /** Y-rotation in degrees. */+ rotYDeg: number;+ /** Uniform scale. */+ scale: number;+}++/** Three canonical scene angles (kiln frame): a hero 3/4, the reverse 3/4, and a+ * top-down — enough to read spacing, facing, groupings, and overlaps at a glance. */+export const SCENE_VIEWS: ViewSpec[] = [+ { name: 'Hero 3/4', dir: [0.7, 0.45, 0.7] },+ { name: 'Reverse 3/4', dir: [-0.7, 0.45, -0.7] },+ { name: 'Top', dir: [0, 1, 0.0001] },+];++export interface ComposedSceneRasterResult {+ /** The assembled grid PNG (1..N cells, ≤3 columns). */+ png: Buffer;+ width: number;+ height: number;+ /** View names in grid order (row-major). */+ views: string[];+}++/**+ * Rasterize a composed scene from each view into one labelled grid. Each unique+ * `code` is executed once and cloned per placement (shared geometry, independent+ * transform); the rasterizer frames to the whole composed scene's bounds.+ */+export async function rasterizeComposedScene(+ parts: ComposedPart[],+ opts: { views?: ViewSpec[]; size?: number } = {},+): Promise<ComposedSceneRasterResult> {+ const views = opts.views?.length ? opts.views : SCENE_VIEWS;+ const size = opts.size ?? 320;++ const group = new THREE.Group();+ const baseByCode = new Map<string, THREE.Object3D>();+ for (const part of parts) {+ let base = baseByCode.get(part.code);+ if (!base) {+ base = (await executeKilnCode(part.code)).root;+ baseByCode.set(part.code, base);+ }+ const inst = base.clone(true);+ inst.position.set(part.pos[0], part.pos[1], part.pos[2]);+ inst.rotation.set(0, part.rotYDeg * DEG, 0);+ inst.scale.setScalar(part.scale);+ group.add(inst);+ }+ group.updateMatrixWorld(true);++ const cols = Math.min(Math.max(views.length, 1), 3);+ const rows = Math.ceil(views.length / cols);+ const width = cols * size + (cols + 1) * PAD;+ const height = rows * size + (rows + 1) * PAD;+ const grid = new Uint8Array(width * height * 3);+ for (let i = 0; i < width * height; i++) {+ grid[i * 3] = PAD_COLOR[0];+ grid[i * 3 + 1] = PAD_COLOR[1];+ grid[i * 3 + 2] = PAD_COLOR[2];+ }++ for (let vi = 0; vi < views.length; vi++) {+ const cell = rasterizeView(group, views[vi]!.dir, { size });+ const col = vi % cols;+ const row = Math.floor(vi / cols);+ const x0 = PAD + col * (size + PAD);+ const y0 = PAD + row * (size + PAD);+ for (let y = 0; y < size; y++) {+ const src = y * size * 3;+ const dst = ((y0 + y) * width + x0) * 3;+ grid.set(cell.subarray(src, src + size * 3), dst);+ }+ }++ return { png: encodePng(grid, width, height), width, height, views: views.map((v) => v.name) };+}