Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Merge remote-tracking branch 'origin/main' into perf/agent-scene-on-demand

Nguyen Xuan An1cc539bf5693
diff --cc CHANGELOG.md
index a1a7cda0,fbfdc253..6de0efe4
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -2,7 -2,12 +2,13 @@@
## 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 joint limits, node constraints and drivers to motion (issue #58). Two-bone IK takes `limits` per joint and axis in degrees and `bendToward`; `scene_inspect` `motionIk` now carries `limited` (each pose a limit changed) and `warnings` (`hyperextended`, and `wrong-bend` for a knee or elbow bent the unnatural way, which a wrong pole used to hide behind `reached`). `motion.constraints` adds `copy_location`, `copy_rotation`, `copy_scale`, `limit_location`, `limit_rotation`, `track_to`, `child_of` (with an inverse and an influence blend) and `floor`, and `motion.drivers` sets a node component or material property from a bounded JSON expression over time and other nodes (never run as code). The order is tracks, IK, drivers, constraints, with no state between samples, so a seek equals playing. `copy_rotation`, `limit_rotation`, `track_to`, `child_of` and `floor` match Blender 5.2 world matrices in 8 recorded cases (`tests/fixtures/blender/constraints.json`). Joint limits are also in `67js/addons/skeleton-pose`. The `leg-plant` task joins the agent modeling suite. The expression language is a new small one in `src/motion-expression.js`: the field expressions of the mesh addon were not on `main` yet
+
+ - Reach Rapier from recipes: a `physics` section (and a `set-physics` operation) puts rigid bodies on node IDs with box, ball, capsule, convex or trimesh colliders fitted to their geometry, joints, gravity and a duration of up to 10 seconds. It is recorded once at 60 steps a second and seeks like `motion`, so a seek back repeats the same frame (checked as identical PNG bytes on SwiftShader through MCP). `scene_inspect` reports per-body final positions and resting times, contacts and sensor enter and leave events. Rapier stays an optional peer, served to the preview from `node_modules` like Manifold, so the MCP server bundle does not grow.
+ - Add trimesh and convex-hull colliders (bounded triangle and point counts, checked before allocation), sensors with enter and leave events, and 16-bit collision groups and masks to `addons/physics`, plus `contactEvents`, `restFrames`, `bakePhysicsScene`, `loadPhysicsEngine` and `setPhysicsModuleLoader`. A collider with `sensor` now bakes instead of throwing.
+ - Add the `tray-drop` task to the agent modeling suite: balls dropped into a pocket cut in an authored mesh, graded on a fixed trimesh body, balls resting on the pocket floor and a repeatable seek. Raise four size budgets for the physics code (`entry:physics` to 17,900, `entry:agent-scene` to 121,100, `entry:agent-asset` to 128,500, `scene:agent-scene` to 147,300 bytes gzip).
+
- 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 --cc scripts/agent-preview-browser.js
index b055b4c4,98814e37..abf2709a
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@@ -1,4 -1,4 +1,4 @@@
- import { createAgentScene, loadAllAgentSceneModules, allAgentSceneModulesLoaded, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from '../src/agent-scene.js';
-import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from '../src/agent-scene.js';
++import { createAgentScene, loadAllAgentSceneModules, allAgentSceneModulesLoaded, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from '../src/agent-scene.js';
import { Renderer67 } from '../src/renderer.js';
import { applyProjection } from '../src/camera.js';
import { mat4 } from 'gl-matrix';
@@@ -191,13 -191,16 +191,18 @@@ function createPreview(scene, { session
// 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));
+ // Rapier is the same kind of optional peer: its WASM travels inside the module served from /vendor/rapier.js.
+ setPhysicsModuleLoader(() => import(/* @vite-ignore */ new URL('/vendor/rapier.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);
+ const loads = [];
+ if (!meshBooleansLoaded() && needsMeshBooleans(value)) loads.push(loadMeshBooleans());
+ if (!physicsEngineLoaded() && needsPhysics(value)) loads.push(loadPhysicsEngine());
+ if (!loads.length) return run();
+ return Promise.all(loads).then(run);
}
function seekForExport(record, motionTime) {
diff --cc src/agent-physics.js
index 00000000,e413ba7e..1007f42f
mode 000000,100644..100644
--- a/src/agent-physics.js
+++ b/src/agent-physics.js
@@@ -1,0 -1,335 +1,331 @@@
-import { bakePhysicsScene, loadPhysicsEngine, physicsEngineLoaded } from './physics.js';
++import { bakePhysicsScene, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from './physics.js';
+
-export { loadPhysicsEngine, physicsEngineLoaded };
++export { loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader };
++export { needsPhysics } from './agent-scene-modules.js';
+
+ const FRAMES_PER_SECOND = 60;
+ const MAX_DURATION_SECONDS = 10;
+ const MAX_BODIES = 64;
+ const MAX_JOINTS = 64;
+ const MAX_LAYER = 15;
+ const MAX_TRIMESH_TRIANGLES = 20000;
+ const MAX_HULL_POINTS = 2048;
+ const MAX_SOURCE_VERTICES = 65536;
+ const MAX_REPORTED_CONTACTS = 64;
+ const MAX_REPORTED_SENSOR_EVENTS = 128;
+ const BODY_TYPES = ['dynamic', 'fixed', 'kinematic'];
+ const SHAPES = ['box', 'ball', 'capsule', 'convex', 'trimesh'];
+ const JOINT_TYPES = ['spherical', 'revolute', 'prismatic', 'fixed'];
+ const BODY_FIELDS = ['node', 'type', 'shape', 'mass', 'density', 'friction', 'restitution', 'sensor', 'velocity', 'angularVelocity', 'layer', 'collidesWith'];
+ const JOINT_FIELDS = ['type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'limits'];
+ const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints'];
+
-/** True when a recipe or an operation list carries a physics section, so the host loads the solver first. */
-export function needsPhysics(value) {
- return JSON.stringify(value ?? null).includes('"physics":{');
-}
-
+ function knownKeys(value, fields, label) {
+ if (!value || Object.getPrototypeOf(value) !== Object.prototype) {
+ throw new TypeError(`${label} must be a plain object.`);
+ }
+ for (const key of Object.keys(value)) {
+ if (!fields.includes(key)) {
+ throw new TypeError(`Unknown or unsupported ${label} field: ${key}.`);
+ }
+ }
+ }
+
+ function finiteNumber(value, label, minimum = -Infinity, maximum = Infinity) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value)) || value < minimum || value > maximum) {
+ throw new RangeError(`${label} must be a finite number within ${minimum} and ${maximum}.`);
+ }
+ return value;
+ }
+
+ function numberList(value, size, label) {
+ if (!Array.isArray(value) || value.length !== size) {
+ throw new TypeError(`${label} needs ${size} numbers.`);
+ }
+ return value.map(component => finiteNumber(component, label));
+ }
+
+ function nodeIdentifier(value, label) {
+ if (typeof value !== 'string' || !value.trim() || value.length > 128) {
+ throw new TypeError(`${label} needs a node ID of 1 to 128 characters.`);
+ }
+ return value;
+ }
+
+ function boundedArray(value, maximum, label) {
+ if (!Array.isArray(value) || value.length > maximum) {
+ throw new TypeError(`${label} must be an array of at most ${maximum} entries.`);
+ }
+ return value;
+ }
+
+ function normalizeBody(input, recipeNodes, motionNodeIds, claimedNodes) {
+ knownKeys(input, BODY_FIELDS, 'physics body');
+ const nodeId = nodeIdentifier(input.node, 'Physics body node');
+ const node = recipeNodes.get(nodeId);
+ if (!node) {
+ throw new RangeError(`Physics body node was not found: ${nodeId}.`);
+ }
+ if (node.geometry === undefined) {
+ throw new RangeError(`Physics body node ${nodeId} has no geometry to fit a collider to.`);
+ }
+ if (node.parent !== null) {
+ throw new RangeError(`Physics body node ${nodeId} must be a root node; reparent it or move its parent into the body.`);
+ }
+ if (claimedNodes.has(nodeId)) {
+ throw new RangeError(`Node ${nodeId} has more than one physics body.`);
+ }
+ if (motionNodeIds.has(nodeId)) {
+ throw new RangeError(`Node ${nodeId} has a motion translation or rotation track and a physics body. Pick one.`);
+ }
+ claimedNodes.add(nodeId);
+ const type = input.type ?? 'dynamic';
+ if (!BODY_TYPES.includes(type)) {
+ throw new RangeError(`Physics body type must be one of ${BODY_TYPES.join(', ')}.`);
+ }
+ if (input.sensor !== undefined && typeof input.sensor !== 'boolean') {
+ throw new TypeError('Physics body sensor must be boolean.');
+ }
+ const sensor = input.sensor ?? false;
+ const shape = input.shape ?? (sensor ? 'box' : type === 'dynamic' ? 'box' : 'trimesh');
+ if (!SHAPES.includes(shape)) {
+ throw new RangeError(`Physics shape must be one of ${SHAPES.join(', ')}.`);
+ }
+ if (shape === 'trimesh' && type === 'dynamic') {
+ throw new RangeError(`Body ${nodeId} is dynamic: use shape convex, box, ball or capsule. Trimesh is for fixed or kinematic bodies.`);
+ }
+ if (type !== 'dynamic' && (input.velocity !== undefined || input.angularVelocity !== undefined)) {
+ throw new TypeError(`Body ${nodeId} is ${type}: only dynamic bodies take velocity.`);
+ }
+ if (input.mass !== undefined && input.density !== undefined) {
+ throw new TypeError('A physics body takes mass or density, not both.');
+ }
+ const body = { node: nodeId, type, shape };
+ if (sensor) body.sensor = true;
+ if (input.mass !== undefined) body.mass = finiteNumber(input.mass, 'Physics mass', 1e-6, 1e9);
+ if (input.density !== undefined) body.density = finiteNumber(input.density, 'Physics density', 1e-6, 1e9);
+ if (input.friction !== undefined) body.friction = finiteNumber(input.friction, 'Physics friction', 0, 100);
+ if (input.restitution !== undefined) body.restitution = finiteNumber(input.restitution, 'Physics restitution', 0, 1);
+ if (input.velocity !== undefined) body.velocity = numberList(input.velocity, 3, 'Physics velocity');
+ if (input.angularVelocity !== undefined) body.angularVelocity = numberList(input.angularVelocity, 3, 'Physics angularVelocity');
+ if (input.layer !== undefined) body.layer = Math.trunc(finiteNumber(input.layer, 'Physics layer', 0, MAX_LAYER));
+ if (input.collidesWith !== undefined) {
+ const layers = boundedArray(input.collidesWith, MAX_LAYER + 1, 'Physics collidesWith');
+ body.collidesWith = [...new Set(layers.map(layer => Math.trunc(finiteNumber(layer, 'Physics collidesWith layer', 0, MAX_LAYER))))].sort((first, second) => first - second);
+ }
+ return body;
+ }
+
+ function normalizeJoint(input, bodyNodeIds) {
+ knownKeys(input, JOINT_FIELDS, 'physics joint');
+ if (!JOINT_TYPES.includes(input.type)) {
+ throw new RangeError(`Physics joint type must be one of ${JOINT_TYPES.join(', ')}.`);
+ }
+ for (const field of ['bodyA', 'bodyB']) {
+ if (!bodyNodeIds.has(input[field])) {
+ throw new RangeError(`Physics joint ${field} must be the node of a physics body: ${input[field]}.`);
+ }
+ }
+ const joint = { type: input.type, bodyA: input.bodyA, bodyB: input.bodyB };
+ for (const field of ['anchorA', 'anchorB', 'axis']) {
+ if (input[field] !== undefined) joint[field] = numberList(input[field], 3, `Physics joint ${field}`);
+ }
+ if (input.limits !== undefined) joint.limits = numberList(input.limits, 2, 'Physics joint limits');
+ return joint;
+ }
+
+ /** Validate a recipe physics section against its nodes. Returns the plain, bounded form stored in the recipe. */
+ export function normalizeAgentPhysics(input, recipe) {
+ if (input === null || input === undefined) {
+ return null;
+ }
+ knownKeys(input, PHYSICS_FIELDS, 'physics');
+ const duration = finiteNumber(input.duration, 'Physics duration', 0.1, MAX_DURATION_SECONDS);
+ const recipeNodes = new Map(recipe.nodes.map(node => [node.id, node]));
+ const motionNodeIds = new Set((recipe.motion?.tracks ?? [])
+ .filter(track => track.kind === 'node' && (track.property === 'translation' || track.property === 'rotation'))
+ .map(track => track.id));
+ const claimedNodes = new Set();
+ const bodies = boundedArray(input.bodies, MAX_BODIES, 'Physics bodies').map(body => normalizeBody(body, recipeNodes, motionNodeIds, claimedNodes));
+ if (!bodies.length) {
+ throw new RangeError('Physics needs at least one body. Use null to clear it.');
+ }
+ const result = { duration, bodies };
+ if (input.gravity !== undefined) result.gravity = numberList(input.gravity, 3, 'Physics gravity');
+ if (input.joints !== undefined) {
+ result.joints = boundedArray(input.joints, MAX_JOINTS, 'Physics joints').map(joint => normalizeJoint(joint, claimedNodes));
+ }
+ return result;
+ }
+
+ function scaledBounds(positions, scale) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let index = 0; index < positions.length; index += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ const coordinate = positions[index + axis] * scale[axis];
+ minimum[axis] = Math.min(minimum[axis], coordinate);
+ maximum[axis] = Math.max(maximum[axis], coordinate);
+ }
+ }
+ const center = minimum.map((value, axis) => (value + maximum[axis]) / 2);
+ const halfExtents = minimum.map((value, axis) => Math.max((maximum[axis] - value) / 2, 1e-4));
+ return { center, halfExtents };
+ }
+
+ function convexPoints(positions, scale, nodeId) {
+ if (positions.length / 3 > MAX_SOURCE_VERTICES) {
+ throw new RangeError(`Geometry of ${nodeId} has ${positions.length / 3} vertices; a convex collider reads at most ${MAX_SOURCE_VERTICES}. Use shape box or a coarser geometry.`);
+ }
+ const distinct = new Map();
+ for (let index = 0; index < positions.length; index += 3) {
+ const point = [positions[index] * scale[0], positions[index + 1] * scale[1], positions[index + 2] * scale[2]];
+ distinct.set(point.map(component => component.toFixed(5)).join(','), point);
+ if (distinct.size > MAX_HULL_POINTS) {
+ throw new RangeError(`Geometry of ${nodeId} has more than ${MAX_HULL_POINTS} distinct vertices for a convex collider. Use shape box or a coarser geometry.`);
+ }
+ }
+ return [...distinct.values()].flat();
+ }
+
+ function trimeshArrays(geometry, scale, nodeId) {
+ const triangleCount = geometry.indices.length / 3;
+ if (triangleCount > MAX_TRIMESH_TRIANGLES) {
+ throw new RangeError(`Geometry of ${nodeId} has ${triangleCount} triangles; a trimesh collider holds at most ${MAX_TRIMESH_TRIANGLES}. Use a coarser geometry or shape box.`);
+ }
+ const vertices = [];
+ for (let index = 0; index < geometry.positions.length; index += 3) {
+ vertices.push(geometry.positions[index] * scale[0], geometry.positions[index + 1] * scale[1], geometry.positions[index + 2] * scale[2]);
+ }
+ return { vertices, indices: Array.from(geometry.indices) };
+ }
+
+ function colliderFromGeometry(body, node, geometry) {
+ const { center, halfExtents } = scaledBounds(geometry.positions, node.scale);
+ if (body.shape === 'box') {
+ return { shape: 'cuboid', halfExtents, translation: center };
+ }
+ if (body.shape === 'ball') {
+ return { shape: 'ball', radius: Math.max(...halfExtents), translation: center };
+ }
+ if (body.shape === 'capsule') {
+ const radius = Math.max(halfExtents[0], halfExtents[2]);
+ return { shape: 'capsule', radius, halfHeight: Math.max(halfExtents[1] - radius, radius * 0.01), translation: center };
+ }
+ if (body.shape === 'convex') {
+ return { shape: 'convexHull', points: convexPoints(geometry.positions, node.scale, node.id) };
+ }
+ return { shape: 'trimesh', ...trimeshArrays(geometry, node.scale, node.id) };
+ }
+
+ function layerBits(layers) {
+ return layers.reduce((bits, layer) => bits | (1 << layer), 0);
+ }
+
+ function physicsDefinition(physics, recipe, geometries) {
+ const nodes = new Map(recipe.nodes.map(node => [node.id, node]));
+ const definition = { bodies: [], colliders: [], joints: [] };
+ if (physics.gravity) definition.gravity = physics.gravity;
+ for (const body of physics.bodies) {
+ const node = nodes.get(body.node);
+ definition.bodies.push({
+ name: node.id, type: body.type, translation: node.translation, rotation: node.rotation,
+ ...(body.velocity ? { linearVelocity: body.velocity } : {}),
+ ...(body.angularVelocity ? { angularVelocity: body.angularVelocity } : {}),
+ });
+ const collider = {
+ name: node.id, body: node.id,
+ ...colliderFromGeometry(body, node, geometries.get(node.geometry)),
+ ...(body.sensor ? { sensor: true } : {}),
+ ...(body.friction !== undefined ? { friction: body.friction } : {}),
+ ...(body.restitution !== undefined ? { restitution: body.restitution } : {}),
+ groups: 1 << (body.layer ?? 0),
+ mask: body.collidesWith ? layerBits(body.collidesWith) : 0xffff,
+ };
+ if (collider.shape !== 'trimesh') {
+ if (body.mass !== undefined) collider.mass = body.mass;
+ else collider.density = body.density ?? 1;
+ }
+ definition.colliders.push(collider);
+ }
+ (physics.joints ?? []).forEach((joint, index) => definition.joints.push({ name: `joint-${index}`, ...joint }));
+ return definition;
+ }
+
+ const roundedTime = (frame, timestep) => Number((frame * timestep).toFixed(3));
+ const roundedVector = values => Array.from(values, value => Number(value.toFixed(4)));
+
+ function contactReport(scene, physics) {
+ const sensorNodes = new Set(physics.bodies.filter(body => body.sensor).map(body => body.node));
+ const pairs = new Map();
+ const sensorEvents = [];
+ for (const event of scene.contactEvents) {
+ const first = scene.colliderNames[event.colliderA];
+ const second = scene.colliderNames[event.colliderB];
+ if (event.kind === 'sensor') {
+ if (sensorEvents.length < MAX_REPORTED_SENSOR_EVENTS) {
+ const sensor = sensorNodes.has(first) ? first : second;
+ sensorEvents.push({ sensor, other: sensor === first ? second : first, kind: event.started ? 'enter' : 'leave', time: roundedTime(event.frame, scene.timestep) });
+ }
+ continue;
+ }
+ const key = [first, second].sort().join('|');
+ const pair = pairs.get(key) ?? { a: first < second ? first : second, b: first < second ? second : first, firstTime: roundedTime(event.frame, scene.timestep), touching: 0, count: 0 };
+ pair.touching += event.started ? 1 : -1;
+ pair.count += event.started ? 1 : 0;
+ pairs.set(key, pair);
+ }
+ const contacts = [...pairs.values()].slice(0, MAX_REPORTED_CONTACTS)
+ .map(({ a, b, firstTime, touching, count }) => ({ a, b, firstTime, count, touchingAtEnd: touching > 0 }));
+ return { contacts, sensorEvents };
+ }
+
+ function bodyReport(scene, physics) {
+ const lastPose = scene.sample(scene.duration);
+ const previousPose = scene.sample(Math.max(0, scene.duration - scene.timestep));
+ return physics.bodies.map(body => {
+ const offset = scene.bodyIndex(body.node) * 7;
+ const finalPosition = Array.from(lastPose.subarray(offset, offset + 3));
+ const finalSpeed = Math.hypot(...finalPosition.map((value, axis) => value - previousPose[offset + axis])) / scene.timestep;
+ const restFrame = scene.restFrames[scene.bodyIndex(body.node)];
+ return {
+ node: body.node, type: body.type, shape: body.shape,
+ finalPosition: roundedVector(finalPosition), finalSpeed: Number(finalSpeed.toFixed(4)),
+ ...(body.type === 'dynamic' ? { restsAtTime: restFrame < 0 ? null : roundedTime(restFrame, scene.timestep) } : {}),
+ };
+ });
+ }
+
+ /**
+ * Bake the physics section with Rapier. The solver must already be loaded (see loadPhysicsEngine).
+ * The result is a pure function of time: `sample(t)` returns node patches and a seek never replays the solver.
+ */
+ export function bakeAgentPhysics(physics, recipe, geometries) {
+ const definition = physicsDefinition(physics, recipe, geometries);
+ const frameCount = Math.round(physics.duration * FRAMES_PER_SECOND) + 1;
+ const scene = bakePhysicsScene(definition, { frameCount, timestep: 1 / FRAMES_PER_SECOND, maxColliderTriangles: MAX_TRIMESH_TRIANGLES, maxHullPoints: MAX_HULL_POINTS });
+ const patches = new Map(physics.bodies.map(body => [body.node, { translation: new Float64Array(3), rotation: new Float64Array(4) }]));
+ const pose = new Float32Array(scene.bodyNames.length * 7);
+ let reportCache = null;
+ return Object.freeze({
+ duration: physics.duration,
+ sample(time) {
+ scene.sample(time, pose);
+ for (const [nodeId, patch] of patches) {
+ const offset = scene.bodyIndex(nodeId) * 7;
+ patch.translation.set(pose.subarray(offset, offset + 3));
+ patch.rotation.set(pose.subarray(offset + 3, offset + 7));
+ }
+ return patches;
+ },
+ /** Contacts, sensor events and resting state, as numbers an agent can read without a picture. */
+ report() {
+ reportCache ??= {
+ duration: physics.duration, frames: scene.frameCount, gravity: physics.gravity ?? [0, -9.81, 0],
+ bodies: bodyReport(scene, physics), ...contactReport(scene, physics),
+ eventsTruncated: scene.contactEventsTruncated,
+ };
+ return structuredClone(reportCache);
+ },
+ });
+ }
diff --cc src/agent-scene-capabilities.js
index 0d8a205b,754d5244..70fba010
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@@ -45,8 -45,15 +45,18 @@@ export const AGENT_SCENE_CAPABILITIES
lightLinking: false,
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim']),
+ motionConstraints: Object.freeze(['copy_location', 'copy_rotation', 'copy_scale', 'limit_location', 'limit_rotation', 'track_to', 'child_of', 'floor']),
+ motionDrivers: Object.freeze({ maxDrivers: 32, maxConstraints: 32, maxExpressionParts: 64, maxExpressionDepth: 8 }),
+ // Recipe physics: Rapier (an optional peer) bakes bodies on nodes offline; playback is a seek into the bake.
+ physics: Object.freeze({
+ bodyTypes: Object.freeze(['dynamic', 'fixed', 'kinematic']),
+ shapes: Object.freeze(['box', 'ball', 'capsule', 'convex', 'trimesh']),
+ jointTypes: Object.freeze(['spherical', 'revolute', 'prismatic', 'fixed']),
+ sensors: true, collisionLayers: 16, boneBodies: false,
+ limits: Object.freeze({ maxBodies: 64, maxJoints: 64, maxDuration: 10, framesPerSecond: 60, maxTrimeshTriangles: 20000, maxHullPoints: 2048 }),
+ }),
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 --cc src/agent-scene-modules.js
index 12e8bc73,00000000..5358c49c
mode 100644,000000..100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@@ -1,98 -1,0 +1,123 @@@
+// 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'),
++ physics: () => import('./agent-physics.js'),
+ patterns: () => import('./material-patterns.js'),
+};
+
+const loadedModules = {};
+const pendingLoads = {};
+let manifoldLoader = null;
++let physicsLoader = 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":{'],
++ physics: ['"physics":{'],
+ 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"');
+}
+
++/** True when a recipe or an operation list carries a physics section, so the host loads the solver first. */
++export function needsPhysics(value) {
++ return JSON.stringify(value ?? null).includes('"physics":{');
++}
++
+/** 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);
++ if (name === 'physics' && physicsLoader) module.setPhysicsModuleLoader(physicsLoader);
+ 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;
+}
++
++/** Replace how the Rapier module is imported. Applied when the physics code loads, if it has not yet. */
++export function setPhysicsModuleLoader(loader) {
++ if (typeof loader !== 'function') throw new TypeError('The physics loader must be a function returning a module promise.');
++ physicsLoader = loader;
++ loadedModules.physics?.setPhysicsModuleLoader(loader);
++}
++
++export async function loadPhysicsEngine(options) {
++ const physics = await loadModule('physics');
++ return physics.loadPhysicsEngine(options);
++}
++
++export function physicsEngineLoaded() {
++ return loadedModules.physics?.physicsEngineLoaded() ?? false;
++}
diff --cc src/agent-scene.js
index 61cbf888,25d1500c..f375a039
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@@ -3,15 -3,21 +3,16 @@@ import { box, cylinder, sphere, torus
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 { normalizeAgentPhysics, bakeAgentPhysics } from './agent-physics.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 { needsPhysics, loadPhysicsEngine, physicsEngineLoaded } from './agent-physics.js';
-export { setPhysicsModuleLoader } from './physics.js';
-export { loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from './mesh-boolean.js';
+export {
+ needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader,
++ needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader,
+ loadAgentSceneModules, loadAllAgentSceneModules, allAgentSceneModulesLoaded, agentSceneModulesNeeded,
+} from './agent-scene-modules.js';
const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAX_MESH_REPORTS = 16;
@@@ -525,8 -527,11 +526,11 @@@ 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);
}
+ if (Object.hasOwn(recipe, 'physics')) {
- recipe.physics = normalizeAgentPhysics(recipe.physics, recipe);
++ recipe.physics = agentSceneModule('physics').normalizeAgentPhysics(recipe.physics, recipe);
+ }
recipe = copiedJson(recipe, limits.maxRecipeBytes);
return recipe;
}
@@@ -801,12 -810,28 +809,28 @@@ export function createAgentScene(input
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);
+ stagedState.physicsSampler = stagePhysics(recipe, geometryRecords);
+ const animated = Boolean(stagedState.motionSampler || stagedState.physicsSampler);
+ stagedState.poseGraph = animated ? compile(recipe, geometries, localBounds, limits) : null;
+ stagedState.initialPose = stagePose(stagedState, animated ? 0 : null);
return stagedState;
}
+ // A bake costs a solver run, so an unchanged section on unchanged geometry reuses the last one.
+ function stagePhysics(recipe, geometryRecords) {
+ if (!recipe.physics) {
+ return null;
+ }
+ const bodyNodes = recipe.nodes.filter(node => recipe.physics.bodies.some(body => body.node === node.id));
+ const key = JSON.stringify([recipe.physics, bodyNodes, bodyNodes.map(node => geometryRecords.get(node.geometry).signature)]);
+ if (physicsBake?.key !== key) {
+ const geometries = new Map([...geometryRecords].map(([id, record]) => [id, record.geometry]));
- physicsBake = { key, sampler: bakeAgentPhysics(recipe.physics, recipe, geometries) };
++ physicsBake = { key, sampler: agentSceneModule('physics').bakeAgentPhysics(recipe.physics, recipe, geometries) };
+ }
+ return physicsBake.sampler;
+ }
+
function commit(stagedState, incrementRevision) {
publishPose(stagedState, stagedState.initialPose);
if (stagedState.topologyChanged) {
@@@ -1041,8 -1074,9 +1073,9 @@@
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,
+ physics: state.physicsSampler ? state.physicsSampler.report() : null,
boundsSpace: 'authored-base-world',
counts: {
nodes: state.recipe.nodes.length, parts: state.parts.length,
diff --cc tests/agent-preview.test.js
index e129e4a2,291eea6b..42ab04ec
--- a/tests/agent-preview.test.js
+++ b/tests/agent-preview.test.js
@@@ -3,7 -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, loadAllAgentSceneModules, allAgentSceneModulesLoaded } from '../src/agent-scene.js';
-import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, needsPhysics, loadPhysicsEngine, physicsEngineLoaded } from '../src/agent-scene.js';
++import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, 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,9 -64,10 +64,10 @@@ 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: () => {},
+ needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},
parseGltf, Uint8Array, atob,
applyProjection, mat4, resolveAgentShadow,
Renderer67: FaultInjectedRenderer,