Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Let a game recipe drive the animation graph and NPC paths (#872)

Nguyen Xuan An4ab3f0411538
diff --git a/changes/872-recipe-animation.md b/changes/872-recipe-animation.md
new file mode 100644
index 00000000..b7b6a026
--- /dev/null
+++ b/changes/872-recipe-animation.md
@@ -0,0 +1 @@
+- A game recipe drives the animation state graph, blend spaces and path-following NPCs with `player.animation` and `npcs`, and the web export plays them (#872)
diff --git a/changes/872-recipe-animation.size.md b/changes/872-recipe-animation.size.md
new file mode 100644
index 00000000..005edd2c
--- /dev/null
+++ b/changes/872-recipe-animation.size.md
@@ -0,0 +1,4 @@
+- entry:game: the web export now plays the animation graph, pose and path follower a recipe declares (about 19.8 KB gzip), the visible capability the issue asks for
+- entry:game+lazy: same code, counted with the lazy chunks (+11.1 KB gzip)
+- scene:agent-scene+lazy: the recipe validator builds the graph and pose once to refuse a bad animation with the field named (+8.8 KB gzip in the on-demand game module)
+- goal:agent-scene: the core scene bundle grows by about 49 bytes gzip for the shared-chunk import of the game module; the animation code itself loads only with a game recipe
diff --git a/docs/animation-graph.md b/docs/animation-graph.md
index 38d5e263..ff620cff 100644
--- a/docs/animation-graph.md
+++ b/docs/animation-graph.md
@@ -63,6 +63,8 @@ const parameterSystem = {
To let the clips move the body instead, see [Root motion](#root-motion).
+An agent builds the same graph without code: a scene recipe carries it in `game.player.animation` and `game.npcs[].animation`, played by the web export (see [game](game.md#animation-and-npcs)).
+
## Parameters
`parameters` maps a name to `{ type, initial }`.
diff --git a/docs/game.md b/docs/game.md
index 585d11f6..84cb5e13 100644
--- a/docs/game.md
+++ b/docs/game.md
@@ -42,6 +42,8 @@ A scene recipe can carry a `game` section. It names the node the player controls
| `player.footOffset` | 0 | Metres from the node origin down to the feet. Zone checks use the feet |
| `camera` | `follow` | `follow`, `first-person` or `top-down`, the [camera rigs](player.md#camera-rigs) |
| `input` | `keyboard` | `keyboard` (WASD move, arrows look, Space jump, Shift run), `gamepad` (adds the first pad) or `touch` (adds a left-half stick and tap to jump) |
+| `player.animation` | none | An [animation graph](animation-graph.md) for the player, see [Animation and NPCs](#animation-and-npcs) |
+| `npcs` | none | Up to 16 characters that walk a path through their own graph, see [Animation and NPCs](#animation-and-npcs) |
| `physics` | `false` | Accepted. The web export refuses `true` until the physics engine can be bundled |
| `ground` | 0 | Height of the walkable ground in metres |
| `rules` | none | A [game rules](game-rules.md) document, checked when it is set |
@@ -62,4 +64,34 @@ const game = await startGame(canvas, recipe, { replay, showStatus: true });
game.dispose();
```
-`startGame` loads the scene modules the recipe needs, builds the scene and renderer, and runs input, controller, camera rig and rules as [runtime](runtime.md) systems. Each frame it moves the player node with `set-node`, so a large scene pays a scene update per frame. Not yet in the web build: live physics, sound, an animation graph and post effects.
+`startGame` loads the scene modules the recipe needs, builds the scene and renderer, and runs input, controller, camera rig and rules as [runtime](runtime.md) systems. Each frame it moves the player node with `set-node`, so a large scene pays a scene update per frame. Not yet in the web build: live physics, sound and post effects.
+
+## Animation and NPCs
+
+`player.animation` and each `npcs[].animation` hold a clip set and an [animation graph](animation-graph.md) as plain data. The player or NPC node is the character, and its child nodes are the parts the clips move: a body, legs, arms. The web build plays them with the same graph, root motion and path follower as the code API.
+
+```json
+{
+ "player": {
+ "node": "walker", "walkSpeed": 1.4,
+ "animation": {
+ "clips": {
+ "idle": { "duration": 1, "tracks": [{ "target": "body", "property": "translation", "keyframes": [{ "time": 0, "value": [0, 0, 0] }, { "time": 1, "value": [0, 0, 0] }] }] },
+ "walk": { "duration": 1, "tracks": [{ "target": "body", "property": "translation", "keyframes": [{ "time": 0, "value": [0, 0, 0] }, { "time": 1, "value": [0, 0, 1.4] }] }] }
+ },
+ "parameters": { "speed": { "type": "number" } },
+ "rootMotion": { "bone": "body" },
+ "layers": [{ "name": "base", "states": [{ "name": "move", "blend": { "parameter": "speed", "motions": [{ "clip": "idle", "threshold": 0 }, { "clip": "walk", "threshold": 1.4 }] } }] }]
+ }
+ },
+ "npcs": [{ "node": "guard", "path": [[4, -6], [8, -6]], "cruiseSpeed": 1.4, "animation": { "...": "same shape; tracks target the guard's child nodes" } }]
+}
+```
+
+- `clips`: 1 to 16, each `{ duration, loop (true), tracks }` with up to 64 tracks of up to 256 keyframes. A track `target` is a child node of the character (never the character itself, which the controller or follower moves) and `property` is `translation` or `rotation` (a quaternion), in the parent's space.
+- `parameters`, `boneGroups`, `layers` and `rootMotion` are the graph definition with every field and limit of [animation-graph](animation-graph.md): 1D and 2D blend spaces, transitions, layers with masks. Clip names refer to `clips`; mask joints are child node ids.
+- `drive` (player only) maps a graph parameter to a controller value: `speed`, `intentSpeed` or `airborne`. The default sets `speed` from `intentSpeed` when there is `rootMotion` (the clips then move the player by the travel of the last step) and from `speed` otherwise.
+- An NPC needs `rootMotion` and a number parameter `speed`. Its path follower sets `speed`, so idle, walk and run blend; it moves by the root motion, turns at corners and stops at the last of up to 256 `[x, z]` waypoints, where `speed` returns to 0. `cruiseSpeed` is 2.2 by default; `yaw` and `footOffset` work as for the player. Each NPC node is separate from the player and the other NPCs.
+- Root travel along +Z works as written; for clips whose root travels -Z set `rootMotion.facing` to `"-z"`.
+
+A wrong field is refused with its path and the values to use, for example `player.animation.clips.walk.tracks[0].target names "Ghost", which is not a child node of the character`. `window.__game.animation` and `window.__game.npcs` expose the graphs. Clips of placed catalog assets and retargeting are not part of the recipe yet, because the web build takes procedural scenes only.
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 72350221..8322feda 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -959,7 +959,7 @@ function normalizeRecipe(input, limits) {
if (Object.hasOwn(recipe, 'postPasses')) recipe.postPasses = agentSceneModule('userPass').normalizeUserPasses(recipe.postPasses ?? []);
if (Object.hasOwn(recipe, 'game')) {
if (recipe.game === null) delete recipe.game;
- else recipe.game = agentSceneModule('game').normalizeGameSetup(recipe.game, new Set(recipe.nodes.map(node => node.id)));
+ else recipe.game = agentSceneModule('game').normalizeGameSetup(recipe.game, recipe.nodes);
}
recipe = copiedJson(recipe, limits.maxRecipeBytes);
return recipe;
diff --git a/src/game-animation.js b/src/game-animation.js
new file mode 100644
index 00000000..91e87bb6
--- /dev/null
+++ b/src/game-animation.js
@@ -0,0 +1,174 @@
+import { createAnimationClip } from './animation.js';
+import { createAnimationGraph } from './animation-graph.js';
+import { createSkeletonPose } from './skeleton-pose.js';
+
+// The `animation` section of a game character in a scene recipe: clips keyed on the character's child nodes, an animation
+// graph (states, 1D and 2D blend spaces, layers with masks) and how the game drives it. It is plain data. The same section
+// serves the player (`game.player.animation`) and each path-following NPC (`game.npcs[].animation`). See docs/game.md.
+
+export const GAME_ANIMATION_LIMITS = Object.freeze({
+ maxClips: 16,
+ maxTracksPerClip: 64,
+ maxKeyframesPerTrack: 256,
+ maxClipSeconds: 300,
+ maxCharacterNodes: 256,
+});
+
+export const GAME_ANIMATION_DRIVES = Object.freeze(['speed', 'intentSpeed', 'airborne']);
+const ANIMATION_FIELDS = ['clips', 'parameters', 'boneGroups', 'layers', 'rootMotion', 'drive'];
+const CLIP_FIELDS = ['duration', 'loop', 'tracks'];
+const TRACK_PROPERTIES = ['translation', 'rotation'];
+
+function fail(path, problem) {
+ throw new RangeError(`Game setup ${path} ${problem}`);
+}
+
+function requireRecord(value, path, example) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail(path, `must be an object, such as ${example}.`);
+}
+
+function rejectUnknownFields(record, allowed, path) {
+ for (const key of Object.keys(record)) {
+ if (!allowed.includes(key)) fail(`${path}.${key}`, `is not a field. Use one of: ${allowed.join(', ')}.`);
+ }
+}
+
+/** The ids of the nodes below `characterId`, parents before children. */
+export function characterDescendants(nodes, characterId) {
+ const childrenByParent = new Map();
+ for (const node of nodes) {
+ if (node.parent === undefined) continue;
+ if (!childrenByParent.has(node.parent)) childrenByParent.set(node.parent, []);
+ childrenByParent.get(node.parent).push(node);
+ }
+ const found = [];
+ const queue = [characterId];
+ while (queue.length > 0) {
+ for (const child of childrenByParent.get(queue.shift()) ?? []) {
+ found.push(child);
+ queue.push(child.id);
+ }
+ }
+ return found;
+}
+
+function checkClips(clips, descendantIds, path) {
+ requireRecord(clips, `${path}.clips`, '{ "idle": { "duration": 1, "tracks": [...] } }');
+ const names = Object.keys(clips);
+ if (names.length === 0 || names.length > GAME_ANIMATION_LIMITS.maxClips) fail(`${path}.clips`, `needs 1 to ${GAME_ANIMATION_LIMITS.maxClips} clips, got ${names.length}.`);
+ const normalized = {};
+ for (const name of names) {
+ const clipPath = `${path}.clips.${name}`;
+ const clip = clips[name];
+ requireRecord(clip, clipPath, '{ "duration": 1, "loop": true, "tracks": [{ "target": "arm", "property": "rotation", "keyframes": [{ "time": 0, "value": [0, 0, 0, 1] }] }] }');
+ rejectUnknownFields(clip, CLIP_FIELDS, clipPath);
+ if (typeof clip.duration !== 'number' || !(clip.duration > 0) || clip.duration > GAME_ANIMATION_LIMITS.maxClipSeconds) {
+ fail(`${clipPath}.duration`, `must be a number of seconds above 0 and up to ${GAME_ANIMATION_LIMITS.maxClipSeconds}, got ${JSON.stringify(clip.duration)}.`);
+ }
+ if (clip.loop !== undefined && typeof clip.loop !== 'boolean') fail(`${clipPath}.loop`, `must be true or false, got ${JSON.stringify(clip.loop)}.`);
+ if (!Array.isArray(clip.tracks) || clip.tracks.length === 0 || clip.tracks.length > GAME_ANIMATION_LIMITS.maxTracksPerClip) {
+ fail(`${clipPath}.tracks`, `needs 1 to ${GAME_ANIMATION_LIMITS.maxTracksPerClip} tracks, each { target, property, keyframes }.`);
+ }
+ clip.tracks.forEach((track, index) => {
+ const trackPath = `${clipPath}.tracks[${index}]`;
+ requireRecord(track, trackPath, '{ "target": "arm", "property": "rotation", "keyframes": [...] }');
+ if (!descendantIds.has(track.target)) {
+ const known = [...descendantIds].slice(0, 12).join(', ') || 'none; give the character child nodes';
+ fail(`${trackPath}.target`, `names ${JSON.stringify(track.target)}, which is not a child node of the character. Use one of: ${known}.`);
+ }
+ if (!TRACK_PROPERTIES.includes(track.property)) fail(`${trackPath}.property`, `is ${JSON.stringify(track.property)}. Use one of: ${TRACK_PROPERTIES.join(', ')}.`);
+ if (!Array.isArray(track.keyframes) || track.keyframes.length === 0 || track.keyframes.length > GAME_ANIMATION_LIMITS.maxKeyframesPerTrack) {
+ fail(`${trackPath}.keyframes`, `needs 1 to ${GAME_ANIMATION_LIMITS.maxKeyframesPerTrack} keyframes, each { time, value }.`);
+ }
+ });
+ try {
+ createAnimationClip({ duration: clip.duration, loop: clip.loop ?? true, tracks: clip.tracks });
+ } catch (error) {
+ fail(clipPath, `is not a valid clip: ${error.message}`);
+ }
+ normalized[name] = { duration: clip.duration, loop: clip.loop ?? true, tracks: structuredClone(clip.tracks) };
+ }
+ return normalized;
+}
+
+function jointsOf(descendants, characterId) {
+ const index = new Map(descendants.map((node, position) => [node.id, position]));
+ return descendants.map(node => ({
+ name: node.id,
+ parent: index.get(node.parent) ?? -1,
+ translation: node.translation ?? [0, 0, 0],
+ rotation: node.rotation ?? [0, 0, 0, 1],
+ scale: node.scale ?? [1, 1, 1],
+ }));
+}
+
+/**
+ * Build the graph and the pose of one character from a `normalizeGameAnimation` result. `nodes` are the recipe nodes and
+ * `characterId` the node the controller or follower moves. `graph` is a normal animation graph; `operations()` poses the nodes
+ * below the character at the graph's time and returns the `set-node` operations that write them.
+ */
+export function createGameAnimation(animation, nodes, characterId) {
+ const descendants = characterDescendants(nodes, characterId);
+ const clips = Object.fromEntries(Object.entries(animation.clips).map(([name, clip]) => [name, createAnimationClip(clip)]));
+ const { clips: _clips, drive: _drive, ...graphDefinition } = animation;
+ const graph = createAnimationGraph({ ...graphDefinition, clips });
+ const pose = createSkeletonPose({ rig: { joints: jointsOf(descendants, characterId) }, layers: graph.poseLayers() });
+ const written = pose.writtenJoints.map(({ index, translation }) => ({ id: descendants[index].id, index, translation }));
+ return {
+ graph,
+ drive: animation.drive,
+ hasRootMotion: Boolean(animation.rootMotion),
+ operations() {
+ pose.apply(graph.time);
+ return written.map(({ id, index, translation }) => ({
+ type: 'set-node',
+ id,
+ rotation: Array.from(pose.localRotation(index)),
+ ...(translation ? { translation: Array.from(pose.localTranslation(index)) } : {}),
+ }));
+ },
+ };
+}
+
+function defaultDrive(animation) {
+ const speed = animation.parameters?.speed;
+ if (!speed || speed.type !== 'number') return {};
+ return { speed: animation.rootMotion ? 'intentSpeed' : 'speed' };
+}
+
+function checkDrive(drive, animation, path) {
+ if (drive === undefined) return defaultDrive(animation);
+ requireRecord(drive, `${path}.drive`, '{ "speed": "intentSpeed" }');
+ const parameters = animation.parameters ?? {};
+ for (const [parameter, source] of Object.entries(drive)) {
+ if (!GAME_ANIMATION_DRIVES.includes(source)) fail(`${path}.drive.${parameter}`, `is ${JSON.stringify(source)}. Use one of: ${GAME_ANIMATION_DRIVES.join(', ')}.`);
+ const type = parameters[parameter]?.type;
+ const expected = source === 'airborne' ? 'boolean' : 'number';
+ if (type !== expected) fail(`${path}.drive.${parameter}`, `needs a ${expected} parameter of that name in parameters, because ${source} is a ${expected}. Declare "${parameter}": { "type": "${expected}" }.`);
+ }
+ return structuredClone(drive);
+}
+
+/**
+ * Check a character's `animation` section against the recipe nodes and return a normalised copy. `characterId` must be a
+ * node of `nodes`; clips target its child nodes, never the node itself, because the controller or follower owns that one.
+ * Options: `path` for messages and `driven` (false for an NPC, whose follower sets the `speed` parameter).
+ */
+export function normalizeGameAnimation(animation, nodes, characterId, { path = 'animation', driven = true } = {}) {
+ requireRecord(animation, path, '{ "clips": {...}, "layers": [...] }');
+ rejectUnknownFields(animation, ANIMATION_FIELDS, path);
+ const descendants = characterDescendants(nodes, characterId);
+ if (descendants.length === 0) fail(path, `has nothing to move: "${characterId}" has no child nodes. Give the character child nodes (a body, limbs) and point clip tracks at them.`);
+ if (descendants.length > GAME_ANIMATION_LIMITS.maxCharacterNodes) fail(path, `would pose ${descendants.length} nodes; the limit is ${GAME_ANIMATION_LIMITS.maxCharacterNodes}.`);
+ if (!Array.isArray(animation.layers)) fail(`${path}.layers`, 'must be a list of animation graph layers, such as [{ "name": "base", "states": [{ "name": "idle", "clip": "idle" }] }].');
+ const normalized = { ...structuredClone(animation), clips: checkClips(animation.clips, new Set(descendants.map(node => node.id)), path) };
+ if (driven) normalized.drive = checkDrive(animation.drive, normalized, path);
+ else if (animation.drive !== undefined) fail(`${path}.drive`, 'is not allowed on an NPC: its path follower sets the "speed" parameter. Remove drive.');
+ try {
+ const built = createGameAnimation(normalized, nodes, characterId);
+ built.operations();
+ } catch (error) {
+ throw new RangeError(`Game setup ${path}: ${error.message}`);
+ }
+ return normalized;
+}
diff --git a/src/game-setup-notes.js b/src/game-setup-notes.js
index 40e17bbb..f0b2c7c9 100644
--- a/src/game-setup-notes.js
+++ b/src/game-setup-notes.js
@@ -5,7 +5,27 @@ export const GAME_CAPABILITIES = Object.freeze({
cameras: Object.freeze(['follow', 'first-person', 'top-down']),
inputPresets: Object.freeze({ keyboard: 'WASD and arrows move and look, Space jumps, Shift runs', gamepad: 'keyboard plus the first gamepad (stick 0, jump on button 0)', touch: 'keyboard plus a left-half virtual stick and tap to jump' }),
rules: 'version 1, variables, zones {id, shape sphere|box, center, radius|size}, parts {id, tags, position}, prefabs, rules [{id, once, when, if, do}]. The rules part named like the player node follows the player; a part named like a node is hidden or shown with it. Triggers enter|exit|contact|input|timer|variable (input actions: jump, run); actions set|add|show|hide|spawn|animation|sound|win|lose|restart. Full list: docs/game-rules.md.',
+ animation: 'player.animation, or npcs[].animation: { clips, parameters, boneGroups, layers, rootMotion, drive }. clips {name: {duration s, loop true, tracks [{target (a CHILD node id of the character, never the character), property translation|rotation, keyframes [{time, value}]}]}}, 1 to 16 clips. parameters, boneGroups, layers (states with clip or 1D/2D blend, transitions, masks) and rootMotion {bone, facing, scale} are the animation graph definition of docs/animation-graph.md, with clip names from clips. drive maps a graph parameter to a controller value (speed|intentSpeed|airborne); default is speed from intentSpeed with rootMotion, else speed. With rootMotion the clips move the player.',
+ npcs: 'npcs [{node, path [[x, z] ...] up to 256 points, cruiseSpeed 2.2 m/s, footOffset 0, yaw 0, animation}], up to 16. Each NPC node is separate from the player and from other NPCs. Its animation needs rootMotion and a number parameter "speed": the path follower sets speed to blend idle, walk and run, moves by the root motion, turns at corners and stops at the last point.',
notes: 'Yaw 0 faces -Z; W moves forward. Zone checks use the feet position. physics true is accepted but the web export refuses it for now. scene_export_web writes the playable folder.',
+ animationExample: Object.freeze({
+ type: 'set-game',
+ game: Object.freeze({
+ player: Object.freeze({
+ node: 'walker',
+ walkSpeed: 1.4,
+ animation: Object.freeze({
+ clips: Object.freeze({
+ idle: Object.freeze({ duration: 1, tracks: Object.freeze([Object.freeze({ target: 'body', property: 'translation', keyframes: Object.freeze([Object.freeze({ time: 0, value: Object.freeze([0, 0, 0]) }), Object.freeze({ time: 1, value: Object.freeze([0, 0, 0]) })]) })]) }),
+ walk: Object.freeze({ duration: 1, tracks: Object.freeze([Object.freeze({ target: 'body', property: 'translation', keyframes: Object.freeze([Object.freeze({ time: 0, value: Object.freeze([0, 0, 0]) }), Object.freeze({ time: 1, value: Object.freeze([0, 0, 1.4]) })]) })]) }),
+ }),
+ parameters: Object.freeze({ speed: Object.freeze({ type: 'number' }) }),
+ rootMotion: Object.freeze({ bone: 'body' }),
+ layers: Object.freeze([Object.freeze({ name: 'base', states: Object.freeze([Object.freeze({ name: 'move', blend: Object.freeze({ parameter: 'speed', motions: Object.freeze([Object.freeze({ clip: 'idle', threshold: 0 }), Object.freeze({ clip: 'walk', threshold: 1.4 })]) }) })]) })]),
+ }),
+ }),
+ }),
+ }),
example: Object.freeze({
type: 'set-game',
game: Object.freeze({
diff --git a/src/game-setup.js b/src/game-setup.js
index cc226840..fe1c3a38 100644
--- a/src/game-setup.js
+++ b/src/game-setup.js
@@ -1,4 +1,5 @@
import { validateGameRules } from './game-rules.js';
+import { normalizeGameAnimation } from './game-animation.js';
// The `game` section of a scene recipe: which node the player controls, how, with what camera and input, and the rules
// that decide when the game is won. It is plain data. The runtime in src/game.js reads it; nothing in it is code.
@@ -12,10 +13,13 @@ export const GAME_SETUP_LIMITS = Object.freeze({
maxJumpSpeed: 100,
maxFootOffset: 100,
maxGround: 10000,
+ maxNpcs: 16,
+ maxPathPoints: 256,
});
-const SETUP_FIELDS = ['player', 'camera', 'input', 'physics', 'ground', 'rules'];
-const PLAYER_FIELDS = ['node', 'controller', 'walkSpeed', 'runSpeed', 'jumpSpeed', 'footOffset'];
+const SETUP_FIELDS = ['player', 'camera', 'input', 'physics', 'ground', 'rules', 'npcs'];
+const PLAYER_FIELDS = ['node', 'controller', 'walkSpeed', 'runSpeed', 'jumpSpeed', 'footOffset', 'animation'];
+const NPC_FIELDS = ['node', 'path', 'cruiseSpeed', 'footOffset', 'yaw', 'animation'];
function fail(path, problem) {
throw new RangeError(`Game setup ${path} ${problem}`);
@@ -45,7 +49,7 @@ function boundedNumber(value, fallback, minimum, maximum, path) {
return value;
}
-function normalizePlayer(player, nodeIds) {
+function normalizePlayer(player, nodeIds, nodes) {
requireRecord(player, 'player');
rejectUnknownFields(player, PLAYER_FIELDS, 'player');
if (typeof player.node !== 'string' || !nodeIds.has(player.node)) {
@@ -60,9 +64,57 @@ function normalizePlayer(player, nodeIds) {
jumpSpeed: boundedNumber(player.jumpSpeed, 7, 0, GAME_SETUP_LIMITS.maxJumpSpeed, 'player.jumpSpeed'),
footOffset: boundedNumber(player.footOffset, 0, -GAME_SETUP_LIMITS.maxFootOffset, GAME_SETUP_LIMITS.maxFootOffset, 'player.footOffset'),
};
+ if (player.animation !== undefined) normalized.animation = normalizeGameAnimation(player.animation, nodes, player.node, { path: 'player.animation' });
return normalized;
}
+function isAncestor(nodes, ancestorId, nodeId) {
+ const parentById = new Map(nodes.map(node => [node.id, node.parent]));
+ for (let id = parentById.get(nodeId); id !== undefined; id = parentById.get(id)) {
+ if (id === ancestorId) return true;
+ }
+ return false;
+}
+
+function normalizePath(path, label) {
+ const valid = Array.isArray(path) && path.length >= 1 && path.length <= GAME_SETUP_LIMITS.maxPathPoints
+ && path.every(point => Array.isArray(point) && (point.length === 2 || point.length === 3) && point.every(Number.isFinite));
+ if (!valid) fail(`${label}.path`, `must be 1 to ${GAME_SETUP_LIMITS.maxPathPoints} waypoints, each [x, z] in metres, such as [[0, -4], [6, -4]].`);
+ return path.map(point => [point[0], point[point.length - 1]]);
+}
+
+function normalizeNpc(npc, index, { nodeIds, nodes, taken }) {
+ const label = `npcs[${index}]`;
+ requireRecord(npc, label);
+ rejectUnknownFields(npc, NPC_FIELDS, label);
+ if (typeof npc.node !== 'string' || !nodeIds.has(npc.node)) {
+ fail(`${label}.node`, `names ${JSON.stringify(npc.node)}, which is not a node of the scene. Use one of: ${[...nodeIds].slice(0, 12).join(', ')}.`);
+ }
+ for (const other of taken) {
+ if (other === npc.node || isAncestor(nodes, other, npc.node) || isAncestor(nodes, npc.node, other)) {
+ fail(`${label}.node`, `is "${npc.node}", which overlaps the character "${other}" (same node, or one inside the other). Give each character its own separate node.`);
+ }
+ }
+ taken.push(npc.node);
+ if (npc.animation === undefined) fail(`${label}.animation`, 'is required: an NPC walks through an animation graph with rootMotion and a number parameter "speed". See scene_capabilities topic game.');
+ const animation = normalizeGameAnimation(npc.animation, nodes, npc.node, { path: `${label}.animation`, driven: false });
+ if (!animation.rootMotion) fail(`${label}.animation.rootMotion`, 'is required for an NPC: the follower moves by the root motion of the clips. Add { "bone": "<child node id the walk clip translates>" }.');
+ if (animation.parameters?.speed?.type !== 'number') fail(`${label}.animation.parameters.speed`, 'must be declared as { "type": "number" }: the follower sets it to blend idle, walk and run.');
+ return {
+ node: npc.node,
+ path: normalizePath(npc.path, label),
+ cruiseSpeed: boundedNumber(npc.cruiseSpeed, 2.2, 0.01, GAME_SETUP_LIMITS.maxSpeed, `${label}.cruiseSpeed`),
+ footOffset: boundedNumber(npc.footOffset, 0, -GAME_SETUP_LIMITS.maxFootOffset, GAME_SETUP_LIMITS.maxFootOffset, `${label}.footOffset`),
+ yaw: boundedNumber(npc.yaw, 0, -2 * Math.PI, 2 * Math.PI, `${label}.yaw`),
+ animation,
+ };
+}
+
+function normalizeNpcs(npcs, context) {
+ if (!Array.isArray(npcs) || npcs.length > GAME_SETUP_LIMITS.maxNpcs) fail('npcs', `must be a list of at most ${GAME_SETUP_LIMITS.maxNpcs} NPCs, each { node, path, animation }.`);
+ return npcs.map((npc, index) => normalizeNpc(npc, index, context));
+}
+
function normalizeRules(rules, playerNode) {
let checked;
try {
@@ -78,13 +130,15 @@ function normalizeRules(rules, playerNode) {
}
/**
- * Check a recipe `game` section against the recipe's node ids and return a normalised copy with every default filled in.
- * The rules document is checked by validateGameRules. Errors name the field and say what to pass.
+ * Check a recipe `game` section against the recipe nodes (a list of nodes, or a Set of node ids when there is no animation) and return
+ * a normalised copy with every default filled in. The rules document is checked by validateGameRules. Errors name the field and say what to pass.
*/
-export function normalizeGameSetup(game, nodeIds) {
+export function normalizeGameSetup(game, nodeSource) {
+ const nodes = Array.isArray(nodeSource) ? nodeSource : [];
+ const nodeIds = Array.isArray(nodeSource) ? new Set(nodeSource.map(node => node.id)) : nodeSource;
requireRecord(game, 'game');
rejectUnknownFields(game, SETUP_FIELDS, 'game');
- const player = normalizePlayer(game.player, nodeIds);
+ const player = normalizePlayer(game.player, nodeIds, nodes);
if (game.physics !== undefined && typeof game.physics !== 'boolean') fail('physics', `must be true or false, got ${JSON.stringify(game.physics)}.`);
const normalized = {
player,
@@ -93,6 +147,7 @@ export function normalizeGameSetup(game, nodeIds) {
physics: game.physics ?? false,
ground: boundedNumber(game.ground, 0, -GAME_SETUP_LIMITS.maxGround, GAME_SETUP_LIMITS.maxGround, 'ground'),
};
+ if (game.npcs !== undefined) normalized.npcs = normalizeNpcs(game.npcs, { nodeIds, nodes, taken: [player.node] });
if (game.rules !== undefined) normalized.rules = normalizeRules(game.rules, player.node);
return normalized;
}
diff --git a/src/game.js b/src/game.js
index 7598bf4d..ec04ce8e 100644
--- a/src/game.js
+++ b/src/game.js
@@ -8,6 +8,8 @@ import { createInput, gamepadSource, keyboardSource } from './input.js';
import { replaySource, touchSource } from './input-sources.js';
import { createCharacterController, createFirstPersonCamera, createFollowCamera, createTopDownCamera } from './player.js';
import { createGameRules } from './game-rules.js';
+import { createGameAnimation } from './game-animation.js';
+import { createPathFollower } from './npc-follower.js';
// Plays the `game` section of a scene recipe in a page: the scene, the input preset, the character controller, the camera rig
// and the game rules, all run by the live runtime. scene_export_web writes a folder whose index.html calls startGame.
@@ -63,6 +65,21 @@ function nodeTranslation(nodes, id) {
return position;
}
+// The node a controller or follower moves: its feet position and the heading about the vertical axis.
+function characterOperation(id, position, yaw, footOffset) {
+ return { type: 'set-node', id, translation: [position[0], position[1] + footOffset, position[2]], rotation: [0, Math.sin(yaw / 2), 0, Math.cos(yaw / 2)] };
+}
+
+// Copies the controller's state into the graph parameters that the animation's `drive` names.
+function parameterSystem(animation, controllerState) {
+ return {
+ name: 'animation-parameters',
+ fixedUpdate() {
+ for (const [parameter, source] of Object.entries(animation.drive)) animation.graph.set(parameter, controllerState[source]);
+ },
+ };
+}
+
function litEnvironment(scene, hasAutomaticGround) {
const environment = scene.environment;
return groundBounceEnvironment(scene.parts, { ...environment, map: agentEnvironmentMap(environment) }, { automaticAlbedo: hasAutomaticGround ? FLOOR_COLOR : null });
@@ -133,6 +150,7 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, createRend
const start = nodeTranslation(recipe.nodes, game.player.node);
const body = { position: [0, 0, 0], rotationY: 0 };
let rig = null;
+ const playerAnimation = game.player.animation ? createGameAnimation(game.player.animation, recipe.nodes, game.player.node) : null;
const controller = createCharacterController({
input,
position: [start[0], start[1] - footOffset, start[2]],
@@ -143,12 +161,28 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, createRend
faceCamera: game.camera === 'first-person',
cameraYaw: () => rig?.yaw ?? 0,
node: body,
+ ...(playerAnimation?.hasRootMotion ? { rootMotion: () => playerAnimation.graph.rootMotion.delta } : {}),
});
rig = cameraRigFor(game.camera, controller, input);
const nodeIds = new Set(recipe.nodes.map(node => node.id));
const rules = game.rules ? createGameRules(game.rules, { input, getPartPosition: id => (id === game.player.node ? [...controller.state.position] : undefined) }) : null;
const shownNodes = new Map();
+ const animatedCharacters = [];
+ const animationSystems = [];
+ if (playerAnimation) {
+ animatedCharacters.push(playerAnimation);
+ animationSystems.push(parameterSystem(playerAnimation, controller.state), playerAnimation.graph.system());
+ }
+ const npcs = (game.npcs ?? []).map(npc => {
+ const animation = createGameAnimation(npc.animation, recipe.nodes, npc.node);
+ const start = nodeTranslation(recipe.nodes, npc.node);
+ const follower = createPathFollower({ graph: animation.graph, position: [start[0], start[1] - npc.footOffset, start[2]], yaw: npc.yaw, cruiseSpeed: npc.cruiseSpeed });
+ follower.follow(npc.path);
+ animatedCharacters.push(animation);
+ animationSystems.push(follower.system(), animation.graph.system());
+ return { node: npc.node, footOffset: npc.footOffset, follower, graph: animation.graph };
+ });
let drawnTopology = scene.topologyRevision;
const status = showStatus && rules ? createStatusLine(canvas) : null;
if (status) cleanups.push(() => status.remove());
@@ -157,7 +191,9 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, createRend
name: 'scene',
update(deltaSeconds, context) {
const position = controller.positionAt(context.alpha);
- const operations = [{ type: 'set-node', id: game.player.node, translation: [position[0], position[1] + footOffset, position[2]], rotation: [0, Math.sin(body.rotationY / 2), 0, Math.cos(body.rotationY / 2)] }];
+ const operations = [characterOperation(game.player.node, position, body.rotationY, footOffset)];
+ for (const npc of npcs) operations.push(characterOperation(npc.node, npc.follower.state.position, npc.follower.state.yaw, npc.footOffset));
+ for (const animation of animatedCharacters) operations.push(...animation.operations());
for (const part of rules?.state.parts ?? []) {
if (!nodeIds.has(part.id) || part.id === game.player.node || shownNodes.get(part.id) === part.visible) continue;
shownNodes.set(part.id, part.visible);
@@ -177,7 +213,7 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, createRend
const baseCamera = scene.camera;
const runtime = createRuntime(renderer, {
fixedRate: 60,
- systems: [input, controller, rig, ...(rules ? [rules] : []), sceneSystem],
+ systems: [input, controller, ...animationSystems, rig, ...(rules ? [rules] : []), sceneSystem],
frame: context => ({ ...baseCamera, ...rig.pose(context), environment, time: context.elapsedSeconds }),
});
cleanups.push(() => runtime.dispose());
@@ -187,5 +223,5 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, createRend
resize();
runtime.start();
- return { scene, runtime, rules, input, controller, renderer };
+ return { scene, runtime, rules, input, controller, renderer, animation: playerAnimation?.graph ?? null, npcs };
}
diff --git a/tests/game-animation.test.js b/tests/game-animation.test.js
new file mode 100644
index 00000000..3bac0177
--- /dev/null
+++ b/tests/game-animation.test.js
@@ -0,0 +1,220 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+import { startGame } from '../src/game.js';
+import { GAME_ANIMATION_LIMITS } from '../src/game-animation.js';
+import { GAME_CAPABILITIES } from '../src/game-setup-notes.js';
+import { gaitClip, standClip } from './fixtures/foot-slide.js';
+
+// The animation graph and NPC paths from a recipe: validation at the boundary, then a started game whose planted feet hold
+// still while the player walks and whose NPC walks a path and stops at its end.
+
+const FRAME_MILLISECONDS = 1000 / 60;
+const WALK_SPEED = 1.4;
+const RUN_SPEED = 3.6;
+const FOOT_DRIFT_BOUND = 1e-4;
+const CONTACT_HEIGHT = 1e-6;
+// The first frames pop from the standing pose into the walk once, which is not a sliding foot; contacts are measured after it.
+const SETTLE_FRAMES = 10;
+
+function plainClip(clip) {
+ return {
+ duration: clip.duration,
+ loop: clip.loop,
+ tracks: clip.tracks.map(track => ({
+ target: track.target,
+ property: track.property,
+ keyframes: track.keyframes.map(({ time, value }) => ({ time, value: [...value] })),
+ })),
+ };
+}
+
+function locomotionAnimation(overrides = {}) {
+ return {
+ clips: {
+ idle: plainClip(standClip()),
+ walk: plainClip(gaitClip({ speed: WALK_SPEED, cycle: 1 })),
+ run: plainClip(gaitClip({ speed: RUN_SPEED, cycle: 0.6 })),
+ },
+ parameters: { speed: { type: 'number' } },
+ rootMotion: { bone: 'Root' },
+ layers: [{
+ name: 'base',
+ states: [{
+ name: 'move',
+ blend: { parameter: 'speed', motions: [{ clip: 'idle', threshold: 0 }, { clip: 'walk', threshold: WALK_SPEED }, { clip: 'run', threshold: RUN_SPEED }] },
+ }],
+ }],
+ ...overrides,
+ };
+}
+
+function characterNodes(prefix = '') {
+ const id = name => `${prefix}${name}`;
+ return [
+ { id: id('Walker') },
+ { id: id('Root'), parent: id('Walker') },
+ { id: id('FootL'), parent: id('Root'), translation: [0.1, 0, 0], geometry: 'block', material: 'paint' },
+ { id: id('FootR'), parent: id('Root'), translation: [-0.1, 0, 0], geometry: 'block', material: 'paint' },
+ ];
+}
+
+function sceneWith(nodes) {
+ return createAgentScene({
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box' }], materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],
+ nodes,
+ });
+}
+
+function setGame(scene, game) {
+ scene.apply([{ type: 'set-game', game }], { expectedRevision: scene.revision });
+ return scene.exportRecipe();
+}
+
+function prefixedAnimation(prefix) {
+ const animation = locomotionAnimation();
+ for (const clip of Object.values(animation.clips)) clip.tracks.forEach(track => { track.target = `${prefix}${track.target}`; });
+ animation.rootMotion = { bone: `${prefix}Root` };
+ return animation;
+}
+
+function rejection(game, nodes = characterNodes()) {
+ const scene = sceneWith(nodes);
+ return () => scene.apply([{ type: 'set-game', game }], { expectedRevision: scene.revision });
+}
+
+const standInRenderer = () => ({ render() {}, resize() {}, updateParts() {}, replaceParts() {}, dispose() {} });
+
+async function startRecipe(recipe, replay) {
+ const previous = { request: globalThis.requestAnimationFrame, cancel: globalThis.cancelAnimationFrame };
+ globalThis.requestAnimationFrame = () => 1;
+ globalThis.cancelAnimationFrame = () => {};
+ const game = await startGame({}, recipe, { replay, showStatus: false, createRenderer: standInRenderer });
+ return {
+ game,
+ finish() {
+ game.dispose();
+ globalThis.requestAnimationFrame = previous.request;
+ globalThis.cancelAnimationFrame = previous.cancel;
+ },
+ };
+}
+
+function nodeNamed(scene, id) {
+ return scene.exportRecipe().nodes.find(node => node.id === id);
+}
+
+test('a recipe blends idle, walk and run by speed and a planted foot stays put while the player walks', async () => {
+ const withAnimation = setGame(sceneWith(characterNodes()), { player: { node: 'Walker', walkSpeed: WALK_SPEED, runSpeed: RUN_SPEED, animation: locomotionAnimation() } });
+ assert.deepEqual(withAnimation.game.player.animation.drive, { speed: 'intentSpeed' });
+ const replay = { version: 1, samples: 600, events: [[1, 'keyboard/KeyW', 1]] };
+ const { game, finish } = await startRecipe(withAnimation, replay);
+ try {
+ const contacts = new Map([['FootL', null], ['FootR', null]]);
+ const drifts = [];
+ for (let frame = 0; frame < 480; frame++) {
+ game.runtime.step(FRAME_MILLISECONDS);
+ if (frame < SETTLE_FRAMES) continue;
+ for (const foot of contacts.keys()) {
+ const local = nodeNamed(game.scene, foot).translation;
+ const world = [game.controller.state.position[0] - local[0], game.controller.state.position[2] - local[2]];
+ if (local[1] > CONTACT_HEIGHT) {
+ contacts.set(foot, null);
+ continue;
+ }
+ if (!contacts.get(foot)) contacts.set(foot, { anchor: world, drift: 0 });
+ const contact = contacts.get(foot);
+ contact.drift = Math.max(contact.drift, Math.hypot(world[0] - contact.anchor[0], world[1] - contact.anchor[1]));
+ drifts.push(contact.drift);
+ }
+ }
+ assert.ok(game.controller.state.position[2] < -5, `the player walked forward, z ${game.controller.state.position[2]}`);
+ assert.ok(Math.abs(game.animation.get('speed') - WALK_SPEED) < 1e-9, 'speed parameter follows the controller intent');
+ assert.ok(Math.max(0, ...drifts) < FOOT_DRIFT_BOUND, `worst planted foot drift ${Math.max(0, ...drifts)} m`);
+ } finally {
+ finish();
+ }
+});
+
+test('an NPC follows a path from the recipe, blends into walk and stops at the end', async () => {
+ const nodes = [...characterNodes(), ...characterNodes('Npc').map(node => ({ ...node, ...(node.id === 'NpcWalker' ? { translation: [4, 0, 0] } : {}) }))];
+ const npc = { node: 'NpcWalker', path: [[4, -6], [8, -6]], cruiseSpeed: WALK_SPEED, animation: prefixedAnimation('Npc') };
+ const recipe = setGame(sceneWith(nodes), { player: { node: 'Walker' }, npcs: [npc] });
+ assert.equal(recipe.game.npcs[0].footOffset, 0);
+ const { game, finish } = await startRecipe(recipe, { version: 1, samples: 1, events: [] });
+ try {
+ const [follower] = game.npcs.map(entry => entry.follower);
+ for (let frame = 0; frame < 60 * 20 && follower.state.status !== 'arrived'; frame++) game.runtime.step(FRAME_MILLISECONDS);
+ assert.equal(follower.state.status, 'arrived');
+ assert.ok(Math.hypot(follower.state.position[0] - 8, follower.state.position[2] + 6) < 0.15, `NPC at ${follower.state.position}`);
+ const placed = nodeNamed(game.scene, 'NpcWalker').translation;
+ assert.deepEqual(placed.map(value => Number(value.toFixed(6))), follower.state.position.map(value => Number(value.toFixed(6))));
+ game.runtime.step(250);
+ assert.equal(game.npcs[0].graph.get('speed'), 0, 'the NPC returns to idle');
+ } finally {
+ finish();
+ }
+});
+
+test('an animation names the field and the fix when it is wrong', () => {
+ const player = animation => ({ player: { node: 'Walker', animation } });
+ assert.throws(rejection(player(locomotionAnimation({ extra: 1 }))), /player\.animation\.extra is not a field\. Use one of: clips/);
+ const missingTarget = locomotionAnimation();
+ missingTarget.clips.walk.tracks[0].target = 'Ghost';
+ assert.throws(rejection(player(missingTarget)), /player\.animation\.clips\.walk\.tracks\[0\]\.target names "Ghost", which is not a child node of the character\. Use one of: Root, FootL, FootR/);
+ const onCharacter = locomotionAnimation();
+ onCharacter.clips.walk.tracks[0].target = 'Walker';
+ assert.throws(rejection(player(onCharacter)), /not a child node of the character/);
+ const badProperty = locomotionAnimation();
+ badProperty.clips.idle.tracks[0].property = 'scale';
+ assert.throws(rejection(player(badProperty)), /property is "scale"\. Use one of: translation, rotation/);
+ assert.throws(rejection(player(locomotionAnimation({ layers: [{ name: 'base', states: [{ name: 'move', clip: 'jog' }] }] }))), /player\.animation: .*jog/);
+ assert.throws(rejection(player(locomotionAnimation({ drive: { speed: 'velocity' } }))), /drive\.speed is "velocity"\. Use one of: speed, intentSpeed, airborne/);
+ assert.throws(rejection(player(locomotionAnimation({ drive: { airborne: 'airborne' } }))), /drive\.airborne needs a boolean parameter/);
+ assert.throws(rejection(player(locomotionAnimation({ clips: {} }))), /clips needs 1 to 16 clips/);
+ assert.throws(rejection({ player: { node: 'Root', animation: locomotionAnimation() } }), /has nothing to move|not a child node/);
+});
+
+test('animation counts are bounded', () => {
+ const tooManyClips = locomotionAnimation();
+ tooManyClips.clips = Object.fromEntries(Array.from({ length: GAME_ANIMATION_LIMITS.maxClips + 1 }, (_, index) => [`clip${index}`, plainClip(standClip())]));
+ assert.throws(rejection({ player: { node: 'Walker', animation: tooManyClips } }), /needs 1 to 16 clips, got 17/);
+ const tooManyKeys = locomotionAnimation();
+ tooManyKeys.clips.idle.tracks[0].keyframes = Array.from({ length: GAME_ANIMATION_LIMITS.maxKeyframesPerTrack + 1 }, (_, index) => ({ time: index / 1000, value: [0.1, 0, 0] }));
+ assert.throws(rejection({ player: { node: 'Walker', animation: tooManyKeys } }), /needs 1 to 256 keyframes/);
+});
+
+test('an NPC needs a node of its own, root motion, a speed parameter and a path', () => {
+ const nodes = [...characterNodes(), ...characterNodes('Npc')];
+ const npc = overrides => ({ player: { node: 'Walker' }, npcs: [{ node: 'NpcWalker', path: [[0, -4]], animation: prefixedAnimation('Npc'), ...overrides }].map(entry => Object.fromEntries(Object.entries(entry).filter(([, value]) => value !== undefined))) });
+ assert.throws(rejection(npc({ animation: undefined }), nodes), /npcs\[0\]\.animation is required/);
+ assert.throws(rejection(npc({ node: 'Walker', animation: locomotionAnimation() }), nodes), /overlaps the character "Walker"/);
+ assert.throws(rejection(npc({ node: 'Ghost' }), nodes), /npcs\[0\]\.node names "Ghost"/);
+ assert.throws(rejection(npc({ path: [] }), nodes), /npcs\[0\]\.path must be 1 to 256 waypoints, each \[x, z\]/);
+ assert.throws(rejection(npc({ path: [[0, 'far']] }), nodes), /npcs\[0\]\.path must be/);
+ assert.throws(rejection(npc({ cruiseSpeed: 500 }), nodes), /npcs\[0\]\.cruiseSpeed must be a number from 0\.01 to 100/);
+ const noRootMotion = prefixedAnimation('Npc');
+ delete noRootMotion.rootMotion;
+ assert.throws(rejection(npc({ animation: noRootMotion }), nodes), /rootMotion is required for an NPC/);
+ const noSpeed = prefixedAnimation('Npc');
+ noSpeed.parameters = { pace: { type: 'number' } };
+ noSpeed.layers[0].states[0].blend.parameter = 'pace';
+ assert.throws(rejection(npc({ animation: noSpeed }), nodes), /parameters\.speed must be declared/);
+ assert.throws(rejection(npc({ animation: { ...prefixedAnimation('Npc'), drive: { speed: 'speed' } } }), nodes), /drive is not allowed on an NPC/);
+});
+
+test('the scene_capabilities animation example is a valid operation', () => {
+ const scene = sceneWith([{ id: 'walker' }, { id: 'body', parent: 'walker' }]);
+ scene.apply([structuredClone(GAME_CAPABILITIES.animationExample)], { expectedRevision: scene.revision });
+ assert.equal(scene.exportRecipe().game.player.animation.drive.speed, 'intentSpeed');
+ assert.match(GAME_CAPABILITIES.animation, /never the character/);
+});
+
+test('clearing the game removes the animation with it', () => {
+ const scene = sceneWith(characterNodes());
+ setGame(scene, { player: { node: 'Walker', animation: locomotionAnimation() } });
+ scene.apply([{ type: 'set-game', game: null }], { expectedRevision: scene.revision });
+ assert.equal(scene.exportRecipe().game, undefined);
+});