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
Voxel bodies as objects (ROADMAP § 6 step 10 a): VoxelBody, per-body edits, mass by cell (#25)
Yujiaac9bc205536d
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 430905a..d4497d4 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -4193,17 +4193,17 @@ benchmark level. The order follows the dependencies; a step that meets a furtherWhat is left is the terrain's 1,600 tiles, a shape each. Decided against (2026-11-11): a shell of 2 cells(a body would get through it at 12 m/s), and building them after the first frame (a level whose firstseconds have no collision behaves by its load time).- - The script surface is `voxelBodies()`, `voxelImpulse` and the ids physics hits report; the rest is step 10's- (voxel bodies as objects with `.physics`, paint and added voxels on bodies, mass by cell).+ - The script surface was `voxelBodies()`, `voxelImpulse` and the ids physics hits report; voxel bodies as+ objects, paint and added voxels on bodies and mass by cell are step 10 (a), done.+ - **Export and import of the voxel world's and the physics world's state** (a level's edits, its bodies, their+ poses and velocities): waits for the general layer's design of saving (step 9 is that layer's).- A tick's time is still not bounded: the first tick after an edit that frees many parts steps them all (400jagged pieces in one heap: 7 ms a tick, at worst 19; 1,000: 23 ms, at worst 52).- **A large loose part's collider holds every cell** (the level's are shells): a solid block of 200³ cutloose is an edit of 2.8 s and 619 MB, and past 2²⁴ cells the part is refused and becomes debris (a largebuilding cut loose whole would vanish, not fall). Measured by the review; a shell for bodies (they are hitfrom every side, so 4 cells all round), or a split into pieces, is for when a level has such parts.- - Scene code can put colliders of its own on the engine's voxel bodies (a design question: step 10's voxel- bodies as objects); scene code's and the engine's bodies and colliders share one count of the physics- world's limits (a level with `maxBodies: 20000` leaves scripts none); every part cut off a body leaves an+ - Scene code's and the engine's bodies and colliders share one count of the physics world's limits (a level with `maxBodies: 20000` leaves scripts none); every part cut off a body leaves anempty slot in the level's object list for good.- Tree crowns cost more than buildings: five crowns of 10,616–18,894 voxels moving step in 1.6–2.2 ms (leavesmake many contacts), a building part of 32,680 in under 0.5 ms. They sleep 5–10 s after the cut.@@ -4222,7 +4222,9 @@ benchmark level. The order follows the dependencies; a step that meets a furtherthat moves, on one thread, so a hundred moving bodies are the frame; its parallel solver, now the nativedefault, is worth a factor of 3 on 4 threads at the same bits (about 450–500 moving bodies in a frame). What an engine of our own would have to beat is that step, and it would haveto bring the determinism, the sleeping and the voxel-voxel contacts with it.-9. **[ThreeRT] World data and command replay.** Binary world blocks on the node outside the JSON game state, changed by+9. **[ThreeRT] World data and command replay.** *Not in this line's order (the user, 2026-11-12): world data, command+ replay, multiplayer and saving belong to the general layer, to come later; the voxel line goes from step 8 to step+ 10. What is below stays as that layer's starting point.* Binary world blocks on the node outside the JSON game state, changed bydeterministic commands the room logs and replays to late joiners.- Acceptance: a room replayed from its log gives bit-identical world data.- **The log carries world-hash checkpoints** (required by the supervisor of this line, 2026-11-10): at a fixed@@ -4272,16 +4274,46 @@ benchmark level. The order follows the dependencies; a step that meets a further- A body that drives an object starts at `Scene::world_pose`, which is the renderer's own glam arithmetic (notunder `enhanced-determinism`): the log should carry the pose the body was made at, as it should carry a voxelcommand's fixed-point shape (step 6).-10. **[engine] The game API and effects.**+10. **[engine] The game API and effects.** Four PRs, each reviewed and merged on its own (the user, 2026-11-12: the+ four are independent, and step 8 in one PR of over 3,000 lines had four faults found in review): (a) voxel bodies+ as objects; (b) fire and smoke; (c) vehicles and ropes; (d) the acceptance scene.- `packages/voxel`: voxel edits, bodies, joints, lights, scene queries and effects.- - **Voxel bodies as objects** (left by step 8, decided 2026-11-11): a loose part is today a body id- (`voxelBodies()`, a physics hit's `body`, `voxelImpulse`), drawn by objects scene code did not make. How it- appears to a game in three's style (an object with `.physics`: `applyImpulse`, `getLinearVelocity`, contact- events, joints between voxel objects) is designed here. With it: paint and added voxels reaching bodies, and- a body's mass spread by its cells' own densities (it is their mean today).- - Fire and smoke on the existing volume and particle paths.- - Vehicles and ropes on step 7's joints.- - Acceptance: the benchmark level played through as a game, every line of `docs/VOXEL.md`'s benchmark measured.+ - **(a) Voxel bodies as objects** (branch `voxel-objects`; design `out/web-probe/step10/a-design.md`; docs/VOXEL.md+ "Voxel bodies as objects"). A loose part is a `VoxelBody` (an `Object3D`): `voxelBodies()`, `voxelBody(id)` and+ a physics hit give it, the same object for the same body. It has the physics methods every body has (at once:+ the body exists), its pose read from the engine, contacts on request (to `addEventListener`, as any body's),+ joints with voxel or scene objects, and edits of its own (`paint`, `addVoxels`, `carve`); cut, the part keeping+ the body keeps the object; retired, carved away or fallen, it is `gone` with a reason and a "gone" event. Scene+ code's colliders on a voxel body are refused. Paint reaches bodies; a body's mass is its cells', each at its+ own density. Step 8's `voxelBodies()` fields stay (`position` / `rotation` are now the object's vector and+ euler, the quaternion `quaternion`), `voxelImpulse` is kept and deprecated, `hit.object` on a body is its+ object. `packages/scene` gets an internal hook (`setEngineBodies`) for hits, joints and the frame's events, and+ delivers contacts with the voxel level (`other: engineColliders`). Checks: the adapter's recorded script with a+ paint and an add (native at 1 to 8 threads = wasm32 = recorded), `physics_fuzz` with body edits, contact+ switches, the gone list and the level's collider shells against brute force every 50 iterations.+ - Found on the way and fixed: an add on a body could scan an unbounded box (at most 65,536 voxels added, 64+ times that looked at), and both it and voxel-core's shape check counted cells in an i64 that wraps (a box of+ 1e30 m was 2^69 cells, counted as 0: a level `add` that large would never return).+ - The independent review of #25 found, fixed here with tests: an add far from a body made its mesh over the+ whole box (2.4 GB at 120 m; out of memory at 2e8 m): a body now stays within 2^21 cells spanning at most+ 1,024 a side and 2^25 in all, checked before anything changes; an add the physics refused left the mesh and+ the collider apart (the collider is edited first now); a body could grow past the physics' limit and keep+ being drawn without a collider (never now: it is debris); a getter in a descriptor that called the engine+ panicked it ("already mutably borrowed", on main too: ten entries read their arguments after borrowing; all+ read first now); a held object threw between the engine retiring its body and the next look (it finds it+ gone and does nothing); every redraw left a geometry behind for good (the level's own edits too, on main:+ +200 geometries in 400 edits; now +1); contacts started twice through an edit and never ended for a body+ that went; the engine's gone list grew with nobody taking it; a material outside the palette was taken; ids+ could meet in use ones after a wrap; `scene.add` of a voxel body threw only at the next sync (it refuses+ at once).+ - Open: a level `add` still accepts up to 2^27 cells (the fuzz keeps its adds tame for that, step 8's Open);+ a voxel body's pose is read from the engine at every read of `position` (one call; no per-frame cache);+ `World::drop_geometry` looks through every object for a user (a few hundred microseconds an edit on the+ benchmark level's 10,000 objects; a count per geometry would make it nothing).+ - (b) Fire and smoke on the existing volume and particle paths. Whether fire spreads along burning voxels is the+ user's to decide; not started.+ - (c) Vehicles and ropes on step 7's joints.+ - (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 36a6720..a8a129c 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -216,16 +216,17 @@ crate.position.set(0, 5, 0); // a write moves the body therethe engine's own shape (`physics_core::Shape::Voxels`: parry's voxel shape; a collider's cells are changed whereit is by `Physics::edit_voxels`, at a cost by the cells that change). Rays, shape casts and contacts report themlike any collider. They are **the engine's bodies**: their ids are from 2^30 up, scene code cannot make or remove- one (`body`, `collider` and `remove` refuse those ids), and can name one in every other call; `voxelBodies()`- (`packages/voxel`) lists the bodies with their ids, and `voxelImpulse(body, impulse, point?)` pushes one. A hit of- `Raycaster.intersectPhysics` or of a `Shapecaster` on one of them has `engineColliders` for its `object` (they- are no scene object's) and carries `collider` and, on a body, `body`: the id those calls take. **On the voxel- level `hit.object.physics` is null and there is no `body`; on a voxel body there is a `body`.** So hello world's- test for something fixed, `hit.object.physics?.type === "fixed"`, does not find the level: it is- `hit.object === engineColliders && hit.body === undefined`. A level that collides is in the physics world, and- the queries ask it, whether or not any scene object has `physics` (`tests/render/voxel-cut-body-push.ts`: a- ray's hit on a body, its `body` into `voxelImpulse`, the part thrown). (A voxel body as an object with `.physics`- is ROADMAP § 6 step 10's.) A voxel shape's limits: cells of 1 cm to 100 m, at most 2^24+ one (`body`, `collider` and `remove` refuse those ids, and a `collider` on one of those bodies is refused too: the+ engine edits and splits them by their cells), and can name one in every other call. **A voxel body is an object+ to scene code** (ROADMAP § 6 step 10 a; docs/VOXEL.md "Voxel bodies as objects"): `voxelBodies()` (`packages/voxel`)+ returns `VoxelBody` objects, the same object for the same body, with the physics methods every body has (sent at+ once), its pose, contacts on request and its own edits; joints take it as one of their objects; a hit of+ `Raycaster.intersectPhysics` or of a `Shapecaster` on it has it for its `object` and carries `collider` and `body`.+ **On the voxel level `hit.object` is `engineColliders` (in no scene, `physics` null) and there is no `body`.** So+ hello 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 or+ not 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. 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.- Two things the world does itself for voxel shapes, because Rapier 0.36 and parry 0.31 do them wrongly(`physics-core/src/world.rs` has the tests): rays are walked cell by cell (parry's ray misses every cell when itdiff --git a/docs/VOXEL.md b/docs/VOXEL.mdindex aacba0d..d8f8bde 100644--- a/docs/VOXEL.md+++ b/docs/VOXEL.md@@ -518,6 +518,55 @@ asleep at the same frames as under hardware traversal. Explosions of 1, 2, 4 m:194 ms (the parts' trees are built on the CPU: the commit is 117 ms of it); after it a frame's CPU p50 8.1, p959.1 ms, none over 16.7 ms; a frame's GPU 7.5–8.1 ms (trace 4.2–4.6).+### Voxel bodies as objects (ROADMAP § 6 step 10 a; design: `out/web-probe/step10/a-design.md`)++A loose part is, to scene code, an object: `voxelBodies()` returns `VoxelBody` objects (`@threert/voxel`, an+`Object3D`), the same object for the same body as long as it is; `voxelBody(id)` and a physics hit (`hit.object`) give+it too (the level itself stays `engineColliders`).++- **What it has**: the physics methods every body has, same names and units as a `Mesh` with `physics`+ (`applyImpulse`, `applyForce`, `setLinearVelocity`, `getLinearVelocity`, `sleeping`, ...), sent to the engine at+ once (the body exists: no sync to wait for); `position` / `quaternion` / `rotation` read from the engine (writes do+ not move it); `physics` read-only (`{ type: "dynamic", mass }`); `paint`, `addVoxels`, `carve` of that body alone.+- **Contacts**: a "contactstart" / "contactend" listener turns its collider's reports on; contacts arrive as for any+ body, on both objects with `other` (the level is `engineColliders`: a contact with a collider on no body was+ dropped before, for scene objects too), and in the scene's "contacts" batch. World handlers (`on`) are for the+ game's named events; a listener added in setup acts on the scene directly, as for ordinary bodies.+- **Joints**: `FixedJoint`, `HingeJoint`, ... between voxel objects, or a voxel object and a scene object with+ `physics`: the binding takes a voxel object's engine body (anchors in its own frame, unscaled). Removing a body+ removes its joints in the engine.+- **When it stops being one**: cut, the part that keeps the body keeps the object; retired for the cap, carved away+ or fallen out of the world, it is `gone` (`goneReason`: "cap", "carved", "fell") with a "gone" event at the frame's+ events, and its calls do nothing. A level edit looks at the bodies again at once; a call on a body the engine took+ out before the objects noticed finds it gone then and does nothing either (it does not throw).+- **Contacts, kept straight** (the bridge): a pair's start is reported once, even when an edit takes the collider out+ and puts it back; a collider that goes (a body carved away, retired, removed) ends its pairs.+- **Refused**: scene code's own colliders on a voxel body (the engine edits and splits it by its cells, and weighs it+ by them); join a body of your own with a `FixedJoint`.+- **Paint, added voxels, mass**: paint from the world reaches bodies (their surface cells, as the level's paint);+ `addVoxels` fills the body's empty cells in the shape, at most 65,536 at once and 64 times that looked at, and only+ if the body stays within 2^21 cells (`MAX_BODY_CELLS`) spanning at most 1,024 cells a side and 2^25 in all+ (`MAX_BODY_SIDE`, `MAX_BODY_BOX`: its mesh is made over that box, at most 47 MB a redraw; one add 120 m out took+ 2.4 GB before); the collider is edited first, and if anything is refused nothing changes. A part spanning more is+ debris, not a body; a body is never kept without its collider. A material outside the palette is refused. A body's+ mass, centre of mass and inertia are the sum of its cells, each a cube of its palette entry's density (the collider+ carries none). Step 8's `voxelImpulse` is kept, deprecated.++### Where the engine works round its dependencies++Each is a way round a fault or a gap of Rapier 0.36.1, parry 0.31.1, glamx 0.3.1 or rayon 1.12, in our code (no+crate is patched but glamx, in `renderer/third_party`). When a new release comes, this says what can go.++| What | Way round | Where | It can go when | How to tell |+| --- | --- | --- | --- | --- |+| The parallel step can hang: Rapier joins its deferred BVH pass with a blocking `recv` on a pool worker, and rayon does not promise another worker takes the job (ROADMAP § 6 step 8) | the wait for a step injects an empty job into the pool every 0.5 ms (`THREERT_PHYSICS_KICK=off` waits without) | `renderer/src/physics.rs` `in_pool` | Rapier joins that pass without blocking a worker (or runs it inline) | `cargo run --release --example physics_fuzz -- --runs 0 --stress 10000000` with `THREERT_PHYSICS_KICK=off`: no hang (today it hangs within 10⁵–10⁶ steps); then delete `in_pool`'s kick |+| A ball on voxels panics the solver ("stale ContactRef manifold ordinal"): parry's voxels-ball contact keeps no workspace, so Rapier takes the pair for a simple one | the pair goes through parry's general voxels-shape function (a query dispatcher) | `renderer/physics-core/src/world.rs` `VoxelsWithBalls` | parry's voxels-ball contact keeps a workspace (or Rapier stops deciding by it) | take the dispatcher out and run `check::cases` (its voxel kind), `voxel_worlds_never_panic` (20,000 worlds, ignored: `-- --ignored`) and `random_calls_on_voxel_shapes_never_panic`: none panics |+| parry's ray misses voxels when it lies on a lattice plane and runs along it | the world walks the cells itself (Amanatides–Woo) | `world.rs` `voxel_ray`, `shape_ray` | parry's ray cast on `Voxels` hits along lattice planes | `rays_at_voxel_shapes` with parry's ray in place of `voxel_ray` (it compares with brute force) |+| parry's `Voxels::voxels()` leaves cells out: it takes its range from the shape's box in metres, and f32 rounding can drop a layer (one cell at (-1000, 9, -673) of 0.1 m is listed as none; found by the fuzz, a body's count 29 short) | the world lists a shape's cells over its exact `domain()` (`voxels_in_range`) | `world.rs` `listed` | `Voxels::voxels()` takes its range as `domain()` does (from voxel centres) | `every_voxel_is_listed` with `voxels()` in place of `listed` |+| A voxel shape edited where it sits (`shape_mut`) leaves stale recycled contacts on pairs that do not move | `edit_voxels` takes the collider out and puts it back under the same id | `world.rs` `Physics::edit_voxels` | Rapier refreshes a collider's manifolds when its shape is edited in place | `voxel_shapes_are_edited` and the voxel fuzz with the edit done through `shape_mut` |+| glamx's eigen decomposition calls the platform's `acos` / `cos` when `std` is in the crate graph: other bits natively than in wasm32 | the three calls through `simba`'s libm, by name | `renderer/third_party/glamx` (`PATCH.md`), `[patch.crates-io]` in both manifests | a glamx release has the fix (dimforge/glamx #9, #10) and Rapier uses it | delete the copy and the patch tables; `tools/physics-determinism.ts` (its "std in the crate graph" run) and the recorded hashes hold |+| Rapier takes the sine and cosine of a hinge's limits' centre with the platform's methods (0.024 % of angles differ in the last bit between macOS and wasm32) | limits reach Rapier centred, [−h, h], and the centre turns the first body's joint frame | `world.rs` `Physics::add_joint` | Rapier computes them with libm under `enhanced-determinism` (dimforge/rapier #1054 lists such calls) | `revolute_limits_off_centre` and `tools/physics-determinism.ts` (cases with joints) with the limits passed as given |+## Two published designs for destructible voxel worlds- **Dense grids and a world occupancy volume** (the raster-era design):diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.tsindex 4adfa0a..25aaa65 100644--- a/packages/scene/src/core.ts+++ b/packages/scene/src/core.ts@@ -157,6 +157,28 @@ export function usePhysicsEngine(e: PhysicsEngine): void {physicsEngine = e;}+/**+ * @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.+ */+export interface EngineBodies {+ object(body: number): Object3D | undefined;+ bodyOf(o: Object3D): number | undefined;+ frame(): boolean;+}+let engineBodies: EngineBodies | null = null;++/** @internal Registers (or with null drops) the engine's bodies as objects. */+export function setEngineBodies(e: EngineBodies | null): void {+ engineBodies = e;+}++/** @internal The registered engine bodies, if any. */+export function getEngineBodies(): EngineBodies | null {+ return engineBodies;+}+/** @internal The engine may have stepped the world: poses are read again. */export function physicsStepped(): void {physicsEpoch++;@@ -498,6 +520,8 @@ export class Object3D {add(...objects: Object3D[]): this {for (const o of objects) {if (o === this) throw new Error("object can't be added as a child of itself");+ // (An object the engine draws itself, a voxel body: it is in no scene.)+ if ((o as { engineOwned?: boolean }).engineOwned) throw new TypeError(`${o.name || o.type}: the engine draws it; it is in no scene`);o.parent?.remove(o);o.parent = this;this.children.push(o);diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.tsindex 869d383..629cee3 100644--- a/packages/scene/src/engine.ts+++ b/packages/scene/src/engine.ts@@ -11,11 +11,12 @@ import {AmbientLight, compatNote, DirectionalLight, Fog, FogExp2, GLTFModel, HDRIEnvironment, HemisphereLight, InstancedMesh, Light, MeshBasicMaterial, MaterialFunction, Mesh, MeshPhysicalMaterial, type MeshStandardMaterial, Object3D,type ParticleBinding, type ParticleFunction, Particles, GpuParticles, type ParticleProgram, type ParticleProgramBinding, type VolumeBinding, type VolumeFunction, VolumeMesh, type DensityGrid, type GridProgram, type GridProgramBinding, ProceduralMesh, ProceduralGeometry,DataTexture, PerspectiveCamera, PointLight, RectAreaLight, Scene, SkyAtmosphere, SkyColor, SkyGradient, SpotLight, Texture, trackChanges, vec3, takePhysicsCommands,- bindBody, unbindBody, usePhysicsEngine, physicsStepped, physicsBodies, Joint,+ bindBody, unbindBody, usePhysicsEngine, physicsStepped, physicsBodies, Joint, getEngineBodies,type SceneChanges, type ShaderBinding, type SwayDesc, type PhysicsDesc, type BoundBody,} from "./core.ts";import { BoxGeometry, BufferGeometry, CapsuleGeometry, SphereGeometry } from "./geometry.ts";import { Matrix4, Quaternion, Vector3 } from "./math.ts";+import { ENGINE_IDS, engineColliders } from "./raycaster.ts";export type Vec2 = [number, number];export type Vec3 = [number, number, number];@@ -815,14 +816,22 @@ export class SceneBinding {// made anew included) makes it anew.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 = j.bodyA ? this.objects.get(j.bodyA) : undefined, b = j.bodyB ? this.objects.get(j.bodyB) : undefined;+ const a = bodyOf(j.bodyA), b = bodyOf(j.bodyB);let key = "";let desc: Record<string, unknown> | null = null;- if (a?.body && b?.body) {- const [sa, sb] = [a.body.scale, b.body.scale];+ if (a && b) {+ const [sa, sb] = [a.scale, b.scale];desc = {- ...j.jointDesc(), a: a.body.id, b: b.body.id,+ ...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);@@ -856,12 +865,18 @@ export class SceneBinding {*/deliverPhysicsEvents(): void {if (this.bodies) this.takeFaults();- if (!this.contactBodies) return;- const list = JSON.parse(this.engine.physics("contacts", {})) as { bodyA: number | null; bodyB: number | null; started: boolean }[] | null;+ // (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;+ const list = JSON.parse(this.engine.physics("contacts", {})) as { a?: number; b?: number; bodyA: number | null; bodyB: number | null; started: boolean }[] | null;if (!list?.length) return;const contacts: { a: Object3D; b: Object3D; started: boolean }[] = [];+ // (An engine body with no object yet, a part just cut loose, gets one from the hook; a collider on no body is the+ // voxel level's, when it is one of the engine's: `engineColliders`.)+ const of = (body: number | null, collider: number | undefined) =>+ body !== null ? (physicsBodies.get(body) ?? (body >= ENGINE_IDS ? getEngineBodies()?.object(body) : undefined)) : collider !== undefined && collider >= ENGINE_IDS ? engineColliders : undefined;for (const c of list) {- const a = c.bodyA === null ? undefined : physicsBodies.get(c.bodyA), b = c.bodyB === null ? undefined : physicsBodies.get(c.bodyB);+ const a = of(c.bodyA, c.a), b = of(c.bodyB, c.b);if (!a || !b) continue;contacts.push({ a, b, started: c.started });const type = c.started ? "contactstart" : "contactend";diff --git a/packages/scene/src/raycaster.ts b/packages/scene/src/raycaster.tsindex cfea6a3..2f936e8 100644--- a/packages/scene/src/raycaster.ts+++ b/packages/scene/src/raycaster.ts@@ -9,7 +9,7 @@// what a shape overlaps or meets when moved. Both see the world as the engine has it, with or without a tick since// the last change; what the running script changed in the scene reaches the engine when it returns (docs/RUNTIME.md,// World handlers).-import { InstancedMesh, Mesh, Object3D, type PerspectiveCamera, physicsBodies, physicsQuery, ProceduralGeometry, ProceduralMesh } from "./core.ts";+import { getEngineBodies, InstancedMesh, Mesh, Object3D, type PerspectiveCamera, physicsBodies, physicsQuery, ProceduralGeometry, ProceduralMesh } from "./core.ts";import { Box3, Matrix4, Quaternion, Ray, Vector2, Vector3 } from "./math.ts";import type { BufferGeometry } from "./geometry.ts";@@ -24,8 +24,8 @@ export interface Intersection {instanceId?: number;/** The surface's normal at the point, in the world (hits of the physics world). */normal?: Vector3;- /** A hit on one of the engine's own colliders (`object` is `engineColliders`): the physics world's id of the- * collider. */+ /** A hit on one of the engine's own colliders (`object` is a voxel body's object, or `engineColliders` for the+ * voxel level): the physics world's id of the collider. */collider?: number;/** On such a hit, the physics world's id of the body the collider is on: there on a voxel body (a part that came* loose), absent on the voxel level itself, which is fixed and on no body. */@@ -33,15 +33,17 @@ export interface Intersection {}/** The physics world's ids from here up are the engine's own bodies and colliders: a voxel level's objects (fixed- * colliders) and the parts that came loose from it (bodies). No scene object stands for them. */+ * colliders) and the parts that came loose from it (bodies). No scene object stands for them; a voxel body has an+ * object of its own (`@threert/voxel`'s `VoxelBody`), in no scene. */export const ENGINE_IDS = 2 ** 30;/**- * The `object` of a physics hit on one of the engine's own colliders (a voxel level: `@threert/voxel`). It is in no- * scene and has no `physics` (`hit.object.physics` is null): what was met is in the hit's `collider` and `body`.- * - The voxel level: `body` is absent. The level is fixed; `hit.object.physics?.type === "fixed"`, the test for a- * fixed scene object, does not say so here: test `hit.object === engineColliders && hit.body === undefined`.- * - A voxel body (a part that came loose): `body` is its id, the one `voxelBodies()` lists and `voxelImpulse` takes.+ * The `object` of a physics hit on the voxel level (`@threert/voxel`): its objects are fixed colliders of the+ * engine's, and no scene object stands for them. It is in no scene and has no `physics` (`hit.object.physics` is+ * null); the hit's `collider` names what was met and it has no `body`. Test it with `hit.object === engineColliders`+ * (`hit.object.physics?.type === "fixed"`, the test for a fixed scene object, does not say so here).+ * A hit on a voxel body (a part that came loose) has that body's object (`VoxelBody`, with the physics methods every+ * body has) and its `body` id; `engineColliders` is that object only where `@threert/voxel` has none registered.*/export const engineColliders = new Object3D();engineColliders.name = "engine colliders";@@ -61,11 +63,17 @@ interface PhysicsHit {function physicsIntersection(h: PhysicsHit): Intersection | null {const hit = { distance: h.distance, point: new Vector3(...h.point), face: null, faceIndex: null, normal: new Vector3(...h.normal) };- if (h.collider !== undefined && h.collider >= ENGINE_IDS) return { ...hit, object: engineColliders, collider: h.collider, ...(h.body === null ? {} : { body: h.body }) };+ // (A voxel body has an object of its own, `@threert/voxel`'s; the level is `engineColliders`.)+ if (h.collider !== undefined && h.collider >= ENGINE_IDS) return { ...hit, object: engineObject(h.body), collider: h.collider, ...(h.body === null ? {} : { body: h.body }) };const object = h.body === null ? undefined : physicsBodies.get(h.body);return object ? { ...hit, object } : null;}+/** The object a hit on an engine collider reports: its body's object when one is registered, else `engineColliders`. */+function engineObject(body: number | null): Object3D {+ return (body === null ? undefined : getEngineBodies()?.object(body)) ?? engineColliders;+}+function skipOf(o: PhysicsQueryOptions): { skip?: number } {const id = o.exclude?._body?.id;return id === undefined ? {} : { skip: id };@@ -226,8 +234,8 @@ export class Shapecaster {const hits = physicsQuery("overlap", { ...this.at(), ...skipOf(options) }) as { collider?: number; body: number | null }[] | null;const out = new Set<Object3D>();for (const h of hits ?? []) {- // (The engine's own colliders, a voxel level's: `engineColliders`, once.)- const o = h.collider !== undefined && h.collider >= ENGINE_IDS ? engineColliders : h.body === null ? undefined : physicsBodies.get(h.body);+ // (The engine's own colliders: a voxel body's object, the level's `engineColliders` once.)+ const o = h.collider !== undefined && h.collider >= ENGINE_IDS ? engineObject(h.body) : h.body === null ? undefined : physicsBodies.get(h.body);if (o) out.add(o);}return [...out];diff --git a/packages/voxel/src/native.ts b/packages/voxel/src/native.tsindex aeef4d1..e930369 100644--- a/packages/voxel/src/native.ts+++ b/packages/voxel/src/native.ts@@ -5,13 +5,14 @@// world metres, applied in fixed point, so the same commands give the same voxels on every machine (`voxelHash`).// After an edit, what no chain of voxels sharing a face joins to an anchor (the terrain, objects marked `anchor`) is// cut loose: a rigid body of the physics world (it tumbles, lands on the level and on other bodies, and sleeps; an-// explosion carves it like the level). The removed voxels are debris (`voxelDebris`).+// explosion carves it like the level), and to scene code an object, `VoxelBody` (`voxelBodies()`, a physics hit's+// `object`), with the physics methods every body has. The removed voxels are debris (`voxelDebris`).//// The level collides without being asked: every object is a fixed collider of its voxels, kept up to date by edits, so// `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 { usePhysicsEngine } from "@threert/scene";+import { bindBody, Object3D, type ObjectEvent, type PhysicsDesc, physicsQuery, setEngineBodies, unbindBody, usePhysicsEngine, Vector3 as Vector3Ctor, type Vector3 } from "@threert/scene";export type Hardness = "soft" | "medium" | "hard" | "indestructible";@@ -89,16 +90,6 @@ export interface VoxelEdit {bodies_ms?: number;}-/** A loose part as a rigid body. `body` and `collider` are the physics world's ids of it: ray and shape cast hits- * and contacts report them. */-export interface VoxelBody {- body: number;- collider: number;- voxels: number;- asleep: boolean;- position: [number, number, number];- rotation: [number, number, number, number];-}/** (The name before step 6.) */export type Explosion = VoxelEdit;@@ -114,6 +105,262 @@ export interface VoxelFrame {world_objects?: number;}+/** A voxel body as the engine lists it (`__engine.voxelBodies()`). */+interface BodyRecord {+ body: number;+ collider: number;+ voxels: number;+ asleep: boolean;+ position: [number, number, number];+ rotation: [number, number, number, number];+}++/** Why a voxel body is gone: retired for the cap, carved away whole, or taken out by the physics world (it fell). */+export type VoxelBodyGone = "cap" | "carved" | "fell";++/** Every voxel body's object, by its engine body id: the same object for as long as the body is. */+const registry = new Map<number, VoxelBody>();+/** Objects that listen for contacts (the binding then asks the engine for them each frame). */+let listening = 0;+/** Objects retired since the frame's events were last delivered, and why: their "gone" events, whoever noticed. */+let pendingGone: { o: VoxelBody; reason: VoxelBodyGone }[] = [];+/** Objects retired lately, by body id, with the frame they went in: the frame's contacts still name them (a pair's+ * end when its body goes), so they are found for those until the frame after (`frame`). */+const recentlyGone = new Map<number, { o: VoxelBody; frame: number }>();+let frameCount = 0;+const CONTACTS = new Set(["contactstart", "contactend"]);++/**+ * A loose voxel part, a rigid body of the engine's (ROADMAP § 6 step 10), as an object: `voxelBodies()`, `voxelBody(id)`+ * and a physics hit on it (`hit.object`) give it, the same object for the same body as long as the body is.+ *+ * - It has the physics methods every body has (`applyImpulse`, `applyForce`, `setLinearVelocity`, ...,+ * `getLinearVelocity`, `sleeping`), with the same names and units as a `Mesh` with `physics`; they reach the engine+ * at once (a voxel body exists already: no sync to wait for).+ * - `position` / `quaternion` / `rotation` read the body's pose (its grid's corner): the engine moves it, and a write is+ * overwritten at the next read. `physics` describes it and cannot be set.+ * - "contactstart" / "contactend" listeners turn on its contact reports; contacts arrive as for any body (`other`:+ * the other object; the voxel level is `engineColliders`). Joints take it as one of their objects.+ * - Cut: the part that keeps the body (the largest) keeps this object; the parts cut off are new ones. Retired for the+ * cap, carved away or fallen out of the world: `gone` (with `goneReason`), a "gone" event when the binding delivers+ * the frame's events, and every call does nothing from then on.+ * - `paint`, `addVoxels`, `carve`: edits of this body alone (shapes in world metres).+ * It is in no scene: its meshes are the engine's.+ */+export class VoxelBody extends Object3D {+ readonly isVoxelBody = true;+ /** @internal Drawn by the engine, in no scene: `scene.add` refuses it. */+ readonly engineOwned = true;+ override type = "VoxelBody";+ /** The physics world's ids of its body and its collider (physics calls and hits name them). */+ readonly body: number;+ collider: number;+ /** Its voxels, and whether it slept, as of the last time it was listed or its pose read. */+ voxels: number;+ asleep: boolean;+ /** It is no longer a body (see the class); `goneReason` says why. */+ gone = false;+ goneReason: VoxelBodyGone | undefined;+ private contactsOn = false;++ /** @internal Made by the registry (`voxelBodies`, `voxelBody`, a hit), never by scene code. */+ constructor(r: BodyRecord) {+ super();+ this.body = r.body;+ this.collider = r.collider;+ this.voxels = r.voxels;+ this.asleep = r.asleep;+ this.name = `voxel body ${r.body}`;+ // (Known to the physics bindings by its body id: contacts and hits find it; it has no slot in the pose table.)+ bindBody(this, { id: r.body, slot: -1, epoch: 0, trs: new Float64Array(10), euler: false });+ const p = this.position as Vector3 & { _x: number; _y: number; _z: number }, q = this.quaternion, e = this.rotation;+ const place = (at: readonly number[], rot: readonly number[]) => {+ [p._x, p._y, p._z] = at;+ [q._x, q._y, q._z, q._w] = rot;+ };+ place(r.position, r.rotation);+ const pull = () => {+ const s = this.ask(() => physicsQuery("state", { body: this.body }) as { position?: number[]; rotation?: number[]; sleeping?: boolean } | null, null);+ if (!s?.position || !s.rotation) return;+ place(s.position, s.rotation);+ this.asleep = s.sleeping ?? this.asleep;+ };+ this.update = (rec) => {+ this.collider = rec.collider;+ this.voxels = rec.voxels;+ this.asleep = rec.asleep;+ place(rec.position, rec.rotation);+ };+ Object.defineProperty(this, "position", { configurable: true, enumerable: true, get: () => (pull(), p) });+ Object.defineProperty(this, "quaternion", { configurable: true, enumerable: true, get: () => (pull(), q) });+ Object.defineProperty(this, "rotation", { configurable: true, enumerable: true, get: () => (pull(), e.setFromQuaternion(q, false), e) });+ }++ /** @internal The engine's record of it, taken in. */+ update: (r: BodyRecord) => void;++ /** What the body is: dynamic, its mass (kg). Read-only: the engine makes and unmakes these bodies. */+ override get physics(): Readonly<PhysicsDesc> | null {+ const s = this.ask(() => physicsQuery("state", { body: this.body }) as { mass?: number } | null, undefined);+ if (s === undefined) return null;+ return Object.freeze({ type: "dynamic" as const, ...(s?.mass !== undefined ? { mass: s.mass } : {}) });+ }+ override set physics(_v: PhysicsDesc | "dynamic" | "fixed" | "kinematic" | null) {+ throw new TypeError(`${this.name}: a voxel body's physics is the engine's (move it with impulses, forces and velocities)`);+ }++ override applyImpulse(impulse: Vector3, point?: Vector3): this {+ return this.call("impulse", { impulse: impulse.toArray(), ...(point ? { point: point.toArray() } : {}) });+ }+ override applyTorqueImpulse(torque: Vector3): this {+ return this.call("impulse", { torque: torque.toArray() });+ }+ override applyForce(force: Vector3): this {+ return this.call("force", { force: force.toArray() });+ }+ override applyTorque(torque: Vector3): this {+ return this.call("force", { torque: torque.toArray() });+ }+ override setLinearVelocity(v: Vector3): this {+ return this.call("velocity", { linvel: v.toArray() });+ }+ override setAngularVelocity(v: Vector3): this {+ return this.call("velocity", { angvel: v.toArray() });+ }+ // (The readers too: `Object3D`'s would throw on a body the engine took out before the objects noticed.)+ override getLinearVelocity(target?: Vector3): Vector3 {+ return this.ask(() => super.getLinearVelocity(target), undefined) ?? (target ?? new Vector3Ctor()).set(0, 0, 0);+ }+ override getAngularVelocity(target?: Vector3): Vector3 {+ return this.ask(() => super.getAngularVelocity(target), undefined) ?? (target ?? new Vector3Ctor()).set(0, 0, 0);+ }+ override get sleeping(): boolean {+ return this.ask(() => super.sleeping, false);+ }++ /** The exposed voxels of this body inside the shape take palette entry `material`. */+ paint(shape: VoxelShape, material: number): VoxelBodyEdit | null {+ return this.edit({ op: "paint", material, ...shape });+ }+ /** Voxels of palette entry `material` in every empty cell of this body inside the shape (they are part of it).+ * (`add` is `Object3D`'s: children.) */+ addVoxels(shape: VoxelShape, material: number): VoxelBodyEdit | null {+ return this.edit({ op: "add", material, ...shape });+ }+ /** This body alone cut by the shape, whatever the hardness but the indestructible (parts cut off are bodies of+ * their own). */+ carve(shape: VoxelShape): VoxelBodyEdit | null {+ return this.edit({ op: "carve", ...shape });+ }++ override addEventListener(type: string, listener: (e: ObjectEvent) => void): void {+ super.addEventListener(type, listener);+ if (CONTACTS.has(type) && !this.contactsOn && !this.gone) {+ if (this.ask(() => (engine()?.voxelContacts?.(this.body, true), true), false)) {+ this.contactsOn = true;+ listening++;+ }+ }+ }++ private call(op: string, args: object): this {+ this.ask(() => engine()?.physics?.(op, { body: this.body, ...args }), undefined);+ return this;+ }++ private edit(d: object): VoxelBodyEdit | null {+ const e = engine();+ if (!e?.voxelBodyEdit) throw new Error("voxel body edits need the renderer's native voxels");+ const r = this.ask(() => JSON.parse(e.voxelBodyEdit!(this.body, d)) as VoxelBodyEdit, null);+ if (r) refresh();+ return r;+ }++ /**+ * A call on the engine's body: `otherwise` once it is gone. The engine may have taken the body out since the+ * registry last looked (an edit of the level, the cap, a fall): a call that fails is then the registry's cue to look+ * again, and on a body found gone it does nothing, as the class promises. Any other error is thrown.+ */+ private ask<T, U>(f: () => T, otherwise: U): T | U {+ if (this.gone) return otherwise;+ try {+ return f();+ } catch (err) {+ refresh();+ if (this.gone) return otherwise;+ throw err;+ }+ }++ /** @internal It is no longer a body. */+ retire(reason: VoxelBodyGone): void {+ if (this.gone) return;+ this.gone = true;+ this.goneReason = reason;+ recentlyGone.set(this.body, { o: this, frame: frameCount });+ if (this.contactsOn) listening--;+ registry.delete(this.body);+ unbindBody(this);+ }+}++/** What an edit of one voxel body did. */+export interface VoxelBodyEdit {+ /** Voxels painted, added or removed; whether the body is gone (carved away whole). */+ voxels: number;+ gone: boolean;+}++/** The engine's list of bodies taken in: objects made for new ones, the gone ones retired (with the engine's reasons),+ * their "gone" events kept for the frame's events (`pendingGone`), whichever call noticed. */+function refresh(): void {+ const e = engine();+ const out = pendingGone;+ for (const [body, reason] of JSON.parse(e?.voxelGone?.() ?? "[]") as [number, VoxelBodyGone][]) {+ const o = registry.get(body);+ if (o) {+ o.retire(reason);+ out.push({ o, reason });+ }+ }+ if (!e?.voxelBodies) return;+ const seen = new Set<number>();+ for (const r of JSON.parse(e.voxelBodies()) as BodyRecord[]) {+ seen.add(r.body);+ const o = registry.get(r.body);+ if (o) o.update(r);+ else registry.set(r.body, new VoxelBody(r));+ }+ // (One the engine no longer lists without having said why: gone all the same.)+ for (const [body, o] of registry) {+ if (!seen.has(body)) {+ o.retire("carved");+ out.push({ o, reason: "carved" });+ }+ }+}++/** 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),+ frame: () => {+ // (Those that went before the last frame's events have had their contacts' ends delivered.)+ frameCount++;+ for (const [body, g] of recentlyGone) if (g.frame < frameCount - 1) recentlyGone.delete(body);+ // (With no object made yet, the engine's list of gone bodies is only let go of: nothing holds them.)+ if (registry.size) refresh();+ else engine()?.voxelGone?.();+ // (Every "gone" since the last frame's events, noticed here or by any call in between.)+ const gone = pendingGone;+ pendingGone = [];+ for (const { o, reason } of gone) o.dispatchEvent({ type: "gone", reason });+ return listening > 0;+ },+ });+}+interface NativeEngine {voxelLevel?: (d: NativeLevel) => void;voxelExplode?: (x: number, y: number, z: number, r: number) => string;@@ -122,6 +369,9 @@ interface NativeEngine {voxelDebris?: () => Float32Array;voxelHash?: () => string;voxelBodies?: () => string;+ voxelBodyEdit?: (body: number, d: object) => string;+ voxelContacts?: (body: number, on: boolean) => void;+ voxelGone?: () => string;physics?: (op: string, args: object) => string;physicsPoses?: () => Float32Array;}@@ -134,13 +384,19 @@ export function voxelLevel(level: NativeLevel): void {const e = engine();if (!e?.voxelLevel) throw new Error("voxelLevel: needs the renderer's native voxels");e.voxelLevel(level);- if (level.physics !== false && e.physics) usePhysicsEngine(e as Parameters<typeof usePhysicsEngine>[0]);+ if (level.physics !== false && e.physics) {+ usePhysicsEngine(e as Parameters<typeof usePhysicsEngine>[0]);+ register();+ }}function edit(d: object): VoxelEdit | { queued: true } {const e = engine();if (!e?.voxelEdit) throw new Error("voxel edits need the renderer's native voxels");- return JSON.parse(e.voxelEdit(d)) as VoxelEdit | { queued: true };+ const r = JSON.parse(e.voxelEdit(d)) as VoxelEdit | { queued: true };+ // (An edit of the level carves the bodies too: the objects of those it took out are gone from now on.)+ if (registry.size) refresh();+ return r;}/**@@ -191,18 +447,26 @@ export function voxelFrame(dt: number): VoxelFrame | { queued: true } {return JSON.parse(e.voxelFrame(dt)) as VoxelFrame | { queued: true };}-/** The voxel bodies there are now (loose parts the physics world moves), oldest first. */+/** The voxel bodies there are now (loose parts the physics world moves), oldest first, as objects (`VoxelBody`): the+ * same object for the same body each time. Bodies gone since the last call are retired here too (their "gone" event+ * comes with the frame's next events, as for every way a body is found gone). */export function voxelBodies(): VoxelBody[] {const e = engine();if (!e?.voxelBodies) throw new Error("voxelBodies: needs the renderer's native voxels");- return JSON.parse(e.voxelBodies()) as VoxelBody[];+ refresh();+ return [...registry.values()].sort((a, b) => a.body - b.body);+}++/** The object of voxel body `body` (an id a hit or a contact reported), or undefined if there is no such body now. */+export function voxelBody(body: number): VoxelBody | undefined {+ if (!registry.has(body)) refresh();+ return registry.get(body);}/**- * An impulse (N s) on a voxel body: at its centre of mass, or at a point of the world (which turns it too). `body` is- * the id `voxelBodies()` lists and a physics hit reports (`Raycaster.intersectPhysics`: `hit.body`; a hit on the- * level itself has `hit.object === engineColliders`, a null `hit.object.physics` and no `body`: the level is fixed).- * Throws if there is no such body (it may have been carved away, or retired for the cap, since the id was read).+ * An impulse (N s) on a voxel body by its id.+ * @deprecated Use the object: `voxelBody(id)?.applyImpulse(new Vector3(...), point)` (or `hit.object.applyImpulse`):+ * the same call. Kept for step 8's scripts; throws if there is no such body.*/export function voxelImpulse(body: number, impulse: readonly [number, number, number], point?: readonly [number, number, number]): void {const e = engine();diff --git a/packages/voxel/test/voxel.test.ts b/packages/voxel/test/voxel.test.tsindex b9053de..e1ef864 100644--- a/packages/voxel/test/voxel.test.ts+++ b/packages/voxel/test/voxel.test.ts@@ -78,54 +78,226 @@ test("bulk writes: brick() and fillBrick()", () => {assert.equal(g.layout().stats.voxels, 1);});-test("voxel bodies: the list is the engine's, an impulse goes to the physics world by the body's id", async () => {- const { voxelBodies, voxelImpulse } = await import("../src/native.ts");- const calls: [string, object][] = [];+/** An engine for the voxel bodies' tests: the binding's (a recording engine) and the voxel calls, answering the+ * physics' queries from a table and recording every call. */+async function voxelEngine() {+ const { RecordingEngine } = await import("@threert/scene");+ class VoxelEngine extends RecordingEngine {+ answers: Record<string, unknown> = {};+ bodies: object[] = [];+ gone: [number, string][] = [];+ voxelCalls: [string, ...unknown[]][] = [];+ override physics(op: string, args: object): string {+ super.physics(op, args);+ const a = this.answers[op];+ return JSON.stringify(typeof a === "function" ? a(args) : a ?? null);+ }+ voxelLevel(d: object) { this.voxelCalls.push(["voxelLevel", d]); }+ voxelBodies() { return JSON.stringify(this.bodies); }+ voxelGone() { const g = this.gone; this.gone = []; return JSON.stringify(g); }+ voxelContacts(body: number, on: boolean) { this.voxelCalls.push(["voxelContacts", body, on]); }+ voxelBodyEdit(body: number, d: object) { this.voxelCalls.push(["voxelBodyEdit", body, d]); return JSON.stringify({ voxels: 3, bodies: 1, gone: false }); }+ physicsCalls() { return this.calls.filter((c) => c[0] === "physics").map((c) => [c[1], c[2]] as [string, Record<string, unknown>]); }+ }+ return new VoxelEngine();+}++test("a voxel body is an object: the same one for the same body, with the physics methods every body has, its pose, its own edits", async () => {+ const { voxelLevel, voxelBodies, voxelBody, voxelImpulse, VoxelBody } = await import("../src/native.ts");+ const { Vector3 } = await import("@threert/scene");+ const engine = await voxelEngine();const g = globalThis as { __engine?: object };const before = g.__engine;- g.__engine = {- voxelBodies: () => JSON.stringify([{ body: 2 ** 30 + 7, collider: 2 ** 30 + 8, voxels: 416, asleep: true, position: [0, 0.8, 0], rotation: [0, 0, 0, 1] }]),- physics: (op: string, args: object) => { calls.push([op, args]); return "null"; },- };+ g.__engine = engine;+ const [id, col] = [2 ** 30 + 7, 2 ** 30 + 8];try {+ voxelLevel({ route: "mesh", palette: [], objects: [] });+ engine.bodies = [{ body: id, collider: col, voxels: 416, asleep: true, position: [0, 0.8, 0], rotation: [0, 0, 0, 1] }];const [b] = voxelBodies();- assert.deepEqual([b.body, b.voxels, b.asleep], [2 ** 30 + 7, 416, true]);- voxelImpulse(b.body, [0, 50, 0]);- voxelImpulse(b.body, [1, 0, 0], [0, 1, 0]);- assert.deepEqual(calls, [["impulse", { body: 2 ** 30 + 7, impulse: [0, 50, 0] }], ["impulse", { body: 2 ** 30 + 7, impulse: [1, 0, 0], point: [0, 1, 0] }]]);+ assert.ok(b instanceof VoxelBody);+ assert.equal(voxelBodies()[0], b, "the same object each time");+ assert.equal(voxelBody(id), b);+ assert.deepEqual([b.body, b.collider, b.voxels, b.asleep, b.gone], [id, col, 416, true, false]);+ // Its pose, read from the engine when read.+ engine.answers.state = { position: [1, 2, 3], rotation: [0, 0, 0, 1], linvel: [0, -1, 0], angvel: [0, 0, 0], sleeping: false, mass: 416 };+ assert.deepEqual(b.position.toArray(), [1, 2, 3]);+ assert.deepEqual(b.getLinearVelocity().toArray(), [0, -1, 0]);+ assert.deepEqual([b.sleeping, b.physics], [false, { type: "dynamic", mass: 416 }]);+ assert.throws(() => { b.physics = "fixed"; }, /the engine's/);+ // The methods every body has, at once (no sync to wait for).+ engine.calls.length = 0;+ b.applyImpulse(new Vector3(0, 50, 0)).applyImpulse(new Vector3(1, 0, 0), new Vector3(0, 1, 0)).setLinearVelocity(new Vector3(0, 3, 0)).applyForce(new Vector3(9, 0, 0));+ assert.deepEqual(engine.physicsCalls(), [+ ["impulse", { body: id, impulse: [0, 50, 0] }],+ ["impulse", { body: id, impulse: [1, 0, 0], point: [0, 1, 0] }],+ ["velocity", { body: id, linvel: [0, 3, 0] }],+ ["force", { body: id, force: [9, 0, 0] }],+ ]);+ // (Step 8's call by id, kept, deprecated.)+ voxelImpulse(id, [0, 1, 0]);+ assert.deepEqual(engine.physicsCalls().at(-1), ["impulse", { body: id, impulse: [0, 1, 0] }]);+ // Its own edits.+ assert.deepEqual(b.addVoxels({ box: [0, 0, 0, 1, 1, 1] }, 2), { voxels: 3, bodies: 1, gone: false });+ b.paint({ sphere: [0, 1, 0, 0.5] }, 3);+ b.carve({ box: [0, 0, 0, 0.2, 0.2, 0.2] });+ assert.deepEqual(engine.voxelCalls.filter((c) => c[0] === "voxelBodyEdit").map((c) => (c[2] as { op: string }).op), ["add", "paint", "carve"]);+ // Contact listeners turn its reports on, once.+ b.addEventListener("contactstart", () => {});+ b.addEventListener("contactend", () => {});+ assert.deepEqual(engine.voxelCalls.filter((c) => c[0] === "voxelContacts"), [["voxelContacts", id, true]]);} finally {g.__engine = before;}});-test("a voxel level that collides is what the scene's physics queries ask, with no scene object that has physics: a ray's hit on a voxel body goes into voxelImpulse", async () => {- const { voxelLevel, voxelImpulse } = await import("../src/native.ts");- const { engineColliders, Raycaster, Vector3 } = await import("@threert/scene");- const calls: [string, object][] = [];- const [level, part] = [2 ** 30 + 1, 2 ** 30 + 7];+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");+ const engine = await voxelEngine();const g = globalThis as { __engine?: object };const before = g.__engine;- g.__engine = {- voxelLevel: () => {},- physics: (op: string, args: { direction?: number[] }) => {- calls.push([op, args]);- if (op !== "ray") return "null";- // Down: the level (a fixed collider, on no body). Along z: a voxel body, then the level behind it.- const down = { collider: level, body: null, distance: 4.6, point: [1, 0.4, 1], normal: [0, 1, 0] };- return JSON.stringify(args.direction![1] < 0 ? [down] : [{ collider: part + 1, body: part, distance: 4.8, point: [0.05, 2.05, 0.2], normal: [0, 0, 1] }, { ...down, distance: 9 }]);- },- };+ g.__engine = engine;+ const [level, part] = [2 ** 30 + 1, 2 ** 30 + 7];try {voxelLevel({ route: "mesh", palette: [], objects: [] });+ engine.bodies = [{ body: part, collider: part + 1, voxels: 416, asleep: false, position: [0, 0.8, 0], rotation: [0, 0, 0, 1] }];+ // Down: the level (a fixed collider, on no body). Along z: the voxel body, then the level behind it.+ const down = { collider: level, body: null, distance: 4.6, point: [1, 0.4, 1], normal: [0, 1, 0] };+ engine.answers.ray = (a: { direction: number[] }) => (a.direction[1] < 0 ? [down] : [{ collider: part + 1, body: part, distance: 4.8, point: [0.05, 2.05, 0.2], normal: [0, 0, 1] }, { ...down, distance: 9 }]);const [ground] = new Raycaster(new Vector3(1, 5, 1), new Vector3(0, -1, 0)).intersectPhysics();- // The level: `engineColliders` for its object (no scene object: `physics` is null), a collider, no body.- assert.equal(ground.object, engineColliders);- assert.equal(ground.object.physics, null);- assert.deepEqual([ground.collider, ground.body, ground.distance], [level, undefined, 4.6]);+ // The level: `engineColliders` (no scene object: `physics` null), a collider, no body.+ assert.deepEqual([ground.object === engineColliders, ground.object.physics, ground.collider, ground.body], [true, null, level, undefined]);const hits = new Raycaster(new Vector3(0.05, 2.05, 5), new Vector3(0, 0, -1)).intersectPhysics();- assert.deepEqual(hits.map((h) => [h.object === engineColliders, h.collider, h.body]), [[true, part + 1, part], [true, level, undefined]]);- voxelImpulse(hits[0].body!, [1500, 300, 0]);- assert.deepEqual(calls.at(-1), ["impulse", { body: part, impulse: [1500, 300, 0] }]);+ const v = hits[0].object;+ assert.ok(v instanceof VoxelBody, "the body's object");+ assert.deepEqual([v === voxelBodies()[0], hits[0].body, hits[0].collider, hits[1].object === engineColliders], [true, part, part + 1, true]);+ engine.calls.length = 0;+ v.applyImpulse(new Vector3(1500, 300, 0));+ assert.deepEqual(engine.physicsCalls(), [["impulse", { body: part, impulse: [1500, 300, 0] }]]);+ // A joint between it and a scene object's body: the voxel body's engine id, its anchor unscaled.+ const scene = new Scene(), camera = new PerspectiveCamera();+ const binding = new SceneBinding(engine, scene, camera);+ const crate = new Mesh(new BoxGeometry(1, 1, 1));+ crate.physics = "dynamic";+ crate.scale.set(2, 2, 2);+ const j = new FixedJoint(v, crate);+ j.anchorA.set(0.1, 0.2, 0.3);+ scene.add(camera, crate, j);+ binding.sync();+ const joint = engine.physicsCalls().find((c) => c[0] === "joint")!;+ const crateBody = engine.physicsCalls().find((c) => c[0] === "body")![1].id;+ assert.deepEqual([joint[1].a, joint[1].b, joint[1].anchor1], [part, crateBody, [0.1, 0.2, 0.3]]);+ // Its contacts: the binding asks for them each frame now that it listens, and they arrive with `other`.+ const met: unknown[] = [];+ v.addEventListener("contactstart", (e) => met.push(e.other));+ engine.answers.contacts = [{ a: part + 1, b: level, bodyA: part, bodyB: null, started: true }, { a: 3, b: part + 1, bodyA: crateBody, bodyB: part, started: true }];+ binding.deliverPhysicsEvents();+ assert.deepEqual(met, [engineColliders, crate], "with the level (its colliders are on no body: `engineColliders`) and with a scene object");+ // A part just cut loose, never listed yet, in a contact with a scene object that listens: it gets its object.+ const crateMet: unknown[] = [];+ crate.physics = { type: "dynamic", contacts: true };+ binding.sync();+ const crate2 = engine.physicsCalls().filter((c) => c[0] === "body").at(-1)![1].id;+ crate.addEventListener("contactstart", (e) => crateMet.push(e.other));+ const fresh = part + 10;+ engine.bodies = [...engine.bodies, { body: fresh, collider: fresh + 1, voxels: 40, asleep: false, position: [0, 0, 0], rotation: [0, 0, 0, 1] }];+ engine.answers.contacts = [{ a: 3, b: fresh + 1, bodyA: crate2, bodyB: fresh, started: true }];+ binding.deliverPhysicsEvents();+ assert.ok(crateMet[0] instanceof VoxelBody && (crateMet[0] as { body: number }).body === fresh, "the new part's object");+ // Carved away by its own edit: the edit notices it is gone; its "gone" event still comes at the frame's events.+ const f = crateMet[0] as InstanceType<typeof VoxelBody>;+ let fGone: unknown = null;+ f.addEventListener("gone", (e) => (fGone = e.reason));+ engine.gone = [[fresh, "carved"]];+ engine.bodies = engine.bodies.filter((b) => (b as { body: number }).body !== fresh);+ f.carve({ box: [-1, -1, -1, 1, 1, 1] });+ assert.deepEqual([f.gone, fGone], [true, null], "gone at once, the event with the frame's");+ // Its contact with the crate ends at the frame's events (the bridge ends the pairs of a collider that goes): the+ // crate hears it, with the gone part as `other`.+ const crateEnded: unknown[] = [];+ crate.addEventListener("contactend", (e) => crateEnded.push(e.other));+ engine.answers.contacts = [{ a: 3, b: fresh + 1, bodyA: crate2, bodyB: fresh, started: false }];+ binding.deliverPhysicsEvents();+ assert.equal(fGone, "carved");+ assert.deepEqual(crateEnded, [f], "the crate's contact with the gone part ends");+ // Retired for the cap: gone, with the reason, at the frame's events; a call does nothing afterwards.+ engine.gone = [[part, "cap"]];+ engine.bodies = [];+ let gone: unknown = null;+ v.addEventListener("gone", (e) => (gone = e.reason));+ binding.deliverPhysicsEvents();+ assert.deepEqual([gone, v.gone, v.goneReason, voxelBodies().length], ["cap", true, "cap", 0]);+ engine.calls.length = 0;+ v.applyImpulse(new Vector3(1, 0, 0));+ assert.deepEqual([engine.physicsCalls(), v.getLinearVelocity().toArray(), v.physics], [[], [0, 0, 0], null]);+ } finally {+ g.__engine = before;+ }+});++test("a voxel body the engine took out before the objects noticed: every call does nothing, as on a gone one (the review of #25)", async () => {+ const { voxelLevel, voxelBodies, voxelBody, voxelExplode, VoxelBody } = await import("../src/native.ts");+ const { RecordingEngine, Scene, SceneBinding, PerspectiveCamera, Vector3 } = await import("@threert/scene");+ // As the real bridge and voxel world: a call on a body that is not there throws.+ class Bridge extends RecordingEngine {+ bodies: { body: number }[] = [];+ gone: [number, string][] = [];+ override physics(op: string, args: { body?: number }): string {+ super.physics(op, args);+ if (["state", "impulse", "force", "velocity"].includes(op) && (args.body ?? 0) >= 2 ** 30 && !this.bodies.some((b) => b.body === args.body)) throw new Error(`physics: unknown body ${args.body}`);+ if (op === "state") return JSON.stringify({ position: [1, 2, 3], rotation: [0, 0, 0, 1], linvel: [0, 1, 0], angvel: [0, 0, 0], sleeping: false, mass: 5 });+ return op === "contacts" || op === "faults" ? "[]" : "null";+ }+ voxelLevel() {}+ voxelBodies() { return JSON.stringify(this.bodies.map((b) => ({ ...b, collider: b.body + 1, voxels: 100, asleep: false, position: [0, 1, 0], rotation: [0, 0, 0, 1] }))); }+ voxelGone() { const x = this.gone; this.gone = []; return JSON.stringify(x); }+ voxelContacts(body: number) { if (!this.bodies.some((b) => b.body === body)) throw new Error(`voxelContacts: no voxel body ${body}`); }+ voxelBodyEdit(body: number) { if (!this.bodies.some((b) => b.body === body)) throw new Error(`voxelBodyEdit: no voxel body ${body}`); return JSON.stringify({ voxels: 1, bodies: 1, gone: false }); }+ voxelEdit() { return "{}"; }+ takeOut(body: number, why: string) { this.bodies = this.bodies.filter((b) => b.body !== body); this.gone.push([body, why]); }+ }+ const engine = new Bridge();+ const g = globalThis as { __engine?: object };+ const before = g.__engine;+ g.__engine = engine;+ const [a, b] = [2 ** 30 + 7, 2 ** 30 + 9];+ try {+ voxelLevel({ route: "mesh", palette: [], objects: [] });+ engine.bodies = [{ body: a }, { body: b }];+ const [va, vb] = voxelBodies();+ // Taken out by the engine on its own (the cap, a fall), nothing told the objects yet: no call throws, and the first+ // that finds it gone retires the object.+ engine.takeOut(a, "fell");+ const calls: [string, () => unknown][] = [+ ["applyImpulse", () => va.applyImpulse(new Vector3(0, 1, 0))], ["position", () => va.position.x], ["sleeping", () => va.sleeping],+ ["getLinearVelocity", () => va.getLinearVelocity().y], ["physics", () => va.physics], ["contacts", () => va.addEventListener("contactstart", () => {})],+ ["paint", () => va.paint({ sphere: [0, 0, 0, 1] }, 1)], ["carve", () => va.carve({ box: [0, 0, 0, 1, 1, 1] })], ["addVoxels", () => va.addVoxels({ box: [0, 0, 0, 1, 1, 1] }, 1)],+ ];+ for (const [name, f] of calls) assert.doesNotThrow(f, name);+ // Each reader first, on a body nobody has looked at since the engine took it out.+ for (const read of [(o: InstanceType<typeof VoxelBody>) => o.getLinearVelocity(), (o: InstanceType<typeof VoxelBody>) => o.getAngularVelocity(), (o: InstanceType<typeof VoxelBody>) => o.sleeping, (o: InstanceType<typeof VoxelBody>) => o.position]) {+ const id = 2 ** 30 + 50 + engine.bodies.length;+ engine.bodies.push({ body: id });+ const o = voxelBodies().find((x) => x.body === id)!;+ engine.takeOut(id, "cap");+ assert.doesNotThrow(() => read(o));+ assert.equal(o.gone, true);+ }+ assert.deepEqual([va.gone, va.goneReason, va.physics, va.getLinearVelocity().toArray(), va.position.toArray()], [true, "fell", null, [0, 0, 0], [0, 1, 0]]);+ // An edit of the level that carves one away: its object is gone as soon as the edit returns.+ engine.voxelEdit = () => (engine.takeOut(b, "carved"), "{}");+ voxelExplode(0, 0, 0, 5);+ assert.deepEqual([vb.gone, vb.goneReason, voxelBody(b)], [true, "carved", undefined]);+ // Their "gone" events with the frame's events.+ const got: string[] = [];+ va.addEventListener("gone", (e) => got.push(`a ${e.reason}`));+ vb.addEventListener("gone", (e) => got.push(`b ${e.reason}`));+ const scene = new Scene();+ const binding = new SceneBinding(engine, scene, new PerspectiveCamera());+ binding.deliverPhysicsEvents();+ assert.deepEqual(got.sort(), ["a fell", "b carved"]);+ // A voxel body is in no scene.+ assert.throws(() => scene.add(new VoxelBody({ body: 2 ** 30 + 99, collider: 0, voxels: 1, asleep: false, position: [0, 0, 0], rotation: [0, 0, 0, 1] })), /in no scene/);} finally {g.__engine = before;}diff --git a/renderer/examples/physics_fuzz.rs b/renderer/examples/physics_fuzz.rsindex 4fccac9..f0ae3d7 100644--- a/renderer/examples/physics_fuzz.rs+++ b/renderer/examples/physics_fuzz.rs@@ -30,7 +30,7 @@ use serde_json::json;use std::sync::atomic::{AtomicU64, Ordering};use threert_render::api;use threert_render::physics::PhysicsWorld;-use threert_render::voxel::{EditOp, VoxelWorld, MAX_BODIES};+use threert_render::voxel::{EditOp, VoxelWorld, MAX_BODIES, MAX_BODY_CELLS};use threert_render::world::World;struct Rng(u64);@@ -55,33 +55,37 @@ impl Rng {}}+/// How often (iterations) a run checks the level's colliders against their shells by brute force (`--shells`).+const SHELLS: u32 = 50;+/// Where the fuzz is (seed in the high half, iteration in the low), for the watchdog.static AT: AtomicU64 = AtomicU64::new(0);/// One run; returns the kicks its steps took.-fn run(seed: u64, iterations: u32, many: bool) -> u32 {+fn run(seed: u64, iterations: u32, many: bool, shells: u32) -> u32 {let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);let mut w = World::default();let mut ph: Option<PhysicsWorld> = None;- // Two terrain tiles side by side and bars standing on them (a few of them anchors).- let mut blocks = vec![([0, 0, 0], [64, 6, 64], Some((0, 0)), true), ([64, 0, 0], [64, 6, 64], Some((1, 0)), true)];+ // Two terrain tiles side by side, 1.6 m deep (deep enough to have cells under their shells), and bars standing on+ // them (a few of them anchors).+ let mut blocks = vec![([0, 0, 0], [64, 16, 64], Some((0, 0)), true), ([64, 0, 0], [64, 16, 64], Some((1, 0)), true)];if many {for i in 0..24 {for j in 0..20 {- blocks.push(([2 + i * 5, 6, 2 + j * 3], [2, 8 + r.below(12) as i32, 2], None, false));+ blocks.push(([2 + i * 5, 16, 2 + j * 3], [2, 8 + r.below(12) as i32, 2], None, false));}}} else {for i in 0..10 {for j in 0..5 {- blocks.push(([6 + i * 11, 6, 6 + j * 11], [2 + r.below(4) as i32, 6 + r.below(20) as i32, 2 + r.below(4) as i32], None, r.chance(0.1)));+ blocks.push(([6 + i * 11, 16, 6 + j * 11], [2 + r.below(4) as i32, 6 + r.below(20) as i32, 2 + r.below(4) as i32], None, r.chance(0.1)));}}}let mut v = VoxelWorld::of_blocks(&blocks, &mut w, &mut ph);if many {// Every bar cut loose at its foot, then again: more loose parts than the cap holds.- for y in [0.7, 1.1] {+ for y in [1.7, 2.1] {let _ = v.edit(&mut w, &mut ph, &EditOp::parse(&json!({ "op": "carve", "box": [0.0, y, 0.0, 12.8, y + 0.1, 6.4] })).unwrap());w.take_changes();}@@ -95,6 +99,7 @@ fn run(seed: u64, iterations: u32, many: bool) -> u32 {}};let (mut edits, mut refused, mut calls_refused, mut most, mut kicks) = (0u32, 0u32, 0u32, 0usize, 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);w.take_changes();@@ -103,14 +108,14 @@ fn run(seed: u64, iterations: u32, many: bool) -> u32 {for it in 0..iterations {AT.store(seed << 32 | it as u64, Ordering::Relaxed);let wild = it > iterations / 3;- match r.below(10) {+ match r.below(12) {0..=4 => {let op = ["carve", "carve", "explode", "add", "paint"][r.below(5) as usize];let wild = wild && op != "add";let rad = if wild && r.chance(0.2) { weird(&mut r) } else { r.range(0.1, 1.5) };let d = match if many && r.chance(0.5) { 3 } else { r.below(3) } {3 => {- let y = r.range(0.5, 2.5);+ let y = r.range(1.5, 3.5);json!({ "op": "carve", "box": [r.range(0.0, 6.0), y, 0.0, r.range(6.0, 12.8), y + 0.1, 6.4] })}0 => json!({ "op": op, "material": 1, "sphere": [pos(&mut r, wild), r.range(0.0, 3.0), pos(&mut r, wild) * 0.5, rad] }),@@ -126,6 +131,36 @@ fn run(seed: u64, iterations: u32, many: bool) -> u32 {Err(_) => refused += 1,}}+ // One body's own edit (a voxel object's addVoxels / paint / carve), around where it is.+ 10 => {+ let list = v.body_list(ph.as_ref().unwrap());+ if let Some(b) = list.as_array().unwrap().get(r.below(list.as_array().unwrap().len().max(1) as u64) as usize) {+ let (id, at) = (b["body"].as_u64().unwrap() as u32, [0, 1, 2].map(|k| b["position"][k].as_f64().unwrap()));+ // Near it mostly; now and then far (up to 10^8 m out: the review of #25 grew a body's mesh over+ // that), with a wild size, or grown again and again beside it.+ let off = if r.chance(0.1) { [1e2, 1e5, 1e8][r.below(3) as usize] * if r.chance(0.5) { 1.0 } else { -1.0 } } else { 0.0 };+ let c = [at[0] + r.range(-0.5, 1.0) + off, at[1] + r.range(-0.5, 1.5), at[2] + r.range(-0.5, 1.0) + off * r.range(0.0, 1.0)];+ let rad = if wild && r.chance(0.2) { weird(&mut r) } else { r.range(0.05, 0.8) };+ let op = ["add", "paint", "carve"][r.below(3) as usize];+ let material = if r.chance(0.05) { 255 } else { 1 };+ let d = if r.chance(0.5) { json!({ "op": op, "material": material, "sphere": [c[0], c[1], c[2], rad] }) } else { json!({ "op": op, "material": material, "box": [c[0], c[1], c[2], c[0] + rad, c[1] + rad, c[2] + rad] }) };+ let grow = if op == "add" && r.chance(0.02) { 4 } else { 1 };+ for g in 0..grow {+ let d = if grow > 1 { json!({ "op": "add", "material": 1, "box": [at[0] + 0.4 + 3.2 * g as f64, at[1], at[2], at[0] + 3.59 + 3.2 * g as f64, at[1] + 3.19, at[2] + 3.19] }) } else { d.clone() };+ match EditOp::parse(&d).and_then(|e| v.edit_body(&mut w, &mut ph, id, &e)) {+ Ok(_) => body_edits += 1,+ Err(_) => refused += 1,+ }+ }+ }+ }+ // A body's contacts on or off.+ 11 => {+ let list = v.body_list(ph.as_ref().unwrap());+ if let Some(b) = list.as_array().unwrap().first() {+ let _ = v.body_contacts(&mut ph, b["body"].as_u64().unwrap() as u32, r.chance(0.7));+ }+ }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);@@ -166,17 +201,28 @@ fn run(seed: u64, iterations: u32, many: bool) -> u32 {let list = v.body_list(p);let list = list.as_array().unwrap();most = most.max(list.len());+ // The bodies said to be gone are gone, with a reason.+ for g in v.take_gone().as_array().unwrap() {+ let id = g[0].as_u64().unwrap();+ assert!(["cap", "carved", "fell"].contains(&g[1].as_str().unwrap()), "seed {seed}, iteration {it}: {g}");+ assert!(!list.iter().any(|b| b["body"].as_u64() == Some(id)), "seed {seed}, iteration {it}: body {id} said gone and listed");+ }+ // The level's colliders against their shells by brute force, every `shells` iterations and at the end.+ if shells > 0 && (it % shells == shells - 1 || it + 1 == iterations) {+ 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");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);assert!(voxels > 0, "seed {seed}, iteration {it}: body {id} has no voxel");+ assert!(voxels <= MAX_BODY_CELLS.max(1 << 24), "seed {seed}, iteration {it}: body {id} has {voxels} voxels");assert_eq!(p.bridge_ref().engine_voxels(collider), Some(voxels), "seed {seed}, iteration {it}: body {id}'s collider cells are not its grid's");assert!(b["position"].as_array().unwrap().iter().all(|x| x.as_f64().is_some_and(f64::is_finite)), "seed {seed}, iteration {it}: body {id} at {}", b["position"]);}}println!(- "seed {seed}: {iterations} iterations, edits {edits} (refused {refused}), calls refused {calls_refused}, most bodies {most}, retired {}, kicks {kicks}, hash {:016x}/{:016x}",+ "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}",v.retired,v.hash().unwrap_or(0),ph.as_ref().unwrap().hash()@@ -212,6 +258,8 @@ fn main() {let args: Vec<String> = std::env::args().collect();let number = |name: &str, default: u64| args.iter().position(|a| a == name).and_then(|k| args.get(k + 1)).and_then(|v| v.parse().ok()).unwrap_or(default);let (runs, from, iterations, steps, limit) = (number("--runs", 20), number("--from", 1), number("--iterations", 1500) as u32, number("--stress", 2_000_000), number("--limit", 30));+ // (The level's colliders against brute force every this many iterations, and at a run's end; 0: never.)+ let shells = number("--shells", SHELLS as u64) as u32;let many = args.iter().any(|a| a == "--many");// The watchdog: the same place for `limit` seconds is a step (or an edit) that does not return.std::thread::spawn(move || {@@ -239,7 +287,7 @@ fn main() {assert_eq!((script, cases, voxels), (check::EXPECTED, check::EXPECTED_CASES, threert_render::voxel::EXPECTED_SCRIPT), "the recorded hashes");}let t = std::time::Instant::now();- let kicks: u32 = (from..from + runs).map(|seed| run(seed, iterations, many)).sum();+ let kicks: u32 = (from..from + runs).map(|seed| run(seed, iterations, many, shells)).sum();if runs > 0 {println!("physics fuzz: {runs} runs of {iterations} iterations in {:.1} s, every check held, no step hung; kicks {kicks}", t.elapsed().as_secs_f64());}diff --git a/renderer/physics-core/src/bridge.rs b/renderer/physics-core/src/bridge.rsindex a2092cd..0948a99 100644--- a/renderer/physics-core/src/bridge.rs+++ b/renderer/physics-core/src/bridge.rs@@ -52,6 +52,12 @@ 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 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).+ touching: BTreeMap<(u32, u32), (Option<u32>, Option<u32>)>,+ /// Ends of pairs whose collider went, for the next `contacts`.+ ended: Vec<Value>,joints: BTreeMap<u32, JointId>,/// Body (the world's id) -> the scene object it drives and its slot in `poses`.drives: BTreeMap<BodyId, (u32, Option<u32>)>,@@ -136,6 +142,8 @@ impl Default for Bridge {body_ids: BTreeMap::new(),colliders: BTreeMap::new(),collider_ids: BTreeMap::new(),+ touching: BTreeMap::new(),+ ended: vec![],joints: BTreeMap::new(),drives: BTreeMap::new(),driven: Default::default(),@@ -294,6 +302,11 @@ impl Bridge {return Err(format!("physics: collider {cid} exists"));}let owner = opt_id(a, "body")?;+ // (The engine's voxel bodies are edited cell by cell, cut in parts and weighed by their cells: a+ // collider of scene code's on one would ride along in no cell. Join a body of its own instead.)+ if owner.is_some_and(|b| b >= ENGINE_IDS) {+ return Err("physics: a collider cannot be put on one of the engine's bodies (join a body of your own to it with a joint)".into());+ }let body = match owner {Some(b) => Some(*self.bodies.get(&b).ok_or_else(|| format!("physics: unknown body {b}"))?),None => None,@@ -357,7 +370,7 @@ impl Bridge {}if let Some(c) = collider.and_then(|c| self.colliders.remove(&c)) {self.core.remove_collider(c);- self.collider_ids.remove(&c);+ self.unmap(c);}if let Some(j) = joint.and_then(|j| self.joints.remove(&j)) {self.core.remove_joint(j);@@ -454,16 +467,19 @@ impl Bridge {}// The contacts begun and ended since the last call (colliders with `events`), in the order they happened:// [{a, b, bodyA, bodyB, started}].- "contacts" => Value::Array(- self.core- .take_contacts()- .into_iter()- .filter_map(|c| {- let (&(a, ba), &(b, bb)) = (self.collider_ids.get(&c.a)?, self.collider_ids.get(&c.b)?);- Some(if a <= b { json!({ "a": a, "b": b, "bodyA": ba, "bodyB": bb, "started": c.started }) } else { json!({ "a": b, "b": a, "bodyA": bb, "bodyB": ba, "started": c.started }) })- })- .collect(),- ),+ "contacts" => {+ let mut out = std::mem::take(&mut self.ended);+ for c in self.core.take_contacts() {+ let (Some(&(a, ba)), Some(&(b, bb))) = (self.collider_ids.get(&c.a), self.collider_ids.get(&c.b)) else { continue };+ let (a, b, ba, bb) = if a <= b { (a, b, ba, bb) } else { (b, a, bb, ba) };+ // (A start of a pair touching already, or an end of one that is not: not reported again.)+ let new = if c.started { self.touching.insert((a, b), (ba, bb)).is_none() } else { self.touching.remove(&(a, b)).is_some() };+ if new {+ out.push(json!({ "a": a, "b": b, "bodyA": ba, "bodyB": bb, "started": c.started }));+ }+ }+ Value::Array(out)+ }// The world's hash and ticks (16 hex digits): the same calls at the same ticks give the same one."hash" => json!({ "hash": format!("{:016x}", self.core.hash()), "ticks": self.core.ticks(), "bodies": self.core.bodies(), "contactsDropped": self.core.contacts_dropped() }),// The bodies the world took out after a tick since the last call (`Physics::step`), with the object each@@ -516,7 +532,7 @@ impl Bridge {let left = self.core.edit_voxels(c, clear, fill);if !self.core.has_collider(c) {self.colliders.remove(&id);- self.collider_ids.remove(&c);+ self.unmap(c);}left}@@ -528,7 +544,7 @@ impl Bridge {}if let Some(c) = collider.filter(|&c| c >= ENGINE_IDS).and_then(|c| self.colliders.remove(&c)) {self.core.remove_collider(c);- self.collider_ids.remove(&c);+ self.unmap(c);}}@@ -550,6 +566,23 @@ impl Bridge {self.core.velocity(*self.bodies.get(&id)?)}+ /// An engine body's mass properties as the world has them (`Physics::mass_properties`).+ pub fn engine_mass_properties(&self, id: u32) -> Option<(f32, [f32; 3], [f32; 3])> {+ self.core.mass_properties(*self.bodies.get(&id).filter(|_| id >= ENGINE_IDS)?)+ }++ /// An engine body's mass properties (`Physics::set_mass_properties`).+ pub fn engine_mass(&mut self, id: u32, mass: f32, com: [f32; 3], inertia: [f32; 6]) -> Result<(), String> {+ let b = *self.bodies.get(&id).filter(|_| id >= ENGINE_IDS).ok_or_else(|| format!("physics: unknown engine body {id}"))?;+ self.core.set_mass_properties(b, mass, com, inertia)+ }++ /// An engine collider's contacts reported or not (`Physics::set_events`).+ pub fn engine_events(&mut self, id: u32, on: bool) -> Result<(), String> {+ let c = *self.colliders.get(&id).filter(|_| id >= ENGINE_IDS).ok_or_else(|| format!("physics: unknown engine collider {id}"))?;+ self.core.set_events(c, on)+ }+/// The memory of the world's voxel shapes, bytes (`Physics::voxel_bytes`).pub fn voxel_bytes(&self) -> usize {self.core.voxel_bytes()@@ -560,6 +593,11 @@ impl Bridge {self.core.voxels(*self.colliders.get(&id)?)}+ /// An engine voxel collider's cells, sorted (`Physics::voxel_cells`).+ pub fn engine_voxel_cells(&self, id: u32) -> Option<Vec<[i32; 3]>> {+ self.core.voxel_cells(*self.colliders.get(&id)?)+ }+/// The world's body of the caller's id in `a[key]`.fn body(&self, a: &Value, key: &str) -> Result<BodyId, String> {let b = id(a, key)?;@@ -577,6 +615,21 @@ impl Bridge {}/// Removes a body (the world's id) with its colliders and joints, and their ids.+ /// A collider's ids forgotten (it is gone from the world), and the pairs it touched ended for scene code.+ fn unmap(&mut self, c: ColliderId) -> Option<(u32, Option<u32>)> {+ let ids = self.collider_ids.remove(&c)?;+ let gone: Vec<(u32, u32)> = self.touching.keys().copied().filter(|&(a, b)| a == ids.0 || b == ids.0).collect();+ for k in gone {+ let (ba, bb) = self.touching.remove(&k).unwrap();+ // (Held as the world's own contacts are, up to `MAX_CONTACTS`: nobody may take them.)+ if self.ended.len() >= crate::world::limits::MAX_CONTACTS {+ self.ended.remove(0);+ }+ self.ended.push(json!({ "a": k.0, "b": k.1, "bodyA": ba, "bodyB": bb, "started": false }));+ }+ Some(ids)+ }+fn forget_body(&mut self, b: BodyId) {let gone = self.core.remove_body(b);self.forget_ids(b, &gone);@@ -586,7 +639,7 @@ impl Bridge {/// its joints.fn forget_ids(&mut self, b: BodyId, colliders: &[ColliderId]) {for c in colliders {- if let Some((id, _)) = self.collider_ids.remove(c) {+ if let Some((id, _)) = self.unmap(*c) {self.colliders.remove(&id);}}@@ -706,7 +759,7 @@ impl Bridge {fn forget_colliders(&mut self, colliders: &[ColliderId]) {for c in colliders {- if let Some((id, _)) = self.collider_ids.remove(c) {+ if let Some((id, _)) = self.unmap(*c) {self.colliders.remove(&id);}}diff --git a/renderer/physics-core/src/robustness.rs b/renderer/physics-core/src/robustness.rsindex fc8d392..74497de 100644--- a/renderer/physics-core/src/robustness.rs+++ b/renderer/physics-core/src/robustness.rs@@ -284,7 +284,9 @@ fn memory_is_bounded() {run(&mut b, &mut s, 1);}let dropped = ok(&mut b, &mut s, "hash", json!({}))["contactsDropped"].as_u64().unwrap();- assert_eq!(ok(&mut b, &mut s, "contacts", Value::Null).as_array().unwrap().len(), MAX_CONTACTS);+ // (At most that many; fewer, since an end whose start was dropped is not reported.)+ let n = ok(&mut b, &mut s, "contacts", Value::Null).as_array().unwrap().len();+ assert!(n > 0 && n <= MAX_CONTACTS, "{n}");assert!(dropped > 100_000, "{dropped} dropped");// `moved`, 1,000 awake bodies through 3,600 ticks without a sync.let (mut b, mut s) = world();diff --git a/renderer/physics-core/src/world.rs b/renderer/physics-core/src/world.rsindex a2c8368..c095c9e 100644--- a/renderer/physics-core/src/world.rs+++ b/renderer/physics-core/src/world.rs@@ -423,6 +423,14 @@ mod dispatch {/// every cell** (straight down at x = 1.5 onto cells of 0.1 m, which is where a game asks for the ground). Here a/// point belongs to the cell its coordinates floor to, the cell is stepped as an integer, and a cell that is solid/// is a hit.+/// Every cell of a voxel shape. Not parry's `Voxels::voxels()`: it takes its range from the shape's box in metres, and+/// f32's rounding can leave the lowest layer out (found by the fuzz: a body spanning -100.8 m .. 0.1 m listed 29 cells+/// fewer than it holds, all of its lowest z row, at -67.3 m). `domain()` rounds from a voxel's centre, exactly.+fn listed(v: &rapier3d::parry::shape::Voxels) -> impl Iterator<Item = rapier3d::parry::shape::VoxelData> + '_ {+ let d = v.domain();+ v.voxels_in_range(d[0], d[1])+}+fn voxel_ray(v: &rapier3d::parry::shape::Voxels, at: &Pose, ray: &Ray, max: f32) -> Option<(f32, Vector)> {let size = v.voxel_size().x;let (o, d) = (at.inverse_transform_point(ray.origin).to_array(), at.inverse_transform_vector(ray.dir).to_array());@@ -842,7 +850,7 @@ impl Physics {voxels.set_voxel(k, true);}}- let left = voxels.voxels().filter(|v| !v.state.is_empty()).count();+ let left = listed(voxels).filter(|v| !v.state.is_empty()).count();for b in touching.into_iter().chain(parent) {if let Some(b) = self.world.bodies.get_mut(b) {b.wake_up(true);@@ -885,7 +893,15 @@ impl Physics {/// A voxel collider's solid cells, counted; None if it is none.pub fn voxels(&self, id: ColliderId) -> Option<usize> {let &(h, _) = self.colliders.get(&id)?;- self.world.colliders.get(h)?.shape().as_voxels().map(|v| v.voxels().filter(|v| !v.state.is_empty()).count())+ self.world.colliders.get(h)?.shape().as_voxels().map(|v| listed(v).filter(|v| !v.state.is_empty()).count())+ }++ /// A voxel collider's cells, sorted (the checks').+ pub fn voxel_cells(&self, id: ColliderId) -> Option<Vec<[i32; 3]>> {+ let &(h, _) = self.colliders.get(&id)?;+ let mut out: Vec<[i32; 3]> = listed(self.world.colliders.get(h)?.shape().as_voxels()?).filter(|v| !v.state.is_empty()).map(|v| [v.grid_coords.x, v.grid_coords.y, v.grid_coords.z]).collect();+ out.sort_unstable();+ Some(out)}pub fn has_joint(&self, id: JointId) -> bool {@@ -986,6 +1002,38 @@ impl Physics {Some(self.body(id)?.mass())}+ /// A body's mass properties given, on top of its colliders' (give its colliders no density and these are all of+ /// it): `mass` kg, the centre of mass `com` and the inertia tensor about it (xx, yy, zz, xy, xz, yz, kg m²), in the+ /// body's frame. For a body whose mass is not its shapes' at one density: a voxel body, cell by cell. Wakes it.+ pub fn set_mass_properties(&mut self, id: BodyId, mass: f32, com: [f32; 3], inertia: [f32; 6]) -> Result<(), String> {+ if !(mass.is_finite() && mass > 0.0 && mass <= 1e12) || !com.iter().chain(&inertia).all(|v| v.is_finite()) {+ return Err("physics: mass properties must be finite, the mass above 0".into());+ }+ let h = *self.bodies.get(&id).ok_or("physics: unknown body")?;+ let [xx, yy, zz, xy, xz, yz] = inertia;+ let m = rapier3d::math::Matrix::from_cols(Vector::new(xx, xy, xz), Vector::new(xy, yy, yz), Vector::new(xz, yz, zz));+ let props = MassProperties::with_inertia_matrix(Vector::new(com[0], com[1], com[2]), mass, m);+ let world = &mut self.world;+ let b = &mut world.bodies[h];+ b.set_additional_mass_properties(props, true);+ b.recompute_mass_properties_from_colliders(&world.colliders);+ Ok(())+ }++ /// A body's mass properties as the world has them: mass, centre of mass (body frame), principal inertia (the checks').+ pub fn mass_properties(&self, id: BodyId) -> Option<(f32, [f32; 3], [f32; 3])> {+ let m = self.body(id)?.mass_properties().local_mprops;+ let (c, i) = (m.local_com, m.principal_inertia());+ Some((m.mass(), [c.x, c.y, c.z], [i.x, i.y, i.z]))+ }++ /// A collider's contacts reported (`take_contacts`) or not, from now on.+ pub fn set_events(&mut self, id: ColliderId, on: bool) -> Result<(), String> {+ let &(h, _) = self.colliders.get(&id).ok_or("physics: unknown collider")?;+ self.world.colliders[h].set_active_events(if on { ActiveEvents::COLLISION_EVENTS } else { ActiveEvents::empty() });+ Ok(())+ }+/// Bodies that moved in the last step (awake dynamic bodies and kinematic ones), with their poses, in id order.pub fn moved(&self) -> Vec<(BodyId, [f32; 3], [f32; 4])> {self.bodies@@ -1807,6 +1855,37 @@ mod tests {}/// What a voxel shape refuses.+ /// A body's mass given from outside (its collider of no density): the mass is it, the centre of mass where it was+ /// put (a push there does not turn the body), and edits of the collider keep it; bad numbers are refused.+ #[test]+ fn mass_properties_set_from_outside() {+ let mut p = Physics::new([0.0, 0.0, 0.0]);+ let b = p.add_body(&BodyDesc::default()).unwrap();+ let c = p.add_collider(Some(b), &ColliderDesc { density: 0.0, ..ColliderDesc::new(Shape::Voxels { size: 0.1, cells: block([0, 0, 0], [4, 4, 4]) }) }).unwrap();+ // All the mass in the +x half: the centre of mass at x = 0.3, inertia of a 2 x 4 x 4 block of 0.1 m cells.+ let (m, com) = (8.0f32, [0.3, 0.2, 0.2]);+ p.set_mass_properties(b, m, com, [0.01, 0.02, 0.02, 0.0, 0.0, 0.0]).unwrap();+ assert!((p.mass(b).unwrap() - m).abs() < 1e-5);+ p.apply_impulse_at(b, [0.0, 0.0, 1.0], [0.3, 0.2, 0.2], [0.0; 3]).unwrap();+ let (v, w) = p.velocity(b).unwrap();+ assert!((v[2] - 1.0 / m).abs() < 1e-5 && w.iter().all(|x| x.abs() < 1e-5), "at the centre of mass: no turn ({v:?}, {w:?})");+ p.edit_voxels(c, &[[0, 0, 0]], &[]).unwrap();+ assert!((p.mass(b).unwrap() - m).abs() < 1e-5, "an edit keeps it");+ assert!(p.set_mass_properties(b, 0.0, com, [0.01; 6]).is_err() && p.set_mass_properties(b, 1.0, [f32::NAN; 3], [0.01; 6]).is_err());+ }++ /// Every cell of a voxel shape is counted and listed: one cell at (-1000, 9, -673) of 0.1 m, which parry's own+ /// `Voxels::voxels()` leaves out (its range is from the shape's box in metres, rounded), and the same after an edit.+ #[test]+ fn every_voxel_is_listed() {+ let mut p = Physics::new([0.0, 0.0, 0.0]);+ let b = p.add_body(&BodyDesc::default()).unwrap();+ let c = p.add_collider(Some(b), &ColliderDesc { density: 0.0, ..ColliderDesc::new(Shape::Voxels { size: 0.1, cells: vec![[-1000, 9, -673]] }) }).unwrap();+ assert_eq!((p.voxels(c), p.voxel_cells(c)), (Some(1), Some(vec![[-1000, 9, -673]])));+ assert_eq!(p.edit_voxels(c, &[], &[[0, 0, 0]]), Ok(2));+ assert_eq!(p.voxel_cells(c), Some(vec![[-1000, 9, -673], [0, 0, 0]]));+ }+#[test]fn voxel_shapes_are_checked() {let mut p = Physics::default();diff --git a/renderer/src/api.rs b/renderer/src/api.rsindex 38c6afb..7952903 100644--- a/renderer/src/api.rs+++ b/renderer/src/api.rs@@ -69,6 +69,30 @@ pub fn voxel_edit(v: &mut VoxelWorld, w: &mut World, p: &mut Option<PhysicsWorldOk(v.edit(w, p, &op)?.to_string())}+/// An edit of one voxel body alone (`voxelBodyEdit(body, { op, sphere | box | capsule, material })`: a voxel object's+/// `add`, `paint`, `carve`): what it did, as JSON.+pub fn voxel_body_edit(v: &mut VoxelWorld, w: &mut World, p: &mut Option<PhysicsWorld>, body: f64, d: &Value) -> Result<String> {+ let op = crate::voxel::EditOp::parse(d)?;+ let body = whole(body).ok_or_else(|| Error::Type("voxelBodyEdit: body must be a body id".into()))?;+ Ok(v.edit_body(w, p, body, &op)?.to_string())+}++/// A voxel body's contacts reported or not (`voxelContacts(body, on)`).+pub fn voxel_contacts(v: &mut VoxelWorld, p: &mut Option<PhysicsWorld>, body: f64, on: bool) -> Result<()> {+ let body = whole(body).ok_or_else(|| Error::Type("voxelContacts: body must be a body id".into()))?;+ Ok(v.body_contacts(p, body, on)?)+}++/// The voxel bodies gone since the last call (`voxelGone()`): [[body, "cap" | "carved" | "fell"], ...].+pub fn voxel_gone(v: &mut VoxelWorld) -> String {+ v.take_gone().to_string()+}++/// A body id as scene code hands it: a whole number below 2^32.+fn whole(x: f64) -> Option<u32> {+ (x.is_finite() && x >= 0.0 && x <= u32::MAX as f64 && x.fract() == 0.0).then_some(x as u32)+}+/// The voxel bodies (loose parts the physics world moves): each one's body id for `physics` calls, its voxels,/// whether it sleeps, where it is. "[]" without any.pub fn voxel_bodies(v: &VoxelWorld, p: &Option<PhysicsWorld>) -> String {diff --git a/renderer/src/script.rs b/renderer/src/script.rsindex 7741981..f28312c 100644--- a/renderer/src/script.rs+++ b/renderer/src/script.rs@@ -225,17 +225,25 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<R// The voxel engine's level and explosions (renderer/src/voxel.rs): the level is loaded natively once the session// knows the asset root; an explosion returns what it did as JSON.let v = voxels.clone();- e.set("voxelLevel", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> { api::voxel_level(&mut v.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;+ 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)) })?)?;// 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());- e.set("voxelEdit", Function::new(ctx.clone(), move |ctx: Ctx<'js>, d: Value<'js>| -> rquickjs::Result<String> { let _lent = Lent::new(&ctx, &dl)?; api::voxel_edit(&mut v.borrow_mut(), &mut w.borrow_mut(), &mut p.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;+ e.set("voxelEdit", Function::new(ctx.clone(), move |ctx: Ctx<'js>, d: Value<'js>| -> rquickjs::Result<String> { let json = to_json(&d)?; let _lent = Lent::new(&ctx, &dl)?; api::voxel_edit(&mut v.borrow_mut(), &mut w.borrow_mut(), &mut p.borrow_mut(), &json).map_err(|e| thrown(&ctx, e)) })?)?;// The voxel bodies (ROADMAP § 6 step 8), as JSON: [{ body, collider, voxels, asleep, position, rotation }]. `body`// is the physics world's id: `physics("impulse", { body, ... })` and the other calls take it.let (v, p) = (voxels.clone(), physics.clone());e.set("voxelBodies", Function::new(ctx.clone(), move || -> String { api::voxel_bodies(&v.borrow(), &p.borrow()) })?)?;+ // One voxel body's edit (its object's `add` / `paint` / `carve`), its contacts on or off, the bodies gone since+ // the last call (step 10: voxel bodies as objects).+ let (v, w, p, d) = (voxels.clone(), world.clone(), physics.clone(), budget.clone());+ e.set("voxelBodyEdit", Function::new(ctx.clone(), move |ctx: Ctx<'js>, body: f64, d2: Value<'js>| -> rquickjs::Result<String> { let json = to_json(&d2)?; let _lent = Lent::new(&ctx, &d)?; api::voxel_body_edit(&mut v.borrow_mut(), &mut w.borrow_mut(), &mut p.borrow_mut(), body, &json).map_err(|e| thrown(&ctx, e)) })?)?;+ let (v, p) = (voxels.clone(), physics.clone());+ e.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()) })?)?;let v = voxels.clone();e.set("voxelHash", Function::new(ctx.clone(), move || -> String { api::voxel_hash(&v.borrow()) })?)?;let v = voxels.clone();@@ -252,7 +260,8 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<R})?)?;let w = world.clone();e.set("texture", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value, data: Option<TypedArray<u8>>| -> rquickjs::Result<()> {- api::texture(&mut w.borrow_mut(), id, &to_json(&d)?, data.as_ref().map(|d| d.as_ref())).map_err(|e| thrown(&ctx, e))+ let json = to_json(&d)?;+ api::texture(&mut w.borrow_mut(), id, &json, data.as_ref().map(|d| d.as_ref())).map_err(|e| thrown(&ctx, e))})?)?;let w = world.clone();e.set("shader", Function::new(ctx.clone(), move |name: String, code: String, helpers: String| w.borrow_mut().set_shader(&name, code, helpers))?)?;@@ -287,9 +296,9 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Rw.borrow_mut().set_proc_asset(id, function, uri).map_err(|e| fail(&ctx, e))})?)?;let w = world.clone();- e.set("material", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { api::material(&mut w.borrow_mut(), id, &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;+ e.set("material", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { let json = to_json(&d)?; api::material(&mut w.borrow_mut(), id, &json).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();- e.set("object", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { api::object(&mut w.borrow_mut(), id, &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;+ e.set("object", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { let json = to_json(&d)?; api::object(&mut w.borrow_mut(), id, &json).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();e.set("transform", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, t: TypedArray<f32>| -> rquickjs::Result<()> { api::transform(&mut w.borrow_mut(), id, t.as_ref()).map_err(|e| thrown(&ctx, e)) })?)?;// An instanced mesh's instances: count drawn, then matrices (16 numbers each), colours (3) and per-instance data@@ -311,9 +320,9 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Rapi::sway(&mut w.borrow_mut(), id, j.as_ref()).map_err(|e| thrown(&ctx, e))})?)?;let w = world.clone();- e.set("light", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { api::light(&mut w.borrow_mut(), id, &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;+ e.set("light", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { let json = to_json(&d)?; api::light(&mut w.borrow_mut(), id, &json).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();- e.set("camera", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { api::camera(&mut w.borrow_mut(), id, &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;+ e.set("camera", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> { let json = to_json(&d)?; api::camera(&mut w.borrow_mut(), id, &json).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();e.set("animation", Function::new(ctx.clone(), move |ctx: Ctx, id: u32, d: Value| -> rquickjs::Result<()> {let j = if d.is_null() || d.is_undefined() { None } else { Some(to_json(&d)?) };@@ -323,10 +332,11 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Rlet p = physics.clone();e.set("remove", Function::new(ctx.clone(), move |id: u32| api::remove(&mut w.borrow_mut(), &mut p.borrow_mut(), id))?)?;let w = world.clone();- e.set("environment", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> { api::environment(&mut w.borrow_mut(), &to_json(&d)?).map_err(|e| thrown(&ctx, e)) })?)?;+ e.set("environment", Function::new(ctx.clone(), move |ctx: Ctx, d: Value| -> rquickjs::Result<()> { let json = to_json(&d)?; api::environment(&mut w.borrow_mut(), &json).map_err(|e| thrown(&ctx, e)) })?)?;let w = world.clone();e.set("settings", Function::new(ctx.clone(), move |d: Value| -> rquickjs::Result<()> {- api::settings(&mut w.borrow_mut(), &to_json(&d)?);+ let json = to_json(&d)?;+ api::settings(&mut w.borrow_mut(), &json);Ok(())})?)?;ctx.globals().set("__engine", e)@@ -913,6 +923,69 @@ mod tests {assert!((250..800).contains(&ms), "ended after {ms} ms (50 of script and at most 250 lent)");}+ /// The engine's half of a voxel body gone under a held object (the review of #25): a level edit carves it away;+ /// every engine call on its id then throws a script error (which `VoxelBody` takes as its cue to find it gone),+ /// none panics, and the gone list names it with its reason.+ #[test]+ fn calls_on_a_voxel_body_the_level_carved_away_throw_cleanly() {+ let h = ScriptHost::new(GAME).unwrap();+ *h.voxels.borrow_mut() = crate::voxel::VoxelWorld::of_blocks(&[([0, 0, 0], [64, 4, 64], Some((0, 0)), true), ([28, 4, 28], [4, 24, 4], None, false)], &mut h.world.borrow_mut(), &mut h.physics.borrow_mut());+ h.voxels.borrow_mut().edit(&mut h.world.borrow_mut(), &mut h.physics.borrow_mut(), &crate::voxel::EditOp::parse(&serde_json::json!({ "op": "carve", "box": [2.7, 0.5, 2.7, 3.3, 0.7, 3.3] })).unwrap()).unwrap();+ let out: String = h+ .call(1000, |ctx| {+ ctx.eval(+ r#"+ const id = JSON.parse(__engine.voxelBodies())[0].body;+ __engine.voxelEdit({ op: "carve", box: [2.0, 0.6, 2.0, 4.0, 4.0, 4.0] });+ const tries = {+ state: () => __engine.physics("state", { body: id }),+ impulse: () => __engine.physics("impulse", { body: id, impulse: [0, 1, 0] }),+ contacts: () => __engine.voxelContacts(id, true),+ edit: () => __engine.voxelBodyEdit(id, { op: "paint", material: 1, sphere: [3, 1, 3, 1] }),+ };+ const r = [__engine.voxelBodies()];+ for (const [k, f] of Object.entries(tries)) { try { f(); r.push(k + " ok"); } catch (e) { r.push(k + " threw"); } }+ r.push(__engine.voxelGone());+ r.push(String(id));+ JSON.stringify(r)+ "#,+ )+ })+ .unwrap();+ let r: Vec<String> = serde_json::from_str(&out).unwrap();+ let id = &r[6];+ assert_eq!(r[..6], ["[]".to_string(), "state threw".into(), "impulse threw".into(), "contacts threw".into(), "edit threw".into(), format!("[[{id},\"carved\"]]")]);+ }++ /// A descriptor whose getter calls the engine again (the review of #25: the engine was borrowed while the+ /// descriptor was read, and the second call panicked, "already mutably borrowed"): each entry that takes one reads+ /// it first. None panics; each answers or throws a script error.+ #[test]+ fn a_getter_in_a_descriptor_that_calls_the_engine_does_not_panic_it() {+ let h = ScriptHost::new(GAME).unwrap();+ *h.voxels.borrow_mut() = crate::voxel::VoxelWorld::of_blocks(&[([0, 0, 0], [64, 4, 64], Some((0, 0)), true), ([28, 4, 28], [4, 24, 4], None, false)], &mut h.world.borrow_mut(), &mut h.physics.borrow_mut());+ h.voxels.borrow_mut().edit(&mut h.world.borrow_mut(), &mut h.physics.borrow_mut(), &crate::voxel::EditOp::parse(&serde_json::json!({ "op": "carve", "box": [2.7, 0.5, 2.7, 3.3, 0.7, 3.3] })).unwrap()).unwrap();+ // (Every getter calls into the voxel world, the physics and the scene's world: whichever one the entry borrows.)+ let poke = "__engine.voxelBodies(); __engine.voxelHash(); __engine.physics('hash', {}); __engine.visible(1, true)";+ let cases = [+ ("voxelEdit", format!("__engine.voxelEdit({{ get op() {{ {poke}; return 'carve'; }}, sphere: [1, 0.3, 1, 0.2] }})")),+ ("voxelBodyEdit", format!("__engine.voxelBodyEdit(JSON.parse(__engine.voxelBodies())[0].body, {{ get op() {{ {poke}; return 'paint'; }}, material: 1, sphere: [3, 1.5, 3, 0.3] }})")),+ ("voxelLevel", format!("__engine.voxelLevel({{ get route() {{ {poke}; return 'mesh'; }}, palette: [], objects: [] }})")),+ ("material", format!("__engine.material(9, {{ get color() {{ {poke}; return [1, 1, 1]; }} }})")),+ ("object", format!("__engine.object(9, {{ get name() {{ {poke}; return 'x'; }}, kind: 'group' }})")),+ ("light", format!("__engine.light(9, {{ get type() {{ {poke}; return 'point'; }} }})")),+ ("camera", format!("__engine.camera(9, {{ get fov() {{ {poke}; return 50; }} }})")),+ ("environment", format!("__engine.environment({{ get kind() {{ {poke}; return 'color'; }} }})")),+ ("settings", format!("__engine.settings({{ get exposure() {{ {poke}; return 0; }} }})")),+ ("texture", format!("__engine.texture(9, {{ get uri() {{ {poke}; return 'x.png'; }} }})")),+ ("physics", format!("__engine.physics('ray', {{ get origin() {{ {poke}; return [0, 5, 0]; }}, direction: [0, -1, 0] }})")),+ ];+ for (name, js) in cases {+ let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.call(1000, |ctx| ctx.eval::<rquickjs::Value, _>(js.as_str()).map(|_| ()))));+ assert!(r.is_ok(), "{name}: the engine panicked");+ }+ }+/// An id scene code read out of an answer goes back into a call: a ray's hit on a voxel body, its `body` into an/// impulse. (Parsed out of the answer the id is a double in the script engine, and comes back as `1073741837.0`:/// the bridge reads a whole number as the id it is.)diff --git a/renderer/src/voxel.rs b/renderer/src/voxel.rsindex e82c420..81f5a1d 100644--- a/renderer/src/voxel.rs+++ b/renderer/src/voxel.rs@@ -41,6 +41,24 @@ const MAX_TICKS: u32 = 8;/// few frames of a thousand went over; with the physics on one thread, `THREERT_PHYSICS_THREADS=1`, 128 is about at/// the frame).pub const MAX_BODIES: usize = 300;+/// The most voxels one `add` puts on a body (`edit_body`): 65,536, a block of 4 m at 0.1 m. More is refused, nothing+/// added: a body's collider, mesh and mass are made again from all its cells at every edit and its contacts cost by its+/// size (the review of #24, item 6: a block of 200³ cut loose is 2.8 s of edit and 619 MB), so a body is not grown+/// into a building by one call.+pub const MAX_BODY_ADD: usize = 1 << 16;+/// The most cells a voxel body grows to by adds (`edit_body`): 2^21, a block of 128³. Past it an add is refused: an edit+/// of a body that size takes half a second (its collider, mesh and mass are made from all its cells) and 171 MB (the+/// review of #24, item 6); the physics refuses a voxel shape past 2^24 cells, which no body reaches this way.+pub const MAX_BODY_CELLS: usize = 1 << 21;+/// The largest box a voxel body's cells may span: 1,024 cells a side (102.4 m at 0.1 m, more than any building of the+/// benchmark level) and 2^25 cells in all. Its mesh is made over that box (voxel_core `greedy_mesh`: a byte a cell and+/// 3/8 of one in bit columns, so at most 47 MB a redraw), and its cells stay within the physics' coordinate range. An+/// add past it is refused; a part past it is debris, not a body.+pub const MAX_BODY_SIDE: i32 = 1024;+pub const MAX_BODY_BOX: i64 = 1 << 25;+/// The most "gone" records kept for scene code (`take_gone`) when nothing takes them: older ones are let go.+const MAX_GONE: usize = 1 << 16;+/// The most edits and frames scene code can ask for before the level is loaded (in setup), kept until it is: they are/// outside the script engine's memory, so they are counted. 4,096: a setup that cuts a level into its starting state/// takes a few dozen edits and a second of frames (the tests: one cut and 60 frames); one that asks for thousands is@@ -157,7 +175,7 @@ struct VoxelObject {/// 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 = 0xd26e_5461_62ad_7eec;+pub const EXPECTED_SCRIPT: u64 = 0x0235_ba72_5c92_2a63;/// A brick as a collider's shell reads it (`VoxelWorld::brick_at`).#[derive(Clone, Copy)]@@ -258,6 +276,8 @@ pub struct VoxelWorld {objects: Vec<Option<VoxelObject>>,tiles: HashMap<(i32, i32), usize>,next_id: u32,+ /// After the ids wrapped: those still in use then, passed over (`id`).+ in_use: Option<std::collections::HashSet<u32>>,/// Debris kept for scene code (`LevelDesc::debris`): world-space centre and palette index of each removed voxel/// that is in no new object, since `take_debris` last took them (at most `MAX_DEBRIS`; of an edit that removes/// more than `EDIT_DEBRIS`, every n-th).@@ -286,6 +306,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 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.floor: f32,/// Time spent finding the colliders' cells (`shell`), ms: of the load, and of every edit since.@@ -321,8 +343,26 @@ impl VoxelWorld {if self.next_id == 0 {self.next_id = FIRST_ID;}- self.next_id += 1;- self.next_id+ loop {+ if self.next_id == u32::MAX {+ // (The ids ran out: from the first again, past the ones still in use, which are all the voxel world's+ // own: its objects' and their geometries', its colliders', its bodies'.)+ self.next_id = FIRST_ID;+ self.in_use = Some(self.live_ids());+ }+ self.next_id += 1;+ if !self.in_use.as_ref().is_some_and(|u| u.contains(&self.next_id)) {+ return self.next_id;+ }+ }+ }++ /// Every id the voxel world holds now (`id`'s after a wrap).+ 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.bodies.values().flat_map(|b| [b.body, b.collider]));+ u}fn grid(&self, k: usize) -> &Rc<VoxelGrid> {@@ -677,11 +717,17 @@ impl VoxelWorld {// 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();- let b = self.carve_bodies(w, p, op.shape, radii)?;+ let b = self.carve_bodies(w, p, op.shape, radii, None)?;out["body_voxels"] = b.0.into();out["bodies_carved"] = b.1.into();out["bodies_ms"] = (t.elapsed().as_secs_f64() * 1e3).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)?;+ out["body_voxels"] = b.0.into();+ out["bodies_painted"] = b.1.into();+ }out["bodies"] = self.bodies.len().into();Ok(out)}@@ -757,6 +803,7 @@ impl VoxelWorld {if let Some(o) = self.objects.get_mut(k as usize).and_then(|o| o.take()) {for p in o.parts {w.remove(p.1);+ w.drop_geometry(p.2);}if let Some((tx, tz)) = o.tile {self.tiles.remove(&(tx, tz));@@ -979,6 +1026,57 @@ impl VoxelWorld {out}+ /// Every level object's collider against its shell found by brute force (the checks': `examples/physics_fuzz.rs`):+ /// its cells within `SHELL` six-connected steps of a cell that is not solid, solid being the object's own cells and,+ /// for a terrain tile on the bricks' lattice, its neighbours' and the bedrock under it (as `brick_at` reads them).+ /// Err names the first object whose collider differs, and how. Ok: the objects checked.+ pub fn check_shells(&self, p: &PhysicsWorld) -> std::result::Result<usize, String> {+ let Some(level) = self.level.as_ref() else { return Ok(0) };+ let cell = |k: usize, g: [i32; 3]| level.objects.get(k).and_then(|o| o.as_ref()).is_some_and(|o| o.grid.get(g[0], g[1], g[2]) != 0);+ let mut checked = 0;+ for (k, c) in self.colliders.iter().enumerate() {+ let (Some(c), Some(o)) = (*c, level.objects.get(k).and_then(|o| o.as_ref())) else { continue };+ let tile = self.objects.get(k).and_then(|o| o.as_ref()).filter(|v| v.off.iter().all(|x| x % 8 == 0)).and_then(|v| v.tile.map(|t| (t, v.off)));+ let solid = |g: [i32; 3]| -> bool {+ let Some(((tx, tz), off)) = tile else { return cell(k, g) };+ let t = [g[0] + off[0], g[1] + off[1], g[2] + off[2]];+ if t[1] < 0 {+ return true;+ }+ if (0..TILE).contains(&t[0]) && (0..TILE).contains(&t[2]) {+ return cell(k, g);+ }+ let Some(&n) = self.tiles.get(&(tx + t[0].div_euclid(TILE), tz + t[2].div_euclid(TILE))) else { return false };+ match self.objects.get(n).and_then(|v| v.as_ref()).filter(|v| v.off.iter().all(|x| x % 8 == 0)) {+ Some(v) => cell(n, [t[0].rem_euclid(TILE) - v.off[0], t[1] - v.off[1], t[2].rem_euclid(TILE) - v.off[2]]),+ None => false,+ }+ };+ let mut want: Vec<[i32; 3]> = o+ .grid+ .voxels()+ .map(|(g, _)| g)+ .filter(|g| (-SHELL..=SHELL).any(|dx| (-SHELL + dx.abs()..=SHELL - dx.abs()).any(|dy| { let r = SHELL - dx.abs() - dy.abs(); (-r..=r).any(|dz| !solid([g[0] + dx, g[1] + dy, g[2] + dz])) })))+ .collect();+ want.sort_unstable();+ let have = p.bridge_ref().engine_voxel_cells(c).ok_or_else(|| format!("object {k}: its collider {c} is gone"))?;+ if have != want {+ let missing = want.iter().filter(|g| have.binary_search(g).is_err()).count();+ let extra = have.iter().filter(|g| want.binary_search(g).is_err()).count();+ let first = want.iter().find(|g| have.binary_search(g).is_err()).or(have.iter().find(|g| want.binary_search(g).is_err()));+ return Err(format!("object {k}: its collider has {} cells, its shell {}: {missing} missing, {extra} too many (first {first:?})", have.len(), want.len()));+ }+ checked += 1;+ }+ // An object with cells and no collider: its shell is not empty, so it should have one.+ for (k, o) in level.objects.iter().enumerate() {+ if o.as_ref().is_some_and(|o| o.grid.count() > 0) && self.colliders.get(k).copied().flatten().is_none() && self.physics && !self.bodies.contains_key(&k) && self.objects.get(k).is_some_and(|v| v.is_some()) {+ return Err(format!("object {k} has {} cells and no collider", o.as_ref().unwrap().grid.count()));+ }+ }+ Ok(checked)+ }+/// A level of solid blocks of palette entry 1 made here, no file (the checks' and the tests'): each block's corner/// cell, its size in cells, its terrain tile if it is one, and whether it is an anchor. Voxels of 0.1 m, the mesh/// route, the level's physics on.@@ -1057,6 +1155,30 @@ 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 (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);+ v.palette.push(0);+ // (Its middle: the centre of its grid's bounds, through its pose.)+ let (b, at) = ph+ .as_ref()+ .and_then(|p| {+ let x = v.bodies.values().max_by_key(|x| x.grid.count())?;+ let (at, rot, _) = p.bridge_ref().engine_pose(x.body)?;+ let (lo, hi) = x.grid.bounds()?;+ let mid = (Vec3::new(lo[0] as f32, lo[1] as f32, lo[2] as f32) + Vec3::new(hi[0] as f32, hi[1] as f32, hi[2] as f32)) * 0.5 * v.size;+ 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");+ 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");+ w.take_changes();+ }+ fold(&mut h, &v, &ph);+ run(&mut h, &mut v, &mut w, &mut ph, 180);h}@@ -1074,6 +1196,11 @@ impl VoxelWorld {// more voxels than the part that would take its place; else that part is debris itself (a chip cut off at// the cap does not make a bigger body vanish).let count = grid.count();+ // (A part whose cells span more than a body may is debris, as one the physics refuses.)+ if !grid.bounds().is_some_and(|(lo, hi)| body_fits(lo, hi.map(|v| v - 1))) {+ debris(self, &grid);+ return Ok(());+ }while self.bodies.len() >= self.max_bodies.max(1) {let least = self.bodies@@ -1082,7 +1209,7 @@ impl VoxelWorld {.map(|(&k, b)| (!p.bridge_ref().engine_pose(b.body).is_none_or(|s| s.2), b.grid.count(), k)).min();match least {- Some((_, n, k)) if n <= count => self.retire(w, p, k, true),+ Some((_, n, k)) if n <= count => self.retire(w, p, k, true, "cap"),_ => {debris(self, &grid);self.capped += 1;@@ -1091,8 +1218,8 @@ impl VoxelWorld {}}let cells: Vec<[i32; 3]> = grid.voxels().map(|(g, _)| g).collect();- // (A body's density is its voxels' mean: carved, it weighs what its cells still do.)- let density = (grid.voxels().map(|(_, m)| self.density.get(m as usize).copied().unwrap_or(DENSITY[0]) as f64).sum::<f64>() / cells.len().max(1) as f64) as f32;+ // (The collider carries no mass: the body's is its cells', each at its own density: `body_mass`.)+ let density = 0.0;let (body, collider) = (self.id(), self.id());let made = p.bridge().engine_body(body, &BodyDesc { position: position.to_array(), rotation: rotation.to_array(), linvel: velocity.0, angvel: velocity.1, ..Default::default() }).and_then(|_| {let d = ColliderDesc { density, friction: FRICTION, ..ColliderDesc::new(physics_core::Shape::Voxels { size, cells }) };@@ -1104,6 +1231,9 @@ impl VoxelWorld {debris(self, &grid);return Ok(());}+ if let Err(e) = self.weigh(p, body, &grid) {+ eprintln!("voxels: a body's mass was not set ({e})");+ }self.this_edit.insert(k);let parts = self.body_parts(w, k, &grid, position, rotation)?;if self.objects.len() <= k {@@ -1166,8 +1296,12 @@ impl VoxelWorld {/// Body `k` gone: its objects, its body and collider. `debris`: its voxels are kept as debris where they are (it/// was retired for the cap; one that left the world leaves nothing).- fn retire(&mut self, w: &mut World, p: &mut PhysicsWorld, k: usize, debris: bool) {+ fn retire(&mut self, w: &mut World, p: &mut PhysicsWorld, k: usize, debris: bool, reason: &'static str) {let Some(b) = self.bodies.remove(&k) else { return };+ if self.gone.len() >= MAX_GONE {+ self.gone.drain(..MAX_GONE / 2);+ }+ self.gone.push((b.body, reason));if debris {let m = Mat4::from_rotation_translation(Quat::from_array(b.pose.1), Vec3::from(b.pose.0));let size = self.size;@@ -1178,6 +1312,7 @@ impl VoxelWorld {if let Some(o) = self.objects.get_mut(k).and_then(|o| o.take()) {for part in o.parts {w.remove(part.1);+ w.drop_geometry(part.2);}}}@@ -1208,7 +1343,7 @@ impl VoxelWorld {}}for &k in &gone {- self.retire(w, p, k, false);+ self.retire(w, p, k, false, "fell");}(moved, gone.len())}@@ -1218,39 +1353,14 @@ impl VoxelWorld {/// collider loses the cells, its mesh is made again); what the carve cut off it is a body of its own, moving as/// it did (parts under `MIN_PIECE` voxels: debris); a body with nothing left is gone. Returns the voxels carved/// and the bodies carved.- fn carve_bodies(&mut self, w: &mut World, p: &mut PhysicsWorld, shape: ShapeM, radii: [i32; 4]) -> Result<(usize, usize)> {+ fn carve_bodies(&mut self, w: &mut World, p: &mut PhysicsWorld, shape: ShapeM, radii: [i32; 4], only: Option<usize>) -> Result<(usize, usize)> {let size = self.size;let hardness = self.level.as_ref().map_or([0u8; 256], |l| l.hardness);- // The shape as the level's carve takes it (voxel_core `Shape::checked`, `contains`): a radius within 0 and- // `MAX_RADIUS` voxels, each class's share of it; a box whole for every class it reaches at all.- let cap = voxel_core::MAX_RADIUS as f32 * size;- let shape = match shape {- ShapeM::Sphere(c, r) => ShapeM::Sphere(c, if r.is_nan() { 0.0 } else { r.clamp(0.0, cap) }),- ShapeM::Capsule(a, b, r) => ShapeM::Capsule(a, b, if r.is_nan() { 0.0 } else { r.clamp(0.0, cap) }),- other => other,- };- let inside = |q: Vec3, scale: f32| -> bool {- match shape {- ShapeM::Sphere(c, r) => q.distance_squared(Vec3::from(c)) <= (r * scale) * (r * scale),- ShapeM::Box(a, b) => {- let (c, h) = ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).abs() * 0.5);- (q - c).abs().cmple(h).all()- }- ShapeM::Capsule(a, b, r) => {- let (a, ab) = (Vec3::from(a), Vec3::from(b) - Vec3::from(a));- let t = if ab.length_squared() > 0.0 { ((q - a).dot(ab) / ab.length_squared()).clamp(0.0, 1.0) } else { 0.0 };- q.distance_squared(a + ab * t) <= (r * scale) * (r * scale)- }- }- };- // The shape's reach, for a body's bounding sphere.- let (centre, reach) = match shape {- ShapeM::Sphere(c, r) => (Vec3::from(c), r),- ShapeM::Box(a, b) => ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).length() * 0.5),- ShapeM::Capsule(a, b, r) => ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).length() * 0.5 + r),- };+ let shape = level_shape(shape, size);+ let (centre, reach) = shape_reach(shape);+ let inside = |q: Vec3, scale: f32| shape_contains(shape, q, scale);let (mut voxels, mut carved) = (0usize, 0usize);- let keys: Vec<usize> = self.bodies.keys().copied().collect();+ let keys: Vec<usize> = self.bodies.keys().copied().filter(|&k| only.is_none_or(|o| o == k)).collect();for k in keys {// (A body retired for the cap by a part cut off an earlier one in this same carve is no longer there.)let Some(b) = self.bodies.get(&k) else { continue };@@ -1290,22 +1400,10 @@ impl VoxelWorld {}let (collider, left) = (b.collider, b.grid.count());if left == 0 {- self.retire(w, p, k, false);+ self.retire(w, p, k, false, "carved");} else {- if let Err(e) = p.bridge().engine_edit_voxels(collider, &cleared, &[]) {- eprintln!("voxels: a body's collider was not edited ({e})");- }- // Its mesh again: new objects in the old ones' place (a driven object given another geometry would- // rebuild the scene; one removed and one added are both in place).- let old = std::mem::take(&mut self.objects[k].as_mut().unwrap().parts);- for part in old {- w.remove(part.1);- }- let grid = self.bodies[&k].grid.clone();- let parts = self.body_parts(w, k, &grid, Vec3::from(at), Quat::from_array(rot))?;- let o = self.objects[k].as_mut().unwrap();- o.parts = parts;- o.bounds(&grid, size);+ let _ = collider;+ self.redraw_body(w, p, k, &cleared, &[], Vec3::from(at), Quat::from_array(rot))?;}for part in loose {if part.len() < MIN_PIECE {@@ -1330,6 +1428,212 @@ impl VoxelWorld {Ok((voxels, carved))}+ /// A body's mass properties from its cells, each a cube of its palette entry's density (parry's voxel mass is the+ /// same sum at one density): mass, centre of mass and inertia about it in the body's frame, summed in the grid's+ /// fixed order in f64 (the same bits everywhere), then set on the body (its collider carries none).+ fn weigh(&self, p: &mut PhysicsWorld, body: u32, grid: &VoxelGrid) -> std::result::Result<(), String> {+ let s = self.size as f64;+ let v = s * s * s;+ let cell = |m: u8| self.density.get(m as usize).copied().unwrap_or(DENSITY[0]) as f64 * v;+ let (mut mass, mut first) = (0.0f64, [0.0f64; 3]);+ for (g, m) in grid.voxels() {+ let (mm, c) = (cell(m), [0, 1, 2].map(|a| (g[a] as f64 + 0.5) * s));+ mass += mm;+ for a in 0..3 {+ first[a] += mm * c[a];+ }+ }+ if mass <= 0.0 {+ return Err("no cell".into());+ }+ let com = first.map(|f| f / mass);+ // About the centre of mass: each cube's own (m s² / 6 on the diagonal) and the parallel axes' (m (|d|² I - d dᵀ)).+ let mut i = [0.0f64; 6];+ for (g, m) in grid.voxels() {+ let mm = cell(m);+ let d = [0, 1, 2].map(|a| (g[a] as f64 + 0.5) * s - com[a]);+ let (own, dd) = (mm * s * s / 6.0, d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);+ i[0] += own + mm * (dd - d[0] * d[0]);+ i[1] += own + mm * (dd - d[1] * d[1]);+ i[2] += own + mm * (dd - d[2] * d[2]);+ i[3] -= mm * d[0] * d[1];+ i[4] -= mm * d[0] * d[2];+ i[5] -= mm * d[1] * d[2];+ }+ p.bridge().engine_mass(body, mass as f32, com.map(|c| c as f32), i.map(|c| c as f32))+ }++ /// Body `k` after its cells changed (`cleared` out of its grid, `filled` in): its collider edited by them, its mesh+ /// made again as new objects in the old ones' place (a driven object given another geometry would rebuild the+ /// scene; one removed and one added are both in place), its mass from its cells.+ fn redraw_body(&mut self, w: &mut World, p: &mut PhysicsWorld, k: usize, cleared: &[[i32; 3]], filled: &[[i32; 3]], at: Vec3, rot: Quat) -> Result<()> {+ let (body, collider) = (self.bodies[&k].body, self.bodies[&k].collider);+ if !(cleared.is_empty() && filled.is_empty()) {+ if let Err(e) = p.bridge().engine_edit_voxels(collider, cleared, filled) {+ eprintln!("voxels: a body's collider was not edited ({e})");+ }+ }+ // (A body whose collider the physics took out is not kept drawn and weighed without it: its voxels are debris.)+ if p.bridge_ref().engine_voxels(collider).is_none() {+ self.retire(w, p, k, true, "carved");+ return Ok(());+ }+ let old = std::mem::take(&mut self.objects[k].as_mut().unwrap().parts);+ for part in old {+ w.remove(part.1);+ w.drop_geometry(part.2);+ }+ let grid = self.bodies[&k].grid.clone();+ let parts = self.body_parts(w, k, &grid, at, rot)?;+ let o = self.objects[k].as_mut().unwrap();+ o.parts = parts;+ o.bounds(&grid, self.size);+ if let Err(e) = self.weigh(p, body, &grid) {+ eprintln!("voxels: a body's mass was not set ({e})");+ }+ Ok(())+ }++ /// Paint reaching bodies (all, or `only` one): of each body the shape meets, the cells on its surface (a face+ /// open to the outside of its grid, as the level's paint) whose centres are inside take `m`. Collider unchanged,+ /// mesh and mass again. Returns the voxels painted and the bodies.+ fn paint_bodies(&mut self, w: &mut World, p: &mut PhysicsWorld, shape: ShapeM, m: u8, only: Option<usize>) -> Result<(usize, usize)> {+ let size = self.size;+ let shape = level_shape(shape, size);+ let (centre, reach) = shape_reach(shape);+ let (mut voxels, mut painted) = (0, 0);+ let keys: Vec<usize> = self.bodies.keys().copied().filter(|&k| only.is_none_or(|o| o == k)).collect();+ for k in keys {+ let b = &self.bodies[&k];+ let Some((at, rot, _)) = p.bridge_ref().engine_pose(b.body) else { continue };+ let pose = Mat4::from_rotation_translation(Quat::from_array(rot), Vec3::from(at));+ if !reaches(&b.grid, pose, size, centre, reach) {+ continue;+ }+ let grid = &b.grid;+ let open = |g: [i32; 3]| DIRS6.iter().any(|d| grid.get(g[0] + d[0], g[1] + d[1], g[2] + d[2]) == 0);+ let these: Vec<[i32; 3]> = grid.voxels().filter(|&(g, mat)| mat != m && open(g) && shape_contains(shape, pose.transform_point3((Vec3::new(g[0] as f32, g[1] as f32, g[2] as f32) + 0.5) * size), 1.0)).map(|(g, _)| g).collect();+ if these.is_empty() {+ continue;+ }+ let b = self.bodies.get_mut(&k).unwrap();+ for g in &these {+ b.grid.set(g[0], g[1], g[2], m);+ }+ voxels += these.len();+ painted += 1;+ self.redraw_body(w, p, k, &[], &[], Vec3::from(at), Quat::from_array(rot))?;+ }+ Ok((voxels, painted))+ }++ /// Voxels added to body `k`: the empty cells of its grid whose centres are inside the shape (world metres, as the+ /// level takes it), at most `MAX_BODY_ADD` of them and 64 times that looked at. Collider, mesh and mass again. Returns the voxels.+ fn add_to_body(&mut self, w: &mut World, p: &mut PhysicsWorld, k: usize, shape: ShapeM, m: u8) -> Result<usize> {+ let size = self.size;+ let shape = level_shape(shape, size);+ let b = &self.bodies[&k];+ let Some((at, rot, _)) = p.bridge_ref().engine_pose(b.body) else { return Ok(0) };+ let pose = Mat4::from_rotation_translation(Quat::from_array(rot), Vec3::from(at));+ // The shape's world box, into the grid's cells (through the inverse pose: the eight corners' bounds).+ let (lo, hi) = shape_box(shape);+ let inv = pose.inverse();+ let corners = (0..8).map(|c| inv.transform_point3(Vec3::new([lo.x, hi.x][c & 1], [lo.y, hi.y][(c >> 1) & 1], [lo.z, hi.z][c >> 2])) / size);+ let (mut a, mut z) = (Vec3::splat(f32::INFINITY), Vec3::splat(f32::NEG_INFINITY));+ for c in corners {+ (a, z) = (a.min(c), z.max(c));+ }+ if !(a.is_finite() && z.is_finite()) {+ return Err(anyhow!("voxelEdit: the shape is not finite"));+ }+ let (ga, gz) = (a.floor().as_ivec3(), z.ceil().as_ivec3());+ // (Its cells are looked at one by one: at most 64 times what may be added, 2^22, a box of 16 m at 0.1 m.)+ // (In f64: three sides of up to 2^32 cells overflow an i64.)+ let n = (0..3).map(|i| (gz[i] as f64 - ga[i] as f64 + 1.0).max(0.0)).product::<f64>();+ if n > ((MAX_BODY_ADD as u64) << 6) as f64 {+ return Err(anyhow!("voxelBodyEdit: the shape is too large for an add on a body (at most {} cells across its bounds in the body's grid)", MAX_BODY_ADD << 6));+ }+ let mut filled = vec![];+ for x in ga.x..=gz.x {+ for y in ga.y..=gz.y {+ for z in ga.z..=gz.z {+ if b.grid.get(x, y, z) == 0 && shape_contains(shape, pose.transform_point3((Vec3::new(x as f32, y as f32, z as f32) + 0.5) * size), 1.0) {+ filled.push([x, y, z]);+ if filled.len() > MAX_BODY_ADD {+ return Err(anyhow!("voxelBodyEdit: at most {MAX_BODY_ADD} voxels can be added to a body at once"));+ }+ }+ }+ }+ }+ if filled.is_empty() {+ return Ok(0);+ }+ // What the body would be: refused before anything changes if it is too large, or its cells too far apart.+ if b.grid.count() + filled.len() > MAX_BODY_CELLS {+ return Err(anyhow!("voxelBodyEdit: a body grows to at most {MAX_BODY_CELLS} voxels"));+ }+ let (mut lo, mut hi) = b.grid.bounds().map_or(([i32::MAX; 3], [i32::MIN; 3]), |(lo, hi)| (lo, hi.map(|v| v - 1)));+ for g in &filled {+ for a in 0..3 {+ (lo[a], hi[a]) = (lo[a].min(g[a]), hi[a].max(g[a]));+ }+ }+ if !body_fits(lo, hi) {+ return Err(anyhow!("voxelBodyEdit: a body's voxels span at most {MAX_BODY_SIDE} cells a side and {MAX_BODY_BOX} in all"));+ }+ // The collider first: if the physics refuses the cells, nothing changes.+ let collider = b.collider;+ if let Err(e) = p.bridge().engine_edit_voxels(collider, &[], &filled) {+ if p.bridge_ref().engine_voxels(collider).is_none() {+ self.retire(w, p, k, true, "carved");+ }+ return Err(anyhow!("voxelBodyEdit: {e}"));+ }+ let b = self.bodies.get_mut(&k).unwrap();+ for g in &filled {+ b.grid.set(g[0], g[1], g[2], m);+ }+ self.redraw_body(w, p, k, &[], &[], Vec3::from(at), Quat::from_array(rot))?;+ Ok(filled.len())+ }++ /// An edit of one voxel body alone (scene code's `voxelBodyEdit`: a voxel object's `add`, `paint`, `carve`): the+ /// shape in world metres; `explode` and `carve` cut it (parts cut off are bodies of their own), `paint` its+ /// surface, `add` fills its empty cells in the shape.+ pub fn edit_body(&mut self, w: &mut World, ph: &mut Option<PhysicsWorld>, body: u32, op: &EditOp) -> Result<serde_json::Value> {+ let k = self.bodies.iter().find(|(_, b)| b.body == body).map(|(&k, _)| k).ok_or_else(|| anyhow!("voxelBodyEdit: no voxel body {body}"))?;+ let p = ph.as_mut().ok_or_else(|| anyhow!("voxelBodyEdit: no physics world"))?;+ if let EditKind::Add(m) | EditKind::Paint(m) = op.kind {+ if m as usize >= self.palette.len() {+ return Err(anyhow!("voxelBodyEdit: material {m} is not in the level's palette ({} entries)", self.palette.len()));+ }+ }+ self.ticks.0 += 1;+ self.this_edit.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))?,+ EditKind::Add(m) => {+ let n = self.add_to_body(w, p, k, op.shape, m)?;+ (n, (n > 0) as usize)+ }+ };+ Ok(serde_json::json!({ "voxels": voxels, "bodies": n, "gone": !self.bodies.contains_key(&k) }))+ }++ /// A body's contacts reported to scene code or not (its collider's events: `__engine.physics("contacts")`).+ pub fn body_contacts(&mut self, ph: &mut Option<PhysicsWorld>, body: u32, on: bool) -> Result<()> {+ let b = self.bodies.values().find(|b| b.body == body).ok_or_else(|| anyhow!("voxelContacts: no voxel body {body}"))?;+ let p = ph.as_mut().ok_or_else(|| anyhow!("voxelContacts: no physics world"))?;+ p.bridge().engine_events(b.collider, on).map_err(|e| anyhow!(e))+ }++ /// The bodies gone since the last call, with why: [[body, "cap" | "carved" | "fell"], ...].+ pub fn take_gone(&mut self) -> serde_json::Value {+ serde_json::Value::Array(std::mem::take(&mut self.gone).into_iter().map(|(b, r)| serde_json::json!([b, r])).collect())+ }+/// Voxel bodies now.pub fn bodies(&self) -> usize {self.bodies.len()@@ -1406,6 +1710,7 @@ impl VoxelWorld {if let Some(o) = self.objects.get_mut(id as usize).and_then(|o| o.take()) {for p in o.parts {w.remove(p.1);+ w.drop_geometry(p.2);}}}@@ -1470,12 +1775,17 @@ impl VoxelWorld {w.set_object(id, format!("{name}#{m}"), None, kind, true, false)?;parts.push((m, id, g));}- for p in old {+ for p in &old {if !geometry.iter().any(|g| g.0 == p.0) {w.remove(p.1);}}- // Its old geometries (unless another object still shares them) are no longer drawn.+ // Its old geometries are let go, unless another object (of the same file) still draws them.+ for p in old {+ if !geometry.iter().any(|g| g.1 == p.2) {+ w.drop_geometry(p.2);+ }+ }let o = self.objects[k].as_mut().unwrap();o.shared = None;o.parts = parts;@@ -1643,6 +1953,70 @@ impl VoxelWorld {/// Where a level object's collider stands, its cells being the object's own: the rotation of its quarter turns about/// y and the translation that puts the cube of its cell g on the cube of world cell `place.to_world(g)` (a turned/// cube's lowest corner is not the turned corner: `voxel_core::Placement`).+/// Whether cells spanning `lo` ..= `hi` fit a voxel body (`MAX_BODY_SIDE`, `MAX_BODY_BOX`).+fn body_fits(lo: [i32; 3], hi: [i32; 3]) -> bool {+ let side = |a: usize| hi[a] as i64 - lo[a] as i64 + 1;+ (0..3).all(|a| (1..=MAX_BODY_SIDE as i64).contains(&side(a))) && side(0) * side(1) * side(2) <= MAX_BODY_BOX+}++/// The six face neighbours.+const DIRS6: [[i32; 3]; 6] = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]];++/// A shape as the level's edits take it (voxel_core `Shape::checked`): a radius within 0 and `MAX_RADIUS` voxels (NaN:+/// 0), a box as given.+fn level_shape(shape: ShapeM, size: f32) -> ShapeM {+ let cap = voxel_core::MAX_RADIUS as f32 * size;+ let r = |r: f32| if r.is_nan() { 0.0 } else { r.clamp(0.0, cap) };+ match shape {+ ShapeM::Sphere(c, x) => ShapeM::Sphere(c, r(x)),+ ShapeM::Capsule(a, b, x) => ShapeM::Capsule(a, b, r(x)),+ other => other,+ }+}++/// Whether a point (world metres) is inside the shape, its radius scaled by `scale` (a class's share; a box whole).+fn shape_contains(shape: ShapeM, q: Vec3, scale: f32) -> bool {+ match shape {+ ShapeM::Sphere(c, r) => q.distance_squared(Vec3::from(c)) <= (r * scale) * (r * scale),+ ShapeM::Box(a, b) => {+ let (c, h) = ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).abs() * 0.5);+ (q - c).abs().cmple(h).all()+ }+ ShapeM::Capsule(a, b, r) => {+ let (a, ab) = (Vec3::from(a), Vec3::from(b) - Vec3::from(a));+ let t = if ab.length_squared() > 0.0 { ((q - a).dot(ab) / ab.length_squared()).clamp(0.0, 1.0) } else { 0.0 };+ q.distance_squared(a + ab * t) <= (r * scale) * (r * scale)+ }+ }+}++/// A sphere about the shape: its centre and radius.+fn shape_reach(shape: ShapeM) -> (Vec3, f32) {+ match shape {+ ShapeM::Sphere(c, r) => (Vec3::from(c), r),+ ShapeM::Box(a, b) => ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).length() * 0.5),+ ShapeM::Capsule(a, b, r) => ((Vec3::from(a) + Vec3::from(b)) * 0.5, (Vec3::from(b) - Vec3::from(a)).length() * 0.5 + r),+ }+}++/// The shape's world box.+fn shape_box(shape: ShapeM) -> (Vec3, Vec3) {+ match shape {+ ShapeM::Sphere(c, r) => (Vec3::from(c) - r, Vec3::from(c) + r),+ ShapeM::Box(a, b) => (Vec3::from(a).min(Vec3::from(b)), Vec3::from(a).max(Vec3::from(b))),+ ShapeM::Capsule(a, b, r) => (Vec3::from(a).min(Vec3::from(b)) - r, Vec3::from(a).max(Vec3::from(b)) + r),+ }+}++/// Whether a body's grid at its pose can reach the sphere about a shape (its bricks' bounding sphere against it).+fn reaches(grid: &VoxelGrid, pose: Mat4, size: f32, centre: Vec3, reach: f32) -> bool {+ let Some((lo, hi)) = grid.bounds() else { return false };+ // (The grid's bounds are its bricks': from `lo` up to `hi`, not through it.)+ let (lo, hi) = (Vec3::new(lo[0] as f32, lo[1] as f32, lo[2] as f32), Vec3::new(hi[0] as f32, hi[1] as f32, hi[2] as f32));+ let (mid, half) = ((lo + hi) * 0.5 * size, ((hi - lo) * 0.5 * size).length());+ pose.transform_point3(mid).distance(centre) <= reach + half+}+fn collider_pose(place: &Placement, size: f32) -> ([f32; 3], [f32; 4]) {const S: f32 = std::f32::consts::FRAC_1_SQRT_2;let (rotation, corner) = match place.turn & 3 {@@ -2114,6 +2488,184 @@ mod tests {assert_eq!((v.retired, v.capped), (1, capped + 1));}+ /// Step 10 (a): a voxel body weighed cell by cell; paint reaching it from the world and from its own edit; voxels+ /// added to it alone; carved alone; its contacts reported when asked; gone, with why; and scene code's colliders+ /// refused on it.+ #[test]+ fn voxel_bodies_are_weighed_painted_and_grown_cell_by_cell() {+ 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), ([8, 4, 8], [4, 24, 4], None, false)], &mut w, &mut ph);+ // A third palette entry of 8,000 kg/m³.+ v.palette.push(0);+ v.density.push(8000.0);+ for x in [2.7f32, 0.7] {+ v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "box": [x, 0.5, x, x + 0.6, 0.7, x + 0.6] }))).unwrap();+ }+ assert_eq!(v.bodies(), 2);+ let (k, b) = v.bodies.iter().find(|(_, b)| b.grid.count() == 336 && p_pose(&ph, b.body)[0] > 2.0).map(|(&k, b)| (k, b.body)).unwrap();+ let mass = |ph: &mut Option<PhysicsWorld>, w: &mut World| ph.as_mut().unwrap().call(w, "state", &serde_json::json!({ "body": b })).unwrap()["mass"].as_f64().unwrap();+ assert!((mass(&mut ph, &mut w) - 336.0).abs() < 1e-2, "336 cells of 1 l at 1,000 kg/m³");+ // Paint from the world over the bar's upper half: its surface there (the outer ring of each layer) is dense.+ let e = v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "paint", "material": 2, "box": [2.5, 1.75, 2.5, 3.5, 3.0, 3.5] }))).unwrap();+ assert_eq!((e["bodies_painted"].as_u64(), e["body_voxels"].as_u64()), (Some(1), Some(12 * 11 + 4)), "{e}");+ let painted = 12 * 11 + 4;+ assert!((mass(&mut ph, &mut w) - (336.0 + painted as f64 * 7.0)).abs() < 1e-1, "{} kg", mass(&mut ph, &mut w));+ // The other bar is untouched by it.+ assert!(v.bodies.iter().filter(|(&kk, _)| kk != k).all(|(_, o)| o.grid.voxels().all(|(_, m)| m == 1)));+ // A slab added to this body alone, on its top: 4 x 4 cells more; its collider has them.+ let top = p_pose(&ph, b)[1] + 2.1;+ let e = v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "add", "material": 1, "box": [2.7, top + 0.01, 2.7, 3.1, top + 0.09, 3.1] }))).unwrap();+ assert_eq!(e["voxels"].as_u64(), Some(16), "{e}");+ let grid_cells = v.bodies[&k].grid.count();+ assert_eq!(ph.as_ref().unwrap().bridge_ref().engine_voxels(v.bodies[&k].collider), Some(grid_cells));+ assert!((mass(&mut ph, &mut w) - (352.0 + painted as f64 * 7.0)).abs() < 1e-1);+ // Scene code cannot put a collider of its own on it.+ let r = ph.as_mut().unwrap().call(&mut w, "collider", &serde_json::json!({ "id": 7, "body": b, "shape": { "type": "sphere", "radius": 0.2 } }));+ assert!(r.is_err(), "{r:?}");+ // Its contacts, asked for: thrown up, it lands, and the landing is reported.+ v.body_contacts(&mut ph, b, true).unwrap();+ ph.as_mut().unwrap().call(&mut w, "velocity", &serde_json::json!({ "body": b, "linvel": [0, 3, 0] })).unwrap();+ for _ in 0..90 {+ crate::api::physics_advance(&mut ph, &mut v, &mut w, 1.0 / 60.0);+ }+ let c = ph.as_mut().unwrap().call(&mut w, "contacts", &serde_json::json!({})).unwrap();+ assert!(c.as_array().unwrap().iter().any(|c| c["started"] == true && (c["bodyA"].as_u64() == Some(b as u64) || c["bodyB"].as_u64() == Some(b as u64))), "{c}");+ // Carved away whole, alone: gone, "carved"; the other body stays.+ let e = v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "carve", "box": [1.5, -1.0, 1.5, 4.5, 5.0, 4.5] }))).unwrap();+ assert_eq!(e["gone"], true, "{e}");+ assert_eq!(v.bodies(), 1);+ assert_eq!(v.take_gone(), serde_json::json!([[b, "carved"]]));+ assert!(v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "paint", "material": 1, "box": [0, 0, 0, 1, 1, 1] }))).is_err());+ }++ /// The review of #25: adds that would make a body huge or far-flung are refused before anything changes (grid,+ /// collider and mass stay as they were); a body grows to `MAX_BODY_CELLS` and no further; a body is never left+ /// without its collider; redraws let their old geometries go (the level's edits too); a material outside the+ /// palette is refused.+ #[test]+ fn a_body_is_not_grown_too_large_or_too_far() {+ let (mut w, mut ph, mut v) = one_body();+ let (k, b) = v.bodies.iter().map(|(&k, b)| (k, b.body)).next().unwrap();+ let cells = |v: &VoxelWorld, ph: &Option<PhysicsWorld>| (v.bodies[&k].grid.count(), ph.as_ref().unwrap().bridge_ref().engine_voxels(v.bodies[&k].collider));+ let at = p_pose(&ph, b);+ let before = cells(&v, &ph);+ // Far: 120 m out on every axis (it took 2.4 GB), 2e8 m out on one (it ran out of memory), 101 km (past the+ // physics' cell range: the mesh had the cells, the collider not).+ for far in [[120.0f32, 120.0, 120.0], [2e8, 0.0, 0.0], [101_000.0, 0.0, 0.0]] {+ let c = [at[0] + far[0], at[1] + far[1], at[2] + far[2]];+ let t = Instant::now();+ let e = v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "add", "material": 1, "box": [c[0], c[1], c[2], c[0] + 0.3, c[1] + 0.3, c[2] + 0.3] })));+ assert!(e.is_err(), "{far:?}: {e:?}");+ assert!(t.elapsed().as_millis() < 50, "{far:?}: refused after {} ms", t.elapsed().as_millis());+ assert_eq!(cells(&v, &ph), before, "{far:?}: nothing changed");+ }+ // A material the palette does not have.+ assert!(v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "paint", "material": 255, "box": [0, 0, 0, 9, 9, 9] }))).is_err());+ // Grown by adds of 64,000 voxels next to it, again and again: refused at `MAX_BODY_CELLS`, collider and grid+ // alike all the way.+ let mut x = at[0] + 0.4;+ let (mut grown, mut refused) = (0, false);+ for _ in 0..40 {+ match v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "add", "material": 1, "box": [x, at[1], at[2], x + 3.99, at[1] + 3.99, at[2] + 3.99] }))) {+ Ok(e) => grown += e["voxels"].as_u64().unwrap(),+ Err(e) => {+ assert!(format!("{e}").contains("at most"), "{e}");+ refused = true;+ break;+ }+ }+ x += 4.0;+ let (g, c) = cells(&v, &ph);+ assert_eq!(Some(g), c, "grid and collider");+ }+ assert!(refused && v.bodies[&k].grid.count() <= MAX_BODY_CELLS, "{grown} grown, {} cells", v.bodies[&k].grid.count());+ // Its redraws let their geometries go: 200 paints back and forth leave the world's geometries as they were.+ let geometries = w.geometries.len() + w.proc_geometries.len();+ for n in 0..200 {+ v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "paint", "material": 1 + (n % 2), "box": [at[0] - 1.0, at[1] - 1.0, at[2] - 1.0, at[0] + 1.0, at[1] + 4.0, at[2] + 1.0] }))).unwrap();+ }+ assert!(w.geometries.len() + w.proc_geometries.len() <= geometries + 2, "{} geometries for {geometries}", w.geometries.len());+ // And so do the level's edits: 200 small pits in the slab.+ let geometries = w.geometries.len();+ for n in 0..200 {+ let x = 0.3 + (n % 20) as f32 * 0.25;+ v.edit(&mut w, &mut ph, &op(serde_json::json!({ "op": "carve", "sphere": [x, 0.4, 0.3 + (n / 20) as f32 * 0.25, 0.08] }))).unwrap();+ }+ assert!(w.geometries.len() <= geometries + 4, "{} geometries for {geometries}", w.geometries.len());+ }++ /// Contacts of a listening body: a start once per pair, even when an edit takes its collider out and puts it back;+ /// an end when the body goes (the world's own end of a collider it no longer has was lost).+ #[test]+ fn a_bodys_contacts_start_once_and_end_when_it_goes() {+ let (mut w, mut ph, mut v) = one_body();+ let b = *v.bodies.values().map(|x| &x.body).next().unwrap();+ v.body_contacts(&mut ph, b, true).unwrap();+ let mut take = |ph: &mut Option<PhysicsWorld>, w: &mut World| ph.as_mut().unwrap().call(w, "contacts", &serde_json::json!({})).unwrap().as_array().unwrap().iter().filter(|c| c["bodyA"].as_u64() == Some(b as u64) || c["bodyB"].as_u64() == Some(b as u64)).map(|c| c["started"].as_bool().unwrap()).collect::<Vec<_>>();+ let step = |n: usize, v: &mut VoxelWorld, w: &mut World, ph: &mut Option<PhysicsWorld>| (0..n).for_each(|_| { crate::api::physics_advance(ph, v, w, 1.0 / 60.0); });+ ph.as_mut().unwrap().call(&mut w, "velocity", &serde_json::json!({ "body": b, "linvel": [0, 2, 0] })).unwrap();+ step(90, &mut v, &mut w, &mut ph);+ let landed = take(&mut ph, &mut w);+ assert!(landed.contains(&true), "it landed: {landed:?}");+ // Resting on the stump, a voxel added and one carved (each takes its collider out and puts it back): no start again.+ let at = p_pose(&ph, b);+ v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "add", "material": 1, "box": [at[0] + 0.41, at[1] + 1.0, at[2] + 0.1, at[0] + 0.49, at[1] + 1.08, at[2] + 0.18] }))).unwrap();+ v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "carve", "box": [at[0] + 0.41, at[1] + 1.0, at[2] + 0.1, at[0] + 0.49, at[1] + 1.08, at[2] + 0.18] }))).unwrap();+ step(30, &mut v, &mut w, &mut ph);+ let edited = take(&mut ph, &mut w);+ assert!(!edited.contains(&true), "no second start: {edited:?}");+ // Carved away whole: its contacts end.+ v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "carve", "box": [at[0] - 1.0, at[1] - 1.0, at[2] - 1.0, at[0] + 2.0, at[1] + 4.0, at[2] + 2.0] }))).unwrap();+ assert_eq!(v.bodies(), 0);+ let gone = take(&mut ph, &mut w);+ assert!(!gone.is_empty() && gone.iter().all(|s| !s), "its contacts end: {gone:?}");+ }++ /// 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();+ 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);+ v.palette.push(0);+ v.density.push(8000.0);+ 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);+ (w, ph, v)+ }++ /// A body of two densities weighed cell by cell is what parry itself makes of the same cubes (each a cuboid of its+ /// density, placed, summed): mass, centre of mass and principal inertia.+ #[test]+ fn a_body_of_two_densities_weighs_what_parry_says() {+ use physics_core::rapier3d::parry::{mass_properties::MassProperties, math::{Pose, Vector}};+ let (mut w, mut ph, mut v) = one_body();+ let (k, b) = v.bodies.iter().map(|(&k, b)| (k, b.body)).next().unwrap();+ // One side of the bar dense (8,000 kg/m³), the rest 1,000: an off-centre, non-diagonal case.+ let at = p_pose(&ph, b);+ v.edit_body(&mut w, &mut ph, b, &op(serde_json::json!({ "op": "paint", "material": 2, "box": [at[0] - 1.0, at[1] - 1.0, at[2] - 1.0, at[0] + 0.15, at[1] + 1.2, at[2] + 0.15] }))).unwrap();+ let grid = &v.bodies[&k].grid;+ assert!(grid.voxels().any(|(_, m)| m == 2) && grid.voxels().any(|(_, m)| m == 1));+ let s = v.size;+ let parry = grid.voxels().fold(MassProperties::default(), |acc, (g, m)| {+ let c = MassProperties::from_cuboid(v.density[m as usize], Vector::splat(s / 2.0));+ acc + c.transform_by(&Pose::from_translation(Vector::new((g[0] as f32 + 0.5) * s, (g[1] as f32 + 0.5) * s, (g[2] as f32 + 0.5) * s)))+ });+ let (mass, com, inertia) = ph.as_ref().unwrap().bridge_ref().engine_mass_properties(b).unwrap();+ let (pc, pi) = (parry.local_com, parry.principal_inertia());+ let rel = |a: f32, b: f32| (a - b).abs() / b.abs().max(1e-6);+ assert!(rel(mass, parry.mass()) < 1e-5, "mass {mass} for parry's {}", parry.mass());+ assert!((Vector::from(com) - pc).length() < 1e-5, "centre of mass {com:?} for parry's {pc:?}");+ let (mut ours, mut theirs) = (inertia, [pi.x, pi.y, pi.z]);+ ours.sort_by(f32::total_cmp);+ theirs.sort_by(f32::total_cmp);+ assert!((0..3).all(|a| rel(ours[a], theirs[a]) < 1e-4), "principal inertia {ours:?} for parry's {theirs:?}");+ }++ fn p_pose(ph: &Option<PhysicsWorld>, body: u32) -> [f32; 3] {+ ph.as_ref().unwrap().bridge_ref().engine_pose(body).unwrap().0+ }+/// What scene code asks of a level before it is loaded is kept, and counted: past `MAX_QUEUED` an edit or a frame/// is refused (the review of #24: a setup looping on edits grew the queue without bound, outside the script/// engine's memory limit).diff --git a/renderer/src/world.rs b/renderer/src/world.rsindex e99c4f1..c0f7461 100644--- a/renderer/src/world.rs+++ b/renderer/src/world.rs@@ -881,6 +881,21 @@ impl World {}/// Removes an object and its descendants. Returns their ids (those it had: the bodies that drove them go too).+ /// A geometry (triangles or procedural) no object uses any more, let go (the voxel engine's, when it draws a part+ /// again in new objects: the old objects' geometries would otherwise stay for good). One an object still uses is+ /// kept. Returns whether it went.+ pub fn drop_geometry(&mut self, id: u32) -> bool {+ let used = self.objects.values().any(|o| match &o.kind {+ Kind::Mesh { geometry, .. } | Kind::Procedural { geometry, .. } | Kind::Instanced { geometry, .. } => *geometry == id,+ _ => false,+ });+ if used {+ return false;+ }+ self.changes.geometries.remove(&id);+ self.geometries.remove(&id).is_some() | self.proc_geometries.remove(&id).is_some()+ }+pub fn remove(&mut self, id: u32) -> Vec<u32> {let mut doomed = vec![id];let mut k = 0;diff --git a/renderer/voxel-core/src/fixed.rs b/renderer/voxel-core/src/fixed.rsindex 481baf0..9da0df9 100644--- a/renderer/voxel-core/src/fixed.rs+++ b/renderer/voxel-core/src/fixed.rs@@ -42,8 +42,9 @@ impl Shape {Shape::Capsule { a, b, r } => Shape::Capsule { a, b, r: r.clamp(0, cap) },};let (lo, hi) = s.cells();- let n: i64 = (0..3).map(|k| (hi[k] as i64 - lo[k] as i64 + 1).max(0)).product();- (n <= MAX_CELLS).then_some(s)+ // (In i128: three sides of up to 2^23 cells are 2^69, which an i64 wraps to 0.)+ let n: i128 = (0..3).map(|k| (hi[k] as i128 - lo[k] as i128 + 1).max(0)).product();+ (n <= MAX_CELLS as i128).then_some(s)}/// The world cells that can hold a centre inside (inclusive on both ends), at the full radius.@@ -138,6 +139,9 @@ mod tests {#[test]fn edits_are_bounded() {assert_eq!(Shape::Sphere { c: [0; 3], r: i32::MAX }.checked(), Some(Shape::Sphere { c: [0; 3], r: MAX_RADIUS * FP }));+ // The largest box there is (every corner clamped by `to_fp`): 2^69 cells, refused, not wrapped to 0.+ let (a, b) = (to_fp(-1e30), to_fp(1e30));+ assert_eq!(Shape::Box { lo: [a; 3], hi: [b; 3] }.checked(), None);assert_eq!(Shape::Box { lo: [0; 3], hi: [to_fp(600.0); 3] }.checked(), None);assert_eq!(to_fp(f64::NAN), 0);assert_eq!(to_fp(1e30), 1 << 30);diff --git a/renderer/web/src/lib.rs b/renderer/web/src/lib.rsindex dc24a33..cab834c 100644--- a/renderer/web/src/lib.rs+++ b/renderer/web/src/lib.rs@@ -116,6 +116,25 @@ pub fn voxel_bodies() -> String {engine(|e| api::voxel_bodies(&e.voxels, &e.physics))}+/// One voxel body's edit (`api::voxel_body_edit`).+#[wasm_bindgen(js_name = voxelBodyEdit)]+pub fn voxel_body_edit(body: f64, d: &str) -> Result<String, JsValue> {+ let d = desc("voxelBodyEdit", d)?;+ engine(|e| api::voxel_body_edit(&mut e.voxels, &mut e.world, &mut e.physics, body, &d)).map_err(thrown)+}++/// A voxel body's contacts on or off (`api::voxel_contacts`).+#[wasm_bindgen(js_name = voxelContacts)]+pub fn voxel_contacts(body: f64, on: bool) -> Result<(), JsValue> {+ engine(|e| api::voxel_contacts(&mut e.voxels, &mut e.physics, body, on)).map_err(thrown)+}++/// The voxel bodies gone since the last call (`api::voxel_gone`).+#[wasm_bindgen(js_name = voxelGone)]+pub fn voxel_gone() -> String {+ engine(|e| api::voxel_gone(&mut e.voxels))+}+#[wasm_bindgen(js_name = voxelHash)]pub fn voxel_hash() -> String {engine(|e| api::voxel_hash(&e.voxels))diff --git a/renderer/web/www/engine.ts b/renderer/web/www/engine.tsindex 813d834..ef9535b 100644--- a/renderer/web/www/engine.ts+++ b/renderer/web/www/engine.ts@@ -15,6 +15,9 @@ export interface EngineExports {voxelHash(): string;voxelDebris(): Float32Array;voxelBodies(): string;+ voxelBodyEdit(body: number, d: string): string;+ voxelContacts(body: number, on: boolean): void;+ voxelGone(): string;voxelFrame(dt: number): string;geometry(id: number, p: Float32Array, n: Float32Array, uv: Float32Array, idx: Uint32Array, groups?: Uint32Array | null, colors?: Float32Array | null): void;texture(id: number, d: string, data?: Uint8Array | null): void;@@ -54,6 +57,9 @@ export interface VoxelCalls {voxelDebris(): Float32Array;voxelHash(): string;voxelBodies(): string;+ voxelBodyEdit(body: number, d: object): string;+ voxelContacts(body: number, on: boolean): void;+ voxelGone(): string;}export type WebEngine = Engine & VoxelCalls & { physicsPoses(): Float32Array };@@ -71,6 +77,9 @@ export function webEngine(w: EngineExports): WebEngine {voxelHash: () => w.voxelHash(),voxelDebris: () => w.voxelDebris(),voxelBodies: () => w.voxelBodies(),+ voxelBodyEdit: (body, d) => w.voxelBodyEdit(body, json(d)),+ voxelContacts: (body, on) => w.voxelContacts(body, on),+ voxelGone: () => w.voxelGone(),voxelFrame: (dt) => w.voxelFrame(dt),geometry: (id, p, n, uv, idx, groups, colors) => w.geometry(id, p, n, uv, idx, groups, colors),texture: (id, d, data) => w.texture(id, json(d), data),diff --git a/tests/render/voxel-body-gone.ts b/tests/render/voxel-body-gone.tsnew file mode 100644index 0000000..6fbc269--- /dev/null+++ b/tests/render/voxel-body-gone.ts@@ -0,0 +1,60 @@+// A voxel body held by scene code and carved away by an edit of the level (ROADMAP § 6 step 10 a; the review of #25):+// on the real engine, through `@threert/voxel`. voxel/cut-body-live's cut; once the loose part stands on the stump the+// frame script takes its object, carves it away whole with a level edit (`voxelCarve`), and then calls everything an+// object has on it: none may throw (a gone body's calls do nothing), and it must be `gone` with reason "carved". Only+// if all of that holds does the script add a glowing block (palette entry 2, 5 nits) left of the posts, standing on the+// slab; the test reads that block. Anything that throws or is not as said leaves the place dark: 0 for 5.+import { defineGame } from "@threert/gameplay";+import { Vector3 } from "@threert/scene";+import { voxelAdd, voxelBodies, voxelBody, voxelCarve } from "@threert/voxel";+import { camera, result, sceneWithSky, type Region, type TestMeta } from "./lib.ts";+import { test as base } from "./voxel-cut-body.ts";+import { cut, level } from "./voxel-cut-falls.ts";++/** The block's place in the image (x -0.7 .. -0.5 m, y 0.4 .. 1.0 m; the camera of voxel/cut-falls): at 160 x 90 its+ * three columns of pixels. */+const BLOCK: Region = [0.4135, 0.75, 0.428, 0.85];++export const test: TestMeta = {+ ...base, id: "voxel/body-gone", temporal: true, time: undefined, live: 200,+ metric: { kind: "radiance", region: BLOCK, expected: 5, tolerance: 0.05 },+ note: "as voxel/cut-body-live; at frame 90 the part's object is carved away by a level edit, every call on it must do nothing, then a glowing block is added",+};++let frames = 0;+export default defineGame<Record<string, never>>({+ state: {},+ setup: () => {+ frames = 0;+ const 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 !== 90) return;+ const part = voxelBodies()[0];+ if (!part || part.gone) return;+ const id = part.body;+ // The part rests on the stump (from 0.8 m up); the stump's top cell's centre is at 0.75 m, outside this box.+ voxelCarve({ box: [-0.6, 0.81, -0.6, 0.6, 4.0, 0.6] });+ try {+ part.applyImpulse(new Vector3(0, 10, 0));+ part.setLinearVelocity(new Vector3(1, 0, 0));+ void part.position.x;+ void part.getLinearVelocity().y;+ void part.sleeping;+ part.addEventListener("contactstart", () => {});+ part.paint({ sphere: [0, 1, 0, 1] }, 1);+ part.addVoxels({ box: [0, 1, 0, 0.2, 1.2, 0.2] }, 1);+ part.carve({ box: [-1, 0, -1, 1, 4, 1] });+ } catch {+ return;+ }+ if (!part.gone || part.goneReason !== "carved" || part.physics !== null || voxelBody(id) !== undefined) return;+ voxelAdd({ box: [-0.7, 0.4, -0.1, -0.5, 1.0, 0.1] }, 2);+ },+ handlers: {},+});diff --git a/tests/render/voxel-cut-body-push.ts b/tests/render/voxel-cut-body-push.tsindex 66c54d5..4b8aed7 100644--- a/tests/render/voxel-cut-body-push.ts+++ b/tests/render/voxel-cut-body-push.ts@@ -1,14 +1,14 @@-// What a ray gives scene code is enough to act on a voxel body (ROADMAP § 6 step 8): voxel/cut-body-live's cut, and-// once the loose part stands on the stump the frame script casts two rays at the physics world. One straight down-// at the slab: a hit on the voxel level, whose `object` is `engineColliders` (no scene object: its `physics` is-// null) and which has no `body` (the level is fixed). One from the camera's side at the part: the same `object`,-// and a `body`, the id `voxelBodies()` lists. That id goes into `voxelImpulse`, sideways: the part is thrown off-// the stump. So where the part stood (y 2.9 .. 3.2) reads 0 against the stump, which is the level's and stays+// What a ray gives scene code is enough to act on a voxel body (ROADMAP § 6 step 8; step 10: as an object):+// voxel/cut-body-live's cut, and once the loose part stands on the stump the frame script casts two rays at the+// physics world. One straight down at the slab: a hit on the voxel level, whose `object` is `engineColliders` (no+// scene object: its `physics` is null) and which has no `body` (the level is fixed). One from the camera's side at+// the part: its `object` is the part's `VoxelBody`, the one `voxelBodies()` lists, and `hit.object.applyImpulse`+// throws it sideways off the stump. So where the part stood (y 2.9 .. 3.2) reads 0 against the stump, which is the level's and stays// (y 0.45 .. 0.75, 5 nits). A ray that does not report the level or the body as said, or an impulse that does not// move the part, leaves the part standing: the ratio is 1.import { engineColliders, Raycaster, Vector3 } from "@threert/scene";import { defineGame } from "@threert/gameplay";-import { voxelBodies, voxelImpulse } from "@threert/voxel";+import { voxelBodies, VoxelBody } from "@threert/voxel";import { camera, result, sceneWithSky, type Region, type TestMeta } from "./lib.ts";import { test as base } from "./voxel-cut-body.ts";import { BELOW, cut, level } from "./voxel-cut-falls.ts";@@ -18,7 +18,7 @@ const STUMP: Region = [0.485, 0.795, 0.515, 0.855];export const test: TestMeta = {...base, id: "voxel/cut-body-push", temporal: true, time: undefined, live: 240,metric: { kind: "ratio", a: BELOW, b: STUMP, expected: 0, tolerance: 0.02 },- note: "as voxel/cut-body-live; at frame 90 a ray's hit names the body and voxelImpulse throws it off the stump",+ note: "as voxel/cut-body-live; at frame 90 a ray's hit has the part's object, and its applyImpulse throws it off the stump",};let frames = 0;@@ -38,11 +38,12 @@ export default defineGame<Record<string, never>>({// The level (the slab is 1.6 m square about the origin): fixed, no scene object, no body.const ground = new Raycaster(new Vector3(0.55, 5, 0.55), new Vector3(0, -1, 0)).intersectPhysics()[0];if (!ground || ground.object !== engineColliders || ground.object.physics !== null || ground.body !== undefined || ground.collider === undefined) return;- // The part: a body, the one the level lists.+ // The part: its object, the one the level lists.const hit = new Raycaster(new Vector3(0.05, 2.05, 5), new Vector3(0, 0, -1)).intersectPhysics()[0];- if (!hit || hit.object !== engineColliders || hit.body === undefined || !voxelBodies().some((b) => b.body === hit.body)) return;+ const part = hit?.object;+ if (!(part instanceof VoxelBody) || part.body !== hit.body || !voxelBodies().includes(part)) return;// 416 voxels of 900 kg/m³: 374 kg; 1,500 N s is 4 m/s sideways.- voxelImpulse(hit.body, [1500, 300, 0]);+ part.applyImpulse(new Vector3(1500, 300, 0));},handlers: {},});