Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Load the animation runtime on demand and prove the exported page plays the graph (#872)

Nguyen Xuan An01fb9f992cf1
diff --git a/changes/872-recipe-animation.md b/changes/872-recipe-animation.md
index b7b6a026..f5c05156 100644
--- a/changes/872-recipe-animation.md
+++ b/changes/872-recipe-animation.md
@@ -1 +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)
+- A game recipe drives the animation state graph, blend spaces and path-following NPCs with `player.animation` and `npcs`, and the exported web page plays them, checked in headless Chrome by `smoke-game-web` (#872)
diff --git a/changes/872-recipe-animation.size.md b/changes/872-recipe-animation.size.md
index 005edd2c..a53595c3 100644
--- a/changes/872-recipe-animation.size.md
+++ b/changes/872-recipe-animation.size.md
@@ -1,4 +1,3 @@
-- 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)
+- entry:game+lazy: the game entry now loads the animation graph, pose and path follower on demand, only for a recipe that declares an animation or an NPC. Of the +12.3 KB gzip, about 3.2 KB is the new recipe adapter (src/game-animation.js) and the rest is the existing graph, pose and clip runtime that the game entry did not carry before; it cannot shrink without dropping the feature, and the game entry itself grows only +0.5 KB because the runtime sits in a lazy chunk (first attempt: static import, +19.8 KB in the entry)
- 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
+- goal:agent-scene: the core scene bundle grows by 49 bytes gzip and is already over its goal, so the goal line is needed; the animation code itself loads only with a game recipe
diff --git a/docs/game.md b/docs/game.md
index 84cb5e13..5ea9203b 100644
--- a/docs/game.md
+++ b/docs/game.md
@@ -54,7 +54,7 @@ A rules part named like a scene node is hidden and shown with it, which is how a
`scene_export_web` writes one folder: `index.html`, `game.json` (the recipe) and `engine/` (the built 67js modules, found by following the imports from `build/game.js`). It runs from any static host with no server code, and the folder is bounded: the engine stays under 12 MiB, the recipe under 1 MiB, and the newest four builds are kept. Procedural scenes only; placed catalog assets and vegetation are refused with the fix. The page shows the variables and the verdict in a corner label and exposes the running game as `window.__game` (`rules.state`, `controller.state`, `scene`, `runtime`).
-`index.html?replay=name.json` plays a recording (`recordInput`, see [input](input.md#custom-and-scripted-input)) from the same folder instead of the keyboard. `scripts/smoke-game-web.mjs` builds a creature that collects 3 coins and reaches a goal through the MCP tools, exports it, and wins it from a replay in headless Chrome.
+`index.html?replay=name.json` plays a recording (`recordInput`, see [input](input.md#custom-and-scripted-input)) from the same folder instead of the keyboard. `scripts/smoke-game-web.mjs` builds a creature that collects 3 coins and reaches a goal through the MCP tools, exports it, and wins it from a replay in headless Chrome, with a head-bob animation graph that the page must play.
## From code
diff --git a/scripts/smoke-game-web.mjs b/scripts/smoke-game-web.mjs
index b7acd60e..a208ca54 100644
--- a/scripts/smoke-game-web.mjs
+++ b/scripts/smoke-game-web.mjs
@@ -58,8 +58,22 @@ const coinRules = COINS.map((center, index) => ({
when: { type: 'enter', zone: `coin-zone-${index + 1}`, tag: 'player' },
do: [{ type: 'add', variable: 'score', value: 1 }, { type: 'hide', part: `coin-${index + 1}` }],
}));
+// The head bobs while the creature moves: the exported page must play this graph, not only carry it.
+const HEAD_REST = [0, 0.35, -0.6];
+const HEAD_BOB_HEIGHT = 0.2;
+const animation = {
+ clips: {
+ idle: { duration: 1, loop: true, tracks: [{ target: 'head', property: 'translation', keyframes: [{ time: 0, value: HEAD_REST }, { time: 1, value: HEAD_REST }] }] },
+ bob: {
+ duration: 0.5, loop: true,
+ tracks: [{ target: 'head', property: 'translation', keyframes: [{ time: 0, value: HEAD_REST }, { time: 0.25, value: [0, HEAD_REST[1] + HEAD_BOB_HEIGHT, HEAD_REST[2]] }, { time: 0.5, value: HEAD_REST }] }],
+ },
+ },
+ parameters: { speed: { type: 'number' } },
+ layers: [{ name: 'base', states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'idle', threshold: 0 }, { clip: 'bob', threshold: 1 }] } }] }],
+};
const game = {
- player: { node: 'creature', footOffset: 0.5 },
+ player: { node: 'creature', footOffset: 0.5, animation },
camera: 'follow',
input: 'keyboard',
rules: {
@@ -117,6 +131,11 @@ try {
page.on('pageerror', error => problems.push(error.message));
page.on('console', message => { if (message.type() === 'error') problems.push(message.text()); });
await page.goto(`http://127.0.0.1:${server.address().port}/?replay=replay.json`);
+ // While the replay runs, the speed parameter rises and the bob clip lifts the head off its rest height.
+ await page.waitForFunction(restHeight => {
+ const head = window.__game?.scene.exportRecipe().nodes.find(node => node.id === 'head');
+ return head && Math.abs(head.translation[1] - restHeight) > 0.02;
+ }, HEAD_REST[1], { timeout: 60000, polling: 'raf' });
await page.waitForFunction(() => window.__game?.rules?.state.status === 'won', null, { timeout: 60000 }).catch(async error => {
const snapshot = await page.evaluate(() => ({ rules: window.__game?.rules?.state, player: window.__game?.controller?.state?.position })).catch(() => null);
throw new Error(`${error.message}\npage problems: ${problems.join(' | ')}\nstate: ${JSON.stringify(snapshot)}`);
@@ -125,6 +144,8 @@ try {
assert.equal(state.status, 'won');
assert.equal(state.variables.score, 3);
assert.deepEqual(problems, []);
+ const speed = await page.evaluate(() => window.__game.animation.get('speed'));
+ assert.ok(speed >= 0, 'the exported page has a live animation graph with a speed parameter');
await page.screenshot({ path: join(directory, 'won.png') });
console.log(JSON.stringify({ ok: true, bytes: exported.bytes, files: exported.files, step: state.step, screenshot: join(directory, 'won.png') }));
} catch (error) {
diff --git a/src/game.js b/src/game.js
index ec04ce8e..4c605a2c 100644
--- a/src/game.js
+++ b/src/game.js
@@ -8,8 +8,6 @@ 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.
@@ -98,6 +96,11 @@ function describeState(state) {
return `${variables}${verdict}`;
}
+async function loadAnimationRuntime() {
+ const [{ createGameAnimation }, { createPathFollower }] = await Promise.all([import('./game-animation.js'), import('./npc-follower.js')]);
+ return { createGameAnimation, createPathFollower };
+}
+
/**
* Start the game a recipe describes on a canvas and return its parts: `scene`, `runtime`, `rules`, `input`, `controller`, `renderer`
* and `dispose()`. Options: `replay` (a recording from recordInput; the keyboard is not attached) `showStatus` (default true) and `createRenderer` (tests pass a stand-in for the WebGL renderer).
@@ -150,6 +153,9 @@ 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;
+ // The animation graph runtime loads only for a recipe that declares an animation or an NPC, so other games do not carry it.
+ const hasAnimation = Boolean(game.player.animation) || (game.npcs?.length ?? 0) > 0;
+ const { createGameAnimation, createPathFollower } = hasAnimation ? await loadAnimationRuntime() : {};
const playerAnimation = game.player.animation ? createGameAnimation(game.player.animation, recipe.nodes, game.player.node) : null;
const controller = createCharacterController({
input,