Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a live animation state graph addon with blend spaces, crossfades and masked layers (#774)

Nguyen Xuan An9509d442e05e
diff --git a/README.md b/README.md
index 43a5cca3..ae5c138a 100644
--- a/README.md
+++ b/README.md
@@ -140,6 +140,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Physics | `67js/addons/physics` | [Rapier contacts and joints](docs/physics.md) recorded into a timeline |
| Live games | `67js/addons/runtime` | [Game loop](docs/runtime.md) with fixed or variable steps and pluggable systems |
| Live games | `67js/addons/input` | [Input](docs/input.md): keyboard, mouse, gamepad and custom sources mapped to named actions and axes |
+| Live games | `67js/addons/animation-graph` | [Animation graph](docs/animation-graph.md): states, 1D and 2D blend spaces, parameter transitions with crossfades and masked layers for any rig |
| Modeling | `67js/addons/mesh`, `67js/addons/modeling`, `67js/addons/sculpt` | [Mesh editing](docs/mesh.md), [modeling](docs/modeling.md) and [sculpt brushes](https://67js.codepawl.com/sculpt.md) |
| Offline light | `67js/addons/path-tracer`, `67js/addons/light-bake` | [Path-traced stills](https://67js.codepawl.com/path-tracer.md) and [baked lightmaps](https://67js.codepawl.com/light-bake.md) |
| Post passes | `67js/addons/user-pass` | [Your own full-screen GLSL passes](docs/user-passes.md): dither, pixel downscale, quantise |
diff --git a/bench/animation-graph/index.html b/bench/animation-graph/index.html
new file mode 100644
index 00000000..b1d726cd
--- /dev/null
+++ b/bench/animation-graph/index.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Animation graph sample</title>
+<style>
+ html, body { margin: 0; height: 100%; background: #14161a; color: #e8eaed; font: 14px/1.4 system-ui, sans-serif; }
+ canvas { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; }
+ .panel { position: fixed; top: 16px; left: 16px; padding: 12px 14px; border-radius: 10px; background: rgba(20, 22, 26, 0.82); }
+ output { display: block; font-variant-numeric: tabular-nums; white-space: pre; }
+</style>
+</head>
+<body>
+<canvas></canvas>
+<div class="panel"><output id="readout"></output></div>
+<script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/bench/animation-graph/main.js b/bench/animation-graph/main.js
new file mode 100644
index 00000000..debcaeb0
--- /dev/null
+++ b/bench/animation-graph/main.js
@@ -0,0 +1,99 @@
+// Sample for src/animation-graph.js: the CC0 RobotExpressive blends Idle, Walking and Running by speed.
+// 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 { createAnimationGraph } from '/src/animation-graph.js';
+import { createInput, keyboardSource } from '/src/input.js';
+import { createRuntime } from '/src/runtime.js';
+
+const ROBOT_URL = '/tests/fixtures/RobotExpressive.glb';
+const WALK_SPEED = 2.2;
+const RUN_SPEED = 5.5;
+const ACCELERATION = 6; // Speed units per second squared.
+const DEMO_PERIOD_SECONDS = 8;
+const FIXED_RATE = 60;
+
+const query = new URLSearchParams(location.search);
+const pinnedSpeed = query.has('speed') ? Number(query.get('speed')) : null;
+const demo = query.get('demo') === '1';
+
+const response = await fetch(ROBOT_URL);
+const asset = await parseGltf(await response.arrayBuffer(), { maxVertices: 500000 });
+const clips = {};
+for (const name of ['Idle', 'Walking', 'Running']) {
+ const source = asset.animations.find(animation => animation.name === name);
+ clips[name] = clipFromGltfAnimation(source, { loop: true });
+}
+
+const graph = createAnimationGraph({
+ clips,
+ parameters: { speed: { type: 'number' } },
+ layers: [{
+ name: 'locomotion',
+ states: [{
+ name: 'move',
+ blend: {
+ parameter: 'speed',
+ motions: [
+ { clip: 'Idle', threshold: 0 },
+ { clip: 'Walking', threshold: WALK_SPEED },
+ { clip: 'Running', threshold: RUN_SPEED },
+ ],
+ },
+ }],
+ }],
+});
+const pose = createAssetPose(asset, { layers: graph.poseLayers() });
+
+const input = createInput({
+ sources: [keyboardSource()],
+ axes: {
+ forward: ['keyboard/KeyW', 'keyboard/ArrowUp'],
+ sprint: ['keyboard/ShiftLeft', 'keyboard/ShiftRight'],
+ },
+});
+
+// Game logic: turn the keys into a target speed and approach it, then hand the result to the graph as a parameter.
+const locomotionSystem = {
+ name: 'locomotion',
+ speed: 0,
+ targetSpeed() {
+ if (pinnedSpeed !== null) return pinnedSpeed;
+ if (demo) return RUN_SPEED * (0.5 - 0.5 * Math.cos(2 * Math.PI * graph.time / DEMO_PERIOD_SECONDS));
+ if (input.getAxis('forward') <= 0) return 0;
+ return input.getAxis('sprint') > 0 ? RUN_SPEED : WALK_SPEED;
+ },
+ fixedUpdate(stepSeconds) {
+ const difference = this.targetSpeed() - this.speed;
+ const largestChange = ACCELERATION * stepSeconds;
+ this.speed += Math.max(-largestChange, Math.min(largestChange, difference));
+ graph.set('speed', this.speed);
+ },
+};
+
+const canvas = document.querySelector('canvas');
+const renderer = new Renderer67(canvas, asset.parts, { ground: true, hdr: false, samples: 4, memoryBudgetMiB: 512 });
+renderer.resize();
+
+function buildFrame(context) {
+ pose.apply(graph.time);
+ renderer.updateParts(asset.parts);
+ return { eye: [6, 4, 14], target: [0, 2.6, 0], up: [0, 1, 0], fov: 35, near: 0.1, far: 100, time: context.elapsedSeconds };
+}
+
+const runtime = createRuntime(renderer, {
+ mode: 'fixed',
+ fixedRate: FIXED_RATE,
+ frame: buildFrame,
+ systems: [input, locomotionSystem, graph.system()],
+});
+runtime.start();
+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');
+}, 100);
diff --git a/changes/774.md b/changes/774.md
new file mode 100644
index 00000000..43b61874
--- /dev/null
+++ b/changes/774.md
@@ -0,0 +1 @@
+- `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)
diff --git a/docs/animation-graph.md b/docs/animation-graph.md
new file mode 100644
index 00000000..0c39954a
--- /dev/null
+++ b/docs/animation-graph.md
@@ -0,0 +1,101 @@
+# Animation graph: states, blend spaces and layers
+
+`67js/addons/animation-graph` plays clips from live game state. Game logic sets parameters such as `speed` or `grounded`; the graph moves between states, blends clips and says which clip plays at which time and weight. It loads only when imported, adds no dependency and does not touch the film path, where `createAnimationMixer` still plays clips at absolute times.
+
+The graph knows no rig. It reads only `duration` and `loop` from a clip, so a clip from `clipFromGltfAnimation`, `retargetClip` or `createAnimationClip` all work, and one graph can drive any rig whose clips are mapped to it. `graph.poseLayers()` hands the result to `createSkeletonPose` or `createAssetPose` (see [skeleton pose](skeleton-pose.md)), which writes the skin or the node transforms.
+
+```js
+import { createAnimationGraph } from '67js/addons/animation-graph';
+import { createAssetPose } from '67js/addons/skeleton-pose';
+import { createRuntime } from '67js/addons/runtime';
+
+const graph = createAnimationGraph({
+ clips: { Idle, Walking, Running, Wave }, // name -> clip
+ parameters: { speed: { type: 'number' }, wave: { type: 'trigger' } },
+ boneGroups: { upperBody: { joints: ['spine'], exclude: ['head'] } },
+ layers: [
+ {
+ name: 'locomotion',
+ states: [{
+ name: 'move',
+ blend: { parameter: 'speed', motions: [
+ { clip: 'Idle', threshold: 0 }, { clip: 'Walking', threshold: 2.2 }, { clip: 'Running', threshold: 5.5 },
+ ] },
+ }],
+ },
+ {
+ name: 'gesture',
+ mask: 'upperBody',
+ states: [{ name: 'none', clip: 'Idle' }, { name: 'wave', clip: 'Wave' }],
+ transitions: [
+ { from: 'none', to: 'wave', when: [{ parameter: 'wave' }], duration: 0.15 },
+ { from: 'wave', to: 'none', exitPhase: 1, duration: 0.15 },
+ ],
+ },
+ ],
+});
+
+const pose = createAssetPose(character, { layers: graph.poseLayers() });
+const runtime = createRuntime(renderer, {
+ fixedRate: 60,
+ frame: () => { pose.apply(graph.time); renderer.updateParts(character.parts); return camera; },
+ systems: [gameSystem, graph.system()],
+});
+
+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.
+
+## Parameters
+
+`parameters` maps a name to `{ type, initial }`.
+
+| `type` | Set with | Notes |
+| --- | --- | --- |
+| `'number'` | `graph.set(name, number)` | Finite. Default 0. |
+| `'boolean'` | `graph.set(name, true or false)` | Default false. |
+| `'trigger'` | `graph.trigger(name)` | Stays raised until a transition that lists it fires. `graph.resetParameter(name)` clears it. |
+
+`graph.get(name)` reads one. Parameters are read at the next `advance`.
+
+## States and blend spaces
+
+A state is `{ name, clip }` or `{ name, blend }`, plus optional `speed` (play rate, default 1), `speedParameter` (a number parameter that multiplies it, for example to match walking pace to ground speed) and `loop` (default: the clip's `loop`, true for a blend space). A clip that does not loop holds its last frame.
+
+- 1D: `blend: { parameter, motions: [{ clip, threshold }] }`. Weights interpolate linearly between the two nearest thresholds and clamp outside them.
+- 2D: `blend: { parameters: [x, y], motions: [{ clip, position: [x, y] }] }`. Weights use gradient band interpolation: each motion is 1 at its own position, falls to 0 at every other motion, and stays local. Positions must differ.
+
+Weights always sum to 1. All clips of a blend space share one normalized phase, and the phase advances at the blended duration, so walk and run steps stay in sync and the feet do not pop while the speed changes.
+
+## Transitions
+
+`{ from, to, when, exitPhase, duration }`, checked in order, first match wins. `from: '*'` (the default) matches any state.
+
+- `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.
+
+## Layers and masks
+
+Each layer is its own graph with its own states and transitions, over a `mask`: a bone group name from `boneGroups`, or an inline `{ joints, descendants, exclude }` (same shape as the skeleton pose mask; joints are resolved by the pose, by joint or humanoid bone name). `weight` (0 to 1, `graph.setLayerWeight(name, w)`) fades the whole layer in and out. `additive: true` with `reference` (a clip time) adds the layer's change from that pose instead of blending. Layers run in order, later ones over earlier ones.
+
+A clip has one time per layer. When both ends of a crossfade use the same clip, it plays at the incoming state's time.
+
+## Runtime system and determinism
+
+`graph.system({ name, apply })` is a [runtime system](runtime.md): fixed steps call `graph.advance(step)`, and in `'variable'` mode the frame time does. `apply(graph, context)` runs every frame in `'both'` and `'variable'` mode; in `'fixed'` mode do the pose in the runtime `frame` option as above. Put it after the systems that set parameters.
+
+`advance(deltaSeconds)` checks transitions, then moves time, crossfades and weights. The graph reads no clock and no random source, so the same parameter sequence and step sizes always give the same weights and times. `graph.reset()` restores the initial states, parameters and time. Pose layers read the graph's live state, so call `pose.apply` after `advance`; unlike a bare skeleton pose, seeking backward means resetting and replaying.
+
+## Reading the state
+
+`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.
+
+## 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.`
+
+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`.
diff --git a/package.json b/package.json
index 3a073c50..350c717b 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,7 @@
"docs/physics.md",
"docs/runtime.md",
"docs/input.md",
+ "docs/animation-graph.md",
"docs/scene-query.md",
"docs/user-passes.md",
"docs/skeleton-pose.md",
@@ -120,6 +121,7 @@
"./addons/cloth": "./build/cloth.js",
"./addons/runtime": "./build/runtime.js",
"./addons/input": "./build/input.js",
+ "./addons/animation-graph": "./build/animation-graph.js",
"./addons/update-part-vertices": "./build/update-part-vertices.js",
"./package.json": "./package.json"
},
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index c1736dd8..734bb9f9 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -53,7 +53,7 @@ const sourceDocuments = [
'vehicle.md',
'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md', 'path-tracer.md', 'gaussian-splats.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'runtime.md', 'input.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
+ 'runtime.md', 'input.md', 'animation-graph.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/src/animation-graph.js b/src/animation-graph.js
new file mode 100644
index 00000000..e4a9352e
--- /dev/null
+++ b/src/animation-graph.js
@@ -0,0 +1,591 @@
+// Animation state graph for live play: states that hold a clip or a 1D / 2D blend space, transitions that fire on parameter
+// conditions and crossfade, and layers that each run their own graph over a bone group. Game logic sets parameters; the graph
+// 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.
+
+export const ANIMATION_GRAPH_LIMITS = Object.freeze({
+ maximumParameters: 64,
+ maximumLayers: 8,
+ maximumStates: 64,
+ maximumTransitions: 256,
+ maximumConditions: 8,
+ maximumMotions: 16,
+ maximumFadeSeconds: 10,
+ maximumDeltaSeconds: 10,
+});
+
+const PARAMETER_TYPES = ['number', 'boolean', 'trigger'];
+const NUMBER_COMPARATORS = {
+ greater: (value, limit) => value > limit,
+ atLeast: (value, limit) => value >= limit,
+ less: (value, limit) => value < limit,
+ atMost: (value, limit) => value <= limit,
+ equals: (value, limit) => value === limit,
+ notEquals: (value, limit) => value !== limit,
+};
+const FADE_EPSILON = 1e-9;
+
+function describe(value) {
+ return value === null ? 'null' : typeof value;
+}
+
+function requireName(value, label) {
+ if (typeof value !== 'string' || value === '') {
+ throw new TypeError(`${label} must be a non-empty string, got ${describe(value)}.`);
+ }
+ return value;
+}
+
+function requireObject(value, label) {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ throw new TypeError(`${label} must be an object, got ${Array.isArray(value) ? 'array' : describe(value)}.`);
+ }
+ return value;
+}
+
+function requireArray(value, label, maximum) {
+ if (!Array.isArray(value) || value.length === 0 || value.length > maximum) {
+ throw new RangeError(`${label} must be an array of 1 to ${maximum} entries.`);
+ }
+ return value;
+}
+
+function requireFiniteNumber(value, label, minimum = -Infinity, maximum = Infinity) {
+ if (!Number.isFinite(value) || value < minimum || value > maximum) {
+ const range = minimum === -Infinity && maximum === Infinity ? 'a finite number' : `a number from ${minimum} to ${maximum}`;
+ throw new RangeError(`${label} must be ${range}, got ${String(value)}.`);
+ }
+ return value;
+}
+
+function compileClips(clips) {
+ 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 });
+ }
+ return table;
+}
+
+function compileParameters(parameters) {
+ requireObject(parameters, 'createAnimationGraph parameters');
+ const entries = Object.entries(parameters);
+ if (entries.length > ANIMATION_GRAPH_LIMITS.maximumParameters) {
+ throw new RangeError(`createAnimationGraph holds at most ${ANIMATION_GRAPH_LIMITS.maximumParameters} parameters. Merge some.`);
+ }
+ const table = new Map();
+ for (const [name, definition] of entries) {
+ const label = `createAnimationGraph parameters.${name}`;
+ requireObject(definition, label);
+ if (!PARAMETER_TYPES.includes(definition.type)) {
+ throw new TypeError(`${label}.type must be one of ${PARAMETER_TYPES.join(', ')}, got ${String(definition.type)}.`);
+ }
+ let initial = definition.type === 'boolean' ? false : 0;
+ if (definition.type === 'number') initial = requireFiniteNumber(definition.initial ?? 0, `${label}.initial`);
+ if (definition.type === 'boolean') {
+ initial = definition.initial ?? false;
+ if (typeof initial !== 'boolean') throw new TypeError(`${label}.initial must be a boolean, got ${describe(initial)}.`);
+ }
+ if (definition.type === 'trigger') initial = false;
+ table.set(name, { name, type: definition.type, initial, value: initial });
+ }
+ return table;
+}
+
+function parameterOf(parameters, name, label) {
+ const parameter = parameters.get(name);
+ if (!parameter) {
+ throw new RangeError(`${label} names parameter "${String(name)}", which is not declared. Declared: ${[...parameters.keys()].join(', ') || 'none'}.`);
+ }
+ return parameter;
+}
+
+function numberParameterOf(parameters, name, label) {
+ const parameter = parameterOf(parameters, name, label);
+ if (parameter.type !== 'number') throw new TypeError(`${label} needs a number parameter, but "${name}" is a ${parameter.type}.`);
+ return parameter;
+}
+
+function compileMask(mask, boneGroups, label) {
+ if (mask === undefined) return undefined;
+ let definition = mask;
+ if (typeof mask === 'string') {
+ definition = boneGroups[mask];
+ if (!definition) throw new RangeError(`${label} names bone group "${mask}", which is not in boneGroups. Declared: ${Object.keys(boneGroups).join(', ') || 'none'}.`);
+ }
+ requireObject(definition, label);
+ requireArray(definition.joints, `${label}.joints`, 256).forEach((joint, index) => requireName(joint, `${label}.joints[${index}]`));
+ const compiled = { joints: [...definition.joints] };
+ if (definition.descendants !== undefined) compiled.descendants = definition.descendants !== false;
+ if (definition.exclude !== undefined) {
+ compiled.exclude = requireArray(definition.exclude, `${label}.exclude`, 256).map((joint, index) => requireName(joint, `${label}.exclude[${index}]`));
+ }
+ return compiled;
+}
+
+function compileMotion(motion, label, clips) {
+ requireObject(motion, label);
+ const clipName = requireName(motion.clip, `${label}.clip`);
+ const clip = clips.get(clipName);
+ if (!clip) throw new RangeError(`${label}.clip names "${clipName}", which is not in clips. Declared: ${[...clips.keys()].join(', ') || 'none'}.`);
+ return { clip };
+}
+
+function compileBlend1D(blend, label, clips, parameters) {
+ numberParameterOf(parameters, blend.parameter, `${label}.parameter`);
+ const motions = requireArray(blend.motions, `${label}.motions`, ANIMATION_GRAPH_LIMITS.maximumMotions).map((motion, index) => ({
+ ...compileMotion(motion, `${label}.motions[${index}]`, clips),
+ threshold: requireFiniteNumber(motion.threshold, `${label}.motions[${index}].threshold`),
+ }));
+ const sorted = [...motions].sort((first, second) => first.threshold - second.threshold);
+ for (let index = 1; index < sorted.length; index++) {
+ if (sorted[index].threshold === sorted[index - 1].threshold) {
+ throw new RangeError(`${label}.motions has two motions at threshold ${sorted[index].threshold}. Give each its own threshold.`);
+ }
+ }
+ return { kind: 'blend1d', parameterNames: [blend.parameter], motions, sorted };
+}
+
+function compileBlend2D(blend, label, clips, parameters) {
+ if (!Array.isArray(blend.parameters) || blend.parameters.length !== 2) {
+ throw new TypeError(`${label}.parameters must be two number parameter names such as ["strafe", "forward"].`);
+ }
+ blend.parameters.forEach((name, index) => numberParameterOf(parameters, name, `${label}.parameters[${index}]`));
+ const motions = requireArray(blend.motions, `${label}.motions`, ANIMATION_GRAPH_LIMITS.maximumMotions).map((motion, index) => {
+ const position = motion.position;
+ if (!Array.isArray(position) || position.length !== 2) throw new TypeError(`${label}.motions[${index}].position must be [x, y].`);
+ return {
+ ...compileMotion(motion, `${label}.motions[${index}]`, clips),
+ x: requireFiniteNumber(position[0], `${label}.motions[${index}].position[0]`),
+ y: requireFiniteNumber(position[1], `${label}.motions[${index}].position[1]`),
+ };
+ });
+ for (let first = 0; first < motions.length; first++) {
+ for (let second = first + 1; second < motions.length; second++) {
+ if (motions[first].x === motions[second].x && motions[first].y === motions[second].y) {
+ throw new RangeError(`${label}.motions[${second}] sits at the same position as motions[${first}]. Move one of them.`);
+ }
+ }
+ }
+ return { kind: 'blend2d', parameterNames: [...blend.parameters], motions };
+}
+
+function compileState(definition, label, clips, parameters) {
+ requireObject(definition, label);
+ const name = requireName(definition.name, `${label}.name`);
+ if ((definition.clip === undefined) === (definition.blend === undefined)) {
+ throw new TypeError(`${label} (state "${name}") needs exactly one of clip (a clip name) or blend (a blend space).`);
+ }
+ let motion;
+ if (definition.clip !== undefined) {
+ motion = { kind: 'clip', parameterNames: [], motions: [compileMotion({ clip: definition.clip }, label, clips)] };
+ } else {
+ requireObject(definition.blend, `${label}.blend`);
+ motion = definition.blend.parameters === undefined
+ ? compileBlend1D(definition.blend, `${label}.blend`, clips, parameters)
+ : compileBlend2D(definition.blend, `${label}.blend`, clips, parameters);
+ }
+ const speed = requireFiniteNumber(definition.speed ?? 1, `${label}.speed`, 0, 100);
+ const speedParameter = definition.speedParameter;
+ if (speedParameter !== undefined) numberParameterOf(parameters, speedParameter, `${label}.speedParameter`);
+ const loop = definition.loop ?? (motion.kind === 'clip' ? motion.motions[0].clip.loop : true);
+ if (typeof loop !== 'boolean') throw new TypeError(`${label}.loop must be a boolean, got ${describe(loop)}.`);
+ return { name, ...motion, speed, speedParameter, loop };
+}
+
+function compileCondition(condition, label, parameters) {
+ requireObject(condition, label);
+ const parameter = parameterOf(parameters, condition.parameter, `${label}.parameter`);
+ const keys = Object.keys(condition).filter(key => key !== 'parameter');
+ if (parameter.type === 'number') {
+ const comparators = keys.filter(key => Object.hasOwn(NUMBER_COMPARATORS, key));
+ if (comparators.length !== 1 || keys.length !== 1) {
+ throw new TypeError(`${label} on number parameter "${parameter.name}" needs exactly one of ${Object.keys(NUMBER_COMPARATORS).join(', ')}, such as { parameter: "${parameter.name}", greater: 0.1 }.`);
+ }
+ const comparator = comparators[0];
+ return { parameter, test: NUMBER_COMPARATORS[comparator], limit: requireFiniteNumber(condition[comparator], `${label}.${comparator}`) };
+ }
+ if (keys.some(key => key !== 'is')) {
+ throw new TypeError(`${label} on ${parameter.type} parameter "${parameter.name}" takes only is: true or is: false.`);
+ }
+ const expected = condition.is ?? true;
+ if (typeof expected !== 'boolean') throw new TypeError(`${label}.is must be a boolean, got ${describe(expected)}.`);
+ return { parameter, test: (value, limit) => value === limit, limit: expected };
+}
+
+function compileTransition(definition, label, states, parameters) {
+ requireObject(definition, label);
+ const from = definition.from ?? '*';
+ if (from !== '*' && !states.has(from)) throw new RangeError(`${label}.from names "${String(from)}", which is not a state of this layer. Use a state name or "*" for any state.`);
+ const to = definition.to;
+ if (!states.has(to)) throw new RangeError(`${label}.to names "${String(to)}", which is not a state of this layer. States: ${[...states.keys()].join(', ')}.`);
+ if (from === to) throw new RangeError(`${label} goes from "${to}" to itself. Remove it, or use a different target state.`);
+ const conditions = definition.when === undefined ? [] : requireArray(definition.when, `${label}.when`, ANIMATION_GRAPH_LIMITS.maximumConditions);
+ const exitPhase = definition.exitPhase;
+ if (exitPhase !== undefined) requireFiniteNumber(exitPhase, `${label}.exitPhase`, 0, 1000);
+ if (conditions.length === 0 && exitPhase === undefined) {
+ throw new TypeError(`${label} needs when (a list of parameter conditions) or exitPhase, or it would fire at once, every step.`);
+ }
+ return {
+ from,
+ to,
+ duration: requireFiniteNumber(definition.duration ?? 0, `${label}.duration`, 0, ANIMATION_GRAPH_LIMITS.maximumFadeSeconds),
+ exitPhase,
+ conditions: conditions.map((condition, index) => compileCondition(condition, `${label}.when[${index}]`, parameters)),
+ };
+}
+
+function compileLayer(definition, position, clips, parameters, boneGroups) {
+ const label = `createAnimationGraph layers[${position}]`;
+ requireObject(definition, label);
+ const name = requireName(definition.name, `${label}.name`);
+ const stateDefinitions = requireArray(definition.states, `${label}.states`, ANIMATION_GRAPH_LIMITS.maximumStates);
+ const states = new Map();
+ stateDefinitions.forEach((stateDefinition, index) => {
+ const state = compileState(stateDefinition, `${label}.states[${index}]`, clips, parameters);
+ if (states.has(state.name)) throw new RangeError(`${label} has two states named "${state.name}". Rename one.`);
+ states.set(state.name, state);
+ });
+ const initial = definition.initial ?? stateDefinitions[0].name;
+ if (!states.has(initial)) throw new RangeError(`${label}.initial names "${String(initial)}", which is not a state. States: ${[...states.keys()].join(', ')}.`);
+ const transitions = (definition.transitions === undefined ? [] : requireArray(definition.transitions, `${label}.transitions`, ANIMATION_GRAPH_LIMITS.maximumTransitions))
+ .map((transition, index) => compileTransition(transition, `${label}.transitions[${index}]`, states, parameters));
+ const reference = definition.reference ?? 0;
+ requireFiniteNumber(reference, `${label}.reference`);
+ if (definition.additive !== undefined && typeof definition.additive !== 'boolean') throw new TypeError(`${label}.additive must be a boolean.`);
+
+ // One slot per clip of the layer. A slot has one time, so a clip shared by both ends of a crossfade plays at the incoming state's time.
+ const slots = [];
+ const slotOf = new Map();
+ for (const state of states.values()) {
+ for (const motion of state.motions) {
+ if (slotOf.has(motion.clip.name)) continue;
+ slotOf.set(motion.clip.name, slots.length);
+ slots.push({ clip: motion.clip, weight: 0, time: 0, poseWeight: 0 });
+ }
+ }
+ return {
+ name,
+ states,
+ initial,
+ transitions,
+ slots,
+ slotOf,
+ mask: compileMask(definition.mask, boneGroups, `${label}.mask`),
+ additive: definition.additive === true,
+ reference,
+ initialWeight: requireFiniteNumber(definition.weight ?? 1, `${label}.weight`, 0, 1),
+ };
+}
+
+// Weights of the motions of a state for the current parameters. They always sum to 1.
+function writeMotionWeights(state, parameters, weights) {
+ weights.fill(0);
+ if (state.kind === 'clip') {
+ weights[0] = 1;
+ } else if (state.kind === 'blend1d') {
+ writeBlend1DWeights(state, parameters.get(state.parameterNames[0]).value, weights);
+ } else {
+ writeBlend2DWeights(state, parameters.get(state.parameterNames[0]).value, parameters.get(state.parameterNames[1]).value, weights);
+ }
+}
+
+function writeBlend1DWeights(state, value, weights) {
+ const { sorted, motions } = state;
+ const last = sorted.length - 1;
+ if (value <= sorted[0].threshold) {
+ weights[motions.indexOf(sorted[0])] = 1;
+ return;
+ }
+ if (value >= sorted[last].threshold) {
+ weights[motions.indexOf(sorted[last])] = 1;
+ return;
+ }
+ let upper = 1;
+ while (sorted[upper].threshold < value) upper += 1;
+ const lower = sorted[upper - 1];
+ const progress = (value - lower.threshold) / (sorted[upper].threshold - lower.threshold);
+ weights[motions.indexOf(lower)] = 1 - progress;
+ weights[motions.indexOf(sorted[upper])] = progress;
+}
+
+// Gradient band interpolation: a motion's weight falls to 0 at every other motion and stays local, with no triangulation.
+function writeBlend2DWeights(state, x, y, weights) {
+ const { motions } = state;
+ let total = 0;
+ for (let index = 0; index < motions.length; index++) {
+ let weight = 1;
+ for (let other = 0; other < motions.length && weight > 0; other++) {
+ if (other === index) continue;
+ const directionX = motions[other].x - motions[index].x;
+ const directionY = motions[other].y - motions[index].y;
+ const along = ((x - motions[index].x) * directionX + (y - motions[index].y) * directionY) / (directionX * directionX + directionY * directionY);
+ weight = Math.min(weight, Math.max(0, 1 - along));
+ }
+ weights[index] = weight;
+ total += weight;
+ }
+ if (total === 0) {
+ weights[0] = 1;
+ return;
+ }
+ for (let index = 0; index < motions.length; index++) weights[index] /= total;
+}
+
+function createStateRuntime(state) {
+ return { state, phase: 0, frozen: false, weights: new Float64Array(state.motions.length) };
+}
+
+function stateSpeed(runtime, parameters) {
+ const { state } = runtime;
+ const multiplier = state.speedParameter ? parameters.get(state.speedParameter).value : 1;
+ return state.speed * Math.max(0, multiplier);
+}
+
+function advanceStateRuntime(runtime, parameters, deltaSeconds) {
+ const { state, weights } = runtime;
+ 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.phase += deltaSeconds * stateSpeed(runtime, parameters) / duration;
+}
+
+function motionTime(runtime, motion) {
+ const { phase, state } = runtime;
+ const cycle = state.loop ? phase - Math.floor(phase) : Math.min(phase, 1);
+ return cycle * motion.clip.duration;
+}
+
+function conditionsHold(transition, currentRuntime) {
+ if (transition.exitPhase !== undefined && currentRuntime.phase < transition.exitPhase) return false;
+ return transition.conditions.every(condition => condition.test(condition.parameter.value, condition.limit));
+}
+
+function createLayerRuntime(layer, parameters) {
+ const runtime = {
+ layer,
+ weight: layer.initialWeight,
+ current: null,
+ previous: null,
+ fadeElapsed: 0,
+ fadeDuration: 0,
+ };
+
+ function begin() {
+ runtime.current = createStateRuntime(layer.states.get(layer.initial));
+ runtime.previous = null;
+ runtime.fadeElapsed = 0;
+ runtime.fadeDuration = 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;
+ }
+
+ 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));
+ 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;
+ }
+ 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]];
+ for (const [stateRuntime, stateWeight] of contributors) {
+ stateRuntime.state.motions.forEach((motion, index) => {
+ const contribution = stateWeight * stateRuntime.weights[index];
+ if (contribution <= 0) return;
+ const slot = layer.slots[layer.slotOf.get(motion.clip.name)];
+ slot.weight += contribution;
+ slot.time = motionTime(stateRuntime, motion);
+ });
+ }
+ writePoseWeights();
+ }
+
+ // createSkeletonPose layers blend one over another, so a normalized set of weights becomes a chain of lerp factors.
+ function writePoseWeights() {
+ let accumulated = 0;
+ for (const slot of layer.slots) {
+ const share = runtime.weight * slot.weight;
+ if (layer.additive) {
+ slot.poseWeight = share;
+ continue;
+ }
+ const remaining = 1 - accumulated;
+ slot.poseWeight = remaining > 0 ? Math.min(1, Math.max(0, share / remaining)) : 0;
+ accumulated += share;
+ }
+ }
+
+ return {
+ begin() {
+ begin();
+ collect();
+ },
+ advance(deltaSeconds) {
+ if (!runtime.previous) 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;
+ }
+ }
+ collect();
+ },
+ setWeight(weight) {
+ runtime.weight = weight;
+ writePoseWeights();
+ },
+ describe() {
+ return {
+ state: runtime.current.state.name,
+ previousState: runtime.previous ? runtime.previous.state.name : null,
+ fade: runtime.previous ? 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 })),
+ };
+ },
+ };
+}
+
+/**
+ * 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
+ * { type: 'number' | 'boolean' | 'trigger', initial }. Each layer is { name, states, transitions, initial, weight, mask,
+ * additive }. The graph is deterministic: it reads no clock and no random source.
+ */
+export function createAnimationGraph(definition) {
+ requireObject(definition, 'createAnimationGraph definition');
+ const clips = compileClips(definition.clips ?? {});
+ const parameters = compileParameters(definition.parameters ?? {});
+ const boneGroups = requireObject(definition.boneGroups ?? {}, 'createAnimationGraph boneGroups');
+ const layerDefinitions = requireArray(definition.layers, 'createAnimationGraph layers', ANIMATION_GRAPH_LIMITS.maximumLayers);
+ const layers = layerDefinitions.map((layer, position) => compileLayer(layer, position, clips, parameters, boneGroups));
+ const layerNames = new Set();
+ for (const layer of layers) {
+ if (layerNames.has(layer.name)) throw new RangeError(`createAnimationGraph has two layers named "${layer.name}". Rename one.`);
+ layerNames.add(layer.name);
+ }
+ const runtimes = layers.map(layer => createLayerRuntime(layer, parameters));
+ let elapsedSeconds = 0;
+
+ function runtimeOf(name) {
+ const index = layers.findIndex(layer => layer.name === name);
+ if (index < 0) throw new RangeError(`No layer named "${String(name)}". Layers: ${layers.map(layer => layer.name).join(', ')}.`);
+ return runtimes[index];
+ }
+
+ const graph = {
+ get layers() { return layers.map(layer => layer.name); },
+ get time() { return elapsedSeconds; },
+
+ // 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');
+ if (parameter.type === 'trigger') throw new TypeError(`Parameter "${name}" is a trigger. Call graph.trigger("${name}") instead.`);
+ if (parameter.type === 'boolean' && typeof value !== 'boolean') throw new TypeError(`Parameter "${name}" is a boolean; pass true or false, got ${describe(value)}.`);
+ if (parameter.type === 'number') requireFiniteNumber(value, `Parameter "${name}"`);
+ parameter.value = value;
+ return graph;
+ },
+
+ // Raises a trigger. It stays raised until a transition that lists it fires, or until reset(name).
+ trigger(name) {
+ const parameter = parameterOf(parameters, name, 'graph.trigger name');
+ if (parameter.type !== 'trigger') throw new TypeError(`Parameter "${name}" is a ${parameter.type}, not a trigger. Use graph.set("${name}", value).`);
+ parameter.value = true;
+ return graph;
+ },
+
+ // Puts one parameter back to its initial value (clears a raised trigger).
+ resetParameter(name) {
+ const parameter = parameterOf(parameters, name, 'graph.resetParameter name');
+ parameter.value = parameter.initial;
+ return graph;
+ },
+
+ get(name) {
+ return parameterOf(parameters, name, 'graph.get name').value;
+ },
+
+ setLayerWeight(name, weight) {
+ requireFiniteNumber(weight, `Layer "${name}" weight`, 0, 1);
+ runtimeOf(name).setWeight(weight);
+ return graph;
+ },
+
+ // Steps every layer by deltaSeconds: transitions are checked first, then clock, crossfade and weights move on.
+ advance(deltaSeconds) {
+ requireFiniteNumber(deltaSeconds, 'graph.advance deltaSeconds', 0, ANIMATION_GRAPH_LIMITS.maximumDeltaSeconds);
+ for (const runtime of runtimes) runtime.advance(deltaSeconds);
+ elapsedSeconds += deltaSeconds;
+ return graph;
+ },
+
+ // Back to the initial states, the initial parameter values and time 0.
+ reset() {
+ for (const parameter of parameters.values()) parameter.value = parameter.initial;
+ for (const runtime of runtimes) runtime.begin();
+ elapsedSeconds = 0;
+ return graph;
+ },
+
+ // The state a layer is in, its crossfade progress (null when not fading), and the clips it plays: [{ clip, time, weight }].
+ layerState(name) {
+ return runtimeOf(name).describe();
+ },
+
+ // One createSkeletonPose layer per clip of each graph layer, in order. Weight, clip time and mask follow the graph; build the pose once.
+ poseLayers() {
+ return layers.flatMap(layer => layer.slots.map(slot => ({
+ clip: slot.clip.clip,
+ weight: () => slot.poseWeight,
+ clipTime: () => slot.time,
+ ...(layer.mask ? { mask: layer.mask } : {}),
+ ...(layer.additive ? { additive: true, reference: layer.reference } : {}),
+ })));
+ },
+
+ // A runtime system (docs/runtime.md). Fixed steps advance the graph; in 'variable' mode the frame time does. `apply` runs every frame.
+ system({ name = 'animation-graph', apply } = {}) {
+ requireName(name, 'graph.system name');
+ if (apply !== undefined && typeof apply !== 'function') throw new TypeError('graph.system apply must be a function (graph, context) or left out.');
+ return {
+ name,
+ fixedUpdate(stepSeconds) {
+ graph.advance(stepSeconds);
+ },
+ update(deltaSeconds, context) {
+ if (context.mode === 'variable') graph.advance(deltaSeconds);
+ apply?.(graph, context);
+ },
+ };
+ },
+ };
+
+ graph.reset();
+ return graph;
+}
diff --git a/tests/animation-graph.test.js b/tests/animation-graph.test.js
new file mode 100644
index 00000000..4fc73f5e
--- /dev/null
+++ b/tests/animation-graph.test.js
@@ -0,0 +1,316 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { quat } from 'gl-matrix';
+import { createAnimationClip } from '../src/animation.js';
+import { ANIMATION_GRAPH_LIMITS, createAnimationGraph } from '../src/animation-graph.js';
+import { createRuntime } from '../src/runtime.js';
+import { createSkeletonPose } from '../src/skeleton-pose.js';
+
+function poseClip(target, degrees, { duration = 1, loop = true } = {}) {
+ const value = Array.from(quat.setAxisAngle(new Float64Array(4), [0, 0, 1], degrees * Math.PI / 180));
+ return createAnimationClip({
+ duration,
+ loop,
+ tracks: [{ target, property: 'rotation', keyframes: [{ time: 0, value }, { time: duration, value }] }],
+ });
+}
+
+const CLIPS = {
+ idle: poseClip('spine', 0, { duration: 2 }),
+ walk: poseClip('spine', 30, { duration: 1 }),
+ run: poseClip('spine', 60, { duration: 0.5 }),
+ wave: poseClip('arm', 90, { loop: false }),
+};
+
+function locomotionDefinition(overrides = {}) {
+ return {
+ clips: CLIPS,
+ parameters: { speed: { type: 'number' }, jump: { type: 'trigger' }, armed: { type: 'boolean' } },
+ layers: [{
+ name: 'base',
+ states: [
+ { name: 'idle', clip: 'idle' },
+ { name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'idle', threshold: 0 }, { clip: 'walk', threshold: 2 }, { clip: 'run', threshold: 6 }] } },
+ { name: 'wave', clip: 'wave' },
+ ],
+ transitions: [
+ { from: 'idle', to: 'move', when: [{ parameter: 'speed', greater: 0.1 }], duration: 0.2 },
+ { from: 'move', to: 'idle', when: [{ parameter: 'speed', atMost: 0.1 }], duration: 0.2 },
+ { from: '*', to: 'wave', when: [{ parameter: 'jump' }], duration: 0 },
+ ],
+ }],
+ ...overrides,
+ };
+}
+
+function clipWeights(graph, layer = 'base') {
+ return Object.fromEntries(graph.layerState(layer).clips.map(entry => [entry.clip, entry.weight]));
+}
+
+function run(graph, steps, delta = 0.05) {
+ for (let step = 0; step < steps; step++) graph.advance(delta);
+}
+
+function sum(values) {
+ return values.reduce((total, value) => total + value, 0);
+}
+
+test('starts in the initial state and stays there without a matching condition', () => {
+ const graph = createAnimationGraph(locomotionDefinition());
+ run(graph, 10);
+ assert.equal(graph.layerState('base').state, 'idle');
+ assert.deepEqual(clipWeights(graph), { idle: 1 });
+});
+
+test('a parameter condition starts a transition that crossfades over fixed steps', () => {
+ const graph = createAnimationGraph(locomotionDefinition());
+ graph.set('speed', 2);
+ graph.advance(0.05);
+ let state = graph.layerState('base');
+ assert.equal(state.state, 'move');
+ assert.equal(state.previousState, 'idle');
+ assert.ok(Math.abs(state.fade - 0.25) < 1e-9);
+ run(graph, 2);
+ assert.ok(Math.abs(graph.layerState('base').fade - 0.75) < 1e-9);
+ graph.advance(0.05);
+ state = graph.layerState('base');
+ assert.equal(state.previousState, null);
+ assert.equal(state.fade, null);
+ assert.deepEqual(clipWeights(graph), { walk: 1 });
+});
+
+test('a crossfade blends the outgoing and incoming weights and they always sum to 1', () => {
+ const graph = createAnimationGraph(locomotionDefinition());
+ graph.set('speed', 6);
+ for (let step = 0; step < 4; step++) {
+ graph.advance(0.05);
+ assert.ok(Math.abs(sum(Object.values(clipWeights(graph))) - 1) < 1e-9);
+ }
+ assert.deepEqual(clipWeights(graph), { run: 1 });
+ graph.set('speed', 0);
+ graph.advance(0.05);
+ assert.equal(graph.layerState('base').state, 'idle');
+ assert.ok(Math.abs(clipWeights(graph).run - 0.75) < 1e-9);
+});
+
+test('a transition waits for a running crossfade to end before the next one starts', () => {
+ const graph = createAnimationGraph(locomotionDefinition());
+ graph.set('speed', 2);
+ graph.advance(0.05);
+ graph.set('speed', 0);
+ graph.advance(0.05);
+ assert.equal(graph.layerState('base').state, 'move');
+ run(graph, 3);
+ graph.advance(0.05);
+ assert.equal(graph.layerState('base').state, 'idle');
+});
+
+test('1D blend weights interpolate between thresholds and clamp outside them', () => {
+ const graph = createAnimationGraph(locomotionDefinition({ layers: [{
+ name: 'base',
+ initial: 'move',
+ states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'run', threshold: 6 }, { clip: 'idle', threshold: 0 }, { clip: 'walk', threshold: 2 }] } }],
+ }] }));
+ graph.set('speed', -5).advance(0.01);
+ assert.deepEqual(clipWeights(graph), { idle: 1 });
+ graph.set('speed', 1).advance(0.01);
+ assert.deepEqual(clipWeights(graph), { idle: 0.5, walk: 0.5 });
+ graph.set('speed', 5).advance(0.01);
+ assert.deepEqual(clipWeights(graph), { walk: 0.25, run: 0.75 });
+ graph.set('speed', 99).advance(0.01);
+ assert.deepEqual(clipWeights(graph), { run: 1 });
+});
+
+test('blend space clips share one phase so the steps stay in sync', () => {
+ const graph = createAnimationGraph(locomotionDefinition({ layers: [{
+ name: 'base',
+ states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'walk', threshold: 0 }, { clip: 'run', threshold: 1 }] } }],
+ }] }));
+ graph.set('speed', 0.5);
+ run(graph, 5, 0.1);
+ const [walk, fast] = graph.layerState('base').clips;
+ assert.ok(Math.abs(walk.time / 1 - fast.time / 0.5) < 1e-9);
+ assert.ok(walk.time > 0);
+});
+
+test('2D blend weights are 1 at a motion, local between motions, and sum to 1', () => {
+ const graph = createAnimationGraph({
+ clips: CLIPS,
+ parameters: { strafe: { type: 'number' }, forward: { type: 'number' } },
+ layers: [{
+ name: 'base',
+ states: [{ name: 'move', blend: { parameters: ['strafe', 'forward'], motions: [
+ { clip: 'idle', position: [0, 0] }, { clip: 'walk', position: [0, 1] }, { clip: 'run', position: [1, 0] },
+ ] } }],
+ }],
+ });
+ graph.set('strafe', 0).set('forward', 1).advance(0.01);
+ assert.deepEqual(clipWeights(graph), { walk: 1 });
+ graph.set('forward', 0.5).advance(0.01);
+ assert.deepEqual(clipWeights(graph), { idle: 0.5, walk: 0.5 });
+ graph.set('strafe', 0.3).set('forward', 0.2).advance(0.01);
+ const weights = clipWeights(graph);
+ assert.equal(Object.keys(weights).length, 3);
+ assert.ok(Math.abs(sum(Object.values(weights)) - 1) < 1e-9);
+ assert.ok(weights.idle > weights.walk && weights.idle > weights.run);
+ graph.set('strafe', 10).set('forward', 0).advance(0.01);
+ assert.deepEqual(clipWeights(graph), { run: 1 });
+});
+
+test('a trigger fires once, is consumed, and any-state transitions work', () => {
+ const graph = createAnimationGraph(locomotionDefinition());
+ graph.trigger('jump').advance(0.05);
+ assert.equal(graph.layerState('base').state, 'wave');
+ assert.equal(graph.get('jump'), false);
+ run(graph, 5);
+ assert.equal(graph.layerState('base').state, 'wave');
+});
+
+test('exitPhase holds a transition until the state has played that far', () => {
+ const graph = createAnimationGraph(locomotionDefinition({ layers: [{
+ name: 'base',
+ states: [{ name: 'wave', clip: 'wave' }, { name: 'idle', clip: 'idle' }],
+ transitions: [{ from: 'wave', to: 'idle', exitPhase: 1, duration: 0.1 }],
+ }] }));
+ run(graph, 10, 0.05);
+ assert.equal(graph.layerState('base').state, 'wave');
+ run(graph, 11, 0.05);
+ assert.equal(graph.layerState('base').state, 'idle');
+});
+
+test('a clip that does not loop holds its last frame', () => {
+ const graph = createAnimationGraph(locomotionDefinition({ layers: [{ name: 'base', states: [{ name: 'wave', clip: 'wave' }] }] }));
+ run(graph, 30, 0.1);
+ assert.equal(graph.layerState('base').clips[0].time, 1);
+});
+
+test('speedParameter scales how fast a state plays', () => {
+ const graph = createAnimationGraph({
+ clips: CLIPS,
+ parameters: { pace: { type: 'number', initial: 2 } },
+ layers: [{ name: 'base', states: [{ name: 'walk', clip: 'walk', speedParameter: 'pace' }] }],
+ });
+ graph.advance(0.1);
+ assert.ok(Math.abs(graph.layerState('base').clips[0].time - 0.2) < 1e-9);
+});
+
+test('layers run independent graphs and carry a bone mask resolved from a group', () => {
+ const graph = createAnimationGraph(locomotionDefinition({
+ boneGroups: { arms: { joints: ['arm'], exclude: ['hand'] } },
+ layers: [
+ { name: 'base', states: [{ name: 'walk', clip: 'walk' }] },
+ { name: 'upper', mask: 'arms', weight: 0.5, states: [{ name: 'none', clip: 'idle' }, { name: 'wave', clip: 'wave' }], transitions: [{ from: 'none', to: 'wave', when: [{ parameter: 'armed', is: true }], duration: 0.1 }] },
+ ],
+ }));
+ graph.set('armed', true);
+ run(graph, 4, 0.05);
+ assert.equal(graph.layerState('base').state, 'walk');
+ assert.equal(graph.layerState('upper').state, 'wave');
+ assert.equal(graph.layerState('upper').weight, 0.5);
+ const layers = graph.poseLayers();
+ assert.equal(layers.length, 3);
+ assert.equal(layers[0].mask, undefined);
+ assert.deepEqual(layers[1].mask, { joints: ['arm'], exclude: ['hand'] });
+ assert.equal(layers[1].weight(), 0);
+ assert.ok(Math.abs(layers[2].weight() - 0.5) < 1e-9);
+ graph.setLayerWeight('upper', 1);
+ assert.ok(Math.abs(layers[2].weight() - 1) < 1e-9);
+});
+
+test('poseLayers drive createSkeletonPose: a layer mask keeps the other bones on the base pose', () => {
+ const graph = createAnimationGraph({
+ clips: { still: poseClip('spine', 0), bend: poseClip('spine', 60), raise: poseClip('arm', 90) },
+ parameters: { raised: { type: 'boolean' } },
+ boneGroups: { arm: { joints: ['arm'] } },
+ layers: [
+ { name: 'base', states: [{ name: 'still', clip: 'still' }] },
+ { name: 'upper', mask: 'arm', states: [{ name: 'down', clip: 'still' }, { name: 'raise', clip: 'raise' }], transitions: [{ from: 'down', to: 'raise', when: [{ parameter: 'raised' }] }] },
+ ],
+ });
+ const rig = { joints: [
+ { name: 'hips', parent: -1, translation: [0, 1, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },
+ { name: 'spine', parent: 0, translation: [0, 0.3, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },
+ { name: 'arm', parent: 1, translation: [0.2, 0.4, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },
+ ] };
+ const pose = createSkeletonPose({ rig, layers: graph.poseLayers() });
+ graph.set('raised', true).advance(0.1);
+ pose.apply(graph.time);
+ const angleOf = rotation => 2 * Math.acos(Math.min(1, Math.abs(rotation[3]))) * 180 / Math.PI;
+ assert.ok(Math.abs(angleOf(pose.localRotation(2)) - 90) < 1e-4);
+ assert.ok(angleOf(pose.localRotation(1)) < 1e-4);
+});
+
+test('pose weights chain so blended clips match a direct weighted mix', () => {
+ const graph = createAnimationGraph(locomotionDefinition({ layers: [{
+ name: 'base',
+ states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'idle', threshold: 0 }, { clip: 'walk', threshold: 2 }, { clip: 'run', threshold: 4 }] } }],
+ }] }));
+ graph.set('speed', 3).advance(0.01);
+ const weights = graph.poseLayers().map(layer => Number(layer.weight().toFixed(6)));
+ assert.deepEqual(weights, [0, 0.5, 1]);
+});
+
+test('the same parameter sequence gives identical weights and times', () => {
+ const sequence = [0, 0.5, 2, 6, 6, 1, 0, 0, 3, 5, 0.05, 0, 0, 0, 2];
+ const play = () => {
+ const graph = createAnimationGraph(locomotionDefinition());
+ return sequence.map(speed => {
+ graph.set('speed', speed).advance(1 / 60);
+ return JSON.stringify(graph.layerState('base'));
+ });
+ };
+ assert.deepEqual(play(), play());
+});
+
+test('reset returns to the initial state, parameters and time', () => {
+ const graph = createAnimationGraph(locomotionDefinition());
+ graph.set('speed', 6).trigger('jump');
+ run(graph, 10);
+ graph.reset();
+ assert.equal(graph.time, 0);
+ assert.equal(graph.get('speed'), 0);
+ assert.equal(graph.get('jump'), false);
+ assert.equal(graph.layerState('base').state, 'idle');
+});
+
+test('the runtime system advances the graph on fixed steps and calls apply each frame', () => {
+ const graph = createAnimationGraph(locomotionDefinition());
+ const applied = [];
+ const runtime = createRuntime({ render() {} }, {
+ mode: 'both',
+ fixedRate: 20,
+ scheduler: { request: () => 1, cancel() {} },
+ systems: [graph.system({ apply: (target, context) => applied.push(context.elapsedSeconds) })],
+ });
+ graph.set('speed', 2);
+ runtime.step(100);
+ assert.ok(Math.abs(graph.time - 0.1) < 1e-9);
+ assert.equal(graph.layerState('base').state, 'move');
+ assert.equal(applied.length, 1);
+ runtime.dispose();
+});
+
+test('mistakes throw errors that name the field and the fix', () => {
+ const failing = (mutate, pattern) => assert.throws(() => createAnimationGraph(mutate(locomotionDefinition())), pattern);
+ failing(definition => ({ ...definition, layers: [] }), /layers must be an array of 1 to 8/);
+ failing(definition => { definition.layers[0].states[0].clip = 'missing'; return definition; }, /states\[0\]\.clip names "missing".*Declared: idle, walk, run, wave/);
+ failing(definition => { definition.layers[0].transitions[0].to = 'nowhere'; return definition; }, /transitions\[0\]\.to names "nowhere"/);
+ failing(definition => { definition.layers[0].transitions[0].when = [{ parameter: 'speed' }]; return definition; }, /needs exactly one of greater, atLeast/);
+ failing(definition => { definition.layers[0].transitions[0].when = [{ parameter: 'ghost', is: true }]; return definition; }, /parameter "ghost", which is not declared/);
+ failing(definition => { definition.layers[0].states[1].blend.motions[1].threshold = 0; return definition; }, /two motions at threshold 0/);
+ failing(definition => { definition.layers[0].states[0].blend = {}; return definition; }, /exactly one of clip/);
+ failing(definition => { definition.layers[0].mask = 'head'; return definition; }, /bone group "head"/);
+ failing(definition => { definition.layers[0].transitions[0].from = 'move'; definition.layers[0].transitions[0].to = 'move'; return definition; }, /to itself/);
+ const graph = createAnimationGraph(locomotionDefinition());
+ assert.throws(() => graph.set('jump', true), /Call graph\.trigger\("jump"\)/);
+ assert.throws(() => graph.set('speed', Number.NaN), /Parameter "speed" must be a finite number/);
+ assert.throws(() => graph.set('armed', 1), /pass true or false/);
+ assert.throws(() => graph.trigger('speed'), /not a trigger/);
+ assert.throws(() => graph.layerState('top'), /No layer named "top"\. Layers: base/);
+ assert.throws(() => graph.advance(-1), /graph\.advance deltaSeconds/);
+});
+
+test('counts stay bounded', () => {
+ const states = Array.from({ length: ANIMATION_GRAPH_LIMITS.maximumStates + 1 }, (_, index) => ({ name: `s${index}`, clip: 'idle' }));
+ assert.throws(() => createAnimationGraph({ clips: CLIPS, layers: [{ name: 'base', states }] }), /states must be an array of 1 to 64/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 80d48ff3..7c71cae6 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -107,6 +107,7 @@ export default defineConfig({
cloth: 'src/cloth.js',
runtime: 'src/runtime.js',
input: 'src/input.js',
+ 'animation-graph': 'src/animation-graph.js',
'update-part-vertices':'src/update-part-vertices.js',
'replace-textured-parts': 'src/replace-textured-parts.js',
// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.