3D engine that AI agents drive
Add agent motion authoring in 67js 0.7.0
Nguyen Xuan Anc2ed4c5e40c0
diff --git a/.gitignore b/.gitignoreindex 349bb57b..faaa67fc 100644--- a/.gitignore+++ b/.gitignore@@ -40,3 +40,4 @@ public/mcp.mdpublic/agent-look.mdpublic/agent-asset.mdpublic/agent-render-jobs.md+public/agent-motion.mddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 969af416..ae58fe22 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,13 @@# Changelog+## 0.7.0++- Author bounded procedural motion in agent recipes with local node, material and camera tracks.+- Reuse linear, step, smooth and cubic interpolation with looping and absolute-time preview seeks.+- Validate the complete sampled pose before publishing transforms, material handles or camera changes.+- Preserve authored recipes, revisions, geometry identities and checkpoints during transient seeks.+- Sample procedural motion in PNG, still sequence and MP4 snapshot jobs while retaining the source preview pose.+## 0.6.0- Add five MCP tools for asynchronous snapshot rendering, progress, cancellation, results and output release.diff --git a/README.md b/README.mdindex 6c3040ed..a8471c07 100644--- a/README.md+++ b/README.md@@ -133,6 +133,8 @@ The packaged [MCP server](docs/mcp.md) connects these sessions to a persistent bAgents receive PNG previews and structured scene metadata through the stdio tools.Version `0.6.0` adds [snapshot render jobs](docs/agent-render-jobs.md) for PNG images, eight-frame still sequences and silent MP4 video.+Version `0.7.0` adds [agent motion](docs/agent-motion.md) for local joints, materials and authored camera moves.+Recipes, checkpoints and job snapshots retain the keyframes. Preview seeks preserve revisions and reuse geometry.Agents can poll progress, cancel jobs, retrieve verified artifacts and release retained outputs.The source pose, revision and checkpoints remain intact while a job temporarily leases the preview renderer.diff --git a/ROADMAP.md b/ROADMAP.mdindex 2020eb53..c57a1133 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -21,7 +21,9 @@ This document separates shipping capabilities from work in progress. Performance- Static sculpt brushes, clipped surface patches, shrinkwrap and bounded mesh contact and containment queries.Version `0.5.0` includes agent scenes with stable IDs, atomic resource/node edits and checkpoints.-Its stdio MCP server supplies twelve schema-backed tools and persistent CPU/GPU image previews.+Version `0.6.0` adds persistent snapshot jobs with progress, cancellation and verified image/video outputs.+Version `0.7.0` adds recipe-owned procedural motion with deterministic node, material and camera sampling.+The stdio MCP server supplies seventeen schema-backed tools and persistent CPU/GPU image previews.Recipes retain lighting, volumetric fog, grading and directional shadow coverage with atomic edits and undo.Imported asset sessions retain supported textures, rigs, morphs and clips from a configured local GLB catalog.@@ -30,8 +32,8 @@ The npm package includes the prebuilt `67js-mcp` command with lazy browser start## Next1. Extend imported asset sessions with node-level editing, topology changes and deformed geometry diagnostics.-2. Extend MCP visual feedback with bounded multi-angle and absolute animation-time previews.-3. Persistent render jobs with progress, cancellation, explicit CPU/GPU budgets and deterministic image and video export.+2. Extend MCP visual feedback with bounded multi-angle previews and compact rendered diagnostics.+3. Extend render jobs with hardware encoder selection, audio, longer sequences and measured adaptive output quality.4. Geometry, rig and asset diagnostics that help agents correct intersections, invalid transforms and unsupported materials.5. Agent workflows for imported assets, sculpting, surface fitting, lighting and animation, verified against rendered reference scenes.6. GPU timing and adaptive quality based on measured frame time, with stable resolution changes and explicit minimum quality.diff --git a/docs/agent-motion.md b/docs/agent-motion.mdnew file mode 100644index 00000000..0db0e04e--- /dev/null+++ b/docs/agent-motion.md@@ -0,0 +1,132 @@+# Agent motion++Release `0.7.0` adds procedural motion to agent recipes, preview seeks and snapshot render jobs.+The `agent-scene` addon and packaged MCP server share this contract.+The installed package version determines availability.++## Scene and MCP usage++```js+import { createAgentScene } from '67js/addons/agent-scene';++const scene = createAgentScene(recipe);+scene.apply([{ type: 'set-motion', motion }], { expectedRevision: scene.revision });+scene.sampleMotion(1);+renderer.updateParts(scene.parts);+renderer.render(scene.camera);+scene.sampleMotion(null); // Restore the authored base pose.+```++The example assumes a valid recipe, a motion record and a renderer bound to `scene.parts`.+Creation, successful edits and checkpoint restore sample time zero when the recipe contains motion.+`sampleMotion(time)` accepts absolute seconds or `null` to restore base transforms, materials and camera.+It preserves part, matrix, material handle and geometry identities.+It does not regenerate geometry or advance revisions.++MCP `scene_look` accepts optional `motionTime` with the same seconds and `null` semantics.+Omitting `motionTime` preserves the current preview pose.+`scene_inspect` reports authored motion duration, loop, track count and transient time.+Its bounds remain in `authored-base-world` space, independent of the sampled pose.++`set-motion` requires a complete motion record or explicit `null` to clear it.+The final batch must resolve every track reference, including after node or material removal.+Failed edits or seeks preserve the previous recipe, rendered pose and revisions.++Snapshot jobs select motion with `settings.motion: { start: 0 }`.+Frames use `start + elapsed` independently of imported clips and renderer shader time.+Omitting this setting holds the initial motion pose.+Nonlooping job samples must fit the authored duration.+Looping samples wrap, with an absolute maximum of 3600 seconds.+Completion and cancellation preserve the source preview time, revision and checkpoints.++## Authored data++A motion contains one duration, an optional loop flag, and typed keyframe tracks.+Node tracks address final recipe node IDs, including nodes without geometry.+Their values represent absolute local translation, XYZW quaternion rotation, or positive scale.+Material tracks address material IDs and affect every node that shares that material.+Camera tracks omit an ID and address eye, target, vertical FOV, or roll.+Roll uses radians, and FOV uses degrees.++```js+const motion = {+ duration: 2,+ loop: false,+ tracks: [{+ kind: 'node',+ id: 'hinge',+ property: 'rotation',+ interpolation: 'SMOOTH',+ keyframes: [+ { time: 0, value: [0, 0, 0, 1] },+ { time: 2, value: [0, 0, 0.70710678, 0.70710678] },+ ],+ }],+};+```++Node properties are `translation`, `rotation`, and `scale`.+Material properties are `color`, `emissiveColor`, `emission`, `metallic`, and `roughness`.+Camera properties are `eye`, `target`, `fov`, and `roll`.+Untracked properties retain authored base values.+Clipping planes retain authored values. Roll rotates the authored camera up direction.++Tracks support `LINEAR`, `STEP`, `SMOOTH`, and `CUBICSPLINE` interpolation.+Cubic keys require both `inTangent` and `outTangent`, with the same dimensions as the value.+Tangents use change per second.+Quaternion values normalize through the existing animation core.+Quaternion tangents retain their authored values.+Other interpolation modes reject tangents.++## Internal sampling helpers++`normalizeAgentMotion(input, recipe)` returns canonical plain JSON, or `null` for absent motion.+It copies values, sorts keyframes, and rejects duplicate times, unknown fields, missing references, and duplicate target properties.+References must exist in the final recipe after the entire edit batch.++`compileAgentMotion(motion, recipe)` returns a retained sampler, or `null` for absent motion.+The sampler copies its inputs and reuses the existing animation core and camera path implementation.+Its `sample(time)` method returns `{nodes, materials, camera}`.+The node and material maps contain patches keyed by recipe IDs.+Vector patches use retained `Float64Array` values, while scalar patches use numbers.++Camera vectors use retained `Float32Array` values to validate rounded poses.+The camera output is `null` when no camera tracks exist.++Outputs are borrowed staging buffers.+Callers must copy them before retaining a pose and must not mutate the returned maps, patches, or arrays.+A failed sample leaves previously published sampler outputs unchanged.+The caller must validate composed hierarchy transforms, geometry bounds, and renderer constraints before publishing the rendered pose.+This helper does not regenerate geometry or bind directly to renderer parts.++## Sampling and state++Sampling uses absolute time and does not depend on previous seeks.+Nonlooping clips clamp to the duration, while looping clips wrap modulo the duration.+Sample times must be finite and within zero and 3600 seconds.+Cubic scale and material overshoot fails validation rather than silently clamping.++Material samples retain the agent material domain, including roughness zero.+Combined emission and emissive color must remain within Float32 radiance limits.+Unlit materials also obey the HDR radiance ceiling.++Camera samples reject coincident eye and target positions, invalid up directions, and invalid lenses.++Authoring changes belong in revisioned recipe transactions.+Transient sampling must preserve the canonical recipe, source revision, topology revision, and checkpoint contents.+Checkpoint restore must reconstruct bindings from the restored recipe.+Job snapshots must retain authored motion independently of imported animation and renderer shader time.+The helper does not implement mixer controls, imported skin animation authoring, or live playback clocks.++## Bounds and checks++The controller accepts durations between 0.1 and 30 seconds.+A motion requires at least one track.+It can contain at most 128 tracks, 64 keys per track, and 2048 keys in total.+Values and tangents must remain finite at Float32 precision.+The scene integration must also enforce its total recipe byte budget.++1. Run `node --test tests/agent-motion.test.js`.++The CPU tests cover curves, looping, references, bounds, backward seeks, retained buffers, and failed sample publication.+Native rendering and published MCP verification belong to the integration layer.diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.mdindex f053316a..c45db99b 100644--- a/docs/agent-render-jobs.md+++ b/docs/agent-render-jobs.md@@ -4,7 +4,7 @@ Release `0.6.0` includes five MCP tools for asynchronous image and video renderi## Agent workflow-1. Install `67js` with `npm install 67js@npm:@codepawlhq/[email protected]`.+1. Install `67js` with `npm install 67js@npm:@codepawlhq/[email protected]`.2. Launch `npx 67js-mcp --backend cpu --jobs C:/projects/my-scene/render-jobs`.3. Create a scene and inspect its current revision.4. Submit `scene_render_submit` with the session ID, current revision and render settings.@@ -39,8 +39,13 @@ Video uses CPU H.264 encoding, even dimensions and one streamed frame at a time.The render backend can use GPU or CPU. Memory limits can reduce the actual output dimensions.Results report actual dimensions and measured timings. They do not embed video bytes or include audio.-Static procedural scenes remain static unless a shader uses renderer time.-Imported clips use explicit absolute sampling. The job tools do not author new animation tracks.+Release `0.7.0` samples recipe-owned [procedural motion](agent-motion.md) with `settings.motion: { start: 0 }`.+Job frames use `start + elapsed`. Omission holds the initial motion pose.+Nonlooping samples must fit the motion duration. Looping samples wrap and remain bounded by 3600 absolute seconds.++Creation and edits author tracks through scene recipes and `set-motion`, before job submission.+Static recipes remain static unless a shader uses renderer time.+Imported clips retain separate absolute sampling through `settings.animation`.## Controller APIdiff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 87e90abc..811ddd17 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -8,6 +8,9 @@ It does not execute JavaScript, access the DOM, or provide an MCP transport.Recipes also retain [lighting, fog, effects and directional shadow coverage](agent-look.md).Their patches and checkpoints share the same atomic revision contract as model edits.+Release `0.7.0` adds optional [procedural motion](agent-motion.md) and transient `sampleMotion(time)` seeks.+Recipe edits retain authored keyframes. Sampling preserves revisions and geometry while updating rendered transforms, materials and camera.+```jsimport { Renderer67 } from '67js';import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '67js/addons/agent-scene';diff --git a/docs/guide.md b/docs/guide.mdindex 773edab4..13beaf12 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -401,7 +401,8 @@ Disconnect observers, cancel animation frames, release pointer state and call `d## Models and AI agentsVersion `0.5.0` includes [agent scene sessions](/agent-scene.md) and the `67js-mcp` command.-Its [MCP server](/mcp.md) provides twelve tools for creating, inspecting, editing and previewing scenes through a persistent browser renderer.+Its [MCP server](/mcp.md) provides seventeen tools for authoring, previewing and exporting scenes through a persistent browser runtime.+Release `0.7.0` adds [agent motion](/agent-motion.md) for deterministic joint, material and camera keyframes.Read the MCP guide for npm installation, client configuration and CPU/GPU selection.The [agent look contract](/agent-look.md) adds retained lighting, volumetric fog, grading and directional shadows to recipe edits and checkpoints.The [asset adapter](/agent-asset.md) imports local catalog GLBs with supported textures, rigs, morphs and deterministic clip sampling.diff --git a/docs/mcp.md b/docs/mcp.mdindex 4e17fa45..1a8b77e9 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -6,6 +6,7 @@ The [official SDK documentation](https://ts.sdk.modelcontextprotocol.io/v2/) desRelease `0.5.0` exposes twelve tools for bounded JSON scene authoring and local GLB imports.Release `0.6.0` adds five render job tools for PNG images, still sequences and MP4 video.+Release `0.7.0` adds [procedural motion](agent-motion.md), transient preview seeks and motion sampling in snapshot jobs.It renders one active scene and returns PNG images through MCP image content.Tool results also contain JSON text and structured metadata.The image bytes appear only in the image content block.@@ -26,7 +27,7 @@ The MCP connection uses stdin and stdout, without an HTTP MCP listener.```Run the installed command with `npx 67js-mcp --backend gpu --memory 192`.- For a standalone launch, use `npx --package @codepawlhq/[email protected] 67js-mcp --backend gpu --memory 192`.+ For a standalone launch, use `npx --package @codepawlhq/[email protected] 67js-mcp --backend gpu --memory 192`.`67js-mcp --help` lists options. `67js-mcp --version` reports the installed version.2. Configure your MCP client with absolute paths to Node and the installed CLI:@@ -98,7 +99,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| `scene_create_asset` | `recipe` using `67js.asset` | Imported scene ID, revision, inspection and render status || `scene_inspect` | `sessionId`, optional `ids`, `limit`, `includeBounds` | Compact node records and revision || `scene_apply` | `sessionId`, `expectedRevision`, `operations` | Updated revision, inspection, and render status |-| `scene_look` | `sessionId`, optional `width`, `height` | PNG image and metadata |+| `scene_look` | `sessionId`, optional `width`, `height`, `motionTime` | PNG image and metadata || `scene_checkpoint` | `sessionId` | Checkpoint ID, session ID, and revision || `scene_restore` | `sessionId`, `checkpointId`, `expectedRevision` | Updated revision, inspection, and render status || `scene_release_checkpoint` | `sessionId`, `checkpointId` | Release confirmation |@@ -114,6 +115,11 @@ The recipe uses `format: '67js.scene'` and `schemaVersion: 1`.Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, and `tube`.Geometry fields remain flat inside each geometry record.Set operations use `set-node`, `set-material`, or `set-camera`, with fields directly on each command.++`set-motion` accepts a complete motion record or `null` to clear it.+`scene_look` can seek procedural `motionTime` without changing revisions. Omission preserves the last preview pose.+An explicit `null` restores the authored base pose. Imported assets retain their existing `set-animation` workflow.+`set-node` can rebind a mesh to another geometry/material pair.The recipe also accepts [authored lighting, fog, effects and shadow coverage](agent-look.md).@@ -181,7 +187,8 @@ The [asset scene contract](agent-asset.md) defines root transforms, material oveImported scenes retain their decoded topology. Mesh membership edits remain specific to procedural scenes.Their bounds describe authored base vertices in the sampled world transforms, without claiming deformed skin or morph bounds.-The tools expose no arbitrary JavaScript execution, URLs, arbitrary caller-selected file paths or animation track authoring.+The tools expose no arbitrary JavaScript execution, remote URLs or arbitrary caller-selected file paths.+Imported animation track authoring remains unsupported. Procedural tracks use the bounded motion recipe.Render jobs use a configured private store and fixed output filenames.See [render jobs](agent-render-jobs.md) for the snapshot workflow and storage limits.@@ -210,3 +217,6 @@ Use `node scripts/smoke-agent-topology.mjs cpu` for software rendering. Both modRun `node scripts/smoke-agent-assets.mjs` for actual imported WALL-E and textured rig previews through CPU stdio tools.The script checks content IDs, root edits, retained texture decoding, reverse animation sampling and exact checkpoint restoration.++Run `node scripts/smoke-agent-motion.mjs` for procedural motion through actual CPU MCP previews and jobs.+It checks shuffled PNG seeks, decoded MP4 frames, eight stills, active cancellation, source pose retention and checkpoint restoration.diff --git a/docs/release-verification.md b/docs/release-verification.mdindex 065fd4a8..74354166 100644--- a/docs/release-verification.md+++ b/docs/release-verification.md@@ -1,5 +1,28 @@# Release verification+## 0.7.0++Source checks used Windows Node.js, installed Chrome with CPU SwiftShader and FFmpeg H.264 encoding.+Registry publication and live deployment require separate checks against the pushed commit.++| Check | Measured result |+| --- | --- |+| Node tests | 402 tests passed. |+| Motion authoring | Local parent joints, material channels and camera paths sampled without changing authored recipes, revision or topology. |+| Atomicity | Invalid cubic scale, material overshoot, composed graph overflow and camera crossings preserved the previous pose. |+| Native image | The articulated lamp changed pose through actual MCP PNG previews. Shuffled seeks reproduced PNG bytes exactly. |+| Native video | The fixture produced eighteen decoded frames in a three-second H.264 MP4 with BT.709 metadata. First and last frames differed. |+| Jobs | Eight stills, completion and active cancellation preserved a nonzero source preview pose. Checkpoint restore reproduced the initial PNG. |+| Installed package | A clean project omitted development dependencies and source files. Modern and legacy SDK calls retained imported textures, skins and exact undo. |+| Cleanup | The installed motion CLI exited after disposal and MCP connection closure. |++The bounded public contract review found no significant findings within its source scope.+This review used one model family because the other reviewer remained unavailable. Its coverage is weaker than a completed cross review.++Representative square and portrait lamp frames were inspected.+These fixtures establish deterministic authoring and export behavior. They do not establish cinematic quality or hardware GPU performance.+Imported node-track authoring, motion mixing controls, character asset quality and broader agent modeling tools remain unfinished.+## 0.6.0Source checks used Windows Node.js, installed Chrome with CPU SwiftShader and FFmpeg H.264 encoding.diff --git a/package-lock.json b/package-lock.jsonindex 5eeb66f1..1d3e067c 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@codepawlhq/67js",- "version": "0.6.0",+ "version": "0.7.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@codepawlhq/67js",- "version": "0.6.0",+ "version": "0.7.0","license": "MIT","dependencies": {"playwright-core": "1.64.0"diff --git a/package.json b/package.jsonindex 5830c3d2..2096e57e 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@codepawlhq/67js",- "version": "0.6.0",+ "version": "0.7.0","private": false,"type": "module","description": "JavaScript tools for agent-driven 3D authoring, browser previews and memory-aware CPU/GPU rendering",@@ -47,7 +47,8 @@"docs/mcp.md","docs/agent-look.md","docs/agent-asset.md",- "docs/agent-render-jobs.md"+ "docs/agent-render-jobs.md",+ "docs/agent-motion.md"],"main": "./build/67.module.js","module": "./build/67.module.js",@@ -99,6 +100,7 @@"smoke:agent-look": "node scripts/smoke-agent-look.mjs","smoke:agent-assets": "node scripts/smoke-agent-assets.mjs","smoke:agent-render-jobs": "node scripts/smoke-agent-render-jobs.mjs",+ "smoke:agent-motion": "node scripts/smoke-agent-motion.mjs","smoke:frame-encoder": "node scripts/smoke-frame-encoder.mjs","smoke:enhancements": "node scripts/smoke-enhancements.mjs","smoke:site": "node scripts/smoke-site.mjs",diff --git a/public/llms.txt b/public/llms.txtindex 819c2919..fe1ebf1f 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -9,6 +9,13 @@ The installed package determines available APIs. Release metadata describes theVersion `0.5.0` adds `67js/addons/agent-scene` and the `67js-mcp` command.Version `0.6.0` adds asynchronous snapshot render jobs. Read `/agent-render-jobs.md` for submission, progress, cancellation and artifact results.++Version `0.7.0` adds recipe motion and atomic set-motion authoring. Read `/agent-motion.md` before generating tracks.+Use scene_look motionTime for absolute procedural preview seeks. Omit it to preserve the last pose, or use null for the authored base.++Preview seeks do not advance revisions. Creation, edits and restore sample zero when motion exists.+Jobs use settings.motion.start plus elapsed time. Imported clips and renderer shader time retain separate controls.+Read `/agent-scene.md` for versioned JSON recipes, stable IDs, expected revisions, atomic edits and bounded checkpoints.Use `session.inspect()` for compact object facts and `session.exportRecipe()` for detached JSON.Keep renderer-facing geometry immutable. Call `renderer.updateParts(session.parts)` after a successful edit or restore.@@ -42,7 +49,7 @@ Removing a parent requires `recursive: true` or reparenting/removing its childreActive, checkpoint and staged geometry share a budget. Release unused checkpoints before increasing detail.Topology changes reconcile rigid, untextured GPU parts. Geometry stays immutable and surviving shared buffers remain allocated.-It exposes no arbitrary code, file access, asset providers, animation authoring or video jobs.+Tools accept bounded JSON and configured local assets. They expose no arbitrary code, remote asset providers or caller-selected file paths.- [Release metadata](https://67js.codepawl.com/release.json): package name, version, publication status, install command, module URL and commit.- [Complete plain-text guide](https://67js.codepawl.com/guide.md): renderer, parts, materials, cameras, animation, lifecycle, export and troubleshooting.diff --git a/scripts/agent-motion-fixture.mjs b/scripts/agent-motion-fixture.mjsnew file mode 100644index 00000000..dcde4cd3--- /dev/null+++ b/scripts/agent-motion-fixture.mjs@@ -0,0 +1,96 @@+function rotationZ(angle) {+ return [0, 0, Math.sin(angle / 2), Math.cos(angle / 2)];+}++function headRotation(angle) {+ const pitch = -0.8;+ return [Math.sin(pitch / 2) * Math.cos(angle / 2), Math.sin(pitch / 2) * Math.sin(angle / 2),+ Math.cos(pitch / 2) * Math.sin(angle / 2), Math.cos(pitch / 2) * Math.cos(angle / 2)];+}++/** A JSON-only articulated lamp for the real MCP motion and rendering proof. */+export function createAgentMotionFixture() {+ const nodes = [];+ function mesh(id, geometry, material, parent, translation, scale, rotation = [0, 0, 0, 1]) {+ nodes.push({ id, geometry, material, parent, translation, scale, rotation });+ }+ const alongZ = [Math.SQRT1_2, 0, 0, Math.SQRT1_2];+ mesh('desk', 'cylinder', 'desk', null, [0, -0.035, 0], [4, 0.07, 4]);+ mesh('base-foot', 'cylinder', 'rubber', null, [0, 0.06, 0], [0.57, 0.12, 0.57]);+ mesh('base-shell', 'cylinder', 'paint', null, [0, 0.14, 0], [0.54, 0.14, 0.54]);+ mesh('base-cap', 'cylinder', 'paint', null, [0, 0.225, 0], [0.3, 0.06, 0.3]);+ nodes.push({ id: 'shoulder', translation: [0, 0.34, 0], rotation: rotationZ(-0.46) });+ mesh('shoulder-axle', 'cylinder', 'steel', 'shoulder', [0, 0, 0], [0.13, 0.52, 0.13], alongZ);+ for (const side of [-1, 1]) {+ const suffix = side < 0 ? 'back' : 'front';+ mesh(`lower-arm-${suffix}`, 'box', 'paint', 'shoulder', [0, 0.7, side * 0.15], [0.105, 1.34, 0.075]);+ mesh(`shoulder-bolt-${suffix}`, 'cylinder', 'brass', 'shoulder', [0, 0, side * 0.29], [0.078, 0.055, 0.078], alongZ);+ mesh(`spring-${suffix}`, 'spring', 'steel', 'shoulder', [0.15, 0.25, side * 0.15], [1, 1, 1]);+ }+ nodes.push({ id: 'elbow', parent: 'shoulder', translation: [0, 1.4, 0], rotation: rotationZ(1.12) });+ mesh('elbow-axle', 'cylinder', 'steel', 'elbow', [0, 0, 0], [0.12, 0.52, 0.12], alongZ);+ for (const side of [-1, 1]) {+ const suffix = side < 0 ? 'back' : 'front';+ mesh(`upper-arm-${suffix}`, 'box', 'paint', 'elbow', [0, 0.52, side * 0.15], [0.105, 1, 0.075]);+ mesh(`elbow-bolt-${suffix}`, 'cylinder', 'brass', 'elbow', [0, 0, side * 0.29], [0.078, 0.055, 0.078], alongZ);+ }+ nodes.push({ id: 'head', parent: 'elbow', translation: [0, 1.04, 0], rotation: headRotation(-0.68) });+ mesh('head-axle', 'cylinder', 'steel', 'head', [0, 0, 0], [0.095, 0.42, 0.095], alongZ);+ mesh('shade', 'shade', 'paint', 'head', [0, -0.02, 0], [1, 1, 1]);+ mesh('reflector', 'reflector', 'cream', 'head', [0, -0.02, 0], [1, 1, 1]);+ mesh('bulb', 'sphere', 'bulb', 'head', [0, -0.30, 0], [0.17, 0.2, 0.17]);+ mesh('socket', 'cylinder', 'steel', 'head', [0, -0.08, 0], [0.085, 0.16, 0.085]);+ const springPath = Array.from({ length: 97 }, (_, index) => {+ const angle = index / 96 * Math.PI * 16;+ return [Math.cos(angle) * 0.05, index / 96 * 0.7, Math.sin(angle) * 0.05];+ });+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [+ { id: 'box', type: 'box', bevel: 0.14, subdivisions: 3 },+ { id: 'cylinder', type: 'cylinder', segments: 48, bevel: 0.04, bevelSegments: 4 },+ { id: 'sphere', type: 'sphere', segments: 40, rings: 24 },+ { id: 'shade', type: 'lathe', segments: 64,+ profile: [[0.085, 0], [0.13, -0.1], [0.45, -0.48], [0.5, -0.56], [0.485, -0.58], [0.435, -0.5], [0.11, -0.1], [0.07, 0], [0.085, 0]] },+ { id: 'reflector', type: 'lathe', segments: 64,+ profile: [[0.074, -0.04], [0.108, -0.11], [0.426, -0.5], [0.47, -0.556], [0.465, -0.56], [0.422, -0.5], [0.1, -0.11], [0.068, -0.04], [0.074, -0.04]] },+ { id: 'spring', type: 'tube', path: springPath, radius: 0.012, radialSegments: 8 },+ ],+ materials: [+ { id: 'paint', color: [0.06, 0.32, 0.27], metallic: 0.55, roughness: 0.28 },+ { id: 'steel', color: [0.25, 0.29, 0.31], metallic: 0.92, roughness: 0.25 },+ { id: 'brass', color: [0.63, 0.36, 0.12], metallic: 0.85, roughness: 0.27 },+ { id: 'cream', color: [0.72, 0.66, 0.49], metallic: 0.2, roughness: 0.35 },+ { id: 'rubber', color: [0.012, 0.016, 0.019], roughness: 0.9 },+ { id: 'desk', color: [0.08, 0.10, 0.12], roughness: 0.72 },+ { id: 'bulb', color: [0.95, 0.67, 0.30], emissiveColor: [1, 0.57, 0.22], emission: 3, roughness: 0.35 },+ ],+ nodes,+ camera: { eye: [4.2, 2.9, 5.4], target: [0.15, 1.2, 0], fov: 34, near: 0.1, far: 40 },+ environment: { world: true, daylight: 1, keyColor: [0.8, 0.9, 1], keyIntensity: 1.6,+ fillIntensity: 3, ambientIntensity: 1.3, lightDirection: [-0.7, 1, 0.7],+ skyTop: [0.10, 0.13, 0.17], skyBottom: [0.22, 0.25, 0.30], fogDensity: 0 },+ effects: { exposure: 1.15, grain: 0, vignette: 0.15, bloom: { strength: 0.16, threshold: 1.5 } },+ shadow: { target: [0.1, 1.1, 0], extent: 4.5, distance: 9, far: 22 },+ motion: {+ duration: 3,+ tracks: [+ { kind: 'node', id: 'shoulder', property: 'rotation', interpolation: 'SMOOTH', keyframes: [+ { time: 0, value: rotationZ(-0.46) }, { time: 1.5, value: rotationZ(-0.20) }, { time: 3, value: rotationZ(-0.55) },+ ] },+ { kind: 'node', id: 'elbow', property: 'rotation', interpolation: 'SMOOTH', keyframes: [+ { time: 0, value: rotationZ(1.12) }, { time: 1.5, value: rotationZ(0.65) }, { time: 3, value: rotationZ(1.35) },+ ] },+ { kind: 'node', id: 'head', property: 'rotation', interpolation: 'SMOOTH', keyframes: [+ { time: 0, value: headRotation(-0.68) }, { time: 1.5, value: headRotation(-0.85) }, { time: 3, value: headRotation(-0.48) },+ ] },+ { kind: 'material', id: 'bulb', property: 'emission', interpolation: 'SMOOTH', keyframes: [+ { time: 0, value: 1 }, { time: 1.5, value: 5 }, { time: 3, value: 2 },+ ] },+ { kind: 'camera', property: 'eye', interpolation: 'SMOOTH', keyframes: [+ { time: 0, value: [4.2, 2.9, 5.4] }, { time: 3, value: [3.4, 2.6, 5.2] },+ ] },+ ],+ },+ };+}diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex fa68e05f..4e07eeb7 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -28,7 +28,7 @@ function validatePreviewCamera(camera) {}function candidateCamera(record, operations) {- const camera = record.scene.camera;+ const camera = record.scene.exportRecipe().camera;for (const operation of operations) {if (operation.type === 'set-camera') {for (const field of ['eye', 'target', 'up', 'fov', 'near', 'far']) {@@ -198,12 +198,15 @@ window.__agentPreview = {throw error;}},- frame({ sessionId, animation, rendererTime = 0 }) {+ frame({ sessionId, animation, motionTime, rendererTime = 0 }) {const record = requireSession(sessionId);if (!Number.isFinite(rendererTime) || rendererTime < 0 || rendererTime > 3600) throw new RangeError('Invalid render time.');if (animation) {record.scene.apply([{ type: 'set-animation', clip: animation.clip, time: animation.time }], { expectedRevision: record.scene.revision });}+ if (motionTime !== undefined) {+ record.scene.sampleMotion(motionTime);+ }draw(record, rendererTime);return renderInfo(record.renderer);},@@ -248,15 +251,22 @@ window.__agentPreview = {record.scene.apply(operations, { expectedRevision });return mutationStatus(record);},- look({ sessionId }) {+ look({ sessionId, motionTime }) {const record = requireSession(sessionId);+ if (motionTime !== undefined) {+ if (typeof record.scene.sampleMotion !== 'function') {+ throw new RangeError('Procedural motion time is unavailable for imported assets.');+ }+ record.scene.sampleMotion(motionTime);+ }draw(record);const render = renderInfo(record.renderer);record.lastRender = render;return {data: canvas.toDataURL('image/png').split(',')[1],mimeType: 'image/png',- metadata: { sessionId, revision: record.scene.revision, topologyRevision: record.scene.topologyRevision, ...render },+ metadata: { sessionId, revision: record.scene.revision, topologyRevision: record.scene.topologyRevision,+ motionTime: record.scene.motionTime ?? null, ...render },};},checkpoint({ sessionId, checkpointId }) {diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjsindex 6414da3e..3f90f54f 100644--- a/scripts/agent-render-jobs.mjs+++ b/scripts/agent-render-jobs.mjs@@ -51,8 +51,8 @@ function jsonCopy(value, maximum = MAXIMUM_JSON_BYTES) {return JSON.parse(text);}-function settingsFrom(input, clips) {- objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'rendererTime'], 'settings');+function settingsFrom(input, clips, recipe) {+ objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime'], 'settings');if (!['image', 'stills', 'video'].includes(input.kind)) throw new TypeError('kind must be image, stills or video.');const width = boundedNumber(input.width, 64, 1024, 'width', true);const height = boundedNumber(input.height, 64, 1024, 'height', true);@@ -62,6 +62,23 @@ function settingsFrom(input, clips) {const frameCount = input.kind === 'image' ? 1 : input.kind === 'stills' ? 8 : Math.ceil(fps * duration);if (frameCount > 900) throw new RangeError('Job exceeds 900 frames.');const result = { kind: input.kind, width, height, fps, duration, frameCount };+ const lastSampleTime = input.kind === 'image' ? 0 : input.kind === 'stills' ? duration : (frameCount - 1) / fps;+ if (input.motion !== undefined) {+ objectKeys(input.motion, ['start'], 'motion');+ if (recipe?.format !== '67js.scene' || !recipe.motion) {+ throw new RangeError('Motion settings require a procedural recipe with authored motion.');+ }+ const motionDuration = boundedNumber(recipe.motion.duration, 0.1, 30, 'motion duration');+ if (recipe.motion.loop !== undefined && typeof recipe.motion.loop !== 'boolean') {+ throw new TypeError('Motion loop must be boolean.');+ }+ const start = boundedNumber(input.motion.start === undefined ? 0 : input.motion.start, 0, 3600, 'motion start');+ boundedNumber(start + lastSampleTime, 0, 3600, 'motion end');+ if (!recipe.motion.loop && start + lastSampleTime > motionDuration) {+ throw new RangeError('Motion range exceeds the authored duration.');+ }+ result.motion = { start };+ }if (input.animation !== undefined) {objectKeys(input.animation, ['clip', 'start'], 'animation');const clip = boundedNumber(input.animation.clip, 0, clips.length - 1, 'clip', true);@@ -75,7 +92,6 @@ function settingsFrom(input, clips) {} else {result.rendererTime = { start: 0, rate: 1 };}- const lastSampleTime = input.kind === 'image' ? 0 : input.kind === 'stills' ? duration : (frameCount - 1) / fps;boundedNumber(result.rendererTime.start + lastSampleTime * result.rendererTime.rate, 0, 3600, 'renderer time end');return result;}@@ -273,7 +289,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {if (asset.sha256 !== snapshot.recipe.assetId) throw new Error('Persisted asset does not match its recipe digest.');}const { frameCount, ...inputSettings } = record.settings;- const settings = settingsFrom(inputSettings, snapshot.clips ?? []);+ const settings = settingsFrom(inputSettings, snapshot.clips ?? [], snapshot.recipe);if (frameCount !== settings.frameCount) throw new Error('Invalid persisted frame count.');record.settings = settings;objectKeys(record.progress, ['frames', 'maximumPendingFrames'], 'persisted progress');@@ -412,7 +428,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {const recipe = jsonCopy(input.snapshot.recipe);if (!recipe || typeof recipe !== 'object' || Array.isArray(recipe)) throw new TypeError('Snapshot recipe must be a JSON object.');const snapshotMetadata = jsonCopy({ recipe, clips });- const settings = settingsFrom(input.settings, clips);+ const settings = settingsFrom(input.settings, clips, recipe);if (input.snapshot.assetBytes !== undefined && (!Buffer.isBuffer(input.snapshot.assetBytes) || input.snapshot.assetBytes.length > MAXIMUM_ASSET_BYTES || !input.snapshot.assetBytes.length)) throw new RangeError('Asset snapshot must be a nonempty Buffer of at most 16 MiB.');const snapshot = { recipe, clips, ...(input.snapshot.assetBytes ? { assetBytes: Buffer.from(input.snapshot.assetBytes) } : {}) };if (recipe.format === '67js.asset' && (!snapshot.assetBytes || createHash('sha256').update(snapshot.assetBytes).digest('hex') !== recipe.assetId)) throw new Error('Asset snapshot bytes must match the recipe SHA256 assetId.');diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 7c2e722d..d6e48429 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -236,6 +236,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo: settings.kind === 'stills' ? settings.duration * frame / (settings.frameCount - 1) : 0;const frameInput = { sessionId: jobId,rendererTime: (settings.rendererTime?.start ?? 0) + elapsed * (settings.rendererTime?.rate ?? 1),+ ...(settings.motion ? { motionTime: settings.motion.start + elapsed } : {}),...(settings.animation ? { animation: { clip: settings.animation.clip, time: settings.animation.start + elapsed } } : {}) };const renderStarted = performance.now();const rendered = await jobPage.evaluate(input => window.__agentPreview.frame(input), frameInput);@@ -317,7 +318,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoencoder: 'CPU H.264', audio: false, previewSuspendedDuringJob: true,records: jobRoot ? (await jobs()).list().map(record => ({ jobId: record.jobId, state: record.state,sourceRevision: record.sourceRevision, progress: record.progress })) : [] },- unsupported: ['remote asset providers', 'arbitrary code execution', 'animation authoring', 'job audio'],+ unsupported: ['remote asset providers', 'arbitrary code execution', 'imported animation track authoring', 'job audio'],};},create({ recipe }) {@@ -365,7 +366,8 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memothrow new RangeError('Preview dimensions must be integers from 64 to 1024.');}await page.setViewportSize({ width, height });- const result = await invoke('look', { sessionId: input.sessionId });+ const result = await invoke('look', { sessionId: input.sessionId,+ ...(input.motionTime !== undefined ? { motionTime: input.motionTime } : {}) });if (Buffer.byteLength(result.data, 'base64') > MAXIMUM_IMAGE_BYTES) {throw new Error('The PNG exceeds the 1 MiB image response budget. Request a smaller preview.');}diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 36aaeac5..6f859585 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -106,6 +106,36 @@ const geometry = z.discriminatedUnion('type', [z.strictObject({ id: identifier, type: z.literal('extrude'), contour: ring, holes: z.array(ring).max(128).optional(), depth: finite.optional(), steps: detail(1, 256), bevel: finite.optional(), bevelThickness: finite.optional(), bevelSegments: detail(1, 32) }),z.strictObject({ id: identifier, type: z.literal('tube'), path: z.array(vector3).min(2).max(4096), radius: finite.optional(), segments, radialSegments: detail(3, 128), closed: z.boolean().optional() }),]);+function motionTrack(kind, property, value, tangent) {+ return z.strictObject({+ kind: z.literal(kind),+ ...(kind === 'camera' ? {} : { id: identifier }),+ property: z.literal(property),+ interpolation: z.enum(['LINEAR', 'STEP', 'SMOOTH', 'CUBICSPLINE']).optional(),+ keyframes: z.array(z.strictObject({+ time: z.number().min(0).max(30), value,+ inTangent: tangent.optional(), outTangent: tangent.optional(),+ })).min(1).max(64),+ });+}+const motion = z.strictObject({+ duration: z.number().min(0.1).max(30),+ loop: z.boolean().optional(),+ tracks: z.array(z.union([+ motionTrack('node', 'translation', vector3, vector3),+ motionTrack('node', 'rotation', quaternion, quaternion),+ motionTrack('node', 'scale', z.tuple([positive, positive, positive]), vector3),+ motionTrack('material', 'color', color, vector3),+ motionTrack('material', 'emissiveColor', z.tuple([nonnegative, nonnegative, nonnegative]), vector3),+ motionTrack('material', 'emission', nonnegative, finite),+ motionTrack('material', 'metallic', unit, finite),+ motionTrack('material', 'roughness', unit, finite),+ motionTrack('camera', 'eye', vector3, vector3),+ motionTrack('camera', 'target', vector3, vector3),+ motionTrack('camera', 'fov', finite.gt(0).lt(180), finite),+ motionTrack('camera', 'roll', finite, finite),+ ])).min(1).max(128),+}).describe('One absolute-time procedural clip. Local node transforms propagate through parents. Cubic tangents are derivatives per second. Backend checks references, duplicate tracks, 2048 total keys and every sampled pose.');const recipe = z.strictObject({format: z.literal('67js.scene'),schemaVersion: z.literal(1),@@ -116,6 +146,7 @@ const recipe = z.strictObject({environment: environment.optional(),effects: effects.optional(),shadow: shadow.optional(),+ motion: motion.nullable().optional(),}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');const assetRecipe = z.strictObject({format: z.literal('67js.asset'),@@ -136,6 +167,7 @@ const operation = z.discriminatedUnion('type', [z.strictObject({ type: z.literal('set-node'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields }),z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),+ z.strictObject({ type: z.literal('set-motion'), motion: motion.nullable() }),z.strictObject({ type: z.literal('set-environment'), environment }),z.strictObject({ type: z.literal('set-effects'), effects }),z.strictObject({ type: z.literal('set-shadow'), shadow }),@@ -159,8 +191,9 @@ const renderSettings = z.strictObject({fps: z.number().int().min(1).max(30).optional(),duration: z.number().min(0.1).max(30).optional(),animation: z.strictObject({ clip: z.number().int().min(0), start: z.number().min(0).max(3600).optional() }).optional(),+ motion: z.strictObject({ start: z.number().min(0).max(3600).optional() }).optional(),rendererTime: z.strictObject({ start: z.number().min(0).max(3600).optional(), rate: z.number().min(-16).max(16).optional() }).optional(),-}).describe('Immutable snapshot render: one PNG, eight evenly spaced PNGs, or CPU H.264 MP4. Video dimensions must be even. Defaults: 24 fps, one second. Animation must fit the selected imported clip.');+}).describe('Immutable snapshot render: one PNG, eight evenly spaced PNGs, or CPU H.264 MP4. Video dimensions must be even. Defaults: 24 fps, one second. Use motion.start for procedural recipe tracks or animation for an imported clip. Omitted motion holds time zero. Nonlooping samples must fit the authored duration.');const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };const edit = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };@@ -195,8 +228,8 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioregister('scene_asset_catalog', 'List content-bound GLB IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));register('scene_inspect', 'Read revision, counts and selected nodes. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));- register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership commands. Imported assets support set-root and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Look patches and add commands contain nested records. Backend validates each scene mode before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));- register('scene_look', 'Render the active scene as a bounded PNG image for visual assessment.', z.strictObject({ ...sessionFields, width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.') }), readOnly, async argumentsValue => {+ register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership and set-motion authoring. Imported assets support set-root and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Motion, look patches and add commands contain nested records. Backend validates each scene mode before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));+ register('scene_look', 'Render the active scene as a bounded PNG. Optional procedural motionTime seeks without changing revision; null restores the authored base pose. Omit to retain the last preview pose.', z.strictObject({ ...sessionFields, motionTime: z.number().min(0).max(3600).nullable().optional(), width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.') }), readOnly, async argumentsValue => {const { data, mimeType, metadata } = await runtime.look(argumentsValue);return { content: [{ type: 'image', data, mimeType }, { type: 'text', text: JSON.stringify(metadata) }], structuredContent: metadata };});diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex cfb10a9c..b046b884 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -41,7 +41,7 @@ const sourceDocuments = ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md','export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md','camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',- 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md',+ 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md',];for (const name of sourceDocuments) {await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));diff --git a/scripts/smoke-agent-motion.mjs b/scripts/smoke-agent-motion.mjsnew file mode 100644index 00000000..6ae579e4--- /dev/null+++ b/scripts/smoke-agent-motion.mjs@@ -0,0 +1,151 @@+import assert from 'node:assert/strict';+import { mkdtemp, mkdir, writeFile, copyFile } from 'node:fs/promises';+import { tmpdir, constants, setPriority } from 'node:os';+import { join, resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { setTimeout as delay } from 'node:timers/promises';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';+import { createAgentMotionFixture } from './agent-motion-fixture.mjs';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-motion-'));+const jobs = join(directory, 'jobs');+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');+const transport = new StdioClientTransport({ command: process.execPath,+ args: [cli, '--backend', 'cpu', '--memory', '96', '--jobs', jobs],+ cwd: directory, stderr: 'pipe' });+let diagnostics = '';+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });+const client = new Client({ name: '67js-motion-proof', version: '1' });++async function call(name, argumentsValue = {}, timeout = 30000) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);+ return result;+}++async function status(jobId, predicate = record => ['completed', 'cancelled', 'failed'].includes(record.state)) {+ const deadline = Date.now() + 60000;+ while (Date.now() < deadline) {+ const record = (await call('scene_render_status', { jobId })).structuredContent;+ if (predicate(record)) {+ return record;+ }+ await delay(100);+ }+ throw new Error('Motion job did not reach its expected state within 60 seconds.');+}++async function look(sessionId, motionTime, width = 480, height = 480) {+ const result = await call('scene_look', { sessionId, width, height,+ ...(motionTime !== undefined ? { motionTime } : {}) });+ assert.equal(result.structuredContent.revision, 0);+ assert.match(result.structuredContent.graphics, /swiftshader/i);+ return result.content.find(item => item.type === 'image').data;+}++try {+ await client.connect(transport);+ const fixture = createAgentMotionFixture();+ const created = (await call('scene_create', { recipe: fixture }, 180000)).structuredContent;+ assert.equal(created.inspection.motion.tracks, 5);+ const sessionId = created.sessionId;+ const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;+ const canonical = (await call('scene_export_recipe', { sessionId })).structuredContent.recipe;+ const start = await look(sessionId, 0);+ const middle = await look(sessionId, 1.5);+ const end = await look(sessionId, 3);+ assert.notEqual(start, middle);+ assert.notEqual(middle, end);+ for (const time of [0.3, 2.7, 0, 1.5, 3]) {+ const expected = time === 0 ? start : time === 1.5 ? middle : time === 3 ? end : null;+ const actual = await look(sessionId, time);+ if (expected) {+ assert.equal(actual, expected, `Shuffled seek ${time} must reproduce PNG bytes.`);+ }+ }+ await look(sessionId, 1.5);+ assert.deepEqual((await call('scene_export_recipe', { sessionId })).structuredContent.recipe, canonical);+ await mkdir('artifacts', { recursive: true });+ await writeFile('artifacts/agent-motion-start.png', Buffer.from(start, 'base64'));+ await writeFile('artifacts/agent-motion-middle.png', Buffer.from(middle, 'base64'));+ await writeFile('artifacts/agent-motion-end.png', Buffer.from(end, 'base64'));+ const portrait = await look(sessionId, 1.5, 390, 640);+ await writeFile('artifacts/agent-motion-portrait.png', Buffer.from(portrait, 'base64'));+ await look(sessionId, 1.5);+ const completed = [];+ let video;+ let videoResult;+ for (const kind of ['stills', 'video']) {+ const submitted = (await call('scene_render_submit', { sessionId, expectedRevision: 0, settings: {+ kind, width: 480, height: 480, fps: 6, duration: 3, motion: { start: 0 }, rendererTime: { rate: 0 },+ } })).structuredContent;+ assert.equal((await status(submitted.jobId)).state, 'completed');+ const result = (await call('scene_render_result', { jobId: submitted.jobId })).structuredContent;+ assert.equal(result.metrics.maximumPendingFrames, 1);+ assert.equal(await look(sessionId), middle, 'Renderer lease must preserve the nonzero source preview pose.');+ if (kind === 'stills') {+ assert.equal(result.artifacts.length, 8);+ for (let index = 0; index < 8; index++) {+ await copyFile(result.artifacts[index].path, `artifacts/agent-motion-still-${index}.png`);+ }+ } else {+ videoResult = result;+ const output = result.artifacts[0].path;+ await copyFile(output, 'artifacts/agent-motion.mp4');+ const probe = spawnSync('ffprobe', ['-v', 'error', '-count_frames', '-show_entries',+ 'stream=width,height,nb_read_frames,codec_name,color_space:format=duration', '-of', 'json', output],+ { encoding: 'utf8', windowsHide: true });+ assert.equal(probe.status, 0, probe.stderr);+ video = JSON.parse(probe.stdout);+ assert.equal(video.streams[0].nb_read_frames, '18');+ assert.equal(video.streams[0].color_space, 'bt709');+ assert.equal(Number(video.format.duration), 3);+ const decoded = spawnSync('ffmpeg', ['-v', 'error', '-i', output, '-frames:v', '18',+ '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-threads', '1', 'pipe:1'],+ { windowsHide: true, maxBuffer: 16 * 1024 ** 2 });+ assert.equal(decoded.status, 0, decoded.stderr.toString());+ const frameBytes = 480 * 480 * 3;+ assert.equal(decoded.stdout.length, frameBytes * 18);+ assert.notDeepEqual(decoded.stdout.subarray(0, frameBytes), decoded.stdout.subarray(frameBytes * 17));+ }+ completed.push(submitted.jobId);+ }+ const cancelled = (await call('scene_render_submit', { sessionId, expectedRevision: 0,+ settings: { kind: 'video', width: 480, height: 480, fps: 30, duration: 3, motion: {} } })).structuredContent;+ await status(cancelled.jobId, record => record.progress.frames > 0);+ await call('scene_render_cancel', { jobId: cancelled.jobId });+ assert.equal((await status(cancelled.jobId)).state, 'cancelled');+ assert.equal(await look(sessionId), middle);+ const restored = (await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: 0 })).structuredContent;+ assert.equal(restored.revision, 1);+ const restoredImage = await call('scene_look', { sessionId, width: 480, height: 480 });+ assert.equal(restoredImage.content[0].data, start);+ for (const jobId of [...completed, cancelled.jobId]) {+ await call('scene_render_release', { jobId });+ }+ await call('scene_dispose', { sessionId });+ const processId = transport.pid;+ await client.close();+ const deadline = Date.now() + 7000;+ let exited = false;+ while (Date.now() < deadline && !exited) {+ try {+ process.kill(processId, 0);+ await delay(50);+ } catch (error) {+ assert.equal(error.code, 'ESRCH');+ exited = true;+ }+ }+ assert.equal(exited, true, `Owned MCP process must exit: ${diagnostics}`);+ await writeFile('artifacts/mcp-agent-motion-proof.json', JSON.stringify({ cli, video, videoResult,+ shuffledPngSeeksExact: true, sourceNonzeroPosePreserved: true, activeCancel: true,+ canonicalRecipeUnchanged: true, checkpointRetained: true, eightStills: true, eofCleanup: true }, null, 2));+ console.log(JSON.stringify({ frames: 18, duration: 3, shuffledPngSeeksExact: true,+ sourceNonzeroPosePreserved: true, activeCancel: true, eofCleanup: true,+ elapsedSeconds: videoResult.metrics.elapsedSeconds }));+} finally {+ await client.close();+}diff --git a/scripts/smoke-mcp-package.mjs b/scripts/smoke-mcp-package.mjsindex 64c576ad..091c5ef4 100644--- a/scripts/smoke-mcp-package.mjs+++ b/scripts/smoke-mcp-package.mjs@@ -155,7 +155,7 @@ for (const era of ['modern', 'legacy']) {assert.doesNotMatch(diagnostics, /cleanup failed|shutdown failed/);assert.throws(() => process.kill(processId, 0), /ESRCH/);}-const report = { packageName: metadata.name, version: metadata.version, archiveBytes: packed.size,+const report = { packageName: metadata.name, version: metadata.version, archiveBytes: packed.size, cli,published, protocolOnly,runtimeDevelopmentDependencies: false, nativeShimVersion: true, builtOutputHashesMatch: true,sourceCommit: manifest.sourceCommit, eofWithActiveScene: !protocolOnly, results };diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 7531e25a..91b75368 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -168,6 +168,22 @@ if (${!published}) {agentScene.restore(lookCheckpoint, { expectedRevision: agentScene.revision });assert.deepEqual(agentScene.exportRecipe(), originalLook);agentScene.releaseCheckpoint(lookCheckpoint);+ const motionCheckpoint = agentScene.checkpoint();+ const authoredRecipe = agentScene.exportRecipe();+ agentScene.apply([{ type: 'set-motion', motion: { duration: 1, tracks: [{+ kind: 'node', id: 'object', property: 'translation', interpolation: 'SMOOTH',+ keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [3, 0, 0] }],+ }] } }], { expectedRevision: agentScene.revision });+ const motionRevision = agentScene.revision;+ agentScene.sampleMotion(1);+ assert.equal(agentPart.matrix[12], 3);+ agentScene.sampleMotion(0);+ assert.equal(agentPart.matrix[12], 0);+ assert.equal(agentScene.revision, motionRevision);+ assert.equal(agentScene.parts[0], agentPart);+ agentScene.restore(motionCheckpoint, { expectedRevision: agentScene.revision });+ assert.deepEqual(agentScene.exportRecipe(), authoredRecipe);+ agentScene.releaseCheckpoint(motionCheckpoint);const { createAgentAssetScene } = await import('67js/addons/agent-asset');const parsedAgentAsset = await parseGltf(exportGlb(agentScene.parts));const importedSession = createAgentAssetScene(parsedAgentAsset, { format: '67js.asset', schemaVersion: 1, assetId: '0'.repeat(64) });diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex c41a17c3..4114e994 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -32,6 +32,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`. Verify source versus published availability before importing.- Agent tool calls use the installed `67js-mcp` stdio server from release `0.5.0` onward. Read `docs/mcp.md` for launch and PNG feedback.- Agent render jobs use `docs/agent-render-jobs.md`. Check source versus published support, configure a private store and poll until terminal.+- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.- An image or video export uses `render-67js-media`.Read [scene-contract.md](references/scene-contract.md) before creating parts or changing materials.diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 3bd0ddd2..8f321037 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -116,19 +116,22 @@ Static `sculptGeometry` strokes return new geometry before renderer upload. ReadIt rejects skin, morph, assembly and procedural targets. It does not detect arbitrary mesh penetration or provide animated shrinkwrap.Static `createMeshQueryIndex` copies geometry into an owned disposable BVH. Read `docs/mesh-query.md` for numerical and work limits.-Pass current affine matrices to `createMeshPairQuery(...).evaluate()`; rebuild indices after editing geometry.+Pass current affine matrices to `createMeshPairQuery(...).evaluate()`. Rebuild indices after editing geometry.Closed-solid containment requires two `solid: true` indices. Surface contact does not prove volume penetration or z-fighting.+Use `docs/primitives.md` for exact seam closure and preallocation bounds. Preserve indeterminate and budget errors rather than reporting a miss.Static `shrinkwrapGeometry(source, target, options)` returns new target-local geometry and query statistics.Read `docs/shrinkwrap.md` for nearest/project modes, total query budgets and explicit miss handling.Share the target matrix with the wrapped part. Local distances are not world distances under nonuniform target scale.Compute once before renderer upload. Matching topology permits relative morph animation instead of rebuilding the BVH every frame.+Vertex clearance does not certify every triangle interior against a curved or nonconvex target. Use the clipping patch for conforming surface overlays.Use `createSurfaceAttachment(target, { triangle, barycentric, clearance })` for a rigid accessory following a posed triangle.Read `docs/surface-attachment.md`. Share its retained `matrix` with the accessory, update the target pose, then update the attachment before renderer upload.The frame follows relative morphs before four-influence skinning. Clearance uses world units and the geometric triangle normal.+Bind immutable geometry once. This sparse point attachment does not deform the accessory or certify clearance over its footprint.The surface-attachment addon is included in npm `0.4.1`.@@ -136,29 +139,43 @@ Agent authoring uses `createAgentScene(recipe, limits)` from `67js/addons/agent-This addon is included in npm `0.5.0` and later.Read `docs/agent-scene.md` for schema version one, immutable resources and atomic topology commands.Start with capabilities and bounded inspection. Edit stable IDs through one `apply` batch with the current `expectedRevision`.+Checkpoint before uncertain changes, inspect and render the result, then restore or release the checkpoint.For rigid, untextured scenes, compare `session.topologyRevision` with the uploaded revision after successful edits.Call `renderer.replaceParts(session.parts)` for changed topology or `renderer.updateParts(session.parts)` for retained parts, then render the detached camera.+Use add/remove commands for nodes and shared resources, and `set-node` geometry/material fields for rebinding.-Release unused checkpoints before increasing detail; active, checkpoint and staged geometry share a peak allocation budget.-Keep JSON commands and snapshots exposed to agents; retained matrices and immutable geometry belong to the renderer adapter.+Release unused checkpoints before increasing detail. Active, checkpoint and staged geometry share a peak allocation budget.++Keep JSON commands and snapshots exposed to agents. Retained matrices and immutable geometry belong to the renderer adapter.Do not inspect all vertex bounds in a frame loop. Memory estimates cover unique geometry arrays, not total RAM or VRAM.-The scene addon does not implement MCP transport, asset search, animation authoring, or render jobs.++The scene addon does not implement MCP transport, asset search, or render jobs.++Release `0.7.0` adds recipe-owned procedural motion. Read `docs/agent-motion.md` before authoring local node, material or camera tracks.+Use `set-motion` for revisioned edits and `sampleMotion(time)` for transient poses. Sampling preserves geometry, canonical recipes and revisions.+Use `sampleMotion(null)` for the authored base pose. Inspection bounds remain authored-base-world, independent of transient motion.For a configured MCP client, use the packaged `67js-mcp` server documented in `docs/mcp.md`.Call `scene_capabilities`, create one JSON scene, inspect IDs, checkpoint, apply a small batch, and assess `scene_look` PNG content.Use the revision returned by each committed apply or restore. A response with `committed: true` and `renderSucceeded: false` still advances revision.-Inspect or export the canonical recipe after a render failure; do not retry the edit with its old revision.+Inspect or export the canonical recipe after a render failure. Do not retry the edit with its old revision.+The server retains one renderer, bounds image dimensions and payloads, and closes its browser on stdio EOF.-Export the recipe before disposal. Animation authoring and video jobs remain unsupported by these tools.+Export the recipe before disposal. Release `0.6.0` includes bounded snapshot PNG, still and MP4 jobs documented in `docs/agent-render-jobs.md`.+Release `0.7.0` supports procedural `motionTime` preview seeks and `settings.motion.start` in jobs. Imported tracks retain their separate clip workflow.+For imported models, read `docs/agent-asset.md`, configure `--assets` with an absolute local GLB directory, then select a digest from `scene_asset_catalog`.-Use `scene_create_asset` with a `67js.asset` recipe; supported texture maps, skinning, morphs and existing clips remain attached to decoded meshes.+Use `scene_create_asset` with a `67js.asset` recipe. Supported texture maps, skinning, morphs and existing clips remain attached to decoded meshes.Edit imported models through `set-root`, factor-only `set-material`, look commands and absolute `set-animation` sampling. Imported topology is immutable.-Use `{ type: 'set-animation', time }` to sample the current clip; `{ type: 'set-animation', clip: null }` restores the decoded pose.++Use `{ type: 'set-animation', time }` to sample the current clip. `{ type: 'set-animation', clip: null }` restores the decoded pose.Bounds describe authored base geometry, not the deformed skin/morph silhouette. Check the rendered PNG before accepting framing.+Read `docs/agent-look.md` for authored lighting, fog, effects and shadow coverage, included in npm `0.5.0`.Use atomic `set-environment`, `set-effects` and `set-shadow` partial records instead of editing renderer internals through MCP.-Nested volumeFog/bloom fields merge; pointLights replaces the full list. Point lights do not cast local shadows.+Nested `volumeFog` and `bloom` fields merge. The `pointLights` field replaces the full list. Point lights do not cast local shadows.+Volume fog requires opaque HDR/depth rendering. The preview adapter allocates depth support at creation and rejects unsupported fog before commit.Keep key-light direction aligned with the derived shadow projector. The optional addon exports `resolveAgentShadow` for custom adapters.Checkpoint before relighting, inspect the actual image and restore or export the complete recipe. Look changes retain topology and geometry.diff --git a/skills/render-67js-media/SKILL.md b/skills/render-67js-media/SKILL.mdindex bbb964e7..9e5be948 100644--- a/skills/render-67js-media/SKILL.md+++ b/skills/render-67js-media/SKILL.md@@ -9,8 +9,10 @@ license: MITLocate the 67.js checkout and read its `scripts/render-media.mjs` and `src/budget.js`.Read [rendering.md](references/rendering.md) for commands, backends and measurement limits.Use the repository pipeline rather than constructing a parallel exporter.+For MCP snapshot jobs, read the checkout's `docs/agent-render-jobs.md` and verify source versus published support.Configure a private job store. Poll status after cancellation before resuming preview edits.+For procedural motion, read `docs/agent-motion.md` and select `settings.motion.start`. Preview seeks preserve revisions and authored recipes.## Choose and renderdiff --git a/src/agent-motion.js b/src/agent-motion.jsnew file mode 100644index 00000000..811bc7f0--- /dev/null+++ b/src/agent-motion.js@@ -0,0 +1,296 @@+import { createAnimationClip, compileAnimationSampler } from './animation.js';+import { createCameraPath } from './camera-path.js';++const PROPERTIES = {+ node: { translation: 3, rotation: 4, scale: 3 },+ material: { color: 3, emissiveColor: 3, emission: 1, metallic: 1, roughness: 1 },+ camera: { eye: 3, target: 3, fov: 1, roll: 1 },+};+const INTERPOLATIONS = ['LINEAR', 'STEP', 'SMOOTH', 'CUBICSPLINE'];+const CAMERA_DEFAULTS = { eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 };++function knownKeys(value, fields, label) {+ if (!value || Object.getPrototypeOf(value) !== Object.prototype) {+ throw new TypeError(`${label} must be a plain object.`);+ }+ for (const key of Reflect.ownKeys(value)) {+ const descriptor = Object.getOwnPropertyDescriptor(value, key);+ if (typeof key !== 'string' || !fields.includes(key) || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {+ throw new TypeError(`Unknown or unsupported ${label} field: ${String(key)}.`);+ }+ }+}++function finite(value, label) {+ if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {+ throw new RangeError(`${label} must be finite at Float32 precision.`);+ }+ return value;+}++function bounded(value, minimum, maximum, label) {+ finite(value, label);+ if (value < minimum || value > maximum) {+ throw new RangeError(`${label} must be within ${minimum} and ${maximum}.`);+ }+ return value;+}++function denseArray(value, maximum, label) {+ if (!Array.isArray(value) || value.length > maximum || Object.keys(value).length !== value.length ||+ Reflect.ownKeys(value).length !== value.length + 1 || Object.keys(value).some((key, index) => key !== String(index))) {+ throw new TypeError(`${label} must be a bounded dense array.`);+ }+ for (let index = 0; index < value.length; index++) {+ if (!Object.hasOwn(Object.getOwnPropertyDescriptor(value, index), 'value')) {+ throw new TypeError(`${label} cannot contain accessors.`);+ }+ }+ return value;+}++function valueFrom(value, size, label) {+ if (size === 1) {+ return finite(value, label);+ }+ denseArray(value, size, label);+ if (value.length !== size) {+ throw new TypeError(`${label} needs ${size} components.`);+ }+ return value.map(component => finite(component, label));+}++function validateValue(kind, property, value) {+ const components = typeof value === 'number' ? [value] : value;+ for (const component of components) {+ finite(component, `${kind} ${property}`);+ }+ if (property === 'scale' && components.some(component => Math.fround(component) <= 0)) {+ throw new RangeError('Motion scale must remain positive at Float32 precision.');+ }+ if (kind === 'material') {+ if (components.some(component => component < 0)) {+ throw new RangeError(`Motion ${property} cannot be negative.`);+ }+ if (['color', 'metallic', 'roughness'].includes(property) && components.some(component => component > 1)) {+ throw new RangeError(`Motion ${property} must stay within zero and one.`);+ }+ }+ if (kind === 'camera' && property === 'fov' && (Math.fround(value) <= 0 || Math.fround(value) >= 180)) {+ throw new RangeError('Motion fov must stay between zero and 180 at Float32 precision.');+ }+}++function coreProperty(track) {+ if (track.property === 'rotation') {+ return 'rotation';+ }+ return PROPERTIES[track.kind][track.property] === 1 ? 'value' : 'translation';+}++function copiedKeyframe(keyframe, interpolation) {+ const result = {+ time: keyframe.time,+ value: Array.isArray(keyframe.value) ? [...keyframe.value] : keyframe.value,+ };+ if (interpolation === 'CUBICSPLINE') {+ result.inTangent = Array.isArray(keyframe.inTangent) ? [...keyframe.inTangent] : keyframe.inTangent;+ result.outTangent = Array.isArray(keyframe.outTangent) ? [...keyframe.outTangent] : keyframe.outTangent;+ }+ return result;+}++function normalizedKeyframe(keyframe, track, duration, interpolation) {+ knownKeys(keyframe, ['time', 'value', 'inTangent', 'outTangent'], 'motion keyframe');+ const size = PROPERTIES[track.kind][track.property];+ const result = {+ time: bounded(keyframe.time, 0, duration, 'Keyframe time'),+ value: valueFrom(keyframe.value, size, 'Keyframe value'),+ };+ validateValue(track.kind, track.property, result.value);+ if (interpolation === 'CUBICSPLINE') {+ result.inTangent = valueFrom(keyframe.inTangent, size, 'Incoming tangent');+ result.outTangent = valueFrom(keyframe.outTangent, size, 'Outgoing tangent');+ } else if (Object.hasOwn(keyframe, 'inTangent') || Object.hasOwn(keyframe, 'outTangent')) {+ throw new TypeError('Tangents require CUBICSPLINE interpolation.');+ }+ return result;+}++/** Normalize bounded authored data without storing bindings or sampled poses. */+export function normalizeAgentMotion(input, recipe) {+ if (input === null || input === undefined) {+ return null;+ }+ knownKeys(input, ['duration', 'loop', 'tracks'], 'motion');+ const duration = bounded(input.duration, 0.1, 30, 'Motion duration');+ const loop = input.loop === undefined ? false : input.loop;+ if (typeof loop !== 'boolean') {+ throw new TypeError('Motion loop must be boolean.');+ }+ denseArray(input.tracks, 128, 'Motion tracks');+ if (!input.tracks.length) {+ throw new RangeError('Motion needs at least one track. Use null to clear it.');+ }+ const nodes = new Set((recipe.nodes ?? []).map(node => node.id));+ const materials = new Set((recipe.materials ?? []).map(material => material.id));+ const identities = new Set();+ let keyframeCount = 0;+ const tracks = input.tracks.map((track, index) => {+ knownKeys(track, ['kind', 'id', 'property', 'interpolation', 'keyframes'], 'motion track');+ if (!Object.hasOwn(PROPERTIES, track.kind) || !Object.hasOwn(PROPERTIES[track.kind], track.property)) {+ throw new RangeError('Unsupported motion target or property.');+ }+ if (track.kind === 'camera') {+ if (Object.hasOwn(track, 'id')) {+ throw new TypeError('Camera tracks cannot have an ID.');+ }+ } else {+ if (typeof track.id !== 'string' || !track.id.trim() || track.id.length > 128) {+ throw new TypeError('Motion target IDs need 1 to 128 characters.');+ }+ const references = track.kind === 'node' ? nodes : materials;+ if (!references.has(track.id)) {+ throw new RangeError(`Motion target was not found: ${track.id}.`);+ }+ }+ const identity = JSON.stringify([track.kind, track.id ?? null, track.property]);+ if (identities.has(identity)) {+ throw new RangeError('Duplicate motion target property.');+ }+ identities.add(identity);+ const interpolation = track.interpolation ?? 'LINEAR';+ if (!INTERPOLATIONS.includes(interpolation)) {+ throw new RangeError('Unsupported motion interpolation.');+ }+ denseArray(track.keyframes, 64, 'Motion keyframes');+ keyframeCount += track.keyframes.length;+ if (keyframeCount > 2048) {+ throw new RangeError('Motion exceeds 2048 total keyframes.');+ }+ const keyframes = track.keyframes.map(keyframe => normalizedKeyframe(keyframe, track, duration, interpolation));+ const clip = createAnimationClip({+ duration, loop,+ tracks: [{ target: String(index), property: coreProperty(track), interpolation, keyframes }],+ });+ const result = {+ kind: track.kind,+ property: track.property,+ interpolation,+ keyframes: clip.tracks[0].keyframes.map(keyframe => copiedKeyframe(keyframe, interpolation)),+ };+ if (track.kind !== 'camera') {+ result.id = track.id;+ }+ return result;+ });+ return { duration, loop, tracks };+}++function validateRadiance(material) {+ const emission = material.emission ?? 0;+ const color = material.emissiveColor ?? material.color ?? [0.5, 0.5, 0.5];+ for (const component of color) {+ const radiance = Math.fround(component) * Math.fround(emission);+ if (!Number.isFinite(Math.fround(radiance))) {+ throw new RangeError('Motion emissive radiance exceeds Float32 range.');+ }+ if (material.tag === 'unlit' && radiance > 65500) {+ throw new RangeError('Motion unlit radiance exceeds the HDR range.');+ }+ }+}++/** Retains published maps and vectors. A failed sample leaves them unchanged. */+export function compileAgentMotion(input, recipe) {+ const motion = normalizeAgentMotion(input, recipe);+ if (motion === null) {+ return null;+ }+ const ordinaryTracks = motion.tracks.filter(track => track.kind !== 'camera');+ const clip = createAnimationClip({+ duration: motion.duration,+ loop: motion.loop,+ tracks: ordinaryTracks.map((track, index) => ({+ target: String(index),+ property: coreProperty(track),+ interpolation: track.interpolation,+ keyframes: track.keyframes,+ })),+ });+ const sampler = compileAnimationSampler(clip);+ const output = { nodes: new Map(), materials: new Map(), camera: null };+ const bindings = ordinaryTracks.map((track, index) => {+ const patches = track.kind === 'node' ? output.nodes : output.materials;+ if (!patches.has(track.id)) {+ patches.set(track.id, {});+ }+ const patch = patches.get(track.id);+ const size = PROPERTIES[track.kind][track.property];+ patch[track.property] = size === 1 ? 0 : new Float64Array(size);+ return { track, patch, staged: sampler.tracks[index].output };+ });+ const baselines = new Map((recipe.materials ?? []).map(material => [material.id, structuredClone(material)]));+ const cameraTracks = motion.tracks.filter(track => track.kind === 'camera');+ const cameraInput = {+ ...structuredClone(CAMERA_DEFAULTS),+ ...structuredClone(recipe.camera ?? {}),+ duration: motion.duration,+ loop: motion.loop,+ };+ for (const track of cameraTracks) {+ cameraInput[track.property] = { interpolation: track.interpolation, keyframes: track.keyframes };+ }+ const cameraPath = cameraTracks.length ? createCameraPath(cameraInput) : null;+ const stagedCamera = cameraPath ? { eye: new Float32Array(3), target: new Float32Array(3), up: new Float32Array(3) } : null;+ if (cameraPath) {+ output.camera = {+ eye: new Float32Array(3), target: new Float32Array(3), up: new Float32Array(3),+ fov: 45, near: cameraInput.near, far: cameraInput.far, projection: 'perspective',+ };+ }+ const materialSamples = new Map([...output.materials.keys()].map(id => [id, { ...baselines.get(id) }]));+ return Object.freeze({+ sample(time) {+ bounded(time, 0, 3600, 'Motion sample time');+ sampler.sample(time);+ for (const { track, staged } of bindings) {+ const value = staged.length === 1 ? staged[0] : staged;+ validateValue(track.kind, track.property, value);+ if (track.kind === 'material') {+ materialSamples.get(track.id)[track.property] = value;+ }+ }+ for (const material of materialSamples.values()) {+ validateRadiance(material);+ }+ if (cameraPath) {+ cameraPath.sample(time, stagedCamera);+ for (const field of ['fov', 'near', 'far']) {+ finite(stagedCamera[field], `Camera ${field}`);+ }+ if (Math.fround(stagedCamera.fov) <= 0 || Math.fround(stagedCamera.fov) >= 180 ||+ Math.fround(stagedCamera.near) <= 0 || Math.fround(stagedCamera.far) <= Math.fround(stagedCamera.near)) {+ throw new RangeError('Sampled camera lens is invalid at Float32 precision.');+ }+ }+ // Publish only after every track, material product and camera pose passes.+ for (const { track, patch, staged } of bindings) {+ if (staged.length === 1) {+ patch[track.property] = staged[0];+ } else {+ patch[track.property].set(staged);+ }+ }+ if (cameraPath) {+ for (const field of ['eye', 'target', 'up']) {+ output.camera[field].set(stagedCamera[field]);+ }+ for (const field of ['fov', 'near', 'far']) {+ output.camera[field] = stagedCamera[field];+ }+ }+ return output;+ },+ });+}diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 88fad9c7..77f0012e 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -4,6 +4,7 @@ import { lathe, extrude, tube } from './modeling.js';import { createSceneGraph } from './scene-graph.js';import { applyProjection } from './camera.js';import { normalizeAgentLook } from './agent-look.js';+import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';const DEFAULT_LIMITS = Object.freeze({@@ -36,11 +37,13 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({operations: Object.freeze(['set-node', 'set-material', 'set-camera', 'add-node', 'remove-node','add-geometry', 'remove-geometry', 'add-material', 'remove-material',- 'set-environment', 'set-effects', 'set-shadow',+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion',]),materialTags: Object.freeze(['surface', 'unlit']),fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,authoredLook: true, maxPointLights: 8,+ proceduralMotion: true,+ motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),});function knownKeys(value, allowed, label) {@@ -383,6 +386,11 @@ function compile(recipe, geometries, localBounds, limits) {matrix: mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale),geometry: geometries.get(node.geometry), material: materials.get(node.material) };}), limits);+ validateGraph(graph, localBounds);+ return graph;+}++function validateGraph(graph, localBounds) {const normal = mat3.create();for (const node of graph.nodes) {if (!mat3.normalFromMat4(normal, node.worldMatrix) || !normal.every(Number.isFinite)) {@@ -404,7 +412,6 @@ function compile(recipe, geometries, localBounds, limits) {}}}- return graph;}function boundsFor(geometry, matrix) {@@ -423,7 +430,7 @@ function boundsFor(geometry, matrix) {function normalizeRecipe(input, limits) {let recipe = copiedJson(input, limits.maxRecipeBytes);- knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera', 'environment', 'effects', 'shadow'], 'recipe');+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera', 'environment', 'effects', 'shadow', 'motion'], 'recipe');if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {throw new RangeError('Expected 67js.scene schemaVersion 1.');}@@ -447,6 +454,9 @@ function normalizeRecipe(input, limits) {}}Object.assign(recipe, normalizeAgentLook(look));+ if (Object.hasOwn(recipe, 'motion')) {+ recipe.motion = normalizeAgentMotion(recipe.motion, recipe);+ }recipe = copiedJson(recipe, limits.maxRecipeBytes);return recipe;}@@ -494,6 +504,71 @@ function retainedMatrices(parts) {}}+function cameraPoseFrom(pose) {+ const camera = cameraFrom({+ eye: Array.from(pose.eye), target: Array.from(pose.target), up: Array.from(pose.up),+ fov: pose.fov, near: pose.near, far: pose.far,+ });+ const view = mat4.lookAt(mat4.create(), camera.eye, camera.target, camera.up);+ for (const aspect of [1 / 16, 16]) {+ const projection = applyProjection(mat4.create(), camera, aspect);+ const combined = mat4.multiply(mat4.create(), projection, view);+ if (![projection, combined].every(matrix => matrix.every(Number.isFinite))) {+ throw new RangeError('Motion camera matrices exceed the supported Float32 aspect range.');+ }+ }+ return camera;+}++// Candidate buffers are private. A failed seek cannot publish half a pose to render handles.+function stagePose(stagedState, time) {+ const sampled = time === null ? null : stagedState.motionSampler?.sample(time);+ const graph = stagedState.poseGraph ?? stagedState.graph;+ if (stagedState.poseGraph) {+ for (const node of stagedState.recipe.nodes) {+ const patch = sampled?.nodes.get(node.id);+ const translation = patch?.translation ?? node.translation;+ const rotation = patch?.rotation ?? node.rotation;+ const scale = patch?.scale ?? node.scale;+ if (Array.from(scale).some(component => !Number.isFinite(Math.fround(component)) || Math.fround(component) <= 0)) {+ throw new RangeError('Motion scale must remain positive at Float32 precision.');+ }+ mat4.fromRotationTranslationScale(graph.getNode(node.id).localMatrix, rotation, translation, scale);+ }+ graph.update();+ validateGraph(graph, stagedState.localBounds);+ }+ const materialUpdates = [];+ for (const material of stagedState.recipe.materials) {+ const patch = sampled?.materials.get(material.id);+ let snapshot = material;+ if (patch) {+ const definition = { ...material, ...patch };+ for (const field of ['color', 'emissiveColor']) {+ if (definition[field]) {+ definition[field] = Array.from(definition[field]);+ }+ }+ snapshot = immutableMaterial(materialFrom(definition));+ }+ materialUpdates.push({ holder: stagedState.materialHandles.get(material.id).holder, snapshot });+ }+ const camera = sampled?.camera ? cameraPoseFrom(sampled.camera) : stagedState.recipe.camera;+ retainedMatrices(stagedState.parts);+ return { graph, materialUpdates, camera, time };+}++function publishPose(stagedState, pose) {+ for (const part of stagedState.parts) {+ Float32Array.prototype.set.call(part.matrix, pose.graph.getNode(part.name).worldMatrix);+ }+ for (const update of pose.materialUpdates) {+ update.holder.snapshot = update.snapshot;+ }+ stagedState.renderCamera = pose.camera;+ stagedState.motionTime = pose.time;+}+function removeNode(candidate, operation) {knownKeys(operation, ['type', 'id', 'recursive'], 'operation');identifier(operation.id);@@ -605,7 +680,6 @@ export function createAgentScene(input, inputLimits = {}) {const localBounds = new Map([...geometryRecords.values()].map(record => [record.geometry, record.bounds]));const graph = compile(recipe, geometries, localBounds, limits);const materialHandles = new Map();- const materialUpdates = [];for (const material of recipe.materials) {const snapshot = immutableMaterial(material);const preferredHandle = preferred?.materialHandles.get(material.id);@@ -613,7 +687,6 @@ export function createAgentScene(input, inputLimits = {}) {const existing = [preferredHandle, activeHandle].find(handle => handle?.holder.snapshot.tag === material.tag);const handle = existing ?? materialHandle(snapshot);materialHandles.set(material.id, handle);- materialUpdates.push({ holder: handle.holder, snapshot });}const activeParts = new Map(state?.parts.map(part => [part.name, part]) ?? []);const preferredParts = new Map(preferred?.parts.map(part => [part.name, part]) ?? []);@@ -631,21 +704,21 @@ export function createAgentScene(input, inputLimits = {}) {retainedMatrices(nextParts);const sameParts = state && state.parts.length === nextParts.length &&state.parts.every((part, index) => part === nextParts[index]);- return {- recipe, geometryRecords, geometries, graph, materialHandles, materialUpdates,+ const stagedState = {+ recipe, geometryRecords, geometries, graph, materialHandles,parts: sameParts ? state.parts : Object.freeze(nextParts),topologyChanged: Boolean(state && !sameParts),stats: geometryStats(geometryRecords.values()),};+ stagedState.localBounds = localBounds;+ stagedState.motionSampler = compileAgentMotion(recipe.motion ?? null, recipe);+ stagedState.poseGraph = stagedState.motionSampler ? compile(recipe, geometries, localBounds, limits) : null;+ stagedState.initialPose = stagePose(stagedState, stagedState.motionSampler ? 0 : null);+ return stagedState;}function commit(stagedState, incrementRevision) {- for (const part of stagedState.parts) {- Float32Array.prototype.set.call(part.matrix, stagedState.graph.getNode(part.name).worldMatrix);- }- for (const update of stagedState.materialUpdates) {- update.holder.snapshot = update.snapshot;- }+ publishPose(stagedState, stagedState.initialPose);if (stagedState.topologyChanged) {topologyRevision++;}@@ -677,7 +750,20 @@ export function createAgentScene(input, inputLimits = {}) {return topologyRevision;},get camera() {- return structuredClone(state.recipe.camera);+ return structuredClone(state.renderCamera);+ },+ get motionTime() {+ return state.motionTime;+ },+ sampleMotion(time) {+ if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {+ throw new RangeError('Motion time must be null or within zero and 3600 seconds.');+ }+ if (time !== null && !state.motionSampler) {+ throw new RangeError('This procedural recipe has no motion.');+ }+ publishPose(state, stagePose(state, time));+ return state.motionTime;},get environment() {return structuredClone(state.recipe.environment);@@ -701,6 +787,14 @@ export function createAgentScene(input, inputLimits = {}) {const removedNodes = new Set();const removedMaterials = new Set();for (const operation of operations) {+ if (operation.type === 'set-motion') {+ knownKeys(operation, ['type', 'motion'], 'operation');+ if (!Object.hasOwn(operation, 'motion')) {+ throw new TypeError('set-motion requires motion; use null to clear it.');+ }+ candidate.motion = operation.motion;+ continue;+ }const lookField = Object.hasOwn(LOOK_OPERATION_FIELDS, operation.type) ? LOOK_OPERATION_FIELDS[operation.type] : null;if (lookField) {knownKeys(operation, ['type', lookField], 'operation');@@ -813,6 +907,8 @@ export function createAgentScene(input, inputLimits = {}) {const resident = geometryStats(ownedGeometryRecords());return {revision, topologyRevision,+ motion: state.recipe.motion ? { duration: state.recipe.motion.duration, loop: state.recipe.motion.loop, tracks: state.recipe.motion.tracks.length, time: state.motionTime } : null,+ boundsSpace: 'authored-base-world',counts: {nodes: state.recipe.nodes.length, parts: state.parts.length,geometries: state.geometries.size, materials: state.recipe.materials.length,diff --git a/tests/agent-motion.test.js b/tests/agent-motion.test.jsnew file mode 100644index 00000000..b0ef0334--- /dev/null+++ b/tests/agent-motion.test.js@@ -0,0 +1,182 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { constants, setPriority } from 'node:os';+import { normalizeAgentMotion, compileAgentMotion } from '../src/agent-motion.js';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const recipe = {+ nodes: [{ id: 'hinge' }, { id: 'child', parent: 'hinge' }],+ materials: [{ id: 'bulb', tag: 'surface', color: [0.2, 0.3, 0.4], roughness: 0, metallic: 0, emission: 0 }],+ camera: { eye: [1, 0, 0], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 100 },+};+const track = (property, start, end, extra = {}) => ({ kind: 'material', id: 'bulb', property,+ keyframes: [{ time: 0, value: start }, { time: 1, value: end }], ...extra });+const motion = tracks => ({ duration: 1, tracks });+function snapshot(output) {+ function copiedPatches(patches) {+ return [...patches].map(([id, patch]) => {+ const fields = Object.entries(patch).map(([key, value]) => [key, typeof value === 'number' ? value : [...value]]);+ return [id, Object.fromEntries(fields)];+ });+ }+ return {+ nodes: copiedPatches(output.nodes),+ materials: copiedPatches(output.materials),+ camera: output.camera && {+ ...output.camera,+ eye: [...output.camera.eye],+ target: [...output.camera.target],+ up: [...output.camera.up],+ },+ };+}++test('normalization preserves public targets, sorts copied keys and normalizes quaternion values', () => {+ const input = motion([{ kind: 'node', id: 'hinge', property: 'rotation', keyframes: [{ time: 1, value: [0, 0, 2, 0] }, { time: 0, value: [0, 0, 0, 2] }] }]);+ const normalized = normalizeAgentMotion(input, recipe);+ assert.deepEqual(normalized.tracks[0].keyframes[0], { time: 0, value: [0, 0, 0, 1] });+ assert.equal(normalized.tracks[0].property, 'rotation');+ assert.equal(normalized.tracks[0].id, 'hinge');+ assert.equal(normalized.loop, false);+ input.tracks[0].keyframes[0].value[2] = 10;+ assert.deepEqual(normalized.tracks[0].keyframes[1].value, [0, 0, 1, 0]);+ assert.equal(normalizeAgentMotion(null, recipe), null);+ assert.equal(compileAgentMotion(undefined, recipe), null);+});++test('all four curves use core interpolation and material roughness retains authored zero', () => {+ for (const [interpolation, expected] of [['LINEAR', 0.25], ['STEP', 0], ['SMOOTH', 0.15625], ['CUBICSPLINE', 0.34375]]) {+ const channel = track('roughness', 0, 1, { interpolation });+ if (interpolation === 'CUBICSPLINE') {+ for (const keyframe of channel.keyframes) {+ Object.assign(keyframe, { inTangent: 2, outTangent: 2 });+ }+ }+ const sampler = compileAgentMotion(motion([channel]), recipe);+ assert.equal(sampler.sample(0).materials.get('bulb').roughness, 0);+ assert.equal(sampler.sample(0.25).materials.get('bulb').roughness, expected);+ assert.equal(sampler.sample(1).materials.get('bulb').roughness, 1);+ }+});++test('retained vectors, typed camera output and arbitrary seeks are deterministic', () => {+ const input = motion([+ { kind: 'node', id: 'hinge', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [2, 1, 0] }] },+ track('color', [0, 0, 0], [1, 0.5, 0.25]),+ track('emissiveColor', [0, 0, 0], [2, 3, 4]),+ { kind: 'camera', property: 'eye', keyframes: [{ time: 0, value: [1, 0, 0] }, { time: 1, value: [1, 1, 1] }] },+ { kind: 'camera', property: 'roll', keyframes: [{ time: 0, value: 0 }, { time: 1, value: 0.5 }] },+ ]);+ const sampler = compileAgentMotion(input, recipe);+ const output = sampler.sample(0.75);+ const expected = snapshot(output);+ const translation = output.nodes.get('hinge').translation;+ const color = output.materials.get('bulb').color;+ const eye = output.camera.eye;+ assert.ok(translation instanceof Float64Array);+ assert.ok(eye instanceof Float32Array);+ for (const time of [1, 0, 0.25, 0.75]) {+ assert.equal(sampler.sample(time), output);+ }+ assert.deepEqual(snapshot(output), expected);+ assert.equal(output.nodes.get('hinge').translation, translation);+ assert.equal(output.materials.get('bulb').color, color);+ assert.equal(output.camera.eye, eye);+ assert.deepEqual(recipe.materials[0].color, [0.2, 0.3, 0.4]);+});++test('loop modulo and nonloop clamping agree across channels, with bounded absolute time', () => {+ const input = motion([track('emission', 0, 1)]);+ const clamped = compileAgentMotion(input, recipe);+ assert.equal(clamped.sample(3600).materials.get('bulb').emission, 1);+ const looping = compileAgentMotion({ ...input, loop: true }, recipe);+ assert.equal(looping.sample(1).materials.get('bulb').emission, 0);+ assert.equal(looping.sample(2.25).materials.get('bulb').emission, 0.25);+ for (const time of [-1, 3601, NaN, Infinity]) {+ assert.throws(() => looping.sample(time));+ }+});++test('camera-only motion compiles an empty ordinary clip and retains the static camera lens', () => {+ const sampler = compileAgentMotion(motion([{ kind: 'camera', property: 'target', keyframes: [+ { time: 0, value: [0, 0, 0] }, { time: 1, value: [0, 0, 1] },+ ] }]), recipe);+ const output = sampler.sample(0.5);+ assert.equal(output.nodes.size, 0);+ assert.equal(output.materials.size, 0);+ assert.deepEqual([...output.camera.target], [0, 0, 0.5]);+ assert.equal(output.camera.near, 0.1);+ assert.equal(output.camera.far, 100);+ assert.equal(output.camera.fov, 45);+});++test('strict schema, final references, duplicate tracks and allocation bounds reject invalid authoring', () => {+ assert.throws(() => normalizeAgentMotion(motion([]), recipe), /at least one/);+ assert.throws(() => normalizeAgentMotion({ ...motion([]), unknown: true }, recipe), /field/);+ assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), id: 'missing' }]), recipe), /not found/);+ assert.throws(() => normalizeAgentMotion(motion([track('emission', 0, 1), track('emission', 0, 1)]), recipe), /Duplicate/);+ assert.throws(() => normalizeAgentMotion(motion([{ kind: 'camera', id: 'camera', property: 'fov', keyframes: [{ time: 0, value: 45 }] }]), recipe), /cannot have/);+ assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), keyframes: [{ time: 0, value: 0, outTangent: 1 }] }]), recipe), /Tangents/);+ assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), interpolation: 'CUBICSPLINE' }]), recipe), /tangent/i);+ assert.throws(() => normalizeAgentMotion(motion(Array(129)), recipe), /bounded/);+ const tooManyKeys = Array.from({ length: 65 }, (_, index) => ({ time: index / 64, value: 0 }));+ assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), keyframes: tooManyKeys }]), recipe), /bounded/);+ const manyNodes = Array.from({ length: 33 }, (_, index) => ({ id: `node-${index}` }));+ const manyTracks = manyNodes.map(node => ({+ kind: 'node', id: node.id, property: 'translation',+ keyframes: Array.from({ length: 64 }, (_, index) => ({ time: index / 63, value: [0, 0, 0] })),+ }));+ assert.throws(() => normalizeAgentMotion(motion(manyTracks), { ...recipe, nodes: manyNodes }), /2048/);+ assert.throws(() => normalizeAgentMotion({ ...motion([]), duration: 31 }, recipe), /duration/);+ assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), keyframes: [{ time: 0, value: 0 }, { time: 0, value: 1 }] }]), recipe), /distinct/);+});++test('invalid cubic scale and material overshoot throw without clamping or partial publication', () => {+ for (const channel of [+ { kind: 'node', id: 'hinge', property: 'scale', keyframes: [+ { time: 0, value: [1, 1, 1], inTangent: [0, 0, 0], outTangent: [-10, 0, 0] },+ { time: 1, value: [1, 1, 1], inTangent: [10, 0, 0], outTangent: [0, 0, 0] },+ ] },+ { ...track('color', [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), keyframes: [+ { time: 0, value: [0.5, 0.5, 0.5], inTangent: [0, 0, 0], outTangent: [-10, 0, 0] },+ { time: 1, value: [0.5, 0.5, 0.5], inTangent: [10, 0, 0], outTangent: [0, 0, 0] },+ ] },+ ]) {+ const sampler = compileAgentMotion(motion([track('emission', 0, 1), { ...channel, interpolation: 'CUBICSPLINE' }]), recipe);+ const output = sampler.sample(0);+ const before = snapshot(output);+ assert.throws(() => sampler.sample(0.5), /positive|negative/);+ assert.deepEqual(snapshot(output), before);+ sampler.sample(1);+ sampler.sample(0);+ assert.deepEqual(snapshot(output), before);+ }+});++test('radiance overflow, camera midpose collisions and cubic lens overshoot preserve the previous sample', () => {+ const inputs = [+ motion([track('emission', 0, 1e20), track('emissiveColor', [1e20, 1e20, 1e20], [1e20, 1e20, 1e20])]),+ motion([track('emission', 0, 1), { kind: 'camera', property: 'eye', keyframes: [{ time: 0, value: [1, 0, 0] }, { time: 1, value: [-1, 0, 0] }] }]),+ motion([track('emission', 0, 1), { kind: 'camera', property: 'fov', interpolation: 'CUBICSPLINE', keyframes: [+ { time: 0, value: 45, inTangent: 0, outTangent: 1000 },+ { time: 1, value: 45, inTangent: -1000, outTangent: 0 },+ ] }]),+ ];+ for (const input of inputs) {+ const sampler = compileAgentMotion(input, recipe);+ const output = sampler.sample(0);+ const before = snapshot(output);+ assert.throws(() => sampler.sample(0.5), /radiance|distinct|field of view/);+ assert.deepEqual(snapshot(output), before);+ }+});++test('unlit radiance uses the authored base color when emissiveColor is absent', () => {+ const unlitRecipe = { ...recipe, materials: [{ ...recipe.materials[0], tag: 'unlit', color: [1, 0.5, 0] }] };+ const sampler = compileAgentMotion(motion([track('emission', 0, 200000)]), unlitRecipe);+ const output = sampler.sample(0);+ const before = snapshot(output);+ assert.throws(() => sampler.sample(0.5), /unlit radiance/);+ assert.deepEqual(snapshot(output), before);+ assert.equal(sampler.sample(0.25).materials.get('bulb').emission, 50000);+});diff --git a/tests/agent-render-jobs.test.js b/tests/agent-render-jobs.test.jsindex f8cfe21d..cd9bf9ed 100644--- a/tests/agent-render-jobs.test.js+++ b/tests/agent-render-jobs.test.js@@ -38,6 +38,32 @@ async function writeImage({ directory, progress }) {return { artifacts: [{ temporary: 'render.png.partial', filename: 'render.png', mimeType: 'image/png' }], metrics: { maximumPendingFrames: 1 } };}+test('motion job ranges use immutable recipe duration, loops and actual sample times across restart', async context => {+ const root = await temporary(context);+ const controller = await createAgentRenderJobs({ root, limits, run: writeImage });+ const input = request();+ input.snapshot.recipe = { format: '67js.scene', motion: { duration: 1, loop: false } };+ input.settings.motion = { start: 1 };+ const submitted = await controller.submit(input);+ await terminal(controller, submitted.jobId);+ assert.equal(controller.status(submitted.jobId).settings.motion.start, 1);+ input.settings = { kind: 'stills', width: 64, height: 64, duration: 1, motion: { start: 0.1 } };+ await assert.rejects(controller.submit(input), /Motion range/);+ input.snapshot.recipe.motion.loop = true;+ input.settings.motion.start = 3600;+ await assert.rejects(controller.submit(input), /motion end/);+ input.settings.motion.start = null;+ await assert.rejects(controller.submit(input), /motion start/);+ input.snapshot.recipe = { format: '67js.asset', motion: { duration: 1 } };+ input.settings.motion.start = 0;+ await assert.rejects(controller.submit(input), /procedural recipe/);+ await controller.close();+ const reopened = await createAgentRenderJobs({ root, limits, run: writeImage });+ assert.equal(reopened.status(submitted.jobId).settings.motion.start, 1);+ await reopened.release(submitted.jobId);+ await reopened.close();+});+test('real files publish after success with copied snapshots, hashes and restart persistence', async context => {const root = await temporary(context);const started = deferred();diff --git a/tests/agent-scene-motion.test.js b/tests/agent-scene-motion.test.jsnew file mode 100644index 00000000..f95eae25--- /dev/null+++ b/tests/agent-scene-motion.test.js@@ -0,0 +1,172 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAgentScene } from '../src/agent-scene.js';++function recipe() {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],+ materials: [{ id: 'finish', color: [0.2, 0.4, 0.6], emission: 0 }],+ nodes: [+ { id: 'hinge', translation: [3, 0, 0] },+ { id: 'arm', parent: 'hinge', geometry: 'box', material: 'finish', translation: [1, 2, 0] },+ ],+ camera: { eye: [4, 3, 5], target: [0, 0, 0] },+ motion: {+ duration: 1,+ tracks: [+ { kind: 'node', id: 'hinge', property: 'rotation', keyframes: [+ { time: 0, value: [0, 0, 0, 1] }, { time: 1, value: [0, 0, Math.SQRT1_2, Math.SQRT1_2] },+ ] },+ { kind: 'material', id: 'finish', property: 'emission', keyframes: [+ { time: 0, value: 0 }, { time: 1, value: 2 },+ ] },+ { kind: 'camera', property: 'eye', keyframes: [+ { time: 0, value: [4, 3, 5] }, { time: 1, value: [5, 3, 5] },+ ] },+ ],+ },+ };+}++function pose(scene) {+ return { matrices: scene.parts.map(part => Array.from(part.matrix)), camera: scene.camera,+ materials: scene.parts.map(part => structuredClone(part.material)), time: scene.motionTime };+}++test('motion samples local joints with retained resources and exact shuffled seeks', () => {+ const scene = createAgentScene(recipe());+ const canonical = scene.exportRecipe();+ const authoredBounds = scene.inspect({ includeBounds: true });+ const parts = scene.parts;+ const geometry = parts[0].geometry;+ const matrix = parts[0].matrix;+ const material = parts[0].material;+ const start = pose(scene);+ scene.sampleMotion(1);+ const end = pose(scene);+ assert.ok(Math.abs(matrix[12] - 1) < 1e-6);+ assert.ok(Math.abs(matrix[13] - 1) < 1e-6);+ assert.equal(material.emission, 2);+ assert.equal(scene.camera.eye[0], 5);+ for (const time of [0.71, 0.12, 1, 0.5, 0]) {+ scene.sampleMotion(time);+ }+ assert.deepEqual(pose(scene), start);+ scene.sampleMotion(1);+ assert.deepEqual(pose(scene), end);+ assert.equal(scene.parts, parts);+ assert.equal(scene.parts[0].geometry, geometry);+ assert.equal(scene.parts[0].matrix, matrix);+ assert.equal(scene.parts[0].material, material);+ assert.equal(scene.revision, 0);+ assert.equal(scene.topologyRevision, 0);+ assert.deepEqual(scene.exportRecipe(), canonical);+ assert.deepEqual(scene.inspect({ includeBounds: true }).nodes, authoredBounds.nodes);+ assert.equal(scene.inspect().boundsSpace, 'authored-base-world');+});++test('base reset, checkpoints and authored edits rebuild motion bindings without seek revisions', () => {+ const input = recipe();+ input.motion.tracks[0].keyframes[0].value = [0, 0, Math.SQRT1_2, Math.SQRT1_2];+ const scene = createAgentScene(input);+ const checkpoint = scene.checkpoint();+ const canonical = scene.exportRecipe();+ const parts = scene.parts;+ assert.ok(Math.abs(parts[0].matrix[12] - 1) < 1e-6);+ scene.sampleMotion(null);+ assert.equal(parts[0].matrix[12], 4);+ assert.equal(scene.motionTime, null);+ scene.sampleMotion(1);+ scene.apply([{ type: 'set-motion', motion: null }], { expectedRevision: 0 });+ assert.equal(parts[0].matrix[12], 4);+ assert.equal(scene.inspect().motion, null);+ assert.throws(() => scene.sampleMotion(0), /no motion/);+ scene.restore(checkpoint, { expectedRevision: 1 });+ assert.deepEqual(scene.exportRecipe(), canonical);+ assert.equal(scene.motionTime, 0);+ assert.equal(scene.revision, 2);+ assert.equal(scene.parts, parts);+ assert.equal(scene.topologyRevision, 0);+});++test('final batch reference validation prevents dangling tracks and permits atomic replacement', () => {+ const scene = createAgentScene(recipe());+ scene.sampleMotion(1);+ const before = pose(scene);+ const canonical = scene.exportRecipe();+ assert.throws(() => scene.apply([{ type: 'remove-node', id: 'hinge', recursive: true }], { expectedRevision: 0 }), /target/);+ assert.deepEqual(pose(scene), before);+ assert.deepEqual(scene.exportRecipe(), canonical);+ assert.throws(() => scene.apply([{ type: 'set-motion' }], { expectedRevision: 0 }), /requires motion/);+ scene.apply([+ { type: 'remove-node', id: 'hinge', recursive: true },+ { type: 'remove-material', id: 'finish' },+ { type: 'set-motion', motion: null },+ ], { expectedRevision: 0 });+ assert.equal(scene.revision, 1);+ assert.equal(scene.parts.length, 0);+});++test('invalid cubic mid-pose rejects a whole seek without publishing other channels', () => {+ const input = recipe();+ input.motion.tracks.push({ kind: 'node', id: 'arm', property: 'scale', interpolation: 'CUBICSPLINE', keyframes: [+ { time: 0, value: [1, 1, 1], inTangent: [0, 0, 0], outTangent: [-16, 0, 0] },+ { time: 1, value: [1, 1, 1], inTangent: [16, 0, 0], outTangent: [0, 0, 0] },+ ] });+ const scene = createAgentScene(input);+ const before = pose(scene);+ assert.throws(() => scene.sampleMotion(0.5), /scale/);+ assert.deepEqual(pose(scene), before);+ assert.equal(scene.revision, 0);+ scene.sampleMotion(1);+ assert.equal(scene.parts[0].material.emission, 2);+ scene.sampleMotion(0);+ assert.deepEqual(pose(scene), before);+});++test('combined parent transforms and invalid camera crossings cannot publish valid sibling tracks', () => {+ for (const invalid of ['graph', 'camera']) {+ const input = recipe();+ if (invalid === 'graph') {+ for (const id of ['hinge', 'arm']) {+ input.motion.tracks.push({ kind: 'node', id, property: 'scale', keyframes: [+ { time: 0, value: [1, 1, 1] }, { time: 1, value: [1e20, 1e20, 1e20] },+ ] });+ }+ } else {+ input.motion.tracks[2].keyframes = [+ { time: 0, value: [4, 3, 5] }, { time: 1, value: [-4, -3, -5] },+ ];+ }+ const scene = createAgentScene(input);+ const before = pose(scene);+ assert.throws(() => scene.sampleMotion(invalid === 'graph' ? 1 : 0.5));+ assert.deepEqual(pose(scene), before);+ assert.equal(scene.revision, 0);+ scene.sampleMotion(0);+ assert.deepEqual(pose(scene), before);+ }+});++test('failed set-motion initial sampling is atomic across recipe, transforms and materials', () => {+ const scene = createAgentScene(recipe());+ scene.sampleMotion(1);+ const before = pose(scene);+ const canonical = scene.exportRecipe();+ const motion = { duration: 1, tracks: [{ kind: 'camera', property: 'eye', keyframes: [{ time: 0, value: [0, 0, 0] }] }] };+ assert.throws(() => scene.apply([+ { type: 'set-material', id: 'finish', color: [1, 0, 0] },+ { type: 'set-node', id: 'arm', translation: [10, 10, 10] },+ { type: 'set-motion', motion },+ ], { expectedRevision: 0 }));+ assert.deepEqual(pose(scene), before);+ assert.deepEqual(scene.exportRecipe(), canonical);+ assert.equal(scene.revision, 0);+});++test('motion loop is optional boolean and never accepts null as a hidden default', () => {+ const input = recipe();+ input.motion.loop = null;+ assert.throws(() => createAgentScene(input), /loop must be boolean/);+});diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex c5de9187..d3f08310 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -43,9 +43,13 @@ async function connect(context) {scene.apply(operations, { expectedRevision });return status();},- async look({ width, height }) {+ async look({ width, height, motionTime }) {calls++;- return { data: png, mimeType: 'image/png', metadata: { sessionId, revision: scene.revision, width, height, backend: 'fake' } };+ if (motionTime !== undefined) {+ scene.sampleMotion(motionTime);+ }+ return { data: png, mimeType: 'image/png', metadata: { sessionId, revision: scene.revision,+ motionTime: scene.motionTime, width, height, backend: 'fake' } };},async checkpoint() {const checkpointId = randomUUID();@@ -125,6 +129,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'const look = tools.find(tool => tool.name === 'scene_look');assert.equal(look.annotations.readOnlyHint, true);assert.equal(look.inputSchema.properties.width.maximum, 1024);+ assert.ok(look.inputSchema.properties.motionTime);});test('SDK rejects unknown fields, missing revisions, invalid vectors and oversized inputs before runtime dispatch', async context => {@@ -137,6 +142,8 @@ test('SDK rejects unknown fields, missing revisions, invalid vectors and oversizawait rejected(client, 'scene_render_result', { jobId: '../video.mp4' });await rejected(client, 'scene_inspect', { sessionId: 'not-a-uuid' });await rejected(client, 'scene_look', { sessionId, width: 1025 });+ await rejected(client, 'scene_look', { sessionId, motionTime: -1 });+ await rejected(client, 'scene_apply', { sessionId, expectedRevision: 0, operations: [{ type: 'set-motion' }] });await rejected(client, 'scene_asset_catalog', { path: 'C:/private/file.glb' });await rejected(client, 'scene_create_asset', { recipe: { format: '67js.asset', schemaVersion: 1, assetId: '../file.glb' } });await rejected(client, 'scene_create_asset', { recipe: { format: '67js.asset', schemaVersion: 1, assetId: 'a'.repeat(64), root: { javascript: 'run' } } });@@ -153,6 +160,26 @@ test('SDK rejects unknown fields, missing revisions, invalid vectors and oversizassert.equal(boundary.calls(), 0);});+test('real SDK round trip authors motion, seeks without revisions and rejects unknown track fields', async context => {+ const { client, sessionId } = await connect(context);+ const motion = { duration: 1, tracks: [{ kind: 'node', id: 'mesh', property: 'translation',+ keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [1, 0, 0] }] }] };+ await client.callTool({ name: 'scene_create', arguments: { recipe: { ...recipe(), motion } } });+ for (const motionTime of [1, 0.2, 0, null]) {+ const looked = await client.callTool({ name: 'scene_look', arguments: { sessionId, motionTime } });+ assert.equal(looked.isError, undefined);+ assert.equal(looked.structuredContent.revision, 0);+ assert.equal(looked.structuredContent.motionTime, motionTime);+ }+ const exported = await client.callTool({ name: 'scene_export_recipe', arguments: { sessionId } });+ assert.equal(exported.structuredContent.recipe.motion.tracks[0].property, 'translation');+ await rejected(client, 'scene_apply', { sessionId, expectedRevision: 0, operations: [{ type: 'set-motion',+ motion: { ...motion, tracks: [{ ...motion.tracks[0], javascript: 'run()' }] } }] });+ const cleared = await client.callTool({ name: 'scene_apply', arguments: { sessionId, expectedRevision: 0,+ operations: [{ type: 'set-motion', motion: null }] } });+ assert.equal(cleared.structuredContent.revision, 1);+});+test('real SDK calls preserve atomic revisions, checkpoints, recipe snapshots and PNG content', async context => {const boundary = await connect(context);const { client, sessionId } = boundary;