The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Joints in place, the world's anchor, joints that follow their anchors, the blast (ROADMAP § 6 step 10 c1) (#31)
Yujia3a22cdb036ae
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 9bdc73e..005eb69 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -4402,7 +4402,35 @@ benchmark level. The order follows the dependencies; a step that meets a furthervoxels**, are not done.- Open: the live march's media are lighter and more see-through than offline (8 steps; in-scattering isotropicfrom the cache): the fireball reads lighter than offline.- - (c) Vehicles and ropes on step 7's joints.+ - **(c1) Joints and the blast** (branch `vehicles-ropes`; design `out/web-probe/step10/c-design.md`; docs/VOXEL.md+ "Joints, the level's anchor and the blast"). (c) split in two (the supervisor, 2026-11-12: engine structure+ first, features after). The user's decisions 1-4 (2026-11-12), each the standard structure where the engine did+ otherwise: a joint's parameters change in place (`joint_set`; before, removed and made again; the engine refuses+ one that names its bodies, anchors or axis); joints to the level hold to the world's anchor, a fixed body with no+ collider (the level's colliders stay static, on no body); a joint belongs to the material at its anchor (it moves+ with a part cut off and the engine reports it, `joint_changes`, so `bodyA` / `anchorA` name the part; it breaks+ when its cell is carved or its body goes, the world's own removals included: `Joint.broken`, a "broken" event);+ an explosion's blast pushes the bodies within 3 radii (impulse by area and distance, through the centre of mass;+ the carve's radius) and kicks the parts it cuts loose (8 m/s at the default push, whatever their mass; at most+ 30 m/s in all; the supervisor for the user, 2026-11-12). Recorded hashes: physics-core's script+ 8e4af124a2061883 (the kick added to its blast), the voxel bodies' 3329720df1b31ca3 (an explosion added that+ cuts a body in two, to kick its part); the anchor body itself changes neither (with the kick off, both are the+ first draft's bits); native = parallel = wasm32.+ - The independent review of #31 (2026-11-12): the first draft hung the level's colliders on a fixed body and hid+ Rapier's per-edit mass sum over them with a zero-mass rule (an explosion's frame had taken 26 s); the tick+ after a carve still grew with the level's colliders (1.2 ms at 10,000). The anchor body is the standard+ structure: main's flat cost (0.02-0.05 ms), no special case. Also fixed: the binding did not know of joints the+ engine moved (a later sync let go of them or remade them on the level); a throwing "broken" listener left the+ rest unmarked; `pose` could move the level; the blast's radius was not the carve's; the world's own removals+ reported no "broken"; joint lookups were linear in the world's joints (40,000 joints: 0.7 to 6 s stalls, now+ 8-11 ms).+ - Open: the blast is not shielded by walls (decision 4: one voxel ray per body would do it); a joint's anchor on+ a face between two cells is held by the cell the point falls in, else the nearest solid neighbour.+ - (c2) Vehicles and ropes: the ray-cast vehicle (Rapier's `DynamicRayCastVehicleController`; the comparison in+ `out/web-probe/step10/c-vehicle-compare.md`: steady, 250-300 times cheaper than a car of wheel joints, as+ deterministic); ropes as `RopeJoint` and a drawn curve (they do not collide: they pass through walls). Waits on+ the user's decision on parry's voxel ray, which misses 8-22 % of rays starting on a lattice plane (the wheels'+ rays go through it).- (d) Acceptance: the benchmark level played through as a game, every line of `docs/VOXEL.md`'s benchmark measured.## Known issuesdiff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 283cbce..e4de0d7 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -226,7 +226,13 @@ crate.position.set(0, 5, 0); // a write moves the body therehello world's test for something fixed, `hit.object.physics?.type === "fixed"`, does not find the level: it is`hit.object === engineColliders`. A level that collides is in the physics world, and the queries ask it, whether ornot any scene object has `physics`; contacts with it reach a body's listeners with `other: engineColliders`.- `voxelImpulse(body, impulse, point?)` (step 8's call by id) is kept, deprecated. An explosion's fire and smoke are+ `voxelImpulse(body, impulse, point?)` (step 8's call by id) is kept, deprecated. A joint's parameters (limits,+ motor, a rope's length) change in place (`joint_set`); a joint may hold to the voxel level (`engineColliders`: the+ world's anchor, a fixed body with no collider); a joint on a voxel body or the level follows the cell its anchor is+ in when bodies are cut (its `bodyA` / `anchorA`, or `bodyB` / `anchorB`, then name the part it is on), and is+ `broken` (a "broken" event) when that cell is carved or its body goes. An explosion's blast pushes the bodies near+ it, and kicks the parts it cuts loose (`push`; docs/VOXEL.md "Joints, the level's anchor and the blast", step 10+ c1). An explosion's fire and smoke are`Explosions` (`packages/voxel`, step 10 b; docs/VOXEL.md "Fire and smoke"): scene objects pooled in setup, no enginecall of their own. A voxel shape's limits: cells of 1 cm to 100 m, at most 2^24cells, each within 2^20 cells and 100 km of the shape's origin.diff --git a/docs/VOXEL.md b/docs/VOXEL.mdindex 25e367b..2541b4d 100644--- a/docs/VOXEL.md+++ b/docs/VOXEL.md@@ -676,6 +676,72 @@ Cost: `--only cost`, the destruction game's routes at 0.75, lockstep (frames as| fire, `peak` (20 within a second) | 8.8 | 11.3 (max 12.7); 8 burning (the pool) | || fire, software traversal (loop guard on: no stop) | 13.0 | 13.7 (max 18.0 while it burns) | 28.9 |+### Joints, the level's anchor and the blast (ROADMAP § 6 step 10 c1; design: `out/web-probe/step10/c-design.md`)++Engine-side physics the vehicles and ropes of (c2) stand on, each the standard structure where the engine's code did+otherwise (the user's decisions 1-4, 2026-11-12; the independent review of #31).++- **A joint's parameters change in place.** A hinge's or a slider's limits and motor, a rope's length: `needsUpdate`+ sends `joint_set` (physics-core `Physics::set_joint`), the same Rapier joint; its frames are not taken anew from the+ bodies' poses, its warm-started impulses are kept. Before, every change removed the joint and made it again (a motor+ set each frame remade it each frame). A change of its bodies, anchors or axis makes it anew; the engine refuses a+ `joint_set` that names any of them (the rule is the engine's, not only the binding's). A hinge's limits are+ re-centred through its first frame with libm (as when it is made: the platform's `sin_cos` of a non-zero centre is+ not on our path).+- **Joints to the level hold to the world's anchor.** One fixed engine body with no collider (made at load, at the+ origin, unturned), as engines give joints to the static world (Rapier's static colliders are on no body; a joint+ needs a body): a joint whose object is `engineColliders` holds to it (a rope tied to a wall), a point of it the same+ point of the world. The level's colliders stay static, on no body, as before: to queries and contacts the level has+ no body (`hit.object` is `engineColliders`, `hit.body` undefined). Scene code cannot move the anchor (`pose` refused);+ a query's `skip` of it skips nothing (it has no collider; the level's colliders are not a body's to skip). An earlier+ draft hung the level's colliders on the fixed body instead, which made Rapier sum the body's colliders' mass+ properties on every edit (O(colliders): a tick after a small carve grew from 0.03 to 1.2 ms over 64 to 10,000 level+ colliders, and an explosion's frame took 26 s before a special case hid it); with the anchor the tick after a carve+ is main's, flat (0.02-0.05 ms at 64 to 10,000 colliders), and no special case is left.+- **A joint belongs to the material at its anchor.** Each joint on a voxel body or on the level is held by the cell its+ anchor is in (or the nearest solid of its 26 neighbours): cut so that the cell is in a part cut off, the joint moves+ onto that part's body (the same joint, its anchor where it was in the world); the cell carved, in debris, or its body+ carved away whole, retired, fallen or taken out by the world (past its edge), the joint breaks. The engine reports+ both (`joint_changes`): a moved joint's `bodyA` (or `bodyB`) becomes the part's `VoxelBody` and its `anchorA` (or+ `anchorB`) the same point in the part's frame, so a rope drawn from them follows and a body of the joint made anew+ joins it to the part; a broken one has `joint.broken` true and a "broken" event (every joint of a batch is marked+ before any event is dispatched; a listener that throws does not stop the rest), and is not made again until it leaves+ the scene. The engine finds a body's joints on the body (Rapier's joint graph), a carve's joints by the cells it took+ (a level carve looks only at joints within a cell of what it cleared): costs go with what an edit touches, not with+ the joints in the world (40,000 joints moved with a cut part: 8-10 ms; before, 6 s and more).+- **The blast.** An explosion (`voxelExplode`, `voxelEdit` "explode", `Explosions.explode`) pushes every dynamic body+ within 3 radii (voxel bodies, the parts it just cut loose, scene code's bodies) away from its centre, through each+ one's centre of mass (no turn, as the industry's radial impulse by default):+ J = push x r x min(1, (r / d)²) x (1 - (d / 3r)²)² x A, with d the distance from the centre to the body's box (0+ inside) and A its box's cross-section across the direction. r is the radius the carve took (at most `MAX_RADIUS`, 128+ voxels: a 600 m explosion pushes as far as the 12.8 m one it carves). `push` defaults to 400 N s / m² per m of radius+ (a 1 m blast throws a 100 kg, 1 m crate whose face is 1 m away at 3.16 m/s), 0 to 10,000, 0 none; out of range+ refused before anything changes. A light, broad body flies faster than a heavy compact one (the impulse goes with+ area, not mass).+- **The debris' kick.** The parts an explosion itself cuts loose also leave at a speed of their own, whatever their+ mass: push x 0.02 m/s (8 m/s at the default push) x min(1, (r / d)²) x (1 - (d / 3r)²)², the same fall-off, added to+ the push's, a body's whole change at most 30 m/s (what the solver and CCD follow). A charge throws what it breaks off+ at a speed of the charge's (as in the Gurney model of fragments: set by the charge and what holds it, not by each+ fragment's size); by area+ alone a 1 m³ chunk of stone (2,400 kg) took 0.1 m/s and stayed where it was cut. `push` 0: neither. On the+ benchmark level (`tools/bench-voxel-fire.ts --only cost --scenario topple | sustained`, against the push alone): a+ tree a 0.6 m explosion cuts loose leaves at 6.5-8.2 m/s (0.2-4.7), a part of a wall a 1 m one cuts loose at 7.9+ (0.75-1.24; the run's top speed 7.9 for 3.06); frame times within run-to-run spread. The level's 4 m explosions (the+ crater on the road, the wall spots of `singles`) cut nothing loose: there is no debris for them to kick. Only +, -, x, /+ and square roots: the same bits natively, in parallel and in wasm32. **Not shielded** (decision 4): a body behind a+ wall is pushed too; one voxel ray per body would shield (ROADMAP Open).++Checks: physics-core `joints_change_in_place`, `a_blast_pushes_by_area_and_distance`,+`a_blast_kicks_its_debris_whatever_their_mass`, `a_bodys_joints_are_its_own`, `the_anchor_and_the_engines_joints`; the+renderer's `the_level_has_an_anchor_that_joints_hold_to`, `joints_follow_the_cells_their_anchors_are_in`,+`an_explosion_pushes_the_bodies_near_it`, `an_explosion_kicks_its_debris_and_reaches_what_it_carves`; the binding's+joint, moved and broken-joint tests (the engine faked), and test-render's `voxel/joint-moved` and+`voxel/joint-moved-body` (the binding on the real engine); recorded hashes with a blast, its kick and an in-place joint+change (physics-core's script) and with a pushing explosion and one that cuts a body in two (the voxel bodies' script):+native = parallel = wasm32 = recorded; `physics_fuzz` with `joint_set` (and refused fields), joints to the level, the+anchor among every call's bodies (`pose` refused, the anchor checked unmoved), the joint reports and pushes (sane and+wild).+### Temporary ways round on the engine's shared paths`Explosions` (step 10 b) works round six faults of the shared renderer, in its own code, until they are fixeddiff --git a/games/voxel-level/level-destruction.game.ts b/games/voxel-level/level-destruction.game.tsindex 9766c7c..1497f77 100644--- a/games/voxel-level/level-destruction.game.ts+++ b/games/voxel-level/level-destruction.game.ts@@ -239,12 +239,21 @@ export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: boolecloud.position.set(cx, cy + 5, cz + 21);cloud.scale.set(22, 14, 36);}+ // (With physics: the voxel bodies' speeds just after an explosion, its blast's push and its debris' kick included:+ // their top speed, and of those moving faster than 0.1 m/s how many and their median and 90th percentile: step 10 c1.)+ const speedsNow = () => {+ if (!physics) return {};+ const v = voxelBodies().map((x) => x.getLinearVelocity().length());+ const moving = v.filter((x) => x > 0.1).sort((a, b) => a - b);+ const at = (q: number) => +(moving[Math.floor(moving.length * q)] ?? 0).toFixed(2);+ return { fastest: +Math.max(0, ...v).toFixed(2), speeds: { n: moving.length, p50: at(0.5), p90: at(0.9) } };+ };const fire = (r: number, spot?: number) => {const [x, y, z] = at[(spot ?? next++) % at.length];const e = boom ? boom.explode(x, y, z, r, now) : voxelExplode(x, y, z, r);const thrown = flying ? flying.spawn(voxelDebris(), [x, y, z]) : dust ? dust.spawn(voxelDebris(), [x, y, z]) : 0;cloud?.puff([x, y + 0.3 * r, z], 0.8 * r + 0.3, { density: 0.9, temperature: 1, push: 1.2 });- console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r, ...e, ...(flying ? { thrown, debris: flying.live } : dust ? { thrown } : {}), ...(boom ? { burning: boom.stats.burning, lit: boom.stats.lit } : {}) })}`);+ console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r, ...e, ...(flying ? { thrown, debris: flying.live } : dust ? { thrown } : {}), ...(boom ? { burning: boom.stats.burning, lit: boom.stats.lit } : {}), ...speedsNow() })}`);};return defineGame<State>({state: { scenario: null, started: 0 },@@ -288,7 +297,7 @@ export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: booleif (b.batches > 0 || (b.settled ?? 0) > 0) console.log(`batch ${JSON.stringify(b)}`);if (physics && frames % 30 === 0) {const bodies = voxelBodies();- if (bodies.length > 0 || hadBodies) console.log(`bodies ${JSON.stringify({ frame: frames, n: bodies.length, asleep: bodies.filter((x) => x.asleep).length, voxels: bodies.reduce((n, x) => n + x.voxels, 0), largest: bodies.reduce((n, x) => Math.max(n, x.voxels), 0) })}`);+ if (bodies.length > 0 || hadBodies) console.log(`bodies ${JSON.stringify({ frame: frames, n: bodies.length, asleep: bodies.filter((x) => x.asleep).length, voxels: bodies.reduce((n, x) => n + x.voxels, 0), largest: bodies.reduce((n, x) => Math.max(n, x.voxels), 0), fastest: +bodies.reduce((n, x) => Math.max(n, x.getLinearVelocity().length()), 0).toFixed(2) })}`);hadBodies = bodies.length > 0;}const s = f.state.scenario;@@ -319,7 +328,7 @@ export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: booleconst [x, y, z] = trunks[k];const e = voxelExplode(x, y + 0.8, z, 0.6);const thrown = flying ? flying.spawn(voxelDebris(), [x, y + 0.8, z]) : dust ? dust.spawn(voxelDebris(), [x, y + 0.8, z]) : 0;- console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r: 0.6, ...e, ...(flying || dust ? { thrown } : {}) })}`);+ console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r: 0.6, ...e, ...(flying || dust ? { thrown } : {}), ...speedsNow() })}`);}} else if (s === "fell") {if (t >= 1 && last !== 0) {diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.tsindex 25aaa65..8637b55 100644--- a/packages/scene/src/core.ts+++ b/packages/scene/src/core.ts@@ -160,12 +160,16 @@ export function usePhysicsEngine(e: PhysicsEngine): void {/*** @internal The engine's own bodies as objects (`@threert/voxel` registers its voxel bodies): the object of an engine* body id, the engine body an object stands for (joints take it), and a call once a frame when the binding delivers- * the physics events, which says whether any of them listens for contacts.+ * the physics events, which says whether any of them listens for contacts. `epoch`: a number that changes whenever+ * what `bodyOf` answers may have (the level's anchor body made anew): the binding then looks at its joints again. (A+ * joint the engine moves onto another body is not an epoch: the engine reports it, `joint_changes`, and the binding+ * changes the joint's `bodyA` / `anchorA` or `bodyB` / `anchorB`.)*/export interface EngineBodies {object(body: number): Object3D | undefined;bodyOf(o: Object3D): number | undefined;frame(): boolean;+ epoch?(): number;}let engineBodies: EngineBodies | null = null;@@ -801,7 +805,9 @@ export interface JointParameters {* A joint between two objects with bodies: an object itself, so it holds while it is in the scene (`scene.add(joint)`)* and both its objects are, and lets go when it is removed. It joins the objects as they are turned when it is made (a* door that stands open stays open; its anchors are pulled together if they are apart). After changing one that is in- * the scene, set `needsUpdate`.+ * the scene, set `needsUpdate`: its parameters (limits, motor, a rope's length) change where it is, the same joint (a+ * motor set every frame is cheap and keeps the joint's frames); a change of its bodies, anchors or axis makes it anew,+ * joined as the bodies are turned then.*/export class Joint extends Object3D {readonly isJoint = true;@@ -810,6 +816,14 @@ export class Joint extends Object3D {bodyB: Object3D | null;readonly anchorA = new Vector3();readonly anchorB = new Vector3();+ /**+ * True once the engine let go of it (a "broken" event too): a joint to a voxel body or to the voxel level belongs to+ * the material at its anchor, and that material was carved away, or the voxel body went. It stays let go of until it+ * is taken out of the scene (and may be added again, joined anew). When that material is cut off instead (a part+ * that comes loose), the joint goes with it: the engine moves it, and `bodyA` (or `bodyB`) becomes that part's voxel+ * body, `anchorA` (or `anchorB`) the same point in the part's frame. A rope drawn from `bodyA` and `anchorA` follows.+ */+ broken = false;constructor(bodyA?: Object3D, bodyB?: Object3D, params: JointParameters = {}) {super();this.bodyA = bodyA ?? null;diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.tsindex 629cee3..1e172f9 100644--- a/packages/scene/src/engine.ts+++ b/packages/scene/src/engine.ts@@ -18,6 +18,9 @@ import { BoxGeometry, BufferGeometry, CapsuleGeometry, SphereGeometry } from "./import { Matrix4, Quaternion, Vector3 } from "./math.ts";import { ENGINE_IDS, engineColliders } from "./raycaster.ts";+/** A joint's state in the binding once the engine let go of it (`Joint.broken`). */+const BROKEN = "broken";+export type Vec2 = [number, number];export type Vec3 = [number, number, number];export type Quat = [number, number, number, number];@@ -358,9 +361,13 @@ export class SceneBinding {private readonly freeSlots: number[] = [];private bodies = 0;private contactBodies = 0;- private readonly joints = new Map<Joint, { id: number; key: string } | null>();+ private readonly joints = new Map<Joint, { id: number; key: string; shape: string } | null>();/** A joint or a body came, went or changed: the joints are looked at again. */private jointsDirty = false;+ /** Joints made to one of the engine's bodies (a voxel body, the voxel level): the engine may let go of them. */+ private readonly engineJoints = new Set<Joint>();+ /** The engine bodies' `epoch` at the last look at the joints. */+ private engineEpoch = 0;/** The first body of this sync that could not be made: thrown when the sync is done (the scene stays bound). */private bodyError: unknown = null;/** Objects with bodies under a parent scaled anew in this sync: checked once every transform is sent. */@@ -760,8 +767,11 @@ export class SceneBinding {private dropJoint(j: Joint): void {const bj = this.joints.get(j);- if (bj) this.engine.physics("remove", { joint: bj.id });+ // (A broken one is already gone from the world; out of the scene, it may be added again, joined anew.)+ if (bj && bj.key !== BROKEN) this.engine.physics("remove", { joint: bj.id });this.joints.delete(j);+ this.engineJoints.delete(j);+ j.broken = false;}/** The collider of an object's body: the engine's shape description and where it sits in the body. */@@ -813,36 +823,42 @@ export class SceneBinding {stats.updated++;}// A joint holds while it and both its objects' bodies are in the scene; whatever it was made from changing (a body- // made anew included) makes it anew.+ // made anew included) makes it anew. (The engine's bodies changing what stands for what: looked at again too.)+ // (What the engine did to the joints since the last look, during the frame script too, first: one it moved onto a+ // part cut off names that part now, and is not remade from what it named before; one let go of is not to be changed+ // or remade here; one whose voxel body went is broken, not merely without a body.)+ if (this.engineJoints.size) this.takeJointChanges();+ const engine = getEngineBodies();+ const epoch = engine?.epoch?.() ?? 0;+ if (epoch !== this.engineEpoch) {+ this.engineEpoch = epoch;+ this.jointsDirty = true;+ }const joints = this.jointsDirty ? this.joints : [];this.jointsDirty = false;- // (An object that stands for one of the engine's bodies, a voxel body, is taken as that body: its anchor is in the- // body's own frame, unscaled.)- const engine = getEngineBodies();- const bodyOf = (o: Object3D | null | undefined): { id: number; scale: readonly number[] } | null | undefined => {- if (!o) return undefined;- const id = engine?.bodyOf(o);- return id !== undefined ? { id, scale: [1, 1, 1] } : this.objects.get(o)?.body;- };for (const [j, bj] of joints) {- const a = bodyOf(j.bodyA), b = bodyOf(j.bodyB);- let key = "";- let desc: Record<string, unknown> | null = null;- if (a && b) {- const [sa, sb] = [a.scale, b.scale];- desc = {- ...j.jointDesc(), a: a.id, b: b.id,- anchor1: [j.anchorA.x * sa[0], j.anchorA.y * sa[1], j.anchorA.z * sa[2]], anchor2: [j.anchorB.x * sb[0], j.anchorB.y * sb[1], j.anchorB.z * sb[2]],- };- key = JSON.stringify(desc);- }+ const { a, b, desc, key, shape } = this.jointDescOf(j);if (key === (bj?.key ?? "")) continue;+ // (A joint the engine let go of stays let go of until it leaves the scene: `broken`.)+ if (bj?.key === BROKEN) continue;+ if (bj && desc && shape === bj.shape) {+ const { a: _a, b: _b, anchor1: _a1, anchor2: _a2, axis: _x, ...params } = desc;+ this.engine.physics("joint_set", { id: bj.id, ...params });+ this.joints.set(j, { id: bj.id, key, shape });+ stats.updated++;+ continue;+ }if (bj) this.engine.physics("remove", { joint: bj.id });if (desc) {const id = this.nextBody++;this.engine.physics("joint", { id, ...desc });- this.joints.set(j, { id, key });- } else this.joints.set(j, null);+ this.joints.set(j, { id, key, shape });+ if (a!.id >= ENGINE_IDS || b!.id >= ENGINE_IDS) this.engineJoints.add(j);+ else this.engineJoints.delete(j);+ } else {+ this.joints.set(j, null);+ this.engineJoints.delete(j);+ }stats.updated++;}for (const c of takePhysicsCommands()) {@@ -856,6 +872,83 @@ export class SceneBinding {if (this.bodies) physicsStepped();}+ /**+ * A joint as the engine takes it: its bodies (an object that stands for one of the engine's bodies, a voxel body or+ * the voxel level, is taken as that body: its anchor is in the body's own frame, unscaled; the level's frame is the+ * world's), its description, `key` (all of it) and `shape` (what makes it this joint: its kind, bodies, anchors and+ * axis; the rest, limits, motor and a rope's length, are its parameters, changed where it is: `joint_set`). No+ * description while either body is missing.+ */+ private jointDescOf(j: Joint): { a?: { id: number }; b?: { id: number }; desc: Record<string, unknown> | null; key: string; shape: string } {+ const engine = getEngineBodies();+ const bodyOf = (o: Object3D | null | undefined): { id: number; scale: readonly number[] } | null | undefined => {+ if (!o) return undefined;+ const id = engine?.bodyOf(o);+ return id !== undefined ? { id, scale: [1, 1, 1] } : this.objects.get(o)?.body;+ };+ const a = bodyOf(j.bodyA), b = bodyOf(j.bodyB);+ if (!a || !b) return { desc: null, key: "", shape: "" };+ const [sa, sb] = [a.scale, b.scale];+ const desc: Record<string, unknown> = {+ ...j.jointDesc(), a: a.id, b: b.id,+ anchor1: [j.anchorA.x * sa[0], j.anchorA.y * sa[1], j.anchorA.z * sa[2]], anchor2: [j.anchorB.x * sb[0], j.anchorB.y * sb[1], j.anchorB.z * sb[2]],+ };+ const { limits: _l, motor: _m, length: _n, ...rest } = desc;+ return { a, b, desc, key: JSON.stringify(desc), shape: JSON.stringify(rest) };+ }++ /**+ * What the engine did to the joints since the last call (one engine call), in this order:+ * - moved: a joint whose anchor's material went into a part cut off is on that part's body now: its `bodyA` (or+ * `bodyB`) is that part's object and its `anchorA` (or `anchorB`) the point in it, where it was in the world (the+ * same joint in the engine: nothing is sent for it);+ * - broken: one whose anchor's material was carved away, or whose engine body went: `broken`, then a "broken" event+ * on each. Every one is marked before any event: a listener that throws does not leave the rest unmarked; the+ * events after it are still dispatched, and the first error is thrown once they have been.+ */+ private takeJointChanges(): void {+ const c = JSON.parse(this.engine.physics("joint_changes", {})) as { moved?: { joint: number; end: "a" | "b"; body: number; anchor: [number, number, number] }[]; broken?: number[] } | null;+ if (!c?.moved?.length && !c?.broken?.length) return;+ const byId = new Map<number, Joint>();+ for (const j of this.engineJoints) {+ const bj = this.joints.get(j);+ if (bj) byId.set(bj.id, j);+ }+ for (const m of c.moved ?? []) {+ const j = byId.get(m.joint);+ const o = getEngineBodies()?.object(m.body);+ if (!j || !o) continue;+ if (m.end === "a") {+ j.bodyA = o;+ j.anchorA.set(m.anchor[0], m.anchor[1], m.anchor[2]);+ } else {+ j.bodyB = o;+ j.anchorB.set(m.anchor[0], m.anchor[1], m.anchor[2]);+ }+ // (What the binding holds for it is the engine's joint as it is now: not sent again.)+ const { key, shape } = this.jointDescOf(j);+ if (key) this.joints.set(j, { id: m.joint, key, shape });+ }+ const broken: Joint[] = [];+ for (const id of c.broken ?? []) {+ const j = byId.get(id);+ if (!j) continue;+ this.joints.set(j, { id: -1, key: BROKEN, shape: BROKEN });+ this.engineJoints.delete(j);+ j.broken = true;+ broken.push(j);+ }+ let error: unknown = null;+ for (const j of broken) {+ try {+ j.dispatchEvent({ type: "broken", target: j });+ } catch (e) {+ error ??= e;+ }+ }+ if (error !== null) throw error;+ }+/*** The contacts since the last call, to their listeners: "contactstart" / "contactend" on each of the two objects* (`other`: the other one), then "contacts" on the scene with the whole batch (`contacts`: { a, b, started } in the@@ -865,6 +958,7 @@ export class SceneBinding {*/deliverPhysicsEvents(): void {if (this.bodies) this.takeFaults();+ if (this.engineJoints.size) this.takeJointChanges();// (The engine's own bodies' events first: voxel bodies gone; and whether any of them listens for contacts.)const engineListens = getEngineBodies()?.frame() ?? false;if (!this.contactBodies && !engineListens) return;diff --git a/packages/scene/test/physics.test.ts b/packages/scene/test/physics.test.tsindex 8a0eae2..916c44a 100644--- a/packages/scene/test/physics.test.ts+++ b/packages/scene/test/physics.test.ts@@ -368,11 +368,26 @@ test("a joint holds while it and both its objects are in the scene", () => {assert.deepEqual(made[2][1], { type: "revolute", axis: [0, 1, 0], limits: [-1.5, 1.5], motor: { velocity: 1, maxForce: 50 }, a: 1, b: 2, anchor1: [0.1, 0, 0], anchor2: [-1, 0, 0], id: 3 });binding.sync();assert.deepEqual(physics(), []);- // Changed in the scene: made anew.+ // Its parameters changed (motor, limits): changed where it is, the same joint (its frames not taken anew).+ hinge.motor = { velocity: -2, maxForce: 80 };+ hinge.limits = [-1, 1];+ hinge.needsUpdate = true;+ binding.sync();+ // (Only what may change: its bodies, anchors and axis are what make it this joint, and the engine refuses them.)+ assert.deepEqual(physics(), [["joint_set", { type: "revolute", limits: [-1, 1], motor: { velocity: -2, maxForce: 80 }, id: 3 }]]);hinge.motor = null;hinge.needsUpdate = true;binding.sync();- assert.deepEqual(physics().map((c) => [c[0], c[1].joint ?? c[1].motor]), [["remove", 3], ["joint", undefined]]);+ assert.deepEqual(physics().map((c) => [c[0], c[1].id, c[1].motor]), [["joint_set", 3, undefined]]);+ // What makes it this joint changed (its axis, an anchor): made anew.+ hinge.axis.set(0, 0, 1);+ hinge.needsUpdate = true;+ binding.sync();+ assert.deepEqual(physics().map((c) => [c[0], c[1].joint ?? c[1].id]), [["remove", 3], ["joint", 4]]);+ hinge.anchorA.set(0.1, 0.5, 0);+ hinge.needsUpdate = true;+ binding.sync();+ assert.deepEqual(physics().map((c) => [c[0], c[1].joint ?? c[1].id]), [["remove", 4], ["joint", 5]]);// The door's body made anew: so is the joint, on the new body.door.physics = { type: "dynamic", density: 300 };binding.sync();diff --git a/packages/voxel/src/explosions.ts b/packages/voxel/src/explosions.tsindex b7fbfcb..331405d 100644--- a/packages/voxel/src/explosions.ts+++ b/packages/voxel/src/explosions.ts@@ -9,7 +9,7 @@// follow the fireball's age, from a table measured against the offline renderer (`FIRE_LIGHT`; tools/bench-voxel-fire.ts// --only calibrate).import { Fireball, Group, PointLight, type Object3D } from "@threert/scene";-import { voxelExplode, type VoxelEdit } from "./native.ts";+import { MAX_PUSH, voxelExplode, type VoxelEdit } from "./native.ts";/** The most fireballs a pool may have: the kernel draws at most 32 volumes (`MAX_MEDIA`, renderer/src/scene.rs; a* scene with more is refused). */@@ -234,12 +234,13 @@ export class Explosions extends Group {return k;}- /** `voxelExplode(x, y, z, r)` and `fire([x, y, z], r, time)`; the arguments are checked first (nothing happens if- * they are refused). Returns the voxel edit's result. */- explode(x: number, y: number, z: number, r: number, time: number): VoxelEdit | { queued: true } {+ /** `voxelExplode(x, y, z, r, { push })` (its blast pushes the bodies near it) and `fire([x, y, z], r, time)`; the+ * arguments are checked first (nothing happens if they are refused). Returns the voxel edit's result. */+ explode(x: number, y: number, z: number, r: number, time: number, o: { push?: number } = {}): VoxelEdit | { queued: true } {check("Explosions.explode", [x, y, z], r, time);+ if (o.push !== undefined) within("Explosions.explode: push", o.push, 0, MAX_PUSH);this.inWorldFrame("Explosions.explode");- const e = voxelExplode(x, y, z, r);+ const e = voxelExplode(x, y, z, r, o);this.fire([x, y, z], r, time);return e;}diff --git a/packages/voxel/src/native.ts b/packages/voxel/src/native.tsindex e930369..cfe9212 100644--- a/packages/voxel/src/native.ts+++ b/packages/voxel/src/native.ts@@ -12,7 +12,7 @@// `Raycaster.intersectPhysics`, shape casts and the game's own bodies meet it. `physics: false` on the level turns// all of it off (no collider; loose parts fall straight down until they rest, as before); `collide: false` on an// object leaves that object without a collider.-import { bindBody, Object3D, type ObjectEvent, type PhysicsDesc, physicsQuery, setEngineBodies, unbindBody, usePhysicsEngine, Vector3 as Vector3Ctor, type Vector3 } from "@threert/scene";+import { bindBody, engineColliders, Object3D, type ObjectEvent, type PhysicsDesc, physicsQuery, setEngineBodies, unbindBody, usePhysicsEngine, Vector3 as Vector3Ctor, type Vector3 } from "@threert/scene";export type Hardness = "soft" | "medium" | "hard" | "indestructible";@@ -340,11 +340,30 @@ function refresh(): void {}}+/** The body that stands for the voxel level in joints (the world's anchor: fixed, no collider; none before the level is+ * loaded); the epoch moves when it changes. */+let level: number | undefined;+let epoch = 0;+function levelBody(): number | undefined {+ const id = engine()?.voxelLevelBody?.();+ const now = id !== undefined && id >= 0 ? id : undefined;+ if (now !== level) {+ level = now;+ epoch++;+ }+ return level;+}+/** The registry, known to `@threert/scene` (hits, joints, the frame's events). */function register(): void {setEngineBodies({object: (body) => registry.get(body) ?? recentlyGone.get(body)?.o ?? (body >= 2 ** 30 ? (refresh(), registry.get(body) ?? recentlyGone.get(body)?.o) : undefined),- bodyOf: (o) => (o instanceof VoxelBody && !o.gone ? o.body : undefined),+ // (The voxel level is `engineColliders`: in a joint, the world's anchor, once the level is loaded.)+ bodyOf: (o) => (o instanceof VoxelBody && !o.gone ? o.body : o === engineColliders ? levelBody() : undefined),+ epoch: () => {+ levelBody();+ return epoch;+ },frame: () => {// (Those that went before the last frame's events have had their contacts' ends delivered.)frameCount++;@@ -372,6 +391,7 @@ interface NativeEngine {voxelBodyEdit?: (body: number, d: object) => string;voxelContacts?: (body: number, on: boolean) => void;voxelGone?: () => string;+ voxelLevelBody?: () => number;physics?: (op: string, args: object) => string;physicsPoses?: () => Float32Array;}@@ -404,9 +424,22 @@ function edit(d: object): VoxelEdit | { queued: true } {* share of the radius. What it cuts loose falls (`voxelFrame`). Called in setup, before the level is loaded, it is done* once it is (with the `voxelFrame` calls made in setup after it) and returns `{ queued: true }`: the live view and the* offline render start from the same world.+ *+ * Its blast pushes every dynamic body within 3 radii (voxel bodies, the parts it cuts loose, scene code's bodies) away+ * from its centre, through each one's centre of mass: `push` N s / m² per m of radius at the blast (default 400: a 1 m+ * blast throws a 100 kg crate 1 m away at about 3 m/s), falling off with the distance squared to 0 at the reach, times+ * the body's area facing it; at most 30 m/s a body. `push: 0`: none. 0 to 10,000; otherwise refused (RangeError)+ * before anything changes. Walls do not shield (docs/VOXEL.md, "The blast").*/-export function voxelExplode(x: number, y: number, z: number, radius: number): VoxelEdit | { queued: true } {- return edit({ op: "explode", sphere: [x, y, z, radius] });+export function voxelExplode(x: number, y: number, z: number, radius: number, o: { push?: number } = {}): VoxelEdit | { queued: true } {+ return edit({ op: "explode", sphere: [x, y, z, radius], ...(o.push === undefined ? {} : { push: checkPush(o.push) }) });+}++/** The largest push an explosion takes (renderer/src/voxel.rs `MAX_PUSH`). */+export const MAX_PUSH = 10000;+function checkPush(p: unknown): number {+ if (typeof p !== "number" || !Number.isFinite(p) || p < 0 || p > MAX_PUSH) throw new RangeError(`voxelExplode: push must be a number from 0 to ${MAX_PUSH}`);+ return p;}/** A cut: every voxel inside the shape removed, whatever its hardness (but the indestructible). A saw is a `box`, adiff --git a/packages/voxel/test/explosions.test.ts b/packages/voxel/test/explosions.test.tsindex 656d9ac..1cb605b 100644--- a/packages/voxel/test/explosions.test.ts+++ b/packages/voxel/test/explosions.test.ts@@ -197,7 +197,12 @@ test("explode: the voxel explosion, then the fire; dispose takes the pool out",scene.add(x);assert.deepEqual(x.explode(1, 2, 3, 0.5, 4), { removed: 12 });assert.deepEqual(calls, [{ op: "explode", sphere: [1, 2, 3, 0.5] }]);- assert.equal(x.stats.fired, 1);+ // Its blast's push (step 10 c1): passed on; out of range refused before the voxel call.+ x.explode(20, 2, 3, 0.5, 4.1, { push: 0 });+ assert.deepEqual(calls[1], { op: "explode", sphere: [20, 2, 3, 0.5], push: 0 });+ for (const push of [-1, NaN, Infinity, 1e9]) assert.throws(() => x.explode(0, 0, 0, 1, 4.2, { push }), RangeError, String(push));+ assert.equal(calls.length, 2);+ assert.equal(x.stats.fired, 2);assert.equal(x.fireballs[0].position.x, 1);assert.deepEqual(x.fireballs[0].customData, [4, 0, 0, 0]);x.dispose();@@ -205,7 +210,7 @@ test("explode: the voxel explosion, then the fire; dispose takes the pool out",assert.equal(x.children.length, 0);assert.throws(() => x.fire([0, 0, 0], 1, 5), /disposed/);assert.throws(() => x.explode(0, 0, 0, 1, 5), /disposed/);- assert.equal(calls.length, 1, "no voxel call after dispose");+ assert.equal(calls.length, 2, "no voxel call after dispose");} finally {g.__engine = before;}diff --git a/packages/voxel/test/voxel.test.ts b/packages/voxel/test/voxel.test.tsindex e1ef864..4736785 100644--- a/packages/voxel/test/voxel.test.ts+++ b/packages/voxel/test/voxel.test.ts@@ -150,6 +150,43 @@ test("a voxel body is an object: the same one for the same body, with the physic}});+test("a rope to the level (`engineColliders`): made on the world's anchor once the level is loaded, its anchor in the world's frame", async () => {+ const { voxelLevel } = await import("../src/native.ts");+ const { engineColliders, Mesh, BoxGeometry, PerspectiveCamera, RopeJoint, Scene, SceneBinding, Vector3 } = await import("@threert/scene");+ const engine = await voxelEngine();+ let levelBody = -1;+ (engine as unknown as { voxelLevelBody: () => number }).voxelLevelBody = () => levelBody;+ const g = globalThis as { __engine?: object };+ const before = g.__engine;+ g.__engine = engine;+ try {+ voxelLevel({ route: "mesh", palette: [], objects: [] });+ const scene = new Scene(), camera = new PerspectiveCamera();+ const binding = new SceneBinding(engine, scene, camera);+ const lamp = new Mesh(new BoxGeometry(0.3, 0.3, 0.3));+ lamp.physics = "dynamic";+ const rope = new RopeJoint(engineColliders, lamp, { length: 2, anchorA: new Vector3(4, 6, 1) });+ scene.add(camera, lamp, rope);+ binding.sync();+ assert.deepEqual(engine.physicsCalls().filter((c) => c[0] === "joint"), [], "no level yet: no joint");+ // The level loaded (its body made): the next sync makes the joint on it.+ levelBody = 2 ** 30 + 1;+ engine.calls.length = 0;+ binding.sync();+ const joint = engine.physicsCalls().find((c) => c[0] === "joint");+ assert.ok(joint, "made once the level is there");+ assert.deepEqual([joint![1].a, joint![1].type, joint![1].length, joint![1].anchor1], [levelBody, "rope", 2, [4, 6, 1]]);+ // Its length changed: in place.+ rope.length = 1.5;+ rope.needsUpdate = true;+ engine.calls.length = 0;+ binding.sync();+ assert.deepEqual(engine.physicsCalls().filter((c) => /^joint(_set)?$/.test(c[0])).map((c) => [c[0], c[1].length]), [["joint_set", 1.5]]);+ } finally {+ g.__engine = before;+ }+});+test("a voxel body in the scene's physics: a ray's hit has its object, a joint takes it, its contacts arrive, and it goes with a reason", async () => {const { voxelLevel, voxelBodies, VoxelBody } = await import("../src/native.ts");const { BoxGeometry, engineColliders, FixedJoint, Mesh, PerspectiveCamera, Raycaster, Scene, SceneBinding, Vector3 } = await import("@threert/scene");@@ -302,3 +339,212 @@ test("a voxel body the engine took out before the objects noticed: every call dog.__engine = before;}});++// (Last: its frame of the physics events retires the earlier tests' bodies, whose ids the tests share.)+test("a joint the engine let go of: broken, a \"broken\" event, not made again until it leaves the scene", async () => {+ const { voxelLevel } = await import("../src/native.ts");+ const { engineColliders, Mesh, BoxGeometry, PerspectiveCamera, RopeJoint, Scene, SceneBinding, Vector3 } = await import("@threert/scene");+ const engine = await voxelEngine();+ (engine as unknown as { voxelLevelBody: () => number }).voxelLevelBody = () => 2 ** 30 + 1;+ const g = globalThis as { __engine?: object };+ const before = g.__engine;+ g.__engine = engine;+ try {+ voxelLevel({ route: "mesh", palette: [], objects: [] });+ const scene = new Scene(), camera = new PerspectiveCamera();+ const binding = new SceneBinding(engine, scene, camera);+ const lamp = new Mesh(new BoxGeometry(0.3, 0.3, 0.3));+ lamp.physics = "dynamic";+ const rope = new RopeJoint(engineColliders, lamp, { length: 2, anchorA: new Vector3(4, 6, 1) });+ scene.add(camera, lamp, rope);+ binding.sync();+ const id = engine.physicsCalls().find((c) => c[0] === "joint")![1].id as number;+ const events: unknown[] = [];+ rope.addEventListener("broken", (e) => events.push(e.type));+ engine.answers.joint_changes = { moved: [], broken: [id] };+ binding.deliverPhysicsEvents();+ assert.deepEqual([rope.broken, events], [true, ["broken"]]);+ engine.answers.joint_changes = { moved: [], broken: [] };+ // Changed: still let go of (no joint, no joint_set).+ rope.length = 1;+ rope.needsUpdate = true;+ engine.calls.length = 0;+ binding.sync();+ assert.deepEqual(engine.physicsCalls().filter((c) => /^joint(_set)?$/.test(c[0]) || c[0] === "remove"), []);+ // Out of the scene (nothing to remove: it is gone) and back: joined anew.+ scene.remove(rope);+ binding.sync();+ assert.deepEqual(engine.physicsCalls().filter((c) => c[0] === "remove"), []);+ assert.equal(rope.broken, false);+ scene.add(rope);+ binding.sync();+ assert.equal(engine.physicsCalls().filter((c) => c[0] === "joint").length, 1);+ } finally {+ g.__engine = before;+ }+});++test("a joint let go of during the frame script: the next sync knows it before a change to it (no joint_set on a gone joint)", async () => {+ const { voxelLevel } = await import("../src/native.ts");+ const { engineColliders, Mesh, BoxGeometry, PerspectiveCamera, RopeJoint, Scene, SceneBinding, Vector3 } = await import("@threert/scene");+ const engine = await voxelEngine();+ (engine as unknown as { voxelLevelBody: () => number }).voxelLevelBody = () => 2 ** 30 + 1;+ const g = globalThis as { __engine?: object };+ const before = g.__engine;+ g.__engine = engine;+ try {+ voxelLevel({ route: "mesh", palette: [], objects: [] });+ const scene = new Scene(), camera = new PerspectiveCamera();+ const binding = new SceneBinding(engine, scene, camera);+ const lamp = new Mesh(new BoxGeometry(0.3, 0.3, 0.3));+ lamp.physics = "dynamic";+ const rope = new RopeJoint(engineColliders, lamp, { length: 2, anchorA: new Vector3(4, 6, 1) });+ scene.add(camera, lamp, rope);+ binding.sync();+ const id = engine.physicsCalls().find((c) => c[0] === "joint")![1].id as number;+ const events: string[] = [];+ rope.addEventListener("broken", (e) => events.push(e.type));+ // The frame script carves the anchor (the engine lets go) and sets the rope's length in the same frame.+ engine.answers.joint_changes = { moved: [], broken: [id] };+ rope.length = 1;+ rope.needsUpdate = true;+ engine.calls.length = 0;+ binding.sync();+ assert.deepEqual(engine.physicsCalls().filter((c) => /^joint(_set)?$/.test(c[0])), [], "no joint_set on the gone joint");+ assert.deepEqual([rope.broken, events], [true, ["broken"]]);+ } finally {+ g.__engine = before;+ }+});+++test("a joint the engine moved onto a part cut off names that part: its body going later does not let go of the joint", async () => {+ const { voxelLevel, voxelBodies } = await import("../src/native.ts");+ const { Mesh, BoxGeometry, PerspectiveCamera, RopeJoint, Scene, SceneBinding, Vector3 } = await import("@threert/scene");+ const engine = await voxelEngine();+ const g = globalThis as { __engine?: object };+ const before = g.__engine;+ g.__engine = engine;+ try {+ voxelLevel({ route: "mesh", palette: [], objects: [] });+ const X = 2 ** 30 + 507, X2 = 2 ** 30 + 511;+ const rec = (body: number, voxels: number) => ({ body, collider: body + 1, voxels, asleep: false, position: [0, 1, 0], rotation: [0, 0, 0, 1] });+ engine.bodies = [rec(X, 300)];+ const [beam] = voxelBodies();+ const scene = new Scene(), camera = new PerspectiveCamera();+ const binding = new SceneBinding(engine, scene, camera);+ const lamp = new Mesh(new BoxGeometry(0.3, 0.3, 0.3));+ lamp.physics = "dynamic";+ const rope = new RopeJoint(beam, lamp, { length: 2, anchorA: new Vector3(0.2, 0.05, 0.2) });+ const events: string[] = [];+ rope.addEventListener("broken", (e) => events.push(e.type));+ scene.add(camera, lamp, rope);+ binding.sync();+ const id = engine.physicsCalls().find((c) => c[0] === "joint")![1].id as number;+ // The engine cuts X: the rope's anchor cell is in the part cut off, X2; it moves the joint there.+ engine.bodies = [rec(X, 160), rec(X2, 140)];+ engine.answers.joint_changes = { moved: [{ joint: id, end: "a", body: X2, anchor: [0.2, 0.35, 0.2] }], broken: [] };+ engine.calls.length = 0;+ binding.deliverPhysicsEvents();+ engine.answers.joint_changes = { moved: [], broken: [] };+ const part = voxelBodies().find((b) => b.body === X2)!;+ assert.equal(rope.bodyA, part, "the joint names the part it is on");+ assert.deepEqual(rope.anchorA.toArray(), [0.2, 0.35, 0.2]);+ // X goes later (retired); then something makes the binding look at its joints (a body added): the joint stays.+ engine.bodies = [rec(X2, 140)];+ engine.gone = [[X, "cap"]];+ const crate = new Mesh(new BoxGeometry(1, 1, 1));+ crate.physics = "dynamic";+ scene.add(crate);+ engine.calls.length = 0;+ binding.deliverPhysicsEvents();+ binding.sync();+ assert.deepEqual(engine.physicsCalls().filter((c) => /^joint(_set)?$/.test(c[0]) || c[1].joint !== undefined), [], "nothing sent for the joint");+ assert.deepEqual([rope.broken, events], [false, []]);+ // A parameter changed: in place, the same joint.+ rope.length = 1;+ rope.needsUpdate = true;+ engine.calls.length = 0;+ binding.sync();+ assert.deepEqual(engine.physicsCalls().filter((c) => /^joint(_set)?$/.test(c[0])).map((c) => [c[0], c[1].id, c[1].length]), [["joint_set", id, 1]]);+ } finally {+ g.__engine = before;+ }+});++test("a joint to the level the engine moved onto a loose part: the lamp's body made anew joins it to that part, not to the level", async () => {+ const { voxelLevel, voxelBodies } = await import("../src/native.ts");+ const { engineColliders, Mesh, BoxGeometry, PerspectiveCamera, RopeJoint, Scene, SceneBinding, Vector3 } = await import("@threert/scene");+ const engine = await voxelEngine();+ (engine as unknown as { voxelLevelBody: () => number }).voxelLevelBody = () => 2 ** 30 + 1;+ const g = globalThis as { __engine?: object };+ const before = g.__engine;+ g.__engine = engine;+ try {+ voxelLevel({ route: "mesh", palette: [], objects: [] });+ const scene = new Scene(), camera = new PerspectiveCamera();+ const binding = new SceneBinding(engine, scene, camera);+ const lamp = new Mesh(new BoxGeometry(0.3, 0.3, 0.3));+ lamp.physics = "dynamic";+ const rope = new RopeJoint(engineColliders, lamp, { length: 2, anchorA: new Vector3(4, 6, 1) });+ scene.add(camera, lamp, rope);+ binding.sync();+ const id = engine.physicsCalls().find((c) => c[0] === "joint")![1].id as number;+ // The level cut under the anchor: its material is a body now, the joint on it.+ const P = 2 ** 30 + 521;+ engine.bodies = [{ body: P, collider: P + 1, voxels: 400, asleep: false, position: [3.8, 4, 0.8], rotation: [0, 0, 0, 1] }];+ engine.answers.joint_changes = { moved: [{ joint: id, end: "a", body: P, anchor: [0.2, 2, 0.2] }], broken: [] };+ binding.deliverPhysicsEvents();+ engine.answers.joint_changes = { moved: [], broken: [] };+ const part = voxelBodies().find((b) => b.body === P)!;+ assert.equal(rope.bodyA, part);+ // The lamp's body made anew: the joint is made anew on the part, at its anchor there.+ lamp.physics = { type: "dynamic", density: 300 };+ engine.calls.length = 0;+ binding.sync();+ const made = engine.physicsCalls().filter((c) => c[0] === "joint");+ assert.deepEqual(made.map((c) => [c[1].a, c[1].anchor1]), [[P, [0.2, 2, 0.2]]]);+ } finally {+ g.__engine = before;+ }+});++test("joints broken in one batch: all are marked before any \"broken\" event; a listener that throws does not stop the others", async () => {+ const { voxelLevel } = await import("../src/native.ts");+ const { engineColliders, Mesh, BoxGeometry, PerspectiveCamera, RopeJoint, Scene, SceneBinding, Vector3 } = await import("@threert/scene");+ const engine = await voxelEngine();+ (engine as unknown as { voxelLevelBody: () => number }).voxelLevelBody = () => 2 ** 30 + 1;+ const g = globalThis as { __engine?: object };+ const before = g.__engine;+ g.__engine = engine;+ try {+ voxelLevel({ route: "mesh", palette: [], objects: [] });+ const scene = new Scene(), camera = new PerspectiveCamera();+ const binding = new SceneBinding(engine, scene, camera);+ const lamp = new Mesh(new BoxGeometry(0.3, 0.3, 0.3));+ lamp.physics = "dynamic";+ const r1 = new RopeJoint(engineColliders, lamp, { length: 2, anchorA: new Vector3(4, 6, 1) });+ const r2 = new RopeJoint(engineColliders, lamp, { length: 2, anchorA: new Vector3(5, 6, 1) });+ scene.add(camera, lamp, r1, r2);+ binding.sync();+ const ids = engine.physicsCalls().filter((c) => c[0] === "joint").map((c) => c[1].id as number);+ const seen: string[] = [];+ r1.addEventListener("broken", () => {+ seen.push(`r1 sees r2 broken: ${r2.broken}`);+ throw new Error("listener");+ });+ r2.addEventListener("broken", () => seen.push("r2"));+ engine.answers.joint_changes = { moved: [], broken: ids };+ assert.throws(() => binding.deliverPhysicsEvents(), /listener/);+ engine.answers.joint_changes = { moved: [], broken: [] };+ assert.deepEqual([r1.broken, r2.broken, seen], [true, true, ["r1 sees r2 broken: true", "r2"]]);+ // Changed afterwards: nothing sent (both are gone), no error.+ r2.length = 1;+ r2.needsUpdate = true;+ engine.calls.length = 0;+ binding.sync();+ assert.deepEqual(engine.physicsCalls().filter((c) => /^joint(_set)?$/.test(c[0]) || c[0] === "remove"), []);+ } finally {+ g.__engine = before;+ }+});diff --git a/renderer/examples/physics_fuzz.rs b/renderer/examples/physics_fuzz.rsindex f0ae3d7..622cd3b 100644--- a/renderer/examples/physics_fuzz.rs+++ b/renderer/examples/physics_fuzz.rs@@ -99,6 +99,8 @@ fn run(seed: u64, iterations: u32, many: bool, shells: u32) -> u32 {}};let (mut edits, mut refused, mut calls_refused, mut most, mut kicks) = (0u32, 0u32, 0u32, 0usize, 0u32);+ let mut broken_seen = 0u32;+ let mut moved_seen = 0u32;let (mut body_edits, mut checked) = (0u32, 0usize);let mut advance = |v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>| {api::physics_advance(ph, v, w, 1.0 / 60.0);@@ -163,31 +165,60 @@ fn run(seed: u64, iterations: u32, many: bool, shells: u32) -> u32 {}5 => {let radius = if wild && r.chance(0.3) { [f64::NAN, f64::INFINITY, -f64::INFINITY, 1e300, -3.0][r.below(5) as usize] } else { r.range(0.2, 2.0) };- let _ = api::voxel_explode(&mut v, &mut w, &mut ph, pos(&mut r, wild), r.range(0.0, 3.0), pos(&mut r, wild) * 0.5, radius);+ // (Its push too, step 10 c1: none, sane, or wild.)+ let push = match r.below(4) { 0 => None, 1 => Some(r.range(0.0, 2000.0)), 2 => Some([f64::NAN, f64::INFINITY, -1.0, 1e9, 1e300][r.below(5) as usize]), _ => Some(10_000.0) };+ let _ = api::voxel_explode(&mut v, &mut w, &mut ph, pos(&mut r, wild), r.range(0.0, 3.0), pos(&mut r, wild) * 0.5, radius, push);}_ => {// Scene code's physics calls, on the voxel bodies too.let list = v.body_list(ph.as_ref().unwrap());let ids: Vec<u64> = list.as_array().unwrap().iter().map(|b| b["body"].as_u64().unwrap()).collect();let cols: Vec<u64> = list.as_array().unwrap().iter().map(|b| b["collider"].as_u64().unwrap()).collect();- let body = if ids.is_empty() || r.chance(0.2) { 1 + r.below(6) } else { ids[r.below(ids.len() as u64) as usize] };+ // (The world's anchor, the voxel level's body, now and then too: `pose` must refuse it, `skip` of it+ // skips nothing, the rest leave a fixed body as it is.)+ let anchor = v.level_body().map(|l| l as u64);+ let body = match anchor {+ Some(a) if r.chance(0.1) => a,+ _ if ids.is_empty() || r.chance(0.2) => 1 + r.below(6),+ _ => ids[r.below(ids.len() as u64) as usize],+ };let big = |r: &mut Rng| if r.chance(0.1) { 1e6 } else { r.range(-300.0, 300.0) };- let (op, args) = match r.below(12) {+ let (op, args) = match r.below(14) {0 => ("impulse", json!({ "body": body, "impulse": [big(&mut r), big(&mut r), big(&mut r)], "point": [r.range(0.0, 12.0), 1.0, 3.0] })),1 => ("velocity", json!({ "body": body, "linvel": [r.range(-1e4, 1e4), r.range(-50.0, 50.0), 0.0], "angvel": [r.range(-1e3, 1e3), 0.0, 0.0] })),2 => ("pose", json!({ "body": body, "position": [pos(&mut r, false), r.range(-300.0, 20.0), 3.0], "rotation": [r.unit(), r.unit(), r.unit(), r.unit() + 0.01] })),3 => ("body", json!({ "id": 1 + r.below(6), "position": [r.range(0.0, 12.0), r.range(1.0, 6.0), 3.0], "kind": (["dynamic", "kinematic", "fixed"][r.below(3) as usize]) })),4 => ("collider", json!({ "id": 10 + r.below(12), "body": body, "shape": { "type": "box", "halfExtents": [r.range(0.05, 2.0), 0.2, 0.2] }, "mass": if r.chance(0.3) { 1e7 } else { 10.0 }, "events": true })),- 5 => ("joint", json!({ "id": 30 + r.below(8), "a": body, "b": if ids.is_empty() { 2 } else { ids[r.below(ids.len() as u64) as usize] }, "type": (["fixed", "revolute", "spherical", "rope", "prismatic"][r.below(5) as usize]), "length": 1.0, "limits": [-0.5, 0.5] })),+ // (Joints to the level's anchor too: step 10 c1.)+ 5 => ("joint", json!({ "id": 30 + r.below(8), "a": if r.chance(0.3) { anchor.unwrap_or(body) } else { body }, "b": if ids.is_empty() { 2 } else { ids[r.below(ids.len() as u64) as usize] }, "type": (["fixed", "revolute", "spherical", "rope", "prismatic"][r.below(5) as usize]), "length": 1.0, "limits": [-0.5, 0.5] })),6 => ("remove", json!({ "body": if r.chance(0.5) { body } else { 1 + r.below(6) }, "collider": if r.chance(0.5) && !cols.is_empty() { cols[0] } else { 10 + r.below(12) }, "joint": 30 + r.below(8) })),7 => ("force", json!({ "body": body, "force": [big(&mut r) * 100.0, 0.0, 0.0], "torque": [0.0, big(&mut r) * 100.0, 0.0] })),8 => ("ray", json!({ "origin": [r.range(0.0, 12.0), 8.0, r.range(0.0, 6.0)], "direction": [r.range(-0.2, 0.2), -1.0, 0.0], "all": r.chance(0.5), "skip": body })),9 => ("target", json!({ "body": body, "position": [1.0, 2.0, 3.0] })),10 => ("contacts", json!({})),+ // What the engine did to the joints (anchors carried off or carved, step 10 c1).+ 12 => ("joint_changes", json!({})),+ // A joint's parameters changed in place (step 10 c1): any kind named, sane or wild numbers.+ 11 => {+ let wild_num = |r: &mut Rng| if r.chance(0.2) { [f64::NAN, f64::INFINITY, -1.0, 1e30, 0.0][r.below(5) as usize] } else { r.range(-3.0, 3.0) };+ let (lo, hi) = (wild_num(&mut r), wild_num(&mut r));+ let mut a = json!({ "id": 30 + r.below(9), "type": (["fixed", "revolute", "spherical", "rope", "prismatic", "weld"][r.below(6) as usize]), "length": wild_num(&mut r), "limits": [lo, hi], "motor": { "velocity": wild_num(&mut r), "damping": wild_num(&mut r) * 1e4, "maxForce": wild_num(&mut r) * 1e3 } });+ // (Now and then naming what makes the joint: refused.)+ if r.chance(0.1) {+ a[["a", "b", "anchor1", "anchor2", "axis"][r.below(5) as usize]] = json!([0.0, 1.0, 0.0]);+ }+ ("joint_set", a)+ }_ => ("overlap", json!({ "shape": { "type": "sphere", "radius": r.range(0.1, 3.0) }, "position": [r.range(0.0, 12.0), 1.0, 3.0] })),};- if ph.as_mut().unwrap().call(&mut w, op, &args).is_err() {- calls_refused += 1;+ match ph.as_mut().unwrap().call(&mut w, op, &args) {+ Err(_) => calls_refused += 1,+ Ok(v) if op == "joint_changes" => {+ broken_seen += v["broken"].as_array().map_or(0, |a| a.len()) as u32;+ moved_seen += v["moved"].as_array().map_or(0, |a| a.len()) as u32;+ }+ Ok(_) if op == "pose" && anchor == Some(body) => panic!("pose of the world's anchor was taken"),+ Ok(_) => {}}}}@@ -212,6 +243,10 @@ fn run(seed: u64, iterations: u32, many: bool, shells: u32) -> u32 {checked += v.check_shells(p).unwrap_or_else(|e| panic!("seed {seed}, iteration {it}: {e}"));}assert_eq!(list.len(), v.bodies(), "seed {seed}, iteration {it}: a voxel body without an engine body");+ // (The world's anchor where it was made, whatever was called on it.)+ if let Some(a) = v.level_body() {+ assert_eq!(p.bridge_ref().engine_pose(a).map(|x| (x.0, x.1)), Some(([0.0; 3], [0.0, 0.0, 0.0, 1.0])), "seed {seed}, iteration {it}: the anchor moved");+ }assert!(list.len() <= MAX_BODIES, "seed {seed}, iteration {it}: {} bodies", list.len());for b in list {let (id, collider, voxels) = (b["body"].as_u64().unwrap() as u32, b["collider"].as_u64().unwrap() as u32, b["voxels"].as_u64().unwrap() as usize);@@ -222,7 +257,7 @@ fn run(seed: u64, iterations: u32, many: bool, shells: u32) -> u32 {}}println!(- "seed {seed}: {iterations} iterations, edits {edits} (refused {refused}), body edits {body_edits}, calls refused {calls_refused}, most bodies {most}, retired {}, shells checked {checked}, kicks {kicks}, hash {:016x}/{:016x}",+ "seed {seed}: {iterations} iterations, edits {edits} (refused {refused}), body edits {body_edits}, calls refused {calls_refused}, joints broken {broken_seen}, moved {moved_seen}, most bodies {most}, retired {}, shells checked {checked}, kicks {kicks}, hash {:016x}/{:016x}",v.retired,v.hash().unwrap_or(0),ph.as_ref().unwrap().hash()diff --git a/renderer/physics-core/src/bridge.rs b/renderer/physics-core/src/bridge.rsindex 0948a99..45f3ee3 100644--- a/renderer/physics-core/src/bridge.rs+++ b/renderer/physics-core/src/bridge.rs@@ -52,6 +52,16 @@ pub struct Bridge {colliders: BTreeMap<u32, ColliderId>,/// The world's collider -> the caller's id of it and of its body.collider_ids: BTreeMap<ColliderId, (u32, Option<u32>)>,+ /// The world's anchor (`engine_anchor`): a fixed body with no collider that joints to the voxel level hold to (the+ /// level's colliders are on no body, as static colliders are). Scene code cannot move it.+ anchor: Option<u32>,+ /// The world's joint -> scene code's id of it (the engine finds its joints by body: `Physics::joints_of`).+ joint_ids: BTreeMap<JointId, u32>,+ /// What the engine did to scene code's joints since the last `joint_changes` call (step 10 c1): the joints it moved+ /// onto another body (their anchor's material went into a part cut off), by id, with where each end is now; and+ /// those it let go of (their anchor's material carved away, or an engine body they held to gone).+ joints_moved: BTreeMap<u32, (u32, bool, [f32; 3])>,+ broken: Vec<u32>,/// The pairs of colliders (the caller's ids, lower first) touching as reported, with their bodies: a start is/// reported once (a collider edited in place, taken out and put back, starts again without having ended), and a/// collider that goes ends its pairs (`ended`; the world's own end events of a collider it no longer has are lost).@@ -86,6 +96,27 @@ pub struct Bridge {/// The most faults "faults" holds until it is called, and "state" remembers.pub const MAX_FAULTS: usize = 1024;+/// A joint's description in a call (`joint`, `joint_set`).+fn joint_desc(a: &Value) -> Result<JointDesc, String> {+ let (anchor1, anchor2) = (vec3(a, "anchor1", [0.0; 3])?, vec3(a, "anchor2", [0.0; 3])?);+ let limits = match &a["limits"] {+ Value::Null => None,+ v => Some(nums::<2>(v).map(|l| Limits { min: l[0], max: l[1] }).ok_or("physics: limits must be [min, max]")?),+ };+ let motor = match &a["motor"] {+ Value::Null => None,+ m => Some(Motor { velocity: num(m, "velocity", 0.0)?, damping: num(m, "damping", 1e4)?, max_force: num(m, "maxForce", f32::MAX)? }),+ };+ Ok(match a["type"].as_str() {+ Some("fixed") => JointDesc::Fixed { anchor1, anchor2 },+ Some("revolute") => JointDesc::Revolute { anchor1, anchor2, axis: vec3(a, "axis", [0.0, 1.0, 0.0])?, limits, motor },+ Some("prismatic") => JointDesc::Prismatic { anchor1, anchor2, axis: vec3(a, "axis", [1.0, 0.0, 0.0])?, limits, motor },+ Some("spherical") => JointDesc::Spherical { anchor1, anchor2 },+ Some("rope") => JointDesc::Rope { anchor1, anchor2, length: num(a, "length", f32::NAN)? },+ other => return Err(format!("physics: joint type {other:?} is none of fixed, revolute, prismatic, spherical, rope")),+ })+}+fn nums<const N: usize>(v: &Value) -> Option<[f32; N]> {let a = v.as_array().filter(|a| a.len() == N)?;let mut out = [0.0f32; N];@@ -142,6 +173,10 @@ impl Default for Bridge {body_ids: BTreeMap::new(),colliders: BTreeMap::new(),collider_ids: BTreeMap::new(),+ anchor: None,+ joint_ids: BTreeMap::new(),+ joints_moved: BTreeMap::new(),+ broken: vec![],touching: BTreeMap::new(),ended: vec![],joints: BTreeMap::new(),@@ -337,26 +372,33 @@ impl Bridge {if self.joints.contains_key(&jid) {return Err(format!("physics: joint {jid} exists"));}- let (anchor1, anchor2) = (vec3(a, "anchor1", [0.0; 3])?, vec3(a, "anchor2", [0.0; 3])?);- let limits = match &a["limits"] {- Value::Null => None,- v => Some(nums::<2>(v).map(|l| Limits { min: l[0], max: l[1] }).ok_or("physics: limits must be [min, max]")?),- };- let motor = match &a["motor"] {- Value::Null => None,- m => Some(Motor { velocity: num(m, "velocity", 0.0)?, damping: num(m, "damping", 1e4)?, max_force: num(m, "maxForce", f32::MAX)? }),- };- let d = match a["type"].as_str() {- Some("fixed") => JointDesc::Fixed { anchor1, anchor2 },- Some("revolute") => JointDesc::Revolute { anchor1, anchor2, axis: vec3(a, "axis", [0.0, 1.0, 0.0])?, limits, motor },- Some("prismatic") => JointDesc::Prismatic { anchor1, anchor2, axis: vec3(a, "axis", [1.0, 0.0, 0.0])?, limits, motor },- Some("spherical") => JointDesc::Spherical { anchor1, anchor2 },- Some("rope") => JointDesc::Rope { anchor1, anchor2, length: num(a, "length", f32::NAN)? },- other => return Err(format!("physics: joint type {other:?} is none of fixed, revolute, prismatic, spherical, rope")),- };+ let d = joint_desc(a)?;let (ba, bb) = (self.body(a, "a")?, self.body(a, "b")?);let j = self.core.add_joint(ba, bb, &d)?;self.joints.insert(jid, j);+ self.joint_ids.insert(j, jid);+ Value::Null+ }+ // What the engine did to scene code's joints since the last call (step 10 c1), in id order: {moved: [{joint,+ // end, body, anchor}], broken: [id]}. A moved joint's end ("a" or "b": its first or second body) is now on+ // `body` at `anchor` in that body's space: its anchor's material went into a part cut off, and the joint+ // with it (the same joint: id, kind and parameters). A broken one is gone from the world: its anchor's+ // material was carved away, or an engine body it held to went (retired, carved away, fallen, taken out by+ // the world). One moved and then broken is only broken.+ "joint_changes" => {+ let moved: Vec<Value> = std::mem::take(&mut self.joints_moved).into_iter().map(|(j, (body, first, anchor))| json!({ "joint": j, "end": if first { "a" } else { "b" }, "body": body, "anchor": anchor })).collect();+ json!({ "moved": moved, "broken": std::mem::take(&mut self.broken) })+ }+ // {id, type, limits?, motor?, length?}: a joint's parameters changed where it is (a hinge's or a slider's+ // limits and motor, a rope's length). Its bodies, anchors and axis are what make it this joint: a call+ // naming any of them (`a`, `b`, `anchor1`, `anchor2`, `axis`) is refused (remove the joint and make it anew).+ "joint_set" => {+ let jid = id(a, "id")?;+ if let Some(k) = ["a", "b", "anchor1", "anchor2", "axis"].into_iter().find(|k| !a[*k].is_null()) {+ return Err(format!("physics: joint_set changes a joint's limits, motor and length only, not its {k} (remove the joint and make it anew)"));+ }+ let &j = self.joints.get(&jid).ok_or_else(|| format!("physics: unknown joint {jid}"))?;+ self.core.set_joint(j, &joint_desc(a)?)?;Value::Null}"remove" => {@@ -372,8 +414,12 @@ impl Bridge {self.core.remove_collider(c);self.unmap(c);}- if let Some(j) = joint.and_then(|j| self.joints.remove(&j)) {- self.core.remove_joint(j);+ if let Some(jid) = joint {+ if let Some(j) = self.joints.remove(&jid) {+ self.joint_ids.remove(&j);+ self.core.remove_joint(j);+ }+ self.joints_moved.remove(&jid);}Value::Null}@@ -405,7 +451,12 @@ impl Bridge {self.core.set_velocity(b, opt("linvel")?, opt("angvel")?)?;Value::Null}+ // {body, position?, rotation?}: the body put there at once. (Not the world's anchor: the joints to the level+ // would go with it.)"pose" => {+ if whole(&a["body"]).is_some_and(|b| Some(b) == self.anchor) {+ return Err("physics: the world's anchor (the voxel level's body) does not move".into());+ }let b = self.body(a, "body")?;let (p, q) = (vec3(a, "position", [0.0; 3])?, quat(a, "rotation")?);self.core.set_pose(b, p, q)?;@@ -497,7 +548,8 @@ impl Bridge {if id < ENGINE_IDS || self.bodies.contains_key(&id) {return Err(format!("physics: engine body {id} exists or is below {ENGINE_IDS}"));}- if self.bodies.range(ENGINE_IDS..).count() >= MAX_ENGINE_BODIES {+ // (The anchor is not one of the bodies the engine makes as it goes.)+ if self.bodies.range(ENGINE_IDS..).count() - self.anchor.is_some() as usize >= MAX_ENGINE_BODIES {return Err(format!("physics: more than {MAX_ENGINE_BODIES} engine bodies"));}let b = self.core.add_body(d)?;@@ -519,12 +571,85 @@ impl Bridge {Some(b) => Some(*self.bodies.get(&b).ok_or_else(|| format!("physics: unknown body {b}"))?),None => None,};+ if body.is_some() && body == self.anchor {+ return Err("physics: the world's anchor holds joints, not colliders".into());+ }let c = self.core.add_collider(owner, d)?;self.colliders.insert(id, c);self.collider_ids.insert(c, (id, body));Ok(())}+ /// The world's anchor (step 10 c1): a fixed body at the origin, unturned, with no collider, that joints to the voxel+ /// level hold to (a point of it is the same point of the world). The level's colliders are static, on no body, as+ /// before; the engine moves a joint off the anchor when its anchor's material comes loose, and lets it go when that+ /// material is carved (docs/VOXEL.md). Scene code cannot move it (`pose` refuses it) and a query's `skip` of it+ /// passes through nothing. A level loaded again makes it anew: the old one goes, its joints broken.+ pub fn engine_anchor(&mut self, id: u32) -> Result<(), String> {+ if id < ENGINE_IDS || self.bodies.contains_key(&id) {+ return Err(format!("physics: engine body {id} exists or is below {ENGINE_IDS}"));+ }+ if let Some(old) = self.anchor.take() {+ self.engine_remove(Some(old), None);+ }+ let b = self.core.add_body(&BodyDesc { kind: BodyKind::Fixed, ..Default::default() })?;+ self.bodies.insert(id, b);+ self.body_ids.insert(b, id);+ self.faulted.remove(&id);+ self.anchor = Some(id);+ Ok(())+ }++ /// The joints on an engine body (step 10 c1): each one's world id, whether the body is its first, and its anchor+ /// in the body's space; in id order.+ pub fn engine_joints_of(&self, body: u32) -> Vec<(JointId, bool, [f32; 3])> {+ self.bodies.get(&body).map_or(vec![], |&b| self.core.joints_of(b))+ }++ /// One end of a joint moved from engine body `from` to `to` (its anchor's material went into another body), the same+ /// joint to scene code.+ /// Reported to scene code (`joint_changes`: moved), so that its joint names the body and anchor it is on now.+ pub fn engine_rebind_joint(&mut self, joint: JointId, from: u32, to: u32) -> Result<(), String> {+ let (f, t) = (*self.bodies.get(&from).ok_or("physics: unknown body")?, *self.bodies.get(&to).ok_or("physics: unknown body")?);+ let (anchor, first) = self.core.rebind_joint(joint, f, t)?;+ if let Some(&id) = self.joint_ids.get(&joint) {+ self.joints_moved.insert(id, (to, first, anchor));+ }+ Ok(())+ }++ /// A joint let go of by the engine (its anchor's material carved away): gone from the world, reported to scene code+ /// as broken (`joint_changes`).+ pub fn engine_break_joint(&mut self, joint: JointId) {+ if let Some(id) = self.joint_ids.remove(&joint) {+ self.joints.remove(&id);+ self.note_broken(id);+ }+ self.core.remove_joint(joint);+ }++ /// A broken joint noted for `joint_changes` (the newest `MAX_JOINTS` kept: nobody asking does not make it grow).+ fn note_broken(&mut self, id: u32) {+ self.joints_moved.remove(&id);+ if self.broken.len() >= MAX_JOINTS {+ self.broken.remove(0);+ }+ self.broken.push(id);+ }++ /// An explosion's push on every dynamic body near it, and the kick of the engine bodies in `kicked` (the debris it+ /// cut loose: `Physics::blast`): how many were pushed.+ pub fn engine_blast(&mut self, centre: [f32; 3], radius: f32, push: f32, kick: f32, kicked: &[u32]) -> Result<usize, String> {+ let mut k: Vec<BodyId> = kicked.iter().filter_map(|b| self.bodies.get(b).copied()).collect();+ k.sort_unstable();+ self.core.blast(centre, radius, push, kick, &k)+ }++ /// The world's anchor, if a voxel level with colliders is loaded (`engine_anchor`).+ pub fn engine_anchor_body(&self) -> Option<u32> {+ self.anchor+ }+/// An engine voxel collider's cells changed (`Physics::edit_voxels`). Returns the cells it has; with none left/// it is gone, its id with it.pub fn engine_edit_voxels(&mut self, id: u32, clear: &[[i32; 3]], fill: &[[i32; 3]]) -> Result<usize, String> {@@ -540,7 +665,10 @@ impl Bridge {/// An engine body with its colliders and joints, or an engine collider, gone. (Unknown ids: nothing.)pub fn engine_remove(&mut self, body: Option<u32>, collider: Option<u32>) {if let Some(b) = body.filter(|&b| b >= ENGINE_IDS).and_then(|b| self.bodies.get(&b).copied()) {- self.forget_body(b);+ // (Scene code's joints on it go with it: broken.)+ for id in self.forget_body(b) {+ self.note_broken(id);+ }}if let Some(c) = collider.filter(|&c| c >= ENGINE_IDS).and_then(|c| self.colliders.remove(&c)) {self.core.remove_collider(c);@@ -604,7 +732,8 @@ impl Bridge {self.bodies.get(&b).copied().ok_or_else(|| format!("physics: unknown body {b}"))}- /// A query's `skip`: the body whose colliders it passes through.+ /// A query's `skip`: the body whose colliders it passes through. (The world's anchor has none: it skips nothing. The+ /// voxel level's colliders are on no body, as every static collider: a query does not skip them.)fn skip(&self, a: &Value) -> Result<Option<BodyId>, String> {Ok(opt_id(a, "skip")?.and_then(|b| self.bodies.get(&b).copied()))}@@ -630,14 +759,15 @@ impl Bridge {Some(ids)}- fn forget_body(&mut self, b: BodyId) {- let gone = self.core.remove_body(b);- self.forget_ids(b, &gone);+ /// Removes a body with its colliders and joints; returns scene code's ids of the joints that went.+ fn forget_body(&mut self, b: BodyId) -> Vec<u32> {+ let (colliders, joints) = self.core.remove_body(b);+ self.forget_ids(b, &colliders, &joints)}- /// Forgets the ids of a body the world no longer has (the world's id), of the colliders that went with it and of- /// its joints.- fn forget_ids(&mut self, b: BodyId, colliders: &[ColliderId]) {+ /// Forgets the ids of a body the world no longer has (the world's id), of the colliders and the joints that went+ /// with it. Returns scene code's ids of those joints.+ fn forget_ids(&mut self, b: BodyId, colliders: &[ColliderId], joints: &[JointId]) -> Vec<u32> {for c in colliders {if let Some((id, _)) = self.unmap(*c) {self.colliders.remove(&id);@@ -652,11 +782,15 @@ impl Bridge {if let Some(id) = self.body_ids.remove(&b) {self.bodies.remove(&id);}- // (Its joints went with it: those the world no longer has.)- if !self.joints.is_empty() {- let core = &self.core;- self.joints.retain(|_, j| core.has_joint(*j));+ let mut ids = vec![];+ for j in joints {+ if let Some(id) = self.joint_ids.remove(j) {+ self.joints.remove(&id);+ self.joints_moved.remove(&id);+ ids.push(id);+ }}+ ids}fn hit(&self, h: Option<Hit>) -> Value {@@ -745,8 +879,15 @@ impl Bridge {};let caller = self.body_ids.get(&b).copied();let object = self.drives.get(&b).map(|d| d.0);- self.forget_ids(b, &f.colliders);+ let joints = self.forget_ids(b, &f.colliders, &f.joints);let Some(caller) = caller else { return };+ // (An engine body's joints are scene code's to hear of as broken, as when the engine removes the body itself;+ // a body of scene code's own is in "faults", its joints with it.)+ if caller >= ENGINE_IDS {+ for id in joints {+ self.note_broken(id);+ }+ }if self.faults.len() == MAX_FAULTS {self.faults.remove(0);}@@ -1099,4 +1240,79 @@ mod tests {}assert_eq!((b.due_until(120), b.due_until(40), b.due_until(1_000_000)), (70, 0, 35_950));}+ /// The world's anchor and what the engine does to scene code's joints (step 10 c1): the anchor has no collider and+ /// does not move (`pose` refused, a collider on it refused); the level's static colliders are on no body (a hit+ /// names none; a `skip` of the anchor skips nothing). A joint to it moved onto an engine body is reported once as+ /// moved, with its end, body and anchor; one moved and then let go of only as broken; joints of an engine body the+ /// engine removes, of one the world takes out after a tick (it left the world) and of an anchor made anew are+ /// broken; `joint_set` naming a joint's bodies, anchors or axis is refused.+ #[test]+ fn the_anchor_and_the_engines_joints() {+ let (mut b, mut s) = (Bridge::default(), scene());+ let (anchor, part, other) = (ENGINE_IDS, ENGINE_IDS + 1, ENGINE_IDS + 2);+ b.engine_anchor(anchor).unwrap();+ b.engine_collider(ENGINE_IDS + 10, None, &ColliderDesc { position: [0.0, -0.5, 0.0], ..ColliderDesc::new(Shape::Box([20.0, 0.5, 20.0])) }).unwrap();+ assert!(b.engine_collider(ENGINE_IDS + 11, Some(anchor), &ColliderDesc::new(Shape::Sphere(0.1))).is_err(), "no collider on the anchor");+ let err = b.call(&mut s, "pose", &json!({ "body": anchor, "position": [0, 50, 0] })).unwrap_err();+ assert!(err.contains("anchor"), "{err}");+ let ray = |b: &mut Bridge, s: &mut Objects, skip: Value| b.call(s, "ray", &json!({ "origin": [1, 5, 1], "direction": [0, -1, 0], "skip": skip })).unwrap();+ let hit = ray(&mut b, &mut s, json!(anchor));+ assert_eq!((hit["collider"].as_u64(), hit["body"].is_null(), hit["distance"].as_f64()), (Some(ENGINE_IDS as u64 + 10), true, Some(5.0)), "skipping the anchor skips nothing: {hit}");+ for (id, at) in [(part, [3.0, 1.0, 0.0]), (other, [6.0, 1.0, 0.0])] {+ b.engine_body(id, &BodyDesc { position: at, gravity_scale: 0.0, ..Default::default() }).unwrap();+ b.engine_collider(id + 20, Some(id), &ColliderDesc::new(Shape::Box([0.5; 3]))).unwrap();+ }+ b.call(&mut s, "body", &json!({ "id": 2, "object": 2 })).unwrap();+ b.call(&mut s, "collider", &json!({ "id": 2, "body": 2, "shape": { "type": "sphere", "radius": 0.1 } })).unwrap();+ for id in [7, 8] {+ b.call(&mut s, "joint", &json!({ "id": id, "a": anchor, "b": 2, "type": "rope", "length": 4.0, "anchor1": [3.2, 1.3, 0.0] })).unwrap();+ }+ b.call(&mut s, "body", &json!({ "id": 3, "position": [6.0, 3.0, 0.0], "gravityScale": 0.0 })).unwrap();+ b.call(&mut s, "joint", &json!({ "id": 9, "a": other, "b": 3, "type": "rope", "length": 4.0 })).unwrap();+ let changes = |b: &mut Bridge, s: &mut Objects| b.call(s, "joint_changes", &json!({})).unwrap();+ assert_eq!(changes(&mut b, &mut s), json!({ "moved": [], "broken": [] }));+ // Joint 7's anchor material came loose into `part`: moved, its anchor in the part's space (part at (3, 1, 0)).+ let j7 = b.engine_joints_of(anchor)[0].0;+ b.engine_rebind_joint(j7, anchor, part).unwrap();+ let c = changes(&mut b, &mut s);+ assert_eq!((&c["moved"][0]["joint"], &c["moved"][0]["end"], &c["moved"][0]["body"]), (&json!(7), &json!("a"), &json!(part)), "{c}");+ let at: Vec<f64> = c["moved"][0]["anchor"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();+ assert!((at[0] - 0.2).abs() < 1e-5 && (at[1] - 0.3).abs() < 1e-5 && at[2].abs() < 1e-5, "{at:?}");+ assert_eq!(changes(&mut b, &mut s), json!({ "moved": [], "broken": [] }), "reported once");+ // Moved and let go of in one batch: broken only.+ let j8 = b.engine_joints_of(anchor)[0].0;+ b.engine_rebind_joint(j8, anchor, part).unwrap();+ b.engine_break_joint(j8);+ assert_eq!(changes(&mut b, &mut s), json!({ "moved": [], "broken": [8] }));+ // In place only: no bodies, anchors or axis.+ for k in ["a", "b", "anchor1", "anchor2", "axis"] {+ let mut a = json!({ "id": 7, "type": "rope", "length": 2.0 });+ a[k] = json!([0, 0, 0]);+ assert!(b.call(&mut s, "joint_set", &a).unwrap_err().contains(k), "{k}");+ }+ b.call(&mut s, "joint_set", &json!({ "id": 7, "type": "rope", "length": 2.0 })).unwrap();+ // The engine removes `part`: joint 7 with it, broken.+ b.engine_remove(Some(part), None);+ assert_eq!(changes(&mut b, &mut s), json!({ "moved": [], "broken": [7] }));+ // `other` leaves the world after a tick: joint 9 broken (and the body in "faults").+ b.call(&mut s, "joint", &json!({ "id": 10, "a": anchor, "b": 2, "type": "rope", "length": 4.0, "anchor1": [0.0, 3.0, 0.0] })).unwrap();+ // (Both ends of joint 9 thrown outward, the rope slack; they go at 400 m/s, which takes some 135,000 ticks.)+ b.call(&mut s, "pose", &json!({ "body": other, "position": [99_999.0, 1.0, 0.0] })).unwrap();+ b.call(&mut s, "pose", &json!({ "body": 3, "position": [99_999.0, 3.0, 0.0] })).unwrap();+ for id in [other, 3] {+ b.call(&mut s, "velocity", &json!({ "body": id, "linvel": [1e4, 0, 0] })).unwrap();+ }+ let mut ticks = 0;+ while b.engine_pose(other).is_some() && ticks < 200_000 {+ b.tick();+ ticks += 1;+ }+ b.sync(&mut s);+ assert_eq!(changes(&mut b, &mut s)["broken"], json!([9]));+ assert!(b.call(&mut s, "faults", &json!({})).unwrap().as_array().unwrap().iter().any(|f| f["body"] == json!(other) && f["kind"] == json!("leftWorld")));+ // An anchor made anew: the joints on the old one broken.+ b.engine_anchor(ENGINE_IDS + 3).unwrap();+ assert_eq!(changes(&mut b, &mut s)["broken"], json!([10]));+ assert!(b.engine_pose(anchor).is_none() && b.engine_anchor_body() == Some(ENGINE_IDS + 3));+ }}diff --git a/renderer/physics-core/src/check.rs b/renderer/physics-core/src/check.rsindex 4da824f..24ca803 100644--- a/renderer/physics-core/src/check.rs+++ b/renderer/physics-core/src/check.rs@@ -5,20 +5,27 @@ use crate::world::*;/// The hash `script(600)` leaves with `enhanced-determinism` (recorded: a change of behaviour, or of Rapier, shows/// here). Natively and in wasm32 alike.-pub const EXPECTED: u64 = 0x113d_50eb_06a4_7636;+pub const EXPECTED: u64 = 0x8e4a_f124_a206_1883;/// A tower of boxes hit by a ball, a hinged door pushed by another, a rope pendulum and a slider: contacts, friction,-/// stacking and four kinds of joints, for `ticks` ticks. Returns the world's hash.+/// stacking and four kinds of joints, for `ticks` ticks; an explosion's push and kick and a joint changed in place+/// (step 10 c1).+/// Returns the world's hash.pub fn script(ticks: u32) -> u64 {let mut p = Physics::default();p.add_collider(None, &ColliderDesc::new(Shape::Box([50.0, 0.5, 50.0]))).unwrap();let dynamic = |position: [f32; 3]| BodyDesc { position, ..Default::default() };- // Ground at y = 0.5 (the box above is centred at 0): a 4 x 6 x 4 tower of half-metre boxes.+ // Ground at y = 0.5 (the box above is centred at 0): a 4 x 6 x 4 tower of half-metre boxes (its top layer kicked by+ // the explosion, as debris it cut loose would be).+ let mut top = vec![];for y in 0..6 {for x in 0..4 {for z in 0..4 {let b = p.add_body(&dynamic([x as f32 * 0.5 - 0.75 + 0.01 * y as f32, 0.75 + y as f32 * 0.5, z as f32 * 0.5 - 0.75])).unwrap();p.add_collider(Some(b), &ColliderDesc::new(Shape::Box([0.25; 3]))).unwrap();+ if y == 5 {+ top.push(b);+ }}}}@@ -40,7 +47,7 @@ pub fn script(ticks: u32) -> u64 {p.add_joint(post, hull, &JointDesc::Spherical { anchor1: [3.0, 1.5, -3.0], anchor2: [0.0, 0.5, 0.0] }).unwrap();let slider = p.add_body(&dynamic([0.0, 3.0, -6.0])).unwrap();p.add_collider(Some(slider), &ColliderDesc::new(Shape::Box([0.3; 3]))).unwrap();- p.add_joint(post, slider, &JointDesc::Prismatic { anchor1: [-5.0, 1.5, -6.0], anchor2: [0.0; 3], axis: [1.0, 0.0, 0.0], limits: Some(Limits { min: -2.0, max: 2.0 }), motor: Some(Motor { velocity: 1.5, damping: 400.0, max_force: 500.0 }) }).unwrap();+ let rail = p.add_joint(post, slider, &JointDesc::Prismatic { anchor1: [-5.0, 1.5, -6.0], anchor2: [0.0; 3], axis: [1.0, 0.0, 0.0], limits: Some(Limits { min: -2.0, max: 2.0 }), motor: Some(Motor { velocity: 1.5, damping: 400.0, max_force: 500.0 }) }).unwrap();let mut h = 0u64;for t in 0..ticks {p.step();@@ -48,6 +55,14 @@ pub fn script(ticks: u32) -> u64 {if t == ticks / 2 {p.apply_impulse(ball, [0.0, 80.0, 30.0], [0.0; 3]).unwrap();}+ // Step 10 c1: an explosion's push among the boxes a quarter in; the slider's motor turned round in place (its+ // limits moved) three quarters in.+ if t == ticks / 4 {+ p.blast([1.0, 0.6, 0.5], 1.5, 400.0, 10.0, &top).unwrap();+ }+ if t == 3 * ticks / 4 {+ p.set_joint(rail, &JointDesc::Prismatic { anchor1: [-5.0, 1.5, -6.0], anchor2: [0.0; 3], axis: [1.0, 0.0, 0.0], limits: Some(Limits { min: -1.0, max: 2.5 }), motor: Some(Motor { velocity: -2.0, damping: 400.0, max_force: 600.0 }) }).unwrap();+ }if t % 30 == 29 {h = (h ^ p.hash()).wrapping_mul(0x0000_0100_0000_01b3);}diff --git a/renderer/physics-core/src/lib.rs b/renderer/physics-core/src/lib.rsindex 21c303f..33fb2a3 100644--- a/renderer/physics-core/src/lib.rs+++ b/renderer/physics-core/src/lib.rs@@ -11,7 +11,7 @@ pub mod check;mod world;pub use world::{- limits, BodyDesc, BodyId, BodyKind, ColliderDesc, ColliderId, Contact, CustomShape, Fault, Hit, JointDesc, JointId, Limits, Motor, Physics, Shape, SharedVoxels, TICK,+ limits, BodyDesc, BodyId, BodyKind, ColliderDesc, ColliderId, Contact, CustomShape, Fault, Hit, JointDesc, JointId, JointKind, Limits, Motor, Physics, Shape, SharedVoxels, TICK,};/// Rapier itself, for engine code that implements `CustomShape` (not for game scripts).pub use rapier3d;diff --git a/renderer/physics-core/src/world.rs b/renderer/physics-core/src/world.rsindex c095c9e..8c16ac3 100644--- a/renderer/physics-core/src/world.rs+++ b/renderer/physics-core/src/world.rs@@ -29,6 +29,10 @@ pub mod limits {pub const MAX_ANGVEL: f32 = 1e3;/// N s (and N m s for an angular one), N (and N m).pub const MAX_IMPULSE: f32 = 1e6;+ /// An explosion's reach in radii, and the most it changes a body's velocity (m/s): what the solver and CCD follow+ /// (`Physics::blast`).+ pub const BLAST_REACH: f32 = 3.0;+ pub const BLAST_MAX_DV: f32 = 30.0;pub const MAX_FORCE: f32 = 1e8;/// A collider's mass (kg) and density (kg/m³): 0 (it adds nothing to its body) or within these.pub const MASS: [f32; 2] = [1e-3, 1e7];@@ -188,6 +192,28 @@ pub enum JointDesc {Rope { anchor1: [f32; 3], anchor2: [f32; 3], length: f32 },}+/// What kind of joint a `JointDesc` makes (what `Physics::set_joint` may not change).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum JointKind {+ Fixed,+ Revolute,+ Prismatic,+ Spherical,+ Rope,+}++impl JointKind {+ pub fn of(d: &JointDesc) -> JointKind {+ match d {+ JointDesc::Fixed { .. } => JointKind::Fixed,+ JointDesc::Revolute { .. } => JointKind::Revolute,+ JointDesc::Prismatic { .. } => JointKind::Prismatic,+ JointDesc::Spherical { .. } => JointKind::Spherical,+ JointDesc::Rope { .. } => JointKind::Rope,+ }+ }+}+/// Two colliders began or stopped touching.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct Contact {@@ -201,6 +227,8 @@ pub struct Contact {pub struct Fault {pub body: Option<BodyId>,pub colliders: Vec<ColliderId>,+ /// The joints that went with the body.+ pub joints: Vec<JointId>,/// The body left the world (past `WORLD_EDGE`: it fell off the level, an ordinary thing in a game); otherwise its/// state or a shape went non-finite (bad data or a blown-up simulation: an error the author should hear of).pub left_world: bool,@@ -529,6 +557,9 @@ pub struct Physics {/// The voxel colliders there are: rays are cast at them here (`voxel_ray`), not by the broad phase's query.voxel_colliders: std::collections::BTreeSet<ColliderId>,joints: BTreeMap<JointId, ImpulseJointHandle>,+ /// Per joint: its kind (what `set_joint` may change), and for a hinge the centre of its limits (rad) by which its+ /// first frame is turned (`add_joint`).+ joint_kinds: BTreeMap<JointId, (JointKind, f32)>,/// The kinematic bodies (`awake`: the islands hold dynamic ones only).kinematic: std::collections::BTreeSet<BodyId>,next: u32,@@ -567,6 +598,7 @@ impl Physics {shape_data: 0,voxel_colliders: Default::default(),joints: BTreeMap::new(),+ joint_kinds: BTreeMap::new(),kinematic: Default::default(),next: 0,ticks: 0,@@ -629,12 +661,13 @@ impl Physics {}/// Removes a body with its colliders and joints. Returns the colliders that went with it.- pub fn remove_body(&mut self, id: BodyId) -> Vec<ColliderId> {- let Some(h) = self.bodies.remove(&id) else { return vec![] };+ pub fn remove_body(&mut self, id: BodyId) -> (Vec<ColliderId>, Vec<JointId>) {+ let Some(h) = self.bodies.remove(&id) else { return (vec![], vec![]) };self.kinematic.remove(&id);// (Its own colliders and joints only: removing a body costs what it holds, not what the world holds.)let gone: Vec<ColliderId> = self.world.bodies.get(h).map(|b| b.colliders().iter().filter_map(|&c| self.world.colliders.get(c).map(|c| c.user_data as u32)).collect()).unwrap_or_default();- let jointed = self.world.impulse_joints.attached_joints(h).next().is_some();+ let mut joints: Vec<JointId> = self.world.impulse_joints.attached_joints(h).map(|(.., j)| j.data.user_data as JointId).collect();+ joints.sort_unstable();self.world.remove_body_with_colliders(h, true);for c in &gone {self.fresh.remove(c);@@ -643,11 +676,11 @@ impl Physics {self.shape_data -= data;}}- if jointed {- let world = &self.world;- self.joints.retain(|_, j| world.impulse_joints.get(*j).is_some());+ for j in &joints {+ self.joints.remove(j);+ self.joint_kinds.remove(j);}- gone+ (gone, joints)}/// Adds a collider to `body` (None: a static collider in the world). Err (why) if the body is unknown, the shape@@ -790,13 +823,142 @@ impl Physics {let (s, c) = libm::sincosf(centre * 0.5);joint.local_frame1.rotation = (joint.local_frame1.rotation * Rotation::from_xyzw(s, 0.0, 0.0, c)).normalize();}- let h = self.world.insert_impulse_joint(ha, hb, joint);let id = self.id();+ // (Its id in the joint, as bodies and colliders hold theirs: a body's joints are read off it, `joints_of`.)+ joint.user_data = id as u128;+ let h = self.world.insert_impulse_joint(ha, hb, joint);self.joints.insert(id, h);+ self.joint_kinds.insert(id, (JointKind::of(d), centre));Ok(id)}+ /// A joint's parameters changed where it is (`joint_set`): a hinge's or a slider's limits and motor, a rope's+ /// length. Its bodies, anchors, axis and frames stay as they were made (nothing is taken anew from the bodies'+ /// poses, no warm-started impulse is lost); its bodies are woken. Err, the joint unchanged: no such joint, another+ /// kind of joint than it was made as, a kind without parameters (fixed, ball), bad numbers.+ pub fn set_joint(&mut self, id: JointId, d: &JointDesc) -> Result<(), String> {+ let (&h, &(kind, old_centre)) = match (self.joints.get(&id), self.joint_kinds.get(&id)) {+ (Some(h), Some(k)) => (h, k),+ _ => return Err("physics: unknown joint".into()),+ };+ if JointKind::of(d) != kind {+ return Err("physics: a joint's kind is not changed in place (make a new joint)".into());+ }+ let limits = |l: &Option<Limits>| -> Result<Option<[f32; 2]>, String> {+ match l {+ None => Ok(None),+ Some(l) => {+ within(&[l.min, l.max], MAX_COORD, "a joint's limits")?;+ if l.min > l.max {+ return Err("physics: a joint's limits must be [min, max] with min <= max".into());+ }+ Ok(Some([l.min, l.max]))+ }+ }+ };+ let motor = |m: &Option<Motor>| -> Result<Option<Motor>, String> {+ match m {+ None => Ok(None),+ Some(m) => {+ within(&[m.velocity], MAX_MOTOR_VELOCITY, "a motor's velocity")?;+ between(m.damping, 0.0, MAX_MOTOR_DAMPING, "a motor's damping")?;+ between(m.max_force, 0.0, f32::MAX, "a motor's maximum force")?;+ Ok(Some(*m))+ }+ }+ };+ // Everything checked before anything changes.+ let (axis, l, m, length) = match d {+ JointDesc::Revolute { limits: l, motor: m, .. } => (JointAxis::AngX, limits(l)?, motor(m)?, None),+ JointDesc::Prismatic { limits: l, motor: m, .. } => (JointAxis::LinX, limits(l)?, motor(m)?, None),+ JointDesc::Rope { length, .. } => {+ between(*length, 0.0, MAX_COORD, "a rope's length")?;+ (JointAxis::LinX, None, None, Some(*length))+ }+ JointDesc::Fixed { .. } | JointDesc::Spherical { .. } => return Err("physics: a fixed or ball joint has no parameters to change".into()),+ };+ let j = &mut self.world.impulse_joints.get_mut(h, true).ok_or("physics: unknown joint")?.data;+ if let Some(length) = length {+ j.set_limits(JointAxis::LinX, [0.0, length]);+ return Ok(());+ }+ let mut centre = 0.0f32;+ match (l, kind) {+ // A hinge's limits centred as `add_joint` does: the first frame turned back by the old centre, on by the new.+ (Some([min, max]), JointKind::Revolute) => {+ centre = (min + max) * 0.5;+ j.set_limits(axis, [-(max - min) * 0.5, (max - min) * 0.5]);+ }+ (Some(lim), _) => {+ j.set_limits(axis, lim);+ }+ (None, _) => j.limit_axes.remove(axis.into()),+ }+ if kind == JointKind::Revolute && centre != old_centre {+ let (s0, c0) = libm::sincosf(-old_centre * 0.5);+ let (s1, c1) = libm::sincosf(centre * 0.5);+ let back = j.local_frame1.rotation * Rotation::from_xyzw(s0, 0.0, 0.0, c0);+ j.local_frame1.rotation = (back.normalize() * Rotation::from_xyzw(s1, 0.0, 0.0, c1)).normalize();+ }+ match m {+ Some(m) => {+ j.set_motor_velocity(axis, m.velocity, m.damping);+ j.set_motor_max_force(axis, m.max_force);+ }+ None => j.motor_axes.remove(axis.into()),+ }+ self.joint_kinds.insert(id, (kind, centre));+ Ok(())+ }++ /// The joints on a body: each one's id, whether the body is its first, and its anchor in the body's space.+ /// In joint id order. (Read off the body's own joints, Rapier's joint graph: what the body holds, not what the+ /// world does.)+ pub fn joints_of(&self, body: BodyId) -> Vec<(JointId, bool, [f32; 3])> {+ let Some(&h) = self.bodies.get(&body) else { return vec![] };+ let mut out: Vec<(JointId, bool, [f32; 3])> = self+ .world+ .impulse_joints+ .attached_joints(h)+ .map(|(.., j)| {+ let first = j.body1() == h;+ (j.data.user_data as JointId, first, if first { j.data.local_frame1.translation } else { j.data.local_frame2.translation }.to_array())+ })+ .collect();+ out.sort_unstable_by_key(|x| x.0);+ out+ }++ /// Moves one end of a joint from body `from` to body `to`, the same joint (its id, kind and parameters): that+ /// end's frame is where it was in the world, now in `to`'s space (a joint whose anchor's material went into+ /// another body, step 10 c1). Returns that end's anchor in `to`'s space, and whether it is the joint's first end.+ /// Err: no such joint or body, `from` not one of its bodies, `to` its other body.+ pub fn rebind_joint(&mut self, id: JointId, from: BodyId, to: BodyId) -> Result<([f32; 3], bool), String> {+ let jh = *self.joints.get(&id).ok_or("physics: unknown joint")?;+ let (hf, ht) = (*self.bodies.get(&from).ok_or("physics: unknown body")?, *self.bodies.get(&to).ok_or("physics: unknown body")?);+ let j = self.world.impulse_joints.get(jh).ok_or("physics: unknown joint")?;+ let first = if j.body1() == hf { true } else if j.body2() == hf { false } else { return Err("physics: the joint is not on that body".into()) };+ let other = if first { j.body2() } else { j.body1() };+ if other == ht {+ return Err("physics: a joint joins two different bodies".into());+ }+ let mut data = j.data;+ let (pf, pt) = (*self.world.bodies[hf].position(), *self.world.bodies[ht].position());+ let frame = if first { data.local_frame1 } else { data.local_frame2 };+ let moved = pt.inverse() * (pf * frame);+ if first {+ data.local_frame1 = moved;+ } else {+ data.local_frame2 = moved;+ }+ self.world.remove_impulse_joint(jh);+ let nh = if first { self.world.insert_impulse_joint(ht, other, data) } else { self.world.insert_impulse_joint(other, ht, data) };+ self.joints.insert(id, nh);+ Ok((moved.translation.to_array(), first))+ }+pub fn remove_joint(&mut self, id: JointId) {+ self.joint_kinds.remove(&id);if let Some(h) = self.joints.remove(&id) {self.world.remove_impulse_joint(h);}@@ -941,14 +1103,14 @@ impl Physics {for c in statics {if let Some(id) = self.world.colliders.get(c).map(|c| c.user_data as u32) {self.remove_collider(id);- self.faults.push(Fault { body: None, colliders: vec![id], left_world: false, reason: "its shape went non-finite" });+ self.faults.push(Fault { body: None, colliders: vec![id], joints: vec![], left_world: false, reason: "its shape went non-finite" });}}for (h, left_world, reason) in out {let Some(id) = self.world.bodies.get(h).map(|b| b.user_data as u32) else { continue };if self.bodies.contains_key(&id) {- let colliders = self.remove_body(id);- self.faults.push(Fault { body: Some(id), colliders, left_world, reason });+ let (colliders, joints) = self.remove_body(id);+ self.faults.push(Fault { body: Some(id), colliders, joints, left_world, reason });}}}@@ -1099,6 +1261,71 @@ impl Physics {Ok(())}+ /// An explosion's push (step 10 c1, docs/VOXEL.md "The blast"): every dynamic body whose colliders' box comes within+ /// `BLAST_REACH` x `radius` of `centre` takes an impulse away from the centre, through its centre of mass (no turn):+ /// its area facing the blast (its box's cross-section across the direction) times+ /// i(d) = push x radius x min(1, (radius / d)²) x (1 - (d / reach)²)² N s / m², d the distance from the centre to its+ /// box (0 inside). The bodies in `kicked` (sorted: the debris the explosion itself cut loose) also take a change of+ /// velocity of their own, whatever their mass: `kick` m/s x min(1, (radius / d)²) x (1 - (d / reach)²)², the same+ /// way. A body's whole change of velocity is at most `BLAST_MAX_DV`. Only +, -, x, / and square roots (IEEE: the+ /// same bits on every platform); bodies in id order. Returns how many were pushed (none for a radius of 0 or less).+ /// Err: a centre past the world's edge or not finite, a push or kick below 0 or not finite (nothing changes).+ pub fn blast(&mut self, centre: [f32; 3], radius: f32, push: f32, kick: f32, kicked: &[BodyId]) -> Result<usize, String> {+ within(¢re, WORLD_EDGE, "a blast's centre")?;+ between(push, 0.0, f32::MAX, "a blast's push")?;+ between(kick, 0.0, BLAST_MAX_DV, "a blast's kick")?;+ // (A radius of 0 or less, as an edit may have, pushes nothing; one past the world's sizes is held to them.)+ if !(radius > 0.0) {+ return Ok(0);+ }+ let radius = radius.min(MAX_SIZE);+ let reach = BLAST_REACH * radius;+ if !(reach > 0.0) || (push == 0.0 && (kick == 0.0 || kicked.is_empty())) {+ return Ok(0);+ }+ let c = Vector::new(centre[0], centre[1], centre[2]);+ let mut pushed = vec![];+ for (&id, &h) in &self.bodies {+ let Some(b) = self.world.bodies.get(h) else { continue };+ if !b.is_dynamic() || !b.is_enabled() || !(b.mass() > 0.0) {+ continue;+ }+ // Its colliders' box.+ let mut boxed: Option<Aabb> = None;+ for &ch in b.colliders() {+ if let Some(col) = self.world.colliders.get(ch) {+ let a = col.compute_aabb();+ boxed = Some(boxed.map_or(a, |x| x.merged(&a)));+ }+ }+ let Some(aabb) = boxed else { continue };+ let nearest = c.clamp(aabb.mins, aabb.maxs);+ let d = (nearest - c).length();+ if d >= reach {+ continue;+ }+ let towards = b.center_of_mass() - c;+ let len = towards.length();+ let n = if len > 1e-6 { towards / len } else { Vector::Y };+ let e = aabb.maxs - aabb.mins;+ let area = n.x.abs() * e.y * e.z + n.y.abs() * e.x * e.z + n.z.abs() * e.x * e.y;+ let near = if d > radius { (radius / d) * (radius / d) } else { 1.0 };+ let fall = 1.0 - (d / reach) * (d / reach);+ let per_area = push * radius * near * fall * fall;+ let own = if kicked.binary_search(&id).is_ok() { kick * near * fall * fall } else { 0.0 };+ let j = (per_area * area + own * b.mass()).min(BLAST_MAX_DV * b.mass());+ if j > 0.0 && j.is_finite() {+ pushed.push((id, n * j));+ }+ }+ for &(id, j) in &pushed {+ if let Some(b) = self.body_mut(id) {+ b.apply_impulse(j, true);+ }+ }+ Ok(pushed.len())+ }+/// An impulse (N s) at a point of the world (it turns the body as well, unless the point is its centre of mass), and/// an angular one (N m s). All of it is checked before any of it acts: a call that is refused changes nothing.pub fn apply_impulse_at(&mut self, id: BodyId, impulse: [f32; 3], point: [f32; 3], torque: [f32; 3]) -> Result<(), String> {@@ -1480,6 +1707,165 @@ mod tests {}}+ /// A body's joints are read off the body (`joints_of`, Rapier's joint graph), not found among the world's: with+ /// 5,000 joints elsewhere, a body's two are its own, in id order, with its end and anchor; removing it returns them+ /// and the world no longer has them; the others stay.+ #[test]+ fn a_bodys_joints_are_its_own() {+ let mut p = Physics::default();+ let post = fixed(&mut p, [0.0, 5.0, 0.0]);+ let ball = |p: &mut Physics, at: [f32; 3]| {+ let b = p.add_body(&BodyDesc { position: at, ..Default::default() }).unwrap();+ p.add_collider(Some(b), &ColliderDesc::new(Shape::Sphere(0.1))).unwrap();+ b+ };+ let (a, b) = (ball(&mut p, [1.0, 4.0, 0.0]), ball(&mut p, [2.0, 4.0, 0.0]));+ let rope = |p: &mut Physics, x: BodyId, y: BodyId, anchor1: [f32; 3]| p.add_joint(x, y, &JointDesc::Rope { anchor1, anchor2: [0.0; 3], length: 3.0 }).unwrap();+ let mut others = vec![];+ for _ in 0..5000 {+ others.push(rope(&mut p, post, b, [0.5, 0.0, 0.0]));+ }+ let j1 = rope(&mut p, post, a, [0.25, 0.0, 0.0]);+ let j2 = rope(&mut p, a, b, [0.0, 0.1, 0.0]);+ assert_eq!(p.joints_of(a), vec![(j1, false, [0.0; 3]), (j2, true, [0.0, 0.1, 0.0])]);+ assert_eq!(p.joints_of(post).len(), 5001);+ let (_, gone) = p.remove_body(a);+ assert_eq!(gone, vec![j1, j2]);+ assert!(!p.has_joint(j1) && !p.has_joint(j2) && others.iter().all(|&j| p.has_joint(j)));+ assert_eq!(p.joints_of(b).len(), 5000);+ }++ /// An explosion's push (`blast`): a 1 m cube of 100 kg whose near face is 1 m from a 1 m blast takes+ /// 400 x 1 x 1 x (1 - (1/3)²)² N s across its 1 m² face, away from the centre, through its centre of mass (no turn);+ /// one at the reach (3 m) none; a fixed one none; a 1 kg one at most 30 m/s; one around the centre straight away+ /// from it; a push of 0, or a radius of 0 or less, nothing; a centre or push not finite refused.+ #[test]+ fn a_blast_pushes_by_area_and_distance() {+ let cube = |p: &mut Physics, at: [f32; 3], mass: f32, kind: BodyKind| {+ let b = p.add_body(&BodyDesc { kind, position: at, can_sleep: false, gravity_scale: 0.0, ..Default::default() }).unwrap();+ let mut d = ColliderDesc::new(Shape::Box([0.5; 3]));+ d.mass = Some(mass);+ p.add_collider(Some(b), &d).unwrap();+ b+ };+ let mut p = Physics::default();+ let near = cube(&mut p, [1.5, 0.0, 0.0], 100.0, BodyKind::Dynamic);+ let edge = cube(&mut p, [0.0, 0.0, 3.5], 100.0, BodyKind::Dynamic);+ let wall = cube(&mut p, [-1.5, 0.0, 0.0], 100.0, BodyKind::Fixed);+ let light = cube(&mut p, [0.0, -1.5, 0.0], 1.0, BodyKind::Dynamic);+ assert_eq!(p.blast([0.0; 3], 1.0, 400.0, 0.0, &[]).unwrap(), 2);+ let fall = 1.0 - (1.0f32 / 3.0) * (1.0 / 3.0);+ let want = 400.0 * fall * fall / 100.0;+ let (lv, av) = p.velocity(near).unwrap();+ assert!((lv[0] - want).abs() < 1e-5 && lv[1].abs() < 1e-6 && lv[2].abs() < 1e-6 && av.iter().all(|a| a.abs() < 1e-6), "{lv:?} {av:?}, want {want}");+ assert_eq!(p.velocity(edge).unwrap().0, [0.0; 3], "at the reach: none");+ assert_eq!(p.velocity(wall).unwrap().0, [0.0; 3], "fixed: none");+ let lv = p.velocity(light).unwrap().0;+ assert!((lv[1] + BLAST_MAX_DV).abs() < 1e-4 && lv[0].abs() < 1e-6, "capped: {lv:?}");+ // Around the centre: away from it (up when they coincide).+ let mut q = Physics::default();+ let around = cube(&mut q, [0.0, 0.0, 0.0], 100.0, BodyKind::Dynamic);+ assert_eq!(q.blast([0.0, 0.0, 0.0], 1.0, 400.0, 0.0, &[]).unwrap(), 1);+ let lv = q.velocity(around).unwrap().0;+ assert!(lv[1] > 0.0 && lv[0] == 0.0 && lv[2] == 0.0, "{lv:?}");+ // Nothing, and refusals.+ assert_eq!(q.blast([0.0; 3], 1.0, 0.0, 0.0, &[]).unwrap(), 0);+ assert_eq!(q.blast([0.0; 3], -1.0, 400.0, 0.0, &[]).unwrap(), 0);+ assert_eq!(q.blast([0.0; 3], 0.0, 400.0, 0.0, &[]).unwrap(), 0);+ assert!(q.blast([f32::NAN, 0.0, 0.0], 1.0, 400.0, 0.0, &[]).is_err());+ assert!(q.blast([0.0; 3], 1.0, f32::INFINITY, 0.0, &[]).is_err());+ assert!(q.blast([0.0; 3], 1.0, -1.0, 0.0, &[]).is_err());+ assert!(q.blast([0.0; 3], 1.0, 400.0, -1.0, &[around]).is_err() && q.blast([0.0; 3], 1.0, 400.0, 31.0, &[around]).is_err());+ assert_eq!(q.velocity(around).unwrap().0, lv, "refused: nothing changed");+ }++ /// The kick of a blast (`blast`'s `kicked`, the debris an explosion cut loose): a change of velocity whatever the+ /// mass, falling off as the push does: a 100 kg and a 10 t cube side by side 1 m from a 1 m blast with no push both+ /// leave at 5 x (1 - (1/3)²)² m/s; one not in `kicked` stays; with the push as well the two add, at most 30 m/s.+ #[test]+ fn a_blast_kicks_its_debris_whatever_their_mass() {+ let mut p = Physics::default();+ let cube = |p: &mut Physics, at: [f32; 3], mass: f32| {+ let b = p.add_body(&BodyDesc { position: at, can_sleep: false, gravity_scale: 0.0, ..Default::default() }).unwrap();+ p.add_collider(Some(b), &ColliderDesc { mass: Some(mass), ..ColliderDesc::new(Shape::Box([0.5; 3])) }).unwrap();+ b+ };+ let light = cube(&mut p, [1.5, 0.0, 0.0], 100.0);+ let heavy = cube(&mut p, [-1.5, 0.0, 0.0], 1e4);+ let other = cube(&mut p, [0.0, 1.5, 0.0], 100.0);+ let mut kicked = vec![light, heavy];+ kicked.sort_unstable();+ assert_eq!(p.blast([0.0; 3], 1.0, 0.0, 5.0, &kicked).unwrap(), 2);+ let fall = 1.0 - (1.0f32 / 3.0) * (1.0 / 3.0);+ let want = 5.0 * fall * fall;+ assert!((p.velocity(light).unwrap().0[0] - want).abs() < 1e-5, "{:?}", p.velocity(light));+ assert!((p.velocity(heavy).unwrap().0[0] + want).abs() < 1e-5, "{:?}", p.velocity(heavy));+ assert_eq!(p.velocity(other).unwrap().0, [0.0; 3], "not debris, no push: none");+ let mut q = Physics::default();+ let b = cube(&mut q, [1.5, 0.0, 0.0], 100.0);+ q.blast([0.0; 3], 1.0, 400.0, 5.0, &[b]).unwrap();+ assert!((q.velocity(b).unwrap().0[0] - (400.0 * fall * fall / 100.0 + want)).abs() < 1e-4, "push and kick add: {:?}", q.velocity(b));+ let mut q = Physics::default();+ let b = cube(&mut q, [1.5, 0.0, 0.0], 1.0);+ q.blast([0.0; 3], 1.0, 400.0, 30.0, &[b]).unwrap();+ assert!((q.velocity(b).unwrap().0[0] - BLAST_MAX_DV).abs() < 1e-4, "capped: {:?}", q.velocity(b));+ }++ /// A joint's parameters changed in place (`set_joint`): the same Rapier joint (no frame taken anew); a hinge whose+ /// limits move from [-0.9, -0.2] to [0.2, 0.9] comes to rest at the new lower one, as a hinge made with those limits+ /// does; a motor turned on drives it; a rope shortened holds its weight at the new length; another kind, a fixed+ /// joint, an unknown id or bad numbers are refused and change nothing.+ #[test]+ fn joints_change_in_place() {+ let mut p = Physics::default();+ let post = fixed(&mut p, [0.0, 5.0, 0.0]);+ let door = p.add_body(&BodyDesc { position: [0.5, 5.0, 0.0], can_sleep: false, ..Default::default() }).unwrap();+ p.add_collider(Some(door), &ColliderDesc::new(Shape::Box([0.5, 0.05, 0.4]))).unwrap();+ let hinge = |limits: Option<Limits>, motor: Option<Motor>| JointDesc::Revolute { anchor1: [0.0; 3], anchor2: [-0.5, 0.0, 0.0], axis: [0.0, 0.0, 1.0], limits, motor };+ let j = p.add_joint(post, door, &hinge(Some(Limits { min: -0.9, max: -0.2 }), None)).unwrap();+ let h = p.joints[&j];+ run(&mut p, 400);+ let down = |p: &Physics| { let pos = p.pose(door).unwrap().0; (-(pos[1] - 5.0)).atan2(pos[0]) };+ assert!((down(&p) - 0.9).abs() < 0.03, "rests at its limit: {}", down(&p));+ let frame2 = p.world.impulse_joints.get(h).unwrap().data.local_frame2;+ p.set_joint(j, &hinge(Some(Limits { min: 0.2, max: 0.9 }), None)).unwrap();+ assert_eq!(p.joints[&j], h, "the same joint");+ assert_eq!(p.world.impulse_joints.get(h).unwrap().data.local_frame2, frame2, "its frame on the door not taken anew");+ run(&mut p, 400);+ assert!((down(&p) + 0.2).abs() < 0.03, "rests at the new limit (0.2 rad up): {}", down(&p));+ // A motor, no limits: it turns.+ p.set_joint(j, &hinge(None, Some(Motor { velocity: 2.0, damping: 1e5, max_force: 1e5 }))).unwrap();+ run(&mut p, 30);+ assert!((p.velocity(door).unwrap().1[2] - 2.0).abs() < 0.1, "{:?}", p.velocity(door));+ // Refused, nothing changed.+ let before = p.world.impulse_joints.get(h).unwrap().data.clone();+ for bad in [+ JointDesc::Prismatic { anchor1: [0.0; 3], anchor2: [0.0; 3], axis: [1.0, 0.0, 0.0], limits: None, motor: None },+ hinge(Some(Limits { min: 1.0, max: 0.0 }), None),+ hinge(None, Some(Motor { velocity: f32::NAN, damping: 1.0, max_force: 1.0 })),+ hinge(None, Some(Motor { velocity: 1.0, damping: -1.0, max_force: 1.0 })),+ ] {+ assert!(p.set_joint(j, &bad).is_err(), "{bad:?}");+ assert_eq!(format!("{:?}", p.world.impulse_joints.get(h).unwrap().data), format!("{before:?}"));+ }+ assert!(p.set_joint(9999, &hinge(None, None)).is_err());+ let weld = p.add_joint(post, door, &JointDesc::Fixed { anchor1: [0.0; 3], anchor2: [-0.5, 0.0, 0.0] }).unwrap();+ assert!(p.set_joint(weld, &JointDesc::Fixed { anchor1: [0.0; 3], anchor2: [0.0; 3] }).is_err());+ p.remove_joint(weld);+ // A rope from 3 m to 1.5 m.+ let mut q = Physics::default();+ let top = fixed(&mut q, [0.0, 10.0, 0.0]);+ let w = q.add_body(&BodyDesc { position: [0.0, 8.0, 0.0], can_sleep: false, ..Default::default() }).unwrap();+ q.add_collider(Some(w), &ColliderDesc::new(Shape::Sphere(0.1))).unwrap();+ let rope = q.add_joint(top, w, &JointDesc::Rope { anchor1: [0.0; 3], anchor2: [0.0; 3], length: 3.0 }).unwrap();+ run(&mut q, 200);+ assert!((10.0 - q.pose(w).unwrap().0[1] - 3.0).abs() < 0.03);+ q.set_joint(rope, &JointDesc::Rope { anchor1: [0.0; 3], anchor2: [0.0; 3], length: 1.5 }).unwrap();+ run(&mut q, 300);+ assert!((10.0 - q.pose(w).unwrap().0[1] - 1.5).abs() < 0.03, "{:?}", q.pose(w));+ assert!(q.set_joint(rope, &JointDesc::Rope { anchor1: [0.0; 3], anchor2: [0.0; 3], length: -1.0 }).is_err());+ }+/// A slider along x: gravity does not take it off its axis (within 2 mm); its motor brings it to 1.5 m/s; it stops at/// the limit, 2 m along.#[test]@@ -1759,7 +2145,7 @@ mod tests {// Carved to nothing: the collider is gone, the body is the caller's to remove.assert_eq!(p.edit_voxels(c, &block([0, 0, 0], [4, 2, 4]), &[]).unwrap(), 0);assert!(!p.has_collider(c) && p.voxels(c).is_none());- assert!(p.remove_body(b).is_empty());+ assert!(p.remove_body(b).0.is_empty());run(&mut p, 30);assert!(p.take_faults().is_empty());}diff --git a/renderer/src/api.rs b/renderer/src/api.rsindex 7952903..4a4521c 100644--- a/renderer/src/api.rs+++ b/renderer/src/api.rs@@ -59,8 +59,10 @@ pub fn voxel_level(v: &mut VoxelWorld, d: &Value) -> Result<()> {}/// An explosion: what it did, as JSON.-pub fn voxel_explode(v: &mut VoxelWorld, w: &mut World, p: &mut Option<PhysicsWorld>, x: f64, y: f64, z: f64, r: f64) -> Result<String> {- Ok(v.explode(w, p, Vec3::new(x as f32, y as f32, z as f32), r as f32)?.to_string())+pub fn voxel_explode(v: &mut VoxelWorld, w: &mut World, p: &mut Option<PhysicsWorld>, x: f64, y: f64, z: f64, r: f64, push: Option<f64>) -> Result<String> {+ // (A push out of range or not finite is refused before anything changes: `VoxelWorld::explode`.)+ let push = push.map_or(crate::voxel::DEFAULT_PUSH, |p| if p.is_finite() && p.abs() <= f32::MAX as f64 { p as f32 } else { f32::NAN });+ Ok(v.explode(w, p, Vec3::new(x as f32, y as f32, z as f32), r as f32, push)?.to_string())}/// An edit of the level (`voxelEdit({ op, sphere | box | capsule, material })`; voxel.rs `EditOp`).diff --git a/renderer/src/script.rs b/renderer/src/script.rsindex f28312c..21cb2bd 100644--- a/renderer/src/script.rs+++ b/renderer/src/script.rs@@ -227,7 +227,7 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Rlet v = voxels.clone();e.set("voxelLevel", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> { let json = to_json(&d)?; api::voxel_level(&mut v.borrow_mut(), &json).map_err(|e| thrown(&ctx, e)) })?)?;let (v, w, p, d) = (voxels.clone(), world.clone(), physics.clone(), budget.clone());- e.set("voxelExplode", Function::new(ctx.clone(), move |ctx: Ctx, x: f64, y: f64, z: f64, r: f64| -> rquickjs::Result<String> { let _lent = Lent::new(&ctx, &d)?; api::voxel_explode(&mut v.borrow_mut(), &mut w.borrow_mut(), &mut p.borrow_mut(), x, y, z, r).map_err(|e| thrown(&ctx, e)) })?)?;+ e.set("voxelExplode", Function::new(ctx.clone(), move |ctx: Ctx, x: f64, y: f64, z: f64, r: f64, push: rquickjs::function::Opt<f64>| -> rquickjs::Result<String> { let _lent = Lent::new(&ctx, &d)?; api::voxel_explode(&mut v.borrow_mut(), &mut w.borrow_mut(), &mut p.borrow_mut(), x, y, z, r, push.0).map_err(|e| thrown(&ctx, e)) })?)?;// An edit of the level (`voxelEdit({ op, sphere | box | capsule, material })`; voxel.rs `EditOp`), and the level's// hash (16 hex digits; "" before a level): the same commands give the same hash.let (v, w, p, dl) = (voxels.clone(), world.clone(), physics.clone(), budget.clone());@@ -244,6 +244,10 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Re.set("voxelContacts", Function::new(ctx.clone(), move |ctx: Ctx, body: f64, on: bool| -> rquickjs::Result<()> { api::voxel_contacts(&mut v.borrow_mut(), &mut p.borrow_mut(), body, on).map_err(|e| thrown(&ctx, e)) })?)?;let v = voxels.clone();e.set("voxelGone", Function::new(ctx.clone(), move || -> String { api::voxel_gone(&mut v.borrow_mut()) })?)?;+ // The world's anchor (step 10 c1: a fixed body with no collider; a joint to the level holds to it), -1 before a level+ // that collides.+ let v = voxels.clone();+ e.set("voxelLevelBody", Function::new(ctx.clone(), move || -> f64 { v.borrow().level_body().map_or(-1.0, |b| b as f64) })?)?;let v = voxels.clone();e.set("voxelHash", Function::new(ctx.clone(), move || -> String { api::voxel_hash(&v.borrow()) })?)?;let v = voxels.clone();diff --git a/renderer/src/voxel.rs b/renderer/src/voxel.rsindex 81f5a1d..a9bef42 100644--- a/renderer/src/voxel.rs+++ b/renderer/src/voxel.rs@@ -173,9 +173,35 @@ struct VoxelObject {flying: Option<Vec<MeshPart>>,}+/// The cell a joint's anchor is held by (step 10 c1): the cell the point is in if it is solid, else the solid one of its+/// 26 neighbours whose centre is nearest the point (first in x, y, z order on a tie); none if all are empty (the+/// joint is then on the body, not on a cell, and follows the body).+fn anchor_cell(a: [f32; 3], size: f32, mut solid: impl FnMut([i32; 3]) -> bool) -> Option<[i32; 3]> {+ let c = a.map(|v| (v / size).floor() as i32);+ if solid(c) {+ return Some(c);+ }+ let mut best: Option<([i32; 3], f32)> = None;+ for dz in -1..=1 {+ for dy in -1..=1 {+ for dx in -1..=1 {+ let n = [c[0] + dx, c[1] + dy, c[2] + dz];+ if (dx, dy, dz) == (0, 0, 0) || !solid(n) {+ continue;+ }+ let d = (0..3).map(|k| ((n[k] as f32 + 0.5) * size - a[k]).powi(2)).sum::<f32>();+ if best.is_none_or(|(_, bd)| d < bd) {+ best = Some((n, d));+ }+ }+ }+ }+ best.map(|b| b.0)+}+/// What `VoxelWorld::check_script` ends in, natively and in wasm32 alike (recorded: a change of the voxel bodies'/// behaviour, of the physics or of a platform's arithmetic shows here).-pub const EXPECTED_SCRIPT: u64 = 0x0235_ba72_5c92_2a63;+pub const EXPECTED_SCRIPT: u64 = 0x3329_720d_f1b3_1ca3;/// A brick as a collider's shell reads it (`VoxelWorld::brick_at`).#[derive(Clone, Copy)]@@ -213,8 +239,23 @@ enum Queued {pub struct EditOp {pub shape: ShapeM,pub kind: EditKind,+ /// An explosion's push (step 10 c1): the impulse per area at the blast, N s / m² per m of its radius, on every+ /// dynamic body within 3 radii (`physics_core::Physics::blast`). None: no push (a carve).+ pub blast: Option<f32>,}+/// An explosion's push when scene code names none (N s / m² per m of radius): a 1 m blast gives a 1 m² face at 1 m+/// 400 x (1 - (1/3)²)² = 316 N s (a 100 kg crate thrown at 3.16 m/s).+pub const DEFAULT_PUSH: f32 = 400.0;+/// The kick of the debris an explosion cuts loose (m/s at its radius per unit of push): the parts it makes leave at+/// `push` x this, whatever their mass, falling off with distance as the push does (`physics_core::Physics::blast`).+/// The default push's 400 gives 8 m/s next to the crater: the push alone, by area, throws a 1 m³ chunk of stone+/// (2,400 kg) at 0.1 m/s and leaves it where it was cut; a charge throws the fragments it breaks off at their own+/// speed whatever their size (docs/VOXEL.md "The blast").+pub const KICK_PER_PUSH: f32 = 0.02;+/// The largest push scene code may ask for.+pub const MAX_PUSH: f32 = 10_000.0;+#[derive(Clone, Copy, Debug)]pub enum ShapeM {Sphere([f32; 3], f32),@@ -250,6 +291,17 @@ impl EditOp {return Err(anyhow!("voxelEdit: a shape of finite numbers is needed: sphere [x, y, z, r], box [x0, y0, z0, x1, y1, z1] or capsule [x0, y0, z0, x1, y1, z1, r]"));};let material = || j["material"].as_u64().filter(|m| (1..256).contains(m)).map(|m| m as u8).ok_or_else(|| anyhow!("voxelEdit: material must be a palette index from 1 to 255"));+ let explode = j["op"].as_str() == Some("explode");+ let blast = match &j["push"] {+ serde_json::Value::Null => explode.then_some(DEFAULT_PUSH),+ v => {+ let push = v.as_f64().filter(|p| p.is_finite() && (0.0..=MAX_PUSH as f64).contains(p)).ok_or_else(|| anyhow!("voxelEdit: push must be a number from 0 to {MAX_PUSH}"))? as f32;+ if !explode {+ return Err(anyhow!("voxelEdit: push is an explosion's (op \"explode\")"));+ }+ Some(push)+ }+ };let kind = match j["op"].as_str() {Some("explode") => EditKind::Carve(RADII),Some("carve") => EditKind::Carve([256, 256, 256, 0]),@@ -257,7 +309,7 @@ impl EditOp {Some("add") => EditKind::Add(material()?),other => return Err(anyhow!("voxelEdit: op {other:?} is none of explode, carve, paint, add")),};- Ok(EditOp { shape, kind })+ Ok(EditOp { shape, kind, blast })}}@@ -297,6 +349,8 @@ pub struct VoxelWorld {/// the loose parts that are bodies (by their index in `objects`), each palette entry's density, the cap on/// bodies, and how many it retired.physics: bool,+ /// The world's anchor (ROADMAP § 6 step 10 c1): a fixed body with no collider that joints to the level hold to.+ level_body: Option<u32>,colliders: Vec<Option<u32>>,bodies: BTreeMap<usize, VoxelBody>,density: Vec<f32>,@@ -306,6 +360,8 @@ pub struct VoxelWorld {pub capped: u64,/// The bodies the edit being made has carved or made: none of them is retired for the cap while it runs.this_edit: std::collections::BTreeSet<usize>,+ /// The engine bodies the edit being made has made (an explosion kicks them: `KICK_PER_PUSH`).+ made: Vec<u32>,/// The bodies gone since scene code last asked (`take_gone`): engine body id and why ("cap", "carved", "fell").gone: Vec<(u32, &'static str)>,/// Under this height (m) a body has left the level: 100 m below its lowest cell.@@ -339,6 +395,12 @@ impl VoxelWorld {Ok(())}+ /// The body that stands for the level in joints (the world's anchor: fixed, with no collider; the level's colliders+ /// are static), once a level that collides is loaded.+ pub fn level_body(&self) -> Option<u32> {+ self.level_body+ }+fn id(&mut self) -> u32 {if self.next_id == 0 {self.next_id = FIRST_ID;@@ -361,6 +423,7 @@ impl VoxelWorld {fn live_ids(&self) -> std::collections::HashSet<u32> {let mut u: std::collections::HashSet<u32> = self.objects.iter().flatten().flat_map(|o| o.parts.iter().flat_map(|p| [p.1, p.2])).collect();u.extend(self.colliders.iter().flatten());+ u.extend(self.level_body);u.extend(self.bodies.values().flat_map(|b| [b.body, b.collider]));u}@@ -527,6 +590,11 @@ impl VoxelWorld {self.floor = self.level.as_ref().map_or(f32::MIN, |l| l.objects.iter().flatten().map(|o| o.lo[1]).min().map_or(f32::MIN, |y| y as f32 * size - 100.0));if self.physics {let p = ph.get_or_insert_with(Default::default);+ // The world's anchor for joints to the level (a fixed body with no collider: the level's colliders are+ // static, on no body).+ let lb = self.id();+ p.bridge().engine_anchor(lb).map_err(|e| anyhow!(e))?;+ self.level_body = Some(lb);let (mut full, mut shapes) = (HashMap::new(), HashMap::new());for k in 0..self.objects.len() {if d.objects.get(k).is_some_and(|o| o.collide == Some(false)) {@@ -677,8 +745,11 @@ impl VoxelWorld {/// Scene code's `voxelExplode`: an explosion at a world position (m) of a radius, each material within its/// hardness's share of it.- pub fn explode(&mut self, w: &mut World, ph: &mut Option<PhysicsWorld>, center: Vec3, radius: f32) -> Result<serde_json::Value> {- self.edit(w, ph, &EditOp { shape: ShapeM::Sphere(center.to_array(), radius), kind: EditKind::Carve(RADII) })+ pub fn explode(&mut self, w: &mut World, ph: &mut Option<PhysicsWorld>, center: Vec3, radius: f32, push: f32) -> Result<serde_json::Value> {+ if !(push.is_finite() && (0.0..=MAX_PUSH).contains(&push)) {+ return Err(anyhow!("voxelExplode: push must be a number from 0 to {MAX_PUSH}"));+ }+ self.edit(w, ph, &EditOp { shape: ShapeM::Sphere(center.to_array(), radius), kind: EditKind::Carve(RADII), blast: Some(push) })}/// An edit (`voxelEdit`): the level's voxels changed (`voxel_core::Level`), the touched objects drawn again in place,@@ -693,6 +764,7 @@ impl VoxelWorld {}self.ticks.0 += 1;self.this_edit.clear();+ self.made.clear();let size = self.size as f64;let fp = |p: [f32; 3]| p.map(|v| to_fp(v as f64 / size));let shape = match op.shape {@@ -714,6 +786,50 @@ impl VoxelWorld {let bounds = (Vec3::new(lo[0] as f32, lo[1] as f32, lo[2] as f32) * s, Vec3::new(hi[0] as f32 + 1.0, hi[1] as f32 + 1.0, hi[2] as f32 + 1.0) * s);let mut out = self.apply(w, ph, &e, vec![bounds])?;out["carve_ms"] = carve_ms.into();+ // Scene code's joints on the level whose anchor's cell the carve took (step 10 c1): on the body its loose part+ // became (they move onto it), or carved (they let go). A carve only takes cells: a joint whose anchor is in a+ // cell still solid is held by it as before (one lookup); for the others the cells as they were are those solid+ // now and those the edit cleared (`Edit::cleared`: carved, cut loose or debris).+ // (A joint whose anchor is more than a cell from every cleared cell is not looked at at all.)+ let joints = match (op.kind, self.level_body, ph.as_ref()) {+ (EditKind::Carve(_), Some(lb), Some(p)) if e.cleared.values().any(|c| !c.is_empty()) => p.bridge_ref().engine_joints_of(lb),+ _ => vec![],+ };+ if let (false, Some(lb), Some(p)) = (joints.is_empty(), self.level_body, ph.as_mut()) {+ let size = self.size;+ let lost: std::collections::HashSet<[i32; 3]> = e.cleared.values().flatten().copied().collect();+ let (mut lo, mut hi) = ([i32::MAX; 3], [i32::MIN; 3]);+ for c in &lost {+ for k in 0..3 {+ lo[k] = lo[k].min(c[k].saturating_sub(1));+ hi[k] = hi[k].max(c[k].saturating_add(1));+ }+ }+ let mut taken = vec![];+ let level = self.level.as_mut().unwrap();+ for (j, _, a) in joints {+ let c0 = a.map(|v| (v / size).floor() as i32);+ if (0..3).any(|k| c0[k] < lo[k] || c0[k] > hi[k]) || level.solid(c0) {+ continue;+ }+ if let Some(c) = anchor_cell(a, size, |c| level.solid(c) || lost.contains(&c)).filter(|&c| !level.solid(c)) {+ taken.push((j, c));+ }+ }+ for (j, c) in taken {+ let at = Vec3::new(c[0] as f32 + 0.5, c[1] as f32 + 0.5, c[2] as f32 + 0.5) * self.size;+ let holder = e.created.iter().filter_map(|&id| self.bodies.get(&(id as usize))).find_map(|x| {+ let (pos, rot, _) = p.bridge_ref().engine_pose(x.body)?;+ let local = Quat::from_array(rot).inverse() * (at - Vec3::from(pos)) / self.size;+ let g = [local.x.floor() as i32, local.y.floor() as i32, local.z.floor() as i32];+ (x.grid.get(g[0], g[1], g[2]) != 0).then_some(x.body)+ });+ match holder {+ Some(nb) if p.bridge().engine_rebind_joint(j, lb, nb).is_ok() => {}+ _ => p.bridge().engine_break_joint(j),+ }+ }+ }// The bodies the shape reaches are carved too (a carve only: paint and added voxels are the level's).if let (EditKind::Carve(radii), Some(p)) = (op.kind, ph.as_mut().filter(|_| !self.bodies.is_empty())) {let t = Instant::now();@@ -722,6 +838,15 @@ impl VoxelWorld {out["bodies_carved"] = b.1.into();out["bodies_ms"] = (t.elapsed().as_secs_f64() * 1e3).into();}+ // An explosion's push: on every dynamic body near it, the parts it just cut loose too, and those kicked as well+ // (step 10 c1). Its radius is the one the carve took (held to `MAX_RADIUS` voxels).+ if let (Some(push), Some(p)) = (op.blast, ph.as_mut()) {+ let (centre, radius) = shape_reach(level_shape(op.shape, self.size));+ let kick = (push * KICK_PER_PUSH).min(physics_core::limits::BLAST_MAX_DV);+ let n = p.bridge().engine_blast(centre.to_array(), radius, push, kick, &self.made).map_err(|e| anyhow!(e))?;+ out["pushed"] = n.into();+ out["kicked"] = self.made.len().into();+ }// Paint reaches the bodies too; added voxels are the level's (`edit_body` adds to a body).if let (EditKind::Paint(m), Some(p)) = (op.kind, ph.as_mut().filter(|_| !self.bodies.is_empty())) {let b = self.paint_bodies(w, p, op.shape, m, None)?;@@ -1107,6 +1232,10 @@ impl VoxelWorld {}v.colliders = vec![None; blocks.len()];let p = ph.get_or_insert_with(Default::default);+ // (The world's anchor, as a loaded level has.)+ let lb = v.id();+ p.bridge().engine_anchor(lb).unwrap();+ v.level_body = Some(lb);let (mut full, mut shapes) = (HashMap::new(), HashMap::new());for k in 0..blocks.len() {v.collide(p, k, &mut full, &mut shapes);@@ -1117,8 +1246,9 @@ impl VoxelWorld {/// The voxel bodies' determinism script (tools/physics-determinism.ts runs it natively and in wasm32, in the/// renderer's graph): a tower on two terrain tiles is undercut on one side, so what is above the cut is a body/// that lands on the stump off its balance and topples; an explosion where it lies carves it as it is turned (its- /// cells' centres through the body's pose) and cuts it in bodies; the ground under them is carved. The level's- /// hash and the physics world's, folded every 20 ticks and after every edit.+ /// cells' centres through the body's pose) and cuts it in bodies; the ground under them is carved; an explosion+ /// beside them pushes them (step 10 c1). The level's hash and the physics world's, folded every 20 ticks and after+ /// every edit.pub fn check_script() -> u64 {let mut w = World::default();let mut ph: Option<PhysicsWorld> = None;@@ -1139,7 +1269,7 @@ impl VoxelWorld {}};let edit = |h: &mut u64, v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>, shape: ShapeM| {- v.edit(w, ph, &EditOp { shape, kind: EditKind::Carve([256; 4]) }).expect("an edit");+ v.edit(w, ph, &EditOp { shape, kind: EditKind::Carve([256; 4]), blast: None }).expect("an edit");w.take_changes();fold(h, v, ph);};@@ -1155,6 +1285,22 @@ impl VoxelWorld {run(&mut h, &mut v, &mut w, &mut ph, 120);edit(&mut h, &mut v, &mut w, &mut ph, ShapeM::Sphere([at[0], 0.8, at[2]], 0.9));run(&mut h, &mut v, &mut w, &mut ph, 240);+ // Step 10 c1: an explosion beside the bodies, its push throwing them (and the parts it cuts loose).+ v.explode(&mut w, &mut ph, Vec3::new(at[0] - 0.6, 0.9, at[2]), 0.5, DEFAULT_PUSH).expect("an explosion");+ w.take_changes();+ fold(&mut h, &v, &ph);+ run(&mut h, &mut v, &mut w, &mut ph, 120);+ // An explosion through the largest body's centre of mass: the parts it cuts the body into kicked away from it.+ let mid = ph.as_ref().and_then(|p| {+ let b = v.bodies.values().max_by_key(|b| b.grid.count())?;+ let (at, rot, _) = p.bridge_ref().engine_pose(b.body)?;+ let com = p.bridge_ref().engine_mass_properties(b.body)?.1;+ Some(Mat4::from_rotation_translation(Quat::from_array(rot), Vec3::from(at)).transform_point3(Vec3::from(com)))+ });+ v.explode(&mut w, &mut ph, mid.unwrap_or(Vec3::new(5.5, 0.9, 3.1)), 0.5, DEFAULT_PUSH).expect("an explosion");+ w.take_changes();+ fold(&mut h, &v, &ph);+ run(&mut h, &mut v, &mut w, &mut ph, 120);// Step 10 (a): the largest body painted dense on one side from the world, then grown by a block of its own on// that side (mass by cell: it settles another way).v.density.push(7800.0);@@ -1170,11 +1316,11 @@ impl VoxelWorld {Some((x.body, Mat4::from_rotation_translation(Quat::from_array(rot), Vec3::from(at)).transform_point3(mid).to_array()))}).unwrap_or((0, [5.5, 1.0, 3.1]));- v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Sphere([at[0] + 0.3, at[1], at[2]], 0.7), kind: EditKind::Paint(2) }).expect("a paint");+ v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Sphere([at[0] + 0.3, at[1], at[2]], 0.7), kind: EditKind::Paint(2), blast: None }).expect("a paint");w.take_changes();fold(&mut h, &v, &ph);if v.bodies.values().any(|x| x.body == b) {- v.edit_body(&mut w, &mut ph, b, &EditOp { shape: ShapeM::Box([at[0] + 0.2, at[1] - 0.3, at[2] - 0.3], [at[0] + 0.8, at[1] + 0.3, at[2] + 0.3]), kind: EditKind::Add(2) }).expect("an add");+ v.edit_body(&mut w, &mut ph, b, &EditOp { shape: ShapeM::Box([at[0] + 0.2, at[1] - 0.3, at[2] - 0.3], [at[0] + 0.8, at[1] + 0.3, at[2] + 0.3]), kind: EditKind::Add(2), blast: None }).expect("an add");w.take_changes();}fold(&mut h, &v, &ph);@@ -1235,6 +1381,7 @@ impl VoxelWorld {eprintln!("voxels: a body's mass was not set ({e})");}self.this_edit.insert(k);+ self.made.push(body);let parts = self.body_parts(w, k, &grid, position, rotation)?;if self.objects.len() <= k {self.objects.resize_with(k + 1, || None);@@ -1380,6 +1527,9 @@ impl VoxelWorld {}voxels += gone.len();carved += 1;+ // Scene code's joints on it, each by the cell its anchor is held by (before the carve takes cells).+ let body_id = b.body;+ let anchored: Vec<(physics_core::JointId, [i32; 3])> = p.bridge_ref().engine_joints_of(body_id).into_iter().filter_map(|(j, _, a)| anchor_cell(a, size, |c| b.grid.get(c[0], c[1], c[2]) != 0).map(|c| (j, c))).collect();// (What is left of it is not retired for the cap while this carve makes the parts it cut off.)self.this_edit.insert(k);self.keep(gone.iter().map(|&(g, mat)| (centre_of(g), mat)));@@ -1398,6 +1548,21 @@ impl VoxelWorld {cleared.extend(part);loose.push(with);}+ // Each anchored joint: its cell carved (broken), gone into a part cut off (it moves with that part), or still+ // here. A joint is the material's at its anchor.+ // (By cell: what the carve took, and which part each loose cell is in.)+ let mut moves: Vec<(physics_core::JointId, usize)> = vec![];+ if !anchored.is_empty() {+ let carved: std::collections::HashSet<[i32; 3]> = gone.iter().map(|g| g.0).collect();+ let part_of: HashMap<[i32; 3], usize> = loose.iter().enumerate().flat_map(|(i, part)| part.iter().map(move |&(g, _)| (g, i))).collect();+ for &(j, c) in &anchored {+ if carved.contains(&c) {+ p.bridge().engine_break_joint(j);+ } else if let Some(&i) = part_of.get(&c) {+ moves.push((j, i));+ }+ }+ }let (collider, left) = (b.collider, b.grid.count());if left == 0 {self.retire(w, p, k, false, "carved");@@ -1405,8 +1570,12 @@ impl VoxelWorld {let _ = collider;self.redraw_body(w, p, k, &cleared, &[], Vec3::from(at), Quat::from_array(rot))?;}- for part in loose {+ for (i, part) in loose.into_iter().enumerate() {if part.len() < MIN_PIECE {+ // (Debris: a joint held by a cell of it lets go.)+ for &(j, _) in moves.iter().filter(|m| m.1 == i) {+ p.bridge().engine_break_joint(j);+ }self.keep(part.iter().map(|&(g, mat)| (centre_of(g), mat)));continue;}@@ -1423,6 +1592,14 @@ impl VoxelWorld {l.objects.resize_with(n + 1, || None);}self.add_body(w, p, n, grid, corner, Quat::from_array(rot), velocity)?;+ // The joints held by a cell of this part move onto its body (or let go if it was not made one).+ let new_body = self.bodies.get(&n).map(|x| x.body);+ for &(j, _) in moves.iter().filter(|m| m.1 == i) {+ match new_body {+ Some(nb) if p.bridge().engine_rebind_joint(j, body_id, nb).is_ok() => {}+ _ => p.bridge().engine_break_joint(j),+ }+ }}}Ok((voxels, carved))@@ -1611,6 +1788,7 @@ impl VoxelWorld {}self.ticks.0 += 1;self.this_edit.clear();+ self.made.clear();let (voxels, n) = match op.kind {EditKind::Carve(radii) => self.carve_bodies(w, p, op.shape, radii, Some(k))?,EditKind::Paint(m) => self.paint_bodies(w, p, op.shape, m, Some(k))?,@@ -2168,7 +2346,7 @@ mod tests {assert!(v.objects[part].as_ref().unwrap().flying.is_none());assert_eq!(v.frame(&mut w, 1.0 / 60.0).unwrap()["batches"], 0);// An explosion at the stump: the post is hard (0.4 of the radius), the slab soft (a crater 0.3 m deep under it).- let e = v.explode(&mut w, &mut None, Vec3::new(0.0, 0.6, 0.0), 0.5).unwrap();+ let e = v.explode(&mut w, &mut None, Vec3::new(0.0, 0.6, 0.0), 0.5, DEFAULT_PUSH).unwrap();assert!(e["voxels"].as_u64().unwrap() > 100, "{e}");// (It took the stump's foot: what stood on it falls into the crater. Edits reach static voxels only: let it// land.)@@ -2445,7 +2623,7 @@ mod tests {let mut v = VoxelWorld::of_blocks(&blocks, &mut w, &mut ph);v.max_bodies = 6;v.keep_debris = true;- let cut = |v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>, lo: [f32; 3], hi: [f32; 3]| v.edit(w, ph, &EditOp { shape: ShapeM::Box(lo, hi), kind: EditKind::Carve([256; 4]) }).unwrap();+ let cut = |v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>, lo: [f32; 3], hi: [f32; 3]| v.edit(w, ph, &EditOp { shape: ShapeM::Box(lo, hi), kind: EditKind::Carve([256; 4]), blast: None }).unwrap();for k in 0..6 {let x = 0.8 + 0.8 * k as f32;cut(&mut v, &mut w, &mut ph, [x - 0.1, 0.5, 0.7], [x + 0.5, 0.7, 1.3]);@@ -2622,6 +2800,192 @@ mod tests {assert!(!gone.is_empty() && gone.iter().all(|s| !s), "its contacts end: {gone:?}");}+ /// Joints to the level hold to the world's anchor (step 10 c1), a fixed body with no collider: a scene body hangs+ /// from the level by a rope (2 m, held within 2 cm); the level's colliders are static, on no body (`body` null to a+ /// ray and to contacts: `engineColliders`); a body resting on it falls asleep; the anchor does not move (`pose`+ /// refused); a fixed body of scene code's weighs what its colliders do.+ #[test]+ fn the_level_has_an_anchor_that_joints_hold_to() {+ let mut w = World::default();+ let mut ph: Option<PhysicsWorld> = None;+ let mut v = VoxelWorld::of_blocks(&[([0, 0, 0], [64, 4, 64], Some((0, 0)), true)], &mut w, &mut ph);+ let level = v.level_body().expect("a level body");+ assert!(level >= physics_core::bridge::ENGINE_IDS);+ let p = ph.as_mut().unwrap();+ assert_eq!(p.bridge().engine_anchor_body(), Some(level));+ assert!(p.call(&mut w, "pose", &serde_json::json!({ "body": level, "position": [0, 50, 0] })).is_err());+ p.call(&mut w, "body", &serde_json::json!({ "id": 7, "kind": "fixed", "position": [20, 20, 20] })).unwrap();+ p.call(&mut w, "collider", &serde_json::json!({ "id": 7, "body": 7, "shape": { "type": "sphere", "radius": 0.5 }, "mass": 12.0 })).unwrap();+ assert_eq!(p.call(&mut w, "state", &serde_json::json!({ "body": 7 })).unwrap()["mass"], serde_json::json!(12.0));+ // A ray down at the slab: the level, on no body.+ let hit = p.call(&mut w, "ray", &serde_json::json!({ "origin": [3.0, 5.0, 3.0], "direction": [0, -1, 0] })).unwrap();+ assert!(hit["collider"].as_u64().is_some() && hit["body"].is_null(), "{hit}");+ // A box resting on it, listening: its contact's other end is on no body; it falls asleep.+ p.call(&mut w, "body", &serde_json::json!({ "id": 1, "position": [1.0, 0.6, 1.0] })).unwrap();+ p.call(&mut w, "collider", &serde_json::json!({ "id": 1, "body": 1, "shape": { "type": "box", "halfExtents": [0.2, 0.2, 0.2] }, "events": true })).unwrap();+ // A ball hanging from the level by a rope 2 m long, from a point 3 m above the slab's top.+ p.call(&mut w, "body", &serde_json::json!({ "id": 2, "position": [4.0, 3.4, 4.0] })).unwrap();+ p.call(&mut w, "collider", &serde_json::json!({ "id": 2, "body": 2, "shape": { "type": "sphere", "radius": 0.1 } })).unwrap();+ p.call(&mut w, "joint", &serde_json::json!({ "id": 3, "a": level, "b": 2, "type": "rope", "length": 2.0, "anchor1": [4.0, 3.4, 4.0] })).unwrap();+ for _ in 0..240 {+ crate::api::physics_advance(&mut ph, &mut v, &mut w, 1.0 / 60.0);+ }+ let p = ph.as_mut().unwrap();+ let ball = p.call(&mut w, "state", &serde_json::json!({ "body": 2 })).unwrap();+ let y = ball["position"][1].as_f64().unwrap();+ assert!((3.4 - y - 2.0).abs() < 0.02, "hangs 2 m below its anchor: {ball}");+ let contacts = p.call(&mut w, "contacts", &serde_json::json!({})).unwrap();+ let mine: Vec<_> = contacts.as_array().unwrap().iter().filter(|c| c["bodyA"].as_u64() == Some(1) || c["bodyB"].as_u64() == Some(1)).collect();+ assert!(!mine.is_empty() && mine.iter().all(|c| c["bodyA"].is_null() || c["bodyB"].is_null()), "the level's end on no body: {contacts}");+ let crate_ = p.call(&mut w, "state", &serde_json::json!({ "body": 1 })).unwrap();+ assert_eq!(crate_["sleeping"], serde_json::json!(true), "{crate_}");+ }++ /// A joint belongs to the material at its anchor (step 10 c1). On a voxel body: cut so that its anchor's cell is in+ /// the part cut off, the joint moves onto that part's body (the same joint to scene code, its anchor where it was);+ /// its anchor's cell carved, it breaks (reported, gone from the world); its body carved away whole, it breaks. On the+ /// level: its anchor in a part that comes loose, it moves onto that body; its anchor's cell carved, it breaks.+ #[test]+ fn joints_follow_the_cells_their_anchors_are_in() {+ let ball = |p: &mut PhysicsWorld, w: &mut World, id: u32, at: [f32; 3]| {+ p.call(w, "body", &serde_json::json!({ "id": id, "position": at })).unwrap();+ p.call(w, "collider", &serde_json::json!({ "id": id, "body": id, "shape": { "type": "sphere", "radius": 0.05 } })).unwrap();+ };+ // (What the engine did to the joints: the moved ones' ids and bodies, the broken ones' ids.)+ let changes = |p: &mut PhysicsWorld, w: &mut World| {+ let c = p.call(w, "joint_changes", &serde_json::json!({})).unwrap();+ let moved: Vec<(u64, u64)> = c["moved"].as_array().unwrap().iter().map(|m| (m["joint"].as_u64().unwrap(), m["body"].as_u64().unwrap())).collect();+ (moved, c["broken"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect::<Vec<_>>())+ };+ let broken = |p: &mut PhysicsWorld, w: &mut World| changes(p, w).1;+ let on = |p: &PhysicsWorld, body: u32| p.bridge_ref().engine_joints_of(body).len();+ // The bar cut loose (4 x 21 x 4 cells from (2.8, 0.7, 2.8)); a rope from a ball to its lowest layer, one to its top.+ let (mut w, mut ph, mut v) = one_body();+ let b = *v.bodies.values().map(|x| &x.body).next().unwrap();+ let p = ph.as_mut().unwrap();+ ball(p, &mut w, 1, [5.0, 1.0, 3.0]);+ ball(p, &mut w, 2, [5.0, 3.0, 3.0]);+ p.call(&mut w, "joint", &serde_json::json!({ "id": 10, "a": b, "b": 1, "type": "rope", "length": 2.5, "anchor1": [0.2, 0.05, 0.2] })).unwrap();+ p.call(&mut w, "joint", &serde_json::json!({ "id": 11, "a": b, "b": 2, "type": "rope", "length": 2.5, "anchor1": [0.2, 1.95, 0.2] })).unwrap();+ assert_eq!(on(p, b), 2);+ // Cut across its layers 9 and 10: the lower part (144 cells) is cut off, the upper (160) keeps the body.+ v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "carve", "box": [2.7, 1.6, 2.7, 3.3, 1.8, 3.3] }))).unwrap();+ assert_eq!(v.bodies(), 2);+ let low = *v.bodies.values().map(|x| &x.body).find(|&&x| x != b).unwrap();+ let p = ph.as_mut().unwrap();+ assert_eq!((on(p, b), on(p, low)), (1, 1), "the lower rope moved with the lower part");+ let (_, _, anchor) = p.bridge_ref().engine_joints_of(low)[0];+ let (at, _, _) = p.bridge_ref().engine_pose(low).unwrap();+ let world = [at[0] + anchor[0], at[1] + anchor[1], at[2] + anchor[2]];+ assert!((world[0] - 3.0).abs() < 1e-4 && (world[1] - 0.75).abs() < 1e-4 && (world[2] - 3.0).abs() < 1e-4, "its anchor where it was: {world:?}");+ assert_eq!(changes(p, &mut w), (vec![(10, low as u64)], vec![]), "reported as moved onto the lower part");+ // The top rope's anchor cell carved: it breaks.+ v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "carve", "sphere": [3.0, 2.65, 3.0, 0.08] }))).unwrap();+ let p = ph.as_mut().unwrap();+ assert_eq!(broken(p, &mut w), vec![11]);+ assert_eq!(on(p, b), 0);+ assert!(p.call(&mut w, "joint_set", &serde_json::json!({ "id": 11, "type": "rope", "length": 1.0 })).is_err(), "gone from the world");+ // The lower part carved away whole: its rope breaks.+ v.edit_body(&mut w, &mut ph, low, &op(serde_json::json!({ "op": "carve", "box": [2.0, 0.0, 2.0, 4.0, 1.7, 4.0] }))).unwrap();+ assert_eq!(broken(ph.as_mut().unwrap(), &mut w), vec![10]);++ // The level: a rope to the bar's top while it still stands, another to the slab's top.+ let mut w = World::default();+ let mut ph: Option<PhysicsWorld> = None;+ let mut v = VoxelWorld::of_blocks(&[([0, 0, 0], [64, 4, 64], Some((0, 0)), true), ([28, 4, 28], [4, 24, 4], None, false)], &mut w, &mut ph);+ let lb = v.level_body().unwrap();+ let p = ph.as_mut().unwrap();+ ball(p, &mut w, 1, [3.0, 3.5, 3.0]);+ ball(p, &mut w, 2, [1.0, 1.0, 1.0]);+ p.call(&mut w, "joint", &serde_json::json!({ "id": 20, "a": lb, "b": 1, "type": "rope", "length": 1.0, "anchor1": [3.0, 2.75, 3.0] })).unwrap();+ p.call(&mut w, "joint", &serde_json::json!({ "id": 21, "a": lb, "b": 2, "type": "rope", "length": 1.0, "anchor1": [1.05, 0.35, 1.05] })).unwrap();+ // The bar cut at its foot: it is a body now, and the rope to its top is on it.+ v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [2.7, 0.5, 2.7, 3.3, 0.7, 3.3] }))).unwrap();+ assert_eq!(v.bodies(), 1);+ let bar = *v.bodies.values().map(|x| &x.body).next().unwrap();+ let p = ph.as_mut().unwrap();+ assert_eq!((on(p, lb), on(p, bar)), (1, 1), "the rope to the bar's top moved onto its body");+ assert_eq!(changes(p, &mut w), (vec![(20, bar as u64)], vec![]));+ // The slab's anchor cell carved: that rope breaks.+ v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "sphere": [1.05, 0.35, 1.05, 0.1] }))).unwrap();+ let p = ph.as_mut().unwrap();+ assert_eq!(broken(p, &mut w), vec![21]);+ assert_eq!(on(p, lb), 0);+ }++ /// An explosion pushes the bodies near it (step 10 c1): the bar standing 0.4 m from a 0.3 m blast it does not reach+ /// is thrown away from it, along the line from the blast's centre to its centre of mass; with `push` 0 it is not; a push out of range or of the wrong kind is refused before+ /// anything changes (the level's hash the same).+ #[test]+ fn an_explosion_pushes_the_bodies_near_it() {+ for (push, moves) in [(None, true), (Some(0.0), false)] {+ let (mut w, mut ph, mut v) = one_body();+ let b = *v.bodies.values().map(|x| &x.body).next().unwrap();+ let mut j = serde_json::json!({ "op": "explode", "sphere": [3.6, 1.5, 3.0, 0.3] });+ if let Some(p) = push {+ j["push"] = p.into();+ }+ let e = v.edit(&mut w, &mut ph, &op(j)).unwrap();+ let (lv, _) = ph.as_ref().unwrap().bridge_ref().engine_velocity_of(b).unwrap();+ if moves {+ // Along the line from the blast's centre to the bar's centre of mass (above the blast: up as well).+ let com = ph.as_ref().unwrap().bridge_ref().engine_mass_properties(b).unwrap().1;+ let (at, rot, _) = ph.as_ref().unwrap().bridge_ref().engine_pose(b).unwrap();+ let c = Mat4::from_rotation_translation(Quat::from_array(rot), Vec3::from(at)).transform_point3(Vec3::from(com));+ let along = (c - Vec3::new(3.6, 1.5, 3.0)).normalize();+ let got = Vec3::from(lv);+ assert!(e["pushed"].as_u64().unwrap() >= 1 && got.length() > 0.05 && got.normalize().dot(along) > 0.999, "{e} {lv:?} along {along:?}");+ } else {+ assert!(e["pushed"].is_null() || e["pushed"] == 0, "{e}");+ assert!(lv[0].abs() < 1e-6, "{lv:?}");+ }+ }+ let (mut w, mut ph, mut v) = one_body();+ let before = v.hash();+ for bad in [serde_json::json!(-1.0), serde_json::json!(1e9), serde_json::json!("a")] {+ assert!(EditOp::parse(&serde_json::json!({ "op": "explode", "sphere": [3.0, 0.3, 3.0, 0.5], "push": bad })).is_err(), "{bad}");+ }+ assert!(EditOp::parse(&serde_json::json!({ "op": "carve", "sphere": [3.0, 0.3, 3.0, 0.5], "push": 10 })).is_err(), "push is an explosion's");+ assert!(v.explode(&mut w, &mut ph, Vec3::new(3.0, 0.3, 3.0), 0.5, f32::NAN).is_err());+ assert!(v.explode(&mut w, &mut ph, Vec3::new(3.0, 0.3, 3.0), 0.5, -1.0).is_err());+ assert_eq!(v.hash(), before, "refused before anything changed");+ }++ /// An explosion kicks the debris it cuts loose and reaches no further than it carves (step 10 c1). The bar cut off+ /// at its foot by a 0.25 m blast leaves at more than 5 m/s (the push alone, by its area, gives it under 1 m/s), away+ /// from the blast; with `push` 0 it is cut loose and not thrown. A 600 m blast is a 12.8 m one (`MAX_RADIUS`+ /// voxels), as its carve is: a ball 580 m off, within 3 x 600 m, is not pushed.+ #[test]+ fn an_explosion_kicks_its_debris_and_reaches_what_it_carves() {+ for (push, thrown) in [(None, true), (Some(0.0), false)] {+ let mut w = World::default();+ let mut ph: Option<PhysicsWorld> = None;+ let mut v = VoxelWorld::of_blocks(&[([0, 0, 0], [64, 4, 64], Some((0, 0)), true), ([28, 4, 28], [4, 24, 4], None, false)], &mut w, &mut ph);+ let mut j = serde_json::json!({ "op": "explode", "sphere": [3.0, 0.6, 3.0, 0.25] });+ if let Some(p) = push {+ j["push"] = p.into();+ }+ let e = v.edit(&mut w, &mut ph, &op(j)).unwrap();+ assert_eq!((v.bodies(), e["kicked"].as_u64()), (1, Some(1)), "{e}");+ let b = *v.bodies.values().map(|x| &x.body).next().unwrap();+ let (lv, _) = ph.as_ref().unwrap().bridge_ref().engine_velocity_of(b).unwrap();+ let speed = Vec3::from(lv).length();+ if thrown {+ assert!(speed > 5.0 && lv[1] > 0.0, "kicked up and away: {lv:?} {e}");+ } else {+ assert!(speed < 1e-6, "{lv:?}");+ }+ }+ let (mut w, mut ph, mut v) = one_body();+ let p = ph.as_mut().unwrap();+ p.call(&mut w, "gravity", &serde_json::json!({ "gravity": [0, 0, 0] })).unwrap();+ p.call(&mut w, "body", &serde_json::json!({ "id": 1, "position": [-80.0, 0.0, 0.0] })).unwrap();+ p.call(&mut w, "collider", &serde_json::json!({ "id": 1, "body": 1, "shape": { "type": "sphere", "radius": 0.5 } })).unwrap();+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "explode", "sphere": [500.0, 300.0, 0.0, 600.0] }))).unwrap();+ assert_eq!((e["voxels"].as_u64(), e["pushed"].as_u64()), (Some(0), Some(0)), "{e}");+ assert_eq!(ph.as_mut().unwrap().call(&mut w, "state", &serde_json::json!({ "body": 1 })).unwrap()["linvel"], serde_json::json!([0.0, 0.0, 0.0]));+ }+/// The same body as one more check: a slab and a bar cut loose (336 voxels of 1,000 kg/m³).fn one_body() -> (World, Option<PhysicsWorld>, VoxelWorld) {let mut w = World::default();@@ -2699,18 +3063,18 @@ mod tests {let body_voxels = |v: &VoxelWorld| v.bodies.values().map(|b| b.grid.count()).sum::<usize>();// A sphere of 600 m centred 500 m away: 12.8 m as the level takes it, which does not reach.let (mut w, mut ph, mut v) = one();- if let Ok(e) = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Sphere([500.0, 0.0, 0.0], 600.0), kind: EditKind::Carve([256; 4]) }) {+ if let Ok(e) = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Sphere([500.0, 0.0, 0.0], 600.0), kind: EditKind::Carve([256; 4]), blast: None }) {assert_eq!((e["voxels"].as_u64(), e["body_voxels"].as_u64().unwrap_or(0)), (Some(0), 0), "{e}");}assert_eq!(body_voxels(&v), 336);// A negative radius at the body: nothing, as in the level.let (mut w, mut ph, mut v) = one();- let e = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Sphere([3.0, 1.5, 3.0], -2.0), kind: EditKind::Carve([256; 4]) }).unwrap();+ let e = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Sphere([3.0, 1.5, 3.0], -2.0), kind: EditKind::Carve([256; 4]), blast: None }).unwrap();assert_eq!(e["body_voxels"].as_u64().unwrap_or(0), 0, "{e}");assert_eq!(body_voxels(&v), 336);// A box over the body's upper half with every class at half its share: the half, whole.let (mut w, mut ph, mut v) = one();- let e = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Box([2.5, 1.75, 2.5], [3.5, 3.0, 3.5]), kind: EditKind::Carve([128; 4]) }).unwrap();+ let e = v.edit(&mut w, &mut ph, &EditOp { shape: ShapeM::Box([2.5, 1.75, 2.5], [3.5, 3.0, 3.5]), kind: EditKind::Carve([128; 4]), blast: None }).unwrap();assert_eq!(e["body_voxels"].as_u64(), Some(16 * 11), "{e}");}@@ -2872,7 +3236,7 @@ mod tests {for (n, r) in [0.5f32, 1.0, 2.0, 4.0].into_iter().enumerate() {let at = foot + Vec3::new(0.0, 0.0, (n as f32 - 1.5) * (hi.z - lo.z) * 0.2);let t = Instant::now();- let e = v.explode(&mut w, &mut ph, at, r).unwrap();+ let e = v.explode(&mut w, &mut ph, at, r, DEFAULT_PUSH).unwrap();let ms = t.elapsed().as_secs_f64() * 1e3;println!("explosion of {r} m: {ms:.2} ms in all: carve {:.2}, colliders {:.2}, meshes {:.2}, parts {:.2} (meshes and bodies {:.2}), bodies carved {:.2}; {} voxels, {} objects touched, {} parts of {} voxels; bodies now {}", e["carve_ms"].as_f64().unwrap(), e["colliders_ms"].as_f64().unwrap(), e["rebuild_ms"].as_f64().unwrap(), e["pieces_ms"].as_f64().unwrap(), e["piece_mesh_ms"].as_f64().unwrap(), e["bodies_ms"].as_f64().unwrap_or(0.0), e["voxels"], e["touched"], e["pieces"], e["piece_voxels"], e["bodies"]);w.take_changes();@@ -2894,7 +3258,7 @@ mod tests {frames(&mut v, &mut w, &mut ph, 300, "the next five");// An explosion into what fell.let t = Instant::now();- let e = v.explode(&mut w, &mut ph, Vec3::new((lo.x + hi.x) * 0.5, lo.y + 2.0, (lo.z + hi.z) * 0.5), 3.0).unwrap();+ let e = v.explode(&mut w, &mut ph, Vec3::new((lo.x + hi.x) * 0.5, lo.y + 2.0, (lo.z + hi.z) * 0.5), 3.0, DEFAULT_PUSH).unwrap();println!("an explosion of 3 m into it: {:.2} ms in all: carve {:.2}, colliders {:.2}, bodies carved {:.2} ({} bodies, {} voxels); bodies now {}", t.elapsed().as_secs_f64() * 1e3, e["carve_ms"].as_f64().unwrap(), e["colliders_ms"].as_f64().unwrap(), e["bodies_ms"].as_f64().unwrap_or(0.0), e["bodies_carved"], e["body_voxels"], e["bodies"]);w.take_changes();frames(&mut v, &mut w, &mut ph, 300, "five seconds after");@@ -2917,7 +3281,7 @@ mod tests {let trunks = [[-100.6f32, 9.3, -92.0], [-103.9, 9.1, -93.0], [-86.7, 9.8, -91.1], [-105.9, 9.2, -88.8], [-89.3, 10.0, -88.1], [-105.8, 9.2, -86.5], [-88.1, 10.1, -87.0], [-83.9, 10.0, -90.7]];for t in trunks {let at = Vec3::new(t[0], t[1] + 0.8, t[2]);- let e = v.explode(&mut w, &mut ph, at, 0.6).unwrap();+ let e = v.explode(&mut w, &mut ph, at, 0.6, DEFAULT_PUSH).unwrap();println!("a trunk cut at {at:?}: {} voxels carved, {} parts of {} voxels", e["voxels"], e["pieces"], e["piece_voxels"]);w.take_changes();for _ in 0..30 {diff --git a/renderer/web/src/lib.rs b/renderer/web/src/lib.rsindex cab834c..8be0834 100644--- a/renderer/web/src/lib.rs+++ b/renderer/web/src/lib.rs@@ -99,9 +99,16 @@ pub fn voxel_level(d: &str) -> Result<(), JsValue> {engine(|e| api::voxel_level(&mut e.voxels, &d)).map_err(thrown)}+/// An explosion, its blast's push optional (step 10 c1: `api::voxel_explode`).#[wasm_bindgen(js_name = voxelExplode)]-pub fn voxel_explode(x: f64, y: f64, z: f64, r: f64) -> Result<String, JsValue> {- engine(|e| api::voxel_explode(&mut e.voxels, &mut e.world, &mut e.physics, x, y, z, r)).map_err(thrown)+pub fn voxel_explode(x: f64, y: f64, z: f64, r: f64, push: Option<f64>) -> Result<String, JsValue> {+ engine(|e| api::voxel_explode(&mut e.voxels, &mut e.world, &mut e.physics, x, y, z, r, push)).map_err(thrown)+}++/// The world's anchor (a fixed body with no collider: joints to the level hold to it), -1 before a level that collides.+#[wasm_bindgen(js_name = voxelLevelBody)]+pub fn voxel_level_body() -> f64 {+ engine(|e| e.voxels.level_body().map_or(-1.0, |b| b as f64))}#[wasm_bindgen(js_name = voxelEdit)]diff --git a/renderer/web/www/engine.ts b/renderer/web/www/engine.tsindex ef9535b..b43f48e 100644--- a/renderer/web/www/engine.ts+++ b/renderer/web/www/engine.ts@@ -10,7 +10,8 @@ export interface EngineExports {physics(op: string, args: string): string;physicsPoses(): Float32Array;voxelLevel(d: string): void;- voxelExplode(x: number, y: number, z: number, r: number): string;+ voxelExplode(x: number, y: number, z: number, r: number, push?: number): string;+ voxelLevelBody(): number;voxelEdit(d: string): string;voxelHash(): string;voxelDebris(): Float32Array;@@ -51,7 +52,8 @@ export interface EngineExports {/** The voxel engine's calls (packages/voxel/src/native.ts reads them off `__engine`). */export interface VoxelCalls {voxelLevel(d: object): void;- voxelExplode(x: number, y: number, z: number, r: number): string;+ voxelExplode(x: number, y: number, z: number, r: number, push?: number): string;+ voxelLevelBody(): number;voxelEdit(d: object): string;voxelFrame(dt: number): string;voxelDebris(): Float32Array;@@ -72,7 +74,8 @@ export function webEngine(w: EngineExports): WebEngine {physics: (op, args) => w.physics(op, json(args)),physicsPoses: () => w.physicsPoses(),voxelLevel: (d) => w.voxelLevel(json(d)),- voxelExplode: (x, y, z, r) => w.voxelExplode(x, y, z, r),+ voxelExplode: (x, y, z, r, push) => w.voxelExplode(x, y, z, r, push),+ voxelLevelBody: () => w.voxelLevelBody(),voxelEdit: (d) => w.voxelEdit(json(d)),voxelHash: () => w.voxelHash(),voxelDebris: () => w.voxelDebris(),diff --git a/tests/render/voxel-joint-moved-body.ts b/tests/render/voxel-joint-moved-body.tsnew file mode 100644index 0000000..9224605--- /dev/null+++ b/tests/render/voxel-joint-moved-body.ts@@ -0,0 +1,67 @@+// A joint on a voxel body that the engine moved onto a part cut off stays on that part when the body it was made on+// goes (step 10 c1). voxel/cut-body's level and cut: the upper part comes down onto the stump (y 0.8 .. 3.4). At frame+// 60 a glowing 0.2 m box (the lamp) is held to it by a `FixedJoint` whose anchor is in its lower half (world+// (0.15, 1.4, 0)), the lamp beside it at x = 0.45. At frame 90 a cut through the part at y 1.9 .. 2.1: the upper piece+// (1.3 m) keeps the body, the lower (1.1 m, with the anchor) is a part of its own, and the engine moves the joint onto+// it. At frame 150 the upper piece is carved away whole (its body goes); at frame 160 a body is added to the scene,+// which makes the binding look at its joints. The joint names the lower piece and holds: the lamp is where it was+// (y 1.3 .. 1.5) and the region there reads its 5 nits. A binding that let go of the joint when the first body went+// drops the lamp to the slab (dark there); a failed check (the joint not on a `VoxelBody`, or broken) takes the lamp+// out (dark).+import { BoxGeometry, FixedJoint, Mesh, type Scene, Vector3 } from "@threert/scene";+import { defineGame } from "@threert/gameplay";+import { voxelBodies, voxelCarve, VoxelBody } from "@threert/voxel";+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";+import { glow } from "./physics-box-rest.ts";+import { test as base } from "./voxel-cut-body.ts";+import { cut, level } from "./voxel-cut-falls.ts";++export const test: TestMeta = {+ ...base, id: "voxel/joint-moved-body", temporal: true, time: undefined, live: 240,+ // Camera 8 m away at y = 2, 30 deg vertical fov, 16:9: x -3.81 .. 3.81, y 4.14 .. -0.14. The lamp's middle: x 0.40+ // .. 0.50, y 1.35 .. 1.45.+ metric: { kind: "radiance", region: [0.553, 0.627, 0.565, 0.650], expected: 5, tolerance: 0.03 },+ note: "as voxel/cut-body-live; a lamp held to the part by a fixed joint, the part cut in two, the piece without the anchor carved away",+};++let frames = 0;+let scene: Scene;+let lamp: Mesh | null = null;+let joint: FixedJoint | null = null;+let first: VoxelBody | null = null;+export default defineGame<Record<string, never>>({+ state: {},+ setup: () => {+ frames = 0;+ lamp = joint = first = null;+ scene = sceneWithSky(0);+ level(true);+ return result(scene, camera(scene, [0, 2, 8], [0, 2, 0]));+ },+ frame(f) {+ if (f.dt <= 0) return;+ frames++;+ if (frames === 3) cut();+ if (frames === 60) {+ first = voxelBodies()[0] ?? null;+ if (!first) return;+ // The anchor in the part's own frame.+ const local = new Vector3(0.15, 1.4, 0).sub(first.position).applyQuaternion(first.quaternion.clone().invert());+ lamp = new Mesh(new BoxGeometry(0.2, 0.2, 0.2), glow());+ lamp.position.set(0.45, 1.4, 0);+ lamp.physics = "dynamic";+ joint = new FixedJoint(first, lamp, { anchorA: local, anchorB: new Vector3(-0.3, 0, 0) });+ scene.add(lamp, joint);+ }+ if (frames === 90) voxelCarve({ box: [-0.5, 1.9, -0.5, 0.5, 2.1, 0.5] });+ if (frames === 150) voxelCarve({ box: [-0.5, 1.92, -0.5, 0.5, 3.7, 0.5] });+ if (frames === 160) {+ const crate = new Mesh(new BoxGeometry(0.2, 0.2, 0.2), glow());+ crate.position.set(-2.5, 0.6, 0);+ crate.physics = "dynamic";+ scene.add(crate);+ }+ if (frames === 200 && lamp && joint && (!(joint.bodyA instanceof VoxelBody) || joint.bodyA === first || joint.broken)) scene.remove(lamp);+ },+ handlers: {},+});diff --git a/tests/render/voxel-joint-moved.ts b/tests/render/voxel-joint-moved.tsnew file mode 100644index 0000000..071537d--- /dev/null+++ b/tests/render/voxel-joint-moved.ts@@ -0,0 +1,54 @@+// A joint to the voxel level goes with the material at its anchor (step 10 c1), and the binding knows where it went.+// voxel/cut-body's level and cut: a glowing 0.2 m box (the lamp) is held by a `FixedJoint` to the level, its anchor+// in the upper post's side (0.15, 3.0, 0), the lamp beside it at x = 0.45. The cut lets the upper part down 0.2 m onto+// the stump: the engine moves the joint onto that part's body, and the lamp comes down with it. At frame 120 the frame+// script checks that the joint names the part (`bodyA` its `VoxelBody`, not broken) and makes the lamp's body anew+// (its density changed), which makes the joint anew: on the part, at the anchor the engine reported. So the lamp stays+// 0.2 m lower than it was, beside the part: the region there (y 2.76 .. 2.84) reads its 5 nits. A binding that remade+// the joint on the level at the old anchor would pull the lamp back up (the region dark, at the lamp's bottom edge+// at most); a failed check takes the lamp out (dark).+import { BoxGeometry, engineColliders, FixedJoint, Mesh, type Scene, Vector3 } from "@threert/scene";+import { defineGame } from "@threert/gameplay";+import { VoxelBody } from "@threert/voxel";+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";+import { glow } from "./physics-box-rest.ts";+import { test as base } from "./voxel-cut-body.ts";+import { cut, level } from "./voxel-cut-falls.ts";++export const test: TestMeta = {+ ...base, id: "voxel/joint-moved", temporal: true, time: undefined, live: 240,+ // Camera 8 m away at y = 2, 30 deg vertical fov, 16:9: x -3.81 .. 3.81, y 4.14 .. -0.14. The lamp's middle after the+ // fall: x 0.40 .. 0.50, y 2.76 .. 2.84.+ metric: { kind: "radiance", region: [0.553, 0.303, 0.565, 0.322], expected: 5, tolerance: 0.03 },+ note: "as voxel/cut-body-live, with a lamp held to the level by a fixed joint in the upper post; its body made anew at frame 120",+};++let frames = 0;+let scene: Scene;+let lamp: Mesh;+let joint: FixedJoint;+export default defineGame<Record<string, never>>({+ state: {},+ setup: () => {+ frames = 0;+ scene = sceneWithSky(0);+ level(true);+ lamp = new Mesh(new BoxGeometry(0.2, 0.2, 0.2), glow());+ lamp.position.set(0.45, 3, 0);+ lamp.physics = "dynamic";+ joint = new FixedJoint(engineColliders, lamp, { anchorA: new Vector3(0.15, 3, 0), anchorB: new Vector3(-0.3, 0, 0) });+ return result(scene, camera(scene, [0, 2, 8], [0, 2, 0]), [lamp, joint]);+ },+ frame(f) {+ if (f.dt <= 0) return;+ frames++;+ if (frames === 3) cut();+ if (frames !== 120) return;+ if (!(joint.bodyA instanceof VoxelBody) || joint.broken || joint.bodyB !== lamp) {+ scene.remove(lamp);+ return;+ }+ lamp.physics = { type: "dynamic", density: 300 };+ },+ handlers: {},+});diff --git a/tools/bench-voxel-fire.ts b/tools/bench-voxel-fire.tsindex 7c6a2eb..743db5c 100644--- a/tools/bench-voxel-fire.ts+++ b/tools/bench-voxel-fire.ts@@ -14,6 +14,8 @@// goes): the frame's CPU and GPU ms for 2 s before and 4 s after the 4 m explosion (`crater`); with fire,// `sustained` (7 a second for 10 s) and `peak` (20 within a second): frame times, fireballs burning, lights.// `--software`: instead, the fire route's crater under software traversal (THREERT_HWRT=0, loop guard 8,192).+// `--scenario name`: instead, that scenario of the game on every route (`sustained`, `topple`: explosions that+// cut parts loose): each such explosion's parts kicked and the bodies' speeds just after it (step 10 c1).//// node tools/bench-voxel-fire.ts [--only calibrate,quality,cost] [--spp 2048] [--software]//@@ -280,14 +282,27 @@ if (only.includes("cost")) {const st = (xs: number[]) => { const s = frameStats(xs); return `${s.p50.toFixed(1)} / ${s.p95.toFixed(1)} / ${Math.max(...xs).toFixed(1)}`; };for (const [tag, game, env] of routes) {const b = (await bundleGame(join(repoRoot, "games/voxel-level", game), join(dir, game.replace(".ts", ".js")))).out;- for (const scenario of tag === "fire" && !args.includes("--crater") ? ["crater", "sustained", "peak"] : ["crater"]) {+ // (`--scenario name`: that scenario of the game instead, on every route.)+ for (const scenario of args.includes("--scenario") ? [opt("--scenario", "crater")] : tag === "fire" && !args.includes("--crater") ? ["crater", "sustained", "peak"] : ["crater"]) {const log = join(dir, `cost-${tag.replace(/\W+/g, "-")}-${scenario}.jsonl`);const s = live(`cost-${tag}-${scenario}`, b, { env, frameLog: log });await s.frames(240); // warm: the level loaded, the radiance cache traineds.event(scenario);- await s.frames(scenario === "sustained" ? 11 * 60 : scenario === "peak" ? 4 * 60 : 5 * 60);+ await s.frames(scenario === "sustained" ? 11 * 60 : scenario === "peak" ? 4 * 60 : scenario === "singles" ? 10 * 60 : scenario === "topple" ? 6 * 60 : 5 * 60);const explosions = s.lines.filter((l) => /^(\[game\] )?explosion \{/.test(l)).map((l) => JSON.parse(l.slice(l.indexOf("{"))) as { burning?: number; lit?: number });+ // The loose parts' top speed after the explosion (the game logs it every half second; step 10 c1's blast).+ const fastest = Math.max(0, ...s.lines.filter((l) => /^(\[game\] )?(bodies|explosion) \{/.test(l)).map((l) => (JSON.parse(l.slice(l.indexOf("{"))) as { fastest?: number }).fastest ?? 0));+ // The bodies' speeds just after the first explosion (the parts it cut loose, kicked: step 10 c1).+ const speeds = (explosions[0] as { speeds?: { n: number; p50: number; p90: number }; fastest?: number; kicked?: number } | undefined) ?? {};await s.quit();+ // (The renderer's and the game's lines beside the frame log.)+ writeFileSync(log.replace(/\.jsonl$/, ".log"), s.lines.join("\n") + "\n");+ // The explosions that cut parts loose: each one's radius, the parts it kicked and the bodies' speeds just after it.+ const cutting = (explosions as { r?: number; pieces?: number; kicked?: number; pushed?: number; fastest?: number; speeds?: { n: number; p50: number; p90: number } }[]).filter((e) => (e.pieces ?? 0) > 0 || (e.kicked ?? 0) > 0);+ console.log(` ${tag.padEnd(15)} ${scenario.padEnd(9)} ${explosions.length} explosions, ${cutting.length} cut parts loose`);+ for (const e of cutting) {+ if (e.speeds) console.log(` ${"".padEnd(25)} r ${e.r} m: ${e.pieces ?? 0} parts cut loose, ${e.kicked ?? 0} kicked, ${e.pushed ?? 0} pushed; bodies moving ${e.speeds.n}, speed p50 ${e.speeds.p50} / p90 ${e.speeds.p90} / max ${e.fastest} m/s`);+ }const F = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l) as Frame);const ex = F.findIndex((f, k) => k > 200 && (f.voxel?.[0] ?? 0) > 0);if (ex < 0) {@@ -300,12 +315,14 @@ if (only.includes("cost")) {before: { cpu: frameStats(before.map((f) => f.cpu)), gpu: frameStats(before.map((f) => f.gpu)) }, after: { cpu: frameStats(after.map((f) => f.cpu)), gpu: frameStats(after.map((f) => f.gpu)), gpu_max: r2(Math.max(...after.map((f) => f.gpu))) },burning_max: Math.max(0, ...explosions.map((e) => e.burning ?? 0)), lit_max: Math.max(0, ...explosions.map((e) => e.lit ?? 0)), explosions: explosions.length,guard: Math.max(0, ...F.map((f) => f.guard ?? 0)),+ fastest,+ speeds_after_explosion: { kicked: speeds.kicked ?? 0, ...(speeds.speeds ?? { n: 0, p50: 0, p90: 0 }), max: speeds.fastest ?? 0 },rebuilds_after: after.filter((f) => f.rebuild > 0).map((f) => `${r2(f.rebuild)} ms${f.fallback ? ` (${f.fallback})` : ""}`),// The GPU ms per frame over the 4 s after, in 0.25 s bins (the fire burns 1.6 s; the smoke after).gpu_bins: Array.from({ length: Math.ceil(after.length / 15) }, (_, k) => r2(frameStats(after.slice(k * 15, k * 15 + 15).map((f) => f.gpu)).p50)),};rows.push(row);- console.log(` ${tag.padEnd(15)} ${scenario.padEnd(9)} before: CPU ${st(before.map((f) => f.cpu))}, GPU ${st(before.map((f) => f.gpu))}; explosion frame CPU ${row.explosion_frame.cpu}, GPU ${row.explosion_frame.gpu}; after: CPU ${st(after.map((f) => f.cpu))}, GPU ${st(after.map((f) => f.gpu))}${tag.startsWith("fire") ? `; burning at most ${row.burning_max}, lit ${row.lit_max}` : ""}${row.guard ? `; guard ${row.guard}` : ""}; rebuilds after: ${row.rebuilds_after.length ? row.rebuilds_after.join(", ") : "none"}`);+ console.log(` ${tag.padEnd(15)} ${scenario.padEnd(9)} before: CPU ${st(before.map((f) => f.cpu))}, GPU ${st(before.map((f) => f.gpu))}; explosion frame CPU ${row.explosion_frame.cpu}, GPU ${row.explosion_frame.gpu}; after: CPU ${st(after.map((f) => f.cpu))}, GPU ${st(after.map((f) => f.gpu))}${tag.startsWith("fire") ? `; burning at most ${row.burning_max}, lit ${row.lit_max}` : ""}${row.guard ? `; guard ${row.guard}` : ""}; rebuilds after: ${row.rebuilds_after.length ? row.rebuilds_after.join(", ") : "none"}; loose parts' top speed ${row.fastest} m/s; just after the explosion: ${row.speeds_after_explosion.kicked} kicked, ${row.speeds_after_explosion.n} moving, p50 ${row.speeds_after_explosion.p50} / p90 ${row.speeds_after_explosion.p90} / max ${row.speeds_after_explosion.max} m/s`);console.log(` ${"".padEnd(25)} GPU p50 per 0.25 s after: ${row.gpu_bins.join(" ")}`);}}