Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add root motion, interruptible crossfades and IK hooks to the animation graph (#774)

Nguyen Xuan An4de9163b7dd6
diff --git a/bench/animation-graph/main.js b/bench/animation-graph/main.js
index debcaeb0..ff560dfc 100644
--- a/bench/animation-graph/main.js
+++ b/bench/animation-graph/main.js
@@ -1,10 +1,14 @@
// Sample for src/animation-graph.js: the CC0 RobotExpressive blends Idle, Walking and Running by speed.
+// The Walking and Running clips are in place, so a root travel track at the pace of the stride is added to the armature node:
+// the graph takes it out again, the character controller moves the body by it and the feet do not slide.
// Open bench/animation-graph/index.html with `npm run dev`. W or the up arrow walks, Shift runs; ?speed=3.5 pins the speed
// and ?demo=1 ramps it up and down on its own.
import { Renderer67 } from '/src/index.js';
import { parseGltf } from '/src/gltf.js';
import { clipFromGltfAnimation, createAssetPose } from '/src/skeleton-pose.js';
+import { createAnimationClip } from '/src/animation.js';
import { createAnimationGraph } from '/src/animation-graph.js';
+import { createCharacterController } from '/src/player.js';
import { createInput, keyboardSource } from '/src/input.js';
import { createRuntime } from '/src/runtime.js';
@@ -21,13 +25,27 @@ const demo = query.get('demo') === '1';
const response = await fetch(ROBOT_URL);
const asset = await parseGltf(await response.arrayBuffer(), { maxVertices: 500000 });
+const ROOT_BONE = 'RobotArmature';
+
+// The CC0 clips play in place. Give a stride clip a root travel track of `metersPerSecond` so the graph has root motion to extract.
+function withRootTravel(clip, metersPerSecond) {
+ const travel = {
+ target: ROOT_BONE,
+ property: 'translation',
+ keyframes: [{ time: 0, value: [0, 0, 0] }, { time: clip.duration, value: [0, 0, metersPerSecond * clip.duration] }],
+ };
+ return createAnimationClip({ duration: clip.duration, loop: clip.loop, tracks: [...clip.tracks, travel] });
+}
+
const clips = {};
-for (const name of ['Idle', 'Walking', 'Running']) {
+for (const [name, pace] of [['Idle', 0], ['Walking', WALK_SPEED], ['Running', RUN_SPEED]]) {
const source = asset.animations.find(animation => animation.name === name);
- clips[name] = clipFromGltfAnimation(source, { loop: true });
+ const clip = clipFromGltfAnimation(source, { loop: true });
+ clips[name] = pace > 0 ? withRootTravel(clip, pace) : clip;
}
const graph = createAnimationGraph({
+ rootMotion: { bone: ROOT_BONE },
clips,
parameters: { speed: { type: 'number' } },
layers: [{
@@ -73,6 +91,14 @@ const locomotionSystem = {
},
};
+// The controller moves the body by the graph's root motion (the readout shows how far). The robot is drawn in place; a game
+// would write controller.state.position to the character's node. Yaw PI because the robot, like any glTF model, faces +Z.
+const controller = createCharacterController({
+ input: { getAxis: () => 0, isHeld: () => false, wasPressed: () => false },
+ yaw: Math.PI,
+ rootMotion: () => graph.rootMotion.delta,
+});
+
const canvas = document.querySelector('canvas');
const renderer = new Renderer67(canvas, asset.parts, { ground: true, hdr: false, samples: 4, memoryBudgetMiB: 512 });
renderer.resize();
@@ -87,7 +113,7 @@ const runtime = createRuntime(renderer, {
mode: 'fixed',
fixedRate: FIXED_RATE,
frame: buildFrame,
- systems: [input, locomotionSystem, graph.system()],
+ systems: [input, locomotionSystem, controller, graph.system()],
});
runtime.start();
window.animationGraphSample = { graph, runtime };
@@ -95,5 +121,6 @@ window.animationGraphSample = { graph, runtime };
const readout = document.querySelector('#readout');
setInterval(() => {
const clipLines = graph.layerState('locomotion').clips.map(entry => `${entry.clip.padEnd(8)} ${(entry.weight * 100).toFixed(0).padStart(3)}%`);
- readout.textContent = [`speed ${locomotionSystem.speed.toFixed(2)}`, ...clipLines, 'W walks, Shift runs'].join('\n');
+ const rootLine = `root motion ${graph.rootMotion.speed.toFixed(2)} m/s, travelled ${Math.abs(controller.state.position[2]).toFixed(1)} m`;
+ readout.textContent = [`speed ${locomotionSystem.speed.toFixed(2)}`, rootLine, ...clipLines, 'W walks, Shift runs'].join('\n');
}, 100);
diff --git a/changes/774-root-motion.size.md b/changes/774-root-motion.size.md
new file mode 100644
index 00000000..8388e45a
--- /dev/null
+++ b/changes/774-root-motion.size.md
@@ -0,0 +1,2 @@
+- entry:animation-graph: root motion extraction, interruptible crossfades and the two IK hook builders are agent-facing capabilities for any rig (a creature or a machine walks and stands on uneven ground without a custom pose system); they load only with this optional addon.
+- scene:player: the controller reads a root motion function and publishes `intentSpeed`, a few dozen bytes gzip, so a game that hooks animation to movement does not need its own controller.
diff --git a/changes/774.md b/changes/774.md
index 43b61874..39544d0d 100644
--- a/changes/774.md
+++ b/changes/774.md
@@ -1 +1,2 @@
- `67js/addons/animation-graph` adds `createAnimationGraph`, a live animation state graph: states with clips or 1D and 2D blend spaces, parameter transitions with crossfades, masked layers, deterministic fixed steps, a runtime system and pose layers for `createSkeletonPose` (#774)
+- `67js/addons/animation-graph` adds root motion (`rootMotion` option, `graph.rootMotion`, `extractRootMotion`; the player controller takes it through a new `rootMotion` option and `state.intentSpeed`), interruptible transitions (`interrupt: true`) and the IK hooks `createFootPlacement` and `createLookAt` (#774)
diff --git a/docs/animation-graph.md b/docs/animation-graph.md
index 506912be..ec650dbc 100644
--- a/docs/animation-graph.md
+++ b/docs/animation-graph.md
@@ -46,7 +46,7 @@ graph.set('speed', 3.1); // from game logic, any time
graph.trigger('wave');
```
-A runnable sample is `bench/animation-graph/index.html` (`npm run dev`, then open `/bench/animation-graph/`): the CC0 RobotExpressive blends Idle, Walking and Running by speed. W walks, Shift runs, `?speed=3.5` pins the speed.
+A runnable sample is `bench/animation-graph/index.html` (`npm run dev`, then open `/bench/animation-graph/`): the CC0 RobotExpressive blends Idle, Walking and Running by speed. W walks, Shift runs, `?speed=3.5` pins the speed. The in-place clips get a root travel track at the stride pace, the graph extracts it and a character controller moves by it; the readout shows the root speed and the distance travelled.
With the [player](player.md), copy its state into parameters in a system placed between the controller and the graph:
@@ -61,6 +61,8 @@ const parameterSystem = {
// systems: [input, controller, parameterSystem, graph.system()]
```
+To let the clips move the body instead, see [Root motion](#root-motion).
+
## Parameters
`parameters` maps a name to `{ type, initial }`.
@@ -89,7 +91,7 @@ Weights always sum to 1. All clips of a blend space share one normalized phase,
- `when` is a list of conditions that must all hold. A number condition has exactly one of `greater`, `atLeast`, `less`, `atMost`, `equals`, `notEquals`. A boolean or trigger condition is `{ parameter, is: true }` (`is` defaults to true).
- `exitPhase` holds the transition until the source state has played that many cycles (1 is one full play of the clip). A transition needs `when`, `exitPhase` or both.
- `duration` is the crossfade in seconds (0 to 10, default 0 for a cut). Weights fade linearly over fixed steps. The outgoing state keeps the blend weights it had when the fade started, so a parameter change does not bend the fade.
-- A new transition starts only when the current crossfade has ended. The longest wait is the fade time.
+- A new transition starts only when the current crossfade has ended, unless it sets `interrupt: true` (see below).
## Layers and masks
@@ -107,8 +109,59 @@ A clip has one time per layer. When both ends of a crossfade use the same clip,
`graph.layerState(name)` returns `{ state, previousState, fade, phase, weight, clips: [{ clip, time, weight }] }`; `fade` is 0 to 1 during a crossfade and null otherwise. `graph.time` is the advanced time and `graph.layers` the layer names.
+## Interrupting a crossfade
+
+A transition with `interrupt: true` may start while a crossfade is running, for example a jump or a hit that must not wait for a slow blend. The state that was fading in starts fading out from the weight it had reached, together with the shares of the states still fading out, so the pose does not pop; the new state fades in over its own `duration`. Weights keep summing to 1. At most 4 states fade out at once (`maximumFadingStates`); a longer chain drops the oldest and renormalizes the rest. A transition without `interrupt` still waits.
+
+## Root motion
+
+`rootMotion: { bone, layer, facing, scale }` takes the horizontal travel of the root bone out of the clips. The bone is the target of a `translation` track, such as the armature or hips. The graph reads those clips in place (the bone keeps its height but stays at its first-frame x and z, so `graph.poseLayers()` no longer slides the model) and `graph.rootMotion` says how far the root travelled in the last `advance`:
+
+```js
+graph.rootMotion; // { delta: [x, z], distance, speed } in metres; x is to the right, negative z is forward
+```
+
+The travel follows the blend: each clip's travel over the phase step it played, weighted like its pose, so a blend space walks at the speed its clips blend to. `layer` is the layer whose clips carry it (default: the first); its weight scales the result. `facing` is the way the rig faces at rest, `'+z'` (default, glTF) or `'-z'`, and `scale` converts clip units to metres (`0.01` for centimetres). Without the option `graph.rootMotion` throws. `extractRootMotion(clip, { bone, facing, scale })` does the same for one clip: it returns `{ clip, hasMotion, displacement(cycles, loops) }`.
+
+Hand it to the [player](player.md) controller, which then moves by it on the ground instead of by its own speed, and put the graph after the controller so the controller reads the travel of the previous step:
+
+```js
+const controller = createCharacterController({ input, yaw: Math.PI, rootMotion: () => graph.rootMotion.delta });
+const parameterSystem = {
+ name: 'animation-parameters',
+ fixedUpdate() { graph.set('speed', controller.state.intentSpeed); }, // what the player asks for, not the speed it has
+};
+// systems: [input, controller, parameterSystem, graph.system()]
+```
+
+The controller turns the travel by its yaw. It faces -Z at yaw 0 while a glTF model faces +Z, so start it at `yaw: Math.PI` or turn the model's node. In the air the controller falls back to its own velocity, and vertical motion always stays with the controller.
+
+## IK hooks
+
+`createFootPlacement` and `createLookAt` build entries for the `ik` list of `createSkeletonPose` and `createAssetPose`. They read the game through a function, ease toward it with the pose time, and are deterministic.
+
+```js
+const pose = createAssetPose(character, {
+ layers: graph.poseLayers(),
+ ik: [
+ createFootPlacement({ root: 'UpperLegL', middle: 'LowerLegL', end: 'FootL', groundOffset: foot => heightAt(foot) - baseHeight }),
+ createLookAt({ joints: ['Neck', 'Head'], target: () => targetPosition, maxAngle: 60, weight: () => graph.get('alert') }),
+ ],
+});
+```
+
+- `createFootPlacement({ root, middle, end, groundOffset, ankleHeight, liftHeight, maxAdjust, smoothSeconds, weight, pole, bendToward, groundNormal })`: `groundOffset(footPosition)` returns how far the ground under the animated foot is above (positive) or below the ground the clip was made for. A planted foot (near `ankleHeight`, within `liftHeight`, default 0.15) follows it by at most `maxAdjust` (default 0.4); a swinging foot is left alone. `smoothSeconds` (default 0.06) eases the correction.
+- `createLookAt({ joints, target, forward, worldForward, maxAngle, smoothSeconds, weight })`: turns the chain from its base to the aiming joint toward a point or a function `(time, current) => [x, y, z]`, by at most `maxAngle` degrees (default 70) from the animated direction.
+
+`weight` is a number or a function of the pose time from 0 to 1, so a graph parameter can fade a hook in and out. The positions are in the pose's space: the skeleton pose's model space, or the world space of the asset for `createAssetPose`.
+
+## Other rigs
+
+The graph knows no rig, so a creature or a machine runs the same way. The tests drive a quadruped (root, body, neck, head and four legs) and the car from the repo's test assets (wheels spinning while the body travels) through the same graph, root motion and IK hooks.
+
## Limits and errors
-At most 64 parameters, 8 layers, 64 states and 256 transitions per layer, 8 conditions per transition and 16 motions per blend space. Errors name the field and the fix, for example `createAnimationGraph layers[0].transitions[1].to names "run", which is not a state of this layer. States: idle, move.`
+At most 64 parameters, 8 layers, 64 states and 256 transitions per layer, 8 conditions per transition, 16 motions per blend space and 4 states fading out at once. Errors name the field and the fix, for example `createAnimationGraph layers[0].transitions[1].to names "run", which is not a state of this layer. States: idle, move.`
+
-Not part of this addon yet: root motion, IK hooks (use the `ik` option of the skeleton pose), and path-driven NPC speed. An NPC sets `speed` from its path follower, such as the navmesh, through the same `graph.set`.
+Path-driven NPC speed is not a separate feature: an NPC sets `speed` from its path follower, such as the navmesh, through the same `graph.set`.
diff --git a/docs/player.md b/docs/player.md
index 4fcc3a87..c3026595 100644
--- a/docs/player.md
+++ b/docs/player.md
@@ -43,10 +43,11 @@ Order the systems input, controller, rig. The controller reads this step's input
| `position`, `yaw` | origin, 0 | Start pose. Yaw 0 faces -Z, positive turns toward +X |
| `faceCamera`, `turnSpeed` | false, 12 | Face the view yaw (first person) or turn toward the move direction |
| `node` | none | An object with `position` (and `rotationY`) that is written every step |
+| `rootMotion` | none | A function `() => [x, z]` with the travel of the last animation step, such as `() => graph.rootMotion.delta` ([animation graph](animation-graph.md#root-motion)). On the ground the body moves by it instead of by its speed; x is to its right, negative z forward |
| `mover` | kinematic | The seam for physics, see below |
| `name` | `player` | System name, for `replaceSystem` |
-`controller.state` is updated in place for animation and audio: `position`, `previousPosition`, `velocity`, `yaw`, `grounded`, `airborne`, `speed` (horizontal) and `running`. `controller.positionAt(alpha)` returns the position drawn between the last two fixed steps, and `teleport(position, yaw)` places it again.
+`controller.state` is updated in place for animation and audio: `position`, `previousPosition`, `velocity`, `yaw`, `grounded`, `airborne`, `speed` (horizontal), `intentSpeed` (the speed the input asks for) and `running`. `controller.positionAt(alpha)` returns the position drawn between the last two fixed steps, and `teleport(position, yaw)` places it again.
### Collide and slide
diff --git a/src/animation-graph.js b/src/animation-graph.js
index e4a9352e..e20efd24 100644
--- a/src/animation-graph.js
+++ b/src/animation-graph.js
@@ -3,8 +3,13 @@
// advances in fixed steps and says which clip plays at which time and weight. It knows no rig: `poseLayers()` hands the
// result to createSkeletonPose / createAssetPose, and any retargeted clip can be a motion. Same parameters and the same
// steps always give the same weights. See docs/animation-graph.md.
+import { extractRootMotion, normalizeRootMotionSettings } from './animation-root-motion.js';
+
+export { createFootPlacement, createLookAt } from './animation-ik.js';
+export { extractRootMotion } from './animation-root-motion.js';
export const ANIMATION_GRAPH_LIMITS = Object.freeze({
+ maximumFadingStates: 4,
maximumParameters: 64,
maximumLayers: 8,
maximumStates: 64,
@@ -59,14 +64,22 @@ function requireFiniteNumber(value, label, minimum = -Infinity, maximum = Infini
return value;
}
-function compileClips(clips) {
+// With root motion, `clip` is the in-place copy that poses read and `rootMotion` carries the travel taken out of it.
+function compileClips(clips, rootMotion) {
requireObject(clips, 'createAnimationGraph clips');
const table = new Map();
for (const [name, clip] of Object.entries(clips)) {
const label = `createAnimationGraph clips.${name}`;
requireObject(clip, label);
requireFiniteNumber(clip.duration, `${label}.duration`, 1e-6);
- table.set(name, { name, clip, duration: clip.duration, loop: clip.loop === true });
+ const extracted = rootMotion && Array.isArray(clip.tracks) ? extractRootMotion(clip, rootMotion) : null;
+ table.set(name, {
+ name,
+ clip: extracted ? extracted.clip : clip,
+ duration: clip.duration,
+ loop: clip.loop === true,
+ rootMotion: extracted?.hasMotion ? extracted : null,
+ });
}
return table;
}
@@ -217,6 +230,11 @@ function compileCondition(condition, label, parameters) {
return { parameter, test: (value, limit) => value === limit, limit: expected };
}
+function interruptOf(value, label) {
+ if (value !== undefined && typeof value !== 'boolean') throw new TypeError(`${label}.interrupt must be true or false, got ${describe(value)}.`);
+ return value === true;
+}
+
function compileTransition(definition, label, states, parameters) {
requireObject(definition, label);
const from = definition.from ?? '*';
@@ -235,6 +253,7 @@ function compileTransition(definition, label, states, parameters) {
to,
duration: requireFiniteNumber(definition.duration ?? 0, `${label}.duration`, 0, ANIMATION_GRAPH_LIMITS.maximumFadeSeconds),
exitPhase,
+ interrupt: interruptOf(definition.interrupt, label),
conditions: conditions.map((condition, index) => compileCondition(condition, `${label}.when[${index}]`, parameters)),
};
}
@@ -337,7 +356,7 @@ function writeBlend2DWeights(state, x, y, weights) {
}
function createStateRuntime(state) {
- return { state, phase: 0, frozen: false, weights: new Float64Array(state.motions.length) };
+ return { state, phase: 0, previousPhase: 0, frozen: false, weights: new Float64Array(state.motions.length) };
}
function stateSpeed(runtime, parameters) {
@@ -351,9 +370,26 @@ function advanceStateRuntime(runtime, parameters, deltaSeconds) {
if (!runtime.frozen) writeMotionWeights(state, parameters, weights);
let duration = 0;
for (let index = 0; index < weights.length; index++) duration += weights[index] * state.motions[index].clip.duration;
+ runtime.previousPhase = runtime.phase;
runtime.phase += deltaSeconds * stateSpeed(runtime, parameters) / duration;
}
+// Adds the weighted root travel of one state over the last step to `total` ([x, z]).
+function addRootTravel(runtime, stateWeight, total) {
+ const { state, weights, phase, previousPhase } = runtime;
+ state.motions.forEach((motion, index) => {
+ const share = stateWeight * weights[index];
+ const rootMotion = motion.clip.rootMotion;
+ if (share <= 0 || !rootMotion) return;
+ const after = rootMotion.displacement(phase, state.loop);
+ const afterX = after[0];
+ const afterZ = after[1];
+ const before = rootMotion.displacement(previousPhase, state.loop);
+ total[0] += share * (afterX - before[0]);
+ total[1] += share * (afterZ - before[1]);
+ });
+}
+
function motionTime(runtime, motion) {
const { phase, state } = runtime;
const cycle = state.loop ? phase - Math.floor(phase) : Math.min(phase, 1);
@@ -370,45 +406,60 @@ function createLayerRuntime(layer, parameters) {
layer,
weight: layer.initialWeight,
current: null,
- previous: null,
+ // States fading out, oldest first, each with the share `base` it had when the running crossfade began. Their shares and
+ // the incoming state's always sum to 1; an interrupting transition adds the state it interrupts.
+ fading: [],
fadeElapsed: 0,
fadeDuration: 0,
+ rootTravel: [0, 0],
};
function begin() {
runtime.current = createStateRuntime(layer.states.get(layer.initial));
- runtime.previous = null;
+ runtime.fading = [];
runtime.fadeElapsed = 0;
runtime.fadeDuration = 0;
+ runtime.rootTravel = [0, 0];
runtime.weight = layer.initialWeight;
writeMotionWeights(runtime.current.state, parameters, runtime.current.weights);
}
function fadeProgress() {
- return runtime.previous ? Math.min(1, runtime.fadeElapsed / runtime.fadeDuration) : 1;
+ return runtime.fading.length ? Math.min(1, runtime.fadeElapsed / runtime.fadeDuration) : 1;
+ }
+
+ // The outgoing blend keeps the weights it had, so a parameter change does not bend the fade.
+ function fadeOutCurrent(duration) {
+ const progress = fadeProgress();
+ for (const entry of runtime.fading) entry.base *= 1 - progress;
+ runtime.current.frozen = true;
+ runtime.fading.push({ stateRuntime: runtime.current, base: progress });
+ runtime.fading = runtime.fading.filter(entry => entry.base > 0);
+ if (runtime.fading.length > ANIMATION_GRAPH_LIMITS.maximumFadingStates) runtime.fading.shift();
+ const total = runtime.fading.reduce((sum, entry) => sum + entry.base, 0);
+ for (const entry of runtime.fading) entry.base /= total;
+ runtime.fadeElapsed = 0;
+ runtime.fadeDuration = duration;
}
function startTransition() {
const name = runtime.current.state.name;
- const transition = layer.transitions.find(candidate => (candidate.from === '*' || candidate.from === name) && candidate.to !== name && conditionsHold(candidate, runtime.current));
+ const fading = runtime.fading.length > 0;
+ const transition = layer.transitions.find(candidate => (!fading || candidate.interrupt) && (candidate.from === '*' || candidate.from === name) && candidate.to !== name && conditionsHold(candidate, runtime.current));
if (!transition) return;
for (const condition of transition.conditions) {
if (condition.parameter.type === 'trigger') condition.parameter.value = false;
}
const next = createStateRuntime(layer.states.get(transition.to));
- if (transition.duration > 0) {
- runtime.previous = runtime.current;
- runtime.previous.frozen = true; // The outgoing blend keeps the weights it had, so a parameter change does not bend the fade.
- runtime.fadeElapsed = 0;
- runtime.fadeDuration = transition.duration;
- }
+ if (transition.duration > 0) fadeOutCurrent(transition.duration);
+ else runtime.fading = [];
runtime.current = next;
}
function collect() {
for (const slot of layer.slots) slot.weight = 0;
const progress = fadeProgress();
- const contributors = runtime.previous ? [[runtime.previous, 1 - progress], [runtime.current, progress]] : [[runtime.current, 1]];
+ const contributors = [...runtime.fading.map(entry => [entry.stateRuntime, entry.base * (1 - progress)]), [runtime.current, progress]];
for (const [stateRuntime, stateWeight] of contributors) {
stateRuntime.state.motions.forEach((motion, index) => {
const contribution = stateWeight * stateRuntime.weights[index];
@@ -442,18 +493,26 @@ function createLayerRuntime(layer, parameters) {
collect();
},
advance(deltaSeconds) {
- if (!runtime.previous) startTransition();
+ startTransition();
advanceStateRuntime(runtime.current, parameters, deltaSeconds);
- if (runtime.previous) {
- advanceStateRuntime(runtime.previous, parameters, deltaSeconds);
- runtime.fadeElapsed += deltaSeconds;
- if (runtime.fadeElapsed >= runtime.fadeDuration - FADE_EPSILON) {
- runtime.previous = null;
- runtime.fadeElapsed = 0;
- }
+ for (const entry of runtime.fading) advanceStateRuntime(entry.stateRuntime, parameters, deltaSeconds);
+ runtime.fadeElapsed += deltaSeconds;
+ if (layer.followsRootMotion) {
+ const progress = fadeProgress();
+ runtime.rootTravel = [0, 0];
+ for (const entry of runtime.fading) addRootTravel(entry.stateRuntime, entry.base * (1 - progress), runtime.rootTravel);
+ addRootTravel(runtime.current, progress, runtime.rootTravel);
+ }
+ if (runtime.fading.length && runtime.fadeElapsed >= runtime.fadeDuration - FADE_EPSILON) {
+ runtime.fading = [];
+ runtime.fadeElapsed = 0;
}
collect();
},
+ // Root travel of the last step, [x, z] in metres, scaled by the layer weight.
+ rootTravel() {
+ return [runtime.rootTravel[0] * runtime.weight, runtime.rootTravel[1] * runtime.weight];
+ },
setWeight(weight) {
runtime.weight = weight;
writePoseWeights();
@@ -461,8 +520,8 @@ function createLayerRuntime(layer, parameters) {
describe() {
return {
state: runtime.current.state.name,
- previousState: runtime.previous ? runtime.previous.state.name : null,
- fade: runtime.previous ? fadeProgress() : null,
+ previousState: runtime.fading.length ? runtime.fading[runtime.fading.length - 1].stateRuntime.state.name : null,
+ fade: runtime.fading.length ? fadeProgress() : null,
phase: runtime.current.phase,
weight: runtime.weight,
clips: layer.slots.filter(slot => slot.weight > 0).map(slot => ({ clip: slot.clip.name, time: slot.time, weight: slot.weight })),
@@ -471,6 +530,25 @@ function createLayerRuntime(layer, parameters) {
};
}
+const NO_ROOT_MOTION = Object.freeze({ delta: Object.freeze([0, 0]), distance: 0, speed: 0 });
+
+function describeRootMotion(travel, deltaSeconds) {
+ const distance = Math.hypot(travel[0], travel[1]);
+ return Object.freeze({ delta: Object.freeze(travel), distance, speed: deltaSeconds > 0 ? distance / deltaSeconds : 0 });
+}
+
+// The layer whose travel becomes the root motion: the named one, else the first. Fails when no clip carries the bone's translation.
+function chooseRootMotionLayer(settings, layers, clips) {
+ const layer = settings.layer === undefined ? layers[0] : layers.find(candidate => candidate.name === settings.layer);
+ if (!layer) {
+ throw new RangeError(`createAnimationGraph rootMotion.layer names "${String(settings.layer)}", which is not a layer. Layers: ${layers.map(candidate => candidate.name).join(', ')}.`);
+ }
+ if (![...clips.values()].some(clip => clip.rootMotion)) {
+ throw new RangeError(`createAnimationGraph rootMotion.bone "${settings.bone}" has no translation track in any clip. Name the bone that the clips move, as the track target.`);
+ }
+ return layer;
+}
+
/**
* Build a graph from { clips, parameters, boneGroups, layers }. `clips` maps a name to a clip (`createAnimationClip`,
* `clipFromGltfAnimation` or `retargetClip` output; only `duration` and `loop` are read). `parameters` maps a name to
@@ -479,7 +557,8 @@ function createLayerRuntime(layer, parameters) {
*/
export function createAnimationGraph(definition) {
requireObject(definition, 'createAnimationGraph definition');
- const clips = compileClips(definition.clips ?? {});
+ const rootMotionSettings = definition.rootMotion === undefined ? null : normalizeRootMotionSettings(definition.rootMotion, 'createAnimationGraph rootMotion');
+ const clips = compileClips(definition.clips ?? {}, rootMotionSettings);
const parameters = compileParameters(definition.parameters ?? {});
const boneGroups = requireObject(definition.boneGroups ?? {}, 'createAnimationGraph boneGroups');
const layerDefinitions = requireArray(definition.layers, 'createAnimationGraph layers', ANIMATION_GRAPH_LIMITS.maximumLayers);
@@ -489,8 +568,11 @@ export function createAnimationGraph(definition) {
if (layerNames.has(layer.name)) throw new RangeError(`createAnimationGraph has two layers named "${layer.name}". Rename one.`);
layerNames.add(layer.name);
}
+ const rootMotionLayer = rootMotionSettings ? chooseRootMotionLayer(rootMotionSettings, layers, clips) : null;
+ for (const layer of layers) layer.followsRootMotion = layer === rootMotionLayer;
const runtimes = layers.map(layer => createLayerRuntime(layer, parameters));
let elapsedSeconds = 0;
+ let lastRootMotion = NO_ROOT_MOTION;
function runtimeOf(name) {
const index = layers.findIndex(layer => layer.name === name);
@@ -502,6 +584,13 @@ export function createAnimationGraph(definition) {
get layers() { return layers.map(layer => layer.name); },
get time() { return elapsedSeconds; },
+ // Root travel of the last advance as { delta: [x, z], distance, speed } in metres: x to the right, negative z forward (the
+ // player's convention), scaled by the layer weight. Needs the rootMotion option.
+ get rootMotion() {
+ if (!rootMotionSettings) throw new TypeError('graph.rootMotion needs the rootMotion option, for example createAnimationGraph({ rootMotion: { bone: "Root" }, ... }).');
+ return lastRootMotion;
+ },
+
// Sets a number or boolean parameter. Read by the transitions and blend spaces on the next advance.
set(name, value) {
const parameter = parameterOf(parameters, name, 'graph.set name');
@@ -542,6 +631,7 @@ export function createAnimationGraph(definition) {
requireFiniteNumber(deltaSeconds, 'graph.advance deltaSeconds', 0, ANIMATION_GRAPH_LIMITS.maximumDeltaSeconds);
for (const runtime of runtimes) runtime.advance(deltaSeconds);
elapsedSeconds += deltaSeconds;
+ if (rootMotionLayer) lastRootMotion = describeRootMotion(runtimes[layers.indexOf(rootMotionLayer)].rootTravel(), deltaSeconds);
return graph;
},
@@ -550,6 +640,7 @@ export function createAnimationGraph(definition) {
for (const parameter of parameters.values()) parameter.value = parameter.initial;
for (const runtime of runtimes) runtime.begin();
elapsedSeconds = 0;
+ lastRootMotion = NO_ROOT_MOTION;
return graph;
},
diff --git a/src/animation-ik.js b/src/animation-ik.js
new file mode 100644
index 00000000..6527b84c
--- /dev/null
+++ b/src/animation-ik.js
@@ -0,0 +1,102 @@
+// IK hooks for the animation graph: ready-made solver definitions for the `ik` list of createSkeletonPose / createAssetPose.
+// Both read the live game through a function and ease toward what they read, using the pose time and no clock, so the same
+// sequence of times gives the same pose. `createFootPlacement` keeps a planted foot on uneven ground; `createLookAt` turns a
+// head or a chain of bones toward a point.
+
+const SMOOTH_SNAP_SECONDS = 1;
+
+function numberIn(owner, label, value, fallback, minimum, maximum) {
+ const resolved = value ?? fallback;
+ if (!Number.isFinite(resolved) || resolved < minimum || resolved > maximum) {
+ throw new RangeError(`${owner} ${label} must be a number from ${minimum} to ${maximum}, got ${String(resolved)}.`);
+ }
+ return resolved;
+}
+
+// Exponential approach with a time constant, driven by the pose time. The first call, a jump back in time and a long gap snap to the goal.
+function createSmoother(smoothSeconds) {
+ let lastTime = null;
+ return function amount(time) {
+ const elapsed = lastTime === null ? Infinity : time - lastTime;
+ if (elapsed === 0) return 0;
+ lastTime = time;
+ if (smoothSeconds === 0 || elapsed < 0 || elapsed > SMOOTH_SNAP_SECONDS) return 1;
+ return 1 - Math.exp(-elapsed / smoothSeconds);
+ };
+}
+
+/**
+ * A two-bone solver that keeps a planted foot on uneven ground. `groundOffset(footPosition)` says how far the ground under
+ * that foot sits above (positive) or below the ground the clip was made for, in the pose's units; it receives the animated
+ * foot position and returns a number. Only a foot near the ground follows it: the correction fades out over `liftHeight`
+ * above `ankleHeight`, so a swinging foot is not pulled down. The correction is limited to `maxAdjust` and eased over
+ * `smoothSeconds`. Pass the result in the `ik` list of the pose; give `weight` a function to fade it with a graph parameter.
+ */
+export function createFootPlacement(options = {}) {
+ const owner = 'createFootPlacement';
+ for (const [field, role] of [['root', 'hip'], ['middle', 'knee'], ['end', 'ankle']]) {
+ if (options[field] === undefined) throw new TypeError(`${owner} needs ${field}: the joint name of the leg's ${role}.`);
+ }
+ const { groundOffset } = options;
+ if (typeof groundOffset !== 'function') {
+ throw new TypeError(`${owner} groundOffset must be a function (footPosition) => ground height change in metres, such as foot => terrain(foot[0], foot[2]) - baseHeight, got ${groundOffset === null ? 'null' : typeof groundOffset}.`);
+ }
+ const ankleHeight = numberIn(owner, 'ankleHeight', options.ankleHeight, 0, -1000, 1000);
+ const liftHeight = numberIn(owner, 'liftHeight', options.liftHeight, 0.15, 1e-6, 1000);
+ const maxAdjust = numberIn(owner, 'maxAdjust', options.maxAdjust, 0.4, 0, 1000);
+ const smoothSeconds = numberIn(owner, 'smoothSeconds', options.smoothSeconds, 0.06, 0, 10);
+ const smoothingAmount = createSmoother(smoothSeconds);
+ let correction = 0;
+
+ function target(time, foot) {
+ const offset = groundOffset([foot[0], foot[1], foot[2]]);
+ if (!Number.isFinite(offset)) throw new RangeError(`${owner} groundOffset must return a finite number, got ${String(offset)}.`);
+ const clamped = Math.max(-maxAdjust, Math.min(maxAdjust, offset));
+ const lift = Math.min(1, Math.max(0, (foot[1] - ankleHeight) / liftHeight));
+ const planted = 1 - lift * lift * (3 - 2 * lift);
+ correction += (clamped * planted - correction) * smoothingAmount(time);
+ return [foot[0], foot[1] + correction, foot[2]];
+ }
+
+ const solver = { type: 'two-bone', root: options.root, middle: options.middle, end: options.end, target, weight: options.weight ?? 1 };
+ for (const field of ['pole', 'bendToward', 'groundNormal', 'limits', 'keepEndRotation']) {
+ if (options[field] !== undefined) solver[field] = options[field];
+ }
+ return solver;
+}
+
+/**
+ * An aim solver that turns `joints` (listed from the base of the chain to the aiming joint, such as ['neck', 'head']) toward
+ * `target`, a point [x, y, z] or a function (time, current) => point. The turn stops at `maxAngle` degrees from the rest
+ * direction and the target is eased over `smoothSeconds`. `forward` is the aiming joint's own forward axis, or give
+ * `worldForward` for the way the character faces at rest.
+ */
+export function createLookAt(options = {}) {
+ const owner = 'createLookAt';
+ if (!Array.isArray(options.joints) || options.joints.length === 0) {
+ throw new TypeError(`${owner} needs joints: bone names from the base of the chain to the aiming joint, such as ["neck", "head"].`);
+ }
+ const isPoint = Array.isArray(options.target) && options.target.length === 3 && options.target.every(Number.isFinite);
+ if (!isPoint && typeof options.target !== 'function') {
+ throw new TypeError(`${owner} target must be a point [x, y, z] or a function (time, current) => [x, y, z].`);
+ }
+ const maxAngle = numberIn(owner, 'maxAngle', options.maxAngle, 70, 1e-6, 180);
+ const smoothSeconds = numberIn(owner, 'smoothSeconds', options.smoothSeconds, 0.1, 0, 10);
+ const smoothingAmount = createSmoother(smoothSeconds);
+ const smoothed = [0, 0, 0];
+
+ function target(time, current) {
+ const goal = isPoint ? options.target : options.target(time, current);
+ if (!Array.isArray(goal) || goal.length !== 3 || !goal.every(Number.isFinite)) {
+ throw new RangeError(`${owner} target must return three finite numbers, got ${JSON.stringify(goal)}.`);
+ }
+ const amount = smoothingAmount(time);
+ for (let axis = 0; axis < 3; axis++) smoothed[axis] += (goal[axis] - smoothed[axis]) * amount;
+ return [smoothed[0], smoothed[1], smoothed[2]];
+ }
+
+ const solver = { type: 'aim', joints: options.joints, maxAngle, target, weight: options.weight ?? 1 };
+ if (options.forward !== undefined) solver.forward = options.forward;
+ if (options.worldForward !== undefined) solver.worldForward = options.worldForward;
+ return solver;
+}
diff --git a/src/animation-root-motion.js b/src/animation-root-motion.js
new file mode 100644
index 00000000..e71cf16a
--- /dev/null
+++ b/src/animation-root-motion.js
@@ -0,0 +1,75 @@
+// Root motion: the horizontal travel baked into a clip's root bone, taken out of the clip so the player controller can
+// apply it to the body instead of the feet sliding. `extractRootMotion` returns an in-place copy of the clip (the root
+// bone keeps its height but stays at its first-frame x and z) and a `displacement` function that says how far the root
+// had travelled after a number of cycles. Results use the player's convention: x to the right, negative z forward.
+import { sampleAnimationClip } from './animation.js';
+
+export const ROOT_MOTION_LIMITS = Object.freeze({ minimumScale: 1e-6, maximumScale: 1e6 });
+export const ROOT_MOTION_FACINGS = Object.freeze(['+z', '-z']);
+
+const NO_DISPLACEMENT = Object.freeze([0, 0]);
+
+/**
+ * Validate and normalize a rootMotion option: { bone, layer, facing, scale }. `facing` is the way the rig faces at rest
+ * ('+z' for glTF, '-z' for the player's own convention) and `scale` converts the clip's units to metres.
+ */
+export function normalizeRootMotionSettings(definition, label) {
+ if (definition === null || typeof definition !== 'object' || Array.isArray(definition)) {
+ throw new TypeError(`${label} must be an object like { bone: "Root" }, got ${definition === null ? 'null' : typeof definition}.`);
+ }
+ if (typeof definition.bone !== 'string' || !definition.bone.trim()) {
+ throw new TypeError(`${label}.bone must be the name of the root bone whose translation track carries the motion, such as "Root".`);
+ }
+ const facing = definition.facing ?? '+z';
+ if (!ROOT_MOTION_FACINGS.includes(facing)) {
+ throw new RangeError(`${label}.facing must be "+z" or "-z" (the way the rig faces at rest; glTF rigs face "+z"), got ${JSON.stringify(facing)}.`);
+ }
+ const scale = definition.scale ?? 1;
+ const { minimumScale, maximumScale } = ROOT_MOTION_LIMITS;
+ if (!Number.isFinite(scale) || scale < minimumScale || scale > maximumScale) {
+ throw new RangeError(`${label}.scale must be a number from ${minimumScale} to ${maximumScale} (clip units to metres, 0.01 for a rig in centimetres), got ${String(scale)}.`);
+ }
+ return { bone: definition.bone, layer: definition.layer, facing, scale };
+}
+
+function withFlatKeyframes(track) {
+ const restX = track.keyframes[0].value[0];
+ const restZ = track.keyframes[0].value[2];
+ const keyframes = track.keyframes.map(keyframe => {
+ const flat = { ...keyframe, value: [restX, keyframe.value[1], restZ] };
+ if (keyframe.inTangent) flat.inTangent = [0, keyframe.inTangent[1], 0];
+ if (keyframe.outTangent) flat.outTangent = [0, keyframe.outTangent[1], 0];
+ return Object.freeze(flat);
+ });
+ return Object.freeze({ ...track, keyframes: Object.freeze(keyframes) });
+}
+
+/**
+ * Split a clip into an in-place clip and the root bone's horizontal travel. A clip without a translation track on `bone`
+ * comes back unchanged with `hasMotion: false`. `displacement(cycles, loops)` is the travel since the first frame after
+ * `cycles` plays of the clip, as [x, z] in metres; with `loops` false it stops at the last frame. The returned array is
+ * reused by the next call.
+ */
+export function extractRootMotion(clip, settings) {
+ const { bone, facing, scale } = settings;
+ const track = clip.tracks.find(candidate => candidate.target === bone && candidate.property === 'translation');
+ if (!track) return { clip, hasMotion: false, displacement: () => NO_DISPLACEMENT };
+ // Looping is handled by displacement itself, so the end of the clip is sampled as its last frame and not wrapped to the first.
+ const sampler = Object.freeze({ duration: clip.duration, loop: false, tracks: Object.freeze([track]) });
+ const first = track.keyframes[0].value;
+ const last = track.keyframes[track.keyframes.length - 1].value;
+ const flip = facing === '+z' ? -1 : 1;
+ const output = [0, 0];
+
+ function displacement(cycles, loops = clip.loop) {
+ const wholeCycles = loops ? Math.floor(cycles) : 0;
+ const fraction = loops ? cycles - wholeCycles : Math.min(Math.max(cycles, 0), 1);
+ const sampled = sampleAnimationClip(sampler, fraction * clip.duration)[0].value;
+ output[0] = flip * scale * (wholeCycles * (last[0] - first[0]) + sampled[0] - first[0]);
+ output[1] = flip * scale * (wholeCycles * (last[2] - first[2]) + sampled[2] - first[2]);
+ return output;
+ }
+
+ const inPlace = Object.freeze({ ...clip, tracks: Object.freeze(clip.tracks.map(candidate => (candidate === track ? withFlatKeyframes(track) : candidate))) });
+ return { clip: inPlace, hasMotion: true, displacement };
+}
diff --git a/src/player.js b/src/player.js
index 077f27e5..29aed19f 100644
--- a/src/player.js
+++ b/src/player.js
@@ -175,6 +175,10 @@ export function createCharacterController(options = {}) {
jump: options.jump ?? 'jump',
run: options.run ?? 'run',
};
+ const rootMotion = options.rootMotion;
+ if (rootMotion !== undefined && typeof rootMotion !== 'function') {
+ throw new TypeError(`${owner} rootMotion must be a function () => [x, z] giving the travel of the last animation step, such as () => graph.rootMotion.delta, got ${describe(rootMotion)}.`);
+ }
const faceCamera = options.faceCamera ?? false;
const cameraYaw = options.cameraYaw ?? 0;
if (typeof cameraYaw !== 'function' && !Number.isFinite(cameraYaw)) {
@@ -194,6 +198,7 @@ export function createCharacterController(options = {}) {
grounded: false,
airborne: true,
speed: 0,
+ intentSpeed: 0,
running: false,
};
@@ -217,6 +222,17 @@ export function createCharacterController(options = {}) {
state.yaw = wrapAngle(state.yaw + clamp(difference, -maximumTurn, maximumTurn));
}
+ // On the ground the animation moves the body: its travel, turned from the body's frame to the world, replaces the speed-based step.
+ function applyRootMotion(displacement) {
+ const travel = rootMotion();
+ const valid = Array.isArray(travel) && travel.length === 2 && travel.every(Number.isFinite);
+ if (!valid) throw new TypeError(`${owner} rootMotion must return [x, z] as finite numbers, such as graph.rootMotion.delta, got ${JSON.stringify(travel)}.`);
+ const forward = forwardDirection(state.yaw);
+ const right = rightDirection(state.yaw);
+ displacement[0] = right[0] * travel[0] - forward[0] * travel[1];
+ displacement[2] = right[2] * travel[0] - forward[2] * travel[1];
+ }
+
function advance(stepSeconds) {
state.previousPosition = [...state.position];
const sideInput = input.getAxis(names.moveX);
@@ -231,6 +247,7 @@ export function createCharacterController(options = {}) {
const wantedX = (forward[0] * forwardInput + right[0] * sideInput) * intentScale * topSpeed;
const wantedZ = (forward[2] * forwardInput + right[2] * sideInput) * intentScale * topSpeed;
+ state.intentSpeed = Math.hypot(wantedX, wantedZ);
const control = state.grounded ? 1 : settings.airControl;
const maximumChange = settings.acceleration * control * stepSeconds;
const changeX = wantedX - state.velocity[0];
@@ -258,6 +275,7 @@ export function createCharacterController(options = {}) {
grounded: state.grounded,
};
const displacement = state.velocity.map(component => component * stepSeconds);
+ if (rootMotion && state.grounded) applyRootMotion(displacement);
const result = readMoveResult(owner, mover.move(body, displacement, stepSeconds));
state.velocity[0] = (result.position[0] - state.position[0]) / stepSeconds;
state.velocity[2] = (result.position[2] - state.position[2]) / stepSeconds;
diff --git a/tests/animation-root-motion.test.js b/tests/animation-root-motion.test.js
new file mode 100644
index 00000000..ce4b7fa4
--- /dev/null
+++ b/tests/animation-root-motion.test.js
@@ -0,0 +1,394 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { quat, vec3 } from 'gl-matrix';
+import { createAnimationClip, sampleAnimationClip } from '../src/animation.js';
+import { createAnimationGraph, createFootPlacement, createLookAt, extractRootMotion } from '../src/animation-graph.js';
+import { createCharacterController } from '../src/player.js';
+import { parseGltf } from '../src/gltf.js';
+import { createAssetPose, createSkeletonPose } from '../src/skeleton-pose.js';
+import { carAsset } from './fixtures/car-glb.js';
+
+const STEP = 1 / 60;
+const close = (actual, expected, tolerance = 1e-6) => assert.ok(Math.abs(actual - expected) <= tolerance, `${actual} vs ${expected}`);
+
+function rotation(axis, degrees) {
+ return Array.from(quat.setAxisAngle(new Float64Array(4), axis, degrees * Math.PI / 180));
+}
+
+// A clip whose root bone travels `meters` straight along +z (the way glTF rigs face) and bobs 0.1 up in the middle.
+function travelClip(bone, meters, { duration = 1, loop = true, extraTracks = [] } = {}) {
+ return createAnimationClip({
+ duration,
+ loop,
+ tracks: [
+ {
+ target: bone,
+ property: 'translation',
+ keyframes: [
+ { time: 0, value: [0.5, 1, 0.25] },
+ { time: duration / 2, value: [0.5, 1.1, 0.25 + meters / 2] },
+ { time: duration, value: [0.5, 1, 0.25 + meters] },
+ ],
+ },
+ ...extraTracks,
+ ],
+ });
+}
+
+function bendClip(target, degrees, duration = 1) {
+ return createAnimationClip({
+ duration,
+ loop: true,
+ tracks: [{ target, property: 'rotation', keyframes: [{ time: 0, value: rotation([1, 0, 0], 0) }, { time: duration, value: rotation([1, 0, 0], degrees) }] }],
+ });
+}
+
+function stillClip(target, duration = 2) {
+ return createAnimationClip({ duration, loop: true, tracks: [{ target, property: 'rotation', keyframes: [{ time: 0, value: [0, 0, 0, 1] }, { time: duration, value: [0, 0, 0, 1] }] }] });
+}
+
+function locomotion(overrides = {}) {
+ return {
+ rootMotion: { bone: 'Root' },
+ clips: { idle: stillClip('Root'), walk: travelClip('Root', 2) },
+ parameters: { speed: { type: 'number' } },
+ layers: [{
+ name: 'base',
+ states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'idle', threshold: 0 }, { clip: 'walk', threshold: 2.2 }] } }],
+ }],
+ ...overrides,
+ };
+}
+
+function runGraph(graph, seconds) {
+ const total = [0, 0];
+ for (let step = 0; step < Math.round(seconds / STEP); step++) {
+ graph.advance(STEP);
+ total[0] += graph.rootMotion.delta[0];
+ total[1] += graph.rootMotion.delta[1];
+ }
+ return total;
+}
+
+test('extractRootMotion returns the travel in the player convention and an in-place clip', () => {
+ const clip = travelClip('Root', 2);
+ const extracted = extractRootMotion(clip, { bone: 'Root', facing: '+z', scale: 1 });
+ assert.equal(extracted.hasMotion, true);
+ const half = Array.from(extracted.displacement(0.5));
+ close(half[0], 0);
+ close(half[1], -1); // A rig that faces +z travels toward negative z in the player's convention.
+ const loops = Array.from(extracted.displacement(2.5));
+ close(loops[1], -5);
+ const stopped = Array.from(extracted.displacement(2.5, false));
+ close(stopped[1], -2);
+
+ const sampled = sampleAnimationClip(extracted.clip, 0.5)[0].value;
+ close(sampled[0], 0.5);
+ close(sampled[2], 0.25);
+ close(sampled[1], 1.1);
+ assert.equal(extractRootMotion(clip, { bone: 'Root', facing: '-z', scale: 0.5 }).displacement(1)[1], 1);
+});
+
+test('a clip without a translation track on the bone comes back unchanged', () => {
+ const clip = stillClip('Root');
+ const extracted = extractRootMotion(clip, { bone: 'Root', facing: '+z', scale: 1 });
+ assert.equal(extracted.hasMotion, false);
+ assert.equal(extracted.clip, clip);
+ assert.deepEqual(Array.from(extracted.displacement(3)), [0, 0]);
+});
+
+test('the graph reports the root travel of each step, blended by the motion weights', () => {
+ const graph = createAnimationGraph(locomotion());
+ graph.set('speed', 1.1);
+ // Half walk (2 m per cycle) and half idle: the blended duration is 1.5 s, so 3 s plays two cycles.
+ const total = runGraph(graph, 3);
+ close(total[0], 0, 1e-9);
+ close(total[1], -2, 1e-6);
+ const last = graph.rootMotion;
+ assert.ok(last.distance > 0 && last.speed > 0);
+ graph.reset();
+ assert.equal(graph.rootMotion.distance, 0);
+});
+
+test('the pose reads the in-place clips, so the root bone does not slide', () => {
+ const graph = createAnimationGraph(locomotion({ clips: { idle: stillClip('Root'), walk: travelClip('Root', 2) } }));
+ const rig = { joints: [{ name: 'Root', parent: -1, translation: [0.5, 1, 0.25], rotation: [0, 0, 0, 1], scale: [1, 1, 1] }] };
+ const pose = createSkeletonPose({ rig, layers: graph.poseLayers() });
+ graph.set('speed', 2.2);
+ runGraph(graph, 0.75);
+ pose.apply(graph.time);
+ const position = pose.jointWorld('Root').position;
+ close(position[0], 0.5, 1e-6);
+ close(position[2], 0.25, 1e-6);
+});
+
+test('rootMotion mistakes name the field and the fix', () => {
+ assert.throws(() => createAnimationGraph(locomotion({ rootMotion: { bone: 'Hips' } })), /rootMotion\.bone "Hips" has no translation track/);
+ assert.throws(() => createAnimationGraph(locomotion({ rootMotion: {} })), /rootMotion\.bone must be the name of the root bone/);
+ assert.throws(() => createAnimationGraph(locomotion({ rootMotion: { bone: 'Root', facing: 'up' } })), /rootMotion\.facing must be "\+z" or "-z"/);
+ assert.throws(() => createAnimationGraph(locomotion({ rootMotion: { bone: 'Root', scale: 0 } })), /rootMotion\.scale must be a number from/);
+ assert.throws(() => createAnimationGraph(locomotion({ rootMotion: { bone: 'Root', layer: 'nope' } })), /rootMotion\.layer names "nope", which is not a layer\. Layers: base/);
+ const plain = createAnimationGraph({ ...locomotion(), rootMotion: undefined });
+ assert.throws(() => plain.rootMotion, /graph\.rootMotion needs the rootMotion option/);
+});
+
+function fakeInput(forward) {
+ return { getAxis: name => (name === 'moveForward' ? forward.value : 0), isHeld: () => false, wasPressed: () => false };
+}
+
+test('the controller moves by the root motion of the graph instead of its own speed', () => {
+ const graph = createAnimationGraph(locomotion());
+ const forward = { value: 1 };
+ const controller = createCharacterController({ input: fakeInput(forward), walkSpeed: 3, rootMotion: () => graph.rootMotion.delta });
+ for (let step = 0; step < 30; step++) controller.fixedUpdate(STEP);
+ assert.equal(controller.state.grounded, true);
+ const startZ = controller.state.position[2];
+ let travelled = 0;
+ for (let step = 0; step < 120; step++) {
+ controller.fixedUpdate(STEP);
+ graph.set('speed', controller.state.intentSpeed * 2.2 / 3);
+ graph.advance(STEP);
+ travelled += graph.rootMotion.distance;
+ }
+ // Intent is the full walk speed (3), mapped to the walk threshold; the walk clip travels 2 m per second, not 3.
+ const moved = startZ - controller.state.position[2];
+ close(moved, travelled, 0.05);
+ assert.ok(moved > 3.5 && moved < 4.3, `moved ${moved}`);
+ close(controller.state.position[0], 0, 1e-9);
+
+ forward.value = 0;
+ for (let step = 0; step < 30; step++) {
+ controller.fixedUpdate(STEP);
+ graph.set('speed', controller.state.intentSpeed);
+ graph.advance(STEP);
+ }
+ const resting = controller.state.position[2];
+ for (let step = 0; step < 30; step++) {
+ controller.fixedUpdate(STEP);
+ graph.set('speed', controller.state.intentSpeed);
+ graph.advance(STEP);
+ }
+ close(controller.state.position[2], resting, 1e-9);
+});
+
+test('root motion follows the body yaw, and bad input is rejected', () => {
+ const sideways = { rootMotion: () => [1, 0] };
+ const controller = createCharacterController({ input: fakeInput({ value: 0 }), yaw: Math.PI / 2, ...sideways });
+ for (let step = 0; step < 10; step++) controller.fixedUpdate(STEP);
+ // Facing +X, the body's right is +Z.
+ assert.ok(controller.state.position[2] > 0.1);
+ close(controller.state.position[0], 0, 1e-6);
+ assert.throws(() => createCharacterController({ input: fakeInput({ value: 0 }), rootMotion: 5 }), /rootMotion must be a function/);
+ const broken = createCharacterController({ input: fakeInput({ value: 0 }), rootMotion: () => [NaN, 0] });
+ for (let step = 0; step < 30; step++) {
+ try { broken.fixedUpdate(STEP); } catch (error) {
+ assert.match(error.message, /rootMotion must return \[x, z\] as finite numbers/);
+ return;
+ }
+ }
+ assert.fail('a non-finite root motion must throw once the body is grounded');
+});
+
+function crossfadeGraph(extraTransitions = {}) {
+ return createAnimationGraph({
+ clips: { idle: stillClip('spine'), walk: bendClip('spine', 30), run: bendClip('spine', 60, 0.5) },
+ parameters: { toWalk: { type: 'trigger' }, toRun: { type: 'trigger' } },
+ layers: [{
+ name: 'base',
+ states: [{ name: 'idle', clip: 'idle' }, { name: 'walk', clip: 'walk' }, { name: 'run', clip: 'run' }],
+ transitions: [
+ { from: 'idle', to: 'walk', when: [{ parameter: 'toWalk' }], duration: 1 },
+ { from: 'walk', to: 'run', when: [{ parameter: 'toRun' }], duration: 0.5, ...extraTransitions },
+ ],
+ }],
+ });
+}
+
+function weightsOf(graph) {
+ return Object.fromEntries(graph.layerState('base').clips.map(entry => [entry.clip, entry.weight]));
+}
+
+test('an interrupting transition starts during a crossfade from the pose it had reached', () => {
+ const graph = crossfadeGraph({ interrupt: true });
+ graph.trigger('toWalk');
+ for (let step = 0; step < 4; step++) graph.advance(0.1);
+ graph.trigger('toRun');
+ graph.advance(0);
+ assert.equal(graph.layerState('base').state, 'run');
+ assert.equal(graph.layerState('base').previousState, 'walk');
+ const start = weightsOf(graph);
+ close(start.idle, 0.6, 1e-9);
+ close(start.walk, 0.4, 1e-9);
+ assert.equal(start.run, undefined);
+ graph.advance(0.1);
+ const later = weightsOf(graph);
+ close(later.idle, 0.48, 1e-9);
+ close(later.walk, 0.32, 1e-9);
+ close(later.run, 0.2, 1e-9);
+ for (let step = 0; step < 5; step++) graph.advance(0.1);
+ assert.deepEqual(Object.keys(weightsOf(graph)), ['run']);
+ assert.equal(graph.layerState('base').fade, null);
+});
+
+test('without interrupt a transition still waits for the crossfade to end', () => {
+ const graph = crossfadeGraph();
+ graph.trigger('toWalk');
+ for (let step = 0; step < 4; step++) graph.advance(0.1);
+ graph.trigger('toRun');
+ graph.advance(0.1);
+ assert.equal(graph.layerState('base').state, 'walk');
+ for (let step = 0; step < 6; step++) graph.advance(0.1);
+ graph.advance(0.1);
+ assert.equal(graph.layerState('base').state, 'run');
+});
+
+test('a chain of interruptions keeps the weights summing to 1 and the fading states bounded', () => {
+ const states = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
+ const graph = createAnimationGraph({
+ clips: { idle: stillClip('spine'), walk: bendClip('spine', 30) },
+ parameters: { next: { type: 'number' } },
+ layers: [{
+ name: 'base',
+ states: states.map((name, index) => ({ name, clip: index % 2 ? 'walk' : 'idle' })),
+ transitions: states.slice(1).map((name, index) => ({ to: name, when: [{ parameter: 'next', equals: index + 1 }], duration: 1, interrupt: true })),
+ }],
+ });
+ for (let index = 1; index < states.length; index++) {
+ graph.set('next', index);
+ graph.advance(0.1);
+ const total = graph.layerState('base').clips.reduce((sum, entry) => sum + entry.weight, 0);
+ close(total, 1, 1e-9);
+ }
+ assert.equal(graph.layerState('base').state, 'g');
+ assert.throws(() => createAnimationGraph({
+ clips: { idle: stillClip('spine') },
+ layers: [{ name: 'base', states: [{ name: 'a', clip: 'idle' }, { name: 'b', clip: 'idle' }], transitions: [{ to: 'b', exitPhase: 1, interrupt: 'yes' }] }],
+ }), /transitions\[0\]\.interrupt must be true or false/);
+});
+
+// A quadruped: body and head over four legs of hip, knee and paw, with a root bone on the ground.
+function quadrupedRig() {
+ const joints = [];
+ const add = (name, parent, translation) => {
+ joints.push({ name, parent, translation, rotation: [0, 0, 0, 1], scale: [1, 1, 1] });
+ return joints.length - 1;
+ };
+ const root = add('Root', -1, [0, 0, 0]);
+ const body = add('Body', root, [0, 0.9, 0]);
+ const neck = add('Neck', body, [0, 0.2, 0.5]);
+ add('Head', neck, [0, 0.2, 0.2]);
+ for (const [leg, x, z] of [['FL', 0.2, 0.4], ['FR', -0.2, 0.4], ['BL', 0.2, -0.4], ['BR', -0.2, -0.4]]) {
+ const hip = add(`Hip${leg}`, body, [x, 0, z]);
+ const knee = add(`Knee${leg}`, hip, [0, -0.45, 0.02]);
+ add(`Paw${leg}`, knee, [0, -0.45, -0.02]);
+ }
+ return { joints };
+}
+
+function quadrupedGraph() {
+ const gait = createAnimationClip({
+ duration: 0.8,
+ loop: true,
+ tracks: [
+ { target: 'Root', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 0.8, value: [0, 0, 1.6] }] },
+ { target: 'HipFL', property: 'rotation', keyframes: [{ time: 0, value: rotation([1, 0, 0], -20) }, { time: 0.4, value: rotation([1, 0, 0], 20) }, { time: 0.8, value: rotation([1, 0, 0], -20) }] },
+ ],
+ });
+ return createAnimationGraph({
+ rootMotion: { bone: 'Root' },
+ clips: { stand: stillClip('Body'), trot: gait },
+ parameters: { speed: { type: 'number' } },
+ layers: [{ name: 'gait', states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'stand', threshold: 0 }, { clip: 'trot', threshold: 2 }] } }] }],
+ });
+}
+
+test('a quadruped rig runs its own graph with root motion, foot placement and look-at', () => {
+ const graph = quadrupedGraph();
+ const rig = quadrupedRig();
+ const lookTarget = [1.5, 1.4, 2];
+ const foot = createFootPlacement({ root: 'HipBL', middle: 'KneeBL', end: 'PawBL', groundOffset: () => 0.15, ankleHeight: 0 });
+ const look = createLookAt({ joints: ['Neck', 'Head'], forward: [0, 0, 1], target: lookTarget, maxAngle: 40 });
+ const pose = createSkeletonPose({ rig, layers: graph.poseLayers(), ik: [foot, look] });
+ graph.set('speed', 2);
+ const total = runGraph(graph, 0.8);
+ close(total[1], -1.6, 1e-6);
+ pose.apply(graph.time);
+ assert.equal(pose.jointWorld('Root').position[2], 0);
+ assert.ok(pose.ikResults.every(result => Number.isFinite(result.error)));
+ // The planted back-left paw is lifted onto the higher ground.
+ close(pose.jointWorld('PawBL').position[1], 0.15, 1e-3);
+ const headForward = vec3.transformQuat(new Float64Array(3), [0, 0, 1], pose.jointWorld('Head').rotation);
+ assert.ok(headForward[0] > 0.2, `the head turned toward +x: ${headForward}`);
+ const turned = Math.acos(Math.min(1, headForward[2])) * 180 / Math.PI;
+ assert.ok(turned <= 40 + 1e-3, `the turn stays within maxAngle: ${turned}`);
+});
+
+test('foot placement lifts a planted foot, leaves a swinging foot and stays inside maxAdjust', () => {
+ const solver = createFootPlacement({ root: 'a', middle: 'b', end: 'c', groundOffset: () => 1, ankleHeight: 0.1, liftHeight: 0.2, maxAdjust: 0.3, smoothSeconds: 0 });
+ const planted = solver.target(0, [0, 0.1, 0]);
+ close(planted[1], 0.4);
+ const swinging = solver.target(1 / 60, [0, 0.5, 0]);
+ close(swinging[1], 0.5, 1e-9);
+ const eased = createFootPlacement({ root: 'a', middle: 'b', end: 'c', groundOffset: () => 0.2, smoothSeconds: 0.1 });
+ close(eased.target(0, [0, 0, 0])[1], 0.2);
+ const lowered = createFootPlacement({ root: 'a', middle: 'b', end: 'c', groundOffset: foot => (foot[0] > 0 ? 0.2 : 0), smoothSeconds: 0.1 });
+ lowered.target(0, [0, 0, 0]);
+ const partway = lowered.target(0.1, [1, 0, 0])[1];
+ assert.ok(partway > 0.1 && partway < 0.2, `eased partway: ${partway}`);
+});
+
+test('IK hook mistakes name the field and the fix', () => {
+ assert.throws(() => createFootPlacement({ root: 'a', middle: 'b', end: 'c' }), /groundOffset must be a function/);
+ assert.throws(() => createFootPlacement({ middle: 'b', end: 'c', groundOffset: () => 0 }), /needs root: the joint name of the leg's hip/);
+ assert.throws(() => createFootPlacement({ root: 'a', middle: 'b', end: 'c', groundOffset: () => 0, maxAdjust: -1 }), /maxAdjust must be a number from 0 to/);
+ assert.throws(() => createFootPlacement({ root: 'a', middle: 'b', end: 'c', groundOffset: () => NaN }).target(0, [0, 0, 0]), /groundOffset must return a finite number/);
+ assert.throws(() => createLookAt({ target: [0, 0, 0] }), /needs joints/);
+ assert.throws(() => createLookAt({ joints: ['Head'], target: 'camera' }), /target must be a point/);
+ assert.throws(() => createLookAt({ joints: ['Head'], target: [0, 0, 0], maxAngle: 200 }), /maxAngle must be a number from/);
+ assert.throws(() => createLookAt({ joints: ['Head'], target: () => [1, 2] }).target(0, [0, 0, 0]), /target must return three finite numbers/);
+});
+
+test('the same step sequence gives the same IK pose', () => {
+ function runOnce() {
+ const graph = quadrupedGraph();
+ const foot = createFootPlacement({ root: 'HipBL', middle: 'KneeBL', end: 'PawBL', groundOffset: paw => 0.1 * Math.sin(paw[2] * 5) + 0.1 });
+ const pose = createSkeletonPose({ rig: quadrupedRig(), layers: graph.poseLayers(), ik: [foot] });
+ graph.set('speed', 2);
+ const positions = [];
+ for (let step = 0; step < 30; step++) {
+ graph.advance(STEP);
+ pose.apply(graph.time);
+ positions.push(...pose.jointWorld('PawBL').position);
+ }
+ return positions;
+ }
+ assert.deepEqual(runOnce(), runOnce());
+});
+
+test('a machine from the repo assets (the car) runs through the same graph', async () => {
+ const asset = await parseGltf(carAsset());
+ const wheelSpin = (name) => ({ target: name, property: 'rotation', keyframes: [{ time: 0, value: rotation([1, 0, 0], 0) }, { time: 0.5, value: rotation([1, 0, 0], 180) }, { time: 1, value: rotation([1, 0, 0], 359) }] });
+ const drive = createAnimationClip({
+ duration: 1,
+ loop: true,
+ tracks: [
+ { target: 'Car', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [0, 0, 6] }] },
+ wheelSpin('Wheel_FL'),
+ wheelSpin('Wheel_FR'),
+ ],
+ });
+ const graph = createAnimationGraph({
+ rootMotion: { bone: 'Car' },
+ clips: { park: stillClip('Car'), drive },
+ parameters: { throttle: { type: 'number' } },
+ layers: [{ name: 'drive', states: [{ name: 'go', blend: { parameter: 'throttle', motions: [{ clip: 'park', threshold: 0 }, { clip: 'drive', threshold: 1 }] } }] }],
+ });
+ const pose = createAssetPose(asset, { layers: graph.poseLayers() });
+ graph.set('throttle', 1);
+ const total = runGraph(graph, 0.5);
+ close(total[1], -3, 1e-6);
+ pose.apply(graph.time);
+ const wheel = Array.from(pose.jointWorld('Wheel_FL').rotation);
+ assert.ok(Math.abs(wheel[0]) > 0.5, `the wheel turned: ${wheel}`);
+ close(pose.jointWorld('Car').position[2], 0, 1e-6);
+});