Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add skeleton pose layers and IK

Nguyen Xuan An1ec3376090bc
diff --git a/.gitignore b/.gitignore
index a98c6666..5153be0b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,7 @@ public/sculpt.md
public/surface.md
public/mesh-query.md
public/mesh.md
+public/skeleton-pose.md
public/primitives.md
public/shrinkwrap.md
public/spume.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff4c2b75..1fd408d7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## Unreleased
+
+- Add `67js/addons/skeleton-pose`: clip layers for skinned rigs with joint masks and additive blending, two-bone IK with poles and aim IK with angle limits and shared chains, all seekable, with joints named by rig name or humanoid bone
+
## 0.12.0
- Add the recipe material field `pattern`: eleven seeded, tileable procedural surfaces (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric, noise) that need no UVs, keep their real size under node scale, and can change while a scene is open
diff --git a/README.md b/README.md
index 8427ec80..aac4e122 100644
--- a/README.md
+++ b/README.md
@@ -123,7 +123,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Vegetation | `67js/addons/vegetation` | [Seeded trees, bushes and grass](docs/vegetation.md) with scanned leaves and bark, wind and level of detail. |
| Liquid | `67js/addons/spume` | [Baked liquid playback](docs/spume.md) with refraction and spray from the Spume solver. |
| Vehicles | `67js/addons/vehicle` | [Wheeled vehicles on a path](docs/vehicle.md): wheel spin, steering, roll, pitch and ground following. |
-| Characters | `67js/addons/gltf`, `67js/addons/retarget` | [glTF import](docs/gltf.md) with skins, morphs and compressed meshes, and [clip retargeting](docs/retarget.md) between rigs. |
+| Characters | `67js/addons/gltf`, `67js/addons/retarget`, `67js/addons/skeleton-pose` | [glTF import](docs/gltf.md) with skins, morphs and compressed meshes, [clip retargeting](docs/retarget.md) between rigs, and [pose layers with IK](docs/skeleton-pose.md). |
| Physics | `67js/addons/physics` | [Rapier contacts and joints](docs/physics.md) recorded into a timeline for repeatable seeks. |
| Modeling | `67js/addons/modeling`, `sculpt`, `surface`, `shrinkwrap`, `mesh-query` | [Modeling](docs/modeling.md), [sculpt brushes](docs/sculpt.md), [surface patches](docs/surface.md), [shrinkwrap](docs/shrinkwrap.md) and [mesh queries](docs/mesh-query.md). |
| Polygon mesh | `67js/addons/mesh` | [Mesh editing for agents](docs/mesh.md): tagged faces, extrude, inset, bevel, loop cut, booleans, a modifier stack and UV unwrap. |
diff --git a/docs/agent-character-motion.md b/docs/agent-character-motion.md
index c9cb3f41..23c3369d 100644
--- a/docs/agent-character-motion.md
+++ b/docs/agent-character-motion.md
@@ -133,5 +133,5 @@ Candidate buffers belong to the decoder. Their contents expire at the next stagi
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.
+Agent recipes do not have IK, retargeting, facial morph authoring or topology changes. In code, [skeleton pose layers](skeleton-pose.md) add IK and [retargeting](retarget.md) moves clips between rigs.
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/animation-mixer.md b/docs/animation-mixer.md
index 5d94daca..b3502088 100644
--- a/docs/animation-mixer.md
+++ b/docs/animation-mixer.md
@@ -90,5 +90,5 @@ The mixer owns registered properties during playback, so external writes do not
Retained timelines support deterministic film sampling and interrupted fades without depending on previous evaluation calls.
The mixer uses `compileAnimationSampler` from the curve module, so interpolation math has one implementation.
-Additive blending remains an open gap because it needs an explicit reference pose and quaternion delta convention.
+This mixer has no additive blending, because it needs an explicit reference pose and quaternion delta convention. [Skeleton pose layers](skeleton-pose.md) provide additive layers, joint masks and IK for skinned rigs.
This module does not add skeletal skinning, morph targets, hierarchy propagation, root motion extraction, transition warping or animation events.
diff --git a/docs/skeleton-pose.md b/docs/skeleton-pose.md
new file mode 100644
index 00000000..235e88e7
--- /dev/null
+++ b/docs/skeleton-pose.md
@@ -0,0 +1,99 @@
+# Skeleton pose layers and IK
+
+`67js/addons/skeleton-pose` builds a skeletal pose from clip layers, then corrects it with inverse kinematics. Use it to
+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';
+
+const pose = createSkeletonPose({
+ skin: character.skins[0],
+ layers: [
+ { clip: walk },
+ { clip: wave, mask: { joints: ['rightUpperArm'] } },
+ { 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] },
+ ],
+});
+
+pose.apply(seconds);
+renderer.updateParts(character.parts);
+```
+
+Every `apply(time)` rebuilds the pose from the rest pose: layers in order, then solvers in order. Nothing carries over
+between calls, so a backward seek gives the same pose as playing forward, provided your weight and target functions
+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.
+
+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.
+
+## Layers
+
+| Field | Meaning |
+| --- | --- |
+| `clip` | From `createAnimationClip`. Tracks that name no rig joint are ignored; at least one must match |
+| `weight` | 0 to 1 (default 1), or a function of time |
+| `mask` | `{ joints, descendants = true, exclude }`. The layer touches only these joints. `exclude` removes joints with their descendants |
+| `additive` | `true` adds the clip's change from `reference` instead of replacing the pose |
+| `reference` | The clip time an additive layer counts as no change, in seconds (default 0) |
+| `speed`, `offset` | Layer time is `time * speed + offset`. The clip decides looping |
+
+A normal layer blends toward its clip by `weight`: spherical interpolation for rotation, linear for translation. Joints
+its clip does not track keep the pose so far. An additive rotation is `inverse(reference) * sample`, applied in the
+joint's own frame (`local = local * delta`), and weight scales the delta. An additive translation adds
+`(sample - reference) * weight`. So an additive clip is the same at `reference` as no layer at all.
+
+## Two-bone IK
+
+| Field | Meaning |
+| --- | --- |
+| `root`, `middle`, `end` | The chain, such as hip, knee and ankle. `end` must descend from `middle`, and `middle` from `root`; twist joints in between are fine |
+| `target` | World position, or `(time, endPosition) => position` |
+| `pole` | World point the middle joint bends toward, or `(time, middlePosition) => point`. Without one, it keeps the current bend |
+| `weight` | 0 to 1 (default 1), or a function of time |
+| `keepEndRotation` | Default `true`: the end joint keeps its world rotation, so a foot stays flat while the leg moves |
+
+The solve is analytic, keeps bone lengths, and turns the two upper joints by the shortest rotations, so twist already in
+the pose survives. A limb that is straight in the pose with its target straight ahead has no bend direction, so give
+legs and arms a `pole`.
+
+A target out of reach leaves the limb extended toward it. The limit is kept just short of fully straight, because a
+perfectly straight limb has no defined bend for the next frame.
+
+## Aim IK
+
+| 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 |
+| `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 |
+
+The turn is the shortest rotation, so `aim` does not hold an up direction and can add a little roll.
+
+## Reading the result
+
+`pose.jointWorld(name)` returns `{ position, rotation }` after the last `apply`, in world space, for attaching props or
+chaining targets. `pose.ikResults` holds one `{ reached, error }` per solver: `error` is metres from the target for
+two-bone and radians off target for aim.
+
+## Limits
+
+- 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 the
+ body outward.
+- MCP recipes cannot use this yet. Agent tools 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 addon
+ for skinned rigs.
diff --git a/package.json b/package.json
index d319700a..8f28dc10 100644
--- a/package.json
+++ b/package.json
@@ -25,6 +25,7 @@
"docs/release-verification.md",
"docs/animation-curves.md",
"docs/animation-mixer.md",
+ "docs/skeleton-pose.md",
"docs/material-maps.md",
"docs/modeling.md",
"docs/scene-graph.md",
@@ -86,6 +87,7 @@
"./addons/physics": "./build/physics.js",
"./addons/spume": "./build/spume.js",
"./addons/retarget": "./build/retarget.js",
+ "./addons/skeleton-pose": "./build/skeleton-pose.js",
"./addons/vehicle": "./build/vehicle.js",
"./addons/vegetation": "./build/vegetation.js",
"./addons/terrain": "./build/terrain.js",
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index d5ba0ce5..9ac00b24 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -41,6 +41,7 @@ const sourceDocuments = [
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'mesh.md','primitives.md', 'shrinkwrap.md', 'spume.md',
'retarget.md',
+ 'skeleton-pose.md',
'vehicle.md',
'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index ced0c789..9f858443 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -38,6 +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`. It is not available through MCP.
- 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`.
diff --git a/src/retarget.js b/src/retarget.js
index eefe6410..3df325d8 100644
--- a/src/retarget.js
+++ b/src/retarget.js
@@ -197,7 +197,7 @@ function jointOrder(joints, label) {
return order;
}
-function validateRigJoints(joints, label) {
+export function validateRigJoints(joints, label) {
if (!Array.isArray(joints) || !joints.length) throw new TypeError(`${label} rig needs a non-empty joints array.`);
joints.forEach(joint => {
const parentIsValid = Number.isInteger(joint.parent) && joint.parent >= -1 && joint.parent < joints.length;
@@ -206,7 +206,7 @@ function validateRigJoints(joints, label) {
});
}
-function createPoseState(jointCount) {
+export function createPoseState(jointCount) {
const createVectors = (size) => Array.from({ length: jointCount }, () => new Float64Array(size));
return {
rotations: createVectors(4),
@@ -226,7 +226,7 @@ function placeJoint(prepared, state, index, localRotation, localTranslation) {
state.scales[index] = parentScale * prepared.localScales[index];
}
-function computeWorldPose(prepared, state, localRotations, localTranslations) {
+export function computeWorldPose(prepared, state, localRotations, localTranslations) {
for (const index of prepared.order) placeJoint(prepared, state, index, localRotations[index], localTranslations[index]);
}
@@ -250,7 +250,7 @@ function prepareRig(rig, label, overrides) {
return { ...prepareRigGeometry(rig, label), indexByBone };
}
-function prepareRigGeometry(rig, label) {
+export function prepareRigGeometry(rig, label) {
const joints = rig.joints;
const root = decomposeMatrix(rig.rootMatrix ? Float64Array.from(rig.rootMatrix) : mat4.create());
const prepared = {
@@ -293,7 +293,7 @@ function frameTimes(duration, frameRate) {
return times;
}
-function bindSourceTracks(sampler, sourcePrepared) {
+export function bindSourceTracks(sampler, sourcePrepared) {
const bindings = [];
for (const track of sampler.tracks) {
const index = sourcePrepared.indexByName.get(track.target);
diff --git a/src/skeleton-pose.js b/src/skeleton-pose.js
new file mode 100644
index 00000000..62e192ed
--- /dev/null
+++ b/src/skeleton-pose.js
@@ -0,0 +1,354 @@
+import { mat4, quat, vec3 } from 'gl-matrix';
+import { compileAnimationSampler } from './animation.js';
+import { updateSkinPose } from './skinning.js';
+import {
+ bindSourceTracks, computeWorldPose, createPoseState, createRigFromSkin, mapHumanoidBones, prepareRigGeometry, validateRigJoints,
+} from './retarget.js';
+
+// Layered skeletal poses with inverse kinematics. Each apply(time) rebuilds the whole pose from the rest pose, in order:
+// clip layers, then IK solvers. Nothing carries over between calls, so seeking backward gives the same pose as playing
+// forward. Quaternions are XYZW; IK targets and poles are in the rig's world space.
+
+const NEAR_ZERO = 1e-9;
+const TO_RADIANS = Math.PI / 180;
+const IDENTITY_ROTATION = Object.freeze([0, 0, 0, 1]);
+
+function jointResolver(rig, prepared) {
+ const names = rig.joints.map(joint => joint.name);
+ const canonical = rig.mapping ?? mapHumanoidBones(names).mapping;
+ return function resolveJoint(name, label) {
+ const jointName = prepared.indexByName.has(name) ? name : canonical[name];
+ const index = prepared.indexByName.get(jointName);
+ if (index === undefined) {
+ const shown = names.slice(0, 12).join(', ');
+ throw new RangeError(`${label}: joint ${name} is not in the rig. Use a joint name or a humanoid bone such as leftUpperArm. Joints: ${shown}${names.length > 12 ? ', ...' : ''}`);
+ }
+ return index;
+ };
+}
+
+function descendantsOf(prepared, roots) {
+ const inside = new Uint8Array(prepared.joints.length);
+ for (const root of roots) inside[root] = 1;
+ for (const index of prepared.order) {
+ const parent = prepared.joints[index].parent;
+ if (parent >= 0 && inside[parent]) inside[index] = 1;
+ }
+ return inside;
+}
+
+/** Per-joint layer weights from { joints, descendants = true, exclude }. Without a mask every joint counts fully. */
+function maskWeights(prepared, resolveJoint, mask) {
+ const weights = new Float64Array(prepared.joints.length);
+ if (!mask) return weights.fill(1);
+ if (!Array.isArray(mask.joints) || !mask.joints.length) throw new TypeError('A layer mask needs joints: a non-empty list of joint or bone names.');
+ const included = mask.joints.map(name => resolveJoint(name, 'Layer mask'));
+ if (mask.descendants === false) {
+ for (const index of included) weights[index] = 1;
+ } else {
+ weights.set(descendantsOf(prepared, included));
+ }
+ if (mask.exclude) {
+ const removed = descendantsOf(prepared, mask.exclude.map(name => resolveJoint(name, 'Layer mask exclude')));
+ removed.forEach((flag, index) => {
+ if (flag) weights[index] = 0;
+ });
+ }
+ return weights;
+}
+
+function weightFunction(value, label) {
+ if (typeof value === 'function') return value;
+ if (!Number.isFinite(value) || value < 0 || value > 1) throw new RangeError(`${label} must be from 0 to 1, or a function of time.`);
+ return () => value;
+}
+
+function checkedWeight(weight, time, label) {
+ const value = weight(time);
+ if (!Number.isFinite(value) || value < 0 || value > 1) throw new RangeError(`${label} returned ${value} at time ${time}; it must be from 0 to 1.`);
+ return value;
+}
+
+function createLayer(definition, position, prepared, resolveJoint) {
+ const label = `Layer ${position}`;
+ if (!definition?.clip) throw new TypeError(`${label} needs a clip from createAnimationClip.`);
+ const sampler = compileAnimationSampler(definition.clip);
+ const bindings = bindSourceTracks(sampler, prepared);
+ if (!bindings.length) throw new RangeError(`${label}: no clip track names a joint of this rig.`);
+ const additive = definition.additive === true;
+ const referenceTime = definition.reference ?? 0;
+ if (!Number.isFinite(referenceTime)) throw new RangeError(`${label} reference must be a clip time in seconds.`);
+ let references = [];
+ if (additive) {
+ sampler.sample(referenceTime);
+ references = bindings.map(binding => Float64Array.from(binding.output));
+ }
+ const speed = definition.speed ?? 1;
+ const offset = definition.offset ?? 0;
+ if (!Number.isFinite(speed) || !Number.isFinite(offset)) throw new RangeError(`${label} speed and offset must be finite.`);
+ return {
+ label, sampler, bindings, additive, references, speed, offset,
+ weight: weightFunction(definition.weight ?? 1, `${label} weight`),
+ mask: maskWeights(prepared, resolveJoint, definition.mask),
+ };
+}
+
+const scratchDelta = new Float64Array(4);
+const scratchInverse = new Float64Array(4);
+
+function applyAdditiveRotation(rotation, sample, reference, weight) {
+ // delta = inverse(reference) * sample, applied in the joint's own frame: local = local * delta.
+ quat.multiply(scratchDelta, quat.invert(scratchInverse, reference), sample);
+ quat.slerp(scratchDelta, IDENTITY_ROTATION, scratchDelta, weight);
+ quat.normalize(rotation, quat.multiply(rotation, rotation, scratchDelta));
+}
+
+function applyLayer(layer, time, localRotations, localTranslations) {
+ const layerWeight = checkedWeight(layer.weight, time, `${layer.label} weight`);
+ if (layerWeight === 0) return;
+ layer.sampler.sample(time * layer.speed + layer.offset);
+ layer.bindings.forEach((binding, slot) => {
+ const weight = layerWeight * layer.mask[binding.index];
+ if (weight === 0) return;
+ if (binding.property === 'rotation') {
+ const rotation = localRotations[binding.index];
+ if (layer.additive) {
+ applyAdditiveRotation(rotation, binding.output, layer.references[slot], weight);
+ } else {
+ quat.normalize(rotation, quat.slerp(rotation, rotation, binding.output, weight));
+ }
+ return;
+ }
+ const translation = localTranslations[binding.index];
+ for (let axis = 0; axis < 3; axis++) {
+ if (layer.additive) {
+ translation[axis] += (binding.output[axis] - layer.references[slot][axis]) * weight;
+ } else {
+ translation[axis] += (binding.output[axis] - translation[axis]) * weight;
+ }
+ }
+ });
+}
+
+function isDescendant(prepared, index, ancestor) {
+ let current = prepared.joints[index].parent;
+ while (current >= 0) {
+ if (current === ancestor) return true;
+ current = prepared.joints[current].parent;
+ }
+ return false;
+}
+
+function checkedVector(value, label) {
+ if (value?.length !== 3 || !Number.isFinite(value[0]) || !Number.isFinite(value[1]) || !Number.isFinite(value[2])) {
+ throw new RangeError(`${label} must be three finite numbers.`);
+ }
+ return value;
+}
+
+function createSolver(definition, position, prepared, resolveJoint) {
+ const label = `IK ${position}`;
+ const weight = weightFunction(definition?.weight ?? 1, `${label} weight`);
+ if (typeof definition?.target !== 'function') checkedVector(definition?.target, `${label} target`);
+ if (definition.type === 'two-bone') {
+ const root = resolveJoint(definition.root, label);
+ const middle = resolveJoint(definition.middle, label);
+ const end = resolveJoint(definition.end, label);
+ if (!isDescendant(prepared, middle, root) || !isDescendant(prepared, end, middle)) {
+ throw new RangeError(`${label}: end must descend from middle, and middle from root.`);
+ }
+ if (definition.pole !== undefined && typeof definition.pole !== 'function') checkedVector(definition.pole, `${label} pole`);
+ return { type: 'two-bone', label, weight, root, middle, end, target: definition.target, pole: definition.pole, keepEndRotation: definition.keepEndRotation !== false };
+ }
+ if (definition.type === 'aim') {
+ const names = definition.joints ?? (definition.joint === undefined ? [] : [definition.joint]);
+ if (!names.length) throw new TypeError(`${label} needs joint, or joints listed from the base of the chain to the aiming joint.`);
+ const joints = names.map(name => resolveJoint(name, label));
+ 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`));
+ 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 };
+ }
+ throw new RangeError(`${label} type must be two-bone or aim.`);
+}
+
+function resolvedPoint(value, time, reference, label) {
+ return checkedVector(typeof value === 'function' ? value(time, Array.from(reference)) : value, label);
+}
+
+function perpendicularTo(direction) {
+ const reference = Math.abs(direction[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];
+ return vec3.normalize(new Float64Array(3), vec3.cross(new Float64Array(3), direction, reference));
+}
+
+function createSolverContext(prepared, state, localRotations, localTranslations) {
+ const update = () => computeWorldPose(prepared, state, localRotations, localTranslations);
+ const scratch = new Float64Array(4);
+ // Give a joint a new world rotation, faded in by weight against the local rotation it has now.
+ function setWorldRotation(index, worldRotation, weight) {
+ const parent = prepared.joints[index].parent;
+ const parentRotation = parent >= 0 ? state.rotations[parent] : prepared.rootRotation;
+ quat.multiply(scratch, quat.invert(new Float64Array(4), parentRotation), worldRotation);
+ quat.normalize(localRotations[index], quat.slerp(localRotations[index], localRotations[index], scratch, weight));
+ update();
+ }
+ return { state, update, setWorldRotation };
+}
+
+/**
+ * Analytic two-bone IK. Places the middle joint in the plane of the target and the pole (or of the current bend), then
+ * turns the two upper joints with the shortest rotations, so twist already in the pose survives.
+ */
+function solveTwoBone(solver, time, context) {
+ const { state, setWorldRotation } = context;
+ const weight = checkedWeight(solver.weight, time, `${solver.label} weight`);
+ const endPosition = state.positions[solver.end];
+ const target = resolvedPoint(solver.target, time, endPosition, `${solver.label} target`);
+ if (weight === 0) return { reached: true, error: 0 };
+ const rootPosition = Float64Array.from(state.positions[solver.root]);
+ const middlePosition = Float64Array.from(state.positions[solver.middle]);
+ const startEnd = Float64Array.from(endPosition);
+ const endRotation = Float64Array.from(state.rotations[solver.end]);
+ const upperLength = vec3.distance(rootPosition, middlePosition);
+ const lowerLength = vec3.distance(middlePosition, startEnd);
+ const toTarget = vec3.subtract(new Float64Array(3), target, rootPosition);
+ const targetDistance = vec3.length(toTarget);
+ if (targetDistance < NEAR_ZERO || upperLength < NEAR_ZERO || lowerLength < NEAR_ZERO) {
+ return { reached: false, error: vec3.distance(startEnd, target) };
+ }
+ const direction = vec3.scale(new Float64Array(3), toTarget, 1 / targetDistance);
+ // Stop just short of the limits: a fully straight limb has no defined bend plane for the next frame.
+ const margin = (upperLength + lowerLength) * 1e-4;
+ const reachLimit = upperLength + lowerLength - margin;
+ const reach = Math.min(reachLimit, Math.max(Math.abs(upperLength - lowerLength) + margin, targetDistance));
+ const bendReference = solver.pole === undefined
+ ? vec3.subtract(new Float64Array(3), middlePosition, rootPosition)
+ : vec3.subtract(new Float64Array(3), resolvedPoint(solver.pole, time, middlePosition, `${solver.label} pole`), rootPosition);
+ const alongTarget = vec3.dot(bendReference, direction);
+ const bend = vec3.scaleAndAdd(new Float64Array(3), bendReference, direction, -alongTarget);
+ if (vec3.length(bend) < NEAR_ZERO * Math.max(1, upperLength)) {
+ vec3.copy(bend, perpendicularTo(direction));
+ } else {
+ vec3.normalize(bend, bend);
+ }
+ const alongLimb = (upperLength * upperLength - lowerLength * lowerLength + reach * reach) / (2 * reach);
+ const height = Math.sqrt(Math.max(0, upperLength * upperLength - alongLimb * alongLimb));
+ const newMiddle = vec3.scaleAndAdd(new Float64Array(3), rootPosition, direction, alongLimb);
+ vec3.scaleAndAdd(newMiddle, newMiddle, bend, height);
+ const newEnd = vec3.scaleAndAdd(new Float64Array(3), rootPosition, direction, reach);
+
+ const upperFrom = vec3.normalize(new Float64Array(3), vec3.subtract(new Float64Array(3), middlePosition, rootPosition));
+ const upperTo = vec3.normalize(new Float64Array(3), vec3.subtract(new Float64Array(3), newMiddle, rootPosition));
+ const rootTurn = quat.rotationTo(new Float64Array(4), upperFrom, upperTo);
+ const endAfterRoot = vec3.transformQuat(new Float64Array(3), vec3.subtract(new Float64Array(3), startEnd, rootPosition), rootTurn);
+ vec3.add(endAfterRoot, endAfterRoot, rootPosition);
+ const lowerFrom = vec3.normalize(new Float64Array(3), vec3.subtract(new Float64Array(3), endAfterRoot, newMiddle));
+ const lowerTo = vec3.normalize(new Float64Array(3), vec3.subtract(new Float64Array(3), newEnd, newMiddle));
+ const middleTurn = quat.rotationTo(new Float64Array(4), lowerFrom, lowerTo);
+
+ const newRootRotation = quat.multiply(new Float64Array(4), rootTurn, state.rotations[solver.root]);
+ const newMiddleRotation = quat.multiply(new Float64Array(4), middleTurn, quat.multiply(new Float64Array(4), rootTurn, state.rotations[solver.middle]));
+ setWorldRotation(solver.root, newRootRotation, weight);
+ setWorldRotation(solver.middle, newMiddleRotation, weight);
+ if (solver.keepEndRotation) setWorldRotation(solver.end, endRotation, weight);
+ const error = vec3.distance(state.positions[solver.end], target);
+ return { reached: error <= margin * 2 + NEAR_ZERO, error };
+}
+
+/** Turn a joint, or a chain sharing the turn evenly, so its forward axis points at the target. */
+function solveAim(solver, time, context) {
+ const { state, setWorldRotation } = context;
+ const weight = checkedWeight(solver.weight, time, `${solver.label} weight`);
+ const aiming = solver.joints[solver.joints.length - 1];
+ const target = resolvedPoint(solver.target, time, state.positions[aiming], `${solver.label} target`);
+ if (weight === 0) return { reached: true, error: 0 };
+ const forwardNow = () => vec3.transformQuat(new Float64Array(3), solver.forward, state.rotations[aiming]);
+ const toTarget = vec3.subtract(new Float64Array(3), target, state.positions[aiming]);
+ if (vec3.length(toTarget) < NEAR_ZERO) return { reached: false, error: Math.PI };
+ vec3.normalize(toTarget, toTarget);
+ const start = forwardNow();
+ const totalTurn = quat.rotationTo(new Float64Array(4), start, toTarget);
+ const totalAngle = 2 * Math.acos(Math.min(1, Math.abs(totalTurn[3])));
+ // maxAngle limits the whole turn, so the chain ends up pointing along this direction when the target is too far around.
+ const allowed = totalAngle > solver.maxRadians ? solver.maxRadians / totalAngle : 1;
+ const limitedTurn = quat.slerp(new Float64Array(4), IDENTITY_ROTATION, totalTurn, allowed);
+ const goal = vec3.transformQuat(new Float64Array(3), start, limitedTurn);
+ solver.joints.forEach((joint, slot) => {
+ const remaining = solver.joints.length - slot;
+ const turn = quat.rotationTo(new Float64Array(4), forwardNow(), goal);
+ quat.slerp(turn, IDENTITY_ROTATION, turn, 1 / remaining);
+ setWorldRotation(joint, quat.multiply(new Float64Array(4), turn, state.rotations[joint]), weight);
+ });
+ 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 };
+}
+
+const SOLVERS = { 'two-bone': solveTwoBone, aim: solveAim };
+
+/**
+ * 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
+ * `reference` when `additive` is true. IK solvers run in order after every layer.
+ */
+export function createSkeletonPose({ skin, rig = skin && createRigFromSkin(skin), meshWorldMatrix, layers = [], ik = [] } = {}) {
+ if (!rig) throw new TypeError('createSkeletonPose needs a skin or a rig.');
+ validateRigJoints(rig.joints, 'Pose');
+ if (!Array.isArray(layers) || !Array.isArray(ik)) throw new TypeError('layers and ik must be arrays.');
+ const prepared = prepareRigGeometry(rig, 'Pose');
+ 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 jointCount = rig.joints.length;
+ const localRotations = prepared.restRotations.map(rotation => Float64Array.from(rotation));
+ const localTranslations = prepared.restTranslations.map(translation => Float64Array.from(translation));
+ const state = createPoseState(jointCount);
+ const context = createSolverContext(prepared, state, localRotations, localTranslations);
+ const jointWorldMatrices = new Float32Array(jointCount * 16);
+ const scratchMatrix = mat4.create();
+ const results = solvers.map(() => ({ reached: true, error: 0 }));
+ const bindMatrix = skin?.bindMatrix ?? mat4.create();
+ const meshMatrix = meshWorldMatrix ?? bindMatrix;
+
+ function writePalette() {
+ for (let index = 0; index < jointCount; index++) {
+ const scale = state.scales[index];
+ mat4.fromRotationTranslationScale(scratchMatrix, state.rotations[index], state.positions[index], [scale, scale, scale]);
+ jointWorldMatrices.set(scratchMatrix, index * 16);
+ }
+ updateSkinPose(skin, jointWorldMatrices, skin.inverseBindMatrices, meshMatrix, bindMatrix);
+ }
+
+ function jointWorld(name) {
+ const index = resolveJoint(name, 'jointWorld');
+ return { position: Array.from(state.positions[index]), rotation: Array.from(state.rotations[index]) };
+ }
+
+ return {
+ /** Rebuild the pose for an absolute time in seconds. Returns the skin when there is one. */
+ apply(time) {
+ if (!Number.isFinite(time)) throw new RangeError('Pose time must be finite.');
+ for (let index = 0; index < jointCount; index++) {
+ localRotations[index].set(prepared.restRotations[index]);
+ localTranslations[index].set(prepared.restTranslations[index]);
+ }
+ for (const layer of compiledLayers) applyLayer(layer, time, localRotations, localTranslations);
+ context.update();
+ solvers.forEach((solver, position) => {
+ results[position] = SOLVERS[solver.type](solver, time, context);
+ });
+ if (skin) writePalette();
+ return skin;
+ },
+ /** World position and rotation of a joint after the last apply. */
+ jointWorld,
+ /** One { reached, error } per IK solver from the last apply: metres for two-bone, radians for aim. */
+ get ikResults() {
+ return results;
+ },
+ };
+}
diff --git a/tests/skeleton-pose.test.js b/tests/skeleton-pose.test.js
new file mode 100644
index 00000000..cf866265
--- /dev/null
+++ b/tests/skeleton-pose.test.js
@@ -0,0 +1,348 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mat4, quat, vec3 } from 'gl-matrix';
+import { createAnimationClip } from '../src/animation.js';
+import { createSkinPose } from '../src/skinning.js';
+import { createSkinClipPlayer } from '../src/retarget.js';
+import { createSkeletonPose } from '../src/skeleton-pose.js';
+
+const NAMES = {
+ hips: 'mixamorig:Hips', spine: 'mixamorig:Spine', head: 'mixamorig:Head',
+ leftUpperArm: 'mixamorig:LeftArm', leftLowerArm: 'mixamorig:LeftForeArm', leftHand: 'mixamorig:LeftHand',
+ leftUpperLeg: 'mixamorig:LeftUpLeg', leftLowerLeg: 'mixamorig:LeftLeg', leftFoot: 'mixamorig:LeftFoot',
+ rightUpperArm: 'mixamorig:RightArm', rightLowerArm: 'mixamorig:RightForeArm', rightHand: 'mixamorig:RightHand',
+ rightUpperLeg: 'mixamorig:RightUpLeg', rightLowerLeg: 'mixamorig:RightLeg', rightFoot: 'mixamorig:RightFoot',
+};
+
+function createRig() {
+ const joints = [];
+ const add = (bone, parent, translation) => {
+ joints.push({ name: NAMES[bone], parent, translation, rotation: [0, 0, 0, 1], scale: [1, 1, 1] });
+ return joints.length - 1;
+ };
+ const hips = add('hips', -1, [0, 1, 0]);
+ const spine = add('spine', hips, [0, 0.3, 0]);
+ add('head', spine, [0, 0.5, 0]);
+ for (const [side, sign] of [['left', 1], ['right', -1]]) {
+ const upperArm = add(`${side}UpperArm`, spine, [sign * 0.2, 0.4, 0]);
+ const lowerArm = add(`${side}LowerArm`, upperArm, [sign * 0.3, 0, 0]);
+ add(`${side}Hand`, lowerArm, [sign * 0.25, 0, 0]);
+ const upperLeg = add(`${side}UpperLeg`, hips, [sign * 0.1, 0, 0]);
+ const lowerLeg = add(`${side}LowerLeg`, upperLeg, [0, -0.45, 0]);
+ add(`${side}Foot`, lowerLeg, [0, -0.45, 0]);
+ }
+ return { joints };
+}
+
+function rotationAbout(axis, degrees) {
+ return Array.from(quat.setAxisAngle(new Float64Array(4), axis, degrees * Math.PI / 180));
+}
+
+function rotationClip(target, degrees, axis = [0, 0, 1], duration = 1) {
+ return createAnimationClip({
+ duration,
+ tracks: [{ target, property: 'rotation', keyframes: [{ time: 0, value: [0, 0, 0, 1] }, { time: duration, value: rotationAbout(axis, degrees) }] }],
+ });
+}
+
+function assertClose(actual, expected, tolerance = 1e-6, label = '') {
+ for (let index = 0; index < expected.length; index++) {
+ assert.ok(Math.abs(actual[index] - expected[index]) <= tolerance, `${label} ${JSON.stringify(Array.from(actual))} vs ${JSON.stringify(Array.from(expected))}`);
+ }
+}
+
+function assertSameRotation(actual, expected, tolerance = 1e-6) {
+ assert.ok(1 - Math.abs(quat.dot(actual, expected)) <= tolerance, `${JSON.stringify(actual)} vs ${JSON.stringify(expected)}`);
+}
+
+test('with no layers the pose is the rest pose', () => {
+ const pose = createSkeletonPose({ rig: createRig() });
+ pose.apply(0);
+ assertClose(pose.jointWorld('head').position, [0, 1.8, 0]);
+ assertClose(pose.jointWorld('leftFoot').position, [0.1, 0.1, 0]);
+});
+
+test('one full-weight layer matches the existing skin clip player', () => {
+ const rig = createRig();
+ const clip = rotationClip(NAMES.spine, 40);
+ const createSkin = () => {
+ const skin = createSkinPose(rig.joints.length);
+ skin.inverseBindMatrices = new Float32Array(rig.joints.length * 16);
+ for (let joint = 0; joint < rig.joints.length; joint++) skin.inverseBindMatrices.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], joint * 16);
+ return skin;
+ };
+ const skinA = createSkin();
+ const skinB = createSkin();
+ createSkinClipPlayer(skinA, clip, { rig }).apply(0.5);
+ createSkeletonPose({ skin: skinB, rig, layers: [{ clip }] }).apply(0.5);
+ assertClose(skinB.jointMatrices, skinA.jointMatrices, 1e-5);
+});
+
+test('a mask limits a layer to a joint and its descendants, minus exclusions', () => {
+ const clip = createAnimationClip({
+ duration: 1,
+ tracks: [
+ { target: NAMES.leftUpperArm, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([0, 0, 1], 90) }] },
+ { target: NAMES.leftLowerArm, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([0, 0, 1], 90) }] },
+ { target: NAMES.rightUpperArm, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([0, 0, 1], 90) }] },
+ ],
+ });
+ const rest = createSkeletonPose({ rig: createRig() });
+ rest.apply(0);
+ const masked = createSkeletonPose({ rig: createRig(), layers: [{ clip, mask: { joints: ['leftUpperArm'] } }] });
+ masked.apply(0);
+ assertClose(masked.jointWorld('rightHand').position, rest.jointWorld('rightHand').position);
+ assert.ok(vec3.distance(masked.jointWorld('leftHand').position, rest.jointWorld('leftHand').position) > 0.1);
+
+ const noDescendants = createSkeletonPose({ rig: createRig(), layers: [{ clip, mask: { joints: ['leftUpperArm'], descendants: false } }] });
+ noDescendants.apply(0);
+ assertSameRotation(noDescendants.jointWorld('leftLowerArm').rotation, rotationAbout([0, 0, 1], 90));
+
+ const excluded = createSkeletonPose({ rig: createRig(), layers: [{ clip, mask: { joints: ['leftUpperArm'], exclude: ['leftLowerArm'] } }] });
+ excluded.apply(0);
+ assertSameRotation(excluded.jointWorld('leftLowerArm').rotation, rotationAbout([0, 0, 1], 90));
+ assertClose(excluded.jointWorld('leftLowerArm').position, noDescendants.jointWorld('leftLowerArm').position);
+});
+
+test('a masked layer overrides only its joints on top of a base layer', () => {
+ const walk = createAnimationClip({
+ duration: 1,
+ tracks: [
+ { target: NAMES.leftUpperLeg, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([1, 0, 0], 30) }] },
+ { target: NAMES.leftUpperArm, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([1, 0, 0], 30) }] },
+ ],
+ });
+ const wave = createAnimationClip({
+ duration: 1,
+ tracks: [{ target: NAMES.leftUpperArm, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([0, 0, 1], 80) }] }],
+ });
+ const pose = createSkeletonPose({ rig: createRig(), layers: [{ clip: walk }, { clip: wave, mask: { joints: ['leftUpperArm'] } }] });
+ pose.apply(0);
+ assertSameRotation(pose.jointWorld('leftUpperArm').rotation, rotationAbout([0, 0, 1], 80));
+ assertSameRotation(pose.jointWorld('leftUpperLeg').rotation, rotationAbout([1, 0, 0], 30));
+});
+
+test('layer weight blends, and can be a function of time', () => {
+ const clip = createAnimationClip({
+ duration: 1,
+ tracks: [{ target: NAMES.spine, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([0, 0, 1], 90) }] }],
+ });
+ const half = createSkeletonPose({ rig: createRig(), layers: [{ clip, weight: 0.5 }] });
+ half.apply(0);
+ assertSameRotation(half.jointWorld('spine').rotation, rotationAbout([0, 0, 1], 45));
+ const fading = createSkeletonPose({ rig: createRig(), layers: [{ clip, weight: time => Math.min(1, time) }] });
+ fading.apply(0);
+ assertSameRotation(fading.jointWorld('spine').rotation, [0, 0, 0, 1]);
+ fading.apply(1);
+ assertSameRotation(fading.jointWorld('spine').rotation, rotationAbout([0, 0, 1], 90));
+ assert.throws(() => createSkeletonPose({ rig: createRig(), layers: [{ clip, weight: 2 }] }), /weight must be from 0 to 1/);
+ const broken = createSkeletonPose({ rig: createRig(), layers: [{ clip, weight: () => Number.NaN }] });
+ assert.throws(() => broken.apply(0), /returned NaN/);
+});
+
+test('an additive layer adds its change from the reference onto the pose below', () => {
+ const base = createAnimationClip({
+ duration: 1,
+ tracks: [{ target: NAMES.spine, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([0, 0, 1], 30) }] }],
+ });
+ const breathe = rotationClip(NAMES.spine, 20);
+ const pose = createSkeletonPose({ rig: createRig(), layers: [{ clip: base }, { clip: breathe, additive: true }] });
+ pose.apply(0);
+ assertSameRotation(pose.jointWorld('spine').rotation, rotationAbout([0, 0, 1], 30));
+ pose.apply(1);
+ assertSameRotation(pose.jointWorld('spine').rotation, rotationAbout([0, 0, 1], 50));
+
+ const halfway = createSkeletonPose({ rig: createRig(), layers: [{ clip: base }, { clip: breathe, additive: true, weight: 0.5 }] });
+ halfway.apply(1);
+ assertSameRotation(halfway.jointWorld('spine').rotation, rotationAbout([0, 0, 1], 40));
+
+ const fromEnd = createSkeletonPose({ rig: createRig(), layers: [{ clip: base }, { clip: breathe, additive: true, reference: 1 }] });
+ fromEnd.apply(1);
+ assertSameRotation(fromEnd.jointWorld('spine').rotation, rotationAbout([0, 0, 1], 30));
+});
+
+test('additive translation adds the offset from the reference', () => {
+ const bob = createAnimationClip({
+ duration: 1,
+ tracks: [{ target: NAMES.hips, property: 'translation', keyframes: [{ time: 0, value: [0, 1, 0] }, { time: 1, value: [0, 1.1, 0] }] }],
+ });
+ const pose = createSkeletonPose({ rig: createRig(), layers: [{ clip: bob, additive: true }] });
+ pose.apply(1);
+ assertClose(pose.jointWorld('hips').position, [0, 1.1, 0], 1e-6);
+});
+
+test('seeking gives the same pose as playing forward', () => {
+ const clip = rotationClip(NAMES.leftUpperArm, 70);
+ const options = { layers: [{ clip }], ik: [{ type: 'aim', joint: 'head', forward: [0, 0, 1], target: time => [time, 2, 1] }] };
+ const played = createSkeletonPose({ rig: createRig(), ...options });
+ for (const time of [0, 0.2, 0.4, 0.6]) played.apply(time);
+ const seeked = createSkeletonPose({ rig: createRig(), ...options });
+ seeked.apply(0.9);
+ seeked.apply(0.6);
+ assertClose(played.jointWorld('leftHand').position, seeked.jointWorld('leftHand').position, 1e-12);
+ assertClose(played.jointWorld('head').rotation, seeked.jointWorld('head').rotation, 1e-12);
+});
+
+test('two-bone IK reaches a target, keeps bone lengths and keeps the foot rotation', () => {
+ const target = [0.25, 0.35, 0.3];
+ const start = createSkeletonPose({ rig: createRig() });
+ start.apply(0);
+ const footRotation = start.jointWorld('leftFoot').rotation;
+ const pose = createSkeletonPose({
+ rig: createRig(),
+ ik: [{ type: 'two-bone', root: 'leftUpperLeg', middle: 'leftLowerLeg', end: 'leftFoot', target, pole: [0.1, 0.6, 1] }],
+ });
+ pose.apply(0);
+ assert.equal(pose.ikResults[0].reached, true);
+ assert.ok(pose.ikResults[0].error < 1e-6, `error ${pose.ikResults[0].error}`);
+ assertClose(pose.jointWorld('leftFoot').position, target, 1e-6);
+ const hip = pose.jointWorld('leftUpperLeg').position;
+ const knee = pose.jointWorld('leftLowerLeg').position;
+ const ankle = pose.jointWorld('leftFoot').position;
+ assert.ok(Math.abs(vec3.distance(hip, knee) - 0.45) < 1e-6);
+ assert.ok(Math.abs(vec3.distance(knee, ankle) - 0.45) < 1e-6);
+ assertSameRotation(pose.jointWorld('leftFoot').rotation, footRotation);
+ assert.ok(knee[2] > 0.1, `knee bends toward the pole: ${knee}`);
+});
+
+test('two-bone IK bends toward the pole on either side', () => {
+ const makePose = pole => createSkeletonPose({
+ rig: createRig(),
+ ik: [{ type: 'two-bone', root: 'leftUpperLeg', middle: 'leftLowerLeg', end: 'leftFoot', target: [0.1, 0.4, 0], pole }],
+ });
+ const forward = makePose([0.1, 0.5, 1]);
+ forward.apply(0);
+ const backward = makePose([0.1, 0.5, -1]);
+ backward.apply(0);
+ assert.ok(forward.jointWorld('leftLowerLeg').position[2] > 0.1);
+ assert.ok(backward.jointWorld('leftLowerLeg').position[2] < -0.1);
+});
+
+test('two-bone IK reports an unreachable target and reaches toward it', () => {
+ const pose = createSkeletonPose({
+ rig: createRig(),
+ ik: [{ type: 'two-bone', root: 'leftUpperLeg', middle: 'leftLowerLeg', end: 'leftFoot', target: [0.1, 1, 5] }],
+ });
+ pose.apply(0);
+ assert.equal(pose.ikResults[0].reached, false);
+ const hip = pose.jointWorld('leftUpperLeg').position;
+ const ankle = pose.jointWorld('leftFoot').position;
+ assert.ok(Math.abs(vec3.distance(hip, ankle) - 0.9) < 1e-3);
+ assert.ok(ankle[2] > 0.85, `reaches toward the target: ${ankle}`);
+});
+
+test('a target function can plant a foot from the animated position', () => {
+ const swing = createAnimationClip({
+ duration: 1,
+ tracks: [{ target: NAMES.leftUpperLeg, property: 'rotation', keyframes: [{ time: 0, value: rotationAbout([1, 0, 0], 15) }] }],
+ });
+ const groundHeight = 0.2;
+ const pose = createSkeletonPose({
+ rig: createRig(),
+ layers: [{ clip: swing }],
+ ik: [{
+ type: 'two-bone', root: 'leftUpperLeg', middle: 'leftLowerLeg', end: 'leftFoot', pole: [0.1, 0.6, 1],
+ target: (time, foot) => [foot[0], groundHeight, foot[2]],
+ }],
+ });
+ pose.apply(0);
+ const plantedError = Math.abs(pose.jointWorld('leftFoot').position[1] - groundHeight);
+ assert.ok(plantedError < 1e-6, `foot is ${plantedError} from the ground`);
+});
+
+test('IK weight fades the solve in, and zero leaves the pose alone', () => {
+ const rest = createSkeletonPose({ rig: createRig() });
+ rest.apply(0);
+ const make = weight => createSkeletonPose({
+ rig: createRig(),
+ ik: [{ type: 'two-bone', root: 'leftUpperLeg', middle: 'leftLowerLeg', end: 'leftFoot', target: [0.25, 0.35, 0.3], pole: [0.1, 0.6, 1], weight }],
+ });
+ const off = make(0);
+ off.apply(0);
+ assertClose(off.jointWorld('leftFoot').position, rest.jointWorld('leftFoot').position);
+ const half = make(0.5);
+ half.apply(0);
+ const full = make(1);
+ full.apply(0);
+ const restFoot = rest.jointWorld('leftFoot').position;
+ const halfDistance = vec3.distance(half.jointWorld('leftFoot').position, restFoot);
+ const fullDistance = vec3.distance(full.jointWorld('leftFoot').position, restFoot);
+ assert.ok(halfDistance > 0.1 * fullDistance && halfDistance < 0.9 * fullDistance, `${halfDistance} of ${fullDistance}`);
+});
+
+test('aim IK points the forward axis at the target', () => {
+ const pose = createSkeletonPose({ rig: createRig(), ik: [{ type: 'aim', joint: 'head', forward: [0, 0, 1], target: [3, 1.8, 0] }] });
+ pose.apply(0);
+ const forward = vec3.transformQuat(new Float64Array(3), [0, 0, 1], pose.jointWorld('head').rotation);
+ assertClose(forward, [1, 0, 0], 1e-6);
+ assert.equal(pose.ikResults[0].reached, true);
+});
+
+test('aim IK respects maxAngle and shares the turn along a chain', () => {
+ const limited = createSkeletonPose({ rig: createRig(), ik: [{ type: 'aim', joint: 'head', forward: [0, 0, 1], target: [3, 1.8, 0], maxAngle: 30 }] });
+ limited.apply(0);
+ const limitedForward = vec3.transformQuat(new Float64Array(3), [0, 0, 1], limited.jointWorld('head').rotation);
+ assert.ok(Math.abs(vec3.angle(limitedForward, [0, 0, 1]) - 30 * Math.PI / 180) < 1e-6);
+ assert.equal(limited.ikResults[0].reached, false);
+
+ const chain = createSkeletonPose({ rig: createRig(), ik: [{ type: 'aim', joints: ['spine', 'head'], forward: [0, 0, 1], target: [0, 1.8, 3], maxAngle: 180 }] });
+ chain.apply(0);
+ const shared = createSkeletonPose({ rig: createRig(), ik: [{ type: 'aim', joints: ['spine', 'head'], forward: [0, 0, 1], target: [3, 1.8, 0] }] });
+ shared.apply(0);
+ const spineTurn = vec3.angle(vec3.transformQuat(new Float64Array(3), [0, 0, 1], shared.jointWorld('spine').rotation), [0, 0, 1]);
+ assert.ok(spineTurn > 0.5 && spineTurn < 1, `spine takes about half of the turn: ${spineTurn}`);
+});
+
+test('solvers run in order on the pose the previous one left', () => {
+ const pose = createSkeletonPose({
+ rig: createRig(),
+ ik: [
+ { type: 'aim', joint: 'spine', forward: [0, 1, 0], target: [1, 2.3, 0] },
+ { type: 'two-bone', root: 'leftUpperArm', middle: 'leftLowerArm', end: 'leftHand', target: [0.5, 1.5, 0.3], pole: [0.5, 1, -1] },
+ ],
+ });
+ pose.apply(0);
+ assert.ok(pose.ikResults[1].error < 1e-6, `error ${pose.ikResults[1].error}`);
+ assertClose(pose.jointWorld('leftHand').position, [0.5, 1.5, 0.3], 1e-6);
+});
+
+test('joints resolve by name or humanoid bone, and mistakes say what to pass', () => {
+ const rig = createRig();
+ const byName = createSkeletonPose({ rig });
+ byName.apply(0);
+ assert.deepEqual(byName.jointWorld(NAMES.head), byName.jointWorld('head'));
+ assert.throws(() => byName.jointWorld('tail'), /joint tail is not in the rig/);
+ assert.throws(() => createSkeletonPose(), /needs a skin or a rig/);
+ assert.throws(() => createSkeletonPose({ rig, layers: [{}] }), /Layer 0 needs a clip/);
+ assert.throws(() => createSkeletonPose({ rig, layers: [{ clip: rotationClip('nothing', 10) }] }), /no clip track names a joint/);
+ assert.throws(() => createSkeletonPose({ rig, ik: [{ type: 'fabrik', target: [0, 0, 0] }] }), /type must be two-bone or aim/);
+ assert.throws(() => createSkeletonPose({ rig, ik: [{ type: 'two-bone', root: 'leftFoot', middle: 'leftLowerLeg', end: 'leftUpperLeg', target: [0, 0, 0] }] }), /end must descend from middle/);
+ assert.throws(() => createSkeletonPose({ rig, ik: [{ type: 'aim', joint: 'head' }] }), /target must be three finite numbers/);
+ const badTarget = createSkeletonPose({ rig, ik: [{ type: 'aim', joint: 'head', target: () => [Number.NaN, 0, 0] }] });
+ assert.throws(() => badTarget.apply(0), /target must be three finite numbers/);
+ assert.throws(() => byName.apply(Number.NaN), /time must be finite/);
+});
+
+test('on a skin with real bind matrices, rest is the identity palette and IK moves a bound vertex to the target', () => {
+ const rig = createRig();
+ const rest = createSkeletonPose({ rig });
+ rest.apply(0);
+ const skin = createSkinPose(rig.joints.length);
+ skin.joints = rig.joints.map(joint => ({ name: joint.name, parent: joint.parent }));
+ skin.inverseBindMatrices = new Float32Array(rig.joints.length * 16);
+ rig.joints.forEach((joint, index) => {
+ const world = mat4.fromTranslation(mat4.create(), rest.jointWorld(joint.name).position);
+ skin.inverseBindMatrices.set(mat4.invert(mat4.create(), world), index * 16);
+ });
+ const resting = createSkeletonPose({ skin, rig });
+ resting.apply(0);
+ for (let index = 0; index < rig.joints.length; index++) {
+ assertClose(skin.jointMatrices.subarray(index * 16, index * 16 + 16), [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 1e-5, rig.joints[index].name);
+ }
+ const target = [0.25, 0.35, 0.3];
+ const solved = createSkeletonPose({ skin, rig, ik: [{ type: 'two-bone', root: 'leftUpperLeg', middle: 'leftLowerLeg', end: 'leftFoot', target, pole: [0.1, 0.6, 1] }] });
+ solved.apply(0);
+ const footIndex = rig.joints.findIndex(joint => joint.name === NAMES.leftFoot);
+ const footVertex = vec3.transformMat4(new Float64Array(3), rest.jointWorld('leftFoot').position, skin.jointMatrices.subarray(footIndex * 16, footIndex * 16 + 16));
+ assertClose(footVertex, target, 1e-5, 'bound vertex');
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 4c6c9771..07f2ed2c 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -28,6 +28,7 @@ export default defineConfig({
physics: 'src/physics.js',
spume: 'src/spume.js',
retarget: 'src/retarget.js',
+ 'skeleton-pose': 'src/skeleton-pose.js',
vehicle: 'src/vehicle.js',
vegetation: 'src/vegetation.js',
terrain: 'src/terrain.js',