Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Load agent scene code on demand and trim the archive

Nguyen Xuan An298f799610e1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 614e1b4a..a1a7cda0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Load agent scene code on demand: mesh editing, `lathe`/`extrude`/`tube`, material `pattern` and `motion` now sit behind `loadAgentSceneModules(recipe)` (or `loadAllAgentSceneModules()`), and `createAgentScene` throws an error naming that call when a needed module is missing. A recipe of primitives drops from 141,241 to 73,581 bytes gzip in `scene:agent-scene` (every lazy chunk still totals 145,049). `npm run size` now bundles with code splitting and reports the initial load, plus a `+lazy` row for the total. `npm test` preloads every module. The archive no longer carries 29 docs that the site serves (physics, lighting, terrain and the other addon docs); agent docs stay
- Add bounded field expressions: a JSON language of math, comparison, logic, vectors, seeded noise and attributes (position, normal, index, tags) that compiles once to closures over typed arrays and never executes a string. It limits nodes (64), depth (12), elements (250,000) and node-evaluations (8 million) before it evaluates, and only reads operator names from a fixed table. It drives a `{ "field": expression }` face selection rule, `set_position` and `displace` as edits and stack nodes, and a `where` filter for instances. `displace` and `set_position` match Blender's Displace modifier and a Geometry Nodes Set Position node in five new golden cases
- Add `instances` on a recipe node: repeat its geometry at the points of a grid, a seeded scatter in a box or the surface of a geometry, with `where`, `yaw`, `alignToNormal` and `scale`, at most 2048 candidate points. It expands to ordinary nodes that share geometry and material, so the renderer draws one instanced batch. Add the `pillar-court` task to the agent modeling suite
- Add the `scene_export_glb` MCP tool (22 tools now) and morph weight clips in `exportGlb`. The tool writes the active recipe or imported asset scene as a GLB under `<jobs>/exports/` with a server-chosen name and returns the path, byte count and SHA-256; it takes no path, keeps the newest eight files and refuses more than 32 MiB. It exports the current pose (pattern textures, imported textures, skins, morph weights, IK as posed), `motionTime` seeks authored motion first, and `clip` adds an imported asset's source clip. Clip tracks with `property: 'weights'` write a SCALAR sampler of one weight per target. Checked in Blender 5.2: a patterned recipe opens with 2 meshes and 3 images, the robot with IK opens as 1 armature, 43 bones and 20 meshes, and its Walking clip as one action of 23 frames. Nothing in `src/index.js` changes, so no size budget moves
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index 3fb03289..431de5a3 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 269168,
- "gzip": 76869,
- "brotli": 65593
+ "min": 268604,
+ "gzip": 76724,
+ "brotli": 65461
},
"entry:model": {
"min": 40093,
@@ -129,14 +129,24 @@
"brotli": 762
},
"entry:agent-scene": {
- "min": 363196,
- "gzip": 115077,
- "brotli": 97971
+ "min": 160385,
+ "gzip": 47526,
+ "brotli": 40823
+ },
+ "entry:agent-scene+lazy": {
+ "min": 366032,
+ "gzip": 118995,
+ "brotli": 103525
},
"entry:agent-asset": {
- "min": 389720,
- "gzip": 122420,
- "brotli": 104242
+ "min": 223823,
+ "gzip": 67190,
+ "brotli": 58425
+ },
+ "entry:agent-asset+lazy": {
+ "min": 392050,
+ "gzip": 126086,
+ "brotli": 109590
},
"entry:hdri": {
"min": 8075,
@@ -154,9 +164,14 @@
"brotli": 63362
},
"scene:agent-scene": {
- "min": 462799,
- "gzip": 141241,
- "brotli": 120198
+ "min": 259187,
+ "gzip": 73579,
+ "brotli": 63018
+ },
+ "scene:agent-scene+lazy": {
+ "min": 464834,
+ "gzip": 145046,
+ "brotli": 125668
}
}
}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 709f802b..590bf4c0 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -5,7 +5,7 @@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 78500,
+ "entry:core": 78300,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 13600,
@@ -28,11 +28,14 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 117400,
- "entry:agent-asset": 124900,
+ "entry:agent-scene": 48500,
+ "entry:agent-scene+lazy": 121400,
+ "entry:agent-asset": 68600,
+ "entry:agent-asset+lazy": 128700,
"entry:hdri": 3300,
"scene:lit-box": 56000,
"scene:gltf-box": 75300,
- "scene:agent-scene": 144100
+ "scene:agent-scene": 75100,
+ "scene:agent-scene+lazy": 148000
}
}
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index a85a4d79..864b2bb2 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -45,6 +45,22 @@ The renderer owns GPU allocation and disposal.
The authoring session does not allocate GPU resources.
The normal frame loop can render retained parts without calling inspection or exporting the recipe.
+### On-demand code
+
+Mesh editing, `lathe`, `extrude` and `tube` geometry, material `pattern` and `motion` load on demand, so a recipe of
+primitives pays about half the bytes. `createAgentScene` and `apply` stay synchronous. When a recipe uses one of them,
+load its code first; a missing module throws an error that names this call.
+
+```js
+import { createAgentScene, loadAgentSceneModules } from '67js/addons/agent-scene';
+
+await loadAgentSceneModules(recipe);
+const scene = createAgentScene(recipe);
+```
+
+`loadAllAgentSceneModules()` loads everything, for a host that runs any recipe an agent writes (the MCP preview does).
+Call `loadAgentSceneModules(operations)` before `apply` when the operations add such features.
+
## Recipe contract
The recipe must contain `format`, `schemaVersion`, `geometries`, `materials`, and `nodes`.
diff --git a/package.json b/package.json
index 1074a1a5..4962ae57 100644
--- a/package.json
+++ b/package.json
@@ -22,33 +22,8 @@
"skills",
"docs/gltf.md",
"docs/guide.md",
- "docs/verification.md",
- "docs/release-verification.md",
- "docs/animation-curves.md",
- "docs/animation-mixer.md",
- "docs/skeleton-pose.md",
- "docs/material-maps.md",
"docs/modeling.md",
- "docs/scene-graph.md",
- "docs/camera-path.md",
- "docs/skinning.md",
- "docs/physics.md",
- "docs/lighting.md",
- "docs/volumetric.md",
- "docs/film-physics.md",
- "docs/morph-targets.md",
- "docs/gltf-morph.md",
- "docs/export-glb.md",
- "docs/sculpt.md",
- "docs/surface.md",
- "docs/mesh-query.md",
"docs/mesh.md",
- "docs/primitives.md",
- "docs/shrinkwrap.md",
- "docs/vehicle.md",
- "docs/spume.md",
- "docs/retarget.md",
- "docs/surface-attachment.md",
"docs/agent-scene.md",
"docs/mcp.md",
"docs/agent-look.md",
@@ -56,11 +31,7 @@
"docs/agent-render-jobs.md",
"docs/agent-motion.md",
"docs/agent-character-motion.md",
- "docs/agent-review.md",
- "docs/vegetation.md",
- "docs/terrain.md",
- "docs/grass.md",
- "docs/clutter.md"
+ "docs/agent-review.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -107,7 +78,7 @@
"prepack": "npm run build:lib",
"deploy": "node scripts/deploy.mjs",
"preview": "vite preview --host 127.0.0.1",
- "test": "node --test",
+ "test": "node --import ./tests/support/load-agent-scene-modules.mjs --test",
"smoke": "node scripts/smoke.mjs",
"smoke:scenes": "node scripts/smoke-scenes.mjs",
"smoke:transport": "node scripts/smoke-film-transport.mjs",
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 4081b677..b055b4c4 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -1,4 +1,4 @@
-import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from '../src/agent-scene.js';
+import { createAgentScene, loadAllAgentSceneModules, allAgentSceneModulesLoaded, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from '../src/agent-scene.js';
import { Renderer67 } from '../src/renderer.js';
import { applyProjection } from '../src/camera.js';
import { mat4 } from 'gl-matrix';
@@ -192,8 +192,10 @@ function createPreview(scene, { sessionId, memoryBudgetMiB, backend }, asset) {
// Manifold is an optional peer dependency; the runtime serves it from the host's node_modules on this origin.
setManifoldModuleLoader(() => import(/* @vite-ignore */ new URL('/vendor/manifold.js', location.href).href));
-// The boolean engine is WebAssembly and loads asynchronously, once. Calls that do not need it stay synchronous.
+// The preview bundle is one file, so the on-demand scene modules load together on the first call and later calls stay
+// synchronous. The boolean engine is WebAssembly and loads asynchronously, once, only for calls that need it.
function afterMeshBooleans(value, run) {
+ if (!allAgentSceneModulesLoaded()) return loadAllAgentSceneModules().then(() => afterMeshBooleans(value, run));
if (meshBooleansLoaded() || !needsMeshBooleans(value)) return run();
return loadMeshBooleans().then(run);
}
diff --git a/scripts/measure-size.mjs b/scripts/measure-size.mjs
index 2b96dcb8..5ce6f7b4 100644
--- a/scripts/measure-size.mjs
+++ b/scripts/measure-size.mjs
@@ -2,7 +2,7 @@
// It fails when a bundle passes its budget in bench/size/budgets.json. --update-baseline rewrites the baseline after a
// merge-ready change, and --set-budgets also resets each budget to 2% over its current size.
import { readFile, writeFile } from 'node:fs/promises';
-import { resolve } from 'node:path';
+import { relative, resolve } from 'node:path';
import { brotliCompressSync, gzipSync } from 'node:zlib';
import { build } from 'esbuild';
import { budgetsFrom, compareToBudgets, formatRows } from './size-budget.mjs';
@@ -51,16 +51,43 @@ const SCENES = {
},
};
+function gzipSize(contents) {
+ return gzipSync(contents, { level: 9 }).length;
+}
+
+// Dynamic imports become separate chunks. What a page pays at start is the entry chunk and every chunk it imports
+// statically; the rest loads when a feature asks for it. Both are reported so lazy code never hides.
+function chunkSizes(result) {
+ const outputsByPath = new Map(result.outputFiles.map(file => [relative(process.cwd(), file.path).replaceAll('\\', '/'), file]));
+ const entryPath = Object.keys(result.metafile.outputs).find(path => result.metafile.outputs[path].entryPoint);
+ const initialPaths = new Set();
+ const pending = [entryPath];
+ while (pending.length) {
+ const path = pending.pop();
+ if (initialPaths.has(path)) continue;
+ initialPaths.add(path);
+ for (const imported of result.metafile.outputs[path].imports) {
+ if (imported.kind === 'import-statement') pending.push(imported.path);
+ }
+ }
+ const sizeOf = paths => {
+ const parts = [...paths].map(path => outputsByPath.get(path).contents);
+ const bytes = Buffer.concat(parts);
+ return { min: bytes.length, gzip: parts.reduce((total, part) => total + gzipSize(part), 0), brotli: parts.reduce((total, part) => total + brotliCompressSync(part).length, 0) };
+ };
+ return { initial: sizeOf(initialPaths), all: sizeOf(outputsByPath.keys()) };
+}
+
async function measureSource(contents) {
const result = await build({
stdin: { contents, resolveDir: process.cwd(), loader: 'js' },
- bundle: true, minify: true, format: 'esm', write: false, treeShaking: true,
+ bundle: true, minify: true, format: 'esm', write: false, treeShaking: true, metafile: true,
+ splitting: true, outdir: 'size-output',
external: EXTERNAL_PACKAGES, logLevel: 'silent', target: 'es2022',
loader: { '.css': 'empty', '.json': 'json' },
define: { 'process.env.NODE_ENV': '"production"' },
});
- const output = result.outputFiles[0].contents;
- return { min: output.length, gzip: gzipSync(output, { level: 9 }).length, brotli: brotliCompressSync(output).length };
+ return chunkSizes(result);
}
async function packageEntries() {
@@ -69,20 +96,26 @@ async function packageEntries() {
return { [CORE_ENTRY]: 'src/index.js', ...Object.fromEntries(addons.map(name => [name, `src/${name}.js`])) };
}
+// A bundle with on-demand code gets a second row, so the total after every lazy chunk is visible and budgeted.
+function addMeasured(measured, name, sizes) {
+ measured[name] = sizes.initial;
+ if (sizes.all.gzip !== sizes.initial.gzip) measured[`${name}+lazy`] = sizes.all;
+}
+
async function measureAll() {
const measured = {};
for (const [name, path] of Object.entries(await packageEntries())) {
const absolute = resolve(path).replace(/\\/g, '/');
- measured[`entry:${name}`] = await measureSource(`export * from '${absolute}';`);
+ addMeasured(measured, `entry:${name}`, await measureSource(`export * from '${absolute}';`));
}
- for (const [name, scene] of Object.entries(SCENES)) measured[`scene:${name}`] = await measureSource(scene.engine);
+ for (const [name, scene] of Object.entries(SCENES)) addMeasured(measured, `scene:${name}`, await measureSource(scene.engine));
return measured;
}
async function measureThree() {
const measured = {};
for (const [name, scene] of Object.entries(SCENES)) {
- if (scene.three) measured[name] = await measureSource(scene.three);
+ if (scene.three) measured[name] = (await measureSource(scene.three)).initial;
}
return measured;
}
diff --git a/scripts/smoke-agent-look.mjs b/scripts/smoke-agent-look.mjs
index 5e51fc40..a695fb70 100644
--- a/scripts/smoke-agent-look.mjs
+++ b/scripts/smoke-agent-look.mjs
@@ -22,9 +22,10 @@ recipe.environment = {
};
recipe.shadow = { extent: 5, far: 20 };
const harness = `<!doctype html><html><head><style>html,body{margin:0;height:100%}canvas{width:100vw;height:100vh;display:block}</style></head><body><canvas></canvas><script type="module">
-import {createAgentScene} from '/src/agent-scene.js';
+import {createAgentScene,loadAllAgentSceneModules} from '/src/agent-scene.js';
import {resolveAgentShadow} from '/src/agent-look.js';
import {Renderer67} from '/src/renderer.js';
+await loadAllAgentSceneModules();
const session=createAgentScene(${JSON.stringify(recipe)});
const renderer=new Renderer67(document.querySelector('canvas'),session.parts,{ground:false,hdr:true,depth:true,samples:1,pixelRatio:1,memoryBudgetMiB:192});
const counters={buffers:0,textures:0,framebuffers:0,renderbuffers:0};
diff --git a/scripts/smoke-agent-scene.mjs b/scripts/smoke-agent-scene.mjs
index e922dda3..a0a80c3c 100644
--- a/scripts/smoke-agent-scene.mjs
+++ b/scripts/smoke-agent-scene.mjs
@@ -11,9 +11,10 @@ const origin = process.argv[4] ?? 'http://127.0.0.1:5173';
await mkdir('artifacts', { recursive: true });
const recipe = createAgentPreviewFixture();
const harness = `<!doctype html><html><head><style>html,body{margin:0;height:100%;background:#152126}canvas{width:100vw;height:100vh;display:block}</style></head><body><canvas id="scene"></canvas><script type="module">
-import {createAgentScene} from '/src/agent-scene.js';
+import {createAgentScene,loadAllAgentSceneModules} from '/src/agent-scene.js';
import {Renderer67} from '/src/renderer.js';
import {exportGlb} from '/src/export.js';
+await loadAllAgentSceneModules();
const session=createAgentScene(${JSON.stringify(recipe)});
const renderer=new Renderer67(document.querySelector('canvas'),session.parts,{ground:true,hdr:true,samples:4,pixelRatio:1,memoryBudgetMiB:192});
const effects={bloom:{strength:0.12,threshold:1,radius:1},saturation:1,contrast:1,temperature:0,vignette:0,grain:0};
diff --git a/scripts/smoke-agent-topology.mjs b/scripts/smoke-agent-topology.mjs
index 02701d67..675edff4 100644
--- a/scripts/smoke-agent-topology.mjs
+++ b/scripts/smoke-agent-topology.mjs
@@ -12,8 +12,9 @@ assert.ok(['gpu', 'cpu'].includes(backend));
await mkdir('artifacts', { recursive: true });
const fixture = createAgentPreviewFixture();
const harness = `<!doctype html><html><head><style>html,body{margin:0;height:100%;background:#182126}canvas{width:100vw;height:100vh;display:block}</style></head><body><canvas></canvas><script type="module">
-import {createAgentScene} from '/src/agent-scene.js';
+import {createAgentScene,loadAllAgentSceneModules} from '/src/agent-scene.js';
import {Renderer67} from '/src/renderer.js';
+await loadAllAgentSceneModules();
const recipe=${JSON.stringify(fixture)};
const session=createAgentScene({...recipe,geometries:[],materials:[],nodes:[]});
const renderer=new Renderer67(document.querySelector('canvas'),session.parts,{ground:false,hdr:true,samples:4,pixelRatio:1,memoryBudgetMiB:192});
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index e0b50360..cc2f4b48 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -131,7 +131,7 @@ if (${!published || metadata.version !== '0.4.0'}) {
}
solidIndex.dispose();
if (${!published}) {
- const { createAgentScene, resolveAgentShadow } = await import('67js/addons/agent-scene');
+ const { createAgentScene, loadAgentSceneModules, resolveAgentShadow } = await import('67js/addons/agent-scene');
const agentScene = createAgentScene({
format: '67js.scene', schemaVersion: 1,
geometries: [{ id: 'cube', type: 'box', bevel: 0 }],
@@ -169,6 +169,8 @@ if (${!published}) {
agentScene.restore(lookCheckpoint, { expectedRevision: agentScene.revision });
assert.deepEqual(agentScene.exportRecipe(), originalLook);
agentScene.releaseCheckpoint(lookCheckpoint);
+ // The recipe started as primitives; the next edit adds motion, whose code loads on demand.
+ await loadAgentSceneModules({ motion: {} });
const motionCheckpoint = agentScene.checkpoint();
const authoredRecipe = agentScene.exportRecipe();
agentScene.apply([{ type: 'set-motion', motion: { duration: 1, tracks: [{
diff --git a/src/agent-asset.js b/src/agent-asset.js
index f8f671fa..d6f13a31 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -3,7 +3,10 @@ import { createAgentScene } from './agent-scene.js';
import { fitPerspectiveDistance } from './camera.js';
import { validateSkinGeometry, validateSkinPose } from './skinning.js';
import { validateMorphGeometry, validateMorphTransform } from './morph.js';
-import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';
+import * as agentMotion from './agent-motion.js';
+import { registerAgentSceneModule } from './agent-scene-modules.js';
+
+registerAgentSceneModule('motion', agentMotion);
const MAX_RECIPE_BYTES = 1024 * 1024;
const MAX_CHECKPOINTS = 8;
@@ -415,7 +418,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
if (candidate.motion?.ik?.length && Math.max(...result.root.scale) - Math.min(...result.root.scale) > 1e-3 * Math.max(...result.root.scale)) {
throw new RangeError('Motion ik needs a uniform asset root scale.');
}
- result.motion = normalizeAgentMotion(candidate.motion, motionRecipe(result));
+ result.motion = agentMotion.normalizeAgentMotion(candidate.motion, motionRecipe(result));
return copiedJson(result);
}
@@ -457,7 +460,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
if (transientAnimation !== undefined) {
candidate = { ...candidate, animation: transientAnimation };
}
- let stagedSampler = transientTime === undefined ? compileAgentMotion(candidate.motion, motionRecipe(candidate)) : sampler;
+ let stagedSampler = transientTime === undefined ? agentMotion.compileAgentMotion(candidate.motion, motionRecipe(candidate)) : sampler;
const targetTime = transientTime === undefined ? (candidate.motion ? 0 : null) : transientTime;
if (targetTime !== null && !stagedSampler) {
throw new RangeError('The asset has no authored motion to sample.');
@@ -510,7 +513,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
if (autoFrame) {
candidate.camera = framedCamera(framingBounds(records, stagedMatrices));
candidate = normalize(candidate);
- stagedSampler = compileAgentMotion(candidate.motion, motionRecipe(candidate));
+ stagedSampler = agentMotion.compileAgentMotion(candidate.motion, motionRecipe(candidate));
sampled = targetTime === null ? null : stagedSampler.sample(targetTime);
}
const stagedMaterials = new Map([...materialRecords].map(([id, record]) => [id, { ...record.baseline }]));
@@ -564,7 +567,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
/** scene_inspect's motionIk: how each solver fares across the clip, from a sampler that leaves the published pose alone. */
function motionIkReport() {
if (!recipe.motion?.ik?.length) return {};
- const sweeper = compileAgentMotion(recipe.motion, motionRecipe(recipe));
+ const sweeper = agentMotion.compileAgentMotion(recipe.motion, motionRecipe(recipe));
return {
motionIk: sweeper.sweepIk(time => stagedNodePoses(recipe.animation, [...trackOverrides(recipe.nodeOverrides, sweeper.sample(time)).values()])),
};
diff --git a/src/agent-mesh-engine.js b/src/agent-mesh-engine.js
new file mode 100644
index 00000000..dff14173
--- /dev/null
+++ b/src/agent-mesh-engine.js
@@ -0,0 +1,5 @@
+// Everything the agent scene needs for mesh geometry, behind one on-demand import (see agent-scene-modules.js).
+export { meshReport, generateMeshGeometry } from './agent-mesh.js';
+export { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';
+export { expandInstancedNodes } from './mesh-instances.js';
+export { loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from './mesh-boolean.js';
diff --git a/src/agent-mesh.js b/src/agent-mesh.js
index a62113d9..0c7c40af 100644
--- a/src/agent-mesh.js
+++ b/src/agent-mesh.js
@@ -2,18 +2,16 @@ import { meshFromGeometry } from './mesh-convert.js';
import { lintMesh } from './mesh-lint.js';
import { applyMeshEdits, evaluateMeshStack } from './mesh-recipe.js';
import { extractRender } from './mesh-render.js';
+import { MESH_SMOOTH_ANGLE_DEFAULT } from './agent-scene-capabilities.js';
+
+export { MESH_SMOOTH_ANGLE_DEFAULT };
+export { needsMeshBooleans } from './agent-scene-modules.js';
// Compact, agent-facing mesh reports for scene geometry. Reports are cached per immutable geometry object, so
// repeated inspection of an unchanged scene costs nothing.
-export const MESH_SMOOTH_ANGLE_DEFAULT = 30;
const reports = new WeakMap();
-/** Whether a recipe, operation list or edit list contains a boolean edit, which needs loadMeshBooleans() first. */
-export function needsMeshBooleans(value) {
- return JSON.stringify(value ?? null).includes('"op":"boolean"');
-}
-
// Render geometry generated from a mesh recipe keeps its polygon mesh and edit results here.
const polygonMeshes = new WeakMap();
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4a6d9717..0d8a205b 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -47,3 +47,6 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
motionIk: Object.freeze(['two-bone', 'aim']),
motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),
});
+
+/** Degrees between faces above which a mesh geometry keeps a hard edge, as Blender's auto smooth does. */
+export const MESH_SMOOTH_ANGLE_DEFAULT = 30;
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
new file mode 100644
index 00000000..12e8bc73
--- /dev/null
+++ b/src/agent-scene-modules.js
@@ -0,0 +1,98 @@
+// Code that most recipes never run loads on demand, so the agent scene entry stays small. A recipe that uses mesh
+// editing, procedural modeling, motion or material patterns needs its module loaded before createAgentScene runs:
+// call `await loadAgentSceneModules(recipe)` (or `loadAllAgentSceneModules()` in a host that does not mind the
+// size). createAgentScene is still synchronous; when a needed module is missing it says which call to make.
+
+const MODULE_LOADERS = {
+ mesh: () => import('./agent-mesh-engine.js'),
+ modeling: () => import('./modeling.js'),
+ motion: () => import('./agent-motion.js'),
+ patterns: () => import('./material-patterns.js'),
+};
+
+const loadedModules = {};
+const pendingLoads = {};
+let manifoldLoader = null;
+
+// Each test errs on the side of loading: a false positive costs a chunk, a false negative a clear error.
+const MODULE_MARKERS = {
+ mesh: ['"type":"mesh"', '"instances"'],
+ modeling: ['"type":"lathe"', '"type":"extrude"', '"type":"tube"'],
+ motion: ['"motion":{'],
+ patterns: ['"pattern"'],
+};
+
+/** Whether a recipe, operation list or edit list contains a boolean edit, which needs loadMeshBooleans() first. */
+export function needsMeshBooleans(value) {
+ return JSON.stringify(value ?? null).includes('"op":"boolean"');
+}
+
+/** Names of the on-demand modules a recipe, or a list of edit operations, needs. */
+export function agentSceneModulesNeeded(value) {
+ let text;
+ try {
+ text = JSON.stringify(value ?? null);
+ } catch {
+ return Object.keys(MODULE_LOADERS);
+ }
+ const compact = text.replace(/"\s*:\s*/g, '":');
+ return Object.keys(MODULE_MARKERS).filter(name => MODULE_MARKERS[name].some(marker => compact.includes(marker)));
+}
+
+function loadModule(name) {
+ if (loadedModules[name]) return Promise.resolve(loadedModules[name]);
+ pendingLoads[name] ??= MODULE_LOADERS[name]().then(module => {
+ loadedModules[name] = module;
+ if (name === 'mesh' && manifoldLoader) module.setManifoldModuleLoader(manifoldLoader);
+ return module;
+ });
+ return pendingLoads[name];
+}
+
+/** Load the modules a recipe (or a list of edit operations) needs. Safe to call repeatedly. */
+export async function loadAgentSceneModules(value) {
+ await Promise.all(agentSceneModulesNeeded(value).map(loadModule));
+}
+
+/** Load every on-demand module, for hosts that run any recipe an agent writes. */
+export async function loadAllAgentSceneModules() {
+ await Promise.all(Object.keys(MODULE_LOADERS).map(loadModule));
+}
+
+/** Entries that import a module statically register it here, so createAgentScene finds it without a load call. */
+export function registerAgentSceneModule(name, module) {
+ loadedModules[name] ??= module;
+}
+
+/** The loaded module, or an error that names the call that loads it. */
+export function agentSceneModule(name) {
+ const module = loadedModules[name];
+ if (!module) {
+ throw new Error(`This recipe needs the ${name} code, which loads on demand: await loadAgentSceneModules(recipe) before createAgentScene or apply.`);
+ }
+ return module;
+}
+
+export function allAgentSceneModulesLoaded() {
+ return Object.keys(MODULE_LOADERS).every(name => loadedModules[name]);
+}
+
+export function agentSceneModuleLoaded(name) {
+ return Boolean(loadedModules[name]);
+}
+
+/** Replace how the Manifold module is imported. Applied when the mesh code loads, if it has not yet. */
+export function setManifoldModuleLoader(loader) {
+ if (typeof loader !== 'function') throw new TypeError('The Manifold loader must be a function returning a module promise.');
+ manifoldLoader = loader;
+ loadedModules.mesh?.setManifoldModuleLoader(loader);
+}
+
+export async function loadMeshBooleans(options) {
+ const mesh = await loadModule('mesh');
+ return mesh.loadMeshBooleans(options);
+}
+
+export function meshBooleansLoaded() {
+ return loadedModules.mesh?.meshBooleansLoaded() ?? false;
+}
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 36dfd26b..61cbf888 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1,20 +1,17 @@
import { mat4, mat3 } from 'gl-matrix';
import { box, cylinder, sphere, torus } from './geometry.js';
-import { lathe, extrude, tube } from './modeling.js';
import { createSceneGraph } from './scene-graph.js';
import { applyProjection } from './camera.js';
import { normalizeAgentLook } from './agent-look.js';
-import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';
-import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './agent-mesh.js';
-import { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';
-import { expandInstancedNodes } from './mesh-instances.js';
-import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
+import { agentSceneModule } from './agent-scene-modules.js';
+import { MESH_SMOOTH_ANGLE_DEFAULT, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
import { MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
-import { materialPatternTextures, normalizeMaterialPattern } from './material-patterns.js';
export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
-export { needsMeshBooleans } from './agent-mesh.js';
-export { loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from './mesh-boolean.js';
+export {
+ needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader,
+ loadAgentSceneModules, loadAllAgentSceneModules, allAgentSceneModulesLoaded, agentSceneModulesNeeded,
+} from './agent-scene-modules.js';
const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAX_MESH_REPORTS = 16;
@@ -202,7 +199,7 @@ function materialFrom(value) {
}
if (value.pattern !== undefined) {
if (result.tag !== 'surface') throw new RangeError('Material pattern needs the surface tag.');
- result.pattern = normalizeMaterialPattern(value.pattern);
+ result.pattern = agentSceneModule('patterns').normalizeMaterialPattern(value.pattern);
}
result.opacity = defaultValue(value.opacity, 1);
finite(result.opacity, 'opacity');
@@ -384,11 +381,11 @@ function geometryEstimate(value) {
throw new TypeError('mesh base must be a primitive or profile geometry record without an id (box, cylinder, sphere, torus, lathe, extrude or tube).');
}
let estimate = geometryEstimate({ id: 'base', ...base });
- for (const edit of normalizeMeshEdits(value.edits ?? [])) {
+ for (const edit of agentSceneModule('mesh').normalizeMeshEdits(value.edits ?? [])) {
if (edit.op === 'boolean') estimate += cutterEstimate(edit.cutter);
}
// Stack nodes multiply the mesh: arrays by their count, mirror and solidify at most by two.
- for (const node of normalizeMeshStack(value.stack ?? [])) estimate *= node.op === 'array' ? node.count : 2;
+ for (const node of agentSceneModule('mesh').normalizeMeshStack(value.stack ?? [])) estimate *= node.op === 'array' ? node.count : 2;
if (value.smoothAngle !== undefined && (value.smoothAngle < 0 || value.smoothAngle > 180)) {
throw new RangeError('smoothAngle is degrees from 0 to 180.');
}
@@ -398,6 +395,10 @@ function geometryEstimate(value) {
}
}
+function hasInstancedNodes(nodes) {
+ return !Array.isArray(nodes) || nodes.some(node => node && typeof node === 'object' && Object.hasOwn(node, 'instances'));
+}
+
function cutterEstimate(cutter) {
if (cutter.type === 'mesh' || Object.hasOwn(cutter, 'id')) {
throw new TypeError('A boolean cutter must be a primitive or profile record without an id (box, cylinder, sphere, torus, lathe, extrude or tube).');
@@ -416,13 +417,13 @@ function generateGeometry(value, maxVertices) {
case 'torus':
return torus(value.tubeRadius, value.segments, value.sides, value.arc, value.start);
case 'lathe':
- return lathe(value.profile, { ...value, maxVertices });
+ return agentSceneModule('modeling').lathe(value.profile, { ...value, maxVertices });
case 'extrude':
- return extrude(value.contour, { ...value, maxVertices });
+ return agentSceneModule('modeling').extrude(value.contour, { ...value, maxVertices });
case 'tube':
- return tube(value.path, { ...value, maxVertices });
+ return agentSceneModule('modeling').tube(value.path, { ...value, maxVertices });
case 'mesh':
- return generateMeshGeometry(() => generateGeometry(value.base, maxVertices), value.edits ?? [], {
+ return agentSceneModule('mesh').generateMeshGeometry(() => generateGeometry(value.base, maxVertices), value.edits ?? [], {
maxVertices, smoothAngle: value.smoothAngle ?? MESH_SMOOTH_ANGLE_DEFAULT,
stack: value.stack ?? [], cacheKey: JSON.stringify(value.base),
resolveCutter: cutter => {
@@ -506,7 +507,7 @@ function normalizeRecipe(input, limits) {
if (distinctPatterns.size > MAX_MATERIAL_PATTERNS) {
throw new RangeError(`A scene holds at most ${MAX_MATERIAL_PATTERNS} different material patterns; it has ${distinctPatterns.size}. Reuse a pattern and tint it with color.`);
}
- recipe.nodes = expandInstancedNodes(recipe.nodes, {
+ if (hasInstancedNodes(recipe.nodes)) recipe.nodes = agentSceneModule('mesh').expandInstancedNodes(recipe.nodes, {
maxNodes: limits.maxNodes,
resolveSurface: id => {
const definition = recipe.geometries.find(geometry => geometry.id === id);
@@ -524,7 +525,7 @@ function normalizeRecipe(input, limits) {
}
Object.assign(recipe, normalizeAgentLook(look));
if (Object.hasOwn(recipe, 'motion')) {
- recipe.motion = normalizeAgentMotion(recipe.motion, recipe);
+ recipe.motion = recipe.motion === null || recipe.motion === undefined ? null : agentSceneModule('motion').normalizeAgentMotion(recipe.motion, recipe);
}
recipe = copiedJson(recipe, limits.maxRecipeBytes);
return recipe;
@@ -564,7 +565,7 @@ function materialHandle(snapshot) {
enumerable: true,
// Baked on first read, so validating or inspecting a recipe never pays for it.
get() {
- return holder.snapshot.pattern ? materialPatternTextures(holder.snapshot.pattern)[field] : undefined;
+ return holder.snapshot.pattern ? agentSceneModule('patterns').materialPatternTextures(holder.snapshot.pattern)[field] : undefined;
},
});
}
@@ -800,7 +801,7 @@ export function createAgentScene(input, inputLimits = {}) {
stats: geometryStats(geometryRecords.values()),
};
stagedState.localBounds = localBounds;
- stagedState.motionSampler = compileAgentMotion(recipe.motion ?? null, recipe);
+ stagedState.motionSampler = recipe.motion ? agentSceneModule('motion').compileAgentMotion(recipe.motion, recipe) : null;
stagedState.poseGraph = stagedState.motionSampler ? compile(recipe, geometries, localBounds, limits) : null;
stagedState.initialPose = stagePose(stagedState, stagedState.motionSampler ? 0 : null);
return stagedState;
@@ -936,7 +937,7 @@ export function createAgentScene(input, inputLimits = {}) {
throw new TypeError('edit-mesh needs an edits array.');
}
target.edits = operation.replace ? operation.edits : [...(target.edits ?? []), ...operation.edits];
- normalizeMeshEdits(target.edits);
+ agentSceneModule('mesh').normalizeMeshEdits(target.edits);
continue;
}
if (operation.type === 'set-mesh-stack') {
@@ -950,7 +951,7 @@ export function createAgentScene(input, inputLimits = {}) {
throw new TypeError(`Geometry ${operation.geometry} is a ${target.type}. Only mesh geometries have a modifier stack.`);
}
const stack = operation.stack ?? target.stack ?? [];
- normalizeMeshStack(stack);
+ agentSceneModule('mesh').normalizeMeshStack(stack);
const applied = operation.apply ?? 0;
if (!Number.isInteger(applied) || applied < 0 || applied > stack.length) {
throw new RangeError(`apply must be an integer from 0 to the stack length ${stack.length}.`);
@@ -958,7 +959,7 @@ export function createAgentScene(input, inputLimits = {}) {
// Applying moves the first nodes into the edit log, as Blender's Apply modifier does.
target.edits = [...(target.edits ?? []), ...stack.slice(0, applied)];
target.stack = stack.slice(applied);
- normalizeMeshEdits(target.edits);
+ agentSceneModule('mesh').normalizeMeshEdits(target.edits);
continue;
}
if (operation.type === 'remove-node') {
@@ -1040,7 +1041,7 @@ export function createAgentScene(input, inputLimits = {}) {
const resident = geometryStats(ownedGeometryRecords());
return {
revision, topologyRevision,
- ...(state.recipe.motion?.ik?.length ? { motionIk: compileAgentMotion(state.recipe.motion, state.recipe).sweepIk() } : {}),
+ ...(state.recipe.motion?.ik?.length ? { motionIk: agentSceneModule('motion').compileAgentMotion(state.recipe.motion, state.recipe).sweepIk() } : {}),
motion: state.recipe.motion ? { duration: state.recipe.motion.duration, loop: state.recipe.motion.loop, tracks: state.recipe.motion.tracks.length, time: state.motionTime } : null,
boundsSpace: 'authored-base-world',
counts: {
@@ -1077,7 +1078,7 @@ export function createAgentScene(input, inputLimits = {}) {
if (!geometry) {
throw new RangeError(`Geometry ID was not found: ${id}. Known IDs: ${[...state.geometries.keys()].join(', ')}.`);
}
- return { geometry: id, ...meshReport(geometry) };
+ return { geometry: id, ...agentSceneModule('mesh').meshReport(geometry) };
});
return { revision, meshes, truncated: requested.length > selected.length };
},
diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.js
index 7f023f0c..e129e4a2 100644
--- a/tests/agent-preview.test.js
+++ b/tests/agent-preview.test.js
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { Script, createContext } from 'node:vm';
import { mat4 } from 'gl-matrix';
-import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded } from '../src/agent-scene.js';
+import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, loadAllAgentSceneModules, allAgentSceneModulesLoaded } from '../src/agent-scene.js';
import { applyProjection } from '../src/camera.js';
import { resolveAgentShadow } from '../src/agent-look.js';
import { createAgentAssetScene } from '../src/agent-asset.js';
@@ -64,7 +64,7 @@ function previewHarness() {
return new Proxy({}, { get: (target, field) => field === 'sampleFrame'
? frame => scene.sampleFrame(JSON.parse(JSON.stringify(frame))) : scene[field] });
},
- needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded,
+ needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, loadAllAgentSceneModules, allAgentSceneModulesLoaded,
// The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.
setManifoldModuleLoader: () => {},
parseGltf, Uint8Array, atob,
diff --git a/tests/agent-scene-on-demand.test.js b/tests/agent-scene-on-demand.test.js
new file mode 100644
index 00000000..88cccb0c
--- /dev/null
+++ b/tests/agent-scene-on-demand.test.js
@@ -0,0 +1,63 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import test from 'node:test';
+import { agentSceneModulesNeeded } from '../src/agent-scene-modules.js';
+
+// These run in clean child processes: the test script preloads every module into its own process.
+function runInCleanProcess(source) {
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', source], { cwd: process.cwd(), encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(result.stdout);
+}
+
+const MESH_RECIPE = `{
+ format: '67js.scene',
+ schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'mesh', base: { type: 'box' }, edits: [{ op: 'flip_normals' }] }],
+ materials: [{ id: 'paint' }],
+ nodes: [{ id: 'part', geometry: 'block', material: 'paint' }],
+}`;
+
+test('a recipe with only primitives needs no on-demand module', () => {
+ const needed = agentSceneModulesNeeded({
+ geometries: [{ id: 'cube', type: 'box' }],
+ materials: [{ id: 'paint', color: [1, 0, 0] }],
+ nodes: [{ id: 'part', geometry: 'cube', material: 'paint' }],
+ });
+ assert.deepEqual(needed, []);
+});
+
+test('markers name the module a recipe needs', () => {
+ assert.deepEqual(agentSceneModulesNeeded({ geometries: [{ id: 'g', type: 'mesh' }] }), ['mesh']);
+ assert.deepEqual(agentSceneModulesNeeded({ geometries: [{ id: 'g', type: 'lathe' }] }), ['modeling']);
+ assert.deepEqual(agentSceneModulesNeeded({ motion: { tracks: [] } }), ['motion']);
+ assert.deepEqual(agentSceneModulesNeeded({ materials: [{ id: 'm', pattern: { type: 'bricks' } }] }), ['patterns']);
+});
+
+test('a primitive recipe runs without loading any module', () => {
+ const output = runInCleanProcess(`
+ import { createAgentScene, agentSceneModulesNeeded } from './src/agent-scene.js';
+ import { agentSceneModuleLoaded } from './src/agent-scene-modules.js';
+ const recipe = { format: '67js.scene', schemaVersion: 1, geometries: [{ id: 'cube', type: 'box' }], materials: [{ id: 'paint' }], nodes: [{ id: 'part', geometry: 'cube', material: 'paint' }] };
+ const scene = createAgentScene(recipe);
+ console.log(JSON.stringify({ parts: scene.parts.length, needed: agentSceneModulesNeeded(recipe), loaded: ['mesh', 'modeling', 'motion', 'patterns'].filter(agentSceneModuleLoaded) }));
+ `);
+ assert.deepEqual(output, { parts: 1, needed: [], loaded: [] });
+});
+
+test('a mesh recipe says which call loads the mesh code, and runs once it is loaded', () => {
+ const output = runInCleanProcess(`
+ import { createAgentScene, loadAgentSceneModules } from './src/agent-scene.js';
+ const recipe = ${MESH_RECIPE};
+ let message = '';
+ try {
+ createAgentScene(recipe);
+ } catch (error) {
+ message = error.message;
+ }
+ await loadAgentSceneModules(recipe);
+ console.log(JSON.stringify({ message, parts: createAgentScene(recipe).parts.length }));
+ `);
+ assert.match(output.message, /loadAgentSceneModules/);
+ assert.equal(output.parts, 1);
+});
diff --git a/tests/support/load-agent-scene-modules.mjs b/tests/support/load-agent-scene-modules.mjs
new file mode 100644
index 00000000..59874c7f
--- /dev/null
+++ b/tests/support/load-agent-scene-modules.mjs
@@ -0,0 +1,5 @@
+// Preloaded into every test process (see the test script) so recipes of any kind run synchronously, as agents see
+// them in the MCP preview. tests/agent-scene-on-demand.test.js checks the unloaded path in clean child processes.
+import { loadAllAgentSceneModules } from '../../src/agent-scene.js';
+
+await loadAllAgentSceneModules();