Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Reach Rapier from recipes: trimesh and convex colliders, sensors, masks, recipe physics

Nguyen Xuan An66c18769b903
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7534a5ad..d6d0b113 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+- 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 spot lights (`environment.spotLights`, 8), rectangular area lights (`environment.areaLights`, 4) and shadows for point and spot lights (`castShadow: true`). Intensity of a spot light is candela, as for a point light, with Blender's cone mask. Area lights use a representative point, within 1.2 percent of Cycles on the axis. Shadows share one 2048 x 3072 depth atlas of 24 tiles (24 MiB, allocated on first use): a point light takes 6 and a spot light 1, and a request for more is an error. The shader code and the atlas exist only in a scene that uses them. Recipes get all of it through `set-environment`, the MCP schema and `scene_capabilities` (`maxSpotLights`, `maxAreaLights`, `localShadows`). Cascaded directional shadows and light linking are not part of this
- Add ten cutting and repair edits: `fill_holes`, `dissolve_faces`, `dissolve_edges`, `dissolve_verts`, `dissolve_limited`, `bisect_plane` (with `fill`, `clearInner`, `clearOuter`), `bridge_edge_loops` (with `segments`), `subdivide_edges`, `grid_fill` and `knife_project`. Each tags what it makes, and the edge rule `{ "open": true }` picks boundary edges. The lint message for an open boundary now suggests `fill_holes`. 18 new cases match Blender in counts, face sizes, area, volume and positions; the knife is compared only with a straight plane cut and differs where a face runs along the projection direction
diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.md
index a5c95d33..c844e091 100644
--- a/bench/agent-modeling/README.md
+++ b/bench/agent-modeling/README.md
@@ -36,6 +36,7 @@ own mesh report:
| crate-uv | The crate with even UVs |
| crate-wood | The crate with a wood material pattern, to see whether agents find `pattern` |
| arm-reach | A jointed arm whose tip moves between two points, to see whether agents find `motion.ik` |
+| tray-drop | Recipe physics: balls dropped into a pocket cut in an authored mesh, on a fixed trimesh body, graded on resting height, contact and a repeatable seek |
| robot-reach | The CC0 robot from `tests/fixtures`: IK over its Idle clip, found through the asset catalog and hierarchy |
| dice | Rounded edges plus 21 recessed pips, in one piece (harder) |
| flange | A hollow pipe with flanges and 12 bolt holes, in one piece (harder) |
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index 9f2bfa59..f2268e0b 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -79,6 +79,27 @@ function checkOne(check, measures) {
const onPath = close(solver.firstTarget, check.from) && close(solver.lastTarget, check.to);
return { pass: onPath && solver.reached, detail: `targets ${JSON.stringify(solver.firstTarget)} to ${JSON.stringify(solver.lastTarget)}, reached ${solver.reached}, worst ${solver.worstError}` };
}
+ case 'physicsBody': {
+ const body = measures.physics?.bodies.find(candidate => candidate.node === check.node);
+ return { pass: body?.type === check.type && body?.shape === check.shape, detail: body ? `${body.node} is ${body.type} ${body.shape}` : `no physics body on ${check.node}` };
+ }
+ case 'physicsRest': {
+ const problems = check.nodes.flatMap(node => {
+ const body = measures.physics?.bodies.find(candidate => candidate.node === node);
+ if (!body) return [`${node} has no physics body`];
+ const [x, y, z] = body.finalPosition;
+ const touching = measures.physics.contacts.some(contact => [contact.a, contact.b].includes(node) && [contact.a, contact.b].includes(check.touching) && contact.touchingAtEnd);
+ const found = [];
+ if (body.restsAtTime === null || body.restsAtTime === undefined) found.push(`${node} is still moving`);
+ if (y < check.height[0] || y > check.height[1]) found.push(`${node} ends at height ${round(y)}`);
+ if (Math.abs(x) > check.within || Math.abs(z) > check.within) found.push(`${node} ends outside the pocket at ${round(x)}, ${round(z)}`);
+ if (!touching) found.push(`${node} does not touch ${check.touching}`);
+ return found;
+ });
+ return { pass: problems.length === 0, detail: problems.join('; ') || `${check.nodes.length} balls at rest` };
+ }
+ case 'physicsSeek':
+ return { pass: measures.physicsSeekStable === true, detail: measures.physicsSeekStable ? 'identical matrices' : 'no physics, or a seek back differs' };
case 'tips':
return { pass: measures.tips === check.equals, detail: `${measures.tips} tips` };
case 'triangles':
diff --git a/bench/agent-modeling/look.mjs b/bench/agent-modeling/look.mjs
index 032da350..65bedb8c 100644
--- a/bench/agent-modeling/look.mjs
+++ b/bench/agent-modeling/look.mjs
@@ -24,11 +24,17 @@ const SWIFTSHADER_ARGUMENTS = ['--enable-webgl', '--ignore-gpu-blocklist', '--us
const roundScore = value => Number(value.toFixed(4));
+// The look is the authored base pose, which recipe physics does not change, and the render page has no solver.
+function withoutPhysics(recipe) {
+ const { physics, ...staticRecipe } = recipe;
+ return staticRecipe;
+}
+
/** World-space triangles of every drawn node, with motion sampled at time zero. Asset recipes have none here. */
export async function worldGeometriesOf(recipe) {
if (recipe.format === '67js.asset') return null;
if (needsMeshBooleans(recipe)) await loadMeshBooleans();
- const scene = createAgentScene(recipe);
+ const scene = createAgentScene(withoutPhysics(recipe));
if (recipe.motion) scene.sampleMotion(0);
return scene.parts.map(worldGeometry);
}
@@ -84,7 +90,7 @@ export async function renderLookImages(jobs) {
written.push([]);
continue;
}
- const images = await page.evaluate(([sceneRecipe, cameraViews]) => window.renderLookViews(sceneRecipe, cameraViews), [recipe, views]);
+ const images = await page.evaluate(([sceneRecipe, cameraViews]) => window.renderLookViews(sceneRecipe, cameraViews), [withoutPhysics(recipe), views]);
await mkdir(directory, { recursive: true });
const paths = [];
for (const { name, image } of images) {
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index af190bed..47e6cecc 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -4,7 +4,7 @@
// agent sees: welding render triangles again can invent non-manifold edges that the polygon mesh does not have.
import { readFile } from 'node:fs/promises';
import { createAgentAssetScene } from '../../src/agent-asset.js';
-import { createAgentScene, loadMeshBooleans, needsMeshBooleans } from '../../src/agent-scene.js';
+import { createAgentScene, loadMeshBooleans, needsMeshBooleans, loadPhysicsEngine, needsPhysics } from '../../src/agent-scene.js';
import { parseGltf } from '../../src/gltf.js';
const WELD_DISTANCE = 1e-5;
@@ -213,10 +213,26 @@ export async function measureAssetRecipe(recipe) {
};
}
+// Seeking away and back must give the same matrices, whatever the solver did in between.
+function seekIsStable(scene, duration) {
+ const snapshot = () => scene.parts.map(part => Array.from(part.matrix));
+ scene.sampleMotion(duration / 2);
+ const first = snapshot();
+ scene.sampleMotion(duration);
+ scene.sampleMotion(0);
+ scene.sampleMotion(duration / 2);
+ const second = snapshot();
+ scene.sampleMotion(null);
+ return JSON.stringify(first) === JSON.stringify(second);
+}
+
/** Load the recipe and measure what it builds. Throws if the recipe itself is invalid. */
export async function measureRecipe(recipe) {
if (needsMeshBooleans(recipe)) await loadMeshBooleans();
+ if (needsPhysics(recipe)) await loadPhysicsEngine();
const scene = createAgentScene(recipe);
+ const physics = scene.inspect({}).physics;
+ const physicsSeekStable = physics ? seekIsStable(scene, recipe.physics.duration) : null;
const geometries = scene.parts.map(worldGeometry);
const reports = new Map();
const reportOf = id => {
@@ -259,6 +275,8 @@ export async function measureRecipe(recipe) {
const allClosed = closedParts === parts;
return {
nodes: geometries.length,
+ physics,
+ physicsSeekStable,
patternTypes: scene.exportRecipe().materials.filter(material => material.pattern).map(material => material.pattern.type),
parts,
closedParts,
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index 7753e9dd..c20d3947 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -119,6 +119,32 @@ export const REFERENCES = {
}],
},
},
+ 'tray-drop': {
+ ...scene(
+ [
+ { id: 'tray', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [
+ { op: 'inset_region', select: { tag: 'top' }, thickness: 0.2, name: 'pocket' },
+ { op: 'extrude_face_region', select: { tag: 'pocket.cap' }, offset: -0.75 },
+ ] },
+ { id: 'ball', type: 'sphere', segments: 16, rings: 8 },
+ ],
+ [
+ { id: 'tray', geometry: 'tray', translation: [0, 0.2, 0], scale: [2, 0.4, 2] },
+ { id: 'ball-1', geometry: 'ball', translation: [0, 1, 0], scale: [0.1, 0.1, 0.1] },
+ { id: 'ball-2', geometry: 'ball', translation: [0.25, 1.5, 0.1], scale: [0.1, 0.1, 0.1] },
+ { id: 'ball-3', geometry: 'ball', translation: [-0.25, 2, -0.1], scale: [0.1, 0.1, 0.1] },
+ ],
+ ),
+ physics: {
+ duration: 3,
+ bodies: [
+ { node: 'tray', type: 'fixed', shape: 'trimesh' },
+ { node: 'ball-1', shape: 'ball' },
+ { node: 'ball-2', shape: 'ball' },
+ { node: 'ball-3', shape: 'ball' },
+ ],
+ },
+ },
'arm-reach': {
...scene(
[{ id: 'ball', type: 'sphere', segments: 16, rings: 8 }],
diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjs
index 2ae774c9..5c60c596 100644
--- a/bench/agent-modeling/tasks.mjs
+++ b/bench/agent-modeling/tasks.mjs
@@ -245,6 +245,22 @@ For this task the object does not need to rest on the ground.`,
{ kind: 'nodeDistance', from: 'elbow', to: 'tip', time: 1, distance: 0.4 },
],
},
+ {
+ id: 'tray-drop',
+ prompt: `A pocketed block with three balls dropped into it, using recipe physics. The block is node "tray", a mesh of
+2 m by 0.4 m by 2 m (X, Y, Z) standing on the ground, with a square pocket 1.2 m wide cut 0.3 m deep into the middle of
+its top face. Three balls of radius 0.1 m are nodes "ball-1", "ball-2" and "ball-3", starting above the pocket at
+[0, 1, 0], [0.25, 1.5, 0.1] and [-0.25, 2, -0.1]. Add a 3 second physics section: the tray is a fixed body with a
+trimesh collider, so it follows the pocket, and the balls are dynamic ball bodies. The balls must end resting on the
+pocket floor, not on the block's top. Check the result with scene_inspect.
+For this task the balls do not need to rest on the ground at time 0.`,
+ checks: [
+ { kind: 'lint' },
+ { kind: 'physicsBody', node: 'tray', type: 'fixed', shape: 'trimesh', label: 'tray is a fixed trimesh' },
+ { kind: 'physicsRest', nodes: ['ball-1', 'ball-2', 'ball-3'], height: [0.17, 0.23], within: 0.5, touching: 'tray', label: 'balls rest on the pocket floor' },
+ { kind: 'physicsSeek', label: 'seek back repeats the frame' },
+ ],
+ },
{
id: 'robot-reach',
assets: true,
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 1524ddf8..5f36d5b8 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -18,7 +18,7 @@
"entry:mesh": 44700,
"entry:shrinkwrap": 18300,
"entry:surface-attachment": 11800,
- "entry:physics": 16500,
+ "entry:physics": 17900,
"entry:spume": 9000,
"entry:retarget": 15700,
"entry:skeleton-pose": 17200,
@@ -28,11 +28,11 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 109400,
- "entry:agent-asset": 116900,
+ "entry:agent-scene": 121100,
+ "entry:agent-asset": 128500,
"entry:hdri": 3300,
"scene:lit-box": 54200,
"scene:gltf-box": 73300,
- "scene:agent-scene": 135800
+ "scene:agent-scene": 147300
}
}
diff --git a/docs/agent-motion.md b/docs/agent-motion.md
index 5fcf4240..c60de4da 100644
--- a/docs/agent-motion.md
+++ b/docs/agent-motion.md
@@ -158,6 +158,11 @@ Job snapshots must retain authored motion independently of imported animation an
Release `0.8.0` reuses this motion contract for [imported character joints](agent-character-motion.md).
The helper does not implement mixer controls, facial morph tracks or live playback clocks.
+## Physics beside motion
+
+A recipe can also carry a `physics` section (see "Recipe physics" in `docs/physics.md`). It is recorded once with Rapier and played back through the same `sampleMotion(time)` and MCP `motionTime`, so one seek moves tracks, IK and bodies together.
+A body node takes its pose from the recording. A node cannot have a body and a motion translation or rotation track, and a scene may have physics without any motion tracks.
+
## Bounds and checks
The controller accepts durations between 0.1 and 30 seconds.
diff --git a/docs/parity.md b/docs/parity.md
index e764f57b..60bcb2ae 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -109,7 +109,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Normals > Weighted Normal Modifier | missing | No equivalent. | | #42 |
| Modeling > Modifiers > Normals > Smooth By Angle Modifier | partial | `smoothAngle` is a geometry setting. It is not a stack node. | | #42 |
| Modeling > Modifiers > Physics > Cloth Modifier | missing | No cloth. | | #62 |
-| Modeling > Modifiers > Physics > Collision Modifier | partial | Rapier colliders work in code, with no trimesh. Recipes can not reach them. | [physics](../tests/physics.test.js) | #61 |
+| Modeling > Modifiers > Physics > Collision Modifier | partial | Rapier colliders fitted to recipe geometry as box, ball, capsule, convex hull or trimesh, so a body rests on an authored mesh. | [agent-physics](../tests/agent-physics.test.js) | #61 |
| Modeling > Modifiers > Physics > Dynamic Paint Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Physics > Explode Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Physics > Fluid Modifier | partial | `addons/spume` plays back a liquid baked outside the browser. | [spume](../tests/spume.test.js) | #63 |
@@ -171,18 +171,18 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Animation & Rigging > Shape Keys | partial | Morph targets import, render and animate. Recipes can not author them. | [morph](../tests/morph.test.js) | #59 |
| Animation & Rigging > Motion Paths | out of scope | Viewport display for hand work. `scene_inspect` reports motion as numbers. | | |
| Animation & Rigging > In-Betweens | out of scope | Pose tools for a hand. Agents write keyframes and IK targets. | | |
-| Physics > Rigid Body > Rigid Body Properties | partial | Rapier bodies and colliders in code, with no trimesh. | [physics](../tests/physics.test.js) | #61 |
-| Physics > Rigid Body > Rigid Body World | partial | Recorded simulation with deterministic seeks, in code. Recipes can not reach it. | [physics](../tests/physics.test.js) | #61 |
+| Physics > Rigid Body > Rigid Body Properties | partial | Dynamic, fixed and kinematic bodies with mass, density, friction, restitution and velocity, in code and in recipes. Trimesh and convex colliders, no bone-bound bodies yet. | [physics-colliders](../tests/physics-colliders.test.js) | #61 |
+| Physics > Rigid Body > Rigid Body World | partial | Recorded simulation with deterministic seeks, in code and in a recipe `physics` section (MCP, a seek back repeats the PNG). | [agent-physics](../tests/agent-physics.test.js) | #61 |
| Physics > Rigid Body > Rigid Body Constraints | partial | Fixed, spherical, revolute and prismatic joints, with limits and motors, in code. | [physics](../tests/physics.test.js) | #61 |
| Physics > Cloth | missing | No cloth. | | #62 |
| Physics > Soft Body | missing | No soft bodies. | | #62 |
| Physics > Fluid | partial | `addons/spume` plays back a liquid baked outside the browser. There is no smoke or fire. | [spume](../tests/spume.test.js) | #63 |
| Physics > Particle System | missing | No shared particle system. Sparks exist only in the demo film. | | #63 |
| Physics > Dynamic Paint | missing | No equivalent. | | |
-| Physics > Forces > Gravity | partial | Physics definitions set gravity, in code. | [physics](../tests/physics.test.js) | #61 |
+| Physics > Forces > Gravity | partial | Physics definitions and recipe `physics.gravity` set gravity. | [physics](../tests/physics.test.js) | #61 |
| Physics > Forces > Force Fields | missing | No force fields. | | #63 |
-| Physics > Collision | partial | Rapier collisions in code, with no sensors or masks. | [physics](../tests/physics.test.js) | #61 |
-| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 |
+| Physics > Collision | partial | Rapier collisions with sensors (enter and leave events) and 16 collision layers with masks, in code and recipes. `scene_inspect` reports contacts and resting state. | [physics-colliders](../tests/physics-colliders.test.js) | #61 |
+| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 |
| Physics > Simulation Nodes | missing | No node graph. | | #43 |
| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. There are no light probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 |
| Rendering > Render Engines > Cycles | missing | No path tracer and no render baking. | | #55, #57 |
diff --git a/docs/physics.md b/docs/physics.md
index 5bcab942..4f9c24b2 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -331,12 +331,60 @@ The selected shape adds complete joint motor snapshots to the existing serializa
This preserves pre-async validation, deterministic bake order and arbitrary recorded seeks after the solver world is freed.
The addon supports rigid-body contacts, compound colliders, impulses, kinematics, articulated graphs, and single-coordinate joint limits and motors.
-It does not implement cloth, soft bodies, mesh colliders, spherical multi-axis controls, sensors, collision masks, or live solver editing.
+It does not implement cloth, soft bodies, spherical multi-axis controls, or live solver editing.
It does not bind physics directly to skeletal bones or generate a humanoid skeleton.
Those features need additional public contracts.
Creating a scene bakes synchronously after asynchronous WASM initialization and can block the main thread.
A worker integration can move that bake off the render thread.
+## Mesh colliders, sensors and masks
+
+A collider takes `shape: 'convexHull'` with `points` (flat xyz, at most `maxHullPoints`, default 2048) or `shape: 'trimesh'` with `vertices` and `indices` (at most `maxColliderTriangles` triangles across the scene, default 20000).
+Counts are checked before any typed array is allocated, and indices must point at a vertex.
+A trimesh needs a `fixed` or `kinematic` body, because it encloses no volume to take a mass from.
+Use a convex hull for a dynamic body; its true mass comes from the hull, and the bounding box only sizes the safety checks.
+
+`sensor: true` makes a collider report overlaps without pushing anything.
+`groups` and `mask` are 16-bit integers. Two colliders touch only when each one's `groups` shares a bit with the other's `mask`.
+Both default to `0xffff`.
+
+The recorded scene lists what happened:
+
+- `contactEvents`: `{ frame, kind: 'contact' | 'sensor', started, colliderA, colliderB }` in step order, with indices into `colliderNames`. `contactEventsTruncated` is true past `maxContactEvents` (default 4096).
+- `restFrames`: per body, the frame from which it stays under 0.02 m/s and 0.05 rad/s until the end, or `-1` while it still moves.
+
+`bakePhysicsScene` is the synchronous twin of `createPhysicsScene`. Await `loadPhysicsEngine()` once, then bake without awaiting.
+`setPhysicsModuleLoader` replaces how Rapier is imported, for a host that serves it from a URL, as the MCP preview does.
+
+## Recipe physics
+
+A scene recipe takes a `physics` section, and `set-physics` edits it (`null` clears it):
+
+```json
+"physics": {
+ "duration": 3,
+ "gravity": [0, -9.81, 0],
+ "bodies": [
+ { "node": "tray", "type": "fixed", "shape": "trimesh" },
+ { "node": "ball-1", "shape": "ball", "restitution": 0.3, "layer": 1, "collidesWith": [0] }
+ ],
+ "joints": [{ "type": "revolute", "bodyA": "door", "bodyB": "frame", "axis": [0, 1, 0], "limits": [0, 1.5] }]
+}
+```
+
+Each body is a root node with a geometry. Its collider is fitted to that geometry at the node scale: `box`, `ball` and `capsule` from the bounds, `convex` from at most 2048 distinct vertices, `trimesh` from every triangle.
+Defaults are `box` for dynamic bodies and sensors, `trimesh` for fixed ones.
+`layer` (0 to 15) and `collidesWith` replace raw bit masks.
+A node cannot have both a physics body and a motion `translation` or `rotation` track.
+Limits: 64 bodies, 64 joints, 10 seconds, 60 steps a second, so at most 601 frames.
+
+The bake runs once, when the scene is created or the section changes, and is reused while the section and the geometry stay the same.
+After that the scene treats physics like motion: `sampleMotion(time)` and the MCP `motionTime` read the recording, so a seek back gives the same matrices. A time past `duration` holds the last pose, and `null` restores the authored pose.
+Rapier is loaded on demand, an optional peer dependency. The MCP runtime serves it from `node_modules` to the preview page, like Manifold, so the server bundle does not carry it.
+
+`scene_inspect` returns a `physics` report: per body the `finalPosition`, `finalSpeed` and `restsAtTime` (null while moving), the `contacts` between bodies with `firstTime`, `count` and `touchingAtEnd`, and the sensor `enter` and `leave` events with times.
+An agent can check that a ball came to rest on a mesh from these numbers, without a picture.
+
Repeat recordings require identical inputs, creation order, timestep, solver options, and Rapier version.
Rapier documents cross-platform determinism for its WASM solver under identical initial conditions.
Input calculations such as `Math.sin` can differ across platforms and invalidate that guarantee.
diff --git a/package.json b/package.json
index 1074a1a5..8a9bcfe8 100644
--- a/package.json
+++ b/package.json
@@ -123,6 +123,7 @@
"smoke:agent-assets": "node scripts/smoke-agent-assets.mjs",
"smoke:agent-render-jobs": "node scripts/smoke-agent-render-jobs.mjs",
"smoke:agent-motion": "node scripts/smoke-agent-motion.mjs",
+ "smoke:agent-physics": "node scripts/smoke-agent-physics.mjs",
"smoke:frame-encoder": "node scripts/smoke-frame-encoder.mjs",
"smoke:enhancements": "node scripts/smoke-enhancements.mjs",
"smoke:site": "node scripts/smoke-site.mjs",
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 1ab73ca0..48f7d694 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, 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';
@@ -188,11 +188,16 @@ 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));
+// 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.
function 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);
}
window.__agentPreview = {
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index ad12dfae..29f1205c 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -2,7 +2,7 @@ import { createServer } from 'node:http';
import { randomUUID } from 'node:crypto';
import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
-import { isAbsolute, join } from 'node:path';
+import { dirname, isAbsolute, join } from 'node:path';
import { createRequire } from 'node:module';
import packageMetadata from '../package.json' with { type: 'json' };
import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene-capabilities.js';
@@ -19,9 +19,11 @@ const EVALUATION_TIMEOUT_MS = 30000;
const html = '<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#182126}canvas{display:block;width:100vw;height:100vh}</style></head><body><canvas></canvas><script type="module" src="/preview.js"></script></body></html>';
/** Local, serialized browser preview. No browser is launched until scene creation. */
-const MANIFOLD_FILES = Object.freeze({
- '/vendor/manifold.js': { file: 'manifold.js', type: 'application/javascript; charset=utf-8' },
- '/vendor/manifold.wasm': { file: 'manifold.wasm', type: 'application/wasm' },
+// Optional peer dependencies the page loads from the host's node_modules. Rapier ships its WASM inside rapier.mjs.
+const VENDOR_FILES = Object.freeze({
+ '/vendor/manifold.js': { resolve: require => require.resolve('manifold-3d/manifold.js'), type: 'application/javascript; charset=utf-8' },
+ '/vendor/manifold.wasm': { resolve: require => require.resolve('manifold-3d/manifold.wasm'), type: 'application/wasm' },
+ '/vendor/rapier.js': { resolve: require => join(dirname(require.resolve('@dimforge/rapier3d-compat')), 'rapier.mjs'), type: 'application/javascript; charset=utf-8' },
});
export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memory = 192, assets: assetRoot,
@@ -112,12 +114,12 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
}
}
- // Mesh booleans load Manifold, an optional peer dependency, from the host's node_modules. Without it the page gets
- // a 404 and the boolean edit reports the install command.
- function serveManifoldFile({ file, type }, response) {
+ // Mesh booleans load Manifold and recipe physics loads Rapier, both optional peer dependencies, from the host's
+ // node_modules. Without one the page gets a 404 and the edit reports the install command.
+ function serveVendorFile({ resolve, type }, response) {
let path;
try {
- path = createRequire(import.meta.url).resolve(`manifold-3d/${file}`);
+ path = resolve(createRequire(import.meta.url));
} catch {
response.writeHead(404);
response.end();
@@ -150,9 +152,9 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
}
response.setHeader('Cache-Control', 'no-store');
response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'self' blob:");
- const vendor = request.method === 'GET' ? MANIFOLD_FILES[request.url] : undefined;
+ const vendor = request.method === 'GET' ? VENDOR_FILES[request.url] : undefined;
if (vendor) {
- serveManifoldFile(vendor, response);
+ serveVendorFile(vendor, response);
return;
}
if (request.method !== 'GET' || !['/', '/preview.js'].includes(request.url)) {
diff --git a/scripts/build-mcp.mjs b/scripts/build-mcp.mjs
index 32edca15..f976bee0 100644
--- a/scripts/build-mcp.mjs
+++ b/scripts/build-mcp.mjs
@@ -108,7 +108,7 @@ function singleModule(result, filename, browser) {
for (const specifier of chunk.dynamicImports) {
// Rolldown retains a self import to initialize inlined lazy modules without an extra chunk.
// manifold-3d is an optional peer dependency loaded on demand; the preview replaces this import at runtime.
- if (specifier !== filename && specifier !== 'manifold-3d' && (browser || (!isBuiltin(specifier) && specifier !== 'playwright-core'))) {
+ if (specifier !== filename && specifier !== 'manifold-3d' && specifier !== '@dimforge/rapier3d-compat' && (browser || (!isBuiltin(specifier) && specifier !== 'playwright-core'))) {
throw new Error(`${filename} has an unexpected dynamic import: ${specifier}.`);
}
}
@@ -142,7 +142,7 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {
...configuration.build,
target: 'es2022',
lib: { entry: join(root, 'scripts', 'agent-preview-browser.js'), formats: ['es'], fileName: () => 'preview.js' },
- rolldownOptions: { platform: 'browser', external: ['manifold-3d'], output: { codeSplitting: false, comments: { legal: true }, banner: legalBanner } },
+ rolldownOptions: { platform: 'browser', external: ['manifold-3d', '@dimforge/rapier3d-compat'], output: { codeSplitting: false, comments: { legal: true }, banner: legalBanner } },
},
}), 'preview.js', true);
const server = singleModule(await build({
@@ -154,7 +154,7 @@ export async function buildMcp({ outDir = join(root, 'build', 'mcp') } = {}) {
lib: { entry: join(root, 'scripts', 'mcp-server.mjs'), formats: ['es'], fileName: () => 'server.mjs' },
rolldownOptions: {
platform: 'node',
- external: specifier => isBuiltin(specifier) || specifier === 'playwright-core' || specifier === 'manifold-3d',
+ external: specifier => isBuiltin(specifier) || specifier === 'playwright-core' || specifier === 'manifold-3d' || specifier === '@dimforge/rapier3d-compat',
output: { codeSplitting: false, comments: { legal: true }, banner: legalBanner },
},
},
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 5631385e..ece78043 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -295,6 +295,35 @@ const motion = z.strictObject({
motionTrack('camera', 'roll', finite, finite),
])).max(128),
}).describe('One absolute-time procedural clip. Local node transforms propagate through parents. Cubic tangents are derivatives per second. Backend checks references, duplicate tracks, 2048 total keys and every sampled pose.');
+const physicsBody = z.strictObject({
+ node: identifier.describe('A root recipe node with a geometry. The collider is fitted to that geometry at the node scale, and the body drives the node pose.'),
+ type: z.enum(['dynamic', 'fixed', 'kinematic']).optional().describe('Defaults to dynamic. Fixed bodies never move.'),
+ shape: z.enum(['box', 'ball', 'capsule', 'convex', 'trimesh']).optional().describe('Collider fitted to the geometry. Defaults: box for dynamic bodies and sensors, trimesh for fixed ones. Trimesh follows every triangle (at most 20000) and needs a fixed or kinematic body; convex wraps at most 2048 distinct vertices.'),
+ mass: positive.optional().describe('Kilograms. Give mass or density, not both.'),
+ density: positive.optional().describe('Defaults to 1.'),
+ friction: nonnegative.optional(),
+ restitution: unit.optional(),
+ sensor: z.boolean().optional().describe('A trigger volume: nothing bounces off it, and scene_inspect lists enter and leave times.'),
+ velocity: vector3.optional(),
+ angularVelocity: vector3.optional(),
+ layer: z.number().int().min(0).max(15).optional().describe('Collision layer, 0 to 15. Defaults to 0.'),
+ collidesWith: z.array(z.number().int().min(0).max(15)).max(16).optional().describe('Layers this body hits. Two bodies collide only when each lists the other\'s layer. Defaults to all.'),
+});
+const physicsJoint = z.strictObject({
+ type: z.enum(['spherical', 'revolute', 'prismatic', 'fixed']),
+ bodyA: identifier,
+ bodyB: identifier,
+ anchorA: vector3.optional(),
+ anchorB: vector3.optional(),
+ axis: vector3.optional().describe('Unit vector for revolute and prismatic joints.'),
+ limits: z.tuple([finite, finite]).optional().describe('Radians for revolute, metres for prismatic.'),
+});
+const physics = z.strictObject({
+ duration: z.number().min(0.1).max(10),
+ gravity: vector3.optional().describe('Defaults to [0, -9.81, 0].'),
+ bodies: z.array(physicsBody).min(1).max(64),
+ joints: z.array(physicsJoint).max(64).optional().describe('Joint bodies are the node IDs of physics bodies.'),
+}).describe('Rigid-body physics recorded offline with Rapier at 60 steps a second, then played back by time like motion: scene_look and scene_review motionTime seek into the recording, so a seek back shows the identical frame. Bodies are recipe nodes; scene_inspect reports contacts, sensor events and resting state as numbers. Needs the optional peer dependency @dimforge/rapier3d-compat. A node cannot have a physics body and a motion translation or rotation track.');
const recipe = z.strictObject({
format: z.literal('67js.scene'),
schemaVersion: z.literal(1),
@@ -306,6 +335,7 @@ const recipe = z.strictObject({
effects: effects.optional(),
shadow: shadow.optional(),
motion: motion.nullable().optional(),
+ physics: physics.nullable().optional(),
}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');
const assetRecipe = z.strictObject({
format: z.literal('67js.asset'),
@@ -329,6 +359,7 @@ const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),
z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),
z.strictObject({ type: z.literal('set-motion'), motion: motion.nullable() }),
+ z.strictObject({ type: z.literal('set-physics'), physics: physics.nullable() }),
z.strictObject({ type: z.literal('set-environment'), environment }),
z.strictObject({ type: z.literal('set-effects'), effects }),
z.strictObject({ type: z.literal('set-shadow'), shadow }),
@@ -389,7 +420,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
register('scene_create', 'Create the single active render scene from a JSON recipe. Dispose an existing scene first.', z.strictObject({ recipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));
register('scene_asset_catalog', 'List content-bound GLB IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));
register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));
- register('scene_inspect', 'Read revision, counts and selected nodes. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));
+ register('scene_inspect', 'Read revision, counts and selected nodes. For a recipe with physics, the result lists body final positions, resting times, contacts and sensor enter/leave events. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));
register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Procedural scenes only. Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));
register('mesh_edit', 'Append edits to a recipe mesh geometry (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));
register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (mirror, array, solidify, bevel, uv_unwrap, subdivide), evaluated after its edits with each prefix cached, so changing a late node is cheap. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report with per-node results.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));
diff --git a/scripts/smoke-agent-physics.mjs b/scripts/smoke-agent-physics.mjs
new file mode 100644
index 00000000..52eb5e10
--- /dev/null
+++ b/scripts/smoke-agent-physics.mjs
@@ -0,0 +1,98 @@
+// Recipe physics through the real MCP server: Rapier loads in the SwiftShader preview page, the bake is recorded when
+// the scene is created, and seeking back must reproduce the same PNG bytes.
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-physics-'));
+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', 'cpu', '--memory', '96', '--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-physics-proof', version: '1' });
+
+async function call(name, argumentsValue = {}, timeout = 60000) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function look(sessionId, motionTime) {
+ const result = await call('scene_look', { sessionId, width: 480, height: 480, ...(motionTime !== undefined ? { motionTime } : {}) });
+ assert.match(result.structuredContent.graphics, /swiftshader/i);
+ return result.content.find(item => item.type === 'image').data;
+}
+
+// An authored ramp: a box mesh whose right face is lifted, so the top slopes down toward -X.
+const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'ramp', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [{ op: 'translate', select: { tag: 'right' }, offset: [0, 0.5, 0] }] },
+ { id: 'ball', type: 'sphere' },
+ ],
+ materials: [{ id: 'stone', color: [0.5, 0.5, 0.55] }, { id: 'red', color: [0.9, 0.2, 0.15] }],
+ nodes: [
+ { id: 'ramp', geometry: 'ramp', material: 'stone', scale: [4, 1, 3] },
+ { id: 'ball-a', geometry: 'ball', material: 'red', translation: [0.8, 2.5, 0], scale: [0.3, 0.3, 0.3] },
+ { id: 'ball-b', geometry: 'ball', material: 'red', translation: [0.2, 3.2, 0.5], scale: [0.3, 0.3, 0.3] },
+ ],
+ camera: { eye: [5, 4, 6], target: [0, 1, 0] },
+ physics: { duration: 4, bodies: [
+ { node: 'ramp', type: 'fixed', shape: 'trimesh' },
+ { node: 'ball-a', shape: 'ball', restitution: 0.4 },
+ { node: 'ball-b', shape: 'ball', restitution: 0.4 },
+ ] },
+};
+
+try {
+ await client.connect(transport);
+ const capabilities = (await call('scene_capabilities')).structuredContent;
+ assert.deepEqual(capabilities.scene.physics.shapes, ['box', 'ball', 'capsule', 'convex', 'trimesh']);
+ const created = (await call('scene_create', { recipe }, 180000)).structuredContent;
+ const sessionId = created.sessionId;
+ const report = (await call('scene_inspect', { sessionId })).structuredContent.physics;
+ const ballA = report.bodies.find(body => body.node === 'ball-a');
+ assert.ok(ballA.finalPosition[1] < 2.5, 'the ball fell');
+ assert.ok(report.contacts.some(contact => contact.a === 'ball-a' && contact.b === 'ramp'), 'the ball touched the ramp');
+
+ const start = await look(sessionId, 0);
+ const middle = await look(sessionId, 1.2);
+ const end = await look(sessionId, 4);
+ assert.notEqual(start, middle);
+ assert.notEqual(middle, end);
+ for (const [time, expected] of [[2.7, null], [0, start], [1.2, middle], [4, end], [0.4, null], [1.2, middle]]) {
+ const actual = await look(sessionId, time);
+ if (expected) {
+ assert.equal(actual, expected, `Seek to ${time} s must reproduce the same PNG bytes.`);
+ }
+ }
+ await mkdir('artifacts', { recursive: true });
+ for (const [name, data] of [['start', start], ['middle', middle], ['end', end]]) {
+ await writeFile(`artifacts/agent-physics-${name}.png`, Buffer.from(data, 'base64'));
+ }
+ await call('scene_dispose', { sessionId });
+ const processId = transport.pid;
+ await client.close();
+ const deadline = Date.now() + 7000;
+ let exited = false;
+ while (Date.now() < deadline && !exited) {
+ try {
+ process.kill(processId, 0);
+ await delay(50);
+ } catch (error) {
+ assert.equal(error.code, 'ESRCH');
+ exited = true;
+ }
+ }
+ assert.equal(exited, true, `Owned MCP process must exit: ${diagnostics}`);
+ console.log(JSON.stringify({ shuffledPngSeeksExact: true, contacts: report.contacts.length, ballARestsAt: ballA.restsAtTime, eofCleanup: true }));
+} finally {
+ await client.close();
+}
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 1c7fe3b9..87792dc9 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -42,6 +42,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Jointed motion (an arm reaching, a lamp or head tracking a point) on a recipe or an imported character uses `motion.ik`, which needs no quaternions: on a recipe parent the joint nodes and put sizes on child mesh nodes, on an asset find `node-N` IDs with `scene_inspect` kind hierarchy and aim with `worldForward`. Read `motionIk` from `scene_inspect`. See "Inverse kinematics" in the checkout's `docs/agent-motion.md`.
- Agent tool calls use the installed `67js-mcp` stdio server from release `0.5.0` onward. Read `docs/mcp.md` for launch and PNG feedback.
- Agent render jobs use `docs/agent-render-jobs.md`. Check source versus published support, configure a private store and poll until terminal.
+- Things that fall, pile up or rest on an authored mesh (dropped objects, a ball in a bowl, a trigger zone) use the recipe `physics` section: bodies on root node IDs, `shape: 'trimesh'` on a fixed body so objects follow the mesh, `sensor: true` for triggers, `layer` and `collidesWith` for masks. Seek with `motionTime` like motion, and read `physics` from `scene_inspect` (resting times, contacts, sensor events) instead of guessing from a picture. Needs the optional peer `@dimforge/rapier3d-compat`; bodies bound to bones for ragdolls are not supported. See "Recipe physics" in the checkout's `docs/physics.md`.
- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.
- Agent imported character motion uses `docs/agent-character-motion.md` from release `0.8.0`. Inspect source joints before authoring local tracks.
- Agent comparisons use `scene_review` from release `0.9.0`. Read `docs/agent-review.md` for isolated views and independent pose samples.
diff --git a/src/agent-physics.js b/src/agent-physics.js
new file mode 100644
index 00000000..e413ba7e
--- /dev/null
+++ b/src/agent-physics.js
@@ -0,0 +1,335 @@
+import { bakePhysicsScene, loadPhysicsEngine, physicsEngineLoaded } from './physics.js';
+
+export { loadPhysicsEngine, physicsEngineLoaded };
+
+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 --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 09462f2c..20fec9be 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -23,7 +23,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', 'edit-mesh', 'set-mesh-stack',
+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-physics', 'edit-mesh', 'set-mesh-stack',
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),
alphaModes: RECIPE_ALPHA_MODES,
@@ -37,5 +37,13 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
lightLinking: false,
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim']),
+ // 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 }),
});
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 5280641f..cc514d27 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -5,6 +5,7 @@ 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 { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
@@ -12,6 +13,8 @@ import { materialPatternTextures, normalizeMaterialPattern } from './material-pa
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';
const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
@@ -476,7 +479,7 @@ function boundsFor(geometry, matrix) {
function normalizeRecipe(input, limits) {
let recipe = copiedJson(input, limits.maxRecipeBytes);
- knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera', 'environment', 'effects', 'shadow', 'motion'], 'recipe');
+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics'], 'recipe');
if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {
throw new RangeError('Expected 67js.scene schemaVersion 1.');
}
@@ -507,6 +510,9 @@ function normalizeRecipe(input, limits) {
if (Object.hasOwn(recipe, 'motion')) {
recipe.motion = normalizeAgentMotion(recipe.motion, recipe);
}
+ if (Object.hasOwn(recipe, 'physics')) {
+ recipe.physics = normalizeAgentPhysics(recipe.physics, recipe);
+ }
recipe = copiedJson(recipe, limits.maxRecipeBytes);
return recipe;
}
@@ -587,12 +593,15 @@ function cameraPoseFrom(pose) {
// Candidate buffers are private. A failed seek cannot publish half a pose to render handles.
function stagePose(stagedState, time) {
const sampled = time === null ? null : stagedState.motionSampler?.sample(time);
+ // Physics holds its last pose after its duration, so a seek past the end is the resting state.
+ const simulated = time === null ? null : stagedState.physicsSampler?.sample(Math.min(time, stagedState.physicsSampler.duration));
const graph = stagedState.poseGraph ?? stagedState.graph;
if (stagedState.poseGraph) {
for (const node of stagedState.recipe.nodes) {
const patch = sampled?.nodes.get(node.id);
- const translation = patch?.translation ?? node.translation;
- const rotation = patch?.rotation ?? node.rotation;
+ const bodyPatch = simulated?.get(node.id);
+ const translation = bodyPatch?.translation ?? patch?.translation ?? node.translation;
+ const rotation = bodyPatch?.rotation ?? patch?.rotation ?? node.rotation;
const scale = patch?.scale ?? node.scale;
if (Array.from(scale).some(component => !Number.isFinite(Math.fround(component)) || Math.fround(component) <= 0)) {
throw new RangeError('Motion scale must remain positive at Float32 precision.');
@@ -674,6 +683,7 @@ export function createAgentScene(input, inputLimits = {}) {
let state = null;
let revision = 0;
let topologyRevision = 0;
+ let physicsBake = null;
const checkpoints = new Map();
function ownedGeometryRecords() {
@@ -781,11 +791,27 @@ export function createAgentScene(input, inputLimits = {}) {
};
stagedState.localBounds = localBounds;
stagedState.motionSampler = compileAgentMotion(recipe.motion ?? null, recipe);
- 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) };
+ }
+ return physicsBake.sampler;
+ }
+
function commit(stagedState, incrementRevision) {
publishPose(stagedState, stagedState.initialPose);
if (stagedState.topologyChanged) {
@@ -828,8 +854,8 @@ export function createAgentScene(input, inputLimits = {}) {
if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {
throw new RangeError('Motion time must be null or within zero and 3600 seconds.');
}
- if (time !== null && !state.motionSampler) {
- throw new RangeError('This procedural recipe has no motion.');
+ if (time !== null && !state.motionSampler && !state.physicsSampler) {
+ throw new RangeError('This procedural recipe has no motion or physics.');
}
publishPose(state, stagePose(state, time));
return state.motionTime;
@@ -864,6 +890,14 @@ export function createAgentScene(input, inputLimits = {}) {
candidate.motion = operation.motion;
continue;
}
+ if (operation.type === 'set-physics') {
+ knownKeys(operation, ['type', 'physics'], 'operation');
+ if (!Object.hasOwn(operation, 'physics')) {
+ throw new TypeError('set-physics requires physics; use null to clear it.');
+ }
+ candidate.physics = operation.physics;
+ continue;
+ }
const lookField = Object.hasOwn(LOOK_OPERATION_FIELDS, operation.type) ? LOOK_OPERATION_FIELDS[operation.type] : null;
if (lookField) {
knownKeys(operation, ['type', lookField], 'operation');
@@ -1022,6 +1056,7 @@ export function createAgentScene(input, inputLimits = {}) {
revision, topologyRevision,
...(state.recipe.motion?.ik?.length ? { motionIk: 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 --git a/src/physics.js b/src/physics.js
index 94f3e186..b0fe4950 100644
--- a/src/physics.js
+++ b/src/physics.js
@@ -1,6 +1,8 @@
import { mat4, quat, vec3 } from 'gl-matrix';
let rapierPromise;
+let rapierEngine;
+let loadRapierModule = () => import('@dimforge/rapier3d-compat');
const ZERO = [0, 0, 0];
const IDENTITY = [0, 0, 0, 1];
const MIN_NORMAL_FLOAT32 = 2 ** -126;
@@ -15,7 +17,39 @@ const LIMITS = {
maxJoints: [512, 8192],
maxEvents: [10000, 100000],
maxFrames: [3601, 1000000],
+ maxColliderTriangles: [20000, 200000],
+ maxHullPoints: [2048, 16384],
+ maxContactEvents: [4096, 100000],
};
+// A body counts as resting once it stays under both speeds until the last frame.
+const REST_LINEAR_SPEED = 0.02;
+const REST_ANGULAR_SPEED = 0.05;
+const MAX_GROUP_BITS = 0xffff;
+
+/** Replace how the Rapier module is imported, for hosts that serve it from a URL. */
+export function setPhysicsModuleLoader(loader) {
+ loadRapierModule = loader;
+ rapierPromise = undefined;
+ rapierEngine = undefined;
+}
+
+/** Load the Rapier WASM engine once. After it resolves, bakePhysicsScene runs synchronously. */
+export function loadPhysicsEngine() {
+ rapierPromise ??= loadRapierModule().then(async module => {
+ const rapier = module.default ?? module;
+ await rapier.init();
+ rapierEngine = rapier;
+ return rapier;
+ }, error => {
+ rapierPromise = undefined;
+ throw error;
+ });
+ return rapierPromise;
+}
+
+export function physicsEngineLoaded() {
+ return rapierEngine !== undefined;
+}
function fields(value, allowed, label) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
@@ -159,6 +193,69 @@ function initialJointCoordinate(joint, bodies) {
}
}
+function finiteArray(values, label, maximumLength) {
+ if (!Array.isArray(values) && !ArrayBuffer.isView(values)) {
+ throw new TypeError(`${label} must be an array of numbers`);
+ }
+ if (values.length > maximumLength) {
+ throw new RangeError(`${label} has ${values.length} numbers; the limit is ${maximumLength}`);
+ }
+ return Float32Array.from(values, (number, index) => scalar(number, `${label}[${index}]`));
+}
+
+function convexHullCollider(collider, limits) {
+ if (collider.vertices !== undefined || collider.indices !== undefined || collider.radius !== undefined || collider.halfHeight !== undefined || collider.halfExtents !== undefined) {
+ throw new TypeError('convexHull only accepts points');
+ }
+ if (!collider.points || collider.points.length % 3 !== 0 || collider.points.length < 12) {
+ throw new TypeError('convexHull points must hold at least four xyz points');
+ }
+ const points = finiteArray(collider.points, 'points', limits.maxHullPoints * 3);
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ let largestExtent = 0;
+ for (let index = 0; index < points.length; index += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], points[index + axis]);
+ maximum[axis] = Math.max(maximum[axis], points[index + axis]);
+ }
+ largestExtent = Math.max(largestExtent, Math.hypot(points[index], points[index + 1], points[index + 2]));
+ }
+ const size = maximum.map((value, axis) => value - minimum[axis]);
+ // The solver derives true mass from the hull; this bounding box only sizes the safety checks.
+ return { shape: 'convexHull', points, volume: size[0] * size[1] * size[2], smallestExtent: Math.min(...size) / 2, largestExtent };
+}
+
+function trimeshCollider(collider, body, limits, budget) {
+ if (body.type === 'dynamic') {
+ throw new TypeError('trimesh colliders need a fixed or kinematic body; use convexHull for a dynamic body');
+ }
+ if (collider.points !== undefined || collider.radius !== undefined || collider.halfHeight !== undefined || collider.halfExtents !== undefined) {
+ throw new TypeError('trimesh only accepts vertices and indices');
+ }
+ if (!collider.vertices || collider.vertices.length % 3 !== 0 || !collider.indices || collider.indices.length % 3 !== 0 || !collider.indices.length) {
+ throw new TypeError('trimesh needs xyz vertices and triangle indices');
+ }
+ // Counts are checked before any typed array is allocated.
+ budget.triangles += collider.indices.length / 3;
+ if (budget.triangles > limits.maxColliderTriangles) {
+ throw new RangeError(`trimesh colliders hold ${budget.triangles} triangles; maxColliderTriangles is ${limits.maxColliderTriangles}`);
+ }
+ const vertices = finiteArray(collider.vertices, 'vertices', limits.maxColliderTriangles * 3 * 3);
+ const vertexCount = vertices.length / 3;
+ const indices = Uint32Array.from(collider.indices, (index, position) => integer(index, `indices[${position}]`, 0, vertexCount - 1));
+ return { shape: 'trimesh', vertices, indices };
+}
+
+function meshCollider(collider, body, limits, budget) {
+ if (collider.shape === 'convexHull') return convexHullCollider(collider, limits);
+ if (collider.shape === 'trimesh') return trimeshCollider(collider, body, limits, budget);
+ if (collider.points !== undefined || collider.vertices !== undefined || collider.indices !== undefined) {
+ throw new TypeError(`${collider.shape} does not accept points, vertices or indices`);
+ }
+ return null;
+}
+
function prepare(definition, options) {
fields(definition, ['bodies', 'colliders', 'joints', 'events', 'gravity'], 'definition');
fields(options, ['frameCount', 'timestep', 'solverIterations', 'maxMemoryBytes', ...Object.keys(LIMITS)], 'options');
@@ -222,9 +319,27 @@ function prepare(definition, options) {
}
return bodyIndices.get(name);
}
+ const meshBudget = { triangles: 0 };
const colliders = rawColliders.map(collider => {
- fields(collider, ['name', 'body', 'shape', 'radius', 'halfHeight', 'halfExtents', 'translation', 'rotation', 'mass', 'density', 'friction', 'restitution'], `collider ${collider.name}`);
+ fields(collider, ['name', 'body', 'shape', 'radius', 'halfHeight', 'halfExtents', 'points', 'vertices', 'indices', 'translation', 'rotation', 'mass', 'density', 'friction', 'restitution', 'sensor', 'groups', 'mask'], `collider ${collider.name}`);
const body = bodyIndex(collider.body);
+ const mesh = meshCollider(collider, bodies[body], limits, meshBudget);
+ if (collider.sensor !== undefined && typeof collider.sensor !== 'boolean') {
+ throw new TypeError('sensor must be boolean');
+ }
+ const common = {
+ body,
+ translation: vector(collider.translation, 3, 'collider translation', ZERO),
+ rotation: rotation(collider.rotation, 'collider rotation'),
+ friction: scalar(collider.friction ?? 0.5, 'friction', 0),
+ restitution: scalar(collider.restitution ?? 0, 'restitution', 0, 1),
+ sensor: collider.sensor ?? false,
+ groups: integer(collider.groups ?? MAX_GROUP_BITS, 'groups', 0, MAX_GROUP_BITS),
+ mask: integer(collider.mask ?? MAX_GROUP_BITS, 'mask', 0, MAX_GROUP_BITS),
+ };
+ if (mesh?.shape === 'trimesh') {
+ return { ...common, ...mesh, effectiveMass: 0, minimumInertia: 0, largestExtent: 0 };
+ }
let radius;
let halfHeight;
let halfExtents;
@@ -255,6 +370,9 @@ function prepare(definition, options) {
halfHeight = positive(collider.halfHeight, 'halfHeight');
volume = Math.PI * radius ** 2 * 2 * halfHeight + 4 * Math.PI * radius ** 3 / 3;
smallestExtent = radius;
+ } else if (mesh) {
+ volume = mesh.volume;
+ smallestExtent = mesh.smallestExtent;
} else {
throw new TypeError(`unsupported collider shape ${collider.shape}`);
}
@@ -269,23 +387,20 @@ function prepare(definition, options) {
positive(mass / volume, 'collider effective density');
}
const minimumInertia = normalPositive(0.1 * effectiveMass * smallestExtent ** 2, 'collider minimum inertia scale');
- const largestExtent = halfExtents ? Math.max(...halfExtents) : radius + (halfHeight ?? 0);
+ const largestExtent = mesh ? mesh.largestExtent : halfExtents ? Math.max(...halfExtents) : radius + (halfHeight ?? 0);
positive(effectiveMass * largestExtent ** 2, 'collider maximum inertia scale');
return {
- body,
+ ...common,
shape: collider.shape,
radius,
halfHeight,
halfExtents,
+ points: mesh?.points,
mass,
density,
effectiveMass,
minimumInertia,
largestExtent,
- translation: vector(collider.translation, 3, 'collider translation', ZERO),
- rotation: rotation(collider.rotation, 'collider rotation'),
- friction: scalar(collider.friction ?? 0.5, 'friction', 0),
- restitution: scalar(collider.restitution ?? 0, 'restitution', 0, 1),
};
});
const massTotals = Array(bodies.length).fill(0);
@@ -293,6 +408,7 @@ function prepare(definition, options) {
const minimumInertiaTotals = Array(bodies.length).fill(0);
const maximumColliderOffsets = Array(bodies.length).fill(0);
for (const collider of colliders) {
+ if (collider.shape === 'trimesh') continue;
const index = collider.body;
massTotals[index] = normalPositive(massTotals[index] + collider.effectiveMass, 'compound body mass');
inertiaTotals[index] = positive(inertiaTotals[index] + collider.effectiveMass * (collider.largestExtent ** 2 + Math.hypot(...collider.translation) ** 2), 'compound body inertia scale');
@@ -422,6 +538,7 @@ function prepare(definition, options) {
frameCount,
timestep,
solverIterations,
+ maxContactEvents: limits.maxContactEvents,
memoryPlan,
};
}
@@ -570,12 +687,59 @@ function applyJointMotor(rapier, joint, motor) {
/** Bake a named rigid-body graph with Rapier, then release its solver world. */
export async function createPhysicsScene(definition, options = {}) {
const preparedScene = prepare(definition, options);
- rapierPromise ??= import('@dimforge/rapier3d-compat').then(async ({ default: rapier }) => {
- await rapier.init();
- return rapier;
- });
- const rapier = await rapierPromise;
+ await loadPhysicsEngine();
+ return bakePrepared(preparedScene);
+}
+
+/** Synchronous bake for hosts that already awaited loadPhysicsEngine. */
+export function bakePhysicsScene(definition, options = {}) {
+ if (!rapierEngine) {
+ throw new Error('Physics engine is not loaded. Await loadPhysicsEngine() first.');
+ }
+ return bakePrepared(prepare(definition, options));
+}
+
+function colliderDescriptor(rapier, collider) {
+ let descriptor;
+ if (collider.shape === 'ball') {
+ descriptor = rapier.ColliderDesc.ball(collider.radius);
+ } else if (collider.shape === 'cuboid') {
+ descriptor = rapier.ColliderDesc.cuboid(...collider.halfExtents);
+ } else if (collider.shape === 'capsule') {
+ descriptor = rapier.ColliderDesc.capsule(collider.halfHeight, collider.radius);
+ } else if (collider.shape === 'convexHull') {
+ descriptor = rapier.ColliderDesc.convexHull(collider.points);
+ if (!descriptor) {
+ throw new RangeError('convexHull points are degenerate: they must span a volume');
+ }
+ } else {
+ descriptor = rapier.ColliderDesc.trimesh(collider.vertices, collider.indices);
+ }
+ descriptor.setTranslation(...collider.translation);
+ descriptor.setRotation(xyzw(collider.rotation));
+ descriptor.setFriction(collider.friction);
+ descriptor.setRestitution(collider.restitution);
+ descriptor.setSensor(collider.sensor);
+ descriptor.setCollisionGroups(((collider.groups << 16) | collider.mask) >>> 0);
+ descriptor.setActiveEvents(rapier.ActiveEvents.COLLISION_EVENTS);
+ if (collider.shape !== 'trimesh') {
+ if (collider.mass === undefined) {
+ descriptor.setDensity(collider.density);
+ } else {
+ descriptor.setMass(collider.mass);
+ }
+ }
+ return descriptor;
+}
+
+function bakePrepared(preparedScene) {
+ const rapier = rapierEngine;
const world = new rapier.World(xyz(preparedScene.gravity));
+ const eventQueue = new rapier.EventQueue(true);
+ const contactEvents = [];
+ const colliderIndices = new Map();
+ const lastMovingFrames = new Int32Array(preparedScene.bodies.length).fill(-1);
+ let contactEventsTruncated = false;
let timeline;
try {
world.timestep = preparedScene.timestep;
@@ -600,26 +764,10 @@ export async function createPhysicsScene(definition, options = {}) {
}
return world.createRigidBody(descriptor);
});
- for (const collider of preparedScene.colliders) {
- let descriptor;
- if (collider.shape === 'ball') {
- descriptor = rapier.ColliderDesc.ball(collider.radius);
- } else if (collider.shape === 'cuboid') {
- descriptor = rapier.ColliderDesc.cuboid(...collider.halfExtents);
- } else {
- descriptor = rapier.ColliderDesc.capsule(collider.halfHeight, collider.radius);
- }
- descriptor.setTranslation(...collider.translation);
- descriptor.setRotation(xyzw(collider.rotation));
- descriptor.setFriction(collider.friction);
- descriptor.setRestitution(collider.restitution);
- if (collider.mass === undefined) {
- descriptor.setDensity(collider.density);
- } else {
- descriptor.setMass(collider.mass);
- }
- world.createCollider(descriptor, bodies[collider.body]);
- }
+ preparedScene.colliders.forEach((collider, colliderIndex) => {
+ const created = world.createCollider(colliderDescriptor(rapier, collider), bodies[collider.body]);
+ colliderIndices.set(created.handle, colliderIndex);
+ });
const joints = preparedScene.joints.map(joint => {
const anchorA = xyz(joint.anchorA);
const anchorB = xyz(joint.anchorB);
@@ -671,13 +819,26 @@ export async function createPhysicsScene(definition, options = {}) {
}
}
}
- world.step();
+ world.step(eventQueue);
+ eventQueue.drainCollisionEvents((firstHandle, secondHandle, started) => {
+ if (contactEvents.length >= preparedScene.maxContactEvents) {
+ contactEventsTruncated = true;
+ return;
+ }
+ const first = colliderIndices.get(firstHandle);
+ const second = colliderIndices.get(secondHandle);
+ const sensor = preparedScene.colliders[first].sensor || preparedScene.colliders[second].sensor;
+ contactEvents.push(Object.freeze({ frame, kind: sensor ? 'sensor' : 'contact', started, colliderA: first, colliderB: second }));
+ });
}
for (let bodyIndex = 0; bodyIndex < bodies.length; bodyIndex++) {
const linearVelocity = bodies[bodyIndex].linvel();
const angularVelocity = bodies[bodyIndex].angvel();
scalar(linearVelocity.x ** 2 + linearVelocity.y ** 2 + linearVelocity.z ** 2, 'solver linear velocity squared norm', 0);
scalar(angularVelocity.x ** 2 + angularVelocity.y ** 2 + angularVelocity.z ** 2, 'solver angular velocity squared norm', 0);
+ if (Math.hypot(linearVelocity.x, linearVelocity.y, linearVelocity.z) > REST_LINEAR_SPEED || Math.hypot(angularVelocity.x, angularVelocity.y, angularVelocity.z) > REST_ANGULAR_SPEED) {
+ lastMovingFrames[bodyIndex] = frame;
+ }
const position = bodies[bodyIndex].translation();
const bodyRotation = bodies[bodyIndex].rotation();
const offset = (frame * bodies.length + bodyIndex) * 7;
@@ -700,12 +861,13 @@ export async function createPhysicsScene(definition, options = {}) {
}
}
} finally {
+ eventQueue.free();
world.free();
}
- return recordedScene(preparedScene, timeline);
+ return recordedScene(preparedScene, timeline, { contactEvents, contactEventsTruncated, lastMovingFrames });
}
-function recordedScene(preparedScene, timeline) {
+function recordedScene(preparedScene, timeline, recording) {
const bodyNames = Object.freeze(preparedScene.bodies.map(body => body.name));
const indices = new Map(bodyNames.map((name, index) => [name, index]));
const poseStride = bodyNames.length * 7;
@@ -881,6 +1043,12 @@ function recordedScene(preparedScene, timeline) {
bodyIndex,
sample,
bindParts,
+ colliderNames: Object.freeze(preparedScene.colliders.map(collider => preparedScene.bodies[collider.body].name)),
+ /** Contact and sensor start or stop events in step order, with collider indices into colliderNames. */
+ contactEvents: Object.freeze(recording.contactEvents),
+ contactEventsTruncated: recording.contactEventsTruncated,
+ /** Per body: the frame at which it came to rest and stayed there, or -1 while it still moves at the end. */
+ restFrames: Object.freeze(Array.from(recording.lastMovingFrames, frame => frame < preparedScene.frameCount - 1 ? frame + 1 : -1)),
dispose() {
timeline = null;
},
diff --git a/tests/agent-modeling-suite.test.js b/tests/agent-modeling-suite.test.js
index b4b4a3ae..6dba9b31 100644
--- a/tests/agent-modeling-suite.test.js
+++ b/tests/agent-modeling-suite.test.js
@@ -41,3 +41,17 @@ test('an invalid recipe fails every check with the reason', async () => {
assert.equal(grade.passed, 0);
assert.match(grade.results[0].detail, /recipe failed/);
});
+
+test('the tray-drop checks reject a box collider, a missing section and a body that falls through', async () => {
+ const boxCollider = structuredClone(REFERENCES['tray-drop']);
+ boxCollider.physics.bodies[0].shape = 'box';
+ assert.deepEqual(failedKinds(await gradeRecipe(taskById('tray-drop'), boxCollider)), ['tray is a fixed trimesh', 'balls rest on the pocket floor']);
+
+ const noPhysics = structuredClone(REFERENCES['tray-drop']);
+ delete noPhysics.physics;
+ assert.deepEqual(failedKinds(await gradeRecipe(taskById('tray-drop'), noPhysics)), ['tray is a fixed trimesh', 'balls rest on the pocket floor', 'seek back repeats the frame']);
+
+ const fallingThrough = structuredClone(REFERENCES['tray-drop']);
+ fallingThrough.physics.bodies[0].collidesWith = [1];
+ assert.deepEqual(failedKinds(await gradeRecipe(taskById('tray-drop'), fallingThrough)), ['balls rest on the pocket floor']);
+});
diff --git a/tests/agent-physics.test.js b/tests/agent-physics.test.js
new file mode 100644
index 00000000..30820746
--- /dev/null
+++ b/tests/agent-physics.test.js
@@ -0,0 +1,118 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene, loadPhysicsEngine, needsPhysics } from '../src/agent-scene.js';
+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';
+
+await loadPhysicsEngine();
+
+function recipe(physics, extraNodes = []) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'slab', type: 'box' },
+ { id: 'ball', type: 'sphere' },
+ ],
+ materials: [{ id: 'paint', color: [0.6, 0.5, 0.4] }],
+ nodes: [
+ { id: 'floor', geometry: 'slab', material: 'paint', translation: [0, -0.25, 0], scale: [6, 0.5, 6] },
+ { id: 'ball', geometry: 'ball', material: 'paint', translation: [0, 2, 0], scale: [0.5, 0.5, 0.5] },
+ ...extraNodes,
+ ],
+ physics,
+ };
+}
+
+const dropOnFloor = { duration: 3, bodies: [{ node: 'floor', type: 'fixed' }, { node: 'ball', shape: 'ball', restitution: 0.3 }] };
+
+function matrixSnapshot(scene) {
+ return scene.parts.map(part => Array.from(part.matrix));
+}
+
+test('a recipe physics section drops a body onto a trimesh floor and seeks deterministically', () => {
+ const scene = createAgentScene(recipe(dropOnFloor));
+ scene.sampleMotion(1.2);
+ const middle = matrixSnapshot(scene);
+ scene.sampleMotion(0);
+ assert.equal(scene.parts[1].matrix[13], 2, 'time zero is the authored pose');
+ scene.sampleMotion(3);
+ const rested = scene.parts[1].matrix[13];
+ assert.ok(Math.abs(rested - 0.5) < 0.02, `ball rests on the floor, got ${rested}`);
+ scene.sampleMotion(1.2);
+ assert.deepEqual(matrixSnapshot(scene), middle);
+ scene.sampleMotion(null);
+ assert.equal(scene.parts[1].matrix[13], 2);
+});
+
+test('scene_inspect reports contacts, resting state and sensors as numbers', () => {
+ const scene = createAgentScene(recipe({
+ duration: 3,
+ bodies: [
+ { node: 'floor', type: 'fixed' },
+ { node: 'ball', shape: 'ball' },
+ { node: 'zone', type: 'fixed', sensor: true },
+ ],
+ }, [{ id: 'zone', geometry: 'slab', material: 'paint', translation: [0, 1.2, 0], scale: [2, 0.2, 2] }]));
+ const { physics } = scene.inspect({});
+ const ball = physics.bodies.find(body => body.node === 'ball');
+ assert.ok(ball.restsAtTime > 0.3 && ball.restsAtTime < 3);
+ assert.ok(Math.abs(ball.finalPosition[1] - 0.5) < 0.02);
+ assert.deepEqual(physics.contacts.map(({ a, b, touchingAtEnd }) => ({ a, b, touchingAtEnd })), [{ a: 'ball', b: 'floor', touchingAtEnd: true }]);
+ assert.deepEqual(physics.sensorEvents.map(event => [event.sensor, event.other, event.kind]), [['zone', 'ball', 'enter'], ['zone', 'ball', 'leave']]);
+});
+
+test('physics is recorded again only when its inputs change', () => {
+ const scene = createAgentScene(recipe(dropOnFloor));
+ scene.apply([{ type: 'set-physics', physics: { ...dropOnFloor, bodies: [{ node: 'floor', type: 'fixed' }, { node: 'ball', shape: 'ball', restitution: 0.9 }] } }], { expectedRevision: 0 });
+ scene.sampleMotion(0.9);
+ const bouncy = scene.parts[1].matrix[13];
+ scene.apply([{ type: 'set-physics', physics: null }], { expectedRevision: 1 });
+ assert.equal(scene.inspect({}).physics, null);
+ assert.equal(scene.parts[1].matrix[13], 2);
+ assert.ok(bouncy < 2);
+ assert.equal(scene.exportRecipe().physics, null);
+});
+
+test('masks and layers decide what a body falls through', () => {
+ const scene = createAgentScene(recipe({
+ duration: 3,
+ bodies: [{ node: 'floor', type: 'fixed', layer: 1, collidesWith: [1] }, { node: 'ball', shape: 'ball', layer: 2, collidesWith: [2] }],
+ }));
+ scene.sampleMotion(3);
+ assert.ok(scene.parts[1].matrix[13] < -10);
+});
+
+test('bad physics sections fail with a message that names the fix', () => {
+ const cases = [
+ [{ duration: 3, bodies: [{ node: 'missing' }] }, /not found/],
+ [{ duration: 0, bodies: [{ node: 'ball' }] }, /duration/],
+ [{ duration: 3, bodies: [] }, /at least one body/],
+ [{ duration: 3, bodies: [{ node: 'ball', shape: 'trimesh' }] }, /dynamic/],
+ [{ duration: 3, bodies: [{ node: 'ball' }, { node: 'ball' }] }, /more than one/],
+ [{ duration: 3, bodies: [{ node: 'ball', color: 1 }] }, /Unknown/],
+ [{ duration: 3, bodies: [{ node: 'ball' }], joints: [{ type: 'fixed', bodyA: 'ball', bodyB: 'floor' }] }, /physics body/],
+ [{ duration: 3, bodies: [{ node: 'ball', layer: 16 }] }, /layer/],
+ ];
+ for (const [physics, message] of cases) {
+ assert.throws(() => createAgentScene(recipe(physics)), message);
+ }
+});
+
+test('a node cannot have both a physics body and a motion track on its pose', () => {
+ const input = recipe({ duration: 3, bodies: [{ node: 'ball' }] });
+ input.motion = { duration: 1, tracks: [{ kind: 'node', id: 'ball', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [1, 0, 0] }] }] };
+ assert.throws(() => createAgentScene(input), /Pick one/);
+});
+
+test('a trimesh over the triangle limit is refused before it is copied', () => {
+ const input = recipe({ duration: 1, bodies: [{ node: 'floor', type: 'fixed' }] });
+ input.geometries[0] = { id: 'slab', type: 'sphere', segments: 200, rings: 200 };
+ assert.throws(() => createAgentScene(input), /triangles/);
+});
+
+test('capabilities name the physics surface and the detector finds a section', () => {
+ assert.deepEqual(AGENT_SCENE_CAPABILITIES.physics.shapes, ['box', 'ball', 'capsule', 'convex', 'trimesh']);
+ assert.ok(AGENT_SCENE_CAPABILITIES.operations.includes('set-physics'));
+ assert.equal(needsPhysics(recipe(dropOnFloor)), true);
+ assert.equal(needsPhysics(recipe(undefined)), false);
+ assert.equal(needsPhysics([{ type: 'set-physics', physics: null }]), false);
+});
diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.js
index 7f023f0c..291eea6b 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, needsPhysics, loadPhysicsEngine, physicsEngineLoaded } 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';
@@ -67,6 +67,7 @@ function previewHarness() {
needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded,
// 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,
diff --git a/tests/physics-colliders.test.js b/tests/physics-colliders.test.js
new file mode 100644
index 00000000..a638210a
--- /dev/null
+++ b/tests/physics-colliders.test.js
@@ -0,0 +1,100 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createPhysicsScene, planPhysicsScene } from '../src/physics.js';
+
+// A ramp-free tray: a trimesh floor made of two triangles at height zero.
+const FLOOR_VERTICES = [-5, 0, -5, 5, 0, -5, 5, 0, 5, -5, 0, 5];
+const FLOOR_INDICES = [0, 2, 1, 0, 3, 2];
+
+function trimeshFloor() {
+ return {
+ bodies: [{ name: 'floor', type: 'fixed' }],
+ colliders: [{ name: 'floor', body: 'floor', shape: 'trimesh', vertices: FLOOR_VERTICES, indices: FLOOR_INDICES }],
+ };
+}
+
+function dropBall(definition, name, height, extra = {}) {
+ definition.bodies.push({ name, translation: [0, height, 0] });
+ definition.colliders.push({ name, body: name, shape: 'ball', radius: 0.25, mass: 1, ...extra });
+}
+
+function bodyHeight(scene, name, time) {
+ return scene.sample(time)[scene.bodyIndex(name) * 7 + 1];
+}
+
+test('a ball comes to rest on a trimesh floor', async () => {
+ const definition = trimeshFloor();
+ dropBall(definition, 'ball', 2);
+ const scene = await createPhysicsScene(definition, { frameCount: 181 });
+ assert.ok(Math.abs(bodyHeight(scene, 'ball', scene.duration) - 0.25) < 0.02);
+ assert.ok(scene.restFrames[scene.bodyIndex('ball')] > 0);
+ assert.ok(scene.contactEvents.some(event => event.kind === 'contact' && event.started));
+ scene.dispose();
+});
+
+test('a convex hull body rests on a trimesh floor', async () => {
+ const definition = trimeshFloor();
+ const cube = [];
+ for (const x of [-0.5, 0.5]) for (const y of [-0.5, 0.5]) for (const z of [-0.5, 0.5]) cube.push(x, y, z);
+ definition.bodies.push({ name: 'crate', translation: [0, 2, 0] });
+ definition.colliders.push({ name: 'crate', body: 'crate', shape: 'convexHull', points: cube, density: 1 });
+ const scene = await createPhysicsScene(definition, { frameCount: 181 });
+ assert.ok(Math.abs(bodyHeight(scene, 'crate', scene.duration) - 0.5) < 0.03);
+ scene.dispose();
+});
+
+test('trimesh and hull counts are rejected before anything is allocated', () => {
+ const definition = trimeshFloor();
+ assert.throws(() => planPhysicsScene(definition, { maxColliderTriangles: 1 }), /maxColliderTriangles/);
+ const dynamicTrimesh = trimeshFloor();
+ dynamicTrimesh.bodies[0].type = 'dynamic';
+ assert.throws(() => planPhysicsScene(dynamicTrimesh), /fixed or kinematic/);
+ const outOfRange = trimeshFloor();
+ outOfRange.colliders[0].indices = [0, 1, 9];
+ assert.throws(() => planPhysicsScene(outOfRange), /indices/);
+ const hugeHull = trimeshFloor();
+ hugeHull.bodies.push({ name: 'hull' });
+ hugeHull.colliders.push({ name: 'hull', body: 'hull', shape: 'convexHull', points: new Array(3 * 5000).fill(1), mass: 1 });
+ assert.throws(() => planPhysicsScene(hugeHull, { maxHullPoints: 2048 }), /points/);
+ const flatHull = trimeshFloor();
+ flatHull.bodies.push({ name: 'hull' });
+ flatHull.colliders.push({ name: 'hull', body: 'hull', shape: 'convexHull', points: [0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0], mass: 1 });
+ assert.throws(() => planPhysicsScene(flatHull));
+});
+
+test('a sensor reports enter and leave without pushing the body', async () => {
+ const definition = trimeshFloor();
+ definition.bodies.push({ name: 'zone', type: 'fixed', translation: [0, 1, 0] });
+ definition.colliders.push({ name: 'zone', body: 'zone', shape: 'cuboid', halfExtents: [1, 0.25, 1], sensor: true });
+ dropBall(definition, 'ball', 3);
+ const scene = await createPhysicsScene(definition, { frameCount: 181 });
+ const sensorEvents = scene.contactEvents.filter(event => event.kind === 'sensor');
+ assert.deepEqual(sensorEvents.map(event => event.started), [true, false]);
+ assert.ok(sensorEvents[0].frame < sensorEvents[1].frame);
+ assert.ok(Math.abs(bodyHeight(scene, 'ball', scene.duration) - 0.25) < 0.02, 'the ball falls through the sensor');
+ scene.dispose();
+});
+
+test('collision masks let a ball pass through a floor it does not collide with', async () => {
+ const definition = trimeshFloor();
+ definition.colliders[0].groups = 0b01;
+ definition.colliders[0].mask = 0b01;
+ dropBall(definition, 'ghost', 2, { groups: 0b10, mask: 0b10 });
+ dropBall(definition, 'solid', 2, { groups: 0b01, mask: 0b01 });
+ definition.bodies.find(body => body.name === 'solid').translation = [1, 2, 0];
+ const scene = await createPhysicsScene(definition, { frameCount: 181 });
+ assert.ok(bodyHeight(scene, 'ghost', scene.duration) < -5, 'the ghost ball falls through');
+ assert.ok(Math.abs(bodyHeight(scene, 'solid', scene.duration) - 0.25) < 0.02);
+ scene.dispose();
+});
+
+test('a seek back reproduces the same poses', async () => {
+ const definition = trimeshFloor();
+ dropBall(definition, 'ball', 2, { restitution: 0.5 });
+ const scene = await createPhysicsScene(definition, { frameCount: 181 });
+ const first = Float32Array.from(scene.sample(1.3));
+ scene.sample(0.2);
+ scene.sample(scene.duration);
+ assert.deepEqual(Float32Array.from(scene.sample(1.3)), first);
+ scene.dispose();
+});
diff --git a/tests/physics.test.js b/tests/physics.test.js
index 5b3a6f78..aa7e2758 100644
--- a/tests/physics.test.js
+++ b/tests/physics.test.js
@@ -218,7 +218,9 @@ test('malformed bodies, colliders, constraints, and events fail at the boundary'
definition => definition.colliders[1].halfExtents = [0, 1, 1],
definition => definition.colliders[1].body = 'missing',
definition => definition.colliders[1].shape = 'mesh',
- definition => definition.colliders[1].sensor = true,
+ definition => definition.colliders[1].sensor = 'yes',
+ definition => definition.colliders[1].groups = 70000,
+ definition => definition.colliders[1].points = [0, 0, 0],
definition => definition.colliders = [definition.colliders[0]],
definition => definition.joints = [{ name: 'j', type: 'spherical', bodyA: 'box', bodyB: 'box' }],
definition => definition.joints = [{ name: 'j', type: 'revolute', bodyA: 'box', bodyB: 'floor', axis: [0, 0, 0] }],