3D engine that AI agents drive
Make skeleton pose work on real characters
Nguyen Xuan Anbdc1151c5b87
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e3fe77c0..56fa7c9c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## Unreleased++- Add `createAssetPose`, which poses a loaded glTF asset's whole hierarchy so every skin and rigid part moves, and `clipFromGltfAnimation`, which converts its clips for layers and `retargetClip`+- Add `worldForward` to aim IK, because bone axes differ between real rigs+- Accept skin weights one unit of Float32 rounding above 1, which exporters write and which made such files fail to load+## 0.13.0- Add `motion.ik` to procedural recipes: two-bone and aim solvers on node hierarchies, with fixed, keyframed or node-following targets, so agents can animate jointed models without writing quaternions; `scene_inspect` reports whether each solver reaches its target across the clipdiff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex fdde476f..2b80d3b5 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -85,6 +85,10 @@ their complete license and notice texts, including dependencies embedded in thePinned upstream license copies for embedded dependencies are retained in `licenses/mcp/` in the source repository.The external `playwright-core` browser driver includes its own license and notices in its dependency package.+## RobotExpressive (test fixture, not in the npm package)++`tests/fixtures/RobotExpressive.glb` is by Tomás Laulhé, with modifications by Don McCurdy, from the three.js examples, under CC0-1.0.+## Simple Icons (package-manager logos)The npm, pnpm, Yarn and Bun SVG marks are sourced from Simple Icons and distributed under CC0-1.0. See public/licenses/simple-icons.txt. Brand marks remain subject to their respective trademark rights.diff --git a/docs/retarget.md b/docs/retarget.mdindex 037eda8d..4423cdd0 100644--- a/docs/retarget.md+++ b/docs/retarget.md@@ -10,7 +10,8 @@ import { mapHumanoidBones, createRigFromSkin, retargetClip, createSkinClipPlayerconst source = createRigFromSkin(mixamoAsset.skins[0]);const target = createRigFromSkin(characterAsset.skins[0], { rootMatrix: armatureWorldMatrix });-const clip = retargetClip(source, target, mixamoClip, { rootMotion: false });+// asset.animations holds three.js clips; convert them first with clipFromGltfAnimation from 67js/addons/skeleton-pose.+const clip = retargetClip(source, target, clipFromGltfAnimation(mixamoAsset.animations[0]), { rootMotion: false });const player = createSkinClipPlayer(characterAsset.skins[0], clip);player.apply(seconds);diff --git a/docs/skeleton-pose.md b/docs/skeleton-pose.mdindex 4ef3fde9..5e5ddf5b 100644--- a/docs/skeleton-pose.md+++ b/docs/skeleton-pose.md@@ -4,18 +4,21 @@wave while walking, add breathing on top of any clip, keep feet on uneven ground, reach for an object or look at a point.```js-import { createSkeletonPose } from '67js/addons/skeleton-pose';+import { loadGltf } from '67js/addons/gltf';+import { clipFromGltfAnimation, createAssetPose } from '67js/addons/skeleton-pose';-const pose = createSkeletonPose({- skin: character.skins[0],+const character = await loadGltf(url);+const clip = name => clipFromGltfAnimation(character.animations.find(animation => animation.name === name), { loop: true });++const pose = createAssetPose(character, {layers: [- { clip: walk },- { clip: wave, mask: { joints: ['rightUpperArm'] } },- { clip: breathe, additive: true },+ { clip: clip('Walk') },+ { clip: clip('Wave'), mask: { joints: ['rightShoulder'] } },+ { clip: clip('Breathe'), additive: true },],ik: [- { type: 'two-bone', root: 'leftUpperLeg', middle: 'leftLowerLeg', end: 'leftFoot', pole: [0, 1, 2], target: (time, foot) => [foot[0], terrain.heightAt(foot[0], foot[2]), foot[2]] },- { type: 'aim', joints: ['spine', 'head'], forward: [0, 0, 1], maxAngle: 60, target: [2, 1.6, 3] },+ { type: 'two-bone', root: 'leftUpperLeg', middle: 'leftLowerLeg', end: 'leftFoot', target: (time, foot) => [foot[0], terrain.heightAt(foot[0], foot[2]) + ankleHeight, foot[2]] },+ { type: 'aim', joints: ['spine', 'neck', 'head'], worldForward: [0, 0, 1], maxAngle: 60, target: [2, 1.6, 3] },],});@@ -29,12 +32,21 @@ depend only on their arguments.## Setup-`createSkeletonPose({ skin, rig, meshWorldMatrix, layers, ik })` takes a `skin` to write its joint palette, or only a-`rig` to read joint positions. `rig` defaults to `createRigFromSkin(skin)` from `67js/addons/retarget`; pass one with-`rootMatrix` when a scaled node sits above the root joints.+Use `createAssetPose(asset, { layers, ik })` for a loaded glTF asset. It solves on the asset's whole node hierarchy and+writes through its pose transaction, so every skin moves, and so does every rigid part attached to a bone. Many characters+are built that way, or have several skins. Targets are in the asset's world space, including any scaled or rotated+armature above the bones.++`clipFromGltfAnimation(asset.animations[n], { loop })` converts a clip from the file. `asset.animations` holds three.js+clips, which layers and `retargetClip` cannot read directly. Morph weight tracks are skipped.++`createSkeletonPose({ skin, rig, meshWorldMatrix, layers, ik })` is the lower level: it writes one skin's palette, or with+only a `rig` just computes joint positions. `rig` defaults to `createRigFromSkin(skin)` from `67js/addons/retarget`; pass+one with `rootMatrix` when a scaled node sits above the root joints.-Anywhere a joint is named you can use the rig's joint name or a humanoid bone name such as `leftUpperArm`-(see [retargeting](retarget.md)), so a setup can move between rigs.+Anywhere a joint is named you can use the joint name or a humanoid bone name such as `leftUpperArm`+(see [retargeting](retarget.md)), so a setup can move between rigs. An asset's joint names are its decoded node names, in+`asset.nodes[n].name`: the loader removes characters such as dots, so `Foot.L` in the file is `FootL` here.## Layers@@ -74,7 +86,8 @@ perfectly straight limb has no defined bend for the next frame.| Field | Meaning || --- | --- || `joint` or `joints` | One joint, or a chain listed from its base to the aiming joint. A chain shares the turn evenly |-| `forward` | The aiming joint's local axis that should point at the target (default `[0, 0, 1]`). Check this per rig: it depends on the bone axes |+| `worldForward` | The world direction the character faces in its rest pose, such as `[0, 0, 1]`. Use this on real rigs, where bone axes differ |+| `forward` | Instead of `worldForward`: the aiming joint's local axis to point at the target (default `[0, 0, 1]`) || `target` | World position, or `(time, jointPosition) => position` || `maxAngle` | Degrees (default 180). Limits the whole turn; past it the joint stops at the limit || `weight` | 0 to 1 (default 1), or a function of time |@@ -87,13 +100,24 @@ The turn is the shortest rotation, so `aim` does not hold an up direction and cachaining targets. `pose.ikResults` holds one `{ reached, error }` per solver: `error` is metres from the target fortwo-bone and radians off target for aim.+## Rigs seen so far++Checked on two real characters. RobotExpressive (rigid parts on bones, four skinned hands, an armature scaled by 100) ran+walk, wave masked to one arm, an additive nod, arm reach and head aim; its clip playback matches the decoder's own within+5e-4, and `tests/skeleton-pose-asset.test.js` runs on it. A Mixamo-style skinned soldier ran walk, feet held on a slope, and+a three-joint aim, by eye only.++Some rigs do not have a limb chain ending at the foot. RobotExpressive's feet are Blender IK controllers, children of the+root rather than of the lower leg, so two-bone IK refuses them with an error; its arms work.+## Limits+- A foot or hand held by IK keeps its rotation from the clip, so a foot on a slope does not tilt to match the ground.- Uniform scale only, as in the [retargeting](retarget.md) rig. Clip scale tracks are ignored.- No joint angle limits. A pole keeps a knee on the right side, but nothing stops a target from bending it too far.- No full-body solve: moving a hand does not move the hips. Solvers run one at a time, so order them from the base of thebody outward.-- Clip layers and masks are code only. Procedural recipes get IK through [`motion.ik`](agent-motion.md#inverse-kinematics);+- Clip layers and masks are code only, and MCP has no IK for imported assets yet. Procedural recipes get IK through [`motion.ik`](agent-motion.md#inverse-kinematics);imported assets through MCP still author joints by rotation tracks, as in [imported character motion](agent-character-motion.md).- The [animation mixer](animation-mixer.md) works on rigid part transforms and has no layers, masks or IK. Use this addonfor skinned rigs.diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex a2f5ccf6..f7276373 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -38,7 +38,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`. Verify source versus published availability before importing.- Polygon modeling by an agent (extrude, inset, loop cut, bevel, booleans, mirror, array, solidify) uses the recipe `mesh` geometry and the MCP tools `mesh_inspect`, `mesh_edit` and `mesh_stack`. Read [mesh-modeling.md](references/mesh-modeling.md) before the first edit; check that the checkout's `docs/mesh.md` exists, since it is unreleased after npm 0.10.0.- A surface look in a recipe (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric) uses the material `pattern` field, which needs no UVs. See "Material patterns" in the checkout's `docs/agent-scene.md`.-- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. Clip layers are not available through MCP.+- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `createAssetPose` from `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. Clip layers are not available through MCP.- Jointed recipe motion (an arm reaching, a lamp or head tracking a point) uses `motion.ik`, which needs no quaternions: parent the joint nodes, put sizes on child mesh nodes, and read `motionIk` from `scene_inspect`. See "Inverse kinematics" in the checkout's `docs/agent-motion.md`.- 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.diff --git a/src/gltf.js b/src/gltf.jsindex bc064f1c..d75ad5cc 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -1011,7 +1011,8 @@ export async function parseGltf(data, options = {}) {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,+ // `name` is the decoded node name, which clip tracks address; `label` is the name as authored in the file.+ return { id, label: String(original.name ?? id).slice(0, 256), name: node.name, parent: sourceIds.get(parent) ?? null,translation: node.position.toArray(), rotation: node.quaternion.toArray(), scale: node.scale.toArray(),editable, joint: jointNodes.has(node), meshIds };});diff --git a/src/skeleton-pose.js b/src/skeleton-pose.jsindex 91cd5d06..aaf91e87 100644--- a/src/skeleton-pose.js+++ b/src/skeleton-pose.js@@ -1,5 +1,5 @@import { mat4, quat, vec3 } from 'gl-matrix';-import { compileAnimationSampler } from './animation.js';+import { compileAnimationSampler, createAnimationClip } from './animation.js';import { updateSkinPose } from './skinning.js';import {bindSourceTracks, computeWorldPose, createPoseState, createRigFromSkin, mapHumanoidBones, prepareRigGeometry, validateRigJoints,@@ -167,7 +167,13 @@ function createSolver(definition, position, prepared, resolveJoint) {joints.slice(1).forEach((joint, slot) => {if (!isDescendant(prepared, joint, joints[slot])) throw new RangeError(`${label}: list joints from the base of the chain to the aiming joint.`);});- const forward = vec3.normalize(new Float64Array(3), checkedVector(definition.forward ?? [0, 0, 1], `${label} forward`));+ if (definition.forward !== undefined && definition.worldForward !== undefined) throw new TypeError(`${label} takes forward or worldForward, not both.`);+ const forward = vec3.normalize(new Float64Array(3), checkedVector(definition.forward ?? definition.worldForward ?? [0, 0, 1], `${label} forward`));+ if (definition.worldForward !== undefined) {+ // Bone axes differ by rig, but which way a character faces at rest does not: bring that direction into the joint.+ const restRotation = prepared.restWorld.rotations[joints[joints.length - 1]];+ vec3.transformQuat(forward, forward, quat.invert(new Float64Array(4), restRotation));+ }const maxAngle = definition.maxAngle ?? 180;if (!Number.isFinite(maxAngle) || maxAngle <= 0) throw new RangeError(`${label} maxAngle must be a positive number of degrees.`);return { type: 'aim', label, weight, joints, forward, maxRadians: maxAngle * TO_RADIANS, target: definition.target };@@ -285,11 +291,112 @@ function solveAim(solver, time, context) {const finalForward = forwardNow();const direct = vec3.subtract(new Float64Array(3), target, state.positions[aiming]);const error = vec3.angle(finalForward, direct);- return { reached: error < 1e-3, error };+ // A chain's own joints move as it turns, so about a degree is as close as one pass gets.+ return { reached: error < 0.02, error };}const SOLVERS = { 'two-bone': solveTwoBone, aim: solveAim };+const GLTF_TRACK_PROPERTIES = { position: 'translation', quaternion: 'rotation', scale: 'scale' };+const GLTF_STEP_INTERPOLATION = 2300;+const GLTF_LINEAR_INTERPOLATION = 2301;+const RESAMPLE_RATE = 30;++function trackKeyframes(track, size) {+ const interpolation = track.getInterpolation?.();+ if (interpolation === GLTF_LINEAR_INTERPOLATION || interpolation === GLTF_STEP_INTERPOLATION) {+ return Array.from(track.times, (time, index) => ({ time, value: Array.from(track.values.subarray(index * size, (index + 1) * size)) }));+ }+ // Cubic glTF tracks store tangents in their values; sample them instead of carrying a second tangent convention.+ const interpolant = track.createInterpolant(new Float64Array(size));+ const start = track.times[0];+ const end = track.times[track.times.length - 1];+ const steps = Math.max(1, Math.ceil((end - start) * RESAMPLE_RATE));+ return Array.from({ length: steps + 1 }, (_, step) => {+ const time = start + (end - start) * step / steps;+ return { time, value: Array.from(interpolant.evaluate(time)) };+ });+}++/**+ * Convert an animation from a loaded glTF asset (`asset.animations[n]`) into a clip layers and retargetClip can use.+ * Node tracks keep their decoded node names. Morph weight tracks are skipped. Step keys stay step; cubic keys are+ * resampled at 30 frames per second.+ */+export function clipFromGltfAnimation(animation, { loop = false } = {}) {+ if (!Array.isArray(animation?.tracks) || !Number.isFinite(animation.duration)) throw new TypeError('clipFromGltfAnimation needs an animation from asset.animations.');+ const tracks = [];+ for (const track of animation.tracks) {+ const separator = track.name.lastIndexOf('.');+ const property = GLTF_TRACK_PROPERTIES[track.name.slice(separator + 1)];+ if (!property || !track.times.length) continue;+ const size = property === 'rotation' ? 4 : 3;+ tracks.push({+ target: track.name.slice(0, separator), property,+ interpolation: track.getInterpolation?.() === GLTF_STEP_INTERPOLATION ? 'STEP' : 'LINEAR',+ keyframes: trackKeyframes(track, size),+ });+ }+ return createAnimationClip({ duration: Math.max(animation.duration, 1e-3), loop, tracks });+}++function rigFromAssetNodes(nodes) {+ const indexById = new Map(nodes.map((node, index) => [node.id, index]));+ const jointNames = nodes.filter(node => node.joint).map(node => node.name);+ return {+ mapping: mapHumanoidBones(jointNames).mapping,+ joints: nodes.map(node => ({+ name: node.name,+ parent: node.parent === null ? -1 : indexById.get(node.parent),+ translation: node.translation, rotation: node.rotation, scale: node.scale,+ })),+ };+}++function checkAssetIkScales(rig, solvedNames) {+ const indexByName = new Map(rig.joints.map((joint, index) => [joint.name, index]));+ for (const name of solvedNames) {+ let current = rig.joints[indexByName.get(name)]?.parent ?? -1;+ while (current >= 0) {+ const joint = rig.joints[current];+ const [first, second, third] = joint.scale;+ if (Math.max(first, second, third) - Math.min(first, second, third) > 1e-3 * Math.max(first, second, third)) {+ throw new RangeError(`IK: node ${joint.name} above ${name} has non-uniform scale ${JSON.stringify(joint.scale)}, which IK cannot solve through.`);+ }+ current = joint.parent;+ }+ }+}++/**+ * Pose a loaded glTF asset from { layers, ik }. Unlike a skin palette this moves every skin and every rigid part attached+ * to the hierarchy, and IK targets are in the asset's world space. Joints are named by decoded node name or humanoid bone.+ * `apply(time)` commits the pose and returns `asset.parts`; pass them to `renderer.updateParts`.+ */+export function createAssetPose(asset, { layers = [], ik = [] } = {}) {+ if (typeof asset?.stagePose !== 'function' || !Array.isArray(asset.nodes)) throw new TypeError('createAssetPose needs an asset from loadGltf or parseGltf.');+ const { nodes } = asset;+ const rig = rigFromAssetNodes(nodes);+ const pose = createSkeletonPose({ rig, layers, ik });+ checkAssetIkScales(rig, pose.solvedJointNames);+ const written = pose.writtenJoints.filter(({ index }) => nodes[index].editable);+ return {+ apply(time) {+ pose.apply(time);+ const nodeOverrides = written.map(({ index, translation }) => {+ const override = { id: nodes[index].id, rotation: Array.from(pose.localRotation(index)) };+ if (translation) override.translation = Array.from(pose.localTranslation(index));+ return override;+ });+ return asset.stagePose({ animation: null, nodeOverrides }).commit();+ },+ jointWorld: pose.jointWorld,+ get ikResults() {+ return pose.ikResults;+ },+ };+}+/*** Build a pose evaluator from { skin, rig, meshWorldMatrix, layers, ik }. Give `skin` to write its joint palette, or only* `rig` to read joint positions. Layers run in order: each blends its clip over the pose so far, or adds its change from@@ -303,6 +410,9 @@ export function createSkeletonPose({ skin, rig = skin && createRigFromSkin(skin)const resolveJoint = jointResolver(rig, prepared);const compiledLayers = layers.map((layer, position) => createLayer(layer, position, prepared, resolveJoint));const solvers = ik.map((solver, position) => createSolver(solver, position, prepared, resolveJoint));+ const solvedIndices = new Set(solvers.flatMap(solver => (solver.type === 'aim' ? solver.joints : [solver.root, solver.middle, solver.end])));+ const translatedIndices = new Set(compiledLayers.flatMap(layer => layer.bindings.filter(binding => binding.property === 'translation').map(binding => binding.index)));+ const writtenIndices = new Set([...solvedIndices, ...translatedIndices, ...compiledLayers.flatMap(layer => layer.bindings.filter(binding => binding.property === 'rotation').map(binding => binding.index))]);const jointCount = rig.joints.length;const localRotations = prepared.restRotations.map(rotation => Float64Array.from(rotation));const localTranslations = prepared.restTranslations.map(translation => Float64Array.from(translation));@@ -354,6 +464,14 @@ export function createSkeletonPose({ skin, rig = skin && createRigFromSkin(skin)localRotation(index) {return localRotations[index];},+ /** Local translation of a joint by rig index after the last apply. The array is reused by the next apply. */+ localTranslation(index) {+ return localTranslations[index];+ },+ /** Rig indices a layer or solver can change, and whether their translation can change too. */+ writtenJoints: [...writtenIndices].map(index => ({ index, translation: translatedIndices.has(index) })),+ /** Names of the joints IK solvers move. */+ solvedJointNames: [...solvedIndices].map(index => rig.joints[index].name),/** One { reached, error } per IK solver from the last apply: metres for two-bone, radians for aim. */get ikResults() {return results;diff --git a/src/skinning.js b/src/skinning.jsindex 8f6ae6a7..de5d1d80 100644--- a/src/skinning.js+++ b/src/skinning.js@@ -2,6 +2,7 @@ import { mat4 } from 'gl-matrix';const poseWorkspaces = new WeakMap();const IDENTITY_MATRIX = mat4.create();+const MAX_SKIN_WEIGHT = 1.000001;function finiteFloat(value) {return Number.isFinite(value) && Number.isFinite(Math.fround(value));@@ -98,7 +99,8 @@ export function validateSkinGeometry(geometry, pose) {const joint = geometry.skinIndices[offset];const weight = geometry.skinWeights[offset];if (!Number.isInteger(joint) || joint < 0 || joint >= jointCount) throw new Error('Skin joint index is out of range.');- if (!finiteFloat(weight) || weight < 0 || weight > 1) throw new Error('Skin weights must be finite values within zero and one.');+ // Exporters write a full weight as the next Float32 above one, so one unit of rounding must pass.+ if (!finiteFloat(weight) || weight < 0 || weight > MAX_SKIN_WEIGHT) throw new Error('Skin weights must be finite values within zero and one.');total += weight;}if (total <= 1e-8) throw new Error('Skin vertex weights must have a positive total.');diff --git a/tests/fixtures/RobotExpressive.glb b/tests/fixtures/RobotExpressive.glbnew file mode 100644index 00000000..6fec9cfbBinary files /dev/null and b/tests/fixtures/RobotExpressive.glb differdiff --git a/tests/skeleton-pose-asset.test.js b/tests/skeleton-pose-asset.test.jsnew file mode 100644index 00000000..afabf4b1--- /dev/null+++ b/tests/skeleton-pose-asset.test.js@@ -0,0 +1,127 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { quat, vec3 } from 'gl-matrix';+import { parseGltf } from '../src/gltf.js';+import { validateSkinGeometry, createSkinPose } from '../src/skinning.js';+import { clipFromGltfAnimation, createAssetPose } from '../src/skeleton-pose.js';++// A real character: CC0 RobotExpressive by Tomás Laulhé, with modifications by Don McCurdy. Most of it is rigid parts+// attached to bones, with four skinned hand meshes, under an armature scaled by 100 and rotated by -90 degrees.+const bytes = readFileSync(new URL('./fixtures/RobotExpressive.glb', import.meta.url));++function loadRobot() {+ return parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), { maxVertices: 500000 });+}++function clipNamed(asset, name) {+ return clipFromGltfAnimation(asset.animations.find(animation => animation.name === name), { loop: true });+}++function partMatrix(asset, name) {+ return Array.from(asset.parts.find(part => part.name === name).matrix);+}++function matrixDistance(first, second) {+ return Math.max(...first.map((value, index) => Math.abs(value - second[index])));+}++test('a real exported file loads even though some weights are one unit of rounding above 1', async () => {+ const asset = await loadRobot();+ assert.equal(asset.parts.length, 19);+ assert.equal(asset.skins.length, 4);+ const geometry = { positions: { length: 3 }, skinIndices: new Uint16Array([0, 0, 0, 0]), skinWeights: new Float32Array([1.0000001192092896, 0, 0, 0]) };+ assert.doesNotThrow(() => validateSkinGeometry(geometry, createSkinPose(1)));+ geometry.skinWeights = new Float32Array([1.01, 0, 0, 0]);+ assert.throws(() => validateSkinGeometry(geometry, createSkinPose(1)), /within zero and one/);+});++test('a GLB clip through createAssetPose matches the decoder playing it, on rigid parts and skins', async () => {+ const reference = await loadRobot();+ const posed = await loadRobot();+ const clipIndex = reference.animations.findIndex(animation => animation.name === 'Walking');+ const pose = createAssetPose(posed, { layers: [{ clip: clipNamed(posed, 'Walking') }] });+ for (const time of [0, 0.3, 0.71]) {+ reference.applyAnimation(time, clipIndex);+ pose.apply(time);+ reference.parts.forEach((part, index) => {+ const distance = matrixDistance(Array.from(part.matrix), Array.from(posed.parts[index].matrix));+ assert.ok(distance < 5e-4, `${part.name} at ${time}: ${distance}`);+ });+ reference.skins.forEach((skin, index) => {+ const distance = matrixDistance(Array.from(skin.jointMatrices), Array.from(posed.skins[index].jointMatrices));+ assert.ok(distance < 1e-4, `skin ${index} at ${time}: ${distance}`);+ });+ }+});++test('rigid parts follow the pose, and seeking back gives the same matrices', async () => {+ const asset = await loadRobot();+ const pose = createAssetPose(asset, { layers: [{ clip: clipNamed(asset, 'Walking') }] });+ pose.apply(0.1);+ const early = partMatrix(asset, 'LegL');+ pose.apply(0.5);+ assert.ok(matrixDistance(early, partMatrix(asset, 'LegL')) > 1e-3, 'the leg moved');+ pose.apply(0.1);+ assert.deepEqual(partMatrix(asset, 'LegL'), early);+});++test('a mask limits a clip to one arm of a walking character', async () => {+ const plainAsset = await loadRobot();+ const plain = createAssetPose(plainAsset, { layers: [{ clip: clipNamed(plainAsset, 'Walking') }] });+ plain.apply(0.4);+ const maskedAsset = await loadRobot();+ const masked = createAssetPose(maskedAsset, { layers: [{ clip: clipNamed(maskedAsset, 'Walking') }, { clip: clipNamed(maskedAsset, 'Wave'), mask: { joints: ['ShoulderR'] } }] });+ masked.apply(0.4);+ assert.ok(matrixDistance(partMatrix(plainAsset, 'ArmR'), partMatrix(maskedAsset, 'ArmR')) > 1e-3, 'the masked arm changed');+ for (const name of ['ArmL', 'LegL', 'LegR', 'Head_2']) {+ assert.ok(matrixDistance(partMatrix(plainAsset, name), partMatrix(maskedAsset, name)) < 1e-5, `${name} stayed on the walk`);+ }+});++test('arm IK reaches a world point through the armature scale and rotation', async () => {+ const asset = await loadRobot();+ const target = [-1.3, 2.1, 0.8];+ const pose = createAssetPose(asset, {+ layers: [{ clip: clipNamed(asset, 'Idle') }],+ ik: [{ type: 'two-bone', root: 'UpperArmR', middle: 'LowerArmR', end: 'Palm2R', target, keepEndRotation: false }],+ });+ pose.apply(0);+ assert.equal(pose.ikResults[0].reached, true);+ assert.ok(vec3.distance(pose.jointWorld('Palm2R').position, target) < 1e-3);+});++test('worldForward aims by the way the character faces, whatever the bone axes are', async () => {+ const asset = await loadRobot();+ const rest = createAssetPose(asset);+ rest.apply(0);+ const restRotation = rest.jointWorld('Head').rotation;+ const localForward = vec3.transformQuat(new Float64Array(3), [0, 0, 1], quat.invert(new Float64Array(4), restRotation));+ const target = [2, 3, 4];+ const pose = createAssetPose(asset, { ik: [{ type: 'aim', joint: 'Head', worldForward: [0, 0, 1], target }] });+ pose.apply(0);+ const { position, rotation } = pose.jointWorld('Head');+ const facing = vec3.transformQuat(new Float64Array(3), localForward, rotation);+ const toTarget = vec3.subtract(new Float64Array(3), target, position);+ assert.ok(vec3.angle(facing, toTarget) < 1e-3);+ assert.equal(pose.ikResults[0].reached, true);+ assert.throws(() => createAssetPose(asset, { ik: [{ type: 'aim', joint: 'Head', forward: [0, 0, 1], worldForward: [0, 0, 1], target }] }), /forward or worldForward, not both/);+});++test('a foot that is not a child of the lower leg gets a clear error', async () => {+ const asset = await loadRobot();+ assert.throws(() => createAssetPose(asset, {+ ik: [{ type: 'two-bone', root: 'UpperLegL', middle: 'LowerLegL', end: 'FootL', target: [0, 0, 0] }],+ }), /end must descend from middle/);+});++test('clip conversion keeps node tracks and skips morph weights', async () => {+ const asset = await loadRobot();+ const source = asset.animations.find(animation => animation.name === 'Wave');+ const clip = clipFromGltfAnimation(source);+ assert.ok(clip.tracks.every(track => ['rotation', 'translation', 'scale'].includes(track.property)));+ assert.ok(clip.tracks.some(track => track.target === 'ShoulderR' && track.property === 'rotation'));+ assert.ok(clip.tracks.length < source.tracks.length);+ assert.throws(() => clipFromGltfAnimation({}), /needs an animation/);+ assert.throws(() => createAssetPose({}), /needs an asset/);+});