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(views): six-grid labels + axis gnomon + 384px cells + kiln_inspect close-up tool
Matt Kissingera2274a716464
diff --git a/package.json b/package.jsonindex 8d75cb6a..04f672b4 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "@kiln/engine","private": true,- "version": "0.4.0",+ "version": "0.5.0","description": "Kiln 3D engine — text-to-GLB codegen agent loop, deterministic CPU render/rasterizer, primitive/CSG library, palette + instanceability grading, and pairwise ranking arena. Extracted from pixel-forge.","license": "MIT","author": "Matthew Kissinger",diff --git a/src/agent/run-surface.test.ts b/src/agent/run-surface.test.tsindex c364b206..2339ea17 100644--- a/src/agent/run-surface.test.ts+++ b/src/agent/run-surface.test.ts@@ -29,6 +29,7 @@ const UNIFIED = ['kiln_edit','kiln_validate','kiln_render',+ 'kiln_inspect','kiln_screenshot_animation','kiln_view_interior','kiln_finalize',@@ -53,15 +54,21 @@ const CURRENT_EDIT = [];describe('buildAgentTools', () => {- test('unified surface -> the eight buffer tools (fresh generate, empty seed)', () => {+ test('unified surface -> the nine buffer tools (fresh generate, empty seed)', () => {expect(names(buildAgentTools('unified', base, freshSinks()))).toEqual(UNIFIED);});- test('unified surface -> the same eight tools when refining (seeded buffer)', () => {+ test('unified surface -> the same nine tools when refining (seeded buffer)', () => {const opts = { ...base, existingCode: 'const meta = {};', refineMode: 'edit' as const };expect(names(buildAgentTools('unified', opts, freshSinks()))).toEqual(UNIFIED);});+ test('kiln_inspect is unified-only: absent from both current surfaces', () => {+ expect(names(buildAgentTools('current', base, freshSinks()))).not.toContain('kiln_inspect');+ const opts = { ...base, existingCode: 'const meta = {};', refineMode: 'edit' as const };+ expect(names(buildAgentTools('current', opts, freshSinks()))).not.toContain('kiln_inspect');+ });+test('current surface, fresh generate -> the five generate tools', () => {expect(names(buildAgentTools('current', base, freshSinks()))).toEqual(CURRENT_GEN);});diff --git a/src/agent/tools-unified.test.ts b/src/agent/tools-unified.test.tsindex 683a9e1a..c09dff60 100644--- a/src/agent/tools-unified.test.ts+++ b/src/agent/tools-unified.test.ts@@ -19,6 +19,17 @@ function build() {}`;+// Two named parts under one root — the shape kiln_inspect frames by name.+const TWO_PART_CODE = `+const meta = { name: 'test-hammer', category: 'prop' };+function build() {+ const root = createRoot('Hammer');+ createPart('Handle', boxGeo(0.2, 1.2, 0.2), gameMaterial('#8a5a2b'), { parent: root, position: [0, 0.6, 0] });+ createPart('Head', boxGeo(0.6, 0.3, 0.3), gameMaterial('#9aa0a6'), { parent: root, position: [0, 1.35, 0] });+ return root;+}+`;+// An enterable building: a hollow room (walls named Shell_Wall<Side>) under a// separable roof group named 'Roof' — the shape kiln_view_interior lifts.const BUILDING_CODE = `@@ -70,7 +81,7 @@ describe('KilnDraftBuffer', () => {});describe('makeKilnUnifiedTools', () => {- test('exposes exactly the eight unified tools in order (incl. the motion + interior views)', () => {+ test('exposes exactly the nine unified tools in order (incl. the close-up, motion + interior views)', () => {const sink: UnifiedSink = { edits: [] };const tools = makeKilnUnifiedTools({ sink });expect(tools.map((t) => t.name)).toEqual([@@ -79,6 +90,7 @@ describe('makeKilnUnifiedTools', () => {'kiln_edit','kiln_validate','kiln_render',+ 'kiln_inspect','kiln_screenshot_animation','kiln_view_interior','kiln_finalize',@@ -184,6 +196,54 @@ describe('makeKilnUnifiedTools', () => {expect(got).toHaveLength(0); // a failed render has no image → no candidate});+ test('kiln_inspect frames a named part: [ImageBlock, JsonBlock] and the text names part + view', async () => {+ const sink: UnifiedSink = { edits: [] };+ const tools = makeKilnUnifiedTools({ seedCode: TWO_PART_CODE, sink });+ const out = (await findTool(tools, 'kiln_inspect').invoke({ part: 'head' })) as unknown[];+ expect(Array.isArray(out)).toBe(true);+ expect(out).toHaveLength(2);+ expect(out[0]).toBeInstanceOf(ImageBlock);+ expect(out[1]).toBeInstanceOf(JsonBlock);+ const json = (out[1] as JsonBlock).json as Record<string, unknown>;+ expect(json['ok']).toBe(true);+ // createPart prefixes mesh names: 'head' resolves (case-insensitive substring)+ // to the true scene-node name, which is what the model retries with.+ expect(json['part']).toBe('Mesh_Head');+ expect(json['view']).toBe('three-quarter'); // the default camera+ expect(json['framed']).toContain('Mesh_Head');+ expect(json['framed']).toContain('three-quarter');+ expect(json['width']).toBe(512);+ expect('pngBase64' in json).toBe(false); // image stripped by the media extractor+ });++ test('kiln_inspect on an unknown part returns the part list without throwing (image-free)', async () => {+ const sink: UnifiedSink = { edits: [] };+ const tools = makeKilnUnifiedTools({ seedCode: TWO_PART_CODE, sink });+ const out = (await findTool(tools, 'kiln_inspect').invoke({ part: 'Blade' })) as {+ ok: boolean;+ error?: string;+ availableParts?: string[];+ };+ expect(Array.isArray(out)).toBe(false); // no image on a miss+ expect(out.ok).toBe(false);+ expect(out.error).toContain('Blade');+ expect(out.availableParts).toContain('Mesh_Handle');+ expect(out.availableParts).toContain('Mesh_Head');+ });++ test('kiln_inspect with no part frames the whole asset in one view', async () => {+ const sink: UnifiedSink = { edits: [] };+ const tools = makeKilnUnifiedTools({ seedCode: TWO_PART_CODE, sink });+ const out = (await findTool(tools, 'kiln_inspect').invoke({ view: 'front' })) as unknown[];+ expect(Array.isArray(out)).toBe(true);+ expect(out[0]).toBeInstanceOf(ImageBlock);+ const json = (out[1] as JsonBlock).json as Record<string, unknown>;+ expect(json['ok']).toBe(true);+ expect('part' in json).toBe(false); // nothing singled out — whole-asset framing+ expect(json['view']).toBe('front');+ expect(json['framed']).toContain('whole asset');+ });+test('kiln_view_interior returns [ImageBlock, JsonBlock] for a building buffer', async () => {const sink: UnifiedSink = { edits: [] };const tools = makeKilnUnifiedTools({ seedCode: BUILDING_CODE, sink });diff --git a/src/agent/tools.ts b/src/agent/tools.tsindex 027f87ff..98a940d6 100644--- a/src/agent/tools.ts+++ b/src/agent/tools.ts@@ -22,6 +22,7 @@ import { z } from 'zod';import {createKilnToolRegistry,+ createKilnInspectDef,createKilnRenderViewsDef,createKilnScreenshotAnimationDef,createKilnViewInteriorDef,@@ -491,6 +492,25 @@ const draftInput = z.object({.describe('The complete Kiln program (defines `meta` + `build()`, optional `animate()`).'),});+/** Schema for the buffer-aware close-up tool (omits `code` — it reads the working buffer). */+const inspectBufferInput = z.object({+ part: z+ .string()+ .optional()+ .describe(+ 'The part to frame, by node name (case-insensitive; substring match as a fallback). ' ++ 'Omit to frame the whole asset.',+ ),+ view: z+ .string()+ .optional()+ .describe('Camera angle: front, right, back, left, top, or three-quarter (default).'),+ zoom: z+ .number()+ .optional()+ .describe('Padding multiplier around the part bounds, clamped to 1-4. Default 1.2.'),+});+/*** Build the unified 6-tool surface over a working buffer seeded with `seedCode`* (empty for generate, the parent's code for refine). The buffer's live edit@@ -601,6 +621,25 @@ export function makeKilnUnifiedTools(},});+ // Buffer-aware close-up: after kiln_render flags a suspect region, frame ONE+ // view to that part's bounds for detail a grid cell cannot show.+ const inspectDef = createKilnInspectDef();+ const inspectTool: Tool = tool({+ name: 'kiln_inspect',+ description: `${inspectDef.description} Operates on your current working buffer (no code argument).`,+ inputSchema: inspectBufferInput,+ callback: async (input) => {+ const i = input as { part?: string; view?: string; zoom?: number };+ const out = await inspectDef.run({+ code: buffer.code,+ ...(i.part !== undefined ? { part: i.part } : {}),+ ...(i.view !== undefined ? { view: i.view } : {}),+ ...(i.zoom !== undefined ? { zoom: i.zoom } : {}),+ });+ return toCallbackResult(inspectDef, out);+ },+ });+// Buffer-aware motion view: after drafting/editing an animated character, SEE a// clip move (sideways walk, reverse knee, backward swing, item not tracking).const animationTool = makeBufferAnimationTool(() => buffer.code, animationDef);@@ -648,6 +687,7 @@ export function makeKilnUnifiedTools(editTool,validateTool,renderTool,+ inspectTool,animationTool,interiorTool,finalizeTool,diff --git a/src/prompt.ts b/src/prompt.tsindex df411cd3..32f675d4 100644--- a/src/prompt.ts+++ b/src/prompt.ts@@ -309,6 +309,10 @@ After kiln_render you SEE the six views (metrics ride alongside the image). Befostave assemblies (barrels, drums) must look CLOSED — daylight through thewall means staves are rotated radial instead of tangent.If any view looks wrong, fix the code (kiln_edit or kiln_draft) and re-render before finalizing.+If a view reveals a suspect REGION — a floating part, a bad joint, a wrong proportion — call+kiln_inspect with that part's name for a single framed close-up before editing; prefer it over+re-reading the whole grid for fine detail. An unresolved name returns the list of part names to+retry with.If this is an ANIMATED CHARACTER, also call kiln_screenshot_animation on your key clipsbefore finalizing — at least the walk and the main attack — from the right (side) camera,and check the MOTION (the static render cannot show it):diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 78264a26..c7de1387 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -704,6 +704,125 @@ export function createKilnViewInteriorDef(context: KilnToolContext = {}): KilnTo/** Neutral compatibility export. It never reads category from generated source. */export const kilnViewInteriorDef: KilnToolDef = createKilnViewInteriorDef();+// =============================================================================+// kiln_inspect (unified) — part-framed close-up of one suspect region+// =============================================================================++const inspectInput = z.object({+ code: z.string().describe('Kiln source code to execute and inspect.'),+ part: z+ .string()+ .optional()+ .describe(+ 'The part to frame, by node name from your program (case-insensitive; substring match as a ' ++ 'fallback). Omit to frame the whole asset.',+ ),+ view: z+ .string()+ .optional()+ .describe('Camera angle: front, right, back, left, top, or three-quarter (default).'),+ zoom: z+ .number()+ .optional()+ .describe(+ 'Padding multiplier around the part bounds, clamped to 1-4. Default 1.2; raise it to see ' ++ 'more surrounding context.',+ ),+});++export interface KilnInspectResult {+ ok: boolean;+ /** Resolved part name that was framed (absent when the whole asset was framed). */+ part?: string;+ view?: string;+ zoom?: number;+ /** One line stating what was framed and from which view. */+ framed?: string;+ width?: number;+ height?: number;+ /** The close-up PNG, base64 (image transports strip this and attach the bytes). */+ pngBase64?: string;+ /** Part names available for framing (set when the requested part was not found). */+ availableParts?: string[];+ error?: string;+}++/**+ * Execute Kiln code and render ONE view framed to a named part's world bounds+ * (the part and its descendants), so the agent can see a suspect region at+ * full-image detail instead of one grid cell. An unresolved part name is not an+ * error thrown at the loop — it comes back as { ok:false, availableParts } so+ * the model can retry by name. The views module is imported lazily (node:zlib)+ * to keep it out of the browser bundle graph.+ */+async function runInspect(input: z.infer<typeof inspectInput>): Promise<KilnInspectResult> {+ try {+ const { renderInspectView } = await import('../views/inspect');+ const { root } = await executeKilnCode(input.code);+ const r = renderInspectView(root, {+ ...(input.part !== undefined ? { part: input.part } : {}),+ ...(input.view !== undefined ? { view: input.view } : {}),+ ...(input.zoom !== undefined ? { zoom: input.zoom } : {}),+ });+ if (!r.ok) {+ return {+ ok: false,+ view: r.view,+ zoom: r.zoom,+ error: r.error,+ availableParts: r.availableParts,+ };+ }+ const framed = r.part+ ? `Framed part "${r.part}" (with its descendants) from the ${r.view} view at zoom ${r.zoom}.`+ : `Framed the whole asset from the ${r.view} view.`;+ return {+ ok: true,+ ...(r.part ? { part: r.part } : {}),+ view: r.view,+ zoom: r.zoom,+ framed,+ width: r.width,+ height: r.height,+ pngBase64: r.png.toString('base64'),+ };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}++/**+ * The unified-surface close-up tool. Exported separately and intentionally NOT+ * part of `kilnToolRegistry` (the four-tool bench baseline stays unchanged). No+ * host context: it renders pixels only — no validation or category-aware QA.+ * Shares `screenshotMedia` so image transports attach the PNG bytes and strip+ * the base64.+ */+const KILN_INSPECT_DESCRIPTION =+ 'ZOOM IN on one part: renders a single 512x512 close-up framed to the named part (the node name ' ++ 'you gave createPart, matched case-insensitively with a substring fallback) and its descendants, ' ++ 'from one camera. Use it after kiln_render reveals a suspect region — a floating part, a bad ' ++ 'joint, a wrong proportion — to see fine detail one grid cell cannot show. args: part (omit to ' ++ 'frame the whole asset in one large view), view (front/right/back/left/top/three-quarter, ' ++ 'default three-quarter), zoom (padding multiplier around the part bounds, 1 = tight crop up to ' ++ '4 = wide context, default 1.2). If the part name does not resolve you get the list of available ' ++ 'part names back — pick one and retry. Surrounding geometry stays visible and can occlude the ' ++ 'part; pick a different view if blocked. Flat-shaded CPU render; writes no files.';++/** Create the close-up inspection definition. */+export function createKilnInspectDef(): KilnToolDef {+ return {+ name: 'kiln_inspect',+ description: KILN_INSPECT_DESCRIPTION,+ inputSchema: inspectInput,+ run: async (input) => runInspect(inspectInput.parse(input)),+ media: screenshotMedia,+ };+}++/** Neutral compatibility export. It never reads category from generated source. */+export const kilnInspectDef: KilnToolDef = createKilnInspectDef();+// =============================================================================// Registry// =============================================================================diff --git a/src/views/index.ts b/src/views/index.tsindex 1a8504a1..052de651 100644--- a/src/views/index.ts+++ b/src/views/index.ts@@ -6,7 +6,9 @@* rasterizer in ./raster.ts. This is what the agent sees via the* kiln_screenshot tool and what ships as the views.png artifact.*- * Grid order (stated in tool text instead of baked-in labels):+ * Grid order (H-30: now ALSO stamped into each cell as a label + axis gnomon,+ * matching the animation/interior grids — grid-confusion literature shows+ * text-only layout descriptions silently fail):* row 1: Front, Right, Back* row 2: Left, Top, 3/4*/@@ -236,12 +238,84 @@ export interface ViewGridOptions extends RasterOptions {snapPalette?: readonly SnapPaletteSlot[];}+// H-30: kiln-frame axis gnomon colors (+X fwd red, +Y up green, +Z right blue).+const GNOMON_AXES: Array<{+ label: string;+ axis: [number, number, number];+ color: [number, number, number];+}> = [+ { label: 'X', axis: [1, 0, 0], color: [235, 80, 70] },+ { label: 'Y', axis: [0, 1, 0], color: [90, 205, 90] },+ { label: 'Z', axis: [0, 0, 1], color: [90, 145, 245] },+];++/**+ * Stamp a small world-axis gnomon into a rasterized cell (bottom-left corner),+ * using the SAME camera basis as rasterizeView so the arrows are exact+ * (3DAxisPrompt: ticked/annotated axes measurably improve VLM 3D localization).+ * Axes nearly perpendicular to the image plane (projected length < 0.25) are+ * skipped — only in-plane axes disambiguate a view.+ */+export function stampAxisGnomon(rgb: Uint8Array, size: number, viewDir: readonly number[]): void {+ // rasterizeView's basis, duplicated deliberately (raster.ts keeps it private).+ const zl = Math.hypot(viewDir[0]!, viewDir[1]!, viewDir[2]!) || 1;+ const z = [viewDir[0]! / zl, viewDir[1]! / zl, viewDir[2]! / zl] as const;+ const up = Math.abs(z[1]) > 0.99 ? ([0, 0, -1] as const) : ([0, 1, 0] as const);+ const cx = [+ up[1] * z[2] - up[2] * z[1],+ up[2] * z[0] - up[0] * z[2],+ up[0] * z[1] - up[1] * z[0],+ ];+ const xl = Math.hypot(cx[0]!, cx[1]!, cx[2]!) || 1;+ const bx = [cx[0]! / xl, cx[1]! / xl, cx[2]! / xl] as const;+ const by = [+ z[1] * bx[2] - z[2] * bx[1],+ z[2] * bx[0] - z[0] * bx[2],+ z[0] * bx[1] - z[1] * bx[0],+ ] as const;++ const len = Math.max(12, Math.round(size * 0.055));+ // Inset the origin by the arrow length so leftward/downward projections+ // (e.g. +Z in the Front view) aren't clipped at the cell edge.+ const ox = len + 10;+ const oy = size - len - 10;+ for (const { label, axis, color } of GNOMON_AXES) {+ const dx = axis[0] * bx[0] + axis[1] * bx[1] + axis[2] * bx[2];+ const dy = axis[0] * by[0] + axis[1] * by[1] + axis[2] * by[2];+ if (Math.hypot(dx, dy) < 0.25) continue;+ const ex = ox + dx * len;+ const ey = oy - dy * len; // screen y is flipped vs the camera's up+ const steps = Math.ceil(Math.hypot(ex - ox, ey - oy));+ for (let s = 0; s <= steps; s++) {+ const px = Math.round(ox + ((ex - ox) * s) / steps);+ const py = Math.round(oy + ((ey - oy) * s) / steps);+ for (let ty = 0; ty < 2; ty++) {+ for (let tx = 0; tx < 2; tx++) {+ const x = px + tx;+ const y = py + ty;+ if (x < 0 || y < 0 || x >= size || y >= size) continue;+ const p = (y * size + x) * 3;+ rgb[p] = color[0];+ rgb[p + 1] = color[1];+ rgb[p + 2] = color[2];+ }+ }+ }+ stampLabel(rgb, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);+ }+}+/** Render a (possibly sandbox-created) Three.js scene root into the 3x2 grid. */export async function renderViewGrid(root: unknown,opts: ViewGridOptions = {},): Promise<ViewGridResult> {- const size = opts.size ?? 256;+ // H-31: 384px cells (was 256). Measured input-image cost of the full grid:+ // Anthropic ~w*h/750 tokens => 1168x780 ≈ 1,215 tok (vs 784x524 ≈ 548) —+ // negligible against 32-64K reasoning budgets; 512 would double it again for+ // marginal legibility gain at typical asset scales. Candidate thumbnails+ // downscale separately (Studio thumbnailFor), unaffected.+ const size = opts.size ?? 384;const views = opts.views ?? SIX_VIEWS;if (opts.snapPalette?.length) snapSceneToPalette(root, opts.snapPalette);const cols = 3;@@ -256,8 +330,13 @@ export async function renderViewGrid(grid[i * 3 + 2] = PAD_COLOR[2];}+ const labelScale = Math.max(2, Math.round(size / 96));for (let vi = 0; vi < views.length; vi++) {const cell = rasterizeView(root, views[vi]!.dir, { size, backfaceCull: opts.backfaceCull });+ // H-30: stamp the view name + axis gnomon into the cell (small, corner-+ // anchored, away from the centered silhouette — SeeAct caveat).+ stampLabel(cell, size, size, labelScale, labelScale, views[vi]!.name, labelScale);+ stampAxisGnomon(cell, size, views[vi]!.dir);const col = vi % cols;const row = Math.floor(vi / cols);const x0 = PAD + col * (size + PAD);diff --git a/src/views/inspect.ts b/src/views/inspect.tsnew file mode 100644index 00000000..9f041d90--- /dev/null+++ b/src/views/inspect.ts@@ -0,0 +1,188 @@+/**+ * Part-framed close-up rendering for the Kiln vision loop (kiln_inspect).+ *+ * Renders ONE orthographic view of an executed scene, framed to a named part's+ * world bounds (the part and its descendants) instead of the whole asset, so+ * the agent can inspect a suspect region — a joint, a contact point, a+ * proportion — at full-image detail instead of one grid cell. Part selection is+ * name-driven by design (the model authored the names via createPart), NOT a+ * free camera: an unresolved name comes back with the list of available part+ * names so the model can retry. Surrounding geometry stays visible (and may+ * occlude the part from some angles), matching the diagnostic views'+ * focus-bounds framing model (see ./diagnostic.ts).+ */++import { rasterizeView, measureBounds } from './raster';+import { encodePng } from './png';++/** Square close-up size in pixels — one big view, not a grid cell. */+export const INSPECT_SIZE = 512;+export const INSPECT_DEFAULT_ZOOM = 1.2;+export const INSPECT_MIN_ZOOM = 1;+export const INSPECT_MAX_ZOOM = 4;+/** Cap on the part-name listing returned for an unresolved part. */+export const INSPECT_MAX_PART_NAMES = 40;++/** Camera names accepted by kiln_inspect (same directions as the six-view grid). */+const INSPECT_CAMERAS: Record<string, [number, number, number]> = {+ front: [1, 0, 0],+ right: [0, 0, 1],+ back: [-1, 0, 0],+ left: [0, 0, -1],+ top: [0, 1, 0.0001],+ 'three-quarter': [0.7, 0.5, 0.7],+};++/** Minimal duck-typed view of a (possibly cross-realm) scene node. */+interface DuckNamedNode {+ name?: string;+ updateMatrixWorld?(force?: boolean): void;+ traverse?(cb: (obj: unknown) => void): void;+}++export interface InspectViewOptions {+ /** Part to frame, by node name (case-insensitive exact match, then substring).+ * Omit to frame the whole asset. */+ part?: string;+ /** Camera angle: front, right, back, left, top, or three-quarter (default).+ * Unknown names fall back to three-quarter. */+ view?: string;+ /** Padding multiplier around the framed bounds, clamped to 1..4. Default 1.2. */+ zoom?: number;+ /** Square output size in pixels. Default {@link INSPECT_SIZE}. */+ size?: number;+}++export type InspectViewResult =+ | {+ ok: true;+ /** Resolved node name that was framed (absent when the whole asset was framed). */+ part?: string;+ /** Resolved camera name. */+ view: string;+ /** Effective (clamped) padding multiplier. */+ zoom: number;+ width: number;+ height: number;+ png: Buffer;+ }+ | {+ ok: false;+ view: string;+ zoom: number;+ error: string;+ /** Named nodes available for framing (deduped, scene order, capped). */+ availableParts: string[];+ };++/** Named scene nodes in traversal (scene) order, deduped, capped. */+export function listPartNames(root: unknown, cap = INSPECT_MAX_PART_NAMES): string[] {+ const names: string[] = [];+ const seen = new Set<string>();+ (root as DuckNamedNode).traverse?.((obj) => {+ const name = (obj as DuckNamedNode).name?.trim();+ if (!name || seen.has(name) || names.length >= cap) return;+ seen.add(name);+ names.push(name);+ });+ return names;+}++/** First node whose name matches `part` case-insensitively — exact before substring. */+function findPartNode(root: unknown, part: string): DuckNamedNode | undefined {+ const query = part.trim().toLowerCase();+ if (!query) return undefined;+ let exact: DuckNamedNode | undefined;+ let partial: DuckNamedNode | undefined;+ (root as DuckNamedNode).traverse?.((obj) => {+ const node = obj as DuckNamedNode;+ const name = node.name?.trim().toLowerCase();+ if (!name) return;+ if (!exact && name === query) exact = node;+ else if (!partial && name.includes(query)) partial = node;+ });+ return exact ?? partial;+}++type Bounds = { min: [number, number, number]; max: [number, number, number] };++/** Grow a bounds box about its center by `factor` (the zoom padding). */+function expandBounds(b: Bounds, factor: number): Bounds {+ const min: [number, number, number] = [0, 0, 0];+ const max: [number, number, number] = [0, 0, 0];+ for (let a = 0; a < 3; a++) {+ const center = (b.min[a]! + b.max[a]!) / 2;+ const half = ((b.max[a]! - b.min[a]!) / 2) * factor;+ min[a] = center - half;+ max[a] = center + half;+ }+ return { min, max };+}++/** The all-zero sentinel measureBounds returns for a triangle-free subtree. */+function isEmptyBounds(b: Bounds): boolean {+ return b.min.every((v) => v === 0) && b.max.every((v) => v === 0);+}++/**+ * Render one close-up view framed to a named part's world bounds (or the whole+ * asset when no part is given). Never throws on a bad part name — that comes+ * back as { ok:false, availableParts } so the agent loop can retry by name.+ */+export function renderInspectView(root: unknown, opts: InspectViewOptions = {}): InspectViewResult {+ const size = opts.size ?? INSPECT_SIZE;+ const viewKey = (opts.view ?? 'three-quarter').trim().toLowerCase();+ const view = viewKey in INSPECT_CAMERAS ? viewKey : 'three-quarter';+ const zoom = Math.min(+ INSPECT_MAX_ZOOM,+ Math.max(INSPECT_MIN_ZOOM, opts.zoom ?? INSPECT_DEFAULT_ZOOM),+ );++ // World matrices must be current before measuring a subtree in isolation+ // (measureBounds on a child composes from its parent's matrixWorld).+ (root as DuckNamedNode).updateMatrixWorld?.(true);++ let part: string | undefined;+ let bounds: Bounds;+ const requested = opts.part?.trim();+ if (requested) {+ const node = findPartNode(root, requested);+ if (!node) {+ return {+ ok: false,+ view,+ zoom,+ error: `no part named "${requested}" in the scene`,+ availableParts: listPartNames(root),+ };+ }+ const b = measureBounds(node);+ if (isEmptyBounds(b)) {+ return {+ ok: false,+ view,+ zoom,+ error: `part "${node.name}" has no visible geometry to frame`,+ availableParts: listPartNames(root),+ };+ }+ part = node.name!.trim();+ bounds = b;+ } else {+ bounds = measureBounds(root);+ }++ const rgb = rasterizeView(root, INSPECT_CAMERAS[view]!, {+ size,+ frameBounds: expandBounds(bounds, zoom),+ });+ return {+ ok: true,+ ...(part ? { part } : {}),+ view,+ zoom,+ width: size,+ height: size,+ png: encodePng(rgb, size, size),+ };+}diff --git a/src/views/pose.ts b/src/views/pose.tsindex d52c7a2b..8484511f 100644--- a/src/views/pose.ts+++ b/src/views/pose.ts@@ -260,7 +260,10 @@ export function planFrameTimes(duration: number, count: number): number[] {// Tiny bitmap label stamp (annotate each frame with its phase)// =============================================================================-// 3x5 glyphs (msb = leftmost column), only the chars the phase labels need.+// 3x5 glyphs (msb = leftmost column). Digits + % for phase labels; H-30 added+// the uppercase alphabet so view-name labels (FRONT/.../3/4, Eye-level, gnomon+// axis letters) render as real text — letters previously fell through to the+// blank space glyph, leaving unreadable backdrop boxes.const GLYPHS: Record<string, number[]> = {'0': [0b111, 0b101, 0b101, 0b101, 0b111],'1': [0b010, 0b110, 0b010, 0b010, 0b111],@@ -274,6 +277,35 @@ const GLYPHS: Record<string, number[]> = {'9': [0b111, 0b101, 0b111, 0b001, 0b111],'%': [0b101, 0b001, 0b010, 0b100, 0b101],' ': [0, 0, 0, 0, 0],+ A: [0b010, 0b101, 0b111, 0b101, 0b101],+ B: [0b110, 0b101, 0b110, 0b101, 0b110],+ C: [0b011, 0b100, 0b100, 0b100, 0b011],+ D: [0b110, 0b101, 0b101, 0b101, 0b110],+ E: [0b111, 0b100, 0b110, 0b100, 0b111],+ F: [0b111, 0b100, 0b110, 0b100, 0b100],+ G: [0b011, 0b100, 0b101, 0b101, 0b011],+ H: [0b101, 0b101, 0b111, 0b101, 0b101],+ I: [0b111, 0b010, 0b010, 0b010, 0b111],+ J: [0b001, 0b001, 0b001, 0b101, 0b010],+ K: [0b101, 0b101, 0b110, 0b101, 0b101],+ L: [0b100, 0b100, 0b100, 0b100, 0b111],+ M: [0b101, 0b111, 0b111, 0b101, 0b101],+ N: [0b101, 0b111, 0b111, 0b111, 0b101],+ O: [0b010, 0b101, 0b101, 0b101, 0b010],+ P: [0b110, 0b101, 0b110, 0b100, 0b100],+ Q: [0b010, 0b101, 0b101, 0b010, 0b001],+ R: [0b110, 0b101, 0b110, 0b101, 0b101],+ S: [0b011, 0b100, 0b010, 0b001, 0b110],+ T: [0b111, 0b010, 0b010, 0b010, 0b010],+ U: [0b101, 0b101, 0b101, 0b101, 0b111],+ V: [0b101, 0b101, 0b101, 0b101, 0b010],+ W: [0b101, 0b101, 0b101, 0b111, 0b101],+ X: [0b101, 0b101, 0b010, 0b101, 0b101],+ Y: [0b101, 0b101, 0b010, 0b010, 0b010],+ Z: [0b111, 0b001, 0b010, 0b100, 0b111],+ '/': [0b001, 0b001, 0b010, 0b100, 0b100],+ '-': [0b000, 0b000, 0b111, 0b000, 0b000],+ '.': [0b000, 0b000, 0b000, 0b000, 0b010],};const LABEL_FG: [number, number, number] = [255, 224, 64]; // amber, reads on dark + lit faces@@ -314,7 +346,7 @@ export function stampLabel(// Glyphs.let cx = x0 + pad;const cy = y0 + pad;- for (const ch of text) {+ for (const ch of text.toUpperCase()) {const glyph = GLYPHS[ch] ?? GLYPHS[' ']!;for (let row = 0; row < 5; row++) {const bits = glyph[row]!;