3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Name the field in physics errors and fix physics docs (#2116)
Nguyen Xuan An91dc26ce4560
diff --git a/changes/2116.md b/changes/2116.mdnew file mode 100644index 00000000..5ccdec61--- /dev/null+++ b/changes/2116.md@@ -0,0 +1 @@+- Physics joint, cubic keyframe and particle vertex-limit errors name the field and what to pass, `scene_capabilities` motion names the driver expression type instead of `__schema0`, and the physics guide's cloth, spray and box-vertex lines match the code (#2115, #2116, #2117)diff --git a/changes/2116.size.md b/changes/2116.size.mdnew file mode 100644index 00000000..b31c4f87--- /dev/null+++ b/changes/2116.size.md@@ -0,0 +1,2 @@+- scene:agent-scene+lazy: about 460 bytes for field paths, values and fixes in joint, cubic keyframe and particle budget errors; an agent can then tell which entry failed and what to pass.+- goal:agent-scene: 34 bytes gzip for the same error messages; the scene is far over its goal already and the bytes buy field paths agents act on.diff --git a/docs/physics.md b/docs/physics.mdindex edc1368e..226db5e8 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -438,12 +438,21 @@ The boat code is part of the buoyancy chunk, so a scene without floating bodiesAn `ocean` edit with `spray: true` writes the vertex group `spray` and the vector `spray` (the velocity of the surface, m/s). A particle system takes its droplets from the crests that are rising and sends them off with that velocity:```jsonc-{ "geometries": [{ "id": "sea", "type": "mesh", "base": { "type": "box", "bevel": 0 },- "edits": [{ "op": "subdivide", "levels": 5 }, { "op": "ocean", "windSpeed": 12, "choppiness": 2, "spray": true }] }],- "particles": { "systems": [{ "node": "droplet", "count": 400, "speed": [0, 1], "lifetime": [0.6, 1.4],- "emitter": { "shape": "mesh", "mesh": "surface", "from": "vertices", "group": "spray", "groupThreshold": 0.3, "scale": "shrink", "velocityFrom": "spray", "velocityScale": 2 } }] } }+{ "format": "crucible.scene", "schemaVersion": 1,+ "materials": [{ "id": "water", "color": [0.1, 0.3, 0.5] }, { "id": "foam", "color": [0.9, 0.95, 1] }],+ "geometries": [+ { "id": "sea", "type": "mesh", "base": { "type": "box", "bevel": 0 },+ "edits": [{ "op": "subdivide", "levels": 4 }, { "op": "ocean", "windSpeed": 12, "choppiness": 2, "size": 2, "resolution": 4, "time": 1.5, "seed": 3, "spray": true }] },+ { "id": "speck", "type": "box", "bevel": 0 }],+ "nodes": [+ { "id": "surface", "geometry": "sea", "material": "water" },+ { "id": "droplet", "geometry": "speck", "material": "foam" }],+ "particles": { "systems": [{ "node": "droplet", "count": 400, "speed": [0, 1], "lifetime": [0.6, 1.4], "size": 0.05, "scale": "shrink",+ "emitter": { "shape": "mesh", "mesh": "surface", "from": "vertices", "group": "spray", "groupThreshold": 0.3, "velocityFrom": "spray", "velocityScale": 2 } }] } }```+`mesh` names the node that carries the sea (`surface`), not its geometry. The droplets read the mesh after its `edits`, so the `ocean` op with `spray` sits in `edits`. Floating bodies are different: `physics.ocean.geometry` needs the `ocean` op in the geometry `stack`, so a sea that carries boats has it there.+`velocityFrom` (the name of a vector on the emitter mesh; `from` "surface" or "vertices") adds that velocity, times `velocityScale` (1, -1000 to 1000) and in world space, to every particle. A name the mesh lacks is an error that lists the vectors it has. `groupThreshold` (0 to 1, default 0, needs `group`) keeps the emitter off weakly painted water: only points where the group weighs at least that much emit, so spray comes from the crests and not from the whole foamy triangle around them. The foam must fold for there to be spray, so a sea with `choppiness` 0 sprays nowhere. The emitter reads the sea at the edit's `time`: droplets do not follow an `oceanTime` track, and there is no bow-spray emitter on a `boat` yet. The same seed gives the same droplets.## Fracture and breakable glue@@ -536,7 +545,7 @@ A recipe `cloth` section records deformable sheets with a position-based solver- `{ "attach": "leftHand", "shape": "ball", "radius": 0.08, "offset": [0, 0, 0] }` is a ball on a node. `{ "attach": "upperArm", "shape": "capsule", "to": "lowerArm", "radius": 0.05 }` runs a capsule from one node (plus `offset`) to another (plus `toOffset`). Radius 0.001 to 10 m.- `{ "armature": "rig", "radiusFraction": 0.2, "exclude": ["head"] }` adds one capsule per bone, head to tail, the radius a fraction (0.02 to 0.5, default 0.2) of the bone length as the ragdoll fits it. A bone with no length is skipped.- A sheet's `stiffnessGroup: "sleeve"` names a vertex group whose weights scale stretch and bend stiffness per vertex; a constraint is as stiff as the softer of its two ends, and a weight under 0.05 counts as 0.05 so the vertex does not drift off.- - `selfCollision: true` makes the sheet's own particles push each other apart, so cloth folded over itself stays in layers instead of passing through. The contact radius is 0.9 of half the shortest edge, or the sheet's `thickness` when the sheet sets one (never above half the shortest edge), so a thin cloth on a coarse grid stacks its layers 2 x thickness apart instead of about 4 cm. This changes existing scenes that set both `selfCollision: true` and `thickness`: they used to ignore the thickness and now stack layers 2 x thickness apart, so their baked frames differ; pass `selfCollision: { radius }` to keep a fixed radius. A scene that sets no thickness keeps the old radius (`tests/cloth-self-collision-thickness.test.js`). a spatial hash keeps it near linear (the candidate pairs are listed once per substep, so the iterations only test distances; about 3 times faster than testing every neighbour cell each iteration, with the same frames), two particles joined by an edge are skipped, and a sheet over 5000 particles fails with the count and the fix. It is per particle, so a layer can still slip between particles on a mesh much coarser than the fold. The fold test (`tests/soft-body.test.js`) keeps every unjoined pair at least 0.8 of the contact distance apart; without it the same fold interpenetrates.+ - `selfCollision: true` makes the sheet's own particles push each other apart, so cloth folded over itself stays in layers instead of passing through. The contact radius is 0.9 of half the shortest edge, or the sheet's `thickness` when the sheet sets one (never above half the shortest edge), so a thin cloth on a coarse grid stacks its layers 2 x thickness apart instead of about 4 cm. This changes existing scenes that set both `selfCollision: true` and `thickness`: they used to ignore the thickness and now stack layers 2 x thickness apart, so their baked frames differ. The recipe takes only `true` or `false` there (an object fails with `expected boolean`); a fixed radius in metres is `selfCollision: { radius }` in the library call `createCloth` (`src/cloth.js`), not in a recipe. A scene that sets no thickness keeps the old radius (`tests/cloth-self-collision-thickness.test.js`). a spatial hash keeps it near linear (the candidate pairs are listed once per substep, so the iterations only test distances; about 3 times faster than testing every neighbour cell each iteration, with the same frames), two particles joined by an edge are skipped, and a sheet over 5000 particles fails with the count and the fix. It is per particle, so a layer can still slip between particles on a mesh much coarser than the fold. The fold test (`tests/soft-body.test.js`) keeps every unjoined pair at least 0.8 of the contact distance apart; without it the same fold interpenetrates.- `softBody: { "shape": 0.2, "pressure": 1 }` turns the sheet node into a jelly: `shape` (0 to 1) pulls every particle toward the best rigid fit of the rest shape (shape matching, rotation extracted with a warm-started iteration), and `pressure` (0 to 3) is a volume constraint that holds that multiple of the rest volume. Use 1 for a jelly that keeps its volume and squashes on impact; below 1 the body deflates to that volume before it lands (0.85 is a body 15 percent smaller from the first frame), above 1 it inflates. Pressure needs a closed mesh (every edge in two triangles) and fails naming the open edge otherwise; set `pressure: 0` to keep only shape matching. A box or sphere geometry is closed. It rests on the colliders like cloth and bakes to the same frames every run.- `softBody.bounce` (0 to 1, default 0) sets how much of its landing speed the jelly keeps when it turns around: the body remembers the speed its centre arrived with, and when the centre stops moving into the collider it adds `bounce` times that speed to every free particle along the contact normal. It never slows a body that already leaves faster, and approach speeds under 0.5 m/s are ignored so a resting jelly does not buzz. Leaving it out bakes the same frames as before. How soft the jelly is needs no new field: lower `softBody.shape` for a looser body and lower the sheet's `stiffness` for a body that squashes further (the table below). `damping` is air drag on every particle, so a high `damping` also takes height off the bounce (with `damping: 0` and `bounce: 1` the cube returns to 1.85 m of its 1.95 m drop).- A sheet on a mesh geometry can hold chosen vertices with `pinGroup: "hem"`, the name of a vertex group made by a `vertex_group` mesh edit; vertices of weight 0.5 or more are pinned, on their own or together with `pin`. An unknown name fails and lists the groups the mesh has.@@ -748,7 +757,7 @@ A recipe `particles` section holds up to 4 systems (`src/particles.js`, `src/hai"emitter": { "shape": "disc", "position": [-0.8, 0, 0], "radius": 0.15 } }] } }```-- An emitter system draws its root node's own geometry once per particle, so keep the shape low-poly. The node's transform does not move or scale particles. `count` is at most 2000 a system and 4000 in total, and at most 100000 vertices are drawn in total (a box is 24 per particle, so a default sphere is too heavy).+- An emitter system draws its root node's own geometry once per particle, so keep the shape low-poly. The node's transform does not move or scale particles. `count` is at most 2000 a system and 4000 in total, and at most 100000 vertices are drawn in total (a box with `bevel: 0` is 24 per particle, but a default `box` has a bevel and is 1176, so give particle shapes `bevel: 0`; a default sphere is too heavy; the error names the vertices per particle of the node).- Fields and defaults are in `scene_capabilities` under `particles`: `seed`, `count`, `rate` (omit for one burst at time 0), `start` (seconds before the first birth, 0; `delay` is the same field) and `stop` (seconds, after `start`: nothing is born at or after it, so a system with a `rate` emits only inside the window; particles already born finish their life), `lifetime`, `speed` and `size` (a number or `[min, max]`), `direction`, `spread` (cone half angle, degrees), `emitter` (`point`, `box`, `sphere`, `disc` or `mesh`), `instances` and `orient` (see the next two bullets), `scale` (`constant`, `shrink`, `grow`), `drag` and `floor`. `gravity` and a steady `wind` sit on the section; wind pulls the velocity only where `drag` is above zero.- A particle is a closed-form function of its own seeded launch values and the time (drag, wind and gravity have an exact solution), checked against a 1e-5 s integration in `tests/particles.test.js`. There is no stepping, so the state at time t never depends on earlier seeks: the same time gives the same particles, a seek backwards repeats them, the same seed gives identical bytes, and raising `count` keeps the particles already there. The landing time on a `floor` is found once per particle from its launch values.- A hair system (`type: "hair"`) grows `count` strands from area-weighted seeded points of a `surface` node into its own `node` (the surface is only read, so several systems can share one). A strand is a triangular tube of 1 to 8 segments tapering to 15 percent, leaning off the surface normal by `lean`, bending with `droop`, and swaying by `sway` metres along the horizontal wind at `swayRate` hertz. Without `sway` the mesh is built once.diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex c92fb7d4..45fbc74b 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -575,7 +575,7 @@ const expression = z.lazy(() => z.union([z.literal('time'),z.strictObject({ node: identifier, property: z.enum(['translation', 'rotation', 'scale']), component: axisName, space: z.enum(['local', 'world']).optional() }),z.record(z.string().max(24), z.union([z.array(expression).min(1).max(8), expression])),-])).describe('Number, "time", {"node","property","component","space"} read, or an operator like {"mul":[2,"time"]}, {"neg":x} too. Operators as in field expressions (scene_capabilities), no vectors, attributes or noise. At most 64 parts, 8 deep.');+])).describe('Number, "time", {"node","property","component","space"} read, or an operator like {"mul":[2,"time"]}, {"neg":x} too. Operators as in field expressions (scene_capabilities), no vectors, attributes or noise. At most 64 parts, 8 deep.').meta({ id: 'Expression' });const influence = z.union([unit, expression]).optional().describe('0 to 1 blend of the constraint, or an expression.');const constraint = z.discriminatedUnion('type', [z.strictObject({ type: z.literal('copy_location'), node: identifier, target: identifier, axes: axisNames.optional(), invert: axisNames.optional(), offset: z.boolean().optional(), space: constraintSpace, influence }),diff --git a/src/agent-cloth.js b/src/agent-cloth.jsindex bd6ce7b1..92d28d67 100644--- a/src/agent-cloth.js+++ b/src/agent-cloth.js@@ -76,7 +76,7 @@ function normalizeSheet(input, context, path) {}if (input.selfCollision !== undefined) {if (typeof input.selfCollision !== 'boolean') {- throw invalidField(`${path}.selfCollision`, input.selfCollision, 'true or false; the radius follows the mesh edge length');+ throw invalidField(`${path}.selfCollision`, input.selfCollision, 'true or false, not an object; the radius follows the mesh edge length, or the sheet thickness when it is set');}sheet.selfCollision = input.selfCollision;}diff --git a/src/agent-motion.js b/src/agent-motion.jsindex c3988406..732e206c 100644--- a/src/agent-motion.js+++ b/src/agent-motion.js@@ -122,6 +122,16 @@ function copiedKeyframe(keyframe, interpolation) {return result;}+// A CUBICSPLINE keyframe carries both tangents, each as wide as its value.+function tangentFrom(keyframe, field, size) {+ if (keyframe[field] === undefined) {+ const example = size === 1 ? '0' : `[${Array(size).fill(0).join(', ')}]`;+ const shape = size === 1 ? 'a number' : `an array of ${size} numbers`;+ throw invalidField(field, undefined, `${shape}, such as ${example}; a CUBICSPLINE keyframe takes inTangent and outTangent (or use interpolation "SMOOTH")`, TypeError);+ }+ return valueFrom(keyframe[field], size, field);+}+function normalizedKeyframe(keyframe, track, duration, interpolation) {knownKeys(keyframe, ['time', 'value', 'inTangent', 'outTangent', 'easing'], 'motion keyframe');const size = PROPERTIES[track.kind][track.property];@@ -136,8 +146,8 @@ function normalizedKeyframe(keyframe, track, duration, interpolation) {}Object.assign(result, easing);if (interpolation === 'CUBICSPLINE') {- result.inTangent = valueFrom(keyframe.inTangent, size, 'Incoming tangent');- result.outTangent = valueFrom(keyframe.outTangent, size, 'Outgoing tangent');+ result.inTangent = tangentFrom(keyframe, 'inTangent', size);+ result.outTangent = tangentFrom(keyframe, 'outTangent', size);} else if (Object.hasOwn(keyframe, 'inTangent') || Object.hasOwn(keyframe, 'outTangent')) {throw invalidField(Object.hasOwn(keyframe, 'inTangent') ? 'inTangent' : 'outTangent', keyframe.inTangent ?? keyframe.outTangent, `a field left out unless the track interpolation is CUBICSPLINE, such as "interpolation": "CUBICSPLINE" (this track is ${interpolation})`, TypeError);}diff --git a/src/agent-particles.js b/src/agent-particles.jsindex 94f50abc..e9ce9eb0 100644--- a/src/agent-particles.js+++ b/src/agent-particles.js@@ -437,9 +437,18 @@ function surfaceInWorld(geometry, matrix) {return { positions, normals };}-function checkVertexBudget(vertices, totalVertices, nodeId) {+// What to change when the drawn vertices pass the limit: a default box has a bevel, so each particle is 1176 vertices, not 24.+function bevelledBoxAdvice(nodeId, recipe) {+ const node = recipe.nodes.find(candidate => candidate.id === nodeId);+ const definition = (recipe.geometries ?? []).find(candidate => candidate.id === node?.geometry);+ const base = definition?.type === 'mesh' ? definition.base : definition;+ return base?.type === 'box' && base.bevel !== 0 ? '; the shape is a box with a bevel, so pass "bevel": 0 on it to make it 24 vertices' : '';+}++function checkVertexBudget(verticesPerItem, count, totalVertices, nodeId, recipe) {+ const vertices = verticesPerItem * count;if (vertices > PARTICLE_LIMITS.maxVertices || totalVertices > PARTICLE_LIMITS.maxVertices) {- throw invalidField('particles.systems', `${totalVertices} vertices on node ${nodeId}`, `shape vertices times count of at most ${PARTICLE_LIMITS.maxVertices}; use a shape with fewer segments or a lower count`);+ throw invalidField('particles.systems', `${totalVertices} vertices`, `at most ${PARTICLE_LIMITS.maxVertices} vertices drawn in total; node ${nodeId} draws ${verticesPerItem} vertices per particle times count ${count}, so use a shape with fewer vertices or a lower count${bevelledBoxAdvice(nodeId, recipe)}`);}}@@ -606,7 +615,7 @@ export function bakeAgentParticles(particles, recipe, geometries) {const node = nodes.get(system.node);const verticesPerItem = system.type === 'sparks' ? SPARK_VERTICES : system.type === 'hair' ? (system.segments + 1) * HAIR_LIMITS.ringSides : Math.max(...templateNodeIds(system).map(nodeId => geometries.get(nodes.get(nodeId).geometry).positions.length / 3));totalVertices += verticesPerItem * system.count;- checkVertexBudget(verticesPerItem * system.count, totalVertices, system.node);+ checkVertexBudget(verticesPerItem, system.count, totalVertices, system.node, recipe);if (system.type === 'hair') {const surfaceNode = nodes.get(system.surface);return prepareHair(system, node, surfaceNode, geometries.get(surfaceNode.geometry), forces);diff --git a/src/agent-physics.js b/src/agent-physics.jsindex cf7af862..43182312 100644--- a/src/agent-physics.js+++ b/src/agent-physics.js@@ -58,6 +58,9 @@ function finiteNumber(value, path, minimum = -Infinity, maximum = Infinity) {return value;}+// How far a joint axis may be from length 1; the physics engine allows the same.+const UNIT_AXIS_TOLERANCE = 1e-4;+function numberList(value, size, path) {if (!Array.isArray(value) || value.length !== size) {throw invalidField(path, value, `an array of ${size} numbers, such as [${Array(size).fill(0).join(', ')}]`, TypeError);@@ -201,6 +204,10 @@ function normalizeJoint(input, bodyNodeIds, jointNames, path) {throw invalidField(`${path}.${field}`, input[field], `the node of a physics body, one of ${[...bodyNodeIds].slice(0, 5).join(', ') || 'none yet'}`);}}+ if (input.bodyA === input.bodyB) {+ const otherBody = [...bodyNodeIds].find(id => id !== input.bodyA) ?? 'other-body';+ throw invalidField(`${path}.bodyB`, input.bodyB, `a body other than bodyA (${JSON.stringify(input.bodyA)}), such as ${JSON.stringify(otherBody)}`, TypeError);+ }const joint = { type: input.type, bodyA: input.bodyA, bodyB: input.bodyB };if (input.name !== undefined) {const name = nodeIdentifier(input.name, `${path}.name`);@@ -213,6 +220,9 @@ function normalizeJoint(input, bodyNodeIds, jointNames, path) {for (const field of ['anchorA', 'anchorB', 'axis']) {if (input[field] !== undefined) joint[field] = numberList(input[field], 3, `${path}.${field}`);}+ if (joint.axis && Math.abs(Math.hypot(...joint.axis) - 1) > UNIT_AXIS_TOLERANCE) {+ throw invalidField(`${path}.axis`, joint.axis, 'a unit vector of length 1, such as [0, 1, 0] or [1, 0, 0]');+ }if (input.contactsEnabled !== undefined) {if (typeof input.contactsEnabled !== 'boolean') {throw invalidField(`${path}.contactsEnabled`, input.contactsEnabled, 'true or false', TypeError);@@ -225,7 +235,12 @@ function normalizeJoint(input, bodyNodeIds, jointNames, path) {}joint.breakImpulse = finiteNumber(input.breakImpulse, `${path}.breakImpulse`, 1e-6, 1e9);}- if (input.limits !== undefined) joint.limits = numberList(input.limits, 2, `${path}.limits`);+ if (input.limits !== undefined) {+ joint.limits = numberList(input.limits, 2, `${path}.limits`);+ if (Math.fround(joint.limits[0]) >= Math.fround(joint.limits[1])) {+ throw invalidField(`${path}.limits`, joint.limits, 'two numbers, the lower limit first and a gap a 32-bit float can store, such as [-1, 1]');+ }+ }if (input.motor !== undefined) joint.motor = normalizeMotor(input.motor, `${path}.motor`);if (input.type === 'spring') {joint.restLength = finiteNumber(input.restLength ?? 0, `${path}.restLength`, 0, 1e6);diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 4c9e755d..ec2757c0 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -355,7 +355,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({cloth: Object.freeze({sheetGeometry: 'grid { segments 1-64 }: unit sheet in XY facing +Z, sized by node scale; any triangle mesh works',defaults: Object.freeze({ stiffness: 0.9, bend: 0.1, density: 0.2, damping: 0.3, friction: 0.3, thickness: 0.01, colliderShape: 'box' }),- notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Colliders { node, shape ball|box } fit geometry bounds; like sheets they are root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. Sheet pinGroup: a vertex group whose vertices (weight 0.5 or more) are held. Sheet pinTo { node, weight } rides pinned edges on a node. Sheet stiffnessGroup: vertex group whose weights scale stiffness (floor 0.05). Sheet softBody { shape 0-1 (0.2), pressure 0-3 (1), bounce 0-1 (0) }: shape matching plus a volume term; pressure needs a closed mesh, a node with an open mesh fails and says to set pressure 0. bounce is the share of its landing speed the body keeps when it turns around; lower shape or sheet stiffness makes a softer, deeper dent. Sheet bendModel distance (default) or dihedral: dihedral holds the angle between neighbouring triangles, so a fine sheet folds in many soft ripples instead of one crease; set bend about 0.15 with it. Sheet bendYield (radians, dihedral only, off by default) lets a fold keep its crease: past that bend angle the rest angle follows the cloth by bendSet (0-1, 0.1) of the excess each substep, so a crumpled sheet stays crumpled. Sheet pinTo.releaseAt (seconds, optional) lets the pinned edges go at that time and fall with the rest. Sheet staticFriction (0-1, 0) holds cloth still on a collider when its sideways travel is under that multiple of the contact depth, so it rests on a slope below its friction angle. Sheet selfCollision true: particles of the sheet push apart (radius 0.9 of half the shortest edge, or the sheet thickness when set, up to 5000 particles); cloth does not collide with other sheets.',+ notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Colliders { node, shape ball|box } fit geometry bounds; like sheets they are root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. Sheet pinGroup: a vertex group whose vertices (weight 0.5 or more) are held. Sheet pinTo { node, weight } rides pinned edges on a node. Sheet stiffnessGroup: vertex group whose weights scale stiffness (floor 0.05). Sheet softBody { shape 0-1 (0.2), pressure 0-3 (1), bounce 0-1 (0) }: shape matching plus a volume term; pressure needs a closed mesh, a node with an open mesh fails and says to set pressure 0. bounce is the share of its landing speed the body keeps when it turns around; lower shape or sheet stiffness makes a softer, deeper dent. Sheet bendModel distance (default) or dihedral: dihedral holds the angle between neighbouring triangles, so a fine sheet folds in many soft ripples instead of one crease; set bend about 0.15 with it. Sheet bendYield (radians, dihedral only, off by default) lets a fold keep its crease: past that bend angle the rest angle follows the cloth by bendSet (0-1, 0.1) of the excess each substep, so a crumpled sheet stays crumpled. Sheet pinTo.releaseAt (seconds, optional) lets the pinned edges go at that time and fall with the rest. Sheet staticFriction (0-1, 0) holds cloth still on a collider when its sideways travel is under that multiple of the contact depth, so it rests on a slope below its friction angle. Sheet selfCollision true or false (a recipe takes no { radius }; that is the createCloth library option): particles of the sheet push apart (radius 0.9 of half the shortest edge, or the sheet thickness when set, up to 5000 particles); cloth does not collide with other sheets.',limits: Object.freeze({ maxSheets: 8, maxColliders: 16, maxMovingColliders: 64, maxDuration: 10, maxParticles: 5000, framesPerSecond: 60, substeps: 4, iterations: 8 }),}),// Recipe particles: closed-form from seeded launch values, so any time is computed directly and a seek never replays.diff --git a/tests/mcp-agent-errors.test.js b/tests/mcp-agent-errors.test.jsindex 7c2d2f1f..229f01e6 100644--- a/tests/mcp-agent-errors.test.js+++ b/tests/mcp-agent-errors.test.js@@ -153,3 +153,18 @@ test('an unknown topic suggests the nearest topic names', async context => {test('the material pattern limit is listed in the capabilities flags', () => {assert.equal(AGENT_SCENE_CAPABILITIES.maxMaterialPatterns, 16);});++test('no scene_capabilities topic prints an internal __schema placeholder, and motion expands the driver expression', async context => {+ const client = await connect(context);+ const index = (await client.callTool({ name: 'scene_capabilities', arguments: {} })).structuredContent;+ const topics = [...index.topics.scene, ...index.topics.runtime, ...index.topics.schemas];+ for (const topic of topics) {+ const answer = await client.callTool({ name: 'scene_capabilities', arguments: { topic } });+ assert.doesNotMatch(JSON.stringify(answer.structuredContent ?? answer.content), /__schema/, `topic ${topic} leaks a __schema name`);+ }+ const motion = JSON.stringify((await client.callTool({ name: 'scene_capabilities', arguments: { topic: 'motion' } })).structuredContent);+ assert.match(motion, /"expression":"Expression"/);+ assert.match(motion, /"influence\??":"number\[0\.\.1\] \| Expression/);+ assert.ok(motion.includes('"Expression":{"oneOf":["number[-1000000..1000000]","\\"time\\"",'), 'the Expression definition lists its branches');+ assert.ok(motion.includes('an operator like {\\"mul\\":[2,\\"time\\"]}'), 'the Expression definition shows one worked operator');+});diff --git a/tests/particles.test.js b/tests/particles.test.jsindex 731d9e4b..b52b652d 100644--- a/tests/particles.test.js+++ b/tests/particles.test.js@@ -209,7 +209,7 @@ test('total particles and total vertices are bounded across systems', () => {const heavy = sparkRecipe({ systems: [{ node: 'sparks', count: 10 }] });heavy.nodes[0].geometry = 'ball';heavy.particles.systems[0].count = 40;- assert.throws(() => createAgentScene(heavy), /particles\.systems: got "\d+ vertices on node sparks"; expected shape vertices times count of at most 100000/);+ assert.throws(() => createAgentScene(heavy), /particles\.systems: got "\d+ vertices"; expected at most 100000 vertices drawn in total; node sparks draws \d+ vertices per particle times count/);});test('a particle node cannot carry motion or physics, or be a cloth sheet', () => {@@ -359,7 +359,7 @@ test('hair limits the vertices it draws, and an empty surface is refused', () =>const crowded = hairRecipe({ count: 2000, segments: 8 });crowded.particles.systems.push({ type: 'hair', node: 'extra', surface: 'head', count: 2000, segments: 8 });crowded.nodes.push({ id: 'extra', geometry: 'strands', material: 'fur' });- assert.throws(() => createAgentScene(crowded), /particles\.systems: got "\d+ vertices on node extra"; expected shape vertices times count of at most 100000/);+ assert.throws(() => createAgentScene(crowded), /particles\.systems: got "\d+ vertices"; expected at most 100000 vertices drawn in total; node extra draws \d+ vertices per particle times count/);const flat = hairRecipe({});flat.nodes[0].scale = [0, 0, 0];assert.throws(() => createAgentScene(flat), /no triangle with area|scale/);diff --git a/tests/physics-docs-spray-example.test.js b/tests/physics-docs-spray-example.test.jsnew file mode 100644index 00000000..842d64b0--- /dev/null+++ b/tests/physics-docs-spray-example.test.js@@ -0,0 +1,25 @@+import './support/load-agent-scene-modules.mjs';+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { createAgentScene, loadPhysicsEngine } from '../src/agent-scene.js';++// Issue 2116: the "Spray from the sea" example of docs/physics.md ran into a missing node and a mesh name that matched nothing.++await loadPhysicsEngine({ buoyancy: true });++async function sprayExampleRecipe() {+ const guide = await readFile(new URL('../docs/physics.md', import.meta.url), 'utf8');+ const section = guide.slice(guide.indexOf('### Spray from the sea'));+ const block = /```jsonc?\n([\s\S]*?)```/.exec(section);+ assert.ok(block, 'the spray section has a json example');+ return JSON.parse(block[1].replace(/^\s*\/\/.*$/gm, ''));+}++test('the spray example of the guide builds as written and drops droplets from the sea', async () => {+ const recipe = await sprayExampleRecipe();+ const scene = createAgentScene(recipe);+ scene.sampleMotion(0.7);+ const droplets = scene.parts.find(part => part.name === 'droplet').geometry.positions;+ assert.equal(droplets.length / 3, 400 * 24, 'one 24 vertex box per droplet');+});diff --git a/tests/physics-field-errors.test.js b/tests/physics-field-errors.test.jsnew file mode 100644index 00000000..f5b71c07--- /dev/null+++ b/tests/physics-field-errors.test.js@@ -0,0 +1,68 @@+import './support/load-agent-scene-modules.mjs';+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAgentScene, loadPhysicsEngine } from '../src/agent-scene.js';++// Issue 2116: joint, cubic keyframe and particle budget errors name the field, the value received and what to pass.++await loadPhysicsEngine();++function ball(id, x) {+ return { id, geometry: 'ball', material: 'paint', translation: [x, 1, 0] };+}++function jointRecipe(joint) {+ return {+ format: 'crucible.scene', schemaVersion: 1,+ geometries: [{ id: 'ball', type: 'sphere' }],+ materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],+ nodes: [ball('a', 0), ball('b', 2)],+ physics: { duration: 1, bodies: [{ node: 'a' }, { node: 'b' }], joints: [joint] },+ };+}++test('a joint between a body and itself names bodyB and a body to pass instead', () => {+ assert.throws(() => createAgentScene(jointRecipe({ type: 'fixed', bodyA: 'a', bodyB: 'a' })),+ /physics\.joints\[0\]\.bodyB: got "a"; expected a body other than bodyA \("a"\), such as "b"\./);+});++test('a joint axis that is not a unit vector names the axis, the value and an example', () => {+ assert.throws(() => createAgentScene(jointRecipe({ type: 'revolute', bodyA: 'a', bodyB: 'b', axis: [0, 0, 0] })),+ /physics\.joints\[0\]\.axis: got \[0,0,0\]; expected a unit vector of length 1, such as \[0, 1, 0\] or \[1, 0, 0\]\./);+});++test('joint limits that do not increase name the field and give an example', () => {+ assert.throws(() => createAgentScene(jointRecipe({ type: 'revolute', bodyA: 'a', bodyB: 'b', axis: [0, 1, 0], limits: [2, 1] })),+ /physics\.joints\[0\]\.limits: got \[2,1\]; expected two numbers, the lower limit first and a gap a 32-bit float can store, such as \[-1, 1\]\./);+});++function cubicRecipe(keyframe) {+ return {+ format: 'crucible.scene', schemaVersion: 1,+ geometries: [{ id: 'ball', type: 'sphere' }],+ materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],+ nodes: [ball('a', 0)],+ motion: { duration: 1, tracks: [{ kind: 'node', id: 'a', property: 'translation', interpolation: 'CUBICSPLINE', keyframes: [keyframe] }] },+ };+}++test('a cubic keyframe without tangents names the field and says to give both', () => {+ assert.throws(() => createAgentScene(cubicRecipe({ time: 0, value: [0, 0, 0] })),+ /motion\.tracks\[0\]\.keyframes\[0\]\.inTangent: got undefined; expected an array of 3 numbers, such as \[0, 0, 0\]; a CUBICSPLINE keyframe takes inTangent and outTangent/);+ assert.throws(() => createAgentScene(cubicRecipe({ time: 0, value: [0, 0, 0], inTangent: [0, 0, 0] })),+ /motion\.tracks\[0\]\.keyframes\[0\]\.outTangent: got undefined/);+});++test('a particle budget error names the vertices per particle and suggests bevel 0 for a default box', () => {+ const recipe = geometry => ({+ format: 'crucible.scene', schemaVersion: 1,+ geometries: [geometry],+ materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],+ nodes: [{ id: 'speck', geometry: 'shape', material: 'paint' }],+ particles: { systems: [{ node: 'speck', count: 200, lifetime: 1, speed: 1, emitter: { shape: 'point' } }] },+ });+ assert.throws(() => createAgentScene(recipe({ id: 'shape', type: 'box' })),+ /particles\.systems: got "235200 vertices"; expected at most 100000 vertices drawn in total; node speck draws 1176 vertices per particle times count 200, so use a shape with fewer vertices or a lower count; the shape is a box with a bevel, so pass "bevel": 0 on it to make it 24 vertices\./);+ assert.doesNotThrow(() => createAgentScene(recipe({ id: 'shape', type: 'box', bevel: 0 })));+ assert.throws(() => createAgentScene(recipe({ id: 'shape', type: 'sphere' })), error => !/bevel/.test(error.message) && /draws \d+ vertices per particle times count 200/.test(error.message));+});