3D engine that AI agents drive
Fracture convex parts into Voronoi fragments with breakable glue joints (#979)
Nguyen Xuan An1bb377625999
diff --git a/changes/979.md b/changes/979.mdnew file mode 100644index 00000000..1200b22f--- /dev/null+++ b/changes/979.md@@ -0,0 +1 @@+- Physics joints take `breakImpulse` and `src/fracture.js` fractures a convex part into glued Voronoi fragments that break on impact (#979)diff --git a/docs/physics.md b/docs/physics.mdindex b8d99647..a795885d 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -93,7 +93,7 @@ Connected bodies do not collide unless `contactsEnabled` is `true`.| `spherical` | None. The joint permits relative rotation. || `revolute` | Required unit `axis` expressed in both bodies' local frames. Optional `limits` and `motor`. || `prismatic` | Required unit `axis` expressed in both bodies' local frames. Optional `limits` and `motor`. |-| `fixed` | Optional unit `frameA` and `frameB` quaternions. Both default to identity. |+| `fixed` | Optional unit `frameA` and `frameB` quaternions, both default to identity, and optional `breakImpulse` (see Fracture and breakable glue). || `spring` | `restLength` (default `0`), positive `stiffness` and nonnegative `damping` (default `0`). |An articulated ragdoll is a graph of dynamic bodies, colliders, and joints.@@ -389,6 +389,29 @@ Rapier is loaded on demand, an optional peer dependency. The MCP runtime serves`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.+## Fracture and breakable glue++`src/fracture.js` splits a closed convex part (a box, cylinder, sphere or any convex mesh of at most 2048 triangles) into Voronoi fragments and describes the glue that holds them together. A concave part is rejected with a message to split it into convex parts first.++```js+import { fractureMesh, fragmentPhysics } from './src/fracture.js';+const fracture = fractureMesh(wallGeometry, { seed: 7, cells: 24, impact: [1.2, 0.5, 0], impactRadius: 0.6 });+const parts = fragmentPhysics(fracture, { translation: [0, 2, 0], strength: 20, density: 100 });+// parts.bodies, parts.colliders and parts.joints go into a physics definition next to a ball and a floor.+```++| Field | Meaning |+| --- | --- |+| `seed` | Integer from 0 (default 1). The same seed, cell count and impact give the same fragments byte for byte. |+| `cells` | 2 to 64 fragments. |+| `impact`, `impactRadius` | Optional point in the part's local space. Half the cells are placed within `impactRadius` of it (default 0.3 of the part's diagonal), so smaller pieces sit where the hit lands. |++`fractureMesh` returns `fragments`, `glue` and `volume`. Each fragment has `positions`, `normals`, `indices`, `volume` and `center` in the part's local space, and `groups`: the outside faces are material slot 0 and the new inside faces slot 1, each as a `{ slot, start, count }` range of `indices`. Fragment volumes sum to the part volume. `glue` lists each neighbouring pair `{ a, b, anchor, area }`.++`fragmentPhysics` turns that into bodies, convex hull colliders and one fixed joint per neighbouring pair, each with `breakImpulse: strength`. A fixed joint takes `breakImpulse` (N s, above 0): in the bake the joint is removed on the first step in which either of its bodies takes a contact impulse (contact force times the timestep) at or above it. A body resting under its own weight takes about `mass * 9.81 / 60`, so a strength above that holds a structure up and a ball or a falling slab below it breaks the glue. All the joints of a hit fragment that are weaker than the hit break together; the rest of the structure stays glued. `recording.jointBreaks` lists `{ frame, joint, impulse }`. Recipes take `breakImpulse` on a fixed `physics.joints` entry, and `scene_inspect` reports `jointBreaks`.++Not yet: reaching `fractureMesh` from a recipe or the MCP tool without writing the fragments out as nodes, clusters that break as one, and breaking in the live runtime (glue joints there never break).+## Recipe ragdollPart of issue #96. A ragdoll binds one physics body to every bone of a rig and writes the simulated result back as the local pose of each bone node, so skinning, export and seeking work as for any other pose.diff --git a/src/agent-physics.js b/src/agent-physics.jsindex 77ffdf2b..8292cc85 100644--- a/src/agent-physics.js+++ b/src/agent-physics.js@@ -26,7 +26,7 @@ const COMPOUND_PART_SHAPES = ['box', 'ball', 'capsule', 'cylinder', 'cone'];const JOINT_TYPES = ['spherical', 'revolute', 'prismatic', 'fixed', 'spring'];const BODY_FIELDS = ['node', 'type', 'shape', 'shapes', 'mass', 'density', 'friction', 'restitution', 'sensor', 'velocity', 'angularVelocity', 'layer', 'collidesWith'];const COMPOUND_PART_FIELDS = ['shape', 'translation', 'rotation', 'halfExtents', 'radius', 'halfHeight'];-const JOINT_FIELDS = ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'limits', 'motor', 'restLength', 'stiffness', 'damping', 'contactsEnabled'];+const JOINT_FIELDS = ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'limits', 'motor', 'restLength', 'stiffness', 'damping', 'contactsEnabled', 'breakImpulse'];const MOTOR_FIELDS = ['mode', 'target', 'stiffness', 'damping', 'maxForce'];const EVENT_FIELDS = ['time', 'tick', 'type', 'body', 'joint', 'impulse', 'torqueImpulse', 'point', 'translation', 'rotation', 'motor'];const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints', 'events', 'fields', 'ragdoll'];@@ -208,6 +208,12 @@ function normalizeJoint(input, bodyNodeIds, jointNames, path) {}joint.contactsEnabled = input.contactsEnabled;}+ if (input.breakImpulse !== undefined) {+ if (input.type !== 'fixed') {+ throw invalidField(`${path}.breakImpulse`, input.breakImpulse, 'a field left out unless joint type is "fixed"', TypeError);+ }+ joint.breakImpulse = finiteNumber(input.breakImpulse, `${path}.breakImpulse`, 1e-6, 1e9);+ }if (input.limits !== undefined) joint.limits = numberList(input.limits, 2, `${path}.limits`);if (input.motor !== undefined) joint.motor = normalizeMotor(input.motor, `${path}.motor`);if (input.type === 'spring') {@@ -555,6 +561,7 @@ export function bakeAgentPhysics(physics, recipe, geometries) {duration: physics.duration, frames: scene.frameCount, gravity: physics.gravity ?? [0, -9.81, 0],bodies: bodyReport(scene, physics), ...contactReport(scene, physics),eventsTruncated: scene.contactEventsTruncated,+ ...(scene.jointBreaks.length ? { jointBreaks: scene.jointBreaks.slice(0, MAX_REPORTED_CONTACTS).map(({ frame, joint, impulse }) => ({ joint, time: roundedTime(frame, scene.timestep), impulse: Number(impulse.toFixed(3)) })) } : {}),...(ragdoll ? { ragdoll: ragdollReport(ragdoll, scene) } : {}),};return structuredClone(reportCache);diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 940524bd..4cd7c969 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -308,6 +308,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({shapes: Object.freeze(['box', 'ball', 'capsule', 'convex', 'trimesh']),jointTypes: Object.freeze(['spherical', 'revolute', 'prismatic', 'fixed']),sensors: true, collisionLayers: 16,+ breakableJoints: 'joints[].breakImpulse (fixed joints, N s): the joint breaks in the bake when either body takes a contact impulse (force x 1/60 s) at or above it in one step, so resting weight does not. The report lists jointBreaks { joint, time, impulse }. Fracture a convex part into glued fragments with fractureMesh and fragmentPhysics from src/fracture.js (docs/physics.md).',ragdoll: 'physics.ragdoll {armature}: limp capsule per bone; needs a floor',limits: Object.freeze({ maxBodies: 64, maxJoints: 64, maxDuration: 10, framesPerSecond: 60, maxTrimeshTriangles: 20000, maxHullPoints: 2048 }),}),diff --git a/src/fracture.js b/src/fracture.jsnew file mode 100644index 00000000..07b38294--- /dev/null+++ b/src/fracture.js@@ -0,0 +1,334 @@+// Voronoi fracture of a closed convex mesh into fragments, and the glue that holds neighbouring fragments together.+// Pure float64 math from a seed, so the same input gives the same fragments byte for byte.++export const MIN_FRACTURE_CELLS = 2;+export const MAX_FRACTURE_CELLS = 64;+export const MAX_FRACTURE_TRIANGLES = 2048;+export const OUTSIDE_SLOT = 0;+export const INSIDE_SLOT = 1;++const SITE_ATTEMPTS_PER_CELL = 400;+const IMPACT_SHARE = 0.5;+const DEFAULT_IMPACT_RADIUS_SHARE = 0.3;+const MIN_SITE_SPACING_SHARE = 0.02;+const EPSILON_SHARE = 1e-7;+const MIN_CAP_AREA_SHARE = 1e-6;+const CONVEX_TOLERANCE_SHARE = 1e-3;++function seededRandom(seed) {+ let state = seed >>> 0;+ return () => {+ state = (state + 0x6d2b79f5) >>> 0;+ let mixed = Math.imul(state ^ (state >>> 15), 1 | state);+ mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;+ };+}++function subtract(first, second) {+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];+}++function dot(first, second) {+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];+}++function cross(first, second) {+ return [+ first[1] * second[2] - first[2] * second[1],+ first[2] * second[0] - first[0] * second[2],+ first[0] * second[1] - first[1] * second[0],+ ];+}++function normalized(vector) {+ const length = Math.hypot(vector[0], vector[1], vector[2]);+ return length === 0 ? [0, 0, 0] : [vector[0] / length, vector[1] / length, vector[2] / length];+}++function failure(field, received, expected) {+ return new RangeError(`${field} is ${received}; use ${expected}`);+}++function validateOptions(options) {+ const { seed = 1, cells, impact, impactRadius } = options;+ if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) {+ throw failure('fracture seed', seed, 'an integer from 0 to 4294967295, such as 1');+ }+ if (!Number.isInteger(cells) || cells < MIN_FRACTURE_CELLS || cells > MAX_FRACTURE_CELLS) {+ throw failure('fracture cells', cells, `an integer from ${MIN_FRACTURE_CELLS} to ${MAX_FRACTURE_CELLS}, such as 12`);+ }+ if (impact !== undefined && (!Array.isArray(impact) || impact.length !== 3 || !impact.every(Number.isFinite))) {+ throw failure('fracture impact', JSON.stringify(impact), 'a point [x, y, z] in the part local space, such as [0, 1, 0]');+ }+ if (impactRadius !== undefined && !(Number.isFinite(impactRadius) && impactRadius > 0)) {+ throw failure('fracture impactRadius', impactRadius, 'a distance above 0 in the part local space, such as 0.5');+ }+ return { seed, cells, impact, impactRadius };+}++/** The source triangles as convex polygons with a vertex normal each, after checking it is a closed, outward, convex solid. */+function sourcePolygons(geometry) {+ const { positions, indices } = geometry;+ const normals = geometry.normals;+ const triangleCount = indices.length / 3;+ if (!Number.isInteger(triangleCount) || triangleCount < 4) {+ throw failure('fracture geometry', `${triangleCount} triangles`, 'a closed mesh with at least 4 triangles, such as a box');+ }+ if (triangleCount > MAX_FRACTURE_TRIANGLES) {+ throw failure('fracture geometry', `${triangleCount} triangles`, `at most ${MAX_FRACTURE_TRIANGLES} triangles; use fewer segments or subdivisions`);+ }+ const polygons = [];+ const planes = [];+ for (let triangle = 0; triangle < triangleCount; triangle++) {+ const vertices = [0, 1, 2].map(corner => {+ const vertex = indices[triangle * 3 + corner];+ const point = [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]];+ const normal = normals ? [normals[vertex * 3], normals[vertex * 3 + 1], normals[vertex * 3 + 2]] : [0, 0, 0];+ return { point, normal };+ });+ const faceNormal = normalized(cross(subtract(vertices[1].point, vertices[0].point), subtract(vertices[2].point, vertices[0].point)));+ if (faceNormal[0] === 0 && faceNormal[1] === 0 && faceNormal[2] === 0) continue;+ if (!normals) vertices.forEach(vertex => { vertex.normal = faceNormal; });+ polygons.push({ vertices, slot: OUTSIDE_SLOT });+ planes.push({ normal: faceNormal, offset: dot(faceNormal, vertices[0].point) });+ }+ return { polygons, planes };+}++function boundsOf(polygons) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (const polygon of polygons) {+ for (const { point } of polygon.vertices) {+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], point[axis]);+ maximum[axis] = Math.max(maximum[axis], point[axis]);+ }+ }+ }+ return { minimum, maximum, diagonal: Math.hypot(...subtract(maximum, minimum)) };+}++function polygonsVolume(polygons) {+ let volume = 0;+ for (const polygon of polygons) {+ const first = polygon.vertices[0].point;+ for (let corner = 1; corner < polygon.vertices.length - 1; corner++) {+ volume += dot(first, cross(polygon.vertices[corner].point, polygon.vertices[corner + 1].point)) / 6;+ }+ }+ return volume;+}++function checkConvexSolid(polygons, planes, diagonal) {+ if (polygonsVolume(polygons) <= 0) {+ throw failure('fracture geometry', 'inside out or flat', 'a closed mesh whose triangles wind counter-clockwise seen from outside');+ }+ for (const plane of planes) {+ for (const polygon of polygons) {+ for (const { point } of polygon.vertices) {+ if (dot(plane.normal, point) > plane.offset + diagonal * CONVEX_TOLERANCE_SHARE) {+ throw failure('fracture geometry', 'not convex', 'a convex closed part, such as a box, cylinder or sphere; split a concave part into convex parts first');+ }+ }+ }+ }+}++function mixVertex(from, to, fraction) {+ return {+ point: from.point.map((value, axis) => value + (to.point[axis] - value) * fraction),+ normal: normalized(from.normal.map((value, axis) => value + (to.normal[axis] - value) * fraction)),+ };+}++/** Keep the part of a convex polygon where normal . point <= offset. Returns null when less than a triangle is left. */+function clipPolygon(polygon, normal, offset, epsilon) {+ const kept = [];+ const { vertices } = polygon;+ for (let index = 0; index < vertices.length; index++) {+ const current = vertices[index];+ const next = vertices[(index + 1) % vertices.length];+ const currentDistance = dot(normal, current.point) - offset;+ const nextDistance = dot(normal, next.point) - offset;+ if (currentDistance <= epsilon) kept.push(current);+ const crosses = (currentDistance < -epsilon && nextDistance > epsilon) || (currentDistance > epsilon && nextDistance < -epsilon);+ if (crosses) kept.push(mixVertex(current, next, currentDistance / (currentDistance - nextDistance)));+ }+ return kept.length < 3 ? null : { ...polygon, vertices: kept };+}++function distinctPoints(points, epsilon) {+ const distinct = [];+ for (const point of points) {+ if (!distinct.some(existing => Math.hypot(...subtract(existing, point)) <= epsilon * 10)) distinct.push(point);+ }+ return distinct;+}++/** The cut face on a plane: its points ordered counter-clockwise seen from along the outward normal. */+function capPolygon(points, normal, neighbor) {+ const center = points.reduce((sum, point) => [sum[0] + point[0], sum[1] + point[1], sum[2] + point[2]], [0, 0, 0]).map(value => value / points.length);+ const helper = Math.abs(normal[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];+ const axisU = normalized(cross(helper, normal));+ const axisV = cross(normal, axisU);+ const ordered = points+ .map(point => ({ point, angle: Math.atan2(dot(subtract(point, center), axisV), dot(subtract(point, center), axisU)) }))+ .sort((first, second) => first.angle - second.angle);+ return { vertices: ordered.map(({ point }) => ({ point, normal })), slot: INSIDE_SLOT, neighbor };+}++function polygonArea(polygon) {+ const first = polygon.vertices[0].point;+ let doubled = [0, 0, 0];+ for (let corner = 1; corner < polygon.vertices.length - 1; corner++) {+ const piece = cross(subtract(polygon.vertices[corner].point, first), subtract(polygon.vertices[corner + 1].point, first));+ doubled = [doubled[0] + piece[0], doubled[1] + piece[1], doubled[2] + piece[2]];+ }+ return Math.hypot(...doubled) / 2;+}++function polygonCenter(polygon) {+ const sum = polygon.vertices.reduce((total, { point }) => [total[0] + point[0], total[1] + point[1], total[2] + point[2]], [0, 0, 0]);+ return sum.map(value => value / polygon.vertices.length);+}++function insideSolid(point, planes, margin) {+ return planes.every(plane => dot(plane.normal, point) <= plane.offset - margin);+}++function chooseSites(options, bounds, planes) {+ const random = seededRandom(options.seed);+ const margin = bounds.diagonal * MIN_SITE_SPACING_SHARE;+ const impactRadius = options.impactRadius ?? bounds.diagonal * DEFAULT_IMPACT_RADIUS_SHARE;+ const impactSites = options.impact ? Math.floor(options.cells * IMPACT_SHARE) : 0;+ const sites = [];+ let attempts = 0;+ while (sites.length < options.cells) {+ if (attempts++ > options.cells * SITE_ATTEMPTS_PER_CELL) {+ throw failure('fracture cells', options.cells, 'fewer cells for this part, or a larger impactRadius; the part is too thin or small to hold them apart');+ }+ const nearImpact = sites.length < impactSites;+ const candidate = [0, 1, 2].map(axis => {+ const unit = random();+ if (nearImpact) return options.impact[axis] + (unit * 2 - 1) * impactRadius;+ return bounds.minimum[axis] + unit * (bounds.maximum[axis] - bounds.minimum[axis]);+ });+ if (!insideSolid(candidate, planes, margin)) continue;+ if (sites.some(site => Math.hypot(...subtract(site, candidate)) < margin)) continue;+ sites.push(candidate);+ }+ return sites;+}++function buildCell(siteIndex, sites, polygons, epsilon) {+ let cell = polygons;+ for (let other = 0; other < sites.length; other++) {+ if (other === siteIndex) continue;+ const normal = subtract(sites[other], sites[siteIndex]);+ const midpoint = sites[siteIndex].map((value, axis) => (value + sites[other][axis]) / 2);+ const offset = dot(normal, midpoint);+ const unitNormal = normalized(normal);+ const unitOffset = offset / Math.hypot(...normal);+ const clipped = [];+ const planePoints = [];+ for (const polygon of cell) {+ const result = clipPolygon(polygon, unitNormal, unitOffset, epsilon);+ if (!result) continue;+ clipped.push(result);+ for (const { point } of result.vertices) {+ if (Math.abs(dot(unitNormal, point) - unitOffset) <= epsilon) planePoints.push(point);+ }+ }+ const rim = distinctPoints(planePoints, epsilon);+ if (rim.length >= 3) clipped.push(capPolygon(rim, unitNormal, other));+ cell = clipped;+ }+ return cell;+}++function meshOfCell(cell) {+ const ordered = [...cell].sort((first, second) => first.slot - second.slot);+ const positions = [];+ const normals = [];+ const indices = [];+ const groups = [];+ for (const slot of [OUTSIDE_SLOT, INSIDE_SLOT]) {+ const start = indices.length;+ for (const polygon of ordered.filter(candidate => candidate.slot === slot)) {+ const base = positions.length / 3;+ for (const { point, normal } of polygon.vertices) {+ positions.push(...point);+ normals.push(...normal);+ }+ for (let corner = 1; corner < polygon.vertices.length - 1; corner++) indices.push(base, base + corner, base + corner + 1);+ }+ if (indices.length > start) groups.push({ slot, start, count: indices.length - start });+ }+ return {+ positions: new Float32Array(positions),+ normals: new Float32Array(normals),+ indices: new Uint32Array(indices),+ groups,+ };+}++/**+ * Split a closed convex mesh into Voronoi fragments.+ * options: { seed (0), cells (2-64), impact [x, y, z] (packs half the cells near it), impactRadius }.+ * Returns { fragments, glue, volume }. Each fragment has positions, normals, indices, groups (material slot 0 outside,+ * slot 1 inside faces), volume and center. glue lists the neighbouring fragment pairs with the middle of the face they share.+ */+export function fractureMesh(geometry, rawOptions) {+ const options = validateOptions(rawOptions ?? {});+ const { polygons, planes } = sourcePolygons(geometry);+ const bounds = boundsOf(polygons);+ const epsilon = Math.max(bounds.diagonal * EPSILON_SHARE, Number.MIN_VALUE);+ checkConvexSolid(polygons, planes, bounds.diagonal);+ const sites = chooseSites(options, bounds, planes);+ const minimumArea = bounds.diagonal ** 2 * MIN_CAP_AREA_SHARE;+ const cells = sites.map((_, siteIndex) => buildCell(siteIndex, sites, polygons, epsilon));+ const fragments = cells.map((cell, siteIndex) => ({ ...meshOfCell(cell), volume: polygonsVolume(cell), center: sites[siteIndex] }));+ const glue = [];+ cells.forEach((cell, first) => {+ for (const polygon of cell) {+ if (polygon.slot !== INSIDE_SLOT || polygon.neighbor < first || polygonArea(polygon) < minimumArea) continue;+ glue.push({ a: first, b: polygon.neighbor, anchor: polygonCenter(polygon), area: polygonArea(polygon) });+ }+ });+ return { fragments, glue, volume: polygonsVolume(polygons) };+}++function distinctHullPoints(positions) {+ const distinct = new Map();+ for (let index = 0; index < positions.length; index += 3) {+ const key = `${positions[index]},${positions[index + 1]},${positions[index + 2]}`;+ if (!distinct.has(key)) distinct.set(key, [positions[index], positions[index + 1], positions[index + 2]]);+ }+ return [...distinct.values()].flat();+}++/**+ * Physics definition parts for fragments held together by breakable fixed joints.+ * `bodyName(index)` names each fragment body; the bodies sit at `translation` with the part's own rotation.+ * strength is the single-step contact impulse in N s that breaks a joint (see breakImpulse in docs/physics.md).+ */+export function fragmentPhysics(fracture, { translation = [0, 0, 0], rotation = [0, 0, 0, 1], strength, density = 1, bodyName = index => `fragment-${index}`, friction } = {}) {+ if (!(Number.isFinite(strength) && strength > 0)) {+ throw failure('glue strength', strength, 'an impulse above 0 in N s, such as 5');+ }+ const bodies = [];+ const colliders = [];+ fracture.fragments.forEach((fragment, index) => {+ bodies.push({ name: bodyName(index), translation, rotation });+ colliders.push({+ name: bodyName(index), body: bodyName(index), shape: 'convexHull', points: distinctHullPoints(fragment.positions), density,+ ...(friction === undefined ? {} : { friction }),+ });+ });+ const joints = fracture.glue.map(({ a, b, anchor }) => ({+ name: `glue-${a}-${b}`, type: 'fixed', bodyA: bodyName(a), bodyB: bodyName(b), anchorA: anchor, anchorB: anchor, breakImpulse: strength,+ }));+ return { bodies, colliders, joints };+}diff --git a/src/physics.js b/src/physics.jsindex 7c221910..057552a1 100644--- a/src/physics.js+++ b/src/physics.js@@ -434,7 +434,10 @@ function prepare(definition, options) {}}const joints = rawJoints.map(joint => {- fields(joint, ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'frameA', 'frameB', 'contactsEnabled', 'limits', 'motor', 'restLength', 'stiffness', 'damping'], `joint ${joint.name}`);+ fields(joint, ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'frameA', 'frameB', 'contactsEnabled', 'limits', 'motor', 'restLength', 'stiffness', 'damping', 'breakImpulse'], `joint ${joint.name}`);+ if (joint.breakImpulse !== undefined && joint.type !== 'fixed') {+ throw new TypeError('breakImpulse requires a fixed joint');+ }if (!['spherical', 'revolute', 'prismatic', 'fixed', 'spring'].includes(joint.type)) {throw new TypeError('unsupported joint type');}@@ -468,6 +471,7 @@ function prepare(definition, options) {}}const result = {+ name: joint.name,type: joint.type,bodyA,bodyB,@@ -484,11 +488,19 @@ function prepare(definition, options) {if (result.stiffness > MAX_MOTOR_GAIN) throw new RangeError('spring stiffness exceeds the supported gain bound');result.damping = scalar(joint.damping ?? 0, 'damping', 0, MAX_MOTOR_GAIN);}+ if (joint.breakImpulse !== undefined) result.breakImpulse = positive(joint.breakImpulse, 'breakImpulse');if (joint.limits !== undefined) result.limits = jointLimits(joint.limits, joint.type);if (joint.motor !== undefined) result.motor = jointMotor(joint.motor, result);if (joint.type === 'prismatic' || joint.limits !== undefined || joint.motor !== undefined) initialJointCoordinate(result, bodies);return result;});+ for (const joint of joints) {+ if (joint.breakImpulse === undefined) continue;+ for (const collider of colliders) {+ if (collider.body !== joint.bodyA && collider.body !== joint.bodyB) continue;+ collider.breakForceThreshold = Math.min(collider.breakForceThreshold ?? Infinity, joint.breakImpulse / timestep);+ }+ }const jointIndices = new Map(rawJoints.map((joint, index) => [joint.name, index]));const events = rawEvents.map((event, order) => {const tick = integer(event.tick, 'event tick', 0, frameCount - 2);@@ -747,7 +759,9 @@ function colliderDescriptor(rapier, collider) {descriptor.setRestitution(collider.restitution);descriptor.setSensor(collider.sensor);descriptor.setCollisionGroups(((collider.groups << 16) | collider.mask) >>> 0);- descriptor.setActiveEvents(rapier.ActiveEvents.COLLISION_EVENTS);+ const forceEvents = collider.breakForceThreshold === undefined ? 0 : rapier.ActiveEvents.CONTACT_FORCE_EVENTS;+ descriptor.setActiveEvents(rapier.ActiveEvents.COLLISION_EVENTS | forceEvents);+ if (forceEvents) descriptor.setContactForceEventThreshold(collider.breakForceThreshold);if (collider.shape !== 'trimesh') {if (collider.mass === undefined) {descriptor.setDensity(collider.density);@@ -833,11 +847,44 @@ export function applyForceFieldImpulses(preparedScene, bodies, fieldTime) {}}+function breakableJointTable(preparedScene, rapierJoints) {+ const table = [];+ preparedScene.joints.forEach((joint, index) => {+ if (joint.breakImpulse !== undefined) table.push({ index, joint, rapierJoint: rapierJoints[index], broken: false });+ });+ return table;+}++/**+ * Break every glue joint of a body that took a contact impulse over the joint strength in this step.+ * The impulse is the contact force magnitude times the timestep, so a body resting under its own weight stays glued.+ */+function breakJointsHitHard(world, eventQueue, preparedScene, colliderIndices, breakableJoints, frame, jointBreaks) {+ const impulseByBody = new Map();+ eventQueue.drainContactForceEvents(event => {+ const impulse = event.totalForceMagnitude() * preparedScene.timestep;+ for (const handle of [event.collider1(), event.collider2()]) {+ const body = preparedScene.colliders[colliderIndices.get(handle)].body;+ impulseByBody.set(body, Math.max(impulseByBody.get(body) ?? 0, impulse));+ }+ });+ for (const entry of breakableJoints) {+ if (entry.broken) continue;+ const impulse = Math.max(impulseByBody.get(entry.joint.bodyA) ?? 0, impulseByBody.get(entry.joint.bodyB) ?? 0);+ if (impulse < entry.joint.breakImpulse) continue;+ entry.broken = true;+ world.removeImpulseJoint(entry.rapierJoint, true);+ jointBreaks.push(Object.freeze({ frame, joint: entry.joint.name, impulse }));+ }+}+function bakePrepared(preparedScene) {const rapier = rapierEngine;const { world, bodies, joints, colliderIndices } = createRapierWorld(rapier, preparedScene);const eventQueue = new rapier.EventQueue(true);const contactEvents = [];+ const jointBreaks = [];+ const breakableJoints = breakableJointTable(preparedScene, joints);const lastMovingFrames = new Int32Array(preparedScene.bodies.length).fill(-1);let contactEventsTruncated = false;let timeline;@@ -886,6 +933,9 @@ function bakePrepared(preparedScene) {const sensor = preparedScene.colliders[first].sensor || preparedScene.colliders[second].sensor;contactEvents.push(Object.freeze({ frame, kind: sensor ? 'sensor' : 'contact', started, colliderA: first, colliderB: second }));});+ if (breakableJoints.length) {+ breakJointsHitHard(world, eventQueue, preparedScene, colliderIndices, breakableJoints, frame, jointBreaks);+ }}for (let bodyIndex = 0; bodyIndex < bodies.length; bodyIndex++) {const linearVelocity = bodies[bodyIndex].linvel();@@ -920,7 +970,7 @@ function bakePrepared(preparedScene) {eventQueue.free();world.free();}- return recordedScene(preparedScene, timeline, { contactEvents, contactEventsTruncated, lastMovingFrames });+ return recordedScene(preparedScene, timeline, { contactEvents, contactEventsTruncated, lastMovingFrames, jointBreaks });}function recordedScene(preparedScene, timeline, recording) {@@ -1103,6 +1153,8 @@ function recordedScene(preparedScene, timeline, recording) {/** Contact and sensor start or stop events in step order, with collider indices into colliderNames. */contactEvents: Object.freeze(recording.contactEvents),contactEventsTruncated: recording.contactEventsTruncated,+ /** Glue joints that broke, in step order: the frame, the joint name and the contact impulse (N s) that broke it. */+ jointBreaks: Object.freeze(recording.jointBreaks),/** 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() {diff --git a/tests/fracture.test.js b/tests/fracture.test.jsnew file mode 100644index 00000000..e044b082--- /dev/null+++ b/tests/fracture.test.js@@ -0,0 +1,133 @@+import { createHash } from 'node:crypto';+import test from 'node:test';+import assert from 'node:assert/strict';+import { box, sphere } from '../src/geometry.js';+import { fractureMesh, fragmentPhysics } from '../src/fracture.js';+import { createPhysicsScene } from '../src/physics.js';++const wall = () => {+ const source = box(0);+ for (let index = 0; index < source.positions.length; index += 3) {+ source.positions[index] *= 3;+ source.positions[index + 1] *= 2;+ source.positions[index + 2] *= 0.4;+ }+ return source;+};++function fingerprint(fracture) {+ const hash = createHash('sha256');+ for (const fragment of fracture.fragments) {+ hash.update(Buffer.from(fragment.positions.buffer));+ hash.update(Buffer.from(fragment.indices.buffer));+ hash.update(JSON.stringify(fragment.groups));+ }+ return hash.digest('hex');+}++test('the same seed gives the same fragments byte for byte and a new seed gives others', () => {+ const first = fractureMesh(wall(), { seed: 7, cells: 12 });+ const second = fractureMesh(wall(), { seed: 7, cells: 12 });+ const other = fractureMesh(wall(), { seed: 8, cells: 12 });+ assert.equal(first.fragments.length, 12);+ assert.equal(fingerprint(first), fingerprint(second));+ assert.notEqual(fingerprint(first), fingerprint(other));+});++test('fragment volumes sum to the source volume within 1 percent', () => {+ for (const source of [wall(), box(), sphere(24, 16)]) {+ const fracture = fractureMesh(source, { seed: 3, cells: 16 });+ const total = fracture.fragments.reduce((sum, fragment) => sum + fragment.volume, 0);+ assert.ok(Math.abs(total - fracture.volume) / fracture.volume < 0.01, `${total} against ${fracture.volume}`);+ assert.ok(fracture.fragments.every(fragment => fragment.volume > 0));+ }+});++test('inside faces sit on their own material slot after the outside faces', () => {+ const fracture = fractureMesh(wall(), { seed: 1, cells: 6 });+ for (const fragment of fracture.fragments) {+ assert.deepEqual(fragment.groups.map(group => group.slot), [0, 1]);+ const [outside, inside] = fragment.groups;+ assert.equal(outside.start, 0);+ assert.equal(inside.start, outside.count);+ assert.equal(outside.count + inside.count, fragment.indices.length);+ }+});++test('an impact point packs smaller cells near it', () => {+ const impact = [1.2, 0.5, 0];+ const spread = fractureMesh(wall(), { seed: 5, cells: 24 });+ const packed = fractureMesh(wall(), { seed: 5, cells: 24, impact, impactRadius: 0.6 });+ const near = fracture => fracture.fragments.filter(fragment => Math.hypot(fragment.center[0] - impact[0], fragment.center[1] - impact[1]) < 0.8).length;+ assert.ok(near(packed) > near(spread));+});++test('glue joins neighbours and the errors say what to pass', () => {+ const fracture = fractureMesh(wall(), { seed: 2, cells: 10 });+ assert.ok(fracture.glue.length >= fracture.fragments.length - 1);+ assert.ok(fracture.glue.every(({ a, b }) => a < b));+ assert.throws(() => fractureMesh(wall(), { cells: 1 }), /fracture cells is 1; use an integer from 2 to 64/);+ assert.throws(() => fractureMesh(wall(), { cells: 65 }), /cells/);+ assert.throws(() => fractureMesh(wall(), { cells: 4, seed: -1 }), /seed/);+ assert.throws(() => fractureMesh(wall(), { cells: 4, impact: [1] }), /impact/);+ assert.throws(() => fragmentPhysics(fracture, { strength: 0 }), /glue strength/);+ const open = { positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2]) };+ assert.throws(() => fractureMesh(open, { cells: 2 }), /closed mesh/);+});++async function wallScene(strength, ballSpeed) {+ const fracture = fractureMesh(wall(), { seed: 11, cells: 12 });+ const parts = fragmentPhysics(fracture, { translation: [0, 2, 0], strength, density: 100 });+ const definition = {+ bodies: [+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },+ { name: 'ball', translation: [0, 2, 5], linearVelocity: [0, 0, -ballSpeed] },+ ...parts.bodies,+ ],+ colliders: [+ { name: 'ground', body: 'floor', shape: 'cuboid', halfExtents: [20, 0.5, 20] },+ { name: 'ball', body: 'ball', shape: 'ball', radius: 0.4, mass: 20 },+ ...parts.colliders,+ ],+ joints: parts.joints,+ };+ return { fracture, scene: await createPhysicsScene(definition, { frameCount: 181 }) };+}++function spreadOf(scene, fracture, time) {+ const pose = scene.sample(time);+ let widest = 0;+ for (const { a, b } of fracture.glue) {+ const first = scene.bodyIndex(`fragment-${a}`) * 7;+ const second = scene.bodyIndex(`fragment-${b}`) * 7;+ widest = Math.max(widest, Math.hypot(pose[first] - pose[second], pose[first + 1] - pose[second + 1], pose[first + 2] - pose[second + 2]));+ }+ return widest;+}++test('glued fragments hold under gravity and break when a body hits above the strength', async () => {+ const gentle = await wallScene(1e6, 0);+ assert.equal(gentle.scene.jointBreaks.length, 0);+ const restSpread = spreadOf(gentle.scene, gentle.fracture, 0);+ assert.ok(Math.abs(spreadOf(gentle.scene, gentle.fracture, 3) - restSpread) < 0.05);++ const held = await wallScene(1e6, 15);+ assert.equal(held.scene.jointBreaks.length, 0, 'a hit below the strength leaves the glue alone');+ assert.ok(Math.abs(spreadOf(held.scene, held.fracture, 3) - spreadOf(held.scene, held.fracture, 0)) < 0.2);++ const smashed = await wallScene(20, 15);+ assert.ok(smashed.scene.jointBreaks.length > 0);+ assert.ok(smashed.scene.jointBreaks.every(entry => entry.impulse >= 20 && entry.frame > 0));+ assert.ok(spreadOf(smashed.scene, smashed.fracture, 3) > 1);+});++test('breakImpulse is only for fixed joints and must be positive', async () => {+ const definition = {+ bodies: [{ name: 'a', type: 'fixed' }, { name: 'b' }],+ colliders: [{ name: 'a', body: 'a', shape: 'ball', radius: 1 }, { name: 'b', body: 'b', shape: 'ball', radius: 1, mass: 1 }],+ joints: [{ name: 'j', type: 'spherical', bodyA: 'a', bodyB: 'b', breakImpulse: 5 }],+ };+ await assert.rejects(createPhysicsScene(definition, { frameCount: 2 }), /breakImpulse requires a fixed joint/);+ definition.joints[0] = { name: 'j', type: 'fixed', bodyA: 'a', bodyB: 'b', breakImpulse: -1 };+ await assert.rejects(createPhysicsScene(definition, { frameCount: 2 }), /breakImpulse/);+});