Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add imported character motion in 67js 0.8.0

Nguyen Xuan And7db5cbf724c
diff --git a/.gitignore b/.gitignore
index faaa67fc..8020a502 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,3 +41,5 @@ public/agent-look.md
public/agent-asset.md
public/agent-render-jobs.md
public/agent-motion.md
+
+public/agent-character-motion.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ae58fe22..02afa603 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## 0.8.0
+
+- Add stable imported source-node IDs, hierarchy inspection and local joint overrides.
+- Add authored joint, material and camera motion on imported GLBs with independent clip timing.
+- Preserve decoded rigs, morphs and textures through staged pose transactions and failed-pose rollback.
+- Verify a textured nine-joint astronaut through native MCP images, stills and video.
+
## 0.7.0
- Author bounded procedural motion in agent recipes with local node, material and camera tracks.
diff --git a/README.md b/README.md
index a8471c07..d7611afb 100644
--- a/README.md
+++ b/README.md
@@ -142,6 +142,8 @@ Agents can author [lights, volumetric fog, grading and shadow coverage](docs/age
After installing the package, run `npx 67js-mcp --backend gpu --memory 192` with Node.js 20.19 or later and a local Chrome installation.
The server and preview are built into the package. The browser driver loads only when a scene is created.
+Version `0.8.0` adds [imported character motion](docs/agent-character-motion.md) with stable joint IDs and atomic pose transactions.
+
The [asset adapter](docs/agent-asset.md) imports catalog GLBs with supported textures, rigs, morphs and clips.
Animation track authoring, imported mesh topology edits and persistent video jobs remain implementation work.
diff --git a/ROADMAP.md b/ROADMAP.md
index c57a1133..3710f8cc 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -23,6 +23,8 @@ This document separates shipping capabilities from work in progress. Performance
Version `0.5.0` includes agent scenes with stable IDs, atomic resource/node edits and checkpoints.
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.
+Version `0.8.0` adds source-node authoring on imported GLBs with retained rigs, morphs, textures and independent clip timing.
+
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.
diff --git a/docs/agent-asset.md b/docs/agent-asset.md
index 3d2e89a0..7311683e 100644
--- a/docs/agent-asset.md
+++ b/docs/agent-asset.md
@@ -59,9 +59,12 @@ material objects in first-use order. Overrides accept `color`, `metallic`,
domains.
Other glTF material fields and texture descriptors retain their
-decoded values. These commands do not edit alpha modes, maps, skin joints,
+decoded values. These commands do not edit alpha modes, maps, skin bindings,
vertices, indices, mesh membership, or morph target definitions.
+Release `0.8.0` adds [source-node and character motion](agent-character-motion.md).
+Hierarchy inspection exposes joints separately from rendered mesh primitives.
+
## Commands and transactions
`apply(operations, {expectedRevision})` requires 1 to 256 commands. The expected
@@ -72,6 +75,8 @@ pose arrays remain unchanged.
| Command | Fields |
| --- | --- |
+| `set-asset-node` | Existing editable source `id` plus local `translation`, `rotation` or `scale` |
+| `set-motion` | A complete `motion` record or explicit `null` |
| `set-root` | Optional flat `translation`, `rotation`, `scale` |
| `set-animation` | Optional `clip`, `time`; `clip:null` restores the captured pose |
| `set-material` | Existing `id` plus optional editable material fields |
diff --git a/docs/agent-character-motion.md b/docs/agent-character-motion.md
new file mode 100644
index 00000000..c9cb3f41
--- /dev/null
+++ b/docs/agent-character-motion.md
@@ -0,0 +1,137 @@
+# Imported character motion
+
+Release `0.8.0` adds imported character motion. Earlier packages support procedural motion or imported clip sampling only.
+
+Imported asset recipes can retain a GLB hierarchy, skin, textures, morphs and existing clips while adding authored motion.
+The decoder loads the asset once. Sampling reuses decoded geometry, texture descriptors and pose buffers.
+
+## Find the joints
+
+```json
+{
+ "name": "scene_inspect",
+ "arguments": {
+ "sessionId": "SESSION_UUID",
+ "kind": "hierarchy",
+ "offset": 0,
+ "limit": 64
+ }
+}
+```
+
+Hierarchy records expose stable source IDs, labels, parents, local transforms, editability, joint flags and associated mesh IDs.
+The source IDs use `node-N`, where `N` is the node index in the GLB.
+Mesh inspection retains separate `mesh-N` IDs for rendered primitives.
+Names are labels because an asset can contain duplicate names.
+
+
+The `offset` and `limit` fields paginate imported asset inspection.
+Hierarchy inspection does not provide deformed silhouette bounds.
+Mesh bounds describe authored base geometry at the recipe pose and motion time zero.
+Transient motion does not change these bounds. Skin and morph deformation can extend beyond them.
+
+## Author a local joint
+
+```json
+{
+ "name": "scene_apply",
+ "arguments": {
+ "sessionId": "SESSION_UUID",
+ "expectedRevision": 0,
+ "operations": [
+ {
+ "type": "set-asset-node",
+ "id": "node-3",
+ "rotation": [0, 0, 0.3826834324, 0.9238795325]
+ }
+ ]
+ }
+}
+```
+
+`set-asset-node` replaces specified local translation, rotation or scale components.
+It preserves unspecified components from the selected imported clip or decoded base pose.
+The canonical recipe stores these changes in `nodeOverrides`.
+Quaternions use XYZW ordering. Scales must remain positive at Float32 precision.
+
+An unsupported shear or reflection makes the source node uneditable. Its untouched imported matrix remains supported.
+
+## Add motion
+
+```json
+{
+ "type": "set-motion",
+ "motion": {
+ "duration": 2,
+ "tracks": [{
+ "kind": "node",
+ "id": "node-3",
+ "property": "rotation",
+ "interpolation": "SMOOTH",
+ "keyframes": [
+ { "time": 0, "value": [0, 0, 0, 1] },
+ { "time": 2, "value": [0, 0, 0.3826834324, 0.9238795325] }
+ ]
+ }]
+ }
+}
+```
+
+The [motion contract](agent-motion.md) defines curves, keyframes, material channels, camera paths and numeric limits.
+Imported node tracks target editable source IDs. Material tracks target existing `material-N` IDs.
+
+Pose evaluation starts from the decoded base on every seek.
+It applies the selected imported clip, static node overrides and authored motion in that order.
+The outer asset root transform applies last.
+Tracks replace specified components rather than adding rotations or translations.
+
+Imported morph animation remains attached to its clip.
+
+`scene_look.motionTime` and `scene.sampleMotion(time)` sample motion without changing the recipe, revision or checkpoints.
+Explicit `null` restores the authored pose without procedural tracks.
+Creating, editing or restoring a recipe samples its motion at time zero.
+Omitting `motionTime` preserves the last preview pose.
+
+## Export a snapshot
+
+```json
+{
+ "name": "scene_render_submit",
+ "arguments": {
+ "sessionId": "SESSION_UUID",
+ "expectedRevision": 1,
+ "settings": {
+ "kind": "video",
+ "width": 480,
+ "height": 480,
+ "duration": 2,
+ "fps": 24,
+ "animation": { "clip": 0, "start": 0 },
+ "motion": { "start": 0 }
+ }
+ }
+}
+```
+
+An imported clip and authored motion have independent clocks. Either clock can remain fixed while the other advances.
+Snapshot jobs retain the exact GLB bytes and canonical recipe.
+Completion or cancellation restores the source preview pose and revision.
+
+`scene.sampleFrame({ animation, motionTime })` stages both clocks together without changing the canonical recipe or revision.
+Omitting animation uses the recipe selection. Omitting motion time retains the last sampled motion time.
+Explicit `null` animation selects the decoded base. Explicit `null` motion time disables authored tracks.
+
+## Decoder transaction
+
+`asset.stagePose({ animation, nodeOverrides })` returns borrowed candidate `parts`, `commit()` and `discard()`.
+The public asset parts remain unchanged until commit. Only one transaction can remain pending.
+The adapter validates the candidate root, skin, morph, material and camera before publication.
+Discard restores private hierarchy transforms, morph influences and mixer state.
+Failed staging or commit preserves the previous public buffers.
+
+Candidate buffers belong to the decoder. Their contents expire at the next staging operation.
+The asset must remain exclusively owned by its adapter while transactions are active.
+
+This feature does not create a rig for a flat mesh collection.
+It does not implement IK, retargeting, facial morph authoring or topology changes.
+The current WALL·E asset has separate mesh roots and no skeleton. It supports rigid part movement through source-node tracks.
diff --git a/docs/agent-motion.md b/docs/agent-motion.md
index 0db0e04e..659490de 100644
--- a/docs/agent-motion.md
+++ b/docs/agent-motion.md
@@ -116,7 +116,8 @@ 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.
+Release `0.8.0` reuses this motion contract for [imported character joints](agent-character-motion.md).
+The helper does not implement mixer controls, facial morph tracks or live playback clocks.
## Bounds and checks
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index c45db99b..bce9c2ee 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -39,6 +39,8 @@ 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.
+Release `0.8.0` also samples imported character tracks and can layer them over an independently sampled imported clip.
+
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.
diff --git a/docs/guide.md b/docs/guide.md
index 13beaf12..c52655c1 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -405,6 +405,8 @@ Its [MCP server](/mcp.md) provides seventeen tools for authoring, previewing and
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.
+Release `0.8.0` adds [imported character motion](/agent-character-motion.md) with editable joints and retained skin, morph and texture resources.
+
The [asset adapter](/agent-asset.md) imports local catalog GLBs with supported textures, rigs, morphs and deterministic clip sampling.
The addon accepts JSON recipes with stable object IDs, shared geometry and material resources, hierarchy and a camera.
diff --git a/docs/mcp.md b/docs/mcp.md
index 1a8b77e9..0615a0a9 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -118,7 +118,8 @@ Set operations use `set-node`, `set-material`, or `set-camera`, with fields dire
`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.
+An explicit `null` restores the authored base pose. Release `0.8.0` also supports imported source-node motion.
+Imported clip sampling remains available through `set-animation`.
`set-node` can rebind a mesh to another geometry/material pair.
@@ -188,7 +189,8 @@ Imported scenes retain their decoded topology. Mesh membership edits remain spec
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, remote URLs or arbitrary caller-selected file paths.
-Imported animation track authoring remains unsupported. Procedural tracks use the bounded motion recipe.
+Release `0.8.0` supports [imported source-node tracks](agent-character-motion.md) through the bounded motion recipe.
+Facial morph track authoring and rig creation remain unsupported.
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.
@@ -220,3 +222,5 @@ The script checks content IDs, root edits, retained texture decoding, reverse an
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.
+
+Run `node scripts/smoke-agent-character.mjs` for a textured nine-joint astronaut through actual CPU previews and snapshot jobs.
diff --git a/docs/release-verification.md b/docs/release-verification.md
index 74354166..dfc870b9 100644
--- a/docs/release-verification.md
+++ b/docs/release-verification.md
@@ -1,5 +1,31 @@
# Release verification
+## 0.8.0
+
+Source checks used Windows Node.js, installed Chrome with CPU SwiftShader and FFmpeg H.264 encoding.
+Registry publication and live deployment require separate verification against the pushed commit.
+
+| Check | Measured result |
+| --- | --- |
+| Node tests | 416 tests passed. |
+| Decoder | Stable source-node IDs, cloned skins, local joint overrides and private pose rollback passed. |
+| Imported motion | Joint, material and camera tracks retained geometry, maps, skin palettes and canonical recipes. |
+| Combined clocks | A valid combined pose bypassed an invalid intermediate weighted skin pose through one transient transaction. |
+| Native character | An original astronaut retained nine joints and one embedded texture through actual MCP PNG previews. |
+| Native video | Eighteen decoded frames formed a three-second H.264 MP4 with BT.709 metadata and changing character poses. |
+| Jobs | Eight stills, layered clip/motion sampling and cancellation preserved the source preview pose and revision. |
+| Determinism | Shuffled PNG seeks and checkpoint restoration reproduced exact image bytes. |
+| Installed source package | The clean CLI ran modern and legacy SDK calls without development dependencies or source files. |
+| Cleanup | Disposal and MCP connection closure exited the installed character CLI. |
+
+The bounded review found one combined-clock defect. A single transient pose transaction removed its causal path.
+The source follow-up found no remaining significant findings within its scope.
+Only one model family reviewed the contract because the other reviewer remained unavailable. This gives weaker coverage than a completed cross review.
+
+Square and portrait astronaut frames were inspected. These checks establish recognizable rig authoring, deterministic seeking and bounded CPU export.
+They do not establish cinematic character quality, Blender parity or hardware GPU performance.
+Facial morph authoring, IK, retargeting and automatic rig creation remain unfinished.
+
## 0.7.0
Source checks used Windows Node.js, installed Chrome with CPU SwiftShader and FFmpeg H.264 encoding.
diff --git a/package-lock.json b/package-lock.json
index 1d3e067c..4ac0e856 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@codepawlhq/67js",
- "version": "0.7.0",
+ "version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@codepawlhq/67js",
- "version": "0.7.0",
+ "version": "0.8.0",
"license": "MIT",
"dependencies": {
"playwright-core": "1.64.0"
diff --git a/package.json b/package.json
index 2096e57e..3862bbdf 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@codepawlhq/67js",
- "version": "0.7.0",
+ "version": "0.8.0",
"private": false,
"type": "module",
"description": "JavaScript tools for agent-driven 3D authoring, browser previews and memory-aware CPU/GPU rendering",
@@ -48,7 +48,8 @@
"docs/agent-look.md",
"docs/agent-asset.md",
"docs/agent-render-jobs.md",
- "docs/agent-motion.md"
+ "docs/agent-motion.md",
+ "docs/agent-character-motion.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -104,7 +105,8 @@
"smoke:frame-encoder": "node scripts/smoke-frame-encoder.mjs",
"smoke:enhancements": "node scripts/smoke-enhancements.mjs",
"smoke:site": "node scripts/smoke-site.mjs",
- "publish:ci": "node scripts/publish-ci.mjs"
+ "publish:ci": "node scripts/publish-ci.mjs",
+ "smoke:agent-character": "node scripts/smoke-agent-character.mjs"
},
"peerDependencies": {
"@dimforge/rapier3d-compat": "0.21.0"
diff --git a/public/llms.txt b/public/llms.txt
index fe1ebf1f..f4b47628 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -10,6 +10,7 @@ The installed package determines available APIs. Release metadata describes the
Version `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.8.0` adds imported source-node overrides and motion. Read `/agent-character-motion.md` for joint IDs, layering and pose ownership.
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.
@@ -30,6 +31,9 @@ Read `/mcp.md` before configuring it. Start with `scene_capabilities`, create a
Read `/agent-asset.md` for imported asset sessions available since `0.5.0` and the `67js/addons/agent-asset` addon.
Configure --assets with an absolute GLB directory, then call scene_asset_catalog and scene_create_asset with a content-bound asset ID.
Imported scenes preserve supported maps, skins, morphs and clips. Their topology remains fixed.
+
+Use scene_inspect kind:hierarchy with offset/limit to find source node-N IDs and editable joints. Mesh-N IDs describe primitives.
+Use set-asset-node for local TRS and set-motion for source-node, material and camera tracks. Preserve the decoded rig and textures.
Use set-root for asset placement and set-animation for absolute clip/time sampling. Checkpoint before sampling or relighting.
Read `/agent-look.md` for recipe environment, effects and shadow fields.
diff --git a/scripts/agent-character-fixture.mjs b/scripts/agent-character-fixture.mjs
new file mode 100644
index 00000000..39721779
--- /dev/null
+++ b/scripts/agent-character-fixture.mjs
@@ -0,0 +1,133 @@
+import { readFile } from 'node:fs/promises';
+import { sphere, box, cylinder } from '../src/geometry.js';
+import { skinnedStripAsset } from '../tests/fixtures/skinned-strip.js';
+
+/** Original toy astronaut with an actual nine-joint skin and embedded suit patch. */
+export async function createAgentCharacterFixture() {
+ const texture = JSON.parse(await readFile(new URL('../tests/fixtures/textured-triangle.gltf', import.meta.url), 'utf8'));
+ const image = Buffer.from(texture.images[0].uri.split(',')[1], 'base64');
+ const jointPositions = [
+ [0, 1, 0], [0, 1.8, 0], [0, 2.55, 0],
+ [-0.65, 2.05, 0], [-0.95, 1.6, 0], [-1.02, 1.08, 0],
+ [0.65, 2.05, 0], [0.95, 1.6, 0], [1.02, 1.08, 0],
+ ];
+ const parents = [-1, 0, 1, 1, 3, 4, 1, 6, 7];
+ const labels = ['Hips', 'Chest', 'Helmet', 'Left shoulder', 'Left elbow', 'Left glove', 'Right shoulder', 'Right elbow', 'Right glove'];
+ const bytes = skinnedStripAsset((document, append) => {
+ document.nodes = [{ name: 'Pip the astronaut', children: [1] }];
+ jointPositions.forEach((position, index) => {
+ const parentPosition = parents[index] < 0 ? [0, 0, 0] : jointPositions[parents[index]];
+ document.nodes.push({ name: labels[index], translation: position.map((value, axis) => value - parentPosition[axis]), children: [] });
+ });
+ parents.forEach((parent, index) => {
+ if (parent >= 0) document.nodes[parent + 1].children.push(index + 1);
+ });
+ document.meshes = [];
+ document.animations = [];
+ const colors = [[0.78, 0.84, 0.82], [0.015, 0.095, 0.11], [0.035, 0.42, 0.38], [0.83, 0.46, 0.12], [0.22, 0.25, 0.28], [0.82, 0.95, 1], [1, 1, 1], [0.19, 0.23, 0.24]];
+ document.materials = colors.map((color, index) => ({
+ name: ['Ceramic suit', 'Visor', 'Teal trim', 'Brass', 'Boots', 'Eyes', 'Suit patch', 'Stage'][index],
+ pbrMetallicRoughness: { baseColorFactor: [...color, 1], metallicFactor: index === 3 ? 0.8 : 0.15, roughnessFactor: index === 1 ? 0.19 : 0.4 },
+ ...(index === 5 ? { emissiveFactor: [0.08, 0.2, 0.22] } : {}),
+ }));
+ append(new Uint8Array(image), 'SCALAR');
+ document.images = [{ bufferView: document.bufferViews.length - 1, mimeType: 'image/png' }];
+ document.textures = [{ source: 0 }];
+ document.materials[6].pbrMetallicRoughness.baseColorTexture = { index: 0 };
+ const inverseBind = new Float32Array(9 * 16);
+ jointPositions.forEach((position, index) => {
+ inverseBind.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ...position.map(value => -value), 1], index * 16);
+ });
+ document.skins = [{ joints: jointPositions.map((_, index) => index + 1), skeleton: 1, inverseBindMatrices: append(inverseBind, 'MAT4') }];
+ function mesh(label, geometry, position, scale, joint, material, blend = null) {
+ const positions = new Float32Array(geometry.positions.length);
+ const normals = new Float32Array(geometry.normals.length);
+ const count = positions.length / 3;
+ const joints = new Uint16Array(count * 4);
+ const weights = new Float32Array(count * 4);
+ const uvs = new Float32Array(count * 2);
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let vertex = 0; vertex < count; vertex++) {
+ let normalLength = 0;
+ for (let axis = 0; axis < 3; axis++) {
+ const offset = vertex * 3 + axis;
+ const value = geometry.positions[offset] * scale[axis] + position[axis];
+ positions[offset] = value;
+ minimum[axis] = Math.min(minimum[axis], value);
+ maximum[axis] = Math.max(maximum[axis], value);
+ normals[offset] = geometry.normals[offset] / scale[axis];
+ normalLength += normals[offset] ** 2;
+ }
+ for (let axis = 0; axis < 3; axis++) normals[vertex * 3 + axis] /= Math.sqrt(normalLength);
+ joints[vertex * 4] = joint;
+ weights[vertex * 4] = 1;
+ if (blend) {
+ const amount = Math.max(0, Math.min(1, (positions[vertex * 3 + 1] - blend.bottom) / (blend.top - blend.bottom)));
+ joints[vertex * 4 + 1] = blend.joint;
+ weights[vertex * 4] = 1 - amount;
+ weights[vertex * 4 + 1] = amount;
+ }
+ uvs[vertex * 2] = geometry.positions[vertex * 3] + 0.5;
+ uvs[vertex * 2 + 1] = geometry.positions[vertex * 3 + 1] + 0.5;
+ }
+ const positionAccessor = append(positions, 'VEC3');
+ document.accessors[positionAccessor].min = minimum;
+ document.accessors[positionAccessor].max = maximum;
+ const primitive = { attributes: { POSITION: positionAccessor, NORMAL: append(normals, 'VEC3'),
+ TEXCOORD_0: append(uvs, 'VEC2'), ...(joint === null ? {} : { JOINTS_0: append(joints, 'VEC4'), WEIGHTS_0: append(weights, 'VEC4') }) },
+ indices: append(new Uint16Array(geometry.indices), 'SCALAR'), material };
+ const meshIndex = document.meshes.push({ name: label, primitives: [primitive] }) - 1;
+ if (joint === null) document.scenes[0].nodes.push(document.nodes.length);
+ else document.nodes[0].children.push(document.nodes.length);
+ document.nodes.push({ name: label, mesh: meshIndex, ...(joint === null ? {} : { skin: 0 }) });
+ }
+ const rounded = box(0.16, 4);
+ const ball = sphere(32, 20);
+ const tube = cylinder(24, 0.08, 4);
+ mesh('Suit torso', rounded, [0, 1.76, 0], [1.03, 0.98, 0.63], 1, 0);
+ mesh('Backpack', rounded, [0, 1.75, -0.42], [0.76, 0.8, 0.32], 1, 2);
+ mesh('Waist belt', rounded, [0, 1.22, 0], [0.96, 0.18, 0.68], 0, 2);
+ mesh('Helmet shell', ball, [0, 2.62, 0], [0.59, 0.58, 0.53], 2, 0);
+ mesh('Visor', ball, [0, 2.64, 0.22], [0.51, 0.39, 0.42], 2, 1);
+ for (const side of [-1, 1]) {
+ mesh('Glowing eye', rounded, [side * 0.17, 2.67, 0.614], [0.1, 0.17, 0.045], 2, 5);
+ mesh('Helmet hinge', tube, [side * 0.54, 2.54, 0], [0.1, 0.14, 0.1], 2, 3);
+ const shoulder = side < 0 ? 3 : 6;
+ const elbow = shoulder + 1;
+ const glove = shoulder + 2;
+ mesh('Shoulder cap', ball, [side * 0.67, 2.04, 0], [0.25, 0.25, 0.28], shoulder, 2);
+ mesh('Flexible upper sleeve', tube, [side * 0.88, 1.81, 0], [0.19, 0.58, 0.19], elbow, 0, { joint: shoulder, bottom: 1.59, top: 2.06 });
+ mesh('Elbow seam', ball, [side * 0.96, 1.57, 0], [0.19, 0.17, 0.19], elbow, 4);
+ mesh('Forearm sleeve', tube, [side * 1.0, 1.31, 0], [0.18, 0.48, 0.18], elbow, 0);
+ mesh('Cuff', tube, [side * 1.02, 1.1, 0], [0.19, 0.13, 0.19], glove, 2);
+ mesh('Glove', rounded, [side * 1.03, 0.94, 0.04], [0.32, 0.34, 0.31], glove, 0);
+ mesh('Trouser', rounded, [side * 0.27, 0.72, 0], [0.4, 0.85, 0.47], 0, 0);
+ mesh('Boot', rounded, [side * 0.28, 0.24, 0.1], [0.48, 0.39, 0.7], 0, 4);
+ mesh('Chest button', ball, [side * 0.12, 1.62, 0.335], [0.045, 0.045, 0.025], 1, side < 0 ? 3 : 2);
+ }
+ mesh('Chest control', rounded, [0, 1.83, 0.34], [0.51, 0.35, 0.075], 1, 2);
+ mesh('Suit patch', rounded, [0, 1.87, 0.385], [0.31, 0.15, 0.028], 1, 6);
+ mesh('Circular stage', cylinder(64, 0.018, 4), [0, 0.005, 0], [2.2, 0.08, 2.2], null, 7);
+ const times = append(new Float32Array([0, 3]), 'SCALAR');
+ const chestRotation = append(new Float32Array([0, 0, 0, 1, 0, Math.sin(0.13), 0, Math.cos(0.13)]), 'VEC4');
+ document.animations = [{ name: 'Gentle chest turn', samplers: [{ input: times, output: chestRotation }], channels: [{ sampler: 0, target: { node: 2, path: 'rotation' } }] }];
+ });
+ const rotation = (axis, angle) => [...axis.map(value => value * Math.sin(angle / 2)), Math.cos(angle / 2)];
+ return {
+ bytes: Buffer.from(bytes),
+ recipe: {
+ format: '67js.asset', schemaVersion: 1,
+ camera: { eye: [5.2, 3.3, 7.8], target: [0, 1.62, 0], fov: 38, near: 0.1, far: 100 },
+ environment: { daylight: 1, keyIntensity: 1.9, fillIntensity: 2.4, ambientIntensity: 1.05, lightDirection: [-0.7, 1, 0.65] },
+ effects: { bloom: { strength: 0.14 }, grain: 0, vignette: 0.08 },
+ animation: { clip: 0, time: 0 },
+ motion: { duration: 3, tracks: [
+ { kind: 'node', id: 'node-0', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 3, value: [0.35, 0, 0] }] },
+ { kind: 'node', id: 'node-3', property: 'rotation', interpolation: 'SMOOTH', keyframes: [{ time: 0, value: rotation([0, 1, 0], -0.15) }, { time: 1.5, value: rotation([0, 1, 0], 0.38) }, { time: 3, value: rotation([0, 1, 0], -0.2) }] },
+ { kind: 'node', id: 'node-7', property: 'rotation', interpolation: 'SMOOTH', keyframes: [{ time: 0, value: rotation([0, 0, 1], 0) }, { time: 1.5, value: rotation([0, 0, 1], 1.1) }, { time: 3, value: rotation([0, 0, 1], 0.35) }] },
+ { kind: 'node', id: 'node-8', property: 'rotation', interpolation: 'SMOOTH', keyframes: [{ time: 0, value: rotation([0, 0, 1], 0) }, { time: 1.5, value: rotation([0, 0, 1], 0.95) }, { time: 3, value: rotation([0, 0, 1], 0.3) }] },
+ ] },
+ },
+ };
+}
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 4e07eeb7..4ddbd2dd 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -201,10 +201,10 @@ window.__agentPreview = {
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) {
+ if (record.asset && (animation !== undefined || motionTime !== undefined)) {
+ record.scene.sampleFrame({ ...(animation === undefined ? {} : { animation }),
+ ...(motionTime === undefined ? {} : { motionTime }) });
+ } else if (motionTime !== undefined) {
record.scene.sampleMotion(motionTime);
}
draw(record, rendererTime);
diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjs
index 3f90f54f..7ed61370 100644
--- a/scripts/agent-render-jobs.mjs
+++ b/scripts/agent-render-jobs.mjs
@@ -65,8 +65,8 @@ function settingsFrom(input, clips, recipe) {
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.');
+ if (!['67js.scene', '67js.asset'].includes(recipe?.format) || !recipe.motion) {
+ throw new RangeError('Motion settings require a 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') {
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index d6e48429..658135a8 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -311,14 +311,14 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
configured: Boolean(assetRoot), formats: ['self-contained GLB'],
maximumBytes: 16 * 1024 * 1024, maximumAssets: 64,
maximumVertices: 250000, maximumParts: 4096, maximumTexturePixels: 4194304, maximumJoints: 1024, maximumClips: 256,
- commands: ['set-root', 'set-animation', 'set-material', 'set-camera', 'set-environment', 'set-effects', 'set-shadow'],
+ commands: ['set-root', 'set-asset-node', 'set-motion', 'set-animation', 'set-material', 'set-camera', 'set-environment', 'set-effects', 'set-shadow'],
},
jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], maximumActiveJobs: 1,
maximumDuration: 30, maximumFps: 30, maximumFrames: 900, maximumStills: 8,
encoder: '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', 'imported animation track authoring', 'job audio'],
+ unsupported: ['remote asset providers', 'arbitrary code execution', 'imported morph track authoring', 'job audio'],
};
},
create({ recipe }) {
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 6f859585..8e80c84f 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -162,6 +162,8 @@ const assetRecipe = z.strictObject({
}).optional(),
animation: z.strictObject({ clip: z.number().int().min(0), time: nonnegative }).nullable().optional().describe('Absolute clip/time sample. null selects the original decoded pose.'),
materialOverrides: z.array(z.strictObject({ id: identifier, ...materialFields })).max(4096).optional(),
+ nodeOverrides: z.array(z.strictObject({ id: identifier, translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() })).max(4096).optional(),
+ motion: motion.nullable().optional(),
});
const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('set-node'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields }),
@@ -172,6 +174,7 @@ const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('set-effects'), effects }),
z.strictObject({ type: z.literal('set-shadow'), shadow }),
z.strictObject({ type: z.literal('set-root'), translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() }),
+ z.strictObject({ type: z.literal('set-asset-node'), id: identifier, translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() }),
z.strictObject({ type: z.literal('set-animation'), clip: z.number().int().min(0).nullable().optional(), time: nonnegative.optional() }),
z.strictObject({ type: z.literal('add-node'), node: nodeRecord }),
z.strictObject({ type: z.literal('remove-node'), id: identifier, recursive: z.boolean().optional().describe('Remove descendants too. Defaults to false; dangling children reject the batch.') }),
@@ -193,7 +196,7 @@ const renderSettings = z.strictObject({
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. 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.');
+}).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 authored recipe tracks, animation for an imported clip, or both to layer them. 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 };
@@ -227,9 +230,9 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
register('scene_create', 'Create the single active render scene from a JSON recipe. Dispose an existing scene first.', z.strictObject({ recipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));
register('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 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 => {
+ 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.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), 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 and set-motion authoring. Imported assets support set-root, set-asset-node, set-motion 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 authored 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.mjs
index b046b884..102467c7 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', 'agent-motion.md',
+ 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/scripts/smoke-agent-character.mjs b/scripts/smoke-agent-character.mjs
new file mode 100644
index 00000000..c7c13308
--- /dev/null
+++ b/scripts/smoke-agent-character.mjs
@@ -0,0 +1,172 @@
+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 { createAgentCharacterFixture } from './agent-character-fixture.mjs';
+import { createHash } from 'node:crypto';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-character-'));
+const jobs = join(directory, 'jobs');
+const assets = join(directory, 'assets');
+await mkdir(assets);
+const fixture = await createAgentCharacterFixture();
+await writeFile(join(assets, 'pip.glb'), fixture.bytes);
+fixture.recipe.assetId = createHash('sha256').update(fixture.bytes).digest('hex');
+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, '--assets', assets],
+ 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);
+ assert.equal(result.structuredContent.materialTextures, 1);
+ assert.ok(result.structuredContent.skinTextures >= 1);
+ return result.content.find(item => item.type === 'image').data;
+}
+
+try {
+ await client.connect(transport);
+ const catalog = (await call('scene_asset_catalog')).structuredContent;
+ assert.ok(JSON.stringify(catalog).includes(fixture.recipe.assetId));
+ const created = (await call('scene_create_asset', { recipe: fixture.recipe }, 180000)).structuredContent;
+ assert.equal(created.inspection.motion.tracks, 4);
+ const sessionId = created.sessionId;
+ assert.equal(created.render.materialTextures, 1);
+ assert.ok(created.render.skinTextures >= 1);
+ const hierarchy = (await call('scene_inspect', { sessionId, kind: 'hierarchy', limit: 64 })).structuredContent;
+ assert.equal(hierarchy.counts.joints, 9);
+ assert.equal(hierarchy.nodes.find(node => node.id === 'node-8').parent, 'node-7');
+ 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-character-start.png', Buffer.from(start, 'base64'));
+ await writeFile('artifacts/agent-character-middle.png', Buffer.from(middle, 'base64'));
+ await writeFile('artifacts/agent-character-end.png', Buffer.from(end, 'base64'));
+ const portrait = await look(sessionId, 1.5, 390, 640);
+ await writeFile('artifacts/agent-character-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-character-still-${index}.png`);
+ }
+ } else {
+ videoResult = result;
+ const output = result.artifacts[0].path;
+ await copyFile(output, 'artifacts/agent-character.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 layered = (await call('scene_render_submit', { sessionId, expectedRevision: 0, settings: { kind: 'image', width: 480, height: 480, animation: { clip: 0, start: 1.5 }, motion: { start: 1.5 } } })).structuredContent;
+ assert.equal((await status(layered.jobId)).state, 'completed');
+ assert.equal(await look(sessionId), middle);
+ completed.push(layered.jobId);
+ const invalid = await client.callTool({ name: 'scene_apply', arguments: { sessionId, expectedRevision: 0, operations: [{ type: 'set-root', scale: [1e-40, 1e-40, 1e-40] }] } });
+ assert.equal(invalid.isError, true);
+ assert.equal(await look(sessionId), middle);
+ 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-character-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/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 4114e994..ab8aea53 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -33,6 +33,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- 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`.
+- Agent imported character motion uses `docs/agent-character-motion.md` from release `0.8.0`. Inspect source joints before authoring local tracks.
- 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.md
index 8f321037..391d5b97 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -169,6 +169,14 @@ For imported models, read `docs/agent-asset.md`, configure `--assets` with an ab
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.
+Release `0.8.0` adds imported source-node overrides and motion. Read `docs/agent-character-motion.md` before editing a rig.
+Inspect `kind: 'hierarchy'` with offset and limit for stable `node-N` IDs, parents, joint flags and editability.
+Use `set-asset-node` for local TRS and `set-motion` for authored tracks. Keep decoded skin bindings, maps and topology unchanged.
+
+The pose layers decoded base, selected clip, static overrides, motion and outer root in that order.
+Use `scene.sampleFrame({ animation, motionTime })` to stage both clocks together. Sequential edits can introduce an invalid intermediate skin pose.
+Discard failed candidate poses before renderer upload. Flat models need a rig before they can deform as characters.
+
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.
diff --git a/skills/render-67js-media/SKILL.md b/skills/render-67js-media/SKILL.md
index 9e5be948..47ee5420 100644
--- a/skills/render-67js-media/SKILL.md
+++ b/skills/render-67js-media/SKILL.md
@@ -14,6 +14,8 @@ For MCP snapshot jobs, read the checkout's `docs/agent-render-jobs.md` and verif
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.
+For imported character motion from `0.8.0`, read `docs/agent-character-motion.md`. Use independent `settings.animation` and `settings.motion` clocks.
+
## Choose and render
1. Check the available GPU memory before a GPU job on a shared machine.
diff --git a/src/agent-asset.js b/src/agent-asset.js
index c13f6cb9..0a039005 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -3,6 +3,7 @@ import { createAgentScene } from './agent-scene.js';
import { fitPerspectiveDistance } from './camera.js';
import { validateSkinGeometry, validateSkinPose } from './skinning.js';
import { validateMorphGeometry, validateMorphTransform } from './morph.js';
+import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';
const MAX_RECIPE_BYTES = 1024 * 1024;
const MAX_CHECKPOINTS = 8;
@@ -21,7 +22,7 @@ export const AGENT_ASSET_CAPABILITIES = Object.freeze({
format: '67js.asset', schemaVersion: 1, fixedTopology: true,
operations: Object.freeze([
'set-camera', 'set-environment', 'set-effects', 'set-shadow',
- 'set-root', 'set-animation', 'set-material',
+ 'set-root', 'set-animation', 'set-material', 'set-asset-node', 'set-motion',
]),
boundsKind: 'authored-base-world',
});
@@ -143,38 +144,6 @@ function viewRecipe(input, materials = []) {
return createAgentScene(recipe, { maxMaterials: Math.max(256, materials.length) }).exportRecipe();
}
-function poseBuffers(sourceParts) {
- const buffers = new Set();
- for (const part of sourceParts) {
- buffers.add(part.matrix);
- if (part.skin) {
- buffers.add(part.skin.jointMatrices);
- if (part.skin.jointWorldMatrices) {
- buffers.add(part.skin.jointWorldMatrices);
- }
- }
- if (part.morph) {
- buffers.add(part.morph.weights);
- }
- }
- return [...buffers].map(array => ({ array, length: array.length }));
-}
-
-function snapshotPose(buffers) {
- return buffers.map(({ array, length }) => {
- if (!(array instanceof Float32Array) || array.length !== length || array.byteLength !== length * 4) {
- throw new RangeError('Decoded pose buffers must retain their identities and must not detach.');
- }
- return { array, values: new Float32Array(array) };
- });
-}
-
-function restorePose(snapshot) {
- for (const { array, values } of snapshot) {
- Float32Array.prototype.set.call(array, values);
- }
-}
-
function geometryMaxima(geometry) {
const maximum = [0, 0, 0];
for (let offset = 0; offset < geometry.positions.length; offset += 3) {
@@ -280,7 +249,7 @@ function framedCamera(bounds) {
/** Own authoring state around one exclusively owned, decoded parseGltf asset. */
export function createAgentAssetScene(asset, inputRecipe) {
if (!asset || !Array.isArray(asset.parts) || !asset.parts.length || !Array.isArray(asset.animations) ||
- typeof asset.applyAnimation !== 'function') {
+ typeof asset.stagePose !== 'function' || !Array.isArray(asset.nodes)) {
throw new TypeError('createAgentAssetScene requires a decoded parseGltf asset.');
}
if (asset.parts.length > 4096 || asset.animations.length > 256 ||
@@ -321,8 +290,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
};
});
const materialRecords = new Map([...materials.values()].map(record => [record.id, record]));
- const buffers = poseBuffers(sourceParts);
- const initialPose = snapshotPose(buffers);
+ const sourceNodes = new Map(asset.nodes.map(node => [node.id, structuredClone(node)]));
const initialRecipe = copiedJson(inputRecipe);
const assetId = initialRecipe?.assetId;
if (typeof assetId !== 'string' || !/^[a-f0-9]{64}$/i.test(assetId)) {
@@ -334,6 +302,9 @@ export function createAgentAssetScene(asset, inputRecipe) {
let materialSnapshots = new Map();
let matrices = [];
let revision = 0;
+ let sampler = null;
+ let motionTime = null;
+ let sampledCamera;
const checkpoints = new Map();
const materialOutputs = new Map([...materials].map(([source, record]) => {
const output = {};
@@ -379,7 +350,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
function normalize(input) {
const candidate = copiedJson(input);
- knownKeys(candidate, ['format', 'schemaVersion', 'assetId', 'camera', ...LOOK_FIELDS, 'root', 'animation', 'materialOverrides'], 'asset recipe');
+ knownKeys(candidate, ['format', 'schemaVersion', 'assetId', 'camera', ...LOOK_FIELDS, 'root', 'animation', 'materialOverrides', 'nodeOverrides', 'motion'], 'asset recipe');
if (candidate.format !== '67js.asset' || candidate.schemaVersion !== 1 ||
typeof candidate.assetId !== 'string' || candidate.assetId.toLowerCase() !== canonicalAssetId) {
throw new RangeError('Expected the bound 67js.asset schemaVersion 1 assetId.');
@@ -417,15 +388,56 @@ export function createAgentAssetScene(asset, inputRecipe) {
throw new RangeError('Animation needs an existing clip and time within its duration.');
}
}
- return copiedJson({
+ const nodeOverrides = candidate.nodeOverrides === undefined ? [] : candidate.nodeOverrides;
+ if (!Array.isArray(nodeOverrides) || nodeOverrides.length > sourceNodes.size) {
+ throw new RangeError('nodeOverrides must fit the decoded source-node count.');
+ }
+ const seenNodes = new Set();
+ const normalizedNodes = nodeOverrides.map(override => {
+ knownKeys(override, ['id', ...ROOT_FIELDS], 'node override');
+ const node = sourceNodes.get(override.id);
+ if (!node || seenNodes.has(override.id) || !node.editable) {
+ throw new RangeError('Node override IDs must exist, be editable and be distinct.');
+ }
+ seenNodes.add(override.id);
+ const fields = Object.keys(override).filter(field => field !== 'id');
+ if (!fields.length) {
+ throw new RangeError('Node overrides need at least one local transform component.');
+ }
+ const transform = rootFrom(Object.fromEntries(fields.map(field => [field, override[field]])));
+ return { id: override.id, ...Object.fromEntries(fields.map(field => [field, transform[field]])) };
+ });
+ const result = copiedJson({
format: '67js.asset', schemaVersion: 1, assetId: canonicalAssetId,
camera: view.camera, environment: view.environment, effects: view.effects, shadow: view.shadow,
- root: rootFrom(candidate.root), animation, materialOverrides: normalizedOverrides,
+ root: rootFrom(candidate.root), animation, materialOverrides: normalizedOverrides, nodeOverrides: normalizedNodes,
});
+ result.motion = normalizeAgentMotion(candidate.motion, motionRecipe(result));
+ return copiedJson(result);
+ }
+
+ function motionRecipe(candidate) {
+ const baselines = new Map([...materialRecords].map(([id, record]) => [id, { id, ...record.baseline }]));
+ for (const override of candidate.materialOverrides) {
+ baselines.set(override.id, { ...baselines.get(override.id), ...override });
+ }
+ return {
+ nodes: [...sourceNodes.values()].filter(node => node.editable),
+ materials: [...baselines.values()], camera: candidate.camera,
+ };
}
- function publish(input, autoFrame = false, increment = true) {
- let candidate = normalize(input);
+ function publish(input, autoFrame = false, increment = true, transientTime = undefined, transientAnimation = undefined) {
+ let candidate = transientTime === undefined ? normalize(input) : recipe;
+ if (transientAnimation !== undefined) {
+ candidate = { ...candidate, animation: transientAnimation };
+ }
+ let stagedSampler = transientTime === undefined ? compileAgentMotion(candidate.motion, motionRecipe(candidate)) : sampler;
+ const targetTime = transientTime === undefined ? (candidate.motion ? 0 : null) : transientTime;
+ if (targetTime !== null && !stagedSampler) {
+ throw new RangeError('The asset has no authored motion to sample.');
+ }
+ let sampled = targetTime === null ? null : stagedSampler.sample(targetTime);
if (asset.parts.length !== records.length) {
throw new RangeError('Decoded part membership must remain fixed.');
}
@@ -440,40 +452,48 @@ export function createAgentAssetScene(asset, inputRecipe) {
throw new RangeError('Decoded resources and retained adapter matrices must not change identity or detach.');
}
}
- const previousPose = snapshotPose(buffers);
+ const nodeOverrides = new Map(candidate.nodeOverrides.map(override => [override.id, override]));
+ for (const [id, patch] of sampled?.nodes ?? []) {
+ const copiedPatch = Object.fromEntries(Object.entries(patch).map(([field, value]) => [field, Array.from(value)]));
+ nodeOverrides.set(id, { ...nodeOverrides.get(id), id, ...copiedPatch });
+ }
+ let transaction;
try {
- if (candidate.animation === null) {
- restorePose(initialPose);
- } else {
- asset.applyAnimation(candidate.animation.time, candidate.animation.clip);
- }
+ transaction = asset.stagePose({ animation: candidate.animation, nodeOverrides: [...nodeOverrides.values()] });
const rootMatrix = mat4.fromRotationTranslationScale(mat4.create(), candidate.root.rotation, candidate.root.translation, candidate.root.scale);
const normal = mat3.create();
- const stagedMatrices = records.map(record => {
- const world = mat4.multiply(mat4.create(), rootMatrix, record.source.matrix);
+ const stagedMatrices = records.map((record, index) => {
+ const posed = transaction.parts[index];
+ const world = mat4.multiply(mat4.create(), rootMatrix, posed.matrix);
const determinant = mat4.determinant(world);
if (!world.every(Number.isFinite) || !Number.isFinite(determinant) || determinant === 0 ||
!mat3.normalFromMat4(normal, world) || !normal.every(Number.isFinite)) {
throw new RangeError('Asset root/world matrices must remain finite and nonsingular at Float32 precision.');
}
- if (record.source.skin) {
- validateSkinPose(record.source.skin, record.source.geometry, world);
+ if (posed.skin) {
+ validateSkinPose(posed.skin, record.source.geometry, world);
}
- if (record.source.morph) {
- validateMorphTransform(record.source.morph, morphMetadata.get(record.source.geometry), world, record.source.skin);
+ if (posed.morph) {
+ validateMorphTransform(posed.morph, morphMetadata.get(record.source.geometry), world, posed.skin);
} else {
- validatePositionBounds(record.geometry.maxima, world, record.source.skin);
+ validatePositionBounds(record.geometry.maxima, world, posed.skin);
}
return world;
});
if (autoFrame) {
candidate.camera = framedCamera(framingBounds(records, stagedMatrices));
candidate = normalize(candidate);
+ stagedSampler = compileAgentMotion(candidate.motion, motionRecipe(candidate));
+ sampled = targetTime === null ? null : stagedSampler.sample(targetTime);
}
const stagedMaterials = new Map([...materialRecords].map(([id, record]) => [id, { ...record.baseline }]));
for (const override of candidate.materialOverrides) {
stagedMaterials.set(override.id, { ...stagedMaterials.get(override.id), ...override });
}
+ for (const [id, patch] of sampled?.materials ?? []) {
+ const copiedPatch = Object.fromEntries(Object.entries(patch).map(([field, value]) => [field, typeof value === 'number' ? value : Array.from(value)]));
+ stagedMaterials.set(id, { ...stagedMaterials.get(id), ...copiedPatch });
+ }
for (const snapshot of stagedMaterials.values()) {
for (const field of ['color', 'emissiveColor']) {
if (snapshot[field]) {
@@ -482,25 +502,34 @@ export function createAgentAssetScene(asset, inputRecipe) {
}
Object.freeze(snapshot);
}
+ const stagedCamera = sampled?.camera ? {
+ ...candidate.camera,
+ ...Object.fromEntries(Object.entries(sampled.camera).filter(([field]) => field !== 'projection').map(([field, value]) => [field, ArrayBuffer.isView(value) ? Array.from(value) : value])),
+ } : candidate.camera;
+ // Validate camera geometry through the same canonical view contract.
+ viewRecipe({ camera: stagedCamera });
+ const preparedTransaction = transaction;
+ transaction = null;
+ preparedTransaction.commit();
for (let index = 0; index < parts.length; index++) {
Float32Array.prototype.set.call(parts[index].matrix, stagedMatrices[index]);
}
- recipe = candidate;
+ if (transientTime === undefined) {
+ recipe = candidate;
+ sampler = stagedSampler;
+ }
materialSnapshots = stagedMaterials;
- matrices = stagedMatrices;
+ sampledCamera = stagedCamera;
+ motionTime = targetTime;
+ if (transientTime === undefined) {
+ matrices = stagedMatrices;
+ }
if (increment) {
revision++;
}
return revision;
} catch (error) {
- if (recipe?.animation) {
- try {
- asset.applyAnimation(recipe.animation.time, recipe.animation.clip);
- } catch {
- // Accessible pose arrays below remain the authoritative rollback snapshot.
- }
- }
- restorePose(previousPose);
+ transaction?.discard();
throw error;
}
}
@@ -522,7 +551,10 @@ export function createAgentAssetScene(asset, inputRecipe) {
return 0;
},
get camera() {
- return structuredClone(recipe.camera);
+ return structuredClone(sampledCamera);
+ },
+ get motionTime() {
+ return motionTime;
},
get environment() {
return structuredClone(recipe.environment);
@@ -536,6 +568,23 @@ export function createAgentAssetScene(asset, inputRecipe) {
exportRecipe() {
return structuredClone(recipe);
},
+ sampleMotion(time) {
+ if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {
+ throw new RangeError('Motion sample time must be null or within zero and 3600.');
+ }
+ publish(recipe, false, false, time);
+ return motionTime;
+ },
+ sampleFrame(input) {
+ const frame = copiedJson(input);
+ knownKeys(frame, ['animation', 'motionTime'], 'asset frame');
+ const time = frame.motionTime === undefined ? motionTime : frame.motionTime;
+ if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {
+ throw new RangeError('Motion sample time must be null or within zero and 3600.');
+ }
+ publish(recipe, false, false, time, frame.animation);
+ return motionTime;
+ },
apply(inputOperations, options = {}) {
expected(options);
if (!Array.isArray(inputOperations) || !inputOperations.length || inputOperations.length > MAX_OPERATIONS) {
@@ -570,6 +619,29 @@ export function createAgentAssetScene(asset, inputRecipe) {
candidate.root[field] = operation[field];
}
}
+ } else if (operation.type === 'set-motion') {
+ knownKeys(operation, ['type', 'motion'], 'operation');
+ if (!Object.hasOwn(operation, 'motion')) {
+ throw new TypeError('set-motion requires a motion record or explicit null.');
+ }
+ candidate.motion = operation.motion;
+ } else if (operation.type === 'set-asset-node') {
+ knownKeys(operation, ['type', 'id', ...ROOT_FIELDS], 'operation');
+ if (!sourceNodes.has(operation.id)) {
+ throw new RangeError(`Unknown source-node ID: ${operation.id}.`);
+ }
+ const fields = ROOT_FIELDS.filter(field => Object.hasOwn(operation, field));
+ if (!fields.length) {
+ throw new TypeError('set-asset-node needs a local transform component.');
+ }
+ let override = candidate.nodeOverrides.find(value => value.id === operation.id);
+ if (!override) {
+ override = { id: operation.id };
+ candidate.nodeOverrides.push(override);
+ }
+ for (const field of fields) {
+ override[field] = operation[field];
+ }
} else if (operation.type === 'set-animation') {
knownKeys(operation, ['type', 'clip', 'time'], 'operation');
if (operation.clip === null) {
@@ -606,12 +678,36 @@ export function createAgentAssetScene(asset, inputRecipe) {
},
inspect(inputOptions = {}) {
const options = copiedJson(inputOptions);
- knownKeys(options, ['ids', 'limit', 'includeBounds'], 'inspection');
+ knownKeys(options, ['ids', 'limit', 'includeBounds', 'kind', 'offset'], 'inspection');
const limit = options.limit === undefined ? 64 : options.limit;
if (!Number.isInteger(limit) || limit < 1 || limit > 256 ||
(options.includeBounds !== undefined && typeof options.includeBounds !== 'boolean')) {
throw new RangeError('Inspection needs limit from 1 to 256 and boolean includeBounds.');
}
+ const offset = options.offset === undefined ? 0 : options.offset;
+ if (!Number.isInteger(offset) || offset < 0 || offset > 4096 ||
+ (options.kind !== undefined && !['meshes', 'hierarchy'].includes(options.kind))) {
+ throw new RangeError('Inspection kind must be meshes or hierarchy with an offset from zero to 4096.');
+ }
+ if (options.kind === 'hierarchy') {
+ if (options.includeBounds) {
+ throw new TypeError('Hierarchy inspection has no deformed silhouette bounds.');
+ }
+ if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > sourceNodes.size)) {
+ throw new RangeError('Hierarchy IDs must fit the source-node count.');
+ }
+ const selected = options.ids === undefined ? [...sourceNodes.values()] : options.ids.map(id => {
+ if (!sourceNodes.has(id)) {
+ throw new RangeError(`Unknown source-node ID: ${id}.`);
+ }
+ return sourceNodes.get(id);
+ });
+ const nodes = structuredClone(selected.slice(offset, offset + limit));
+ return { revision, topologyRevision: 0, assetId: canonicalAssetId, kind: 'hierarchy',
+ counts: { nodes: sourceNodes.size, joints: [...sourceNodes.values()].filter(node => node.joint).length },
+ nodes, offset, truncated: offset + nodes.length < selected.length,
+ motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, time: motionTime } : null };
+ }
if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > records.length)) {
throw new RangeError('Inspection IDs must be an array within the decoded part count.');
}
@@ -622,7 +718,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
}
return record;
});
- const visible = selected.slice(0, limit);
+ const visible = selected.slice(offset, offset + limit);
if (options.includeBounds && visible.reduce((total, record) => total + record.source.geometry.positions.length / 3, 0) > MAX_INSPECTION_VERTICES) {
throw new RangeError('Bounds inspection exceeds two million authored base vertices. Select fewer meshes.');
}
@@ -657,8 +753,9 @@ export function createAgentAssetScene(asset, inputRecipe) {
revision, topologyRevision: 0, assetId: canonicalAssetId,
counts: { nodes: parts.length, parts: parts.length, geometries: geometries.size, materials: materials.size, vertices },
geometryBytes, animation: structuredClone(recipe.animation),
+ motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, time: motionTime } : null,
animations: asset.animations.map((clip, index) => ({ id: index, label: String(clip.name ?? `Clip ${index}`).slice(0, 256), duration: clip.duration })),
- nodes, truncated: selected.length > nodes.length,
+ nodes, offset, truncated: selected.length > offset + nodes.length,
};
},
checkpoint() {
diff --git a/src/gltf.js b/src/gltf.js
index 8e7d2631..ba2f7b28 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -618,7 +618,9 @@ function skinPreflightPlugin(parser, document, primitiveAssociations) {
const roots = await Promise.all(Array.from(rootIndices, async index => [index, await parser.getDependency('node', index)]));
originalRoots = new Map(roots);
for (const [node, association] of parser.associations) {
- if (node.isMesh) primitiveAssociations.set(node, Object.freeze({ ...association }));
+ if (node.isMesh || Number.isInteger(association?.nodes)) {
+ primitiveAssociations.set(node, Object.freeze({ ...association }));
+ }
}
},
afterRoot(result) {
@@ -805,53 +807,326 @@ export async function parseGltf(data, options = {}) {
});
validateNodeTransforms(nodes, pendingNodeMatrix, pendingTransform);
if (!parts.length) throw new Error('glTF scene contains no supported triangle meshes.');
+ const sourceNodes = new Map();
+ for (const node of nodes) {
+ const index = primitiveAssociations.get(node)?.nodes;
+ if (index === undefined) continue;
+ const id = `node-${index}`;
+ if (sourceNodes.has(id)) {
+ throw new Error('Decoded source node IDs must not alias.');
+ }
+ sourceNodes.set(id, node);
+ }
+ const sourceIds = new Map([...sourceNodes].map(([id, node]) => [node, id]));
+ const jointNodes = new Set(skinBindings.flatMap(binding => binding.node.skeleton.bones));
+ const meshIdsByNode = new Map([...sourceNodes.values()].map(node => [node, []]));
+ for (let index = 0; index < bindings.length; index++) {
+ let ancestor = bindings[index].node;
+ while (ancestor && !sourceIds.has(ancestor)) ancestor = ancestor.parent;
+ if (!ancestor) {
+ throw new Error('Decoded mesh requires a stable source node association.');
+ }
+ meshIdsByNode.get(ancestor).push(`mesh-${index}`);
+ }
+ const nodeMetadata = [...sourceNodes].map(([id, node]) => {
+ let parent = node.parent;
+ while (parent && !sourceIds.has(parent)) parent = parent.parent;
+ const original = document.nodes[Number(id.slice(5))];
+ const composed = new Matrix4().compose(node.position, node.quaternion, node.scale);
+ const authoredMatrix = original.matrix ?? node.matrix.elements;
+ const editable = node.scale.toArray().every(value => value > 0 && Math.fround(value) > 0) &&
+ composed.determinant() > 0 && authoredMatrix.every((value, index) =>
+ Math.abs(value - composed.elements[index]) <= 1e-6 * Math.max(1, Math.abs(value)));
+ const meshIds = meshIdsByNode.get(node);
+ return { id, label: String(original.name ?? id).slice(0, 256), parent: sourceIds.get(parent) ?? null,
+ translation: node.position.toArray(), rotation: node.quaternion.toArray(), scale: node.scale.toArray(),
+ editable, joint: jointNodes.has(node), meshIds };
+ });
+ const metadataById = new Map(nodeMetadata.map(metadata => [metadata.id, metadata]));
+ const candidateParts = bindings.map(binding => ({ ...binding.part, matrix: binding.pendingMatrix }));
+ for (const binding of skinBindings) {
+ const index = bindings.findIndex(transform => transform.node === binding.node);
+ candidateParts[index].skin = Object.assign(binding.pendingPose, {
+ joints: binding.skin.joints, inverseBindMatrices: binding.skin.inverseBindMatrices,
+ jointWorldMatrices: binding.pendingWorld, bindMatrix: binding.skin.bindMatrix,
+ });
+ }
+ for (const binding of morphBindings) {
+ candidateParts[bindings.findIndex(transform => transform.node === binding.node)].morph = binding.pendingPose;
+ }
const mixer = new AnimationMixer(gltf.scene);
let disposed = false;
- function dispose() {
- if (disposed) return;
- disposed = true;
- mixer.stopAllAction();
- mixer.uncacheRoot(gltf.scene);
- releaseParsed(gltf);
- objectUrls.forEach(url => URL.revokeObjectURL(url));
+ let pendingTransaction;
+ let currentAnimation = null;
+
+ function capturePrivatePose() {
+ return nodes.map(node => ({ node, translation: node.position.toArray(), rotation: node.quaternion.toArray(),
+ scale: node.scale.toArray(), matrix: [...node.matrix.elements], world: [...node.matrixWorld.elements],
+ matrixAutoUpdate: node.matrixAutoUpdate, matrixWorldNeedsUpdate: node.matrixWorldNeedsUpdate,
+ weights: node.morphTargetInfluences ? [...node.morphTargetInfluences] : null }));
}
- function applyAnimation(time, clipIndex = 0) {
- if (disposed) throw new Error('The glTF asset was disposed.');
- if (!Number.isFinite(time)) throw new TypeError('Animation time must be finite.');
- if (!Number.isInteger(clipIndex) || !gltf.animations[clipIndex]) throw new RangeError('Animation clip index is out of range.');
- const clip = gltf.animations[clipIndex];
+
+ function restorePrivatePose(snapshot) {
+ for (const entry of snapshot) {
+ entry.node.position.fromArray(entry.translation);
+ entry.node.quaternion.fromArray(entry.rotation);
+ entry.node.scale.fromArray(entry.scale);
+ entry.node.matrix.fromArray(entry.matrix);
+ entry.node.matrixWorld.fromArray(entry.world);
+ entry.node.matrixAutoUpdate = entry.matrixAutoUpdate;
+ entry.node.matrixWorldNeedsUpdate = entry.matrixWorldNeedsUpdate;
+ if (entry.weights) {
+ for (let index = 0; index < entry.weights.length; index++) {
+ entry.node.morphTargetInfluences[index] = entry.weights[index];
+ }
+ }
+ }
+ }
+
+ const basePose = capturePrivatePose();
+
+ function playAnimation(animation) {
mixer.stopAllAction();
+ restorePrivatePose(basePose);
+ mixer.setTime(0);
+ if (animation === null) {
+ return;
+ }
+ const clip = gltf.animations[animation.clip];
const action = mixer.clipAction(clip);
action.reset();
action.setLoop(LoopOnce, 1);
action.clampWhenFinished = true;
action.play();
- mixer.setTime(Math.max(0, Math.min(time, clip.duration)));
+ mixer.setTime(animation.time);
+ }
+
+ function preparePose() {
gltf.scene.updateMatrixWorld(true);
validateNodeTransforms(nodes, pendingNodeMatrix, pendingTransform);
for (const { node, part, mirrored, matrix, pendingMatrix, skin } of bindings) {
- if (part.matrix !== matrix || matrix.length !== 16) throw new Error('Imported part matrix identity must remain unchanged.');
- if (part.skin !== skin) throw new Error('Imported skin pose identity must remain unchanged.');
+ if (part.matrix !== matrix || matrix.length !== 16) {
+ throw new Error('Imported part matrix identity must remain unchanged.');
+ }
+ if (part.skin !== skin) {
+ throw new Error('Imported skin pose identity must remain unchanged.');
+ }
pendingMatrix.set(node.matrixWorld.elements);
- for (const value of pendingMatrix) if (!Number.isFinite(value)) throw new Error('Animation creates a non-finite Float32 world matrix.');
+ for (const value of pendingMatrix) {
+ if (!Number.isFinite(value)) {
+ throw new Error('Animation creates a non-finite Float32 world matrix.');
+ }
+ }
const determinant = node.matrixWorld.determinant();
const roundedDeterminant = pendingTransform.fromArray(pendingMatrix).determinant();
if (!Number.isFinite(determinant) || !Number.isFinite(roundedDeterminant) || Math.abs(roundedDeterminant) < 1e-12 || (determinant < 0) !== mirrored || (roundedDeterminant < 0) !== mirrored) {
throw new Error('Animation creates a singular transform or changes triangle winding.');
}
}
- for (const binding of skinBindings) prepareSkinBinding(binding, binding.geometry);
+ for (const binding of skinBindings) {
+ prepareSkinBinding(binding, binding.geometry);
+ }
for (const binding of morphBindings) {
- if (binding.part.morph !== binding.pose) throw new Error('Imported morph pose identity must remain unchanged.');
+ if (binding.part.morph !== binding.pose) {
+ throw new Error('Imported morph pose identity must remain unchanged.');
+ }
prepareMorphBinding(binding);
validateMorphTransform(binding.pendingPose, binding.metadata, binding.pendingMatrix, binding.pendingSkin);
}
- for (const { matrix, pendingMatrix } of bindings) matrix.set(pendingMatrix);
- for (const binding of skinBindings) commitSkinBinding(binding);
- for (const binding of morphBindings) binding.weights.set(binding.pendingPose.weights);
- return parts;
}
- return { parts, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations, applyAnimation, dispose, capabilities: GLTF_CAPABILITIES };
+
+ function knownPoseFields(value, fields, label) {
+ if (!value || Object.getPrototypeOf(value) !== Object.prototype) {
+ throw new TypeError(`${label} must be a plain object.`);
+ }
+ for (const field of Reflect.ownKeys(value)) {
+ const descriptor = Object.getOwnPropertyDescriptor(value, field);
+ if (typeof field !== 'string' || !fields.includes(field) || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {
+ throw new TypeError(`Unknown or unsupported ${label} field: ${String(field)}.`);
+ }
+ }
+ }
+
+ function poseVector(value, length, label) {
+ if (!Array.isArray(value) || value.length !== length || Reflect.ownKeys(value).length !== length + 1) {
+ throw new TypeError(`${label} needs ${length} finite Float32 values.`);
+ }
+ const result = [];
+ for (let index = 0; index < length; index++) {
+ const descriptor = Object.getOwnPropertyDescriptor(value, index);
+ if (!descriptor || !Object.hasOwn(descriptor, 'value') || !Number.isFinite(descriptor.value) || !Number.isFinite(Math.fround(descriptor.value))) {
+ throw new TypeError(`${label} needs ${length} finite Float32 values.`);
+ }
+ result.push(descriptor.value);
+ }
+ return result;
+ }
+
+ function normalizePose(input) {
+ knownPoseFields(input, ['animation', 'nodeOverrides'], 'pose');
+ const animation = input.animation ?? null;
+ if (animation !== null) {
+ knownPoseFields(animation, ['clip', 'time'], 'pose animation');
+ const clip = gltf.animations[animation.clip];
+ if (!Number.isInteger(animation.clip) || !clip || !Number.isFinite(animation.time) || animation.time < 0 || animation.time > clip.duration) {
+ throw new RangeError('Pose animation needs an existing clip and time within its duration.');
+ }
+ }
+ const inputOverrides = input.nodeOverrides === undefined ? [] : input.nodeOverrides;
+ const maximumOverrides = Math.min(4096, sourceNodes.size);
+ if (!Array.isArray(inputOverrides) || inputOverrides.length > maximumOverrides ||
+ Reflect.ownKeys(inputOverrides).length !== inputOverrides.length + 1) {
+ throw new RangeError(`Pose overrides must be a dense array with at most ${maximumOverrides} entries.`);
+ }
+ const seen = new Set();
+ const overrides = [];
+ for (let index = 0; index < inputOverrides.length; index++) {
+ const descriptor = Object.getOwnPropertyDescriptor(inputOverrides, index);
+ if (!descriptor || !Object.hasOwn(descriptor, 'value')) {
+ throw new TypeError('Pose overrides cannot contain holes or accessors.');
+ }
+ const override = descriptor.value;
+ knownPoseFields(override, ['id', 'translation', 'rotation', 'scale'], 'node override');
+ const metadata = metadataById.get(override.id);
+ if (!metadata || seen.has(override.id)) {
+ throw new RangeError('Pose node IDs must exist and be distinct.');
+ }
+ if (!metadata.editable) {
+ throw new RangeError('Authored node poses require a positive TRS base without shear or reflection.');
+ }
+ seen.add(override.id);
+ const result = { id: override.id };
+ for (const field of ['translation', 'rotation', 'scale']) {
+ if (Object.hasOwn(override, field)) {
+ result[field] = poseVector(override[field], field === 'rotation' ? 4 : 3, field);
+ }
+ }
+ if (Object.keys(result).length === 1) {
+ throw new TypeError('A node override needs at least one transform field.');
+ }
+ if (result.rotation) {
+ const length = Math.hypot(...result.rotation);
+ if (!Number.isFinite(length) || length < 1e-8) {
+ throw new RangeError('Pose rotation needs a nonzero quaternion.');
+ }
+ result.rotation = result.rotation.map(value => value / length);
+ }
+ if (result.scale?.some(value => Math.fround(value) <= 0)) {
+ throw new RangeError('Pose scale must be positive at Float32 precision.');
+ }
+ overrides.push(result);
+ }
+ return { animation: animation === null ? null : { ...animation }, overrides };
+ }
+
+ function stagePose(input) {
+ if (disposed) {
+ throw new Error('The glTF asset was disposed.');
+ }
+ if (pendingTransaction) {
+ throw new Error('A pose transaction is already pending. Commit or discard it first.');
+ }
+ const candidate = normalizePose(input);
+ const previousPose = capturePrivatePose();
+ const previousAnimation = currentAnimation;
+ function rollback() {
+ playAnimation(previousAnimation);
+ restorePrivatePose(previousPose);
+ }
+ try {
+ playAnimation(candidate.animation);
+ for (const override of candidate.overrides) {
+ const node = sourceNodes.get(override.id);
+ if (override.translation) {
+ node.position.fromArray(override.translation);
+ }
+ if (override.rotation) {
+ node.quaternion.fromArray(override.rotation);
+ }
+ if (override.scale) {
+ node.scale.fromArray(override.scale);
+ }
+ node.updateMatrix();
+ }
+ preparePose();
+ } catch (error) {
+ rollback();
+ throw error;
+ }
+ let settled = false;
+ function requirePending() {
+ if (disposed) {
+ throw new Error('The glTF asset was disposed.');
+ }
+ if (settled) {
+ throw new Error('The pose transaction is already settled.');
+ }
+ }
+ const transaction = Object.freeze({
+ parts: candidateParts,
+ commit() {
+ requirePending();
+ try {
+ preparePose();
+ } catch (error) {
+ rollback();
+ settled = true;
+ pendingTransaction = null;
+ throw error;
+ }
+ for (const { matrix, pendingMatrix } of bindings) {
+ Float32Array.prototype.set.call(matrix, pendingMatrix);
+ }
+ for (const binding of skinBindings) {
+ commitSkinBinding(binding);
+ }
+ for (const binding of morphBindings) {
+ Float32Array.prototype.set.call(binding.weights, binding.pendingPose.weights);
+ }
+ currentAnimation = candidate.animation;
+ settled = true;
+ pendingTransaction = null;
+ return parts;
+ },
+ discard() {
+ requirePending();
+ rollback();
+ settled = true;
+ pendingTransaction = null;
+ return parts;
+ },
+ });
+ pendingTransaction = transaction;
+ return transaction;
+ }
+
+ function dispose() {
+ if (disposed) {
+ return;
+ }
+ pendingTransaction?.discard();
+ disposed = true;
+ mixer.stopAllAction();
+ mixer.uncacheRoot(gltf.scene);
+ releaseParsed(gltf);
+ objectUrls.forEach(url => URL.revokeObjectURL(url));
+ }
+
+ function applyAnimation(time, clipIndex = 0) {
+ if (disposed) {
+ throw new Error('The glTF asset was disposed.');
+ }
+ if (!Number.isFinite(time)) {
+ throw new TypeError('Animation time must be finite.');
+ }
+ const clip = gltf.animations[clipIndex];
+ if (!Number.isInteger(clipIndex) || !clip) {
+ throw new RangeError('Animation clip index is out of range.');
+ }
+ return stagePose({ animation: { clip: clipIndex, time: Math.max(0, Math.min(time, clip.duration)) } }).commit();
+ }
+ return { parts, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations,
+ get nodes() { return structuredClone(nodeMetadata); }, stagePose, applyAnimation, dispose, capabilities: GLTF_CAPABILITIES };
} catch (error) {
if (gltf) releaseParsed(gltf);
objectUrls.forEach(url => URL.revokeObjectURL(url));
diff --git a/tests/agent-asset-motion.test.js b/tests/agent-asset-motion.test.js
new file mode 100644
index 00000000..07cfa97e
--- /dev/null
+++ b/tests/agent-asset-motion.test.js
@@ -0,0 +1,151 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { parseGltf } from '../src/gltf.js';
+import { createAgentAssetScene } from '../src/agent-asset.js';
+import { skinnedStripAsset } from './fixtures/skinned-strip.js';
+
+const recipe = () => ({ format: '67js.asset', schemaVersion: 1, assetId: 'ac'.repeat(32) });
+const motion = () => ({ duration: 2, tracks: [{ kind: 'node', id: 'node-3', property: 'rotation',
+ keyframes: [{ time: 0, value: [0, 0, 0, 1] }, { time: 2, value: [0, 0, Math.SQRT1_2, Math.SQRT1_2] }] }] });
+const pose = scene => scene.parts.map(part => ({ matrix: [...part.matrix], palette: [...(part.skin?.jointMatrices ?? [])], weights: [...(part.morph?.weights ?? [])] }));
+
+test('imported source-node authoring reaches actual joints with stable hierarchy IDs', async () => {
+ const asset = await parseGltf(skinnedStripAsset());
+ try {
+ const scene = createAgentAssetScene(asset, recipe());
+ const hierarchy = scene.inspect({ kind: 'hierarchy', limit: 2 });
+ assert.equal(hierarchy.counts.joints, 2);
+ assert.equal(hierarchy.truncated, true);
+ const tip = scene.inspect({ kind: 'hierarchy', ids: ['node-3'] }).nodes[0];
+ assert.equal(tip.joint, true);
+ assert.equal(tip.parent, 'node-2');
+ assert.deepEqual(tip.translation, [0, 1, 0]);
+ assert.equal(scene.inspect({ kind: 'hierarchy', offset: 2, limit: 2 }).nodes.length, 2);
+ const previous = pose(scene);
+ const part = scene.parts[0];
+ const palette = part.skin.jointMatrices;
+ assert.equal(scene.apply([{ type: 'set-asset-node', id: 'node-3', rotation: [0, 0, 0.4, 1] }], { expectedRevision: 0 }), 1);
+ assert.notDeepEqual(pose(scene), previous);
+ assert.equal(scene.parts[0], part);
+ assert.equal(part.skin.jointMatrices, palette);
+ tip.translation[1] = 9;
+ assert.deepEqual(scene.inspect({ kind: 'hierarchy', ids: ['node-3'] }).nodes[0].translation, [0, 1, 0]);
+ } finally { asset.dispose(); }
+});
+
+test('authored asset motion is transient and shuffled seeks preserve every retained binding', async () => {
+ const asset = await parseGltf(skinnedStripAsset());
+ try {
+ const scene = createAgentAssetScene(asset, { ...recipe(), motion: motion() });
+ const canonical = scene.exportRecipe();
+ const retained = scene.parts[0];
+ const base = pose(scene);
+ const checkpoint = scene.checkpoint();
+ scene.sampleMotion(1);
+ const middle = pose(scene);
+ assert.notDeepEqual(middle, base);
+ for (const time of [2, 0.25, 0, 1.9, 1]) scene.sampleMotion(time);
+ assert.deepEqual(pose(scene), middle);
+ assert.equal(scene.revision, 0);
+ assert.equal(scene.motionTime, 1);
+ assert.deepEqual(scene.exportRecipe(), canonical);
+ scene.sampleMotion(null);
+ assert.deepEqual(pose(scene), base);
+ scene.apply([{ type: 'set-asset-node', id: 'node-2', translation: [2, 0, 0] }], { expectedRevision: 0 });
+ assert.notDeepEqual(pose(scene), base);
+ scene.restore(checkpoint, { expectedRevision: 1 });
+ assert.deepEqual(pose(scene), base);
+ assert.equal(scene.parts[0], retained);
+ assert.equal(scene.motionTime, 0);
+ } finally { asset.dispose(); }
+});
+
+test('pose layers preserve imported animation while overriding selected local components', async () => {
+ const asset = await parseGltf(skinnedStripAsset());
+ try {
+ const scene = createAgentAssetScene(asset, { ...recipe(), animation: { clip: 1, time: 1 },
+ nodeOverrides: [{ id: 'node-3', translation: [0, 1.25, 0] }], motion: motion() });
+ const importedTranslation = scene.parts[0].skin.jointWorldMatrices[12];
+ scene.sampleMotion(1.5);
+ assert.equal(scene.parts[0].skin.jointWorldMatrices[12], importedTranslation);
+ assert.equal(scene.exportRecipe().animation.time, 1);
+ assert.equal(scene.inspect().motion.time, 1.5);
+ scene.apply([{ type: 'set-animation', clip: null }], { expectedRevision: 0 });
+ assert.notEqual(scene.parts[0].skin.jointWorldMatrices[12], importedTranslation);
+ } finally { asset.dispose(); }
+});
+
+test('invalid authored poses roll back decoder private state and complete adapter state', async () => {
+ const asset = await parseGltf(skinnedStripAsset());
+ try {
+ const scene = createAgentAssetScene(asset, { ...recipe(), motion: motion() });
+ scene.sampleMotion(1);
+ const before = pose(scene);
+ const canonical = scene.exportRecipe();
+ for (const commands of [
+ [{ type: 'set-asset-node', id: 'node-3', scale: [1e-40, 1e-40, 1e-40] }],
+ [{ type: 'set-asset-node', id: 'node-3', rotation: [0, 0, 0, 0] }],
+ [{ type: 'set-asset-node', id: 'mesh-0', translation: [1, 0, 0] }],
+ [{ type: 'set-asset-node', id: 'node-3' }],
+ [{ type: 'set-motion' }],
+ [{ type: 'set-motion', motion: { ...motion(), tracks: [{ ...motion().tracks[0], id: 'missing' }] } }],
+ [{ type: 'set-material', id: 'material-0', color: [1, 0, 0] }, { type: 'set-root', scale: [1e-40, 1e-40, 1e-40] }],
+ ]) {
+ assert.throws(() => scene.apply(commands, { expectedRevision: 0 }));
+ assert.deepEqual(pose(scene), before);
+ assert.deepEqual(scene.exportRecipe(), canonical);
+ assert.equal(scene.motionTime, 1);
+ }
+ scene.sampleMotion(0.3);
+ scene.sampleMotion(1);
+ assert.deepEqual(pose(scene), before);
+ assert.equal(scene.revision, 0);
+ } finally { asset.dispose(); }
+});
+
+test('material and camera tracks share authored timing while texture resources remain retained', async () => {
+ const asset = await parseGltf(skinnedStripAsset());
+ const descriptor = { data: new Uint8Array([20, 30, 40, 255]), width: 1, height: 1 };
+ asset.parts[0].material.map = descriptor;
+ try {
+ const scene = createAgentAssetScene(asset, { ...recipe(), motion: { duration: 2, tracks: [
+ { kind: 'material', id: 'material-0', property: 'roughness', keyframes: [{ time: 0, value: 0.2 }, { time: 2, value: 0.8 }] },
+ { kind: 'camera', property: 'eye', keyframes: [{ time: 0, value: [4, 3, 5] }, { time: 2, value: [5, 4, 6] }] },
+ ] } });
+ const base = scene.camera;
+ scene.sampleMotion(1);
+ assert.ok(Math.abs(scene.parts[0].material.roughness - 0.5) < 1e-6);
+ assert.deepEqual(scene.camera.eye, [4.5, 3.5, 5.5]);
+ assert.notDeepEqual(scene.camera, base);
+ assert.equal(scene.parts[0].material.map, descriptor);
+ scene.apply([{ type: 'set-motion', motion: null }], { expectedRevision: 0 });
+ assert.equal(scene.motionTime, null);
+ assert.throws(() => scene.sampleMotion(1), /no authored motion/);
+ scene.sampleMotion(null);
+ } finally { asset.dispose(); }
+});
+
+test('independent imported and authored clocks stage once without an invalid intermediate pose', async () => {
+ const asset = await parseGltf(skinnedStripAsset((document, append, chunks) => {
+ const accessor = document.animations[0].samplers[0].output;
+ const bufferView = document.accessors[accessor].bufferView;
+ chunks[bufferView].set([0, 0, 1, 0], 4);
+ }));
+ try {
+ const scene = createAgentAssetScene(asset, { ...recipe(), motion: { duration: 2, tracks: [{
+ kind: 'node', id: 'node-3', property: 'scale', keyframes: [
+ { time: 0, value: [1, 1, 1] }, { time: 2, value: [2, 2, 2] },
+ ],
+ }] } });
+ const canonical = scene.exportRecipe();
+ scene.sampleFrame({ animation: { clip: 0, time: 2 }, motionTime: 2 });
+ const final = pose(scene);
+ assert.equal(scene.revision, 0);
+ assert.deepEqual(scene.exportRecipe(), canonical);
+ assert.throws(() => scene.sampleFrame({ animation: { clip: 0, time: 2 }, motionTime: 0 }), /singular weighted/);
+ assert.deepEqual(pose(scene), final);
+ scene.sampleFrame({ animation: null, motionTime: 0 });
+ scene.sampleFrame({ animation: { clip: 0, time: 2 }, motionTime: 2 });
+ assert.deepEqual(pose(scene), final);
+ } finally { asset.dispose(); }
+});
diff --git a/tests/agent-render-jobs.test.js b/tests/agent-render-jobs.test.js
index cd9bf9ed..44228d4c 100644
--- a/tests/agent-render-jobs.test.js
+++ b/tests/agent-render-jobs.test.js
@@ -56,11 +56,20 @@ test('motion job ranges use immutable recipe duration, loops and actual sample t
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 assert.rejects(controller.submit(input), /Asset snapshot bytes/);
+ const assetBytes = Buffer.from('owned motion asset bytes');
+ input.snapshot.assetBytes = assetBytes;
+ input.snapshot.recipe.assetId = createHash('sha256').update(assetBytes).digest('hex');
+ input.settings = { kind: 'image', width: 64, height: 64, motion: { start: 0.5 } };
+ const assetSubmitted = await controller.submit(input);
+ assert.equal((await terminal(controller, assetSubmitted.jobId)).state, 'completed');
+ assert.equal(controller.status(assetSubmitted.jobId).settings.motion.start, 0.5);
await controller.close();
const reopened = await createAgentRenderJobs({ root, limits, run: writeImage });
assert.equal(reopened.status(submitted.jobId).settings.motion.start, 1);
+ assert.equal(reopened.status(assetSubmitted.jobId).settings.motion.start, 0.5);
await reopened.release(submitted.jobId);
+ await reopened.release(assetSubmitted.jobId);
await reopened.close();
});
diff --git a/tests/gltf-node-pose.test.js b/tests/gltf-node-pose.test.js
new file mode 100644
index 00000000..a0f0cd05
--- /dev/null
+++ b/tests/gltf-node-pose.test.js
@@ -0,0 +1,209 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { constants, setPriority } from 'node:os';
+import { Matrix4, Vector3 } from 'three';
+import { parseGltf } from '../src/gltf.js';
+import { skinnedStripAsset } from './fixtures/skinned-strip.js';
+import { createTexturedRigFixture } from '../scripts/agent-asset-fixture.mjs';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+
+function snapshot(parts) {
+ return parts.map(part => ({ matrix: [...part.matrix],
+ palette: [...part.skin?.jointMatrices ?? []], world: [...part.skin?.jointWorldMatrices ?? []],
+ weights: [...part.morph?.weights ?? []] }));
+}
+
+function skinnedPosition(part, vertex) {
+ const position = new Vector3().fromArray(part.geometry.positions, vertex * 3);
+ const output = new Vector3();
+ let total = 0;
+ for (let influence = 0; influence < 4; influence++) {
+ total += part.geometry.skinWeights[vertex * 4 + influence];
+ }
+ for (let influence = 0; influence < 4; influence++) {
+ const offset = vertex * 4 + influence;
+ const matrix = new Matrix4().fromArray(part.skin.jointMatrices, part.geometry.skinIndices[offset] * 16);
+ output.addScaledVector(position.clone().applyMatrix4(matrix), part.geometry.skinWeights[offset] / total);
+ }
+ return output.applyMatrix4(new Matrix4().fromArray(part.matrix));
+}
+
+test('source hierarchy metadata is detached and staged joint deformation leaves published resources unchanged', async () => {
+ const asset = await parseGltf(skinnedStripAsset());
+ const metadata = asset.nodes;
+ assert.deepEqual(metadata.map(node => node.id), ['node-0', 'node-1', 'node-2', 'node-3']);
+ assert.equal(metadata.find(node => node.id === 'node-3').parent, 'node-2');
+ assert.equal(metadata.find(node => node.id === 'node-3').joint, true);
+ assert.deepEqual(metadata.find(node => node.id === 'node-1').meshIds, ['mesh-0']);
+ metadata[0].translation[0] = 99;
+ assert.equal(asset.nodes[0].translation[0], 1);
+ const part = asset.parts[0];
+ const before = snapshot(asset.parts);
+ const originalVertex = skinnedPosition(part, 5);
+ const palette = part.skin.jointMatrices;
+ const transaction = asset.stagePose({ animation: null, nodeOverrides: [
+ { id: 'node-3', rotation: [0, 0, Math.SQRT1_2, Math.SQRT1_2] },
+ ] });
+ assert.deepEqual(snapshot(asset.parts), before);
+ assert.notEqual(transaction.parts[0].matrix, part.matrix);
+ assert.ok(skinnedPosition(transaction.parts[0], 5).distanceTo(originalVertex) > 0.5);
+ assert.equal(transaction.parts[0].geometry, part.geometry);
+ assert.equal(transaction.parts[0].material, part.material);
+ transaction.commit();
+ assert.equal(part.skin.jointMatrices, palette);
+ assert.ok(skinnedPosition(part, 5).distanceTo(originalVertex) > 0.5);
+ asset.stagePose({ animation: null }).commit();
+ assert.deepEqual(snapshot(asset.parts), before);
+ asset.dispose();
+});
+
+test('discard and failed poses restore private clip state for independent backward seeks', async () => {
+ const asset = await parseGltf(skinnedStripAsset());
+ asset.applyAnimation(0.75);
+ const expected = snapshot(asset.parts);
+ const transaction = asset.stagePose({ animation: { clip: 0, time: 1.5 }, nodeOverrides: [
+ { id: 'node-0', translation: [8, 2, 0] },
+ ] });
+ assert.throws(() => asset.stagePose({ animation: null }), /pending/);
+ transaction.discard();
+ assert.deepEqual(snapshot(asset.parts), expected);
+ assert.throws(() => transaction.commit(), /settled/);
+ assert.throws(() => asset.stagePose({ animation: null, nodeOverrides: [
+ { id: 'node-3', rotation: [0, 0, 1, 0] },
+ ] }), /singular/);
+ assert.deepEqual(snapshot(asset.parts), expected);
+ assert.throws(() => asset.stagePose({ animation: null, nodeOverrides: [
+ { id: 'node-0', scale: [3e38, 3e38, 3e38] },
+ ] }), /finite|singular/);
+ assert.deepEqual(snapshot(asset.parts), expected);
+ for (const time of [1.5, 0, 1.25, 0.75]) asset.applyAnimation(time);
+ assert.deepEqual(snapshot(asset.parts), expected);
+ asset.dispose();
+});
+
+test('strict pose boundaries reject malformed fields, identifiers, scale and quaternions without changing state', async () => {
+ const asset = await parseGltf(skinnedStripAsset());
+ const expected = snapshot(asset.parts);
+ for (const input of [
+ { unknown: true }, { animation: { clip: 99, time: 0 } }, { animation: { clip: 0, time: -1 } },
+ { nodeOverrides: [{ id: 'missing', translation: [0, 0, 0] }] },
+ { nodeOverrides: [{ id: 'node-3', matrix: [] }] },
+ { nodeOverrides: [{ id: 'node-3' }] },
+ { nodeOverrides: [{ id: 'node-3', rotation: [0, 0, 0, 0] }] },
+ { nodeOverrides: [{ id: 'node-3', scale: [1, 0, 1] }] },
+ { nodeOverrides: [{ id: 'node-3', translation: [Infinity, 0, 0] }] },
+ { nodeOverrides: [{ id: 'node-3', translation: [0, 0, 0] }, { id: 'node-3', scale: [1, 1, 1] }] },
+ { nodeOverrides: Array(2) },
+ { nodeOverrides: Array.from({ length: 257 }, () => ({ id: 'node-3', scale: [1, 1, 1] })) },
+ ]) {
+ assert.throws(() => asset.stagePose(input));
+ assert.deepEqual(snapshot(asset.parts), expected);
+ }
+ let accessed = false;
+ const input = {};
+ Object.defineProperty(input, 'animation', { enumerable: true, get() { accessed = true; return null; } });
+ assert.throws(() => asset.stagePose(input), /unsupported/);
+ assert.equal(accessed, false);
+ const pending = asset.stagePose({ animation: null });
+ asset.dispose();
+ assert.throws(() => pending.commit(), /disposed/);
+ assert.throws(() => asset.stagePose({ animation: null }), /disposed/);
+});
+
+test('shared scene clones and grouped primitives keep source node IDs distinct from traversal mesh IDs', async () => {
+ const asset = await parseGltf(skinnedStripAsset(document => {
+ delete document.nodes[1].skin;
+ delete document.meshes[0].primitives[0].attributes.JOINTS_0;
+ delete document.meshes[0].primitives[0].attributes.WEIGHTS_0;
+ document.scenes = [{ nodes: [0] }, { nodes: [0] }];
+ document.scene = 1;
+ document.meshes[0].primitives.push(structuredClone(document.meshes[0].primitives[0]));
+ }));
+ assert.equal(asset.parts.length, 2);
+ assert.deepEqual(asset.nodes.find(node => node.id === 'node-1').meshIds, ['mesh-0', 'mesh-1']);
+ assert.equal(new Set(asset.nodes.map(node => node.id)).size, asset.nodes.length);
+ asset.stagePose({ nodeOverrides: [{ id: 'node-1', translation: [2, 0, 0] }] }).commit();
+ assert.equal(asset.parts[0].matrix[12], 3);
+ assert.equal(asset.parts[1].matrix[12], 3);
+ asset.dispose();
+});
+
+test('selected cloned scenes bind authored joint edits to their actual skin skeleton', async () => {
+ for (const scene of [0, 1]) {
+ const asset = await parseGltf(skinnedStripAsset(document => {
+ document.scenes = [{ nodes: [0] }, { nodes: [0] }];
+ document.scene = scene;
+ }));
+ assert.equal(asset.nodes.find(node => node.id === 'node-3').joint, true);
+ const original = skinnedPosition(asset.parts[0], 5);
+ asset.stagePose({ nodeOverrides: [{ id: 'node-3', rotation: [0, 0, Math.SQRT1_2, Math.SQRT1_2] }] }).commit();
+ assert.ok(skinnedPosition(asset.parts[0], 5).distanceTo(original) > 0.5);
+ asset.dispose();
+ }
+});
+
+test('reflected and sheared source nodes remain uneditable while decoded base poses remain usable', async () => {
+ for (const matrix of [
+ [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0.5, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
+ ]) {
+ const asset = await parseGltf(skinnedStripAsset(document => {
+ delete document.nodes[1].skin;
+ delete document.meshes[0].primitives[0].attributes.JOINTS_0;
+ delete document.meshes[0].primitives[0].attributes.WEIGHTS_0;
+ document.nodes[1].matrix = matrix;
+ }));
+ assert.equal(asset.nodes.find(node => node.id === 'node-1').editable, false);
+ const expected = snapshot(asset.parts);
+ assert.throws(() => asset.stagePose({ nodeOverrides: [{ id: 'node-1', translation: [1, 0, 0] }] }), /TRS/);
+ asset.stagePose({ animation: null }).commit();
+ assert.deepEqual(snapshot(asset.parts), expected);
+ asset.dispose();
+ }
+});
+
+test('skin and morph candidates retain palettes and weights through authored poses', async () => {
+ const asset = await parseGltf(skinnedStripAsset((document, append) => {
+ const positions = append(new Float32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.25, 0, 0, 0.25, 0]), 'VEC3');
+ Object.assign(document.accessors[positions], { min: [0, 0, 0], max: [0, 0.25, 0] });
+ document.meshes[0].primitives[0].targets = [{ POSITION: positions }];
+ document.nodes[1].weights = [0.5];
+ }));
+ const part = asset.parts[0];
+ const weights = part.morph.weights;
+ const palette = part.skin.jointMatrices;
+ const transaction = asset.stagePose({ animation: { clip: 0, time: 0.5 }, nodeOverrides: [{ id: 'node-3', translation: [0.25, 1, 0] }] });
+ const candidate = transaction.parts[0];
+ transaction.commit();
+ const next = asset.stagePose({ animation: null });
+ assert.equal(next.parts[0].skin.jointMatrices, candidate.skin.jointMatrices);
+ assert.equal(next.parts[0].morph.weights, candidate.morph.weights);
+ next.commit();
+ assert.equal(part.morph.weights, weights);
+ assert.equal(part.skin.jointMatrices, palette);
+ assert.deepEqual([...weights], [0.5]);
+ asset.dispose();
+});
+
+test('textured rig parsing preserves texture descriptors across staged poses', async context => {
+ const previousSelf = globalThis.self;
+ const previousBitmap = globalThis.createImageBitmap;
+ globalThis.self = globalThis;
+ globalThis.createImageBitmap = async () => ({ width: 2, height: 2, close() {} });
+ context.after(() => {
+ if (previousSelf === undefined) delete globalThis.self;
+ else globalThis.self = previousSelf;
+ if (previousBitmap === undefined) delete globalThis.createImageBitmap;
+ else globalThis.createImageBitmap = previousBitmap;
+ });
+ const bytes = await createTexturedRigFixture();
+ const asset = await parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
+ const map = asset.parts[0].material.map;
+ assert.ok(map);
+ const transaction = asset.stagePose({ nodeOverrides: [{ id: 'node-3', translation: [0.1, 1, 0] }] });
+ assert.equal(transaction.parts[0].material.map, map);
+ transaction.commit();
+ assert.equal(asset.parts[0].material.map, map);
+ asset.dispose();
+});