Skip to content

armgit / kiln

Public Imported from GitHub
0

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.

feat(kiln): animation-feedback tool + character spatial-fix (3-leg)

Matt Kissingerb3b89b88b76e
diff --git a/agent/run-surface.test.ts b/agent/run-surface.test.ts
index c470eb8a..31961155 100644
--- a/agent/run-surface.test.ts
+++ b/agent/run-surface.test.ts
@@ -27,8 +27,23 @@ function freshSinks() {
const base: ToolBuildOptions = {};
const names = (tools: ReturnType<typeof buildAgentTools>) => tools.map((t) => t.name);
-const UNIFIED = ['kiln_draft', 'kiln_view', 'kiln_edit', 'kiln_validate', 'kiln_render', 'kiln_finalize'];
-const CURRENT_GEN = ['kiln_list_primitives', 'kiln_validate', 'kiln_render', 'kiln_screenshot', 'kiln_submit'];
+const UNIFIED = [
+ 'kiln_draft',
+ 'kiln_view',
+ 'kiln_edit',
+ 'kiln_validate',
+ 'kiln_render',
+ 'kiln_screenshot_animation',
+ 'kiln_finalize',
+];
+const CURRENT_GEN = [
+ 'kiln_list_primitives',
+ 'kiln_validate',
+ 'kiln_render',
+ 'kiln_screenshot',
+ 'kiln_screenshot_animation',
+ 'kiln_submit',
+];
const CURRENT_EDIT = [
'kiln_list_primitives',
'kiln_view',
@@ -36,6 +51,7 @@ const CURRENT_EDIT = [
'kiln_validate',
'kiln_render',
'kiln_screenshot',
+ 'kiln_screenshot_animation',
'kiln_submit',
];
diff --git a/agent/tools-edit.test.ts b/agent/tools-edit.test.ts
index e23738dd..ef0da633 100644
--- a/agent/tools-edit.test.ts
+++ b/agent/tools-edit.test.ts
@@ -89,7 +89,7 @@ test('view returns the raw buffer and a line count that tracks edits', () => {
expect(buf.view().lines).toBe(buf.code.split('\n').length);
});
-test('makeKilnEditTools exposes the seven edit-mode tools and wires the edit trace', () => {
+test('makeKilnEditTools exposes the eight edit-mode tools and wires the edit trace', () => {
const sink: EditSink = { edits: [] };
const tools = makeKilnEditTools({ seedCode: SEED, sink });
expect(tools.map((t) => t.name)).toEqual([
@@ -99,6 +99,7 @@ test('makeKilnEditTools exposes the seven edit-mode tools and wires the edit tra
'kiln_validate',
'kiln_render',
'kiln_screenshot',
+ 'kiln_screenshot_animation',
'kiln_submit',
]);
// The sink's edit trace is the buffer's live array (shared reference).
diff --git a/agent/tools-media.test.ts b/agent/tools-media.test.ts
index 172abeef..1709142b 100644
--- a/agent/tools-media.test.ts
+++ b/agent/tools-media.test.ts
@@ -25,7 +25,7 @@ function findTool(tools: ReturnType<typeof makeKilnTools>, name: string) {
}
describe('makeKilnTools media handling', () => {
- test('exposes the four registry tools plus kiln_submit', () => {
+ test('exposes the four registry tools plus the animation view and kiln_submit', () => {
const sink: SubmitSink = {};
const tools = makeKilnTools(sink);
expect(tools.map((t) => t.name)).toEqual([
@@ -33,6 +33,7 @@ describe('makeKilnTools media handling', () => {
'kiln_validate',
'kiln_render',
'kiln_screenshot',
+ 'kiln_screenshot_animation',
'kiln_submit',
]);
});
diff --git a/agent/tools-unified.test.ts b/agent/tools-unified.test.ts
index 0977de86..cba60e2d 100644
--- a/agent/tools-unified.test.ts
+++ b/agent/tools-unified.test.ts
@@ -61,7 +61,7 @@ describe('KilnDraftBuffer', () => {
});
describe('makeKilnUnifiedTools', () => {
- test('exposes exactly the six unified tools in order', () => {
+ test('exposes exactly the seven unified tools in order (incl. the animation view)', () => {
const sink: UnifiedSink = { edits: [] };
const tools = makeKilnUnifiedTools({ sink });
expect(tools.map((t) => t.name)).toEqual([
@@ -70,9 +70,11 @@ describe('makeKilnUnifiedTools', () => {
'kiln_edit',
'kiln_validate',
'kiln_render',
+ 'kiln_screenshot_animation',
'kiln_finalize',
]);
- // No legacy verbs leak into the unified surface.
+ // No legacy verbs leak into the unified surface (the static screenshot collapsed
+ // into kiln_render; only the dedicated motion view kiln_screenshot_animation is added).
expect(tools.map((t) => t.name)).not.toContain('kiln_list_primitives');
expect(tools.map((t) => t.name)).not.toContain('kiln_screenshot');
expect(tools.map((t) => t.name)).not.toContain('kiln_submit');
diff --git a/agent/tools.ts b/agent/tools.ts
index 116e755b..1a72f5cb 100644
--- a/agent/tools.ts
+++ b/agent/tools.ts
@@ -20,7 +20,7 @@
import { tool, ImageBlock, JsonBlock, type Tool, type JSONValue } from '@strands-agents/sdk';
import { z } from 'zod';
-import { kilnToolRegistry, kilnRenderViewsDef } from '../tools/registry';
+import { kilnToolRegistry, kilnRenderViewsDef, kilnScreenshotAnimationDef } from '../tools/registry';
/** Name of the terminal tool the agent calls to record its final program. */
export const KILN_SUBMIT_TOOL_NAME = 'kiln_submit';
@@ -43,14 +43,23 @@ const submitInput = z.object({
});
/**
- * Convert a registry `run()` output into the tool-callback return value. Defs
- * with a `media` extractor (kiln_screenshot) return [ImageBlock, JsonBlock] so
- * the model literally sees the rendered views; everything else passes the JSON
- * output through unchanged. The array of content blocks is a valid (if untyped)
- * Strands callback return — the SDK's tool-result coercion passes block arrays
- * through as-is — so it is cast past JSONValue.
+ * Convert a registry `run()` output into the tool-callback return value. Defs with
+ * a `mediaMulti` extractor (kiln_screenshot_animation in perFrame mode) return
+ * [ImageBlock×N, JsonBlock]; defs with a `media` extractor (kiln_screenshot, the
+ * animation grid) return [ImageBlock, JsonBlock] so the model literally sees the
+ * render; everything else passes the JSON output through unchanged. The array of
+ * content blocks is a valid (if untyped) Strands callback return — the SDK's
+ * tool-result coercion passes block arrays through as-is — so it is cast past
+ * JSONValue.
*/
function toCallbackResult(def: (typeof kilnToolRegistry)[number], output: unknown): JSONValue {
+ const multi = def.mediaMulti?.(output);
+ if (multi) {
+ return [
+ ...multi.pngs.map((png) => new ImageBlock({ format: 'png', source: { bytes: png } })),
+ new JsonBlock({ json: multi.json as JSONValue }),
+ ] as unknown as JSONValue;
+ }
const media = def.media?.(output);
if (media) {
return [
@@ -61,6 +70,40 @@ function toCallbackResult(def: (typeof kilnToolRegistry)[number], output: unknow
return output as JSONValue;
}
+/** Schema for the buffer-aware animation tool (omits `code` — it reads the working
+ * buffer). Used by the edit + unified refine surfaces. */
+const animationBufferInput = z.object({
+ clip: z.string().describe('The animation clip to view, by name (e.g. "walk", "attack").'),
+ camera: z
+ .string()
+ .optional()
+ .describe('Camera angle: right (default), front, back, left, top, or three-quarter.'),
+ perFrame: z.boolean().optional().describe('Return separate high-res frames instead of one grid. Default false.'),
+});
+
+/** Build a buffer-aware kiln_screenshot_animation tool that runs against `getCode()`
+ * (the working buffer) instead of a `code` argument. Same behavior as the registry
+ * def otherwise; image transports attach the frame(s) via toCallbackResult. */
+function makeBufferAnimationTool(getCode: () => string): Tool {
+ return tool({
+ name: kilnScreenshotAnimationDef.name,
+ description: `${kilnScreenshotAnimationDef.description} Operates on your current working buffer (omit code).`,
+ inputSchema: animationBufferInput,
+ callback: async (input) => {
+ const i = input as { clip: string; camera?: string; perFrame?: boolean };
+ return toCallbackResult(
+ kilnScreenshotAnimationDef,
+ await kilnScreenshotAnimationDef.run({
+ code: getCode(),
+ clip: i.clip,
+ ...(i.camera ? { camera: i.camera } : {}),
+ ...(i.perFrame ? { perFrame: true } : {}),
+ }),
+ );
+ },
+ });
+}
+
function toStrandsTool(def: (typeof kilnToolRegistry)[number]): Tool {
return tool({
name: def.name,
@@ -79,6 +122,9 @@ function toStrandsTool(def: (typeof kilnToolRegistry)[number]): Tool {
*/
export function makeKilnTools(sink: SubmitSink): Tool[] {
const kilnTools = kilnToolRegistry.map(toStrandsTool);
+ // kiln_screenshot_animation rides alongside the four registry tools (it takes a
+ // `code` arg like them) so a from-scratch animated build can SEE its motion.
+ const animationTool = toStrandsTool(kilnScreenshotAnimationDef);
const submitTool: Tool = tool({
name: KILN_SUBMIT_TOOL_NAME,
description:
@@ -91,7 +137,7 @@ export function makeKilnTools(sink: SubmitSink): Tool[] {
return { ok: true, recorded: true, bytes: input.code.length };
},
});
- return [...kilnTools, submitTool];
+ return [...kilnTools, animationTool, submitTool];
}
// =============================================================================
@@ -332,6 +378,10 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
),
});
+ // Buffer-aware motion view: a refine that touches an animated character can SEE
+ // the clip move and confirm the edit didn't break it.
+ const animationTool = makeBufferAnimationTool(() => buffer.code);
+
const submitTool: Tool = tool({
name: KILN_SUBMIT_TOOL_NAME,
description:
@@ -346,7 +396,7 @@ export function makeKilnEditTools(opts: { seedCode: string; sink: EditSink }): T
},
});
- return [listTool, viewTool, editTool, validateTool, renderTool, screenshotTool, submitTool];
+ return [listTool, viewTool, editTool, validateTool, renderTool, screenshotTool, animationTool, submitTool];
}
// =============================================================================
@@ -466,6 +516,10 @@ export function makeKilnUnifiedTools(opts: { seedCode?: string; sink: UnifiedSin
toCallbackResult(kilnRenderViewsDef, await kilnRenderViewsDef.run({ code: buffer.code })),
});
+ // 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);
+
const finalizeTool: Tool = tool({
name: 'kiln_finalize',
description:
@@ -480,5 +534,5 @@ export function makeKilnUnifiedTools(opts: { seedCode?: string; sink: UnifiedSin
},
});
- return [draftTool, viewTool, editTool, validateTool, renderTool, finalizeTool];
+ return [draftTool, viewTool, editTool, validateTool, renderTool, animationTool, finalizeTool];
}
diff --git a/prompt.ts b/prompt.ts
index 8bbdfc67..42430c77 100644
--- a/prompt.ts
+++ b/prompt.ts
@@ -260,6 +260,17 @@ Before kiln_submit, call kiln_screenshot and check each view deliberately:
stave assemblies (barrels, drums) must look CLOSED — daylight through the
wall means staves are rotated radial instead of tangent.
If any view looks wrong, fix the code and re-screenshot before submitting.
+If this is an ANIMATED CHARACTER, also call kiln_screenshot_animation on your key clips
+before submitting — at least the walk and the main attack — from the right (side) camera,
+and check the MOTION (a static screenshot cannot):
+- Walk: legs swing forward and back in the side view (one forward while the other is back),
+ feet stepping; the body must NOT slide or sway sideways. Knees bend so the lower leg goes
+ BACK behind the thigh, never forward.
+- Attack/strike: swings down and FORWARD through the front and finishes in front — never
+ winds up or ends BEHIND the back; a held weapon stays in the hand and follows the arc.
+- Block/guard: the shield or arm comes UP toward the front — the body does not step backward.
+If unresolvedTracks comes back non-empty, the clip is frozen because a track targets a joint
+that doesn't exist — fix the joint name. Fix any motion defect and screenshot the clip again.
</visual-qa>`;
/**
@@ -288,6 +299,17 @@ After kiln_render you SEE the six views (metrics ride alongside the image). Befo
stave assemblies (barrels, drums) must look CLOSED — daylight through the
wall 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 this is an ANIMATED CHARACTER, also call kiln_screenshot_animation on your key clips
+before finalizing — at least the walk and the main attack — from the right (side) camera,
+and check the MOTION (the static render cannot show it):
+- Walk: legs swing forward and back in the side view (one forward while the other is back),
+ feet stepping; the body must NOT slide or sway sideways. Knees bend so the lower leg goes
+ BACK behind the thigh, never forward.
+- Attack/strike: swings down and FORWARD through the front and finishes in front — never
+ winds up or ends BEHIND the back; a held weapon stays in the hand and follows the arc.
+- Block/guard: the shield or arm comes UP toward the front — the body does not step backward.
+If unresolvedTracks comes back non-empty, the clip is frozen because a track targets a joint
+that doesn't exist — fix the joint name. Fix any motion defect and re-render the clip again.
</visual-qa>`;
export const KILN_EXAMPLES = `<example name="animated-chest">
diff --git a/tools/__tests__/registry-animation.test.ts b/tools/__tests__/registry-animation.test.ts
new file mode 100644
index 00000000..d4adaa2c
--- /dev/null
+++ b/tools/__tests__/registry-animation.test.ts
@@ -0,0 +1,87 @@
+/**
+ * kiln_screenshot_animation registry def: the run() contract (grid vs perFrame),
+ * the media/mediaMulti extractors (PNG bytes out, base64 stripped from JSON), and
+ * the image-free failure path. Mirrors registry-screenshot.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+
+import {
+ kilnScreenshotAnimationDef,
+ screenshotAnimationMedia,
+ screenshotAnimationMediaMulti,
+ type KilnScreenshotAnimationResult,
+} from '../registry';
+
+const WALKER = `
+const meta = { name: 'walker', category: 'character' };
+function build() {
+ const root = createRoot('Root');
+ const hips = createPivot('Hips', [0, 1, 0], root);
+ createPart('Pelvis', boxGeo(0.4, 0.3, 0.3), gameMaterial('#888888'), { parent: hips });
+ const legL = createPivot('LegL', [0, 0, 0.12], hips);
+ createPart('LegLMesh', boxGeo(0.15, 0.9, 0.15), gameMaterial('#444444'), { parent: legL, position: [0, -0.45, 0] });
+ return root;
+}
+function animate(root) {
+ return [createClip('walk', 1, [
+ rotationTrack('Joint_LegL', [
+ { time: 0, rotation: [0, 0, 35] }, { time: 0.5, rotation: [0, 0, -35] }, { time: 1, rotation: [0, 0, 35] },
+ ]),
+ ])];
+}
+`;
+
+describe('kilnScreenshotAnimationDef', () => {
+ test('grid mode: returns metrics + a base64 grid PNG', async () => {
+ const out = (await kilnScreenshotAnimationDef.run({ code: WALKER, clip: 'walk' })) as KilnScreenshotAnimationResult;
+ expect(out.ok).toBe(true);
+ expect(out.clip).toBe('walk');
+ expect(out.camera).toBe('Right'); // default camera
+ expect(out.frames).toBe(6);
+ expect(typeof out.pngBase64).toBe('string');
+ expect(out.pngBase64!.length).toBeGreaterThan(0);
+ expect(out.framesBase64).toBeUndefined();
+ });
+
+ test('media extractor strips base64 and returns PNG bytes', async () => {
+ const out = await kilnScreenshotAnimationDef.run({ code: WALKER, clip: 'walk' });
+ const media = screenshotAnimationMedia(out);
+ expect(media).toBeDefined();
+ expect(media!.png).toBeInstanceOf(Uint8Array);
+ expect(media!.png.length).toBeGreaterThan(0);
+ expect('pngBase64' in (media!.json as object)).toBe(false);
+ // PNG magic number.
+ expect(Array.from(media!.png.subarray(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]);
+ });
+
+ test('perFrame mode: 6 separate frame PNGs via mediaMulti', async () => {
+ const out = (await kilnScreenshotAnimationDef.run({
+ code: WALKER,
+ clip: 'walk',
+ perFrame: true,
+ })) as KilnScreenshotAnimationResult;
+ expect(out.framesBase64).toHaveLength(6);
+ expect(out.pngBase64).toBeUndefined();
+ const multi = screenshotAnimationMediaMulti(out);
+ expect(multi!.pngs).toHaveLength(6);
+ expect(multi!.pngs[0]).toBeInstanceOf(Uint8Array);
+ expect('framesBase64' in (multi!.json as object)).toBe(false);
+ // The grid extractor declines a perFrame result.
+ expect(screenshotAnimationMedia(out)).toBeUndefined();
+ });
+
+ test('a build failure is image-free (ok:false, no png)', async () => {
+ const out = (await kilnScreenshotAnimationDef.run({ code: 'not valid (', clip: 'walk' })) as KilnScreenshotAnimationResult;
+ expect(out.ok).toBe(false);
+ expect(out.error).toBeDefined();
+ expect(out.pngBase64).toBeUndefined();
+ expect(screenshotAnimationMedia(out)).toBeUndefined();
+ });
+
+ test('an unknown clip reports the available clips, no image', async () => {
+ const out = (await kilnScreenshotAnimationDef.run({ code: WALKER, clip: 'jump' })) as KilnScreenshotAnimationResult;
+ expect(out.ok).toBe(false);
+ expect(out.availableClips).toEqual(['walk']);
+ expect(out.pngBase64).toBeUndefined();
+ });
+});
diff --git a/tools/registry.ts b/tools/registry.ts
index 452b8aac..46158666 100644
--- a/tools/registry.ts
+++ b/tools/registry.ts
@@ -45,6 +45,13 @@ export interface KilnToolDef {
* Transports without image support just use the raw `run()` output.
*/
media?(output: unknown): { png: Uint8Array; json: unknown } | undefined;
+ /**
+ * Like {@link media} but for tools that return MULTIPLE images in one result
+ * (kiln_screenshot_animation in perFrame mode → N frame PNGs). Transports that
+ * support image arrays attach all PNGs as separate blocks; those that don't fall
+ * back to {@link media} (a composite) or the raw output. Checked before `media`.
+ */
+ mediaMulti?(output: unknown): { pngs: Uint8Array[]; json: unknown } | undefined;
}
// =============================================================================
@@ -72,6 +79,24 @@ const screenshotInput = z.object({
code: z.string().describe('Kiln source code to execute and render to a six-view image grid.'),
});
+const screenshotAnimationInput = z.object({
+ code: z.string().describe('Kiln source code to execute; must define animate() returning the named clip.'),
+ clip: z
+ .string()
+ .describe('The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.'),
+ camera: z
+ .string()
+ .optional()
+ .describe(
+ 'Camera angle: right (default — side profile, best for leg swing + knee bend direction), front ' +
+ '(reveals sideways/lateral motion), back, left, top, or three-quarter.',
+ ),
+ perFrame: z
+ .boolean()
+ .optional()
+ .describe('Return the frames as separate high-res images instead of one composite grid. Default false.'),
+});
+
// =============================================================================
// kiln_list_primitives
// =============================================================================
@@ -359,6 +384,126 @@ export const kilnRenderViewsDef: KilnToolDef = {
media: screenshotMedia,
};
+// =============================================================================
+// kiln_screenshot_animation — SEE one clip's motion (6 phase-labeled frames)
+// =============================================================================
+
+export interface KilnScreenshotAnimationResult {
+ ok: boolean;
+ clip?: string;
+ camera?: string;
+ /** Frames rendered (6). */
+ frames: number;
+ /** Phase fraction (0..1) of each frame, in order. */
+ frameTimes?: number[];
+ duration?: number;
+ /** Track targets that bind to no joint → the clip looks FROZEN. Fix the joint name. */
+ unresolvedTracks?: string[];
+ width?: number;
+ height?: number;
+ /** Composite 3x2 grid PNG, base64 (default; transports with image support strip + attach it). */
+ pngBase64?: string;
+ /** Per-frame PNGs, base64 (perFrame mode; image transports attach each separately). */
+ framesBase64?: string[];
+ /** Clip names available in the scene (set when the requested clip wasn't found). */
+ availableClips?: string[];
+ warnings: string[];
+ error?: string;
+}
+
+/**
+ * Execute Kiln code and rasterize ONE animation clip into a strip of six
+ * evenly-sampled, phase-labeled frames from one camera (pure CPU). This is the
+ * motion analogue of kiln_screenshot: it lets the agent SEE its animation and
+ * catch defects invisible in a static pose — sideways walks, reverse-bending
+ * knees, attacks that swing behind the body, and held items that don't track the
+ * hand. Never throws — build/clip failures come back as { ok:false, error }.
+ */
+async function runScreenshotAnimation(
+ input: z.infer<typeof screenshotAnimationInput>,
+): Promise<KilnScreenshotAnimationResult> {
+ try {
+ const { renderClipAnimation } = await import('../views');
+ const { root, clips } = await executeKilnCode(input.code);
+ const warnings = inspectSceneStructure(root);
+ const r = await renderClipAnimation(root, clips, {
+ clip: input.clip,
+ ...(input.camera ? { camera: input.camera } : {}),
+ ...(input.perFrame ? { perFrame: true } : {}),
+ });
+ if (!r.ok) {
+ return {
+ ok: false,
+ frames: 0,
+ warnings,
+ ...(r.error ? { error: r.error } : {}),
+ ...(r.clip ? { clip: r.clip } : {}),
+ ...(r.availableClips ? { availableClips: r.availableClips } : {}),
+ };
+ }
+ const base: KilnScreenshotAnimationResult = {
+ ok: true,
+ frames: r.frames,
+ warnings,
+ ...(r.clip ? { clip: r.clip } : {}),
+ ...(r.camera ? { camera: r.camera } : {}),
+ ...(r.frameTimes ? { frameTimes: r.frameTimes } : {}),
+ ...(r.duration != null ? { duration: r.duration } : {}),
+ ...(r.unresolvedTracks ? { unresolvedTracks: r.unresolvedTracks } : {}),
+ ...(r.width ? { width: r.width } : {}),
+ ...(r.height ? { height: r.height } : {}),
+ };
+ if (r.pngs) return { ...base, framesBase64: r.pngs.map((p) => p.toString('base64')) };
+ return { ...base, pngBase64: r.png!.toString('base64') };
+ } catch (err) {
+ return { ok: false, frames: 0, error: err instanceof Error ? err.message : String(err), warnings: [] };
+ }
+}
+
+/** Media extractor for the composite-grid result (pngBase64 → bytes + stripped JSON). */
+export function screenshotAnimationMedia(output: unknown): { png: Uint8Array; json: unknown } | undefined {
+ const o = output as KilnScreenshotAnimationResult | undefined;
+ if (!o || typeof o.pngBase64 !== 'string' || o.pngBase64.length === 0) return undefined;
+ const { pngBase64: _png, framesBase64: _frames, ...json } = o;
+ return { png: new Uint8Array(Buffer.from(o.pngBase64, 'base64')), json };
+}
+
+/** Media extractor for the perFrame result (framesBase64 → N bytes + stripped JSON). */
+export function screenshotAnimationMediaMulti(
+ output: unknown,
+): { pngs: Uint8Array[]; json: unknown } | undefined {
+ const o = output as KilnScreenshotAnimationResult | undefined;
+ if (!o || !Array.isArray(o.framesBase64) || o.framesBase64.length === 0) return undefined;
+ const { pngBase64: _png, framesBase64: _frames, ...json } = o;
+ return { pngs: o.framesBase64.map((b) => new Uint8Array(Buffer.from(b, 'base64'))), json };
+}
+
+/**
+ * The animation-feedback tool: render one clip's motion as a 6-frame strip.
+ * Exported separately and intentionally NOT in `kilnToolRegistry` (the bench
+ * baseline stays the unchanged four); the agent tool surfaces add it explicitly.
+ * Carries both `media` (grid) and `mediaMulti` (perFrame) so image transports show
+ * the right thing in either mode.
+ */
+export const kilnScreenshotAnimationDef: KilnToolDef = {
+ name: 'kiln_screenshot_animation',
+ description:
+ 'SEE one animation clip move: renders the named clip as six frames sampled evenly from start to end ' +
+ '(each labeled with its phase %) from one camera, as a 3x2 grid. Use this after building an animated ' +
+ 'character to verify the MOTION — a static screenshot cannot show it. Read the side (right) view to ' +
+ 'check that a walk swings the legs forward and back (not splayed sideways and not sliding the body ' +
+ 'sideways), that knees bend backward at the joint (not forward like a bird), that an attack swings ' +
+ 'down and FORWARD through the front (not behind the back), and that a held weapon tracks the hand ' +
+ 'through the swing. args: clip (required, the clip name), camera (default right; also front/back/left/' +
+ 'top/three-quarter), perFrame (optional, separate high-res frames). If unresolvedTracks comes back ' +
+ 'non-empty the clip targets joints that do not exist (a name mismatch) and looks frozen — fix the ' +
+ 'track names. Flat-shaded CPU render; writes no files.',
+ inputSchema: screenshotAnimationInput,
+ run: async (input) => runScreenshotAnimation(screenshotAnimationInput.parse(input)),
+ media: screenshotAnimationMedia,
+ mediaMulti: screenshotAnimationMediaMulti,
+};
+
// =============================================================================
// Registry
// =============================================================================
diff --git a/views/__tests__/animation.test.ts b/views/__tests__/animation.test.ts
new file mode 100644
index 00000000..0f8af1e2
--- /dev/null
+++ b/views/__tests__/animation.test.ts
@@ -0,0 +1,122 @@
+/**
+ * Animation-view tests: the time-sampled poser + the clip grid renderer that back
+ * kiln_screenshot_animation. The key property is that POSING ACTUALLY MOVES the
+ * scene (so the agent sees motion, not a static repeat) and that a name-mismatched
+ * track surfaces as `unresolvedTracks` (the "frozen clip" signal).
+ */
+import { describe, expect, test } from 'bun:test';
+
+import { executeKilnCode } from '../../render';
+import { renderClipAnimation, planFrameTimes, prepareClip, findClip } from '../index';
+
+// A minimal biped whose legs swing forward/back (rotation about Z) on a 1s walk.
+const WALKER = `
+const meta = { name: 'walker', category: 'character' };
+function build() {
+ const root = createRoot('Root');
+ const hips = createPivot('Hips', [0, 1, 0], root);
+ createPart('Pelvis', boxGeo(0.4, 0.3, 0.3), gameMaterial('#888888'), { parent: hips });
+ const legL = createPivot('LegL', [0, 0, 0.12], hips);
+ createPart('LegLMesh', boxGeo(0.15, 0.9, 0.15), gameMaterial('#444444'), { parent: legL, position: [0, -0.45, 0] });
+ const legR = createPivot('LegR', [0, 0, -0.12], hips);
+ createPart('LegRMesh', boxGeo(0.15, 0.9, 0.15), gameMaterial('#444444'), { parent: legR, position: [0, -0.45, 0] });
+ return root;
+}
+function animate(root) {
+ return [createClip('walk', 1, [
+ rotationTrack('Joint_LegL', [
+ { time: 0, rotation: [0, 0, 35] }, { time: 0.5, rotation: [0, 0, -35] }, { time: 1, rotation: [0, 0, 35] },
+ ]),
+ rotationTrack('Joint_LegR', [
+ { time: 0, rotation: [0, 0, -35] }, { time: 0.5, rotation: [0, 0, 35] }, { time: 1, rotation: [0, 0, -35] },
+ ]),
+ ])];
+}
+`;
+
+// A clip that targets a joint that doesn't exist (the #1 "frozen clip" cause).
+const BROKEN_RIG = `
+const meta = { name: 'broken', category: 'character' };
+function build() {
+ const root = createRoot('Root');
+ const arm = createPivot('ArmR', [0, 1, 0], root);
+ createPart('ArmMesh', boxGeo(0.2, 0.6, 0.2), gameMaterial('#999999'), { parent: arm });
+ return root;
+}
+function animate(root) {
+ // BUG: createPivot('ArmR') makes 'Joint_ArmR' but the track targets bare 'ArmR'.
+ return [createClip('wave', 1, [
+ rotationTrack('ArmR', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [0, 0, 45] }]),
+ ])];
+}
+`;
+
+test('planFrameTimes samples endpoints inclusively', () => {
+ expect(planFrameTimes(1, 6)).toEqual([0, 0.2, 0.4, 0.6, 0.8, 1]);
+ expect(planFrameTimes(2, 6).at(-1)).toBe(2);
+ expect(planFrameTimes(0, 6)).toEqual([0, 0, 0, 0, 0, 0]); // a static "clip"
+});
+
+describe('renderClipAnimation', () => {
+ test('renders a 6-frame grid for a named clip with correct metadata', async () => {
+ const { root, clips } = await executeKilnCode(WALKER);
+ const r = await renderClipAnimation(root, clips, { clip: 'walk', camera: 'right' });
+ expect(r.ok).toBe(true);
+ expect(r.clip).toBe('walk');
+ expect(r.camera).toBe('Right');
+ expect(r.frames).toBe(6);
+ expect(r.duration).toBe(1);
+ expect(r.frameTimes).toEqual([0, 0.2, 0.4, 0.6, 0.8, 1]);
+ expect(r.png).toBeInstanceOf(Buffer);
+ expect(r.png!.length).toBeGreaterThan(100);
+ expect(r.unresolvedTracks).toBeUndefined(); // both tracks bind
+ });
+
+ test('posing actually moves the scene — frames differ from each other', async () => {
+ const { root, clips } = await executeKilnCode(WALKER);
+ const r = await renderClipAnimation(root, clips, { clip: 'walk', camera: 'right', perFrame: true });
+ expect(r.pngs).toHaveLength(6);
+ // Mid-stride (frame 2, ~40%) must look different from the start pose (frame 0).
+ expect(Buffer.compare(r.pngs![0]!, r.pngs![2]!)).not.toBe(0);
+ });
+
+ test('a track targeting a missing joint surfaces as unresolvedTracks (frozen clip)', async () => {
+ const { root, clips } = await executeKilnCode(BROKEN_RIG);
+ const r = await renderClipAnimation(root, clips, { clip: 'wave', camera: 'right' });
+ expect(r.ok).toBe(true);
+ expect(r.unresolvedTracks).toEqual(['ArmR.quaternion']);
+ });
+
+ test('an unknown clip name returns the available clips', async () => {
+ const { root, clips } = await executeKilnCode(WALKER);
+ const r = await renderClipAnimation(root, clips, { clip: 'sprint' });
+ expect(r.ok).toBe(false);
+ expect(r.error).toContain('not found');
+ expect(r.availableClips).toEqual(['walk']);
+ });
+
+ test('a scene with no clips reports it cleanly', async () => {
+ const { root } = await executeKilnCode(WALKER);
+ const r = await renderClipAnimation(root, [], { clip: 'walk' });
+ expect(r.ok).toBe(false);
+ expect(r.error).toContain('no animation');
+ });
+
+ test('findClip resolves case-insensitively and by substring', async () => {
+ const { clips } = await executeKilnCode(WALKER);
+ expect(findClip(clips, 'WALK')?.name).toBe('walk');
+ expect(findClip(clips, 'wal')?.name).toBe('walk');
+ expect(findClip(clips, 'nope')).toBeUndefined();
+ });
+
+ test('prepareClip parses tracks + derives duration', async () => {
+ const { root, clips } = await executeKilnCode(WALKER);
+ const prepared = prepareClip(root, clips[0]!);
+ expect(prepared.name).toBe('walk');
+ expect(prepared.duration).toBe(1);
+ expect(prepared.tracks).toHaveLength(2);
+ expect(prepared.tracks[0]!.prop).toBe('quaternion');
+ expect(prepared.tracks[0]!.stride).toBe(4);
+ expect(prepared.unresolved).toHaveLength(0);
+ });
+});
diff --git a/views/index.ts b/views/index.ts
index 14d8ead5..e4365dfc 100644
--- a/views/index.ts
+++ b/views/index.ts
@@ -11,12 +11,30 @@
* row 2: Left, Top, 3/4
*/
-import { rasterizeView, SIX_VIEWS, type RasterOptions, type ViewSpec } from './raster';
+import { rasterizeView, measureBounds, SIX_VIEWS, type RasterOptions, type ViewSpec } from './raster';
import { encodePng } from './png';
+import {
+ prepareClip,
+ poseSceneAtTime,
+ planFrameTimes,
+ findClip,
+ clipNames,
+ stampLabel,
+ type DuckClip,
+} from './pose';
-export { rasterizeView, SIX_VIEWS, coverage } from './raster';
+export { rasterizeView, measureBounds, SIX_VIEWS, coverage } from './raster';
export type { RasterOptions, ViewSpec } from './raster';
export { encodePng } from './png';
+export {
+ prepareClip,
+ poseSceneAtTime,
+ planFrameTimes,
+ findClip,
+ clipNames,
+ type DuckClip,
+ type PreparedClip,
+} from './pose';
const PAD = 4;
const PAD_COLOR: [number, number, number] = [10, 11, 13];
@@ -82,3 +100,184 @@ export async function renderCodeViewGrid(
const { root } = await executeKilnCode(code);
return renderViewGrid(root, opts);
}
+
+// =============================================================================
+// Animation views — see one clip's MOTION (kiln_screenshot_animation)
+// =============================================================================
+
+/** Friendly camera names → orthographic view directions (kiln frame). The default
+ * is RIGHT: the side profile reveals forward/back leg swing, knee bend direction,
+ * and the arc of an attack — the motion defects a static grid can't show. */
+const ANIM_CAMERAS: Record<string, ViewSpec> = {
+ front: { name: 'Front', dir: [1, 0, 0] },
+ right: { name: 'Right', dir: [0, 0, 1] },
+ back: { name: 'Back', dir: [-1, 0, 0] },
+ left: { name: 'Left', dir: [0, 0, -1] },
+ top: { name: 'Top', dir: [0, 1, 0.0001] },
+ 'three-quarter': { name: '3/4', dir: [0.7, 0.5, 0.7] },
+};
+const ANIM_CAMERA_ALIASES: Record<string, string> = {
+ '3/4': 'three-quarter',
+ '34': 'three-quarter',
+ threequarter: 'three-quarter',
+ quarter: 'three-quarter',
+ perspective: 'three-quarter',
+ side: 'right',
+ profile: 'right',
+};
+
+function resolveCamera(name?: string): ViewSpec {
+ const key = (name ?? 'right').trim().toLowerCase().replace(/[_\s]+/g, '-');
+ return ANIM_CAMERAS[key] ?? ANIM_CAMERAS[ANIM_CAMERA_ALIASES[key] ?? ''] ?? ANIM_CAMERAS['right']!;
+}
+
+export interface AnimationViewOptions extends RasterOptions {
+ /** Clip to render, by name (case-insensitive, substring-tolerant). Omit → first clip. */
+ clip?: string;
+ /** Camera angle. Default 'right' (side profile). */
+ camera?: string;
+ /** Frames sampled across the clip (start→end inclusive). Default 6. */
+ frames?: number;
+ /** Return the frames as separate PNGs instead of one composite grid. Default false. */
+ perFrame?: boolean;
+}
+
+export interface AnimationViewResult {
+ ok: boolean;
+ clip?: string;
+ camera?: string;
+ frames: number;
+ /** Phase fraction (0..1) of each frame, in order. */
+ frameTimes: number[];
+ /** Clip duration in seconds. */
+ duration?: number;
+ /** Track targets that resolve to no joint — the "frozen clip" signal (cause #1). */
+ unresolvedTracks?: string[];
+ width?: number;
+ height?: number;
+ /** Composite grid PNG (default mode). */
+ png?: Buffer;
+ /** Per-frame PNGs (perFrame mode). */
+ pngs?: Buffer[];
+ /** Clip names available in the scene (set on a not-found error). */
+ availableClips?: string[];
+ error?: string;
+}
+
+/** Phase percentage label for frame i of n, e.g. "0%" … "100%". */
+function phaseLabel(i: number, n: number): string {
+ const pct = n <= 1 ? 0 : Math.round((100 * i) / (n - 1));
+ return `${pct}%`;
+}
+
+/**
+ * Render one animation clip as a strip of evenly-sampled, phase-labeled frames
+ * from a single camera, so the agent can SEE the motion (sideways walk, reverse
+ * knee, backward swing, item not tracking the hand). MUTATES `root` (callers pass
+ * a freshly executed scene — the tool re-executes per call).
+ *
+ * Two passes: pose+measure every frame to a union AABB (steady framing so root
+ * travel reads), then pose+rasterize+label each frame against that fixed box.
+ */
+export async function renderClipAnimation(
+ root: unknown,
+ clips: readonly DuckClip[],
+ opts: AnimationViewOptions = {},
+): Promise<AnimationViewResult> {
+ const size = opts.size ?? 256;
+ const frameCount = Math.max(2, Math.min(opts.frames ?? 6, 6));
+ const cam = resolveCamera(opts.camera);
+
+ if (!clips || clips.length === 0) {
+ return { ok: false, frames: 0, frameTimes: [], error: 'this asset has no animation clips', availableClips: [] };
+ }
+ // Resolve the requested clip by name; default to the first when none is named.
+ const requested = opts.clip?.trim();
+ const chosen = requested ? findClip(clips, requested) : clips[0];
+ if (!chosen) {
+ return {
+ ok: false,
+ frames: 0,
+ frameTimes: [],
+ ...(requested ? { clip: requested } : {}),
+ error: `clip "${requested}" not found in this asset`,
+ availableClips: clipNames(clips),
+ };
+ }
+
+ const prepared = prepareClip(root as never, chosen);
+ const times = planFrameTimes(prepared.duration, frameCount);
+ const frameTimes = times.map((t) => (prepared.duration > 0 ? t / prepared.duration : 0));
+
+ // Pass 1 — union the posed bounds so all frames share one camera framing.
+ const min: [number, number, number] = [Infinity, Infinity, Infinity];
+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
+ for (const t of times) {
+ poseSceneAtTime(root as never, prepared, t);
+ const b = measureBounds(root);
+ for (let a = 0; a < 3; a++) {
+ const lo = b.min[a]!;
+ const hi = b.max[a]!;
+ if (lo < min[a]!) min[a] = lo;
+ if (hi > max[a]!) max[a] = hi;
+ }
+ }
+ const frameBounds = Number.isFinite(min[0]) ? { min, max } : undefined;
+
+ // Pass 2 — render + label each frame against the fixed framing.
+ const labelScale = Math.max(2, Math.round(size / 80));
+ const cells: Uint8Array[] = [];
+ for (let i = 0; i < times.length; i++) {
+ poseSceneAtTime(root as never, prepared, times[i]!);
+ const cell = rasterizeView(root, cam.dir, {
+ size,
+ ...(opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {}),
+ ...(frameBounds ? { frameBounds } : {}),
+ });
+ stampLabel(cell, size, size, labelScale, labelScale, phaseLabel(i, times.length), labelScale);
+ cells.push(cell);
+ }
+
+ const baseMeta = {
+ ok: true as const,
+ clip: prepared.name,
+ camera: cam.name,
+ frames: times.length,
+ frameTimes,
+ duration: prepared.duration,
+ ...(prepared.unresolved.length ? { unresolvedTracks: prepared.unresolved } : {}),
+ };
+
+ if (opts.perFrame) {
+ return {
+ ...baseMeta,
+ width: size,
+ height: size,
+ pngs: cells.map((c) => encodePng(c, size, size)),
+ };
+ }
+
+ // Compose into a 3x2 grid (same layout as the six-view grid).
+ const cols = 3;
+ const rows = Math.ceil(cells.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 p = 0; p < width * height; p++) {
+ grid[p * 3] = PAD_COLOR[0];
+ grid[p * 3 + 1] = PAD_COLOR[1];
+ grid[p * 3 + 2] = PAD_COLOR[2];
+ }
+ for (let i = 0; i < cells.length; i++) {
+ const col = i % cols;
+ const row = Math.floor(i / 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(cells[i]!.subarray(src, src + size * 3), dst);
+ }
+ }
+ return { ...baseMeta, width, height, png: encodePng(grid, width, height) };
+}
diff --git a/views/pose.ts b/views/pose.ts
new file mode 100644
index 00000000..4ba0915f
--- /dev/null
+++ b/views/pose.ts
@@ -0,0 +1,325 @@
+/**
+ * Time-sampled posing for the Kiln animation-feedback loop.
+ *
+ * The static six-view grid (./index, ./raster) shows the agent its REST pose, so
+ * it self-corrects geometry/orientation defects. But it is blind to its
+ * animations — a sideways walk, a backward-bending knee, an attack that swings
+ * behind the body, or a held item that doesn't track the hand are all MOTION
+ * defects invisible at author time. This module poses an executed scene at a
+ * given clip time so the rasterizer can render it; ./index composes the result
+ * into an annotated frame strip (kiln_screenshot_animation).
+ *
+ * Strictly duck-typed across the sandbox/module-realm boundary (see ../render):
+ * clips are read via `.tracks[].name/.times/.values`, nodes are found by
+ * `root.traverse` + `.name`, and transforms are written by calling the node's own
+ * `.position/.quaternion/.scale .set()` methods — no `instanceof`, no THREE import.
+ */
+
+/** Minimal duck-typed view of a Three.js node we pose. */
+interface DuckNode {
+ name?: string;
+ position?: { set(x: number, y: number, z: number): void };
+ quaternion?: { set(x: number, y: number, z: number, w: number): void };
+ scale?: { set(x: number, y: number, z: number): void };
+ updateMatrixWorld?(force?: boolean): void;
+ traverse?(cb: (obj: unknown) => void): void;
+}
+
+/** Minimal duck-typed view of a Three.js KeyframeTrack. */
+interface DuckTrack {
+ name?: string;
+ times?: ArrayLike<number>;
+ values?: ArrayLike<number>;
+}
+
+/** Minimal duck-typed view of a Three.js AnimationClip. */
+export interface DuckClip {
+ name?: string;
+ duration?: number;
+ tracks?: DuckTrack[];
+}
+
+type Prop = 'position' | 'quaternion' | 'scale';
+
+interface PreparedTrack {
+ nodeName: string;
+ prop: Prop;
+ stride: number;
+ times: number[];
+ values: number[];
+}
+
+/** A clip prepared for repeated time-sampling: parsed tracks + a derived duration. */
+export interface PreparedClip {
+ name: string;
+ duration: number;
+ tracks: PreparedTrack[];
+ /** Track target names that resolve to no node in the scene (the "frozen clip" signal). */
+ unresolved: string[];
+}
+
+const PROP_STRIDE: Record<Prop, number> = { position: 3, quaternion: 4, scale: 3 };
+
+/** Find a clip by name (case-insensitive, trimmed). Returns the first exact match,
+ * else the first whose name contains the query, else undefined. */
+export function findClip(clips: readonly DuckClip[], name: string): DuckClip | undefined {
+ const q = name.trim().toLowerCase();
+ const named = clips.filter((c) => typeof c.name === 'string');
+ return (
+ named.find((c) => c.name!.toLowerCase() === q) ??
+ named.find((c) => c.name!.toLowerCase().includes(q)) ??
+ undefined
+ );
+}
+
+/** All clip names (for error messages when a requested clip isn't found). */
+export function clipNames(clips: readonly DuckClip[]): string[] {
+ return clips.map((c) => (typeof c.name === 'string' ? c.name : '(unnamed)'));
+}
+
+/**
+ * Parse a clip's tracks into a reusable sampling plan and resolve each track's
+ * target against the scene. Derives a duration from the keyframe times when the
+ * clip doesn't carry one.
+ */
+export function prepareClip(root: DuckNode, clip: DuckClip): PreparedClip {
+ const nodeNames = new Set<string>();
+ root.traverse?.((obj) => {
+ const n = (obj as DuckNode).name;
+ if (n) nodeNames.add(n);
+ });
+
+ const tracks: PreparedTrack[] = [];
+ const unresolved: string[] = [];
+ let maxTime = 0;
+
+ for (const track of clip.tracks ?? []) {
+ const raw = track.name;
+ if (!raw) continue;
+ const dot = raw.lastIndexOf('.');
+ if (dot === -1) continue;
+ const nodeName = raw.slice(0, dot);
+ const property = raw.slice(dot + 1) as Prop;
+ if (property !== 'position' && property !== 'quaternion' && property !== 'scale') continue;
+
+ const times = track.times ? Array.from(track.times) : [];
+ const values = track.values ? Array.from(track.values) : [];
+ if (times.length === 0 || values.length === 0) continue;
+
+ if (!nodeNames.has(nodeName)) unresolved.push(raw);
+ if (times[times.length - 1]! > maxTime) maxTime = times[times.length - 1]!;
+
+ tracks.push({ nodeName, prop: property, stride: PROP_STRIDE[property], times, values });
+ }
+
+ const duration = clip.duration && clip.duration > 0 ? clip.duration : maxTime;
+ return { name: clip.name ?? '(unnamed)', duration, tracks, unresolved };
+}
+
+/** Index of the last keyframe at or before `t`, via linear scan (keyframe counts
+ * are tiny). Returns -1 when `t` precedes the first key. */
+function keyframeIndexAtOrBefore(times: number[], t: number): number {
+ let i = -1;
+ for (let k = 0; k < times.length; k++) {
+ if (times[k]! <= t) i = k;
+ else break;
+ }
+ return i;
+}
+
+/** Spherical-linear interpolation of two flat quaternions into `out` (THREE's
+ * slerpFlat algorithm; dependency-free so this module stays realm-agnostic). */
+function slerpFlat(
+ out: number[],
+ src0: number[],
+ o0: number,
+ src1: number[],
+ o1: number,
+ t: number,
+): void {
+ const x0 = src0[o0]!, y0 = src0[o0 + 1]!, z0 = src0[o0 + 2]!, w0 = src0[o0 + 3]!;
+ const x1 = src1[o1]!, y1 = src1[o1 + 1]!, z1 = src1[o1 + 2]!, w1 = src1[o1 + 3]!;
+ let cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
+ let bx = x1, by = y1, bz = z1, bw = w1;
+ if (cos < 0) {
+ cos = -cos;
+ bx = -x1; by = -y1; bz = -z1; bw = -w1;
+ }
+ let s0: number, s1: number;
+ if (cos > 0.9995) {
+ s0 = 1 - t;
+ s1 = t;
+ } else {
+ const theta = Math.acos(cos);
+ const sin = Math.sin(theta);
+ s0 = Math.sin((1 - t) * theta) / sin;
+ s1 = Math.sin(t * theta) / sin;
+ }
+ const rx = s0 * x0 + s1 * bx;
+ const ry = s0 * y0 + s1 * by;
+ const rz = s0 * z0 + s1 * bz;
+ const rw = s0 * w0 + s1 * bw;
+ const len = Math.hypot(rx, ry, rz, rw) || 1;
+ out[0] = rx / len;
+ out[1] = ry / len;
+ out[2] = rz / len;
+ out[3] = rw / len;
+}
+
+const quatTmp: number[] = [0, 0, 0, 1];
+
+/** Sample one prepared track at time `t` into `out` (length = stride). LINEAR for
+ * vectors, slerp for quaternions; clamps outside the keyframe range. */
+function sampleTrack(track: PreparedTrack, t: number, out: number[]): void {
+ const { times, values, stride } = track;
+ const i = keyframeIndexAtOrBefore(times, t);
+
+ if (i < 0) {
+ for (let s = 0; s < stride; s++) out[s] = values[s]!;
+ return;
+ }
+ if (i >= times.length - 1) {
+ const base = (times.length - 1) * stride;
+ for (let s = 0; s < stride; s++) out[s] = values[base + s]!;
+ return;
+ }
+
+ const t0 = times[i]!;
+ const t1 = times[i + 1]!;
+ const span = t1 - t0;
+ const a = span > 1e-9 ? (t - t0) / span : 0;
+ const o0 = i * stride;
+ const o1 = (i + 1) * stride;
+
+ if (stride === 4) {
+ slerpFlat(quatTmp, values, o0, values, o1, a);
+ out[0] = quatTmp[0]!;
+ out[1] = quatTmp[1]!;
+ out[2] = quatTmp[2]!;
+ out[3] = quatTmp[3]!;
+ } else {
+ for (let s = 0; s < stride; s++) out[s] = values[o0 + s]! + (values[o1 + s]! - values[o0 + s]!) * a;
+ }
+}
+
+/**
+ * Pose `root` at clip time `t`: for every track, sample the value and write it to
+ * the target node's transform, then refresh world matrices. MUTATES the scene
+ * (callers pass a throwaway root — the screenshot tool executes fresh code each
+ * call). Non-animated nodes keep their build transform, exactly as a single clip
+ * played in isolation would leave them.
+ */
+export function poseSceneAtTime(root: DuckNode, prepared: PreparedClip, t: number): void {
+ // Resolve targets each call (cheap; the scene is small) — robust to callers that
+ // pass a clip prepared against a different (but identical) executed root.
+ const byName = new Map<string, DuckNode>();
+ root.traverse?.((obj) => {
+ const node = obj as DuckNode;
+ if (node.name && !byName.has(node.name)) byName.set(node.name, node);
+ });
+
+ const buf: number[] = [0, 0, 0, 0];
+ for (const track of prepared.tracks) {
+ const node = byName.get(track.nodeName);
+ if (!node) continue;
+ sampleTrack(track, t, buf);
+ if (track.prop === 'position') node.position?.set(buf[0]!, buf[1]!, buf[2]!);
+ else if (track.prop === 'scale') node.scale?.set(buf[0]!, buf[1]!, buf[2]!);
+ else node.quaternion?.set(buf[0]!, buf[1]!, buf[2]!, buf[3]!);
+ }
+
+ root.updateMatrixWorld?.(true);
+}
+
+/**
+ * The times (seconds) at which to sample a clip of `duration` into `count` frames,
+ * inclusive of both endpoints (0 → duration). For a one-shot clip the last frame is
+ * the final pose; for a seamless loop the last frame returns to the start (expected).
+ */
+export function planFrameTimes(duration: number, count: number): number[] {
+ if (count <= 1 || duration <= 0) return new Array(Math.max(1, count)).fill(0);
+ const out: number[] = [];
+ for (let i = 0; i < count; i++) out.push((duration * i) / (count - 1));
+ return out;
+}
+
+// =============================================================================
+// Tiny bitmap label stamp (annotate each frame with its phase)
+// =============================================================================
+
+// 3x5 glyphs (msb = leftmost column), only the chars the phase labels need.
+const GLYPHS: Record<string, number[]> = {
+ '0': [0b111, 0b101, 0b101, 0b101, 0b111],
+ '1': [0b010, 0b110, 0b010, 0b010, 0b111],
+ '2': [0b111, 0b001, 0b111, 0b100, 0b111],
+ '3': [0b111, 0b001, 0b111, 0b001, 0b111],
+ '4': [0b101, 0b101, 0b111, 0b001, 0b001],
+ '5': [0b111, 0b100, 0b111, 0b001, 0b111],
+ '6': [0b111, 0b100, 0b111, 0b101, 0b111],
+ '7': [0b111, 0b001, 0b010, 0b010, 0b010],
+ '8': [0b111, 0b101, 0b111, 0b101, 0b111],
+ '9': [0b111, 0b101, 0b111, 0b001, 0b111],
+ '%': [0b101, 0b001, 0b010, 0b100, 0b101],
+ ' ': [0, 0, 0, 0, 0],
+};
+
+const LABEL_FG: [number, number, number] = [255, 224, 64]; // amber, reads on dark + lit faces
+const LABEL_BG: [number, number, number] = [12, 12, 14];
+
+/**
+ * Stamp `text` into an RGB buffer at (x0, y0) using the 3x5 font scaled by `scale`,
+ * over a dark backdrop for legibility. Clipped to the buffer bounds. Used to label
+ * each animation frame with its phase percentage.
+ */
+export function stampLabel(
+ rgb: Uint8Array,
+ width: number,
+ height: number,
+ x0: number,
+ y0: number,
+ text: string,
+ scale = 3,
+): void {
+ const gw = 3 * scale;
+ const gh = 5 * scale;
+ const gap = scale;
+ const pad = scale;
+ const totalW = text.length * gw + (text.length - 1) * gap + pad * 2;
+ const totalH = gh + pad * 2;
+
+ // Backdrop.
+ for (let y = y0; y < y0 + totalH; y++) {
+ for (let x = x0; x < x0 + totalW; x++) {
+ if (x < 0 || y < 0 || x >= width || y >= height) continue;
+ const p = (y * width + x) * 3;
+ rgb[p] = LABEL_BG[0];
+ rgb[p + 1] = LABEL_BG[1];
+ rgb[p + 2] = LABEL_BG[2];
+ }
+ }
+
+ // Glyphs.
+ let cx = x0 + pad;
+ const cy = y0 + pad;
+ for (const ch of text) {
+ const glyph = GLYPHS[ch] ?? GLYPHS[' ']!;
+ for (let row = 0; row < 5; row++) {
+ const bits = glyph[row]!;
+ for (let col = 0; col < 3; col++) {
+ if (!(bits & (1 << (2 - col)))) continue;
+ for (let sy = 0; sy < scale; sy++) {
+ for (let sx = 0; sx < scale; sx++) {
+ const x = cx + col * scale + sx;
+ const y = cy + row * scale + sy;
+ if (x < 0 || y < 0 || x >= width || y >= height) continue;
+ const p = (y * width + x) * 3;
+ rgb[p] = LABEL_FG[0];
+ rgb[p + 1] = LABEL_FG[1];
+ rgb[p + 2] = LABEL_FG[2];
+ }
+ }
+ }
+ }
+ cx += gw + gap;
+ }
+}
diff --git a/views/raster.ts b/views/raster.ts
index b73618fe..a9e33f5a 100644
--- a/views/raster.ts
+++ b/views/raster.ts
@@ -41,6 +41,14 @@ export interface RasterOptions {
size?: number;
/** Cull triangles facing away from the camera. Default true (reveals winding bugs). */
backfaceCull?: boolean;
+ /**
+ * Fixed world-space AABB to frame the camera to, instead of the scene's own
+ * bounds. Used by the animation grid so every sampled frame shares one framing —
+ * otherwise per-frame auto-framing re-centers the model and HIDES root travel
+ * (a sideways/forward-sliding walk would look stationary). The scene's own
+ * geometry is still drawn; only the camera center/zoom come from this box.
+ */
+ frameBounds?: { min: [number, number, number]; max: [number, number, number] };
}
const BG: [number, number, number] = [26, 26, 26]; // #1a1a1a, matches audit grid
@@ -217,18 +225,22 @@ export function rasterizeView(
const x = normalize(cross(upHint, z));
const y = cross(z, x);
+ // Framing box: a caller-supplied fixed AABB (animation grid — keeps the camera
+ // steady so root travel is visible) or the scene's own bounds (static views).
+ const frameMin = opts.frameBounds ? opts.frameBounds.min : bbox.min;
+ const frameMax = opts.frameBounds ? opts.frameBounds.max : bbox.max;
const center: Vec3 = [
- (bbox.min[0] + bbox.max[0]) / 2,
- (bbox.min[1] + bbox.max[1]) / 2,
- (bbox.min[2] + bbox.max[2]) / 2,
+ (frameMin[0] + frameMax[0]) / 2,
+ (frameMin[1] + frameMax[1]) / 2,
+ (frameMin[2] + frameMax[2]) / 2,
];
- // Project the 8 bbox corners to find the framing extent for this view.
+ // Project the 8 framing-box corners to find the framing extent for this view.
let ext = 1e-6;
for (let ci = 0; ci < 8; ci++) {
- const px = (ci & 1 ? bbox.max[0] : bbox.min[0]) - center[0];
- const py = (ci & 2 ? bbox.max[1] : bbox.min[1]) - center[1];
- const pz = (ci & 4 ? bbox.max[2] : bbox.min[2]) - center[2];
+ const px = (ci & 1 ? frameMax[0] : frameMin[0]) - center[0];
+ const py = (ci & 2 ? frameMax[1] : frameMin[1]) - center[1];
+ const pz = (ci & 4 ? frameMax[2] : frameMin[2]) - center[2];
const p: Vec3 = [px, py, pz];
ext = Math.max(ext, Math.abs(dot(p, x)), Math.abs(dot(p, y)));
}
@@ -311,6 +323,15 @@ export function rasterizeView(
return out;
}
+/** World-space AABB of a (possibly sandbox-created) scene's drawable geometry.
+ * Reuses the rasterizer's own triangle collection so the box matches exactly what
+ * gets drawn. Empty scenes report a zero box. Used by the animation grid to union
+ * bounds across posed frames into one steady camera framing. */
+export function measureBounds(root: unknown): { min: [number, number, number]; max: [number, number, number] } {
+ const { bbox } = collectTriangles(root as DuckObject3D);
+ return { min: [...bbox.min], max: [...bbox.max] };
+}
+
/** Fraction of non-background pixels — used by tests and occupancy checks. */
export function coverage(rgb: Uint8Array, size: number): number {
let filled = 0;