Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Smoke the retargeted character on the exported page and document it (#913)

Nguyen Xuan An6d1fad828adb
diff --git a/changes/913-web-and-skill.md b/changes/913-web-and-skill.md
new file mode 100644
index 00000000..e6c228cc
--- /dev/null
+++ b/changes/913-web-and-skill.md
@@ -0,0 +1 @@
+- `set-game` over MCP can turn a placed asset into an animated player or NPC: the server now loads the extra decoded copy the game's animation needs, so a retargeted character set up by `scene_apply` no longer fails with "copy 1 is not loaded"; `smoke-game-web.mjs character` walks a retargeted humanoid to a goal on the exported page, and the `build-67js-scene` skill has a game reference on animating a placed character (Closes #913)
diff --git a/docs/game.md b/docs/game.md
index b30f9291..9f9899f3 100644
--- a/docs/game.md
+++ b/docs/game.md
@@ -55,7 +55,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. Placed catalog assets (and the assets whose clips a character retargets) are copied to `assets/<id>.glb`, up to 64 MiB together; grown vegetation is 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, with a head-bob animation graph that the page must play. `node scripts/smoke-game-web.mjs bin/67js-mcp.mjs drive` does the same for a car that passes 3 gates and reaches a finish line under a `chase` camera.
+`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. `node scripts/smoke-game-web.mjs bin/67js-mcp.mjs drive` does the same for a car that passes 3 gates and reaches a finish line under a `chase` camera. The `character` sample walks a placed, retargeted humanoid (idle and walk clips of another file) to a goal, and checks that the page loads `assets/<id>.glb` and the character's limbs move.
## From code
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 5eff4482..45cc8c65 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -1106,7 +1106,7 @@ window.__agentPreview = {
return afterMeshBooleans(input.operations, () => this.applyLoaded(input));
});
}
- if (recipeAssetNeeds(input.operations).length) return this.applyWithAssets(input);
+ if (input.assetNeeds || recipeAssetNeeds(input.operations).length) return this.applyWithAssets(input);
return afterMeshBooleans(input.operations, () => this.applyLoaded(input));
},
async applyWithAssets(input) {
@@ -1115,7 +1115,7 @@ window.__agentPreview = {
throw new Error('This scene was created without placed assets. Recreate it with an asset node in scene_create, then add more.');
}
await loadAllAgentSceneModules();
- await loadPlacedAssets(record.placedAssets, input.operations, input.assetData);
+ await loadPlacedAssets(record.placedAssets, input.assetNeeds ?? input.operations, input.assetData);
return afterMeshBooleans(input.operations, () => this.applyLoaded(input));
},
applyLoaded({ sessionId, operations, expectedRevision }) {
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index fba9daa4..4e527eed 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -165,6 +165,18 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return { ...(needs.length ? { assetData: Object.fromEntries(entries) } : {}), ...(await sequenceFrameData(value)), ...(await lookFileData(value)) };
}
+ /**
+ * A set-game that animates a node the scene already places needs one more decoded copy of that asset, which the operations alone do not
+ * name. Returns the scene's nodes with the new game, which the page and the byte loader read the asset needs from, or undefined.
+ */
+ async function gameAssetNeeds({ sessionId, operations }) {
+ const setGame = (operations ?? []).findLast(operation => operation.type === 'set-game');
+ if (!setGame?.game) return undefined;
+ const { recipe } = await invoke('exportRecipe', { sessionId });
+ const candidate = { nodes: recipe.nodes, game: setGame.game };
+ return recipeAssetNeeds(candidate).some(need => need.copies > 1) ? { recipe: candidate } : undefined;
+ }
+
/** The HDRI and .cube files a recipe names: shipped ones by name from assets/looks, the others by catalog ID. The page decodes them. */
async function lookFileData(value) {
const { environments, looks } = catalogLookReferences(value);
@@ -851,7 +863,8 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
const hadBake = bakedSessionIds.has(input.sessionId);
const rebakes = hadBake || bakeAfter === true;
const motions = (input.operations ?? []).filter(operation => operation.type === 'set-motion').map(operation => operation.motion);
- const applied = await invoke('apply', { ...input, ...(await motionSources(motions)), ...(await placedAssetData(input.operations)) }, rebakes ? BAKE_EVALUATION_TIMEOUT_MS : EVALUATION_TIMEOUT_MS);
+ const gameAssets = await gameAssetNeeds(input);
+ const applied = await invoke('apply', { ...input, ...(await motionSources(motions)), ...(await placedAssetData(gameAssets?.recipe ?? input.operations)), ...(gameAssets ? { assetNeeds: gameAssets.recipe } : {}) }, rebakes ? BAKE_EVALUATION_TIMEOUT_MS : EVALUATION_TIMEOUT_MS);
if (bakeAfter ?? hadBake) bakedSessionIds.add(input.sessionId);
else bakedSessionIds.delete(input.sessionId);
return applied;
diff --git a/scripts/smoke-game-web.mjs b/scripts/smoke-game-web.mjs
index 6c043e20..f77cd3f9 100644
--- a/scripts/smoke-game-web.mjs
+++ b/scripts/smoke-game-web.mjs
@@ -1,24 +1,29 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
-import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises';
import { tmpdir, constants, setPriority } from 'node:os';
import { dirname, extname, join, resolve } from 'node:path';
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import { chromium } from 'playwright-core';
+import { MIXAMO_LIKE, UNREAL_LIKE, humanoidGlb, humanoidJoints, walkTracks } from '../tests/fixtures/humanoid-glb.js';
// Proves the game path end to end: an agent builds a creature that runs and jumps to collect 3 coins and reach a goal using
// only MCP tools, exports it as a static web build, and a recorded input replay wins the game in headless Chrome on the GPU.
-// A second sample drives a car through 3 gates to a finish line. Run it through your GPU lock if the machine is shared:
-// node scripts/smoke-game-web.mjs [path to 67js-mcp.mjs] [creature|drive]
+// A second sample drives a car through 3 gates to a finish line, and a third walks a placed, retargeted humanoid to a goal while
+// its idle and walk clips blend by speed (the page loads the exported assets/<id>.glb files). Run it through your GPU lock if the machine is shared:
+// node scripts/smoke-game-web.mjs [path to 67js-mcp.mjs] [creature|drive|character]
setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
const CHROME_PATH = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const directory = await mkdtemp(join(tmpdir(), '67js-game-web-'));
const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
-const MIME_TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json' };
+const MIME_TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.glb': 'model/gltf-binary' };
-const transport = new StdioClientTransport({ command: process.execPath, args: [cli, '--backend', 'cpu', '--memory', '128', '--jobs', join(directory, 'jobs')], cwd: directory, stderr: 'pipe' });
+const assetsDirectory = join(directory, 'assets');
+await mkdir(assetsDirectory);
+const transport = new StdioClientTransport({ command: process.execPath, args: [cli, '--backend', 'cpu', '--memory', '128', '--jobs', join(directory, 'jobs'), '--assets', assetsDirectory], cwd: directory, stderr: 'pipe' });
let diagnostics = '';
transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
const client = new Client({ name: '67js-game-web-proof', version: '1' });
@@ -126,10 +131,56 @@ function driveSample() {
return { recipe, game, replay, title: 'Drive', expectedScore: 3 };
}
-const SAMPLES = { creature: creatureSample, drive: driveSample };
+function characterSample() {
+ const WALK_SPEED = 1.2;
+ const GOAL_Z = -4;
+ const sourceJoints = humanoidJoints();
+ const clip = (name, duration, speed) => ({ name, duration, tracks: walkTracks(sourceJoints, { speed, duration }) });
+ const sourceBytes = Buffer.from(humanoidGlb({ names: MIXAMO_LIKE, joints: sourceJoints, clips: [clip('Idle', 1, 0), clip('Walk', 1, WALK_SPEED)] }));
+ const heroBytes = Buffer.from(humanoidGlb({ names: UNREAL_LIKE, joints: humanoidJoints({ armTiltDegrees: 30 }) }));
+ const idOf = bytes => createHash('sha256').update(bytes).digest('hex');
+ const sourceId = idOf(sourceBytes);
+ const heroId = idOf(heroBytes);
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials: [{ id: 'grass', color: [0.2, 0.45, 0.2] }],
+ nodes: [
+ { id: 'floor', geometry: 'block', material: 'grass', translation: [0, -0.1, -4], scale: [10, 0.2, 14] },
+ { id: 'Hero', asset: { id: heroId } },
+ ],
+ camera: { eye: [3, 2, 3], target: [0, 1, -2], fov: 50 },
+ };
+ const game = {
+ player: {
+ node: 'Hero', walkSpeed: WALK_SPEED, runSpeed: 2.4,
+ animation: {
+ clips: { idle: { from: { asset: sourceId, clip: 0 } }, walk: { from: { asset: sourceId, clip: 1 } } },
+ parameters: { speed: { type: 'number' } },
+ rootMotion: { bone: UNREAL_LIKE.hips },
+ layers: [{ name: 'base', states: [{ name: 'move', blend: { parameter: 'speed', motions: [{ clip: 'idle', threshold: 0 }, { clip: 'walk', threshold: WALK_SPEED }] } }] }],
+ },
+ },
+ camera: 'follow',
+ input: 'keyboard',
+ rules: {
+ version: 1,
+ zones: [{ id: 'goal-zone', shape: 'box', center: [0, 1, GOAL_Z], size: [3, 4, 2] }],
+ parts: [{ id: 'Hero', tags: ['player'] }],
+ rules: [{ id: 'reach-goal', when: { type: 'enter', zone: 'goal-zone', tag: 'player' }, do: [{ type: 'win' }] }],
+ },
+ };
+ // Hold forward from sample 1; at walking speed the character reaches the goal in about 3 s.
+ const replay = { version: 1, samples: 400, truncated: false, events: [[1, 'keyboard/KeyW', 1], [390, 'keyboard/KeyW', 0]] };
+ const assetFiles = { 'source.glb': sourceBytes, 'hero.glb': heroBytes };
+ return { recipe, game, replay, title: 'Retargeted walk', expectedScore: undefined, assetFiles, expectedAssets: [sourceId, heroId] };
+}
+
+const SAMPLES = { creature: creatureSample, drive: driveSample, character: characterSample };
const sampleName = process.argv[3] ?? 'creature';
assert.ok(SAMPLES[sampleName], `Unknown sample "${sampleName}". Use one of: ${Object.keys(SAMPLES).join(', ')}.`);
-const { recipe, game, replay, title, expectedScore, headRestHeight } = SAMPLES[sampleName]();
+const { recipe, game, replay, title, expectedScore, headRestHeight, assetFiles = {}, expectedAssets = [] } = SAMPLES[sampleName]();
+for (const [name, bytes] of Object.entries(assetFiles)) await writeFile(join(assetsDirectory, name), bytes);
function serveFolder(folder) {
const server = createServer(async (request, response) => {
@@ -181,18 +232,33 @@ try {
return head && Math.abs(head.translation[1] - restHeight) > 0.02;
}, headRestHeight, { timeout: 60000, polling: 'raf' });
}
+ if (expectedAssets.length > 0) {
+ // The character is a skinned asset: while the replay walks it, some part must rise and fall as the walk clip plays.
+ await page.waitForFunction(() => {
+ const ranges = (window.__heightRanges ??= new Map());
+ for (const part of window.__game?.scene.parts ?? []) {
+ if (!part.name.startsWith('Hero/')) continue;
+ const range = ranges.get(part.name) ?? { low: Infinity, high: -Infinity };
+ range.low = Math.min(range.low, part.matrix[13]);
+ range.high = Math.max(range.high, part.matrix[13]);
+ ranges.set(part.name, range);
+ }
+ return [...ranges.values()].some(range => range.high - range.low > 0.02);
+ }, null, { 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)}`);
});
const state = await page.evaluate(() => ({ ...window.__game.rules.state, y: window.__game.controller.state.position[1] }));
assert.equal(state.status, 'won');
- assert.equal(state.variables.score, expectedScore);
+ if (expectedScore !== undefined) assert.equal(state.variables.score, expectedScore);
assert.deepEqual(problems, []);
if (game.player.animation) {
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');
}
+ for (const id of expectedAssets) assert.ok(await readFile(join(folder, 'assets', `${id}.glb`)), `the export writes assets/${id}.glb`);
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/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 522979af..ca3c37c5 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -35,6 +35,7 @@ Variants: `scene_apply` with a `branch` name, compare in one `scene_review` (a `
| Lens, focal length, depth of field, shift, orthographic | `${CLAUDE_SKILL_DIR}/references/camera.md` |
| Motion tracks (camera, nodes, lights, sun, sky, effects), shots, timeline | `${CLAUDE_SKILL_DIR}/references/film-and-animation.md` |
| A call failed, a diagnostic appeared, the picture is wrong | `${CLAUDE_SKILL_DIR}/references/errors-and-recovery.md` |
+| A playable game: animate a placed, retargeted character (idle, walk, run), web export | `${CLAUDE_SKILL_DIR}/references/game.md` |
| Polygon modeling: extrude, inset, bevel, booleans, mirror, array | `${CLAUDE_SKILL_DIR}/references/mesh-modeling.md` |
| Scene code against the npm library, not MCP | `${CLAUDE_SKILL_DIR}/references/scene-contract.md` |
diff --git a/skills/build-67js-scene/references/game.md b/skills/build-67js-scene/references/game.md
new file mode 100644
index 00000000..31e853d4
--- /dev/null
+++ b/skills/build-67js-scene/references/game.md
@@ -0,0 +1,14 @@
+# Game: animate a placed character
+
+A game is the recipe `game` section (`set-game`); `scene_capabilities` topic `game` lists its fields and `scene_export_web` writes a page that plays it.
+
+## Animate a placed asset character
+
+Place the character as an asset node (`{ "id": "Hero", "asset": { "id": "<catalog id>" } }`), name that node in `game.player.node` (or `game.npcs[].node`) and give `game.player.animation` clips that point at asset files instead of keyed tracks:
+`"clips": { "idle": { "from": { "asset": "<id>", "clip": 0 } }, "walk": { "from": { "asset": "<id>", "clip": 1 } } }`.
+A clip of another humanoid file is retargeted onto the character's skeleton, so one locomotion pack serves many characters; leave out `from.asset` to use the character's own clips.
+Blend them by speed with a `blend` state on the `speed` parameter, thresholds at the clip speeds (idle 0, walk `walkSpeed`, run `runSpeed`), and set `rootMotion.bone` to the character's hips so the controller, not the clip, moves the node.
+Bones in `rootMotion`, `boneGroups` and masks use the character's own joint names. Do not pose the character by hand with `set-node`; the game poses it each frame.
+
+Check it with a replay before exporting: `scene_export_web` copies the character and the clip sources to `assets/<id>.glb`, and a held forward key shows the legs moving in `?replay=name.json`.
+If a clip index or bone is wrong, the error names the field and the valid choices; fix that field rather than changing the clip. A character takes its own decoded copy, and at most 16 placements animate.