Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add MCP game setup (set-game) and scene_export_web static web build (part of #777)

Nguyen Xuan An0f8ca9e79a81
diff --git a/README.md b/README.md
index 89fbb962..e9e59b73 100644
--- a/README.md
+++ b/README.md
@@ -146,6 +146,7 @@ Each addon is a separate import, so a page loads only what it uses.
| 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 |
| Live games | `67js/addons/player` | [Player](docs/player.md): character controller, follow, first-person and top-down camera rigs, swappable at runtime |
| Live games | `67js/addons/game-rules` | [Game rules](docs/game-rules.md): a JSON rule document of variables, triggers and actions, played as a runtime system |
+| Live games | `67js/addons/game` | [Game](docs/game.md): a scene recipe with a `game` section played in a page, and the `scene_export_web` MCP tool that writes it as a static web build |
| 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/changes/777-mcp.md b/changes/777-mcp.md
new file mode 100644
index 00000000..df0d3cf1
--- /dev/null
+++ b/changes/777-mcp.md
@@ -0,0 +1 @@
+- MCP can attach a playable game to a scene (`set-game`, topic `game` in `scene_capabilities`) and `scene_export_web` writes it as a static web build; `67js/addons/game` plays it in a page (#777)
diff --git a/changes/777-mcp.size.md b/changes/777-mcp.size.md
new file mode 100644
index 00000000..e22be23f
--- /dev/null
+++ b/changes/777-mcp.size.md
@@ -0,0 +1,5 @@
+- tool:scene_apply: set-game operation, so a game attaches to a scene without a new tool (408 bytes)
+- tool:scene_create: recipe game section, same reason (275 bytes)
+- tool:scene_export_web: a new tool, 780 bytes, because its result is a folder and its arguments differ from scene_export_glb
+- scene:agent-scene+lazy: the game setup check and the game rules code load on demand with set-game; a recipe without a game never loads them
+- tool-total: set-game and scene_export_web let an agent make a playable game; the detail is in scene_capabilities topic game
diff --git a/docs/game-rules.md b/docs/game-rules.md
index 6333f251..4bac0b41 100644
--- a/docs/game-rules.md
+++ b/docs/game-rules.md
@@ -105,4 +105,4 @@ After `win` or `lose`, `fixedUpdate` does nothing until `restart()`. Same inputs
`GAME_RULES_LIMITS` exports them. `validateGameRules(document)` checks a document alone and returns a normalised copy. An error names the field and says what to pass, such as `Game rules rules[2].do[1].variable names the variable "scor", which is not declared. Use one of: score, secondsLeft.` An unknown field, an undeclared variable, zone, part, prefab or tag, and an input trigger with no `options.input` are all errors.
-The tool surface for an agent (MCP) comes later. It will need the agent bench before it ships.
+An agent sets this document inside a scene recipe `game` section with `set-game`, and `scene_export_web` plays it in a static web build; see [Game](game.md).
diff --git a/docs/game.md b/docs/game.md
new file mode 100644
index 00000000..585d11f6
--- /dev/null
+++ b/docs/game.md
@@ -0,0 +1,65 @@
+# Game: a playable scene from a recipe
+
+A scene recipe can carry a `game` section. It names the node the player controls, the controller, camera and input preset, and a [game rules](game-rules.md) document. `67js/addons/game` plays it in a page, and the MCP tool `scene_export_web` writes it as a static web build. The section is plain data: there is no script, so an agent can create and edit it without running anything it wrote.
+
+## Build one through MCP
+
+1. `scene_create` with the scene. The player is a node (a group is fine: its children move with it).
+2. `scene_apply` with `{ "type": "set-game", "game": { ... } }`. `null` clears it. A wrong field is refused with its name and the values to use; `scene_capabilities` with `topic: "game"` lists every field and one small example.
+3. `scene_export_web` with an optional `title`. The result has the path of `index.html`. It needs `--jobs`, like `scene_export_glb`.
+
+```json
+{
+ "type": "set-game",
+ "game": {
+ "player": { "node": "creature", "footOffset": 0.5 },
+ "camera": "follow",
+ "input": "keyboard",
+ "rules": {
+ "version": 1,
+ "variables": { "score": 0 },
+ "zones": [
+ { "id": "coin-zone-1", "shape": "sphere", "center": [0, 0.5, -3], "radius": 1.2 },
+ { "id": "goal-zone", "shape": "box", "center": [0, 1, -12], "size": [3, 4, 2] }
+ ],
+ "parts": [{ "id": "creature", "tags": ["player"] }, { "id": "coin-1", "tags": ["coin"] }],
+ "rules": [
+ { "once": true, "when": { "type": "enter", "zone": "coin-zone-1", "tag": "player" }, "do": [{ "type": "add", "variable": "score", "value": 1 }, { "type": "hide", "part": "coin-1" }] },
+ { "when": { "type": "enter", "zone": "goal-zone", "tag": "player" }, "if": [">=", "score", 1], "do": [{ "type": "win" }] }
+ ]
+ }
+ }
+}
+```
+
+## Fields
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `player.node` | required | A node of the scene. The rules part with the same id follows the player |
+| `player.controller` | `character` | The [character controller](player.md) |
+| `player.walkSpeed`, `runSpeed`, `jumpSpeed` | 3, 6, 7 | Metres per second, 0 to 100 |
+| `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) |
+| `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 |
+
+A rules part named like a scene node is hidden and shown with it, which is how a coin disappears. Yaw 0 faces -Z, and W moves forward. Removing the player node while a game uses it fails with the field to fix.
+
+## The web build
+
+`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.
+
+## From code
+
+```js
+import { startGame } from '67js/addons/game';
+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.
diff --git a/docs/learn/connect-mcp.md b/docs/learn/connect-mcp.md
index 5f3ffa99..a8bfa176 100644
--- a/docs/learn/connect-mcp.md
+++ b/docs/learn/connect-mcp.md
@@ -6,7 +6,7 @@ This page connects the 67js MCP server to an AI agent harness. A harness is the
`67js-mcp` is a local program. The harness starts it and talks to it over stdin and stdout. It has no network listener for MCP.
-The server holds one active scene. When the agent calls `scene_create`, the server starts your installed Chrome in the background and renders the scene there. It gives the agent 23 tools to build, look at and export the scene. The tools take JSON, and they never run code that the agent writes.
+The server holds one active scene. When the agent calls `scene_create`, the server starts your installed Chrome in the background and renders the scene there. It gives the agent 24 tools to build, look at and export the scene. The tools take JSON, and they never run code that the agent writes.
You need two things:
@@ -248,7 +248,7 @@ The Windsurf documentation pages now redirect to Devin Desktop, which names `.de
## Check that it works
-First, ask the harness to list its MCP tools. You must see 23 tools whose names start with `scene_`, `mesh_` or `scene_render_`. Some harnesses add the server name in front, for example `mcp__67js-scene__scene_look` in Claude Code.
+First, ask the harness to list its MCP tools. You must see 24 tools whose names start with `scene_`, `mesh_` or `scene_render_`. Some harnesses add the server name in front, for example `mcp__67js-scene__scene_look` in Claude Code.
Then give the agent this prompt:
diff --git a/docs/learn/models-and-ai-agents.md b/docs/learn/models-and-ai-agents.md
index ef7ee87f..37b92c51 100644
--- a/docs/learn/models-and-ai-agents.md
+++ b/docs/learn/models-and-ai-agents.md
@@ -10,7 +10,7 @@ Three pages cover the details:
## What the agent does
-The server has 23 tools for authoring, previewing and exporting scenes. A normal session uses them in this order:
+The server has 24 tools for authoring, previewing and exporting scenes. A normal session uses them in this order:
1. `scene_capabilities` reads the supported features and limits.
2. `scene_create` makes a scene from a [recipe](/agent-scene.md). A recipe is JSON with object IDs, geometry, materials, a hierarchy and a camera.
diff --git a/docs/learn/optimize-for-agents.md b/docs/learn/optimize-for-agents.md
index c1180716..3b804034 100644
--- a/docs/learn/optimize-for-agents.md
+++ b/docs/learn/optimize-for-agents.md
@@ -6,7 +6,7 @@ This page shows how to make an agent finish a 67js task with fewer tool calls, f
An agent pays for three things: the tool list, the results of its calls, and the pictures that it reads.
-**The tool list.** The harness sends every tool's name, description and input schema to the model. The 23 tools total 65,777 bytes, about 18,800 tokens (measured 2026-11-09 on the main branch after the schema diet; it was 196,826 bytes before). A tool lists its common fields and one line naming the rest, and every call is still checked against the full schema. `scene_capabilities` with a `topic` gives the field list of one recipe part. Three tools make up most of it:
+**The tool list.** The harness sends every tool's name, description and input schema to the model. The 24 tools total 70,401 bytes, about 20,100 tokens (measured 2026-11-10 on the game branch after the schema diet; it was 196,826 bytes before). A tool lists its common fields and one line naming the rest, and every call is still checked against the full schema. `scene_capabilities` with a `topic` gives the field list of one recipe part. Three tools make up most of it:
| Tool | Schema size | Estimated tokens |
| --- | --- | --- |
diff --git a/docs/mcp.md b/docs/mcp.md
index f1087398..aaa091ea 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -77,7 +77,7 @@ Every recorded agent run used Claude Code. This table says what was tried elsewh
| Client or check | Result |
|---|---|
| Official MCP SDK client over stdio (`npm run smoke:mcp-package`) | Passes. |
-| MCP Inspector CLI 2.13.0 (`npm run smoke:mcp-clients`) | Passes, 2026-11-03, Windows, `--backend cpu`. Lists all 23 tools through `tools/list` in 7 s. `tools/call` of `scene_create` with the lamp recipe succeeds in 10 s. The CLI starts a new server for every command and the scene lives in the server, so it cannot follow with `scene_look`. That call fails with "No scene is active" and returns no image. The preview image is not testable through this CLI. |
+| MCP Inspector CLI 2.13.0 (`npm run smoke:mcp-clients`) | Passes, 2026-11-03, Windows, `--backend cpu`. Lists all 24 tools through `tools/list` in 7 s. `tools/call` of `scene_create` with the lamp recipe succeeds in 10 s. The CLI starts a new server for every command and the scene lives in the server, so it cannot follow with `scene_look`. That call fails with "No scene is active" and returns no image. The preview image is not testable through this CLI. |
| Official MCP Python SDK 2.3.0 (`npm run smoke:mcp-clients`) | Passes, 2026-11-03, Windows, `--backend cpu`. Initialize, `tools/list` (22 tools), `scene_create` and `scene_look` in one session. `scene_look` returns a 20480 byte PNG. 11 s including the first `uv` download. |
| JSON Schema 2020-12 validator with strict mode (Ajv 8), run in `npm test` | Every tool input schema compiles. |
| Tool names and descriptions | Names are 9 to 24 characters from `[a-z_]`, within the 64-character limit OpenAI, Gemini and Anthropic share. No description is over 1024 characters. |
@@ -139,6 +139,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe
| `scene_release_checkpoint` | `sessionId`, `checkpointId` | Release confirmation |
| `scene_export_recipe` | `sessionId` | Canonical recipe and revision |
| `scene_export_glb` | `sessionId`, optional `clip`, `motionTime`, `maxTextureSize` | A GLB file under `<jobs>/exports/` with a server-chosen name: path, bytes, SHA-256. See [GLB export](export-glb.md) |
+| `scene_export_web` | `sessionId`, optional `title` | A static web build folder under `<jobs>/exports/`: path of `index.html`, file count, bytes. Needs a `game` set with `set-game`. See [Game](game.md) |
| `scene_dispose` | `sessionId` | Disposal confirmation |
| `scene_render_submit` | `sessionId`, `expectedRevision`, `settings` | Snapshot job ID and queued record |
| `scene_render_status` | `jobId` | State and durable frame progress |
diff --git a/index.html b/index.html
index 3f5455a2..bfd870ed 100644
--- a/index.html
+++ b/index.html
@@ -46,7 +46,7 @@
</div>
<div class="hero-copy">
<h1>3D engine that<br />AI agents drive</h1>
- <p class="lede">Real-time WebGL2 with Glaze, offline path tracing with Cook, and 23 MCP tools in one package.</p>
+ <p class="lede">Real-time WebGL2 with Glaze, offline path tracing with Cook, and 24 MCP tools in one package.</p>
<div class="hero-actions">
<a href="/docs.html#getting-started" data-icon="book">Get started</a>
<a href="https://www.npmjs.com/package/@codepawlhq/67js"><span class="package-logo package-logo-npm brand-npm" aria-hidden="true"></span>npm</a>
@@ -122,7 +122,7 @@ renderer.render({ eye: [58, 31, 84], target: [-8, 3, -18] });</code></pre>
</div>
</div>
<div class="agent-cards">
- <a href="/mcp.md" data-icon="cube"><h3>23 MCP tools</h3><p>Create, edit, explode, blend and render over stdio.</p></a>
+ <a href="/mcp.md" data-icon="cube"><h3>24 MCP tools</h3><p>Create, edit, explode, blend and render over stdio.</p></a>
<a href="/path-tracer.md" data-icon="code"><h3>Glaze + Cook</h3><p>Real-time WebGL2 frames or path-traced stills.</p></a>
<a href="/agent-review.md" data-icon="image"><h3>Visual review</h3><p>Compare labeled views and normals from one snapshot.</p></a>
</div>
diff --git a/package.json b/package.json
index 6d0fec8d..7d3d417b 100644
--- a/package.json
+++ b/package.json
@@ -49,6 +49,7 @@
"docs/animation-graph.md",
"docs/player.md",
"docs/game-rules.md",
+ "docs/game.md",
"docs/scene-query.md",
"docs/user-passes.md",
"docs/skeleton-pose.md",
@@ -133,6 +134,7 @@
"./addons/animation-graph": "./build/animation-graph.js",
"./addons/player": "./build/player.js",
"./addons/game-rules": "./build/game-rules.js",
+ "./addons/game": "./build/game.js",
"./addons/update-part-vertices": "./build/update-part-vertices.js",
"./package.json": "./package.json"
},
diff --git a/public/llms.txt b/public/llms.txt
index debe697b..15e00beb 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -2,7 +2,7 @@
> A 3D engine that AI agents drive. Real-time WebGL2 scenes in the browser, and deterministic PNG, MP4 and GLB output from the same scene.
-67js has an MCP server (`67js-mcp`, 23 tools) that builds, edits, looks at and renders scenes from JSON recipes.
+67js has an MCP server (`67js-mcp`, 24 tools) that builds, edits, looks at and renders scenes from JSON recipes.
The same engine is a JavaScript library for pages and Node. The library API is in the guide below.
Scenes are plain data with stable IDs, so an agent can edit by ID and check each change with a rendered image.
@@ -34,6 +34,7 @@ Scenes are plain data with stable IDs, so an agent can edit by ID and check each
- Review the result: `scene_look` for one PNG, `scene_review` for a labeled grid of up to four views. [Docs](https://67js.codepawl.com/agent-review.md)
- Render a still or a video: `scene_render_submit`, poll `scene_render_status`, read `scene_render_result`, then `scene_render_release`. [Docs](https://67js.codepawl.com/agent-render-jobs.md)
- Export a model: `scene_export_glb`, or `scene_export_recipe` for the JSON recipe. [Docs](https://67js.codepawl.com/export-glb.md)
+- Make a playable game: `scene_apply` with `set-game` (topic `game` in `scene_capabilities`), then `scene_export_web` for a static folder. [Docs](https://67js.codepawl.com/game.md)
- Recover from an error: `scene_restore` to a `scene_checkpoint`, or `scene_inspect` for the current revision and retry; every error names its next step. [Docs](https://67js.codepawl.com/mcp.md)
## All tools
@@ -55,6 +56,7 @@ Scenes are plain data with stable IDs, so an agent can edit by ID and check each
- `scene_release_checkpoint`: Release one checkpoint slot.
- `scene_export_recipe`: Read a detached canonical JSON recipe for reproduction.
- `scene_export_glb`: Write the active scene as a GLB file in the configured jobs folder, under a server-chosen name (the result has the path, byte count and...
+- `scene_export_web`: Write the scene with its game as a static web build in the jobs folder: index.html, game.json and engine/, which any static host serves...
- `scene_dispose`: Dispose the active scene and its checkpoints, releasing renderer resources.
- `scene_render_submit`: Start one asynchronous snapshot job in the configured private job store.
- `scene_render_status`: Read render job state and durable frame progress.
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 58d6808b..a76255ab 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -1,7 +1,7 @@
import { createServer } from 'node:http';
import { createHash, randomUUID } from 'node:crypto';
import { existsSync } from 'node:fs';
-import { lstat, mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
+import { lstat, mkdir, readFile, rm, unlink, writeFile } from 'node:fs/promises';
import { dirname, isAbsolute, join } from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
@@ -9,6 +9,7 @@ import packageMetadata from '../package.json' with { type: 'json' };
import { VEGETATION_CAPABILITY_NOTE } from '../src/agent-vegetation-notes.js';
import { CROWD_CAPABILITY_NOTE } from '../src/agent-crowd-notes.js';
import { USER_PASS_CAPABILITIES } from '../src/user-pass.js';
+import { GAME_CAPABILITIES } from '../src/game-setup-notes.js';
import { MESH_BLEND_CAPABILITIES } from '../src/mesh-blend.js';
import { MATERIAL_SNIPPET_CAPABILITIES } from '../src/material-snippet.js';
import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB, BAKE_WORKER_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';
@@ -22,6 +23,7 @@ import { recipeAssetNeeds } from '../src/agent-scene-assets.js';
import { sequenceFrameIds } from '../src/agent-texture-sequence.js';
import { catalogLookReferences, BUNDLED_ENVIRONMENT_NAMES, BUNDLED_CUBE_LOOK_NAMES } from '../src/look-catalog.js';
import { TEXTURE_SEQUENCE_CAPABILITIES } from '../src/texture-sequence-limits.js';
+import { writeWebBuild } from './web-export.mjs';
import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME, HIGH_PRECISION_FRAME_FACTOR } from './agent-render-jobs.mjs';
import { encodeRenderOutput, encodeMultilayerExr } from './render-output-encoders.mjs';
import { createFrameEncoder } from './frame-encoder.mjs';
@@ -46,6 +48,7 @@ const PATH_TRACER_THREADS = 8;
const MAXIMUM_QUEUED_CALLS = 16;
const MAXIMUM_GLB_BYTES = 32 * 1024 * 1024;
const MAXIMUM_KEPT_GLBS = 8;
+const MAXIMUM_KEPT_WEB_BUILDS = 4;
const EVALUATION_TIMEOUT_MS = 30000;
const QUERY_ONLY_TIMEOUT_MS = 120000;
/** A bake runs on a worker for up to its own limit, so a call that bakes gets that much more than a plain call. */
@@ -114,6 +117,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
let catalogPromise;
let jobsPromise;
const savedGlbPaths = [];
+ const savedWebBuildPaths = [];
function jobs() {
if (!jobRoot) throw new Error('Configure --jobs with an absolute output directory before submitting render jobs.');
if (!jobsPromise && closing) throw new Error('The agent runtime is closing or closed.');
@@ -721,7 +725,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return Object.freeze({
async capabilities() {
return {
- scene: { ...AGENT_SCENE_CAPABILITIES, postPasses: USER_PASS_CAPABILITIES, meshBlend: MESH_BLEND_CAPABILITIES, materialSnippet: MATERIAL_SNIPPET_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE, crowd: CROWD_CAPABILITY_NOTE, textureSequence: TEXTURE_SEQUENCE_CAPABILITIES },
+ scene: { ...AGENT_SCENE_CAPABILITIES, game: GAME_CAPABILITIES, postPasses: USER_PASS_CAPABILITIES, meshBlend: MESH_BLEND_CAPABILITIES, materialSnippet: MATERIAL_SNIPPET_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE, crowd: CROWD_CAPABILITY_NOTE, textureSequence: TEXTURE_SEQUENCE_CAPABILITIES },
sceneLimits: SCENE_LIMITS,
preview: { backend, memoryBudgetMiB: memory, maximumWidth: 1024, maximumHeight: 1024, maximumImageBytes: MAXIMUM_IMAGE_BYTES, maximumActiveScenes: 1, maximumQueuedCalls: MAXIMUM_QUEUED_CALLS, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS },
review: { ...REVIEW_LIMITS, backend, memoryBudgetMiB: memory, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS,
@@ -1017,6 +1021,21 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return { ...summary, ...file };
});
},
+ exportWeb({ sessionId, title }) {
+ return enqueue(async () => {
+ await requirePreviewRenderer();
+ await jobs();
+ const { recipe, revision } = await invoke('exportRecipe', { sessionId });
+ // Same name rule as GLB exports: the server picks the folder, and only the newest few are kept.
+ const directory = join(jobRoot, EXPORT_DIRECTORY_NAME);
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ while (savedWebBuildPaths.length >= MAXIMUM_KEPT_WEB_BUILDS) await rm(savedWebBuildPaths.shift(), { recursive: true, force: true });
+ const outputDirectory = join(directory, `web-${randomUUID()}`);
+ savedWebBuildPaths.push(outputDirectory);
+ const summary = await writeWebBuild({ recipe, buildDirectory: fileURLToPath(new URL('../', previewUrl)), outputDirectory, title });
+ return { sessionId, revision, ...summary, entry: join(outputDirectory, 'index.html'), host: 'Serve the folder with any static file server; no server code runs.' };
+ });
+ },
submitJob({ sessionId, expectedRevision, settings }) {
return enqueue(async () => {
await requirePreviewRenderer();
diff --git a/scripts/generate-llms.mjs b/scripts/generate-llms.mjs
index 57154046..509aeb69 100644
--- a/scripts/generate-llms.mjs
+++ b/scripts/generate-llms.mjs
@@ -51,6 +51,7 @@ function taskMap() {
['Review the result', '`scene_look` for one PNG, `scene_review` for a labeled grid of up to four views', 'agent-review.md'],
['Render a still or a video', '`scene_render_submit`, poll `scene_render_status`, read `scene_render_result`, then `scene_render_release`', 'agent-render-jobs.md'],
['Export a model', '`scene_export_glb`, or `scene_export_recipe` for the JSON recipe', 'export-glb.md'],
+ ['Make a playable game', '`scene_apply` with `set-game` (topic `game` in `scene_capabilities`), then `scene_export_web` for a static folder', 'game.md'],
['Recover from an error', '`scene_restore` to a `scene_checkpoint`, or `scene_inspect` for the current revision and retry; every error names its next step', 'mcp.md'],
];
return rows.map(([task, calls, doc]) => `- ${task}: ${calls}. [Docs](${page(doc)})`).join('\n');
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index bfdb70bf..4dc55ab5 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -672,6 +672,7 @@ const motionListed = listed('motion', motion, 'One absolute-time clip: duration
const physicsListed = listed('physics', physics, 'Rigid bodies recorded offline with Rapier: duration, gravity, bodies [{node, type, shape, mass, ...}], joints; see scene_capabilities physics.', coreOf(physics.shape, ['duration']));
const clothListed = listed('cloth', cloth, 'Baked cloth sheets: duration, gravity, wind, sheets [{node, pin, pinTo, stiffness, ...}], colliders; see scene_capabilities cloth.', coreOf(cloth.shape, ['duration']));
const armatureListed = listed('armatures', armature, 'A skeleton { id, parent, preset humanoid|quadruped, fit, bones [{name, parent, head, tail}], prefix, translation, rotation }; see scene_capabilities armatures.', { id: identifier });
+const gameReference = z.record(z.string(), z.unknown()).describe('Playable setup as plain JSON, never code: {player:{node}, camera, input, physics, ground, rules}. Fields and an example: scene_capabilities game.');
const recipe = z.strictObject({
format: z.literal('67js.scene'),
schemaVersion: z.literal(1),
@@ -690,6 +691,7 @@ const recipe = z.strictObject({
particles: z.record(z.string(), z.unknown()).nullable().optional().describe('Particle emitters and hair, seeked by motionTime. Fields: scene_capabilities particles.'),
bake: z.record(z.string(), z.unknown()).nullable().optional().describe('Bounced light baked at build time. Fields: scene_capabilities bake.'),
postPasses: z.array(z.record(z.string(), z.unknown())).nullable().optional().describe('Full-screen GLSL passes, [{name, fragment, uniforms, scale}]. Rules: scene_capabilities postPasses.'),
+ game: gameReference.nullable().optional(),
}).describe('Bounded scene recipe; the backend validates it.');
const assetRecipe = z.strictObject({
format: z.literal('67js.asset'),
@@ -731,6 +733,7 @@ const otherOperations = [
z.strictObject({ type: z.literal('set-particles'), particles: z.record(z.string(), z.unknown()).nullable() }),
z.strictObject({ type: z.literal('set-bake'), bake: z.record(z.string(), z.unknown()).nullable() }),
z.strictObject({ type: z.literal('set-post-passes'), postPasses: z.array(z.record(z.string(), z.unknown())).nullable() }),
+ z.strictObject({ type: z.literal('set-game'), game: gameReference.nullable() }),
z.strictObject({ type: z.literal('set-environment'), environment: environmentListed }),
z.strictObject({ type: z.literal('set-effects'), effects: effectsListed }),
z.strictObject({ type: z.literal('set-shadow'), shadow }),
@@ -787,7 +790,7 @@ const TOOL_TITLES = {
scene_capabilities: 'Scene capabilities', scene_create: 'Create scene', scene_asset_catalog: 'Asset catalog', scene_create_asset: 'Create scene from asset',
scene_inspect: 'Inspect scene', scene_walkmap: 'Walkable map', mesh_inspect: 'Inspect meshes', mesh_edit: 'Edit mesh', mesh_stack: 'Set mesh modifiers',
scene_apply: 'Apply scene edits', scene_look: 'Look at scene', scene_review: 'Review camera samples', scene_checkpoint: 'Save checkpoint',
- scene_restore: 'Restore checkpoint', scene_release_checkpoint: 'Release checkpoint', scene_export_recipe: 'Export recipe', scene_export_glb: 'Export GLB',
+ scene_restore: 'Restore checkpoint', scene_release_checkpoint: 'Release checkpoint', scene_export_recipe: 'Export recipe', scene_export_glb: 'Export GLB', scene_export_web: 'Export web game',
scene_dispose: 'Dispose scene', scene_render_submit: 'Submit render job', scene_render_status: 'Render job status', scene_render_cancel: 'Cancel render job',
scene_render_result: 'Render job result', scene_render_release: 'Release render job',
};
@@ -929,6 +932,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
register('scene_release_checkpoint', 'Release one checkpoint slot. Released or foreign checkpoints fail.', z.strictObject(checkpointFields), destroy, async argumentsValue => jsonResult(await runtime.releaseCheckpoint(argumentsValue)));
register('scene_export_recipe', 'Read a detached canonical JSON recipe for reproduction.', z.strictObject(sessionFields), readOnly, async argumentsValue => jsonResult(await runtime.exportRecipe(argumentsValue)));
register('scene_export_glb', 'Write the active scene as a GLB file in the configured jobs folder, under a server-chosen name (the result has the path, byte count and SHA-256). Needs --jobs. Exports the current pose with pattern and imported textures, skins, morph weights and IK as posed; motionTime seeks authored motion first. For an imported asset, clip adds that source clip (translation, rotation, scale and morph weight tracks) on the source skeleton, which needs no animation, node overrides or motion in the scene. At most eight files are kept, oldest removed first; the GLB is at most 32 MiB.', z.strictObject({ ...sessionFields, clip: z.number().int().min(0).max(255).optional().describe('Imported assets only: index of the source clip to write.'), motionTime: z.number().min(0).max(3600).optional().describe('Seek authored motion (and IK) to this time before exporting. Leaves the preview there, like scene_look.'), maxTextureSize: z.number().int().min(1).max(4096).optional().describe('Largest texture side in pixels. Defaults to 2048.') }), edit, async argumentsValue => jsonResult(await runtime.exportGlb(argumentsValue)));
+ register('scene_export_web', 'Write the scene with its game as a static web build in the jobs folder: index.html, game.json and engine/, which any static host serves with no server code. Needs --jobs and a game set with set-game. Procedural scenes only; the newest four builds are kept.', z.strictObject({ ...sessionFields, title: z.string().max(64).optional().describe('Page title.') }), edit, async argumentsValue => jsonResult(await runtime.exportWeb(argumentsValue)));
register('scene_dispose', 'Dispose the active scene and its checkpoints, releasing renderer resources.', z.strictObject(sessionFields), destroy, async argumentsValue => jsonResult(await runtime.dispose(argumentsValue)));
register('scene_render_submit', 'Start one asynchronous snapshot job in the configured private job store. Requires the current revision. Temporarily leases the preview renderer; does not change source revision or checkpoints.', z.strictObject({ ...sessionFields, expectedRevision, settings: renderSettings }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.submitJob(argumentsValue)));
register('scene_render_status', 'Read render job state and durable frame progress. Terminal states are completed, cancelled, failed and interrupted.', z.strictObject(jobFields), readOnly, async argumentsValue => jsonResult(await runtime.jobStatus(argumentsValue)));
diff --git a/scripts/measure-tool-cost.mjs b/scripts/measure-tool-cost.mjs
index b80f8a8e..2f6cc762 100644
--- a/scripts/measure-tool-cost.mjs
+++ b/scripts/measure-tool-cost.mjs
@@ -6,6 +6,7 @@ import { createAgentMcpServer } from './mcp-server.mjs';
import { VEGETATION_CAPABILITY_NOTE } from '../src/agent-vegetation-notes.js';
import { CROWD_CAPABILITY_NOTE } from '../src/agent-crowd-notes.js';
import { USER_PASS_CAPABILITIES } from '../src/user-pass.js';
+import { GAME_CAPABILITIES } from '../src/game-setup-notes.js';
import { MESH_BLEND_CAPABILITIES } from '../src/mesh-blend.js';
import { MATERIAL_SNIPPET_CAPABILITIES } from '../src/material-snippet.js';
import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
@@ -74,7 +75,7 @@ export async function listTools() {
/** What an agent receives from scene_capabilities with no topic: the index on this branch, the whole list on an older one. */
async function defaultCapabilitiesResult() {
- const scene = { ...AGENT_SCENE_CAPABILITIES, postPasses: USER_PASS_CAPABILITIES, meshBlend: MESH_BLEND_CAPABILITIES, materialSnippet: MATERIAL_SNIPPET_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE, crowd: CROWD_CAPABILITY_NOTE, textureSequence: TEXTURE_SEQUENCE_CAPABILITIES };
+ const scene = { ...AGENT_SCENE_CAPABILITIES, game: GAME_CAPABILITIES, postPasses: USER_PASS_CAPABILITIES, meshBlend: MESH_BLEND_CAPABILITIES, materialSnippet: MATERIAL_SNIPPET_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE, crowd: CROWD_CAPABILITY_NOTE, textureSequence: TEXTURE_SEQUENCE_CAPABILITIES };
const runtime = { async close() {}, async capabilities() { return { scene, phase: 'idle', availableIn: '0.0.0' }; } };
return withClient(runtime, async client => (await client.callTool({ name: 'scene_capabilities', arguments: {} })).structuredContent);
}
diff --git a/scripts/smoke-agent-post-pass.mjs b/scripts/smoke-agent-post-pass.mjs
index f82b09cf..2180e26a 100644
--- a/scripts/smoke-agent-post-pass.mjs
+++ b/scripts/smoke-agent-post-pass.mjs
@@ -93,7 +93,7 @@ async function waitForJob(jobId) {
try {
await client.connect(transport);
- assert.equal((await client.listTools()).tools.length, 23);
+ assert.equal((await client.listTools()).tools.length, 24);
const capabilities = (await call('scene_capabilities', { topic: 'postPasses' })).structuredContent;
assert.equal(capabilities.value.limits.maxPasses, 4);
assert.ok((await call('scene_capabilities', { topic: 'operations' })).structuredContent.value.includes('set-post-passes'));
diff --git a/scripts/smoke-agent-render-jobs.mjs b/scripts/smoke-agent-render-jobs.mjs
index b806f073..aee18c3e 100644
--- a/scripts/smoke-agent-render-jobs.mjs
+++ b/scripts/smoke-agent-render-jobs.mjs
@@ -57,7 +57,7 @@ async function close() {
}
try {
await connect();
- assert.equal((await client.listTools()).tools.length, 23);
+ assert.equal((await client.listTools()).tools.length, 24);
const catalog = (await call('scene_asset_catalog')).structuredContent;
const created = (await call('scene_create_asset', { recipe: {
format: '67js.asset', schemaVersion: 1, assetId: catalog.assets[0].assetId,
diff --git a/scripts/smoke-game-web.mjs b/scripts/smoke-game-web.mjs
new file mode 100644
index 00000000..462b0c76
--- /dev/null
+++ b/scripts/smoke-game-web.mjs
@@ -0,0 +1,137 @@
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { 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';
+
+// 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.
+// Run it through the GPU lock: bash ~/.agents/tools/gpu-lock.sh node scripts/smoke-game-web.mjs
+
+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 transport = new StdioClientTransport({ command: process.execPath, args: [cli, '--backend', 'cpu', '--memory', '128', '--jobs', join(directory, 'jobs')], 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' });
+
+async function call(name, argumentsValue = {}) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 60000 });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result.structuredContent ?? JSON.parse(result.content.find(item => item.type === 'text').text);
+}
+
+async function callExpectingError(name, argumentsValue) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 60000 });
+ assert.equal(result.isError, true, `${name} should have been refused`);
+ return result.content.find(item => item.type === 'text').text;
+}
+
+const COINS = [[0, 0.5, -3], [0, 0.5, -6], [0, 0.5, -9]];
+const GOAL = [0, 1, -12];
+const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }, { id: 'ball', type: 'sphere' }],
+ materials: [
+ { id: 'grass', color: [0.2, 0.45, 0.2] }, { id: 'fur', color: [0.85, 0.45, 0.2] },
+ { id: 'gold', color: [0.95, 0.75, 0.1], metallic: 0.8, roughness: 0.3 }, { id: 'flag', color: [0.2, 0.4, 0.9] },
+ ],
+ nodes: [
+ { id: 'floor', geometry: 'block', material: 'grass', translation: [0, -0.1, -6], scale: [12, 0.2, 24] },
+ { id: 'creature', translation: [0, 0.5, 0] },
+ { id: 'body', parent: 'creature', geometry: 'block', material: 'fur', scale: [0.8, 0.8, 1.2] },
+ { id: 'head', parent: 'creature', geometry: 'ball', material: 'fur', translation: [0, 0.35, -0.6], scale: [0.5, 0.5, 0.5] },
+ ...COINS.map((translation, index) => ({ id: `coin-${index + 1}`, geometry: 'ball', material: 'gold', translation, scale: [0.4, 0.4, 0.4] })),
+ { id: 'goal', geometry: 'block', material: 'flag', translation: GOAL, scale: [1.5, 2, 0.2] },
+ ],
+ camera: { eye: [4, 4, 6], target: [0, 0.5, -3], fov: 50 },
+};
+const coinRules = COINS.map((center, index) => ({
+ id: `collect-${index + 1}`, once: true,
+ when: { type: 'enter', zone: `coin-zone-${index + 1}`, tag: 'player' },
+ do: [{ type: 'add', variable: 'score', value: 1 }, { type: 'hide', part: `coin-${index + 1}` }],
+}));
+const game = {
+ player: { node: 'creature', footOffset: 0.5 },
+ camera: 'follow',
+ input: 'keyboard',
+ rules: {
+ version: 1,
+ variables: { score: 0 },
+ zones: [...COINS.map((center, index) => ({ id: `coin-zone-${index + 1}`, shape: 'sphere', center: [center[0], 0.5, center[2]], radius: 1.2 })),
+ { id: 'goal-zone', shape: 'box', center: [0, 1, GOAL[2]], size: [3, 4, 2] }],
+ parts: [{ id: 'creature', tags: ['player'] }, ...COINS.map((center, index) => ({ id: `coin-${index + 1}`, tags: ['coin'] }))],
+ rules: [...coinRules, { id: 'reach-goal', when: { type: 'enter', zone: 'goal-zone', tag: 'player' }, if: ['>=', 'score', 3], do: [{ type: 'win' }] }],
+ },
+};
+// Hold forward and run from sample 1, press jump at sample 40, and let go at sample 240.
+const replay = { version: 1, samples: 260, truncated: false, events: [[1, 'keyboard/KeyW', 1], [1, 'keyboard/ShiftLeft', 1], [40, 'keyboard/Space', 1], [42, 'keyboard/Space', 0], [240, 'keyboard/KeyW', 0], [240, 'keyboard/ShiftLeft', 0]] };
+
+function serveFolder(folder) {
+ const server = createServer(async (request, response) => {
+ const path = new URL(request.url, 'http://localhost').pathname;
+ try {
+ const file = path === '/' ? 'index.html' : path.slice(1);
+ const body = await readFile(join(folder, file));
+ response.writeHead(200, { 'content-type': MIME_TYPES[extname(file)] ?? 'application/octet-stream' });
+ response.end(body);
+ } catch {
+ response.writeHead(404).end();
+ }
+ });
+ return new Promise(resolveListening => server.listen(0, '127.0.0.1', () => resolveListening(server)));
+}
+
+let browser;
+let server;
+try {
+ await client.connect(transport);
+ await call('scene_create', { recipe });
+
+ const badNode = await callExpectingError('scene_apply', { expectedRevision: 0, operations: [{ type: 'set-game', game: { ...game, player: { node: 'creatur' } } }] });
+ assert.match(badNode, /player\.node.*creatur.*Use one of/s);
+ const badRules = await callExpectingError('scene_apply', { expectedRevision: 0, operations: [{ type: 'set-game', game: { ...game, rules: { version: 1, parts: [{ id: 'coin-1', tags: ['coin'] }] } } }] });
+ assert.match(badRules, /rules\.parts has no part "creature"/);
+ const noGame = await callExpectingError('scene_export_web', {});
+ assert.match(noGame, /no game/);
+
+ await call('scene_apply', { expectedRevision: 0, operations: [{ type: 'set-game', game }] });
+ const capabilities = await call('scene_capabilities', { topic: 'game' });
+ assert.ok(capabilities.value?.fields ?? capabilities.fields, 'scene_capabilities topic game answers');
+ const exported = await call('scene_export_web', { title: 'Creature run' });
+ assert.ok(exported.bytes < 12 * 1024 * 1024, `bytes ${exported.bytes}`);
+ const folder = dirname(exported.entry);
+ await writeFile(join(folder, 'replay.json'), JSON.stringify(replay));
+
+ server = await serveFolder(folder);
+ browser = await chromium.launch({ executablePath: CHROME_PATH, headless: true, args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader'] });
+ const page = await browser.newPage({ viewport: { width: 640, height: 400 } });
+ const problems = [];
+ 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`);
+ 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, 3);
+ assert.deepEqual(problems, []);
+ 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) {
+ console.error(diagnostics);
+ throw error;
+} finally {
+ await browser?.close();
+ server?.close();
+ await client.close();
+}
diff --git a/scripts/smoke-mcp-package.mjs b/scripts/smoke-mcp-package.mjs
index a0e67144..ed6a0185 100644
--- a/scripts/smoke-mcp-package.mjs
+++ b/scripts/smoke-mcp-package.mjs
@@ -120,7 +120,7 @@ for (const era of ['modern', 'legacy']) {
const connectMs = performance.now() - start;
processId = transport.pid;
assert.equal(client.getServerVersion().version, metadata.version);
- assert.equal((await client.listTools()).tools.length, 23);
+ assert.equal((await client.listTools()).tools.length, 24);
const capabilities = (await call('scene_capabilities')).structuredContent;
assert.equal(capabilities.phase, 'idle');
assert.equal((await call('scene_capabilities', { topic: 'preview' })).structuredContent.value.maximumActiveScenes, 1);
diff --git a/scripts/smoke-mcp.mjs b/scripts/smoke-mcp.mjs
index d8f6e17f..2cefa33c 100644
--- a/scripts/smoke-mcp.mjs
+++ b/scripts/smoke-mcp.mjs
@@ -53,7 +53,7 @@ try {
await client.connect(transport);
processId = transport.pid;
const listing = await client.listTools();
- assert.equal(listing.tools.length, 23);
+ assert.equal(listing.tools.length, 24);
const capabilities = (await call('scene_capabilities')).structuredContent;
assert.equal(capabilities.phase, 'idle');
const fixture = createAgentPreviewFixture();
diff --git a/scripts/web-export.mjs b/scripts/web-export.mjs
new file mode 100644
index 00000000..f5d8adb0
--- /dev/null
+++ b/scripts/web-export.mjs
@@ -0,0 +1,94 @@
+import { copyFile, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+
+// Writes a playable game as one folder that any static host can serve: index.html, game.json (the recipe with its game
+// section) and engine/ (the built 67js modules that index.html imports, found by following the import statements from
+// build/game.js). There is no server code. The folder is bounded, so an export never fills the disk.
+
+export const WEB_EXPORT_LIMITS = Object.freeze({ maxEngineBytes: 12 * 1024 * 1024, maxEngineFiles: 400, maxTitleLength: 64, maxRecipeBytes: 1024 * 1024 });
+
+const ENTRY_MODULE = 'game.js';
+const IMPORT_PATTERN = /(?:from\s*|import\s*\(\s*|import\s*)["'](\.\/[A-Za-z0-9_.-]+\.js)["']/g;
+
+/** Every module file build/game.js needs, including the ones it loads on demand, as names relative to the build folder. */
+export async function engineModuleNames(buildDirectory) {
+ const found = new Set();
+ const pending = [ENTRY_MODULE];
+ while (pending.length) {
+ const name = pending.pop();
+ if (found.has(name)) continue;
+ let source;
+ try {
+ source = await readFile(join(buildDirectory, name), 'utf8');
+ } catch {
+ // A match inside an error message is not an import; only the entry module must exist.
+ if (name !== ENTRY_MODULE) continue;
+ throw new Error(`The web export needs the built engine, and ${name} is missing from ${buildDirectory}. Run npm run build:lib, or install the published package.`);
+ }
+ found.add(name);
+ if (found.size > WEB_EXPORT_LIMITS.maxEngineFiles) throw new RangeError(`The engine has more than ${WEB_EXPORT_LIMITS.maxEngineFiles} modules, which is not expected. Rebuild the package.`);
+ for (const match of source.matchAll(IMPORT_PATTERN)) pending.push(match[1].slice(2));
+ }
+ return [...found].sort();
+}
+
+function escapeHtml(text) {
+ return text.replace(/[&<>"']/g, character => `&#${character.charCodeAt(0)};`);
+}
+
+function pageTitle(title) {
+ const clean = String(title ?? 'Game').replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, WEB_EXPORT_LIMITS.maxTitleLength);
+ return escapeHtml(clean || 'Game');
+}
+
+/** The page. `?replay=name.json` plays a recording from the same folder instead of the keyboard, for tests and demos. */
+export function indexHtml(title) {
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<link rel="icon" href="data:,">
+<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
+<title>${pageTitle(title)}</title>
+<style>html,body{margin:0;height:100%;background:#101014;overflow:hidden}canvas{display:block;width:100%;height:100%;touch-action:none}</style>
+</head>
+<body>
+<canvas id="game"></canvas>
+<script type="module">
+import { startGame } from './engine/${ENTRY_MODULE}';
+const canvas = document.getElementById('game');
+const recipe = await (await fetch('./game.json')).json();
+const replayName = new URLSearchParams(location.search).get('replay');
+const replay = /^[\\w.-]+\\.json$/.test(replayName ?? '') ? await (await fetch('./' + replayName)).json() : undefined;
+window.__game = await startGame(canvas, recipe, { replay });
+</script>
+</body>
+</html>
+`;
+}
+
+/**
+ * Write the web build of a recipe into `outputDirectory` (created, must not hold a build already) and return its summary.
+ * `buildDirectory` is the package's build/ folder.
+ */
+export async function writeWebBuild({ recipe, buildDirectory, outputDirectory, title }) {
+ if (!recipe?.game) throw new Error('This scene has no game. Add one with scene_apply set-game (fields: scene_capabilities topic game), then export again.');
+ if (recipe.game.physics) throw new Error('game.physics is true, and the web export does not bundle the physics engine yet. Set game.physics to false with set-game.');
+ if (recipe.nodes?.some(node => node.asset || node.vegetation)) throw new Error('The web export holds procedural scenes only. Remove the placed catalog assets and vegetation, or build them from geometry.');
+ if (recipe.format !== '67js.scene') throw new Error('The web export needs a 67js.scene recipe. Create the scene with scene_create.');
+ const recipeText = JSON.stringify(recipe);
+ if (Buffer.byteLength(recipeText) > WEB_EXPORT_LIMITS.maxRecipeBytes) throw new RangeError(`The recipe is larger than ${WEB_EXPORT_LIMITS.maxRecipeBytes} bytes. Simplify the scene.`);
+
+ const names = await engineModuleNames(buildDirectory);
+ let engineBytes = 0;
+ for (const name of names) engineBytes += (await stat(join(buildDirectory, name))).size;
+ if (engineBytes > WEB_EXPORT_LIMITS.maxEngineBytes) throw new RangeError(`The engine is ${engineBytes} bytes, above the ${WEB_EXPORT_LIMITS.maxEngineBytes} byte limit. Rebuild the package.`);
+
+ await mkdir(join(outputDirectory, 'engine'), { recursive: true });
+ for (const name of names) await copyFile(join(buildDirectory, name), join(outputDirectory, 'engine', name));
+ await writeFile(join(outputDirectory, 'game.json'), recipeText);
+ const html = indexHtml(title);
+ await writeFile(join(outputDirectory, 'index.html'), html);
+ const totalBytes = engineBytes + Buffer.byteLength(recipeText) + Buffer.byteLength(html);
+ return { directory: dirname(join(outputDirectory, 'index.html')), files: names.length + 2, engineModules: names.length, bytes: totalBytes };
+}
diff --git a/src/agent-apply-report.js b/src/agent-apply-report.js
index d6238933..afd67c14 100644
--- a/src/agent-apply-report.js
+++ b/src/agent-apply-report.js
@@ -6,9 +6,9 @@ export const APPLY_REPORT_LIMITS = Object.freeze({ maxEntries: 20, maxDiffIds: 8
const COLLECTIONS = Object.freeze({ node: 'nodes', material: 'materials', geometry: 'geometries' });
const LOOK_SECTIONS = Object.freeze({ 'set-environment': 'environment', 'set-effects': 'effects', 'set-shadow': 'shadow' });
-const OWN_SECTIONS = Object.freeze({
+export const OWN_SECTIONS = Object.freeze({
'set-motion': 'motion', 'set-physics': 'physics', 'set-timeline': 'timeline', 'set-cloth': 'cloth',
- 'set-bake': 'bake', 'set-particles': 'particles', 'set-post-passes': 'postPasses', 'set-armatures': 'armatures',
+ 'set-bake': 'bake', 'set-particles': 'particles', 'set-post-passes': 'postPasses', 'set-armatures': 'armatures', 'set-game': 'game',
});
function isPlainObject(value) {
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 387e6029..4b66d15f 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -224,7 +224,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
operations: Object.freeze([
'set-node', 'set-material', 'set-camera', 'add-node', 'remove-node',
'add-geometry', 'remove-geometry', 'add-material', 'remove-material',
- 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'set-timeline', 'set-particles', 'set-bake', 'set-post-passes', 'edit-mesh', 'set-mesh-stack', 'bake-motion',
+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'set-timeline', 'set-particles', 'set-bake', 'set-post-passes', 'set-game', 'edit-mesh', 'set-mesh-stack', 'bake-motion',
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']),
// A flat water sheet; the largest sets the level. A bed d metres down keeps exp(-absorption * d) per channel (RGB per metre).
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 641bf3ea..41c6f280 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -36,6 +36,7 @@ const MODULE_LOADERS = {
physicalSky: () => import('./physical-sky.js'),
floorSky: () => import('./floor-sky-visibility.js'),
userPass: () => import('./user-pass.js'),
+ game: () => import('./game-setup.js'),
objectMotionBlur: () => import('./object-motion-blur.js'),
postSteps: () => import('./post-steps.js'),
materialSnippet: () => import('./material-snippet.js'),
@@ -87,6 +88,7 @@ const MODULE_MARKERS = {
floorSky: ['"keyColor"', '"keyIntensity"'],
physicalSky: ['"type":"physical"'],
userPass: ['"postPasses"'],
+ game: ['"game":{', '"set-game"'],
materialSnippet: ['"snippet":{'],
// Only a motionBlur object that sets a non-zero `objects` loads it; the common `"shutter":0` look does not.
objectMotionBlur: [/"motionBlur":\{[^}]*"objects":(?!0[,}])/],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index b63a5a3a..783c3d38 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -20,6 +20,7 @@ export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
*/
export const REVISION_HISTORY_LIMIT = 4;
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
+import { OWN_SECTIONS as NULLABLE_SECTION_OPERATIONS } from './agent-apply-report.js';
export { describeApplication } from './agent-apply-report.js';
export {
needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader,
@@ -50,11 +51,6 @@ const LOOK_OPERATION_FIELDS = Object.freeze({
'set-effects': 'effects',
'set-shadow': 'shadow',
});
-// Each of these replaces one recipe section whole; null clears it.
-const NULLABLE_SECTION_OPERATIONS = Object.freeze({
- 'set-motion': 'motion', 'set-physics': 'physics', 'set-timeline': 'timeline', 'set-cloth': 'cloth',
- 'set-bake': 'bake', 'set-particles': 'particles', 'set-post-passes': 'postPasses', 'set-armatures': 'armatures',
-});
const ADDITION_FIELDS = Object.freeze({
'add-geometry': ['geometries', 'geometry'],
'add-material': ['materials', 'material'],
@@ -879,7 +875,7 @@ function linkedMaterial(liveMaterial, lightMask, wrappers) {
function normalizeRecipe(input, limits) {
let recipe = copiedJson(input, limits.maxRecipeBytes);
- knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth', 'timeline', 'particles', 'bake', 'postPasses'], 'recipe');
+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth', 'timeline', 'particles', 'bake', 'postPasses', 'game'], 'recipe');
if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {
throw invalidField(recipe.format !== '67js.scene' ? 'format' : 'schemaVersion', recipe.format !== '67js.scene' ? recipe.format : recipe.schemaVersion, recipe.format !== '67js.scene' ? '"67js.scene"' : '1');
}
@@ -959,6 +955,10 @@ function normalizeRecipe(input, limits) {
recipe.bake = recipe.bake === null ? null : agentSceneModule('bake').normalizeAgentBake(recipe.bake);
}
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)));
+ }
recipe = copiedJson(recipe, limits.maxRecipeBytes);
return recipe;
}
diff --git a/src/game-setup-notes.js b/src/game-setup-notes.js
new file mode 100644
index 00000000..40e17bbb
--- /dev/null
+++ b/src/game-setup-notes.js
@@ -0,0 +1,24 @@
+// What scene_capabilities topic game says. It sits beside game-setup.js, not in the agent scene capabilities, so the core agent-scene bundle does not carry it; the MCP runtime adds it to the scene capabilities. A test keeps the names in step with game-setup.js.
+export const GAME_CAPABILITIES = Object.freeze({
+ field: 'recipe.game, set with set-game (null clears). Plain data, never code.',
+ fields: 'player {node (a node id; its children move with it), controller character, walkSpeed 3, runSpeed 6, jumpSpeed 7 (0-100 m/s), footOffset 0 (m from the node origin down to the feet)}, camera, input, physics (bool, false), ground (height in m, 0), rules (game rules document).',
+ 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.',
+ 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.',
+ example: Object.freeze({
+ type: 'set-game',
+ game: Object.freeze({
+ player: Object.freeze({ node: 'creature', footOffset: 0.5 }),
+ camera: 'follow',
+ input: 'keyboard',
+ rules: Object.freeze({
+ version: 1,
+ variables: Object.freeze({ score: 0 }),
+ zones: Object.freeze([Object.freeze({ id: 'goal-zone', shape: 'box', center: Object.freeze([0, 0, -6]), size: Object.freeze([2, 4, 2]) })]),
+ parts: Object.freeze([Object.freeze({ id: 'creature', tags: Object.freeze(['player']) })]),
+ rules: Object.freeze([Object.freeze({ when: Object.freeze({ type: 'enter', zone: 'goal-zone', tag: 'player' }), do: Object.freeze([Object.freeze({ type: 'win' })]) })]),
+ }),
+ }),
+ }),
+});
diff --git a/src/game-setup.js b/src/game-setup.js
new file mode 100644
index 00000000..cc226840
--- /dev/null
+++ b/src/game-setup.js
@@ -0,0 +1,98 @@
+import { validateGameRules } from './game-rules.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.
+
+export const GAME_CAMERAS = Object.freeze(['follow', 'first-person', 'top-down']);
+export const GAME_INPUT_PRESETS = Object.freeze(['keyboard', 'gamepad', 'touch']);
+export const GAME_CONTROLLERS = Object.freeze(['character']);
+
+export const GAME_SETUP_LIMITS = Object.freeze({
+ maxSpeed: 100,
+ maxJumpSpeed: 100,
+ maxFootOffset: 100,
+ maxGround: 10000,
+});
+
+const SETUP_FIELDS = ['player', 'camera', 'input', 'physics', 'ground', 'rules'];
+const PLAYER_FIELDS = ['node', 'controller', 'walkSpeed', 'runSpeed', 'jumpSpeed', 'footOffset'];
+
+function fail(path, problem) {
+ throw new RangeError(`Game setup ${path} ${problem}`);
+}
+
+function requireRecord(value, path) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail(path, 'must be an object, such as { "node": "creature" }.');
+}
+
+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(', ')}.`);
+ }
+}
+
+function chooseName(value, choices, fallback, path) {
+ if (value === undefined) return fallback;
+ if (!choices.includes(value)) fail(path, `is ${JSON.stringify(value)}. Use one of: ${choices.join(', ')}.`);
+ return value;
+}
+
+function boundedNumber(value, fallback, minimum, maximum, path) {
+ if (value === undefined) return fallback;
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {
+ fail(path, `must be a number from ${minimum} to ${maximum}, got ${JSON.stringify(value)}.`);
+ }
+ return value;
+}
+
+function normalizePlayer(player, nodeIds) {
+ requireRecord(player, 'player');
+ rejectUnknownFields(player, PLAYER_FIELDS, 'player');
+ if (typeof player.node !== 'string' || !nodeIds.has(player.node)) {
+ const known = [...nodeIds].slice(0, 12).join(', ') || 'none yet; add the node first';
+ fail('player.node', `names ${JSON.stringify(player.node)}, which is not a node of the scene. Use one of: ${known}.`);
+ }
+ const normalized = {
+ node: player.node,
+ controller: chooseName(player.controller, GAME_CONTROLLERS, 'character', 'player.controller'),
+ walkSpeed: boundedNumber(player.walkSpeed, 3, 0, GAME_SETUP_LIMITS.maxSpeed, 'player.walkSpeed'),
+ runSpeed: boundedNumber(player.runSpeed, 6, 0, GAME_SETUP_LIMITS.maxSpeed, 'player.runSpeed'),
+ 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'),
+ };
+ return normalized;
+}
+
+function normalizeRules(rules, playerNode) {
+ let checked;
+ try {
+ checked = validateGameRules(rules, { hasInput: true });
+ } catch (error) {
+ throw new RangeError(`Game setup rules: ${error.message}`);
+ }
+ if (!checked.parts.some(part => part.id === playerNode)) {
+ fail('rules.parts', `has no part "${playerNode}", the player node. Add { "id": "${playerNode}", "tags": ["player"] } so zones can see the player.`);
+ }
+ // Keep the document as written: validateGameRules fills fields (such as a null position) that it does not accept back.
+ return structuredClone(rules);
+}
+
+/**
+ * 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.
+ */
+export function normalizeGameSetup(game, nodeIds) {
+ requireRecord(game, 'game');
+ rejectUnknownFields(game, SETUP_FIELDS, 'game');
+ const player = normalizePlayer(game.player, nodeIds);
+ if (game.physics !== undefined && typeof game.physics !== 'boolean') fail('physics', `must be true or false, got ${JSON.stringify(game.physics)}.`);
+ const normalized = {
+ player,
+ camera: chooseName(game.camera, GAME_CAMERAS, 'follow', 'camera'),
+ input: chooseName(game.input, GAME_INPUT_PRESETS, 'keyboard', 'input'),
+ physics: game.physics ?? false,
+ ground: boundedNumber(game.ground, 0, -GAME_SETUP_LIMITS.maxGround, GAME_SETUP_LIMITS.maxGround, 'ground'),
+ };
+ if (game.rules !== undefined) normalized.rules = normalizeRules(game.rules, player.node);
+ return normalized;
+}
diff --git a/src/game.js b/src/game.js
new file mode 100644
index 00000000..11caee89
--- /dev/null
+++ b/src/game.js
@@ -0,0 +1,170 @@
+import { Renderer67 } from './renderer.js';
+import { createAgentScene, loadAgentSceneModules } from './agent-scene.js';
+import { agentGroundPlacement, createAgentGround, FLOOR_COLOR } from './agent-ground.js';
+import { agentEnvironmentMap } from './agent-look.js';
+import { groundBounceEnvironment } from './ground-bounce.js';
+import { createRuntime } from './runtime.js';
+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';
+
+// 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.
+
+const KEYBOARD_ACTIONS = { jump: ['keyboard/Space'], run: ['keyboard/ShiftLeft'] };
+const KEYBOARD_AXES = {
+ moveX: ['keyboard/KeyD', { control: 'keyboard/KeyA', scale: -1 }],
+ moveForward: ['keyboard/KeyW', { control: 'keyboard/KeyS', scale: -1 }],
+ lookX: ['keyboard/ArrowRight', { control: 'keyboard/ArrowLeft', scale: -1 }],
+ lookY: ['keyboard/ArrowUp', { control: 'keyboard/ArrowDown', scale: -1 }],
+};
+const MOVE_STICK = { name: 'move', area: { x: 0, y: 0, width: 0.5, height: 1 }, radius: 60 };
+
+function inputDefinition(preset) {
+ const actions = { jump: [...KEYBOARD_ACTIONS.jump], run: [...KEYBOARD_ACTIONS.run] };
+ const axes = Object.fromEntries(Object.entries(KEYBOARD_AXES).map(([name, bindings]) => [name, [...bindings]]));
+ if (preset === 'gamepad') {
+ actions.jump.push('gamepad/0.button0');
+ axes.moveX.push('gamepad/0.axis0');
+ axes.moveForward.push({ control: 'gamepad/0.axis1', scale: -1 });
+ axes.lookX.push('gamepad/0.axis2');
+ axes.lookY.push({ control: 'gamepad/0.axis3', scale: -1 });
+ }
+ if (preset === 'touch') {
+ actions.jump.push('touch/tap');
+ axes.moveX.push('touch/moveX');
+ axes.moveForward.push({ control: 'touch/moveY', scale: -1 });
+ }
+ return { actions, axes };
+}
+
+function inputSources(preset, canvas) {
+ const sources = [keyboardSource()];
+ if (preset === 'gamepad') sources.push(gamepadSource());
+ if (preset === 'touch') sources.push(touchSource({ target: canvas, sticks: [MOVE_STICK] }));
+ return sources;
+}
+
+function cameraRigFor(kind, controller, input) {
+ const rigOptions = { subject: controller.state, input };
+ if (kind === 'first-person') return createFirstPersonCamera(rigOptions);
+ if (kind === 'top-down') return createTopDownCamera(rigOptions);
+ return createFollowCamera(rigOptions);
+}
+
+// A node's world position, from the translations along its parents. The player starts there.
+function nodeTranslation(nodes, id) {
+ const byId = new Map(nodes.map(node => [node.id, node]));
+ const position = [0, 0, 0];
+ for (let node = byId.get(id); node; node = byId.get(node.parent)) {
+ for (let axis = 0; axis < 3; axis++) position[axis] += node.translation?.[axis] ?? 0;
+ }
+ return position;
+}
+
+function litEnvironment(scene, hasAutomaticGround) {
+ const environment = scene.environment;
+ return groundBounceEnvironment(scene.parts, { ...environment, map: agentEnvironmentMap(environment) }, { automaticAlbedo: hasAutomaticGround ? FLOOR_COLOR : null });
+}
+
+function createStatusLine(canvas) {
+ const element = document.createElement('div');
+ element.style.cssText = 'position:fixed;left:12px;top:12px;padding:6px 10px;border-radius:6px;background:rgba(0,0,0,.55);color:#fff;font:14px system-ui,sans-serif;pointer-events:none;user-select:none';
+ canvas.parentNode.appendChild(element);
+ return element;
+}
+
+function describeState(state) {
+ const variables = Object.entries(state.variables).map(([name, value]) => `${name} ${value}`).join(' ');
+ const verdict = state.status === 'won' ? ' YOU WIN' : state.status === 'lost' ? ' GAME OVER' : '';
+ return `${variables}${verdict}`;
+}
+
+/**
+ * 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) and `showStatus` (default true).
+ */
+export async function startGame(canvas, recipe, { replay, showStatus = true } = {}) {
+ const setup = recipe.game;
+ if (!setup) throw new Error('startGame needs a recipe with a game section. Add one with the set-game operation.');
+ await loadAgentSceneModules(recipe);
+ const scene = createAgentScene(recipe);
+ const { game } = scene.exportRecipe();
+ const placement = agentGroundPlacement(scene.parts, scene.environment);
+ const environment = litEnvironment(scene, Boolean(placement));
+ const renderer = new Renderer67(canvas, scene.parts, {
+ ground: placement ? createAgentGround(placement) : false,
+ hdr: true,
+ depth: true,
+ world: scene.environment.world,
+ environment,
+ pixelRatio: Math.min(globalThis.devicePixelRatio ?? 1, 2),
+ });
+
+ const { actions, axes } = inputDefinition(game.input);
+ const input = createInput({ sources: replay ? [replaySource(replay)] : inputSources(game.input, canvas), actions, axes });
+ const footOffset = game.player.footOffset;
+ const start = nodeTranslation(recipe.nodes, game.player.node);
+ const body = { position: [0, 0, 0], rotationY: 0 };
+ let rig = null;
+ const controller = createCharacterController({
+ input,
+ position: [start[0], start[1] - footOffset, start[2]],
+ ground: game.ground,
+ walkSpeed: game.player.walkSpeed,
+ runSpeed: game.player.runSpeed,
+ jumpSpeed: game.player.jumpSpeed,
+ faceCamera: game.camera === 'first-person',
+ cameraYaw: () => rig?.yaw ?? 0,
+ node: body,
+ });
+ 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();
+ let drawnTopology = scene.topologyRevision;
+ const status = showStatus && rules ? createStatusLine(canvas) : null;
+
+ const sceneSystem = {
+ 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)] }];
+ 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);
+ operations.push({ type: 'set-node', id: part.id, visible: part.visible });
+ }
+ scene.apply(operations, { expectedRevision: scene.revision });
+ if (scene.topologyRevision === drawnTopology) {
+ renderer.updateParts(scene.parts);
+ } else {
+ renderer.replaceParts(scene.parts);
+ drawnTopology = scene.topologyRevision;
+ }
+ if (status) status.textContent = describeState(rules.state);
+ },
+ };
+
+ const baseCamera = scene.camera;
+ const runtime = createRuntime(renderer, {
+ fixedRate: 60,
+ systems: [input, controller, rig, ...(rules ? [rules] : []), sceneSystem],
+ frame: context => ({ ...baseCamera, ...rig.pose(context), environment, time: context.elapsedSeconds }),
+ });
+ const resize = () => renderer.resize();
+ globalThis.addEventListener?.('resize', resize);
+ resize();
+ runtime.start();
+
+ return {
+ scene, runtime, rules, input, controller, renderer,
+ dispose() {
+ globalThis.removeEventListener?.('resize', resize);
+ runtime.dispose();
+ status?.remove();
+ },
+ };
+}
diff --git a/tests/game-setup.test.js b/tests/game-setup.test.js
new file mode 100644
index 00000000..972b7fa3
--- /dev/null
+++ b/tests/game-setup.test.js
@@ -0,0 +1,127 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, readdir, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
+import { GAME_CAPABILITIES } from '../src/game-setup-notes.js';
+import { normalizeGameSetup, GAME_CAMERAS, GAME_INPUT_PRESETS, GAME_CONTROLLERS, GAME_SETUP_LIMITS } from '../src/game-setup.js';
+import { writeWebBuild, engineModuleNames, indexHtml, WEB_EXPORT_LIMITS } from '../scripts/web-export.mjs';
+
+const NODE_IDS = new Set(['creature', 'coin-1']);
+const RULES = {
+ version: 1,
+ variables: { score: 0 },
+ zones: [{ id: 'goal-zone', shape: 'box', center: [0, 1, -6], size: [2, 4, 2] }],
+ parts: [{ id: 'creature', tags: ['player'] }],
+ rules: [{ when: { type: 'enter', zone: 'goal-zone', tag: 'player' }, do: [{ type: 'win' }] }],
+};
+
+function recipeWith(game) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box' }], materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],
+ nodes: [{ id: 'creature', geometry: 'block', material: 'paint' }, { id: 'coin-1', geometry: 'block', material: 'paint' }],
+ ...(game ? { game } : {}),
+ };
+}
+
+test('a minimal setup gets its defaults', () => {
+ const setup = normalizeGameSetup({ player: { node: 'creature' } }, NODE_IDS);
+ assert.deepEqual(setup, {
+ player: { node: 'creature', controller: 'character', walkSpeed: 3, runSpeed: 6, jumpSpeed: 7, footOffset: 0 },
+ camera: 'follow', input: 'keyboard', physics: false, ground: 0,
+ });
+});
+
+test('each bad field names itself and says what to pass', () => {
+ const player = { node: 'creature' };
+ const unknownZone = { version: 1, rules: [{ when: { type: 'enter', zone: 'nowhere', tag: 'player' }, do: [] }] };
+ const cases = [
+ [{}, /player must be an object/],
+ [{ player: { node: 'creatur' } }, /player\.node names "creatur".*Use one of: creature, coin-1/],
+ [{ player, camera: 'orbit' }, /camera is "orbit". Use one of: follow, first-person, top-down/],
+ [{ player, input: 'mouse' }, /input is "mouse". Use one of: keyboard, gamepad, touch/],
+ [{ player: { ...player, controller: 'car' } }, /player\.controller is "car". Use one of: character/],
+ [{ player: { ...player, walkSpeed: 101 } }, /player\.walkSpeed must be a number from 0 to 100/],
+ [{ player: { ...player, jumpSpeed: Infinity } }, /player\.jumpSpeed must be a number/],
+ [{ player, physics: 'yes' }, /physics must be true or false/],
+ [{ player, ground: 1e9 }, /ground must be a number/],
+ [{ player, script: 'alert(1)' }, /script is not a field. Use one of: player, camera, input, physics, ground, rules/],
+ [{ player, rules: unknownZone }, /Game setup rules: Game rules/],
+ [{ player, rules: { ...RULES, parts: [{ id: 'coin-1', tags: ['coin'] }], rules: [] } }, /rules\.parts has no part "creature"/],
+ ];
+ for (const [game, pattern] of cases) assert.throws(() => normalizeGameSetup(game, NODE_IDS), pattern, JSON.stringify(game).slice(0, 80));
+});
+
+test('the rules document keeps its written form and its limits apply', () => {
+ const setup = normalizeGameSetup({ player: { node: 'creature' }, rules: RULES }, NODE_IDS);
+ assert.deepEqual(setup.rules, RULES);
+ const tooMany = { ...RULES, variables: Object.fromEntries(Array.from({ length: 33 }, (_, index) => [`v${index}`, 0])) };
+ assert.throws(() => normalizeGameSetup({ player: { node: 'creature' }, rules: tooMany }, NODE_IDS), /Game setup rules/);
+});
+
+test('a scene recipe holds the game, checks it against its nodes, and removing the player node fails', () => {
+ const scene = createAgentScene(recipeWith({ player: { node: 'creature', footOffset: 0.5 }, rules: RULES }));
+ assert.equal(scene.exportRecipe().game.player.footOffset, 0.5);
+ assert.throws(() => scene.apply([{ type: 'remove-node', id: 'creature' }], { expectedRevision: scene.revision }), /player\.node names "creature"/);
+ scene.apply([{ type: 'set-game', game: null }], { expectedRevision: scene.revision });
+ assert.equal(scene.exportRecipe().game, undefined);
+ scene.apply([{ type: 'set-game', game: { player: { node: 'coin-1' } } }], { expectedRevision: scene.revision });
+ assert.equal(scene.exportRecipe().game.player.node, 'coin-1');
+ assert.throws(() => createAgentScene(recipeWith({ player: { node: 'ghost' } })), /player\.node names "ghost"/);
+});
+
+test('scene_capabilities topic game lists the names the validator accepts', () => {
+ const topic = GAME_CAPABILITIES;
+ assert.deepEqual(topic.cameras, GAME_CAMERAS);
+ assert.deepEqual(Object.keys(topic.inputPresets), GAME_INPUT_PRESETS);
+ assert.ok(GAME_CONTROLLERS.every(name => topic.fields.includes(name)));
+ assert.ok(topic.fields.includes(`0-${GAME_SETUP_LIMITS.maxSpeed} m/s`));
+ assert.ok(AGENT_SCENE_CAPABILITIES.operations.includes('set-game'));
+ // The example in the topic is a valid operation on a scene that has its player node.
+ const scene = createAgentScene({ ...recipeWith(), nodes: [{ id: 'creature', geometry: 'block', material: 'paint' }] });
+ scene.apply([structuredClone(topic.example)], { expectedRevision: scene.revision });
+ assert.equal(scene.exportRecipe().game.camera, 'follow');
+});
+
+async function fakeBuild() {
+ const build = await mkdtemp(join(tmpdir(), '67js-fake-build-'));
+ await writeFile(join(build, 'game.js'), 'import { a } from "./chunk-a.js";\nconst lazy = () => import("./chunk-b.js");\n');
+ await writeFile(join(build, 'chunk-a.js'), 'export const a = 1; throw new Error("add import \'./not-a-file.js\'");');
+ await writeFile(join(build, 'chunk-b.js'), 'import "./chunk-a.js";');
+ await writeFile(join(build, 'unused.js'), 'export {};');
+ return build;
+}
+
+test('the web export copies only the engine modules the entry reaches and writes a runnable folder', async () => {
+ const build = await fakeBuild();
+ assert.deepEqual(await engineModuleNames(build), ['chunk-a.js', 'chunk-b.js', 'game.js']);
+ const out = join(await mkdtemp(join(tmpdir(), '67js-web-out-')), 'site');
+ const summary = await writeWebBuild({ recipe: recipeWith({ player: { node: 'creature' } }), buildDirectory: build, outputDirectory: out, title: 'A <b>"game"</b>' });
+ assert.deepEqual((await readdir(out)).sort(), ['engine', 'game.json', 'index.html']);
+ assert.deepEqual((await readdir(join(out, 'engine'))).sort(), ['chunk-a.js', 'chunk-b.js', 'game.js']);
+ assert.equal(summary.files, 5);
+ assert.equal(JSON.parse(await readFile(join(out, 'game.json'), 'utf8')).game.player.node, 'creature');
+ const html = await readFile(join(out, 'index.html'), 'utf8');
+ assert.match(html, /<title>A &#60;b&#62;&#34;game&#34;&#60;\/b&#62;<\/title>/);
+ assert.match(html, /import \{ startGame \} from '\.\/engine\/game\.js'/);
+ assert.doesNotMatch(html, /https?:\/\//);
+ assert.match(indexHtml('x'), /replay/);
+});
+
+test('the web export refuses what it cannot play and says how to fix it', async () => {
+ const build = await fakeBuild();
+ const out = () => mkdtemp(join(tmpdir(), '67js-web-refuse-'));
+ const game = { player: { node: 'creature' } };
+ await assert.rejects(async () => writeWebBuild({ recipe: recipeWith(), buildDirectory: build, outputDirectory: await out() }), /no game.*set-game/);
+ await assert.rejects(async () => writeWebBuild({ recipe: recipeWith({ ...game, physics: true }), buildDirectory: build, outputDirectory: await out() }), /Set game\.physics to false/);
+ const placed = recipeWith(game);
+ placed.nodes.push({ id: 'tree', asset: { id: 'a'.repeat(64) } });
+ await assert.rejects(async () => writeWebBuild({ recipe: placed, buildDirectory: build, outputDirectory: await out() }), /procedural scenes only/);
+ await assert.rejects(async () => writeWebBuild({ recipe: recipeWith(game), buildDirectory: await mkdtemp(join(tmpdir(), '67js-empty-build-')), outputDirectory: await out() }), /game\.js is missing.*build:lib/);
+ const big = await fakeBuild();
+ await writeFile(join(big, 'chunk-a.js'), `${'/'.repeat(WEB_EXPORT_LIMITS.maxEngineBytes)}\nexport {};`);
+ await assert.rejects(async () => writeWebBuild({ recipe: recipeWith(game), buildDirectory: big, outputDirectory: await out() }), /above the \d+ byte limit/);
+});
diff --git a/tests/mcp-annotations.test.js b/tests/mcp-annotations.test.js
index 354b1c0a..10e58e43 100644
--- a/tests/mcp-annotations.test.js
+++ b/tests/mcp-annotations.test.js
@@ -32,7 +32,7 @@ async function connect(context, runtime) {
test('every tool has a title and complete annotations, with the read-only and destructive sets fixed', async context => {
const client = await connect(context, { activeSessionId: () => null, async close() {} });
const { tools } = await client.listTools();
- assert.equal(tools.length, 23);
+ assert.equal(tools.length, 24);
for (const tool of tools) {
assert.ok(tool.title && tool.annotations.title === tool.title, `${tool.name} has a title`);
for (const hint of ['readOnlyHint', 'destructiveHint', 'idempotentHint']) {
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
index 414fd3f7..15e80299 100644
--- a/tests/mcp-tools.test.js
+++ b/tests/mcp-tools.test.js
@@ -136,7 +136,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'
const { tools } = await client.listTools();
assert.deepEqual(tools.map(tool => tool.name).sort(), [
'mesh_edit', 'mesh_inspect', 'mesh_stack', 'scene_apply', 'scene_asset_catalog', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_create_asset', 'scene_dispose',
- 'scene_export_glb', 'scene_export_recipe', 'scene_inspect', 'scene_look', 'scene_review', 'scene_release_checkpoint', 'scene_restore',
+ 'scene_export_glb', 'scene_export_recipe', 'scene_export_web', 'scene_inspect', 'scene_look', 'scene_review', 'scene_release_checkpoint', 'scene_restore',
'scene_render_cancel', 'scene_render_release', 'scene_render_result', 'scene_render_status', 'scene_render_submit', 'scene_walkmap',
].sort());
for (const tool of tools) {
@@ -195,7 +195,7 @@ test('review SDK exposes one image and rejects unknown or unbounded shot fields
await client.callTool({ name: 'scene_create', arguments: { recipe: recipe() } });
const { tools } = await client.listTools();
const tool = tools.find(tool => tool.name === 'scene_review');
- assert.equal(tools.length, 23);
+ assert.equal(tools.length, 24);
assert.equal(tool.annotations.readOnlyHint, true);
assert.equal(tool.inputSchema.properties.shots.maxItems, 4);
assert.equal(tool.inputSchema.properties.shots.items.additionalProperties, false);
@@ -222,7 +222,7 @@ test('branch names and labels are bounded in every tool schema and rejected befo
await client.callTool({ name: 'scene_create', arguments: { recipe: recipe() } });
const { tools } = await client.listTools();
const schema = name => tools.find(tool => tool.name === name).inputSchema;
- assert.equal(tools.length, 23, 'branches add fields, not tools');
+ assert.equal(tools.length, 24, 'branches add fields, not tools');
const pattern = '^[a-z][a-z0-9_-]{0,23}$';
assert.equal(schema('scene_apply').properties.branch.pattern, pattern);
assert.equal(schema('scene_restore').properties.branch.pattern, pattern);
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 3a477d40..529490ca 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -113,6 +113,7 @@ export default defineConfig({
'animation-graph': 'src/animation-graph.js',
player: 'src/player.js',
'game-rules': 'src/game-rules.js',
+ game: 'src/game.js',
streaming: 'src/streaming.js',
'update-part-vertices':'src/update-part-vertices.js',
'replace-textured-parts': 'src/replace-textured-parts.js',