3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Build cone and compound bodies in the live game physics (#2123)
Nguyen Xuan Anc5b06efb6e13
diff --git a/changes/2123.md b/changes/2123.mdnew file mode 100644index 00000000..101e4abd--- /dev/null+++ b/changes/2123.md@@ -0,0 +1 @@+- The live game physics now builds `cone` and `compound` bodies (up to 16 sub-colliders), so a recipe that bakes with those shapes plays in a game; only `trimesh` is refused, with a message that lists the live shapes (#2123).diff --git a/changes/2123.size.md b/changes/2123.size.mdnew file mode 100644index 00000000..fb1e4b98--- /dev/null+++ b/changes/2123.size.md@@ -0,0 +1 @@+- entry:physics-jolt: builds cone and compound bodies for the live game physics (134 bytes gzip), so a recipe that bakes with those shapes plays in a game instead of being refused.diff --git a/docs/game.md b/docs/game.mdindex 453e389e..1324867b 100644--- a/docs/game.md+++ b/docs/game.md@@ -85,7 +85,7 @@ The `scene` system sends each frame's poses through `scene.apply`, and sends onl- The player node can be a `kinematic` body (shape `capsule`, `box` or `ball`): the controller drives it, so the player pushes dynamic bodies and is never pushed back.- A rules part named like a dynamic body reports that body's position, so a zone, a tag and `enter` work on crates and balls.-- Give every fixed body `shape: "box"` (or `ball`, `capsule`, `convex`): the default `trimesh` is not built. Joints, ragdolls, trimesh and compound shapes are refused with the field to change, and `physics.duration` is only the length of the recorded film.+- Give every fixed body `shape: "box"` (or `ball`, `capsule`, `convex`): the default `trimesh` is not built. Joints, ragdolls and trimesh are refused with the field to change (`cone` and `compound` bodies play, see [physics](physics.md)), and `physics.duration` is only the length of the recorded film.- The web export copies `jolt-physics.wasm.js` and its `.wasm` file to `engine/physics/` (about 3 MiB) and gives the page their URL, so Jolt fetches the wasm from beside the page. Nothing loads from another origin: a `physicsUrl` on another origin is refused. The `jolt-physics` package must be installed to export.The `puzzle` sample of `scripts/smoke-game-web.mjs` is two plank crates, two marble plates in brick pockets and an iron gate on a stone floor (pattern materials). The player walks into the first crate and pushes it onto its plate, crosses over and pushes the second; when both plates are pressed the gate part is hidden and the game is won. The smoke checks that the page loads only its own files, that the wasm comes from `engine/physics/`, that both crates moved, and that an export without physics carries no `engine/physics/` folder.diff --git a/docs/physics-runtime.md b/docs/physics-runtime.mdindex 181f6cb6..8a2b039d 100644--- a/docs/physics-runtime.md+++ b/docs/physics-runtime.md@@ -90,7 +90,7 @@ import { joltAdapter } from 'crucible/addons/physics-jolt';const physics = await createPhysicsSystem(definition, { adapter: joltAdapter });```-`jolt-physics` (JoltPhysics built to wasm, MIT, install it with `npm install jolt-physics`) is an optional peer dependency of the `physics-jolt` addon; the core and the other addons never import it. The adapter covers bodies, sensors, collision groups and masks, kinematic control, force fields, ray, shape-cast and overlap queries, and contact and sensor events. What it does not cover yet throws an error that names the fix: joints, `cone` and `trimesh` colliders, and more than one collider per body. It also limits a scene to 256 distinct group and mask pairs. Engines differ in friction and restitution combining and in solver details, so a settled pose can differ between engines: a box that falls straight down settles within a few centimetres, but an offset cuboid rested at y 0.5 on one engine and 0.48 on the other, and a cylinder came to rest in different poses (Rapier tips and rolls it). Events are shown to match only for a dynamic box falling through a fixed sensor. For a kinematic body moving through a fixed sensor, Rapier gave no sensor events and Jolt did, so do not rely on kinematic-versus-fixed sensor events being the same on both engines. Jolt reports a contact as ended when a body falls asleep; the adapter hides that, so a sleeping box keeps its contact.+`jolt-physics` (JoltPhysics built to wasm, MIT, install it with `npm install jolt-physics`) is an optional peer dependency of the `physics-jolt` addon; the core and the other addons never import it. The adapter covers bodies, sensors, collision groups and masks, kinematic control, force fields, ray, shape-cast and overlap queries, and contact and sensor events. What it does not cover yet throws an error that names the fix: joints and `trimesh` colliders. A body takes up to 16 colliders (a compound), and `cone` is built as a tapered cylinder; events and queries name the first collider of a compound body. It also limits a scene to 256 distinct group and mask pairs. Engines differ in friction and restitution combining and in solver details, so a settled pose can differ between engines: a box that falls straight down settles within a few centimetres, but an offset cuboid rested at y 0.5 on one engine and 0.48 on the other, and a cylinder came to rest in different poses (Rapier tips and rolls it). Events are shown to match only for a dynamic box falling through a fixed sensor. For a kinematic body moving through a fixed sensor, Rapier gave no sensor events and Jolt did, so do not rely on kinematic-versus-fixed sensor events being the same on both engines. Jolt reports a contact as ended when a body falls asleep; the adapter hides that, so a sleeping box keeps its contact.## Limitsdiff --git a/docs/physics.md b/docs/physics.mdindex edc1368e..ccced515 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -378,6 +378,8 @@ A scene recipe takes a `physics` section, and `set-physics` edits it (`null` cleEach body is a root node with a geometry. Its collider is fitted to that geometry at the node scale: `box`, `ball`, `capsule`, `cylinder` and `cone` from the bounds, `convex` from at most 2048 distinct vertices, `trimesh` from every triangle, or `compound` with a `shapes` list of up to 16 sub-colliders (`box`, `ball`, `capsule`, `cylinder`, `cone` with optional `translation` and `rotation`).Recipe joints also accept `name` (what `jointMotor` events refer to; fracture-node writes `glue-a-b`), `breakImpulse` (fixed joints only), `spring` (`restLength`, `stiffness`, `damping`), `motor` (`{ mode: "position" | "velocity", target, stiffness?, damping, maxForce }`) and `contactsEnabled`. Recipe `physics.events` schedules up to 128 `impulse`, `kinematicPose` and `jointMotor` events by `time` in seconds (or `tick`), and `physics.fields` applies up to 8 force fields (`wind`, `turbulence`, `vortex`, `drag`, `magnet`) to dynamic bodies at every step.Defaults are `box` for dynamic bodies and sensors, `trimesh` for fixed ones.++The live game runtime (`game.physics`, Jolt) takes the same shapes except `trimesh`: `box`, `ball`, `capsule`, `cylinder`, `cone`, `convex` and `compound` (up to 16 sub-colliders). A recipe with a `trimesh` body is refused with a message that lists these shapes and names `box` as the replacement. In a compound, events and ray hits report the first sub-collider.`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: 128 bodies, 512 joints, 10 seconds, 60 steps a second, so at most 601 frames.diff --git a/src/game-needs.js b/src/game-needs.jsindex 645497c9..1475cef0 100644--- a/src/game-needs.js+++ b/src/game-needs.js@@ -2,15 +2,17 @@// and the web export copies that piece only when the same check says so, so a plain game does not carry the physics engine or the// texture swap code.-const UNSUPPORTED_SHAPES = ['trimesh', 'cone', 'compound'];+// The body shapes the game physics builds: every baked shape except trimesh. A compound is up to 16 parts (box, ball, capsule,+// cylinder or cone), as in the baked path.+export const GAME_PHYSICS_BODY_SHAPES = Object.freeze(['box', 'ball', 'capsule', 'cylinder', 'cone', 'convex', 'compound']);/** Why a recipe cannot play physics in a game (the engine is Jolt), or null. */export function gamePhysicsProblem(recipe) {const physics = recipe.physics;if (!physics?.bodies?.length) return 'game.physics is true, but the recipe has no physics section with bodies. Add one with set-physics, or set game.physics to false with set-game.';if (physics.joints?.length || physics.ragdoll) return 'The game physics engine builds no joints or ragdolls yet. Remove physics.joints and physics.ragdoll, or set game.physics to false with set-game.';- const unsupported = physics.bodies.find(body => UNSUPPORTED_SHAPES.includes(body.shape));- if (unsupported) return `Body "${unsupported.node}" has shape ${unsupported.shape}, which the game physics engine does not build. Use box, ball, capsule or convex (give a fixed body shape "box": its default is trimesh).`;+ const unsupported = physics.bodies.find(body => body.shape === 'trimesh');+ if (unsupported) return `Body "${unsupported.node}" has shape ${unsupported.shape}, which the game physics engine does not build. The game physics builds ${GAME_PHYSICS_BODY_SHAPES.join(', ')}. Use "box" for a floor or wall (a fixed body defaults to trimesh) or "convex" for a closed solid.`;return null;}diff --git a/src/physics-jolt.js b/src/physics-jolt.jsindex 351562ea..1428ae79 100644--- a/src/physics-jolt.js+++ b/src/physics-jolt.js@@ -10,7 +10,9 @@ export const JOLT_ADAPTER_LIMITS = Object.freeze({});const MAX_CONVEX_RADIUS = 0.05;-const SUPPORTED_SHAPES = ['ball', 'cuboid', 'capsule', 'cylinder', 'convexHull'];+const SUPPORTED_SHAPES = ['ball', 'cuboid', 'capsule', 'cylinder', 'cone', 'convexHull'];+// A compound body is several colliders on one body; the baked path allows the same number.+const MAX_COMPOUND_COLLIDERS = 16;const INSTALL_HINT = 'Install it with `npm install jolt-physics`, or build the system with rapierAdapter.';let joltPromise;@@ -68,8 +70,8 @@ function validateSupported(prepared) {}colliderCount.forEach((count, bodyIndex) => {const body = prepared.bodies[bodyIndex];- if (count > 1) {- throw new TypeError(`The jolt adapter takes one collider per body; body "${body.name}" has ${count}. Split it into one body per collider, or use rapierAdapter.`);+ if (count > MAX_COMPOUND_COLLIDERS) {+ throw new RangeError(`The jolt adapter takes at most ${MAX_COMPOUND_COLLIDERS} colliders per body; body "${body.name}" has ${count}. Merge colliders or split the body.`);}if (count === 0 && body.type === 'dynamic') {throw new TypeError(`A dynamic body needs a collider for the jolt adapter; body "${body.name}" has none.`);@@ -120,9 +122,10 @@ function createJoltWorld(prepared) {const bodyIds = [];const colliderOfBodyIndex = new Map();const bodyOfIdIndex = new Map();- const colliderOfBody = new Array(prepared.bodies.length).fill(-1);+ // A compound body lists several colliders; the first one stands for the body in events, rays and overlaps.+ const collidersOfBody = prepared.bodies.map(() => []);prepared.colliders.forEach((collider, colliderIndex) => {- colliderOfBody[collider.body] = colliderIndex;+ collidersOfBody[collider.body].push(colliderIndex);});const motionTypes = { dynamic: Jolt.EMotionType_Dynamic, fixed: Jolt.EMotionType_Static, kinematic: Jolt.EMotionType_Kinematic };@@ -138,6 +141,9 @@ function createJoltWorld(prepared) {shapeSettings = new Jolt.CapsuleShapeSettings(collider.halfHeight, collider.radius);} else if (collider.shape === 'cylinder') {shapeSettings = new Jolt.CylinderShapeSettings(collider.halfHeight, collider.radius, Math.min(MAX_CONVEX_RADIUS, collider.halfHeight, collider.radius) * 0.5);+ } else if (collider.shape === 'cone') {+ // Rapier's cone has its apex at +Y; Jolt has no cone, so a tapered cylinder with a zero top radius stands in for it.+ shapeSettings = new Jolt.TaperedCylinderShapeSettings(collider.halfHeight, 0, collider.radius, 0);} else {shapeSettings = new Jolt.ConvexHullShapeSettings();for (let index = 0; index < collider.points.length; index += 3) {@@ -154,10 +160,21 @@ function createJoltWorld(prepared) {return new Jolt.RotatedTranslatedShapeSettings(offset, rotation, shapeSettings);}- function createShape(collider) {- const shapeResult = createShapeSettings(collider).Create();+ function createShape(colliderIndices) {+ const colliders = colliderIndices.map(colliderIndex => prepared.colliders[colliderIndex]);+ let shapeSettings;+ if (colliders.length === 1) {+ shapeSettings = createShapeSettings(colliders[0]);+ } else {+ // Each part carries its own offset inside its settings, so the compound places every part at the origin.+ shapeSettings = new Jolt.StaticCompoundShapeSettings();+ const origin = own(new Jolt.Vec3(0, 0, 0));+ const identity = own(new Jolt.Quat(0, 0, 0, 1));+ for (const collider of colliders) shapeSettings.AddShape(origin, identity, createShapeSettings(collider), 0);+ }+ const shapeResult = shapeSettings.Create();if (shapeResult.HasError()) {- throw new RangeError(`Collider "${collider.name}" could not be built by jolt: ${shapeResult.GetError().c_str()}. Convex hull points must span a volume.`);+ throw new RangeError(`Collider "${colliders[0].name}" could not be built by jolt: ${shapeResult.GetError().c_str()}. Convex hull points must span a volume.`);}return shapeResult.Get();}@@ -172,11 +189,12 @@ function createJoltWorld(prepared) {}function addBody(body, bodyIndex) {- const colliderIndex = colliderOfBody[bodyIndex];+ const colliderIndices = collidersOfBody[bodyIndex];+ const colliderIndex = colliderIndices.length ? colliderIndices[0] : -1;const collider = colliderIndex >= 0 ? prepared.colliders[colliderIndex] : undefined;let shape;if (collider) {- shape = createShape(collider);+ shape = createShape(colliderIndices);} else {shape = new Jolt.EmptyShapeSettings().Create().Get();}@@ -192,7 +210,7 @@ function createJoltWorld(prepared) {creation.mRestitution = collider.restitution;if (collider.mass !== undefined && body.type === 'dynamic') {creation.mOverrideMassProperties = Jolt.EOverrideMassProperties_CalculateInertia;- creation.mMassPropertiesOverride.mMass = collider.mass;+ creation.mMassPropertiesOverride.mMass = colliderIndices.reduce((total, index) => total + prepared.colliders[index].mass, 0);}}if (body.type === 'dynamic') {diff --git a/tests/game-physics.test.js b/tests/game-physics.test.jsindex 30d00ba8..179e0cca 100644--- a/tests/game-physics.test.js+++ b/tests/game-physics.test.js@@ -83,6 +83,49 @@ test('a game with physics steps its bodies, moves their nodes and lets a rules z}});+test('a cone body and a compound body fall and rest on the floor in the live runtime', async () => {+ const restore = withAnimationFrameStubs();+ try {+ const recipe = await exportedRecipe({+ nodes: [+ { id: 'floor', geometry: 'block', material: 'paint', translation: [0, -0.25, 0], scale: [10, 0.5, 10] },+ { id: 'hero', geometry: 'block', material: 'paint', translation: [4, 0.8, 0], scale: [0.6, 1.6, 0.6] },+ { id: 'cone', geometry: 'block', material: 'paint', translation: [-2, 3, 0] },+ { id: 'stack', geometry: 'block', material: 'paint', translation: [2, 3, 0] },+ ],+ physics: {+ duration: 1,+ bodies: [+ { node: 'floor', type: 'fixed', shape: 'box' },+ { node: 'hero', type: 'kinematic', shape: 'capsule' },+ { node: 'cone', shape: 'cone' },+ {+ node: 'stack', shape: 'compound',+ shapes: [+ { shape: 'box', halfExtents: [0.5, 0.25, 0.5], translation: [0, -0.25, 0] },+ { shape: 'cylinder', radius: 0.25, halfHeight: 0.25, translation: [0, 0.25, 0] },+ ],+ },+ ],+ },+ game: { player: { node: 'hero', footOffset: 0.8 }, camera: 'follow', input: 'keyboard', physics: true, ground: 0 },+ });+ assert.equal(gamePhysicsProblem(recipe), null);+ const game = await playFor(recipe, 3);+ const cone = game.physics.getPose('cone').translation;+ const stack = game.physics.getPose('stack').translation;+ // The cone fits the unit block: base on the floor puts its centre 0.5 up. The compound's lowest part reaches 0.5 below its origin.+ assert.ok(Math.abs(cone[1] - 0.5) < 0.05, `the cone rests on its base, y ${cone[1]}`);+ assert.ok(Math.abs(stack[1] - 0.5) < 0.05, `the compound rests on its wide part, y ${stack[1]}`);+ for (const [name, position] of [['cone', cone], ['compound', stack]]) {+ assert.ok(Math.hypot(position[0] - (name === 'cone' ? -2 : 2), position[2]) < 0.05, `the ${name} stays where it fell`);+ }+ game.dispose();+ } finally {+ restore();+ }+});+test('the same recipe plays the same physics twice', async () => {const restore = withAnimationFrameStubs();try {@@ -200,7 +243,7 @@ test('a game without physics starts none and does not load the engine files', astest('a physics game without a body list, with joints or with an unsupported shape says what to change', () => {assert.match(gamePhysicsProblem({}), /no physics section with bodies.*set-physics/);assert.match(gamePhysicsProblem(physicsRecipe({ physics: { duration: 1, bodies: [{ node: 'crate', type: 'dynamic', shape: 'box' }], joints: [{ type: 'fixed' }] } })), /no joints or ragdolls/);- assert.match(gamePhysicsProblem(physicsRecipe({ physics: { duration: 1, bodies: [{ node: 'floor', type: 'fixed', shape: 'trimesh' }] } })), /Body "floor" has shape trimesh.*shape "box"/);+ assert.match(gamePhysicsProblem(physicsRecipe({ physics: { duration: 1, bodies: [{ node: 'floor', type: 'fixed', shape: 'trimesh' }] } })), /Body "floor" has shape trimesh.*builds box, ball, capsule, cylinder, cone, convex, compound.*"box"/);assert.equal(gamePhysicsProblem(physicsRecipe()), null);});diff --git a/tests/physics-jolt.test.js b/tests/physics-jolt.test.jsindex 87099780..dfe9f6b9 100644--- a/tests/physics-jolt.test.js+++ b/tests/physics-jolt.test.js@@ -137,16 +137,35 @@ test('unsupported scenes fail with a message that names the fix', async () => {joints: [{ name: 'hinge', type: 'spherical', bodyA: 'a', bodyB: 'b' }],};await assert.rejects(createPhysicsSystem(jointed, { adapter: joltAdapter }), /does not build joints yet.*rapierAdapter/);- const cone = {+ const trimesh = {bodies: [{ name: 'a', type: 'fixed' }],- colliders: [{ name: 'tip', body: 'a', shape: 'cone', halfHeight: 1, radius: 0.5 }],+ colliders: [{ name: 'ground', body: 'a', shape: 'trimesh', vertices: [0, 0, 0, 1, 0, 0, 0, 0, 1], indices: [0, 1, 2] }],};- await assert.rejects(createPhysicsSystem(cone, { adapter: joltAdapter }), /collider "tip" is cone/);- const pair = {+ await assert.rejects(createPhysicsSystem(trimesh, { adapter: joltAdapter }), /collider "ground" is trimesh/);+ const crowd = {bodies: [{ name: 'a' }],- colliders: [{ name: 'one', body: 'a', shape: 'ball', radius: 0.5, mass: 1 }, { name: 'two', body: 'a', shape: 'ball', radius: 0.5, translation: [1, 0, 0] }],+ colliders: Array.from({ length: 17 }, (_, index) => ({ name: `part${index}`, body: 'a', shape: 'ball', radius: 0.1, mass: 1, translation: [index, 0, 0] })),};- await assert.rejects(createPhysicsSystem(pair, { adapter: joltAdapter }), /one collider per body; body "a" has 2/);+ await assert.rejects(createPhysicsSystem(crowd, { adapter: joltAdapter }), /at most 16 colliders per body; body "a" has 17/);+});++test('cone and compound bodies fall on a floor and rest at the heights their shapes give', async () => {+ const definition = {+ bodies: [{ name: 'floor', type: 'fixed' }, { name: 'cone', translation: [-2, 3, 0] }, { name: 'stack', translation: [2, 3, 0] }],+ colliders: [+ { name: 'floor', body: 'floor', shape: 'cuboid', halfExtents: [10, 0.5, 10], translation: [0, -0.5, 0] },+ { name: 'cone', body: 'cone', shape: 'cone', halfHeight: 0.5, radius: 0.5, density: 1 },+ { name: 'stack', body: 'stack', shape: 'cuboid', halfExtents: [0.5, 0.25, 0.5], translation: [0, -0.25, 0], density: 1 },+ { name: 'stack#1', body: 'stack', shape: 'cylinder', halfHeight: 0.25, radius: 0.25, translation: [0, 0.25, 0], density: 1 },+ ],+ };+ const physics = await createPhysicsSystem(definition, { adapter: joltAdapter });+ stepMany(physics, 240);+ const cone = physics.getPose('cone').translation;+ const stack = physics.getPose('stack').translation;+ assert.ok(Math.abs(cone[1] - 0.5) < 0.05, `the cone rests on its base, y ${cone[1]}`);+ assert.ok(Math.abs(stack[1] - 0.5) < 0.05, `the compound rests on its wide part, y ${stack[1]}`);+ physics.dispose();});test('force fields push dynamic bodies under jolt', async () => {