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
Fire and smoke (ROADMAP § 6 step 10 b): the Explosions pool, the fire light measured (#29)
Yujia99d86e891c46
diff --git a/docs/MATERIAL_FUNCTIONS.md b/docs/MATERIAL_FUNCTIONS.mdindex 9c4d3b4..977edf6 100644--- a/docs/MATERIAL_FUNCTIONS.md+++ b/docs/MATERIAL_FUNCTIONS.md@@ -463,7 +463,8 @@ Layer A:- `volume/grid-smoke`: `SimulatedSmoke`'s puff rises (a regression value).Not done: collision of the smoke with scene geometry or voxels; grids in sphere volumes; reflection, GI and shadow-rays through grid media live (as for every medium but the homogeneous ones).+rays through grid media live (as for every medium but the homogeneous ones). A live rebuild (any structural change) starts every+simulated grid again from its data: the smoke there vanishes (ROADMAP § 6 step 10 b, Open).### Waterdiff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex d4497d4..acc13c6 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -4310,8 +4310,45 @@ benchmark level. The order follows the dependencies; a step that meets a furthera 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 thebenchmark 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.+ - **(b) Fire and smoke** (branch `explosion-fire`; design `out/web-probe/step10/b-design.md`; docs/VOXEL.md "Fire+ and smoke"). The user's scope (2026-11-12): an explosion's fireball and smoke, on the existing volume and particle+ paths. `Explosions` (`packages/voxel`): a pool of fireballs (each cooling to its own dark smoke) and a pool of+ point lights made in setup; `fire` / `explode` / `step` / `dispose`. No smoke grid: its box is a volume, a+ fireball in it would overlap it, and volumes must not overlap (`Explosions` refuses one; the destruction game's+ `-fire` variant is fireballs only, `-smoke` unchanged). Caps on fireballs (32) and lights (8), with what happens+ past each; every number checked before anything changes. No engine call of its own, so nothing new for+ `physics_fuzz` (`voxelExplode` is in its set already). The scene sync checks grid sources and `customData` only,+ not transforms or lights: `Explosions` checks everything it sends. `scene::build` refuses a scene with more than+ 32 volumes shown (the kernel's 32-bit mask; the 33rd was not drawn, silently). The stand-in light's table+ `FIRE_LIGHT`, measured against offline (`tools/bench-voxel-fire.ts`); `voxel/fire-light` 0.987 for 1.+ - Measured at render scale 0.75 against offline (docs/VOXEL.md): the whole image meets ΔE ≤ 3 / SSIM ≥ 0.9 at+ 0.2 s (2.11 / 0.949), not at 1.0 s (3.53 / 0.876); the street meets at every age; the fireball itself not (ΔE+ 4.4-6.9): half the live march's own picture (held: 2.8-4.3), half the temporal filter. With a smoke grid around+ the fireballs (the first `-fire`) the fire was not seen at all at 0.2 and 0.5 s (its region ΔE 19.9, 9.4): kept+ in the docs as the evidence for the rule. The fire burning in the grid instead was tried and set aside+ (coverage, one to four cells for a small fire, every cell every frame, no offline reference).+ - Found on the way and fixed: each pool object's first move promoted it to movable with a rebuild (281 ms, and+ it wiped the live smoke); idle lights had unbounded reach (0.9 ms of GPU with nothing burning).+ - The independent review of #29 found, fixed here with tests: the fireballs sat inside the smoke box and the+ puff hid them whole (no grid now); 32 fireballs and the grid were 33 volumes, the 33rd never drawn; finite+ positions past f32 passed the check; options went unchecked to the engine; the puffs' cap was per distinct+ time and they piled up out of a scene (no puffs now); a new fire at age 0 took a light from an older one; time+ going back left fires to burn again later; a fire waiting to start was taken over uncounted; the pool's+ objects lived in the group's space; no `dispose`.+ - Temporary ways round the shared renderer, in `Explosions` until the shared paths are fixed (the user and the+ supervisor, 2026-11-12; docs/VOXEL.md "Temporary ways round on the engine's shared paths", with each one's+ cause, side effects, and when and how to take it out; this line's worker takes them out in a PR of its own once+ the shared paths are fixed): the stand-in light (live rays have no media code: offline it counts the fire's+ light twice unless `lights: 0`, live it lights the fireball a second time); idle objects parked far away+ (hiding a volume rebuilds); idle lights reaching 1 mm (a black rangeless light reaches without limit); the+ fire's history capped by its light's change (the temporal filter has no "this medium changes" signal: a fire+ without a light ghosts); the smoke kept by never rebuilding (a rebuild loses a grid's simulation); and volumes+ that must not overlap (`media_track` / `media_march` take media whole in entry order: no smoke grid around+ explosions, and two fires close together still overlap).+ - Open, the user's scope of 2026-11-12: **fire spreading along burnable voxels**, and **smoke stopped by+ voxels**, are not done.+ - Open: the live march's media are lighter and more see-through than offline (8 steps; in-scattering isotropic+ from the cache): the fireball reads lighter than offline.- (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.diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex a8a129c..283cbce 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -226,7 +226,9 @@ crate.position.set(0, 5, 0); // a write moves the body therehello world's test for something fixed, `hit.object.physics?.type === "fixed"`, does not find the level: it is`hit.object === engineColliders`. A level that collides is in the physics world, and the queries ask it, whether ornot any scene object has `physics`; contacts with it reach a body's listeners with `other: engineColliders`.- `voxelImpulse(body, impulse, point?)` (step 8's call by id) is kept, deprecated. A voxel shape's limits: cells of 1 cm to 100 m, at most 2^24+ `voxelImpulse(body, impulse, point?)` (step 8's call by id) is kept, deprecated. An explosion's fire and smoke are+ `Explosions` (`packages/voxel`, step 10 b; docs/VOXEL.md "Fire and smoke"): scene objects pooled in setup, no engine+ call of their own. A voxel shape's limits: cells of 1 cm to 100 m, at most 2^24cells, each within 2^20 cells and 100 km of the shape's origin.- 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 d8f8bde..25e367b 100644--- a/docs/VOXEL.md+++ b/docs/VOXEL.md@@ -552,6 +552,145 @@ it too (the level itself stays `engineColliders`).mass, centre of mass and inertia are the sum of its cells, each a cube of its palette entry's density (the collidercarries none). Step 8's `voxelImpulse` is kept, deprecated.+### Fire and smoke (ROADMAP § 6 step 10 b; design: `out/web-probe/step10/b-design.md`)++An explosion's fireball and smoke, on the existing volume and particle paths (the user's scope, 2026-11-12: no fire+spreading along burnable voxels, no smoke stopped by voxels). `Explosions` (`@threert/voxel`) is a group made once in+setup: a pool of fireballs (`Fireball`) and a pool of point lights. It adds no engine call. **The smoke is each+fireball's own**: it cools to dark smoke over its life. `Explosions` takes no smoke grid (it throws if given one): the+grid's box is a volume, a fireball in it would overlap it, and volumes must not overlap (the media are taken whole,+in the order a ray enters them; why, below, "Why volumes must not overlap"). A game may keep its own `SimulatedSmoke`+where nothing blows up.++```ts+const boom = new Explosions();+scene.add(boom);+// frame(f):+boom.explode(x, y, z, 4, f.time); // voxelExplode, then fire([x, y, z], 4, f.time)+boom.step(f.time); // once a frame: lights follow their fireballs, burnt-out ones parked+```++Positions are the world's: the group stays at the origin, unrotated, unscaled (a fire throws otherwise). `dispose()`+takes the pool out of the scene for good.++- **A fire** (`fire(at, r, time)`): the next fireball of the pool, 2.2 r across (5 cm to 40 m), its centre 0.3 r above+ the explosion's point, from `time` (now or later); a light at its centre while it burns, from the first step after+ it starts (at age 0 it gives none, and takes no light from an older fire). Time going back (a restart) ends every+ fire. Two fires close together make two fireballs that overlap: the engine cannot draw that rightly yet (the sixth+ temporary way round below; nothing in `Explosions` keeps them apart). The fireball's default peak is 30,000 nits (a+ flame's; `Fireball`'s own 40 is a stylised night's and does not show by day). Every object of the pool is made in+ setup and `movable`: firing moves them in place (a fixed object's first move rebuilds the live scene once: 281 ms on+ the benchmark level, and every pool member would do it once).+- **Why a light**: live, GI, reflection and shadow rays do not see media (MATERIAL_FUNCTIONS.md, live media), so a+ fireball's emission lights nothing around it; offline it does. The light stands in: its intensity and colour over+ the fireball's life come from `FIRE_LIGHT`, measured against the offline renderer (`tools/bench-voxel-fire.ts --only+ calibrate`: fireballs of 1.1, 2.2, 4.4 and 8.8 m at 12 ages over a floor and a wall, against a 1,000 cd light; floor+ and wall agree within about 10 %). It is not one curve scaled by size²: a larger fireball's hot core lies under more+ of its own smoke, so its light falls sooner (at half its life 0.0090 cd per m² of size² per nit at 2.2 m, 0.0020 at+ 8.8 m). `voxel/fire-light` checks it in the renderer: the fire light alone gives a floor 0.987 of what the fireball's+ own emission gives it. The light, the parking of idle objects and the rest are temporary ways round the shared live renderer (the table+ below, "Temporary ways round on the engine's shared paths").++Caps, and what happens past them (node tests in `packages/voxel/test/explosions.test.ts`):++| what | cap | past it |+| --- | --- | --- |+| fireballs | `fireballs`, default 8, at most 32 (`MAX_FIREBALLS`): the kernel draws at most 32 volumes (`MAX_MEDIA`; a scene with more is refused by `scene::build`, no longer drawn without the last) | the oldest burning or waiting one is taken over: it ends early, the new one starts (`stats.reused`) |+| fire lights | `lights`, default min(fireballs, 8), at most 8 (`MAX_FIRE_LIGHTS`: the kernel evaluates up to 8 shadowed local lights exactly, `RIS_EXACT`) | the youngest fires have them; the rest burn without (`stats.unlit`: the most at once) |+| fireball size | 40 m (`MAX_FIREBALL`: r over about 18 m) | the largest; `voxelExplode` keeps its own limits |++Arguments: every number is checked before anything changes, since the scene sync checks only grid sources and+`customData` (not transforms or lights): a position outside ±1,000 km (finite numbers past f32 included) or not three+finite numbers, a radius not finite or not above 0, a time outside ±1e9 s, or the pool moved off the world's frame,+throws a `RangeError` from `fire`, `explode` (before its voxel call) and `step`; a huge radius (1e30) gives the largest+fireball, a tiny one (1e-46) the smallest; the constructor checks every option (ranges in the code; `intensity: 1e308`, `life: 61`, a+smoke grid are refused). 1,000 fires in one frame, at one time or 1 µs apart, make no object (the pool cycles; the+last 8 burn). An idle light has a reach of 1 mm where+it is parked (a distance of 0 is unbounded reach: the sphere of its group of 16 lights held every pixel, 0.9 ms of GPU+with nothing burning).++**Offline, the fire's light counts twice unless the game passes `lights: 0`**: an offline path reaches the+fire's emission, and the stand-in light is there as well. The bench's references are made with `lights: 0`+(`fireShot({ light: false })`); `level-destruction-fire` rendered offline has both. Live, surfaces see only the light+(their rays have no media code).++#### Measured: fire and smoke on the benchmark level (2026-11-12)++`tools/bench-voxel-fire.ts` (games/voxel-level/level-fire.game.ts): the 4 m explosion at the destruction game's+`crater` spot, by day (fireballs, no grid), the live frame at render scale 0.75 (never 1: at exactly 1 the live frame has no edge+anti-aliasing), 1280 x 720, lockstep at 60 fps from the start, against our offline render of the same scene time+(2,048 spp, no clamps, no denoiser; 1,024 against 2,048 spp: ΔE 0.40, SSIM 0.993), which has the fireball's own light+and no fire light. Live in lockstep is bit-reproducible (A/A ΔE 0.00). Targets ΔE ≤ 3, SSIM ≥ 0.9.++| after the fire starts | whole image ΔE / SSIM | the fireball (its box) ΔE / p99 / SSIM / luminance | the street below it ΔE / SSIM / luminance |+| --- | --- | --- | --- |+| 0.2 s | **2.11 / 0.949** | 6.90 / 31 / 0.846 / 1.02 | **1.38 / 0.960** / 1.00 |+| 0.5 s | 3.08 / 0.930 | 6.61 / 31 / 0.850 / 1.22 | **1.00 / 0.978** / 1.03 |+| 1.0 s | 3.53 / 0.876 | 4.36 / 28 / 0.839 / 1.09 | (the fireball's box reaches the image's foot) |++Where it falls short, and why:+- **The fireball** misses at every age. Half of it is the live media's own picture: the same moment held (time all+ but stopped, 120 frames) against offline reads ΔE 3.78 / 4.28 / 2.80, SSIM 0.908 / 0.894 / 0.911: the live view+ marches 8 steps through a fireball whose noise is finer than that, and lights it from the radiance cache's voxels+ (isotropic); its cooled smoke reads lighter and more see-through than offline. The other half is the temporal+ filter: the real-time frame against the held one, ΔE 5.92 / 3.96 / 2.45. The filter does not know a procedural+ medium changes with time, so it keeps the hotter fireball of the frames before (luminance 1.22 of offline at 0.5 s).+ The fire light's change each frame caps the history (live.rs `lit_changed`): without the light the fireball reads+ ΔE 11.2 / 9.9 / 9.5 and luminance 0.95 / 1.40 / 1.46. By day the light changes the street little (its luminance+ 0.98 → 1.00 of offline at 0.2 s).+- **The whole image** meets at 0.2 s, is 0.08 over in ΔE at 0.5 s (SSIM met), and misses at 1.0 s (the fireball's box now spans+ the image's height, its smoke over the top cells). The p99 of about 21 everywhere is the level's own at 0.75+ (foliage), not the fire's.+++#### Why volumes must not overlap (measured 2026-11-12, kept as the evidence)++The first `-fire` had the fireballs inside the smoke grid's box and puffed hot smoke at each fireball's centre. Live+and offline both take the media whole in the order a ray enters them: the smoke box first, so each fireball was drawn+behind all the smoke on that ray. With the grid (fire at 0 s offline, at 2 s live, the same age;+`out/voxel-fire/sheet-grid-vs-none.jpg`) the fire was not seen at all at 0.2 and 0.5 s, offline or live:++| after the fire starts | the fireball's region, no grid: ΔE / SSIM / luminance | with the grid around it |+| --- | --- | --- |+| 0.2 s | 6.90 / 0.846 / 1.02 | 19.93 / 0.664 / 2.40 |+| 0.5 s | 6.61 / 0.850 / 1.22 | 9.36 / 0.820 / 1.30 |+| 1.0 s | 4.36 / 0.839 / 1.09 | 6.14 / 0.851 / 1.14 |++Burning the fire in the grid instead (hot smoke that flames, one medium; fires in the grid, fireballs outside it) was+tried and set aside, on its measurements (`out/voxel-fire/sheet-gridfire.jpg`): at 0.2 s a large white ball without+detail, at 0.5 and 1 s its region ΔE 17.0 and 10.8 with live 1.5 times offline's luminance (at 1 s offline dark smoke,+live light flecks), against the fireball's 6.9 / 6.6 / 4.4 with a flame's shape; and a grid covers its box only (16 of+the level's 160 wall spots), a small fire is one to four cells, every cell is simulated every frame, and offline has+no reference for a fire that does not start at 0 s (`out/web-probe/step10/b-structure-data.md`). Until the engine+draws overlapping media together (the sixth temporary way round below), the fire stays out of the grid.++Cost: `--only cost`, the destruction game's routes at 0.75, lockstep (frames as fast as the GPU goes), GPU ms p50 over+2 s before and 4 s after the explosion; no rebuild in any run.++| route | before | after | the explosion frame's CPU |+| --- | --- | --- | --- |+| the level (`level-destruction`) | 8.2 | 8.4 | 25.5 |+| with the smoke grid (`-smoke`, 709,632 cells; no fire) | 9.5 | 10.2 | 27.5 |+| with fire (`-fire`: fireballs and their lights, no grid) | 8.5 | 9.0 (10.3-10.6 while it burns, then 8.7) | 25.7 |+| fire, `sustained` (7 a second for 10 s) | 8.6 | 11.8 (p95 12.4, max 12.8); at most 8 burning, 8 lit | |+| fire, `peak` (20 within a second) | 8.8 | 11.3 (max 12.7); 8 burning (the pool) | |+| fire, software traversal (loop guard on: no stop) | 13.0 | 13.7 (max 18.0 while it burns) | 28.9 |++### Temporary ways round on the engine's shared paths++`Explosions` (step 10 b) works round six faults of the shared renderer, in its own code, until they are fixed+there (the user, 2026-11-12: these are temporary; the shared paths are fixed in their own PRs, then these go, in a PR+of their own). Each place in `packages/voxel/src/explosions.ts` points here.++| What | Now | The fault at its source | Known side effects | It can go when | How to tell |+| --- | --- | --- | --- | --- | --- |+| The stand-in light | a point light at each burning fire, its intensity and colour from `FIRE_LIGHT`, measured against offline | live secondary and shadow rays have no media code: `pathtrace.wgsl` `media_shadows()` is false live (line 796), GI and reflection rays never meet a medium | offline the fire's light counts twice unless the game passes `lights: 0` (`level-destruction-fire` rendered offline has both); live, `media_train` adds the light to the radiance cache's voxels (`point_direct`, `point_sphere`): the fireball (and its smoke) is lit by it a second time; the table holds for the defaults (density, life scaled; measured by day over a floor and a wall, the fireball 0.6 of its size above it; past 8.8 m the 8.8 m values) | live rays see media: a medium's emission lights surfaces and shadows pass through it | `lights: 0`, then `tools/bench-voxel-fire.ts --only quality`: the street and the fireball's regions at least as close to offline as with the light; `voxel/fire-light` replaced by a live test of the fire's own light |+| Idle fireballs parked | at y = −10,000, scale 1e-3, instead of hidden | `World::set_visible` (`world.rs` line 750): hiding anything but particles rebuilds the live scene | parked fireballs keep their slots among the kernel's 32 volumes, and every pixel's march still tests their boxes | hiding a volume or a light is done in place | `visible = false` instead of parking; the bench's cost runs report no rebuild after an explosion |+| Idle lights reach 1 mm | an idle light's `distance` is 1 mm where it is parked | `light_reach` (`lib.rs` line 211): a black light without a range reaches without limit, and the kernel does not skip black lights before the group test (`pathtrace.wgsl` line 1578) | parked lights 10 km away share a group of 16 with lit ones, and groups are not sorted again when lights move (`lib.rs` line 277): the group's sphere is about 5 km wide while any fire burns (the per-light range test still works) | black lights reach nothing (or are hidden in place) and moved lights are grouped again | distance 0 on idle lights; the fire route's GPU time before any explosion within 0.1 ms of the smoke route's |+| The fire's history capped by its light | the light's change each frame caps the live view's history | `live.rs` line 1892: any light change caps the whole frame's history at 16; the temporal filter has no "this medium changes" signal (surfaces have `o.animated`) | without a light (`lights: 0`, more fires than lights, a fire at age 0) the fire ghosts: the fireball read ΔE about 10 and 1.4 times offline's luminance; with one, the whole frame's history is capped every frame a fire burns | media carry a "changes with time" signal the temporal pass uses per pixel | `lights: 0`, `--only quality`: the fire's region within its held (converged) value |+| The smoke kept by never rebuilding | the pool's objects movable from the start; idle ones parked, not hidden (`Explosions` has no grid now: this keeps a game's own `SimulatedSmoke`) | `LiveCore::rebuild` (`live.rs` line 3474) → `load_scene` → `Gpu::upload` makes new grid textures (`gpu.rs` line 1664): the simulated state is not carried over | any other structural change in the game (an object added, a texture, an edit's fallback) wipes the smoke and the fire burning in it | a rebuild carries every simulated grid's state over | the bench's smoke check with a rebuild forced at 1 s (an object added): the smoke at 3 s as without it |+| Volumes must not overlap | `Explosions` has no smoke grid (it refuses one); the smoke is each fireball's own. Two fires close together still make two fireballs that overlap: nothing keeps them apart (no distance rule) | `media_track` (offline) and `media_march` (live) in `pathtrace.wgsl` take the media whole, in the order a ray enters them (at most 32, a 32-bit mask), not their coefficients summed along the ray; hence the rule (`core.ts` `VolumeMesh`, MATERIAL_FUNCTIONS.md) | a fire inside smoke is drawn behind all of it (measured: not seen at all at 0.2 and 0.5 s, "Why volumes must not overlap"); neighbouring fireballs hide each other in the same way; no smoke grid around explosions | overlapping media are drawn together: one march summing every medium's coefficients per step along the ray (or a froxel volume), offline and live | puff a `SimulatedSmoke` around fireballs again (`Explosions` taking a grid) and run the comparison that found it (`bench-voxel-fire` at d7b4e4a, `--only smoke --ages 0.2,0.5`): the fire seen in its smoke offline and live; two overlapping fireballs both seen |+### Where the engine works round its dependenciesEach 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 (nodiff --git a/games/voxel-level/level-destruction-fire.game.ts b/games/voxel-level/level-destruction-fire.game.tsnew file mode 100644index 0000000..67fa6f0--- /dev/null+++ b/games/voxel-level/level-destruction-fire.game.ts@@ -0,0 +1,5 @@+// The benchmark level under explosions as triangles, every explosion with its fireball (cooling to its own dark smoke)+// and a light that follows it (ROADMAP § 6 step 10 b; level-destruction.game.ts, `Explosions` in @threert/voxel). No+// smoke grid: its box is a volume, and the fireballs would be in it (volumes must not overlap).+import { destructionGame } from "./level-destruction.game.ts";+export default destructionGame("mesh", 1, false, false, true, undefined, true);diff --git a/games/voxel-level/level-destruction.game.ts b/games/voxel-level/level-destruction.game.tsindex 3451946..9766c7c 100644--- a/games/voxel-level/level-destruction.game.ts+++ b/games/voxel-level/level-destruction.game.ts@@ -27,14 +27,16 @@// thrown out from the explosion, collided with the ground and the level's voxels (its occupancy grid), no CPU work// per particle. With `smoke` (level-destruction-smoke.game.ts; ROADMAP § 6 step 5b), every explosion leaves a puff of// simulated smoke (`SimulatedSmoke`: a density grid over the streets ahead of the camera, advected, diffused and lifted-// on the GPU every frame), which rises and drifts with the wind. Spots alternate between the ground ahead+// on the GPU every frame), which rises and drifts with the wind. With `flames` instead (level-destruction-fire.game.ts;+// ROADMAP § 6 step 10 b), every explosion is `Explosions.explode`: the voxel explosion, a fireball from a pool of 8+// (cooling to its own dark smoke), and a light following it. Spots alternate between the ground ahead// of the camera and the walls of the buildings nearest to it. Each explosion// logs what it did (`explosion {...}`, renderer timings included) for the bench. Sun and sky; the lamps do not glow (at// night they do, and their pieces fly: level-night.game.ts).// node tools/voxel-level/generate.ts --granularity object && node tools/bundle-game.ts games/voxel-level/level-destruction.game.tsimport { BoxGeometry, Color, DirectionalLight, GpuParticles, InstancedMesh, MaterialFunction, Mesh, MeshStandardMaterial, ParticleProgram, SimulatedSmoke, PerspectiveCamera, PlaneGeometry, ProceduralGeometry, ProceduralMesh, Scene, SkyAtmosphere } from "@threert/scene";import { defineGame } from "@threert/gameplay";-import { VOXEL_BRICKS, voxelBodies, voxelCarve, voxelDebris, voxelExplode, voxelFrame, voxelHash, voxelLevel, type VoxelFrame } from "@threert/voxel";+import { Explosions, VOXEL_BRICKS, voxelBodies, voxelCarve, voxelDebris, voxelExplode, voxelFrame, voxelHash, voxelLevel, type VoxelFrame } from "@threert/voxel";import { nativeObjects, nativePalette } from "./native.ts";import { EDGE, PALETTE, SIZE, VOXEL, cameraPath, groundHeight, levelPlan, toScene } from "./plan.ts";@@ -43,7 +45,7 @@ interface State { scenario: Scenario | null; started: number }/** Spots for explosions: alternately on the ground ahead of the camera and on the walls of the buildings nearest it* (deterministic: the k-th spot is always the same). */-function spots(seed: number): [number, number, number][] {+export function spots(seed: number): [number, number, number][] {const plan = levelPlan(seed);const key = cameraPath(seed)[0];const [cx, , cz] = key.pos, [tx, , tz] = key.target;@@ -214,30 +216,35 @@ class Dust {* `smoke`: the cells of the simulated smoke's grid. `physics` (ROADMAP § 6 step 8; on by default): the level* collides and what comes loose is a rigid body, logged every half second while there are any as `bodies {...}`* (how many, how many sleep, the fastest); off, loose parts fall through the lattice as in step 6 and are logged- * per frame as `batch {...}`. `maxBodies`: the level's cap on voxel bodies (300 unless given). */-export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: boolean | "dust" = false, smoke: false | [number, number, number] = false, physics = true, maxBodies?: number) {+ * per frame as `batch {...}`. `maxBodies`: the level's cap on voxel bodies (300 unless given). `flames` (ROADMAP § 6+ * step 10 b): every explosion through `Explosions` (fireball and light); not with `smoke` (volumes must not overlap). */+export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: boolean | "dust" = false, smoke: false | [number, number, number] = false, physics = true, maxBodies?: number, flames = false) {const keys = cameraPath(seed);const at = spots(seed);// The ground points of the eight trees nearest ahead of the camera (`topple`).const [camX, , camZ] = keys[0].pos;const trunks = levelPlan(seed).props.filter((p) => p.kind === "tree").map((p) => toScene(p.x, p.y, p.z)).filter((p) => p[2] > camZ + 4).sort((a, b) => Math.hypot(a[0] - camX, a[2] - camZ) - Math.hypot(b[0] - camX, b[2] - camZ)).slice(0, 8);- let next = 0, fired = 0, frames = 0, last = -1, hadBodies = false;+ let next = 0, fired = 0, frames = 0, last = -1, hadBodies = false, now = 0;const flying = debris === true ? new Debris(seed) : null;const dust = debris === "dust" ? new Dust() : null;// Smoke: a box 22 x 14 x 36 m over the streets ahead of the camera (from 3 m ahead; the level's +z), `smoke` cells// across it, a light wind across the road.+ const [cx, cy, cz] = keys[0].pos;+ // Fireballs and the smoke grid are not both on: the grid's box is a volume, and the fireballs would be in it (volumes+ // must not overlap; docs/VOXEL.md, "Temporary ways round on the engine's shared paths").+ if (flames && smoke) throw new Error("destructionGame: fire and the smoke grid are not both on (volumes must not overlap)");+ const boom = flames ? new Explosions() : null;const cloud = smoke ? new SimulatedSmoke({ size: smoke, density: 2.5, wind: [0.8, 0, 0.3], buoyancy: 3.5, dissipation: 0.2, cooling: 0.9 }) : null;if (cloud) {- const [cx, cy, cz] = keys[0].pos;cloud.position.set(cx, cy + 5, cz + 21);cloud.scale.set(22, 14, 36);}const fire = (r: number, spot?: number) => {const [x, y, z] = at[(spot ?? next++) % at.length];- const e = voxelExplode(x, y, z, r);+ const e = boom ? boom.explode(x, y, z, r, now) : voxelExplode(x, y, z, r);const thrown = flying ? flying.spawn(voxelDebris(), [x, y, z]) : dust ? dust.spawn(voxelDebris(), [x, y, z]) : 0;cloud?.puff([x, y + 0.3 * r, z], 0.8 * r + 0.3, { density: 0.9, temperature: 1, push: 1.2 });- console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r, ...e, ...(flying ? { thrown, debris: flying.live } : dust ? { thrown } : {}) })}`);+ console.log(`explosion ${JSON.stringify({ k: fired++, frame: frames, r, ...e, ...(flying ? { thrown, debris: flying.live } : dust ? { thrown } : {}), ...(boom ? { burning: boom.stats.burning, lit: boom.stats.lit } : {}) })}`);};return defineGame<State>({state: { scenario: null, started: 0 },@@ -269,10 +276,13 @@ export function destructionGame(route: "mesh" | "boxes", seed = 1, debris: booleif (flying) scene.add(flying.mesh);if (dust) scene.add(dust.node);if (cloud) scene.add(cloud);- return { scene, camera, options: { name: `voxel-level-destruction-${route}${debris === true ? "-debris" : debris ? "-dust" : ""}${smoke ? "-smoke" : ""}${physics ? "" : "-lattice"}`, width: 1280, height: 720, preset: "cinematic" as const } };+ if (boom) scene.add(boom);+ return { scene, camera, options: { name: `voxel-level-destruction-${route}${debris === true ? "-debris" : debris ? "-dust" : ""}${smoke ? "-smoke" : ""}${flames ? "-fire" : ""}${physics ? "" : "-lattice"}`, width: 1280, height: 720, preset: "cinematic" as const } };},frame(f) {frames++;+ now = f.time;+ boom?.step(now);flying?.step(f.dt);const b = voxelFrame(f.dt) as VoxelFrame; // (the level is loaded by the first frame)if (b.batches > 0 || (b.settled ?? 0) > 0) console.log(`batch ${JSON.stringify(b)}`);diff --git a/games/voxel-level/level-fire.game.ts b/games/voxel-level/level-fire.game.tsnew file mode 100644index 0000000..f9102e3--- /dev/null+++ b/games/voxel-level/level-fire.game.ts@@ -0,0 +1,135 @@+// One explosion's fire on the benchmark level by day, and a bare room to calibrate the fire light in, for measuring+// them (ROADMAP § 6 step 10 b; tools/bench-voxel-fire.ts). Every frame script here is a function of the scene time, so+// an offline render at a time shows what a live frame at that time does.+//+// fireShot: the level by day from the destruction game's first camera, a 4 m explosion at its `crater` spot (9 m ahead+// on the road; done in setup, so the crater is there from the start in both renders), its fire (`Explosions`) starting+// at scene time `at`: with the fire light or without. Offline, the fire light is left+// out: the fireball's own emission lights the street there (paths reach the medium), which is what the light stands in+// for live.+//+// fireRoom: a grey floor and a wall, no sky; either one fireball of size `size` m burning from scene time 0, high enough+// that the floor is below it, or a white point light of 1,000 cd at its centre. The floor's and the wall's radiance+// near it, fire against light, is the fireball's equivalent intensity (`FIRE_LIGHT`).+import { DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera, PlaneGeometry, PointLight, Scene, SkyAtmosphere } from "@threert/scene";+import { defineGame } from "@threert/gameplay";+import { Explosions, voxelExplode, voxelLevel } from "@threert/voxel";+import { spots } from "./level-destruction.game.ts";+import { nativeObjects, nativePalette } from "./native.ts";+import { EDGE, PALETTE, SIZE, VOXEL, cameraPath } from "./plan.ts";++export interface FireShot {+ /** The fire light (live); off for the offline reference. Default on. */+ light?: boolean;+ /** When the fire starts (scene time, s; default 4). */+ at?: number;+ /** The explosion's radius (m; default 4). */+ r?: number;+}++/** The shot's camera (the destruction game's first) and the explosion's spot. */+export function fireShotView(seed = 1) {+ const key = cameraPath(seed)[0];+ return { pos: key.pos, target: key.target, fov: 55, spot: spots(seed)[2 * 62] };+}++export function fireShot(o: FireShot = {}) {+ const seed = 1, at = o.at ?? 4, r = o.r ?? 4;+ const view = fireShotView(seed);+ let boom: Explosions;+ let fired = false;+ return defineGame<Record<string, never>>({+ state: {},+ setup: () => {+ fired = false;+ const scene = new Scene();+ const sun = new DirectionalLight(0xffffff, 90000);+ sun.setSunAngles(38, 300);+ scene.add(sun);+ scene.environment = new SkyAtmosphere({ sun });+ const camera = new PerspectiveCamera(view.fov, 16 / 9, 0.05, 2000);+ camera.name = "camera";+ camera.position.set(...view.pos);+ camera.lookAt(...view.target);+ camera.setManualExposure(13);+ scene.add(camera);+ const ground = new MeshStandardMaterial({ name: "ground", color: PALETTE[1][1], roughness: 0.9 });+ const half = (SIZE / 2) * VOXEL, far = 100000;+ for (const [w, d, x, z] of [[2 * far, far - half, 0, -(far + half) / 2], [2 * far, far - half, 0, (far + half) / 2], [far - half, 2 * half, -(far + half) / 2, 0], [far - half, 2 * half, (far + half) / 2, 0]]) {+ const strip = new Mesh(new PlaneGeometry(w, d), ground);+ strip.rotation.x = -Math.PI / 2;+ strip.position.set(x, EDGE * VOXEL, z);+ scene.add(strip);+ }+ voxelLevel({ route: "mesh", palette: nativePalette(false), objects: nativeObjects(seed), physics: false });+ voxelExplode(...view.spot, r);+ boom = new Explosions({ fireballs: 1, lights: o.light === false ? 0 : 1 });+ scene.add(boom);+ // A fire at scene time 0 is started in setup.+ if (at <= 0) {+ boom.fire(view.spot, r, at);+ fired = true;+ }+ return { scene, camera, options: { name: `voxel-level-fire`, width: 1280, height: 720, preset: "cinematic" as const } };+ },+ frame(f) {+ if (!fired && f.time >= at) {+ fired = true;+ boom.fire(view.spot, r, at);+ console.log(`fire ${JSON.stringify({ at, time: f.time })}`);+ }+ boom.step(f.time);+ },+ handlers: {},+ });+}++export interface FireRoom {+ /** The fireball's full size (m). */+ size: number;+ /** A point light of 1,000 cd at the centre instead of the fireball. */+ light?: boolean;+}++/** The room's camera and the fireball's centre, by the fireball's size `d`. */+export function fireRoomView(d: number) {+ return { pos: [0, 0.8 * d, 4 * d] as const, target: [0.8 * d, 0.4 * d, -0.5 * d] as const, fov: 55, center: [0, 0.6 * d, 0] as const, wall: -1.5 * d };+}++export function fireRoom(o: FireRoom) {+ const d = o.size, v = fireRoomView(d);+ return defineGame<Record<string, never>>({+ state: {},+ setup: () => {+ const scene = new Scene();+ const camera = new PerspectiveCamera(v.fov, 16 / 9, 0.05, 2000);+ camera.name = "camera";+ camera.position.set(...v.pos);+ camera.lookAt(...v.target);+ camera.setManualExposure(8);+ scene.add(camera);+ const grey = new MeshStandardMaterial({ name: "grey", color: 0xbcbcbc, roughness: 1 });+ const floor = new Mesh(new PlaneGeometry(20 * d, 20 * d), grey);+ floor.rotation.x = -Math.PI / 2;+ scene.add(floor);+ const wall = new Mesh(new PlaneGeometry(20 * d, 6 * d), grey);+ wall.position.set(0, 3 * d, v.wall);+ scene.add(wall);+ if (o.light) {+ const l = new PointLight(0xffffff, 1000);+ l.position.set(...v.center);+ scene.add(l);+ } else {+ // r such that the fireball's size is d; its centre 0.3 r above the explosion's point.+ const r = d / 2.2;+ const boom = new Explosions({ fireballs: 1, lights: 0 });+ boom.fire([v.center[0], v.center[1] - 0.3 * r, v.center[2]], r, 0);+ scene.add(boom);+ }+ return { scene, camera, options: { name: `fire-room`, width: 640, height: 360, preset: "cinematic" as const } };+ },+ handlers: {},+ });+}++export default fireShot();diff --git a/packages/voxel/src/explosions.ts b/packages/voxel/src/explosions.tsnew file mode 100644index 0000000..b7fbfcb--- /dev/null+++ b/packages/voxel/src/explosions.ts@@ -0,0 +1,318 @@+// An explosion's fire and smoke (ROADMAP § 6 step 10 b): a pool of fireballs (each cools to its own dark smoke) and a+// pool of point lights, made once in setup and reused, so that many explosions do not each add objects to the scene.+// Built only from `@threert/scene`'s `Fireball` and `PointLight`; it adds no engine call. No smoke grid: its box is a+// volume, and volumes must not overlap (docs/VOXEL.md, "Temporary ways round on the engine's shared paths").+//+// Why a light: the live viewport marches media for what the camera sees, but its GI, reflection and shadow rays do not+// see them (docs/MATERIAL_FUNCTIONS.md), so a fireball's own emission lights nothing around it live. Offline it does+// (paths reach the medium). Each burning fireball therefore has a point light at its centre whose intensity and colour+// follow the fireball's age, from a table measured against the offline renderer (`FIRE_LIGHT`; tools/bench-voxel-fire.ts+// --only calibrate).+import { Fireball, Group, PointLight, type Object3D } from "@threert/scene";+import { voxelExplode, type VoxelEdit } from "./native.ts";++/** The most fireballs a pool may have: the kernel draws at most 32 volumes (`MAX_MEDIA`, renderer/src/scene.rs; a+ * scene with more is refused). */+export const MAX_FIREBALLS = 32;+export const MAX_MEDIA = 32;+/** The most fire lights: the kernel evaluates up to 8 shadowed local lights exactly at camera hits (`RIS_EXACT` in+ * pathtrace.wgsl); past that they are resampled, noisier. */+export const MAX_FIRE_LIGHTS = 8;+/** Positions (m) and scene times (s) a fire takes: past them f32 coordinates and times lose their meaning. */+export const MAX_COORD = 1e6;+export const MAX_TIME = 1e9;+/** A fireball's full size (diameter) for an explosion of radius r, and the largest and smallest. */+export const FIREBALL_SIZE = 2.2;+export const MAX_FIREBALL = 40;+export const MIN_FIREBALL = 0.05;+/** Where idle fireballs wait: tiny, far below any level (moving a volume is done in place; hiding one is not+ * promised to be). */+const PARK: [number, number, number] = [0, -10000, 0];+const PARKED = 1e-3;+/** An idle light's reach (m): its light group's sphere, parked with it, then holds no pixel. */+const IDLE_REACH = 1e-3;++/** The fireball sizes (full size, m) the fire light was measured at. */+export const FIRE_LIGHT_SIZES = [1.1, 2.2, 4.4, 8.8] as const;++type Rgb = readonly [number, number, number];+type LightTable = readonly (readonly [number, Rgb, Rgb, Rgb, Rgb])[];+/**+ * The fire light's luminous intensity over the fireball's life, per m² of its full size squared and per nit of its+ * `intensity`: a row is age / life, then (r, g, b) cd for each of `FIRE_LIGHT_SIZES`. Measured against the offline+ * renderer: the light at the fireball's centre that gives a floor and a wall near it what the fireball's own emission+ * gives them there (tools/bench-voxel-fire.ts --only calibrate; docs/VOXEL.md, "Fire and smoke"). Not one curve+ * scaled by the size²: a larger fireball's hot core lies under more of its own smoke, so its light falls sooner.+ * Linear in age between rows, in log size between sizes (the end sizes past them); 0 before the fire and after it.+ */+export const FIRE_LIGHT: LightTable = [+ [0, [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],+ [0.02, [0.000862, 0.000656, 0.000383], [0.00152, 0.00113, 0.000641], [0.00162, 0.00123, 0.000718], [0.00309, 0.00225, 0.00126]],+ [0.05, [0.00291, 0.00217, 0.00124], [0.00476, 0.00351, 0.00199], [0.00596, 0.00431, 0.0024], [0.00788, 0.00562, 0.00308]],+ [0.1, [0.00662, 0.00475, 0.00262], [0.00958, 0.00697, 0.00388], [0.0121, 0.00849, 0.0046], [0.0121, 0.00805, 0.00413]],+ [0.15, [0.00986, 0.00685, 0.00367], [0.0129, 0.00905, 0.00486], [0.0152, 0.0101, 0.00524], [0.0132, 0.00804, 0.00373]],+ [0.2, [0.0122, 0.00812, 0.00419], [0.0149, 0.00983, 0.00501], [0.0161, 0.0101, 0.00489], [0.0126, 0.00708, 0.00299]],+ [0.3, [0.0136, 0.00838, 0.00392], [0.0153, 0.00911, 0.0041], [0.014, 0.00781, 0.00323], [0.00864, 0.00418, 0.00143]],+ [0.4, [0.012, 0.00665, 0.00273], [0.0126, 0.0068, 0.00266], [0.0102, 0.00508, 0.0018], [0.00477, 0.00202, 0.000567]],+ [0.5, [0.00858, 0.0043, 0.00147], [0.009, 0.00435, 0.00143], [0.00601, 0.00264, 0.000763], [0.00204, 0.000756, 0.000176]],+ [0.6, [0.00495, 0.00219, 0.000591], [0.00552, 0.00238, 0.000622], [0.00299, 0.00115, 0.00026], [0.000681, 0.00022, 0.0000448]],+ [0.7, [0.00234, 0.000885, 0.000179], [0.00298, 0.00114, 0.000235], [0.00122, 0.000407, 0.0000776], [0.000186, 0.0000526, 0.00000949]],+ [0.8, [0.000989, 0.000331, 0.0000596], [0.00133, 0.000449, 0.0000811], [0.000399, 0.000111, 0.0000199], [0.000031, 0.00000687, 0.0000012]],+ [0.9, [0.000394, 0.00011, 0.0000194], [0.000429, 0.000119, 0.0000208], [0.0000941, 0.0000217, 0.00000379], [0.00000445, 7.18e-7, 1.24e-7]],+ [1, [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],+];++/** A light table at `x` (its first column) for a fire of full size `size` (m): linear in x between rows, in log size+ * between `FIRE_LIGHT_SIZES` (the end sizes past them); 0 outside the table. */+function lookup(table: LightTable, x: number, size: number): [number, number, number] {+ if (!(x > table[0][0]) || x >= table[table.length - 1][0] || !(size > 0)) return [0, 0, 0];+ let k = 1;+ while (k < table.length - 1 && table[k][0] < x) k++;+ const a = table[k - 1], b = table[k];+ const s = (x - a[0]) / (b[0] - a[0]);+ const at = (j: number): Rgb => {+ const p = a[j + 1] as Rgb, q = b[j + 1] as Rgb;+ return [p[0] + s * (q[0] - p[0]), p[1] + s * (q[1] - p[1]), p[2] + s * (q[2] - p[2])];+ };+ const n = FIRE_LIGHT_SIZES.length;+ const lx = Math.min(Math.max(Math.log(size), Math.log(FIRE_LIGHT_SIZES[0])), Math.log(FIRE_LIGHT_SIZES[n - 1]));+ let j = 0;+ while (j < n - 2 && Math.log(FIRE_LIGHT_SIZES[j + 1]) < lx) j++;+ const t = (lx - Math.log(FIRE_LIGHT_SIZES[j])) / (Math.log(FIRE_LIGHT_SIZES[j + 1]) - Math.log(FIRE_LIGHT_SIZES[j]));+ const p = at(j), q = at(j + 1);+ return [p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1]), p[2] + t * (q[2] - p[2])];+}++/** `FIRE_LIGHT` at `u` (age / life) for a fireball of full size `size` (m): rgb cd per m² of size² per nit. */+export function fireLight(u: number, size: number): [number, number, number] {+ return lookup(FIRE_LIGHT, u, size);+}++export interface ExplosionsOptions {+ /** Fireballs in the pool (1..32: the kernel draws at most 32 volumes; default 8): at most this many burn at once,+ * the oldest taken over past it. */+ fireballs?: number;+ /** Fire lights (0..8; default min(fireballs, 8)): the youngest fireballs that give light have one. */+ lights?: number;+ /** A fireball's life (s, 0.001..60; default 1.6), peak radiance at the core (nits, 0..1e7; default 30,000: a flame's,+ * which by day shows over sunlit walls; `Fireball`'s own 40 is a stylised night's) and extinction (1/m, up to 1,000;+ * default 6). The fire light's table was measured with the defaults' density and life scaled; other densities do+ * not change it. */+ life?: number;+ intensity?: number;+ density?: number;+ /** Not taken: a smoke grid's box is a volume, and a fireball in it would overlap it (volumes must not overlap:+ * docs/VOXEL.md, "Temporary ways round on the engine's shared paths"). A fireball cools to its own dark smoke. */+ smoke?: never;+}++/** What the pool did. */+export interface ExplosionStats {+ /** Fires made. */+ fired: number;+ /** Fireballs taken over while still burning or waiting to start (the pool was full). */+ reused: number;+ /** The most fires burning without a light at once (more glowing than there are lights). */+ unlit: number;+ /** The most burning at once. */+ most: number;+ /** Burning, and lit, at the last `step`. */+ burning: number;+ lit: number;+}++const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);+function within(what: string, v: unknown, lo: number, hi: number): number {+ if (!finite(v) || v < lo || v > hi) throw new RangeError(`${what} must be a number from ${lo} to ${hi}`);+ return v;+}+function triple(what: string, v: unknown, lo: number, hi: number): [number, number, number] {+ if (!Array.isArray(v) || v.length !== 3) throw new RangeError(`${what} must be three numbers`);+ return v.map((x, k) => within(`${what}[${k}]`, x, lo, hi)) as [number, number, number];+}+function whole(what: string, v: number, lo: number, hi: number): number {+ if (!Number.isInteger(v) || v < lo || v > hi) throw new RangeError(`Explosions: ${what} must be a whole number from ${lo} to ${hi}`);+ return v;+}+function check(what: string, at: readonly number[], radius: number, time: number): void {+ triple(`${what}: the position`, at, -MAX_COORD, MAX_COORD);+ if (!finite(radius) || radius <= 0) throw new RangeError(`${what}: the radius must be a finite number above 0`);+ within(`${what}: the time (the frame's f.time)`, time, -MAX_TIME, MAX_TIME);+}++/**+ * `scene.add(new Explosions())` in setup; `explosions.explode(x, y, z, r, f.time)` (or `fire([x, y, z], r, f.time)`+ * after a `voxelExplode` of your own) when something blows; `explosions.step(f.time)` once a frame. A fire is a+ * fireball, which cools to its own dark smoke. Positions are the world's: the group stays at the origin, unrotated,+ * unscaled (a fire throws if it or a parent is not). Every number is checked before anything changes.+ */+export class Explosions extends Group {+ readonly fireballs: Fireball[] = [];+ readonly lights: PointLight[] = [];+ readonly life: number;+ readonly intensity: number;+ readonly stats: ExplosionStats = { fired: 0, reused: 0, unlit: 0, most: 0, burning: 0, lit: 0 };+ /** Per fireball: when it started (scene time; NaN = parked), its full size, its centre, the order it was fired in. */+ private started: number[] = [];+ private sizes: number[] = [];+ private centers: [number, number, number][] = [];+ private order: number[] = [];+ private next = 0;+ /** The scene time of the last `step` (-Infinity before the first). */+ private now = -Infinity;+ private disposed = false;++ constructor(o: ExplosionsOptions = {}) {+ super();+ this.name = "explosions";+ if ((o as { smoke?: unknown }).smoke != null) {+ throw new RangeError("Explosions: no smoke grid: its box is a volume, and a fireball in it would overlap it (volumes must not overlap; a fireball cools to its own smoke)");+ }+ const n = whole("fireballs", o.fireballs ?? 8, 1, Math.min(MAX_FIREBALLS, MAX_MEDIA));+ const nl = whole("lights", o.lights ?? Math.min(n, MAX_FIRE_LIGHTS), 0, Math.min(n, MAX_FIRE_LIGHTS));+ this.life = within("Explosions: life", o.life ?? 1.6, 1e-3, 60);+ this.intensity = within("Explosions: intensity", o.intensity ?? 30000, 0, 1e7);+ const density = within("Explosions: density", o.density ?? 6, 1e-9, 1e3);+ for (let k = 0; k < n; k++) {+ const f = new Fireball({ life: this.life, intensity: this.intensity, density });+ f.name = `fireball-${k}`;+ // Moved at every fire: movable from the start (a fixed object's first move rebuilds the live scene once).+ f.movable = true;+ // Parked while idle: a temporary way round (docs/VOXEL.md, "Temporary ways round on the engine's shared paths").+ f.position.set(...PARK);+ f.scale.setScalar(PARKED);+ f.customData = [-1e6, 0, 0, 0];+ this.add(f);+ this.fireballs.push(f);+ this.started.push(NaN);+ this.sizes.push(0);+ this.centers.push([...PARK]);+ this.order.push(-1);+ }+ for (let k = 0; k < nl; k++) {+ // The stand-in light, and its idle reach of 1 mm where it is parked: temporary ways round (docs/VOXEL.md,+ // "Temporary ways round on the engine's shared paths").+ const l = new PointLight(0xffffff, 0);+ l.name = `fire-light-${k}`;+ l.distance = IDLE_REACH;+ l.movable = true;+ l.position.set(...PARK);+ this.add(l);+ this.lights.push(l);+ }+ }++ /**+ * A fire where an explosion of radius `r` (m) went off at `at` (world, m), starting at scene time `time` (the frame's+ * `f.time`; now or later): the next fireball of the pool (the oldest taken over if every one burns or waits to+ * start), 2.2 r across (5 cm to 40 m), its centre 0.3 r above the explosion's point; a light while it burns. Two fires+ * close together make two fireballs that overlap (docs/VOXEL.md, "Temporary ways round on the engine's shared+ * paths"). Throws a `RangeError` before changing anything for a position outside ±1,000 km or not three finite+ * numbers, a radius that is not finite or not above 0, a time outside ±1e9 s, or the group moved off the world's+ * frame. Returns the fireball's index.+ */+ fire(at: readonly [number, number, number], r: number, time: number): number {+ check("Explosions.fire", at, r, time);+ this.inWorldFrame("Explosions.fire");+ const rr = Math.min(r, MAX_FIREBALL / FIREBALL_SIZE);+ const size = Math.max(FIREBALL_SIZE * rr, MIN_FIREBALL);+ // The centre a little above the explosion's: a ground blast's fireball is not half in the crater, its light not+ // in the hole.+ const c: [number, number, number] = [at[0], at[1] + 0.3 * rr, at[2]];+ const k = this.next;+ this.next = (k + 1) % this.fireballs.length;+ const s = this.started[k];+ if (!Number.isNaN(s) && time - s < this.life) this.stats.reused++;+ const f = this.fireballs[k];+ f.position.set(...c);+ f.scale.setScalar(size);+ f.customData = [time, 0, 0, 0];+ this.started[k] = time;+ this.sizes[k] = size;+ this.centers[k] = c;+ this.order[k] = this.stats.fired++;+ return k;+ }++ /** `voxelExplode(x, y, z, r)` and `fire([x, y, z], r, time)`; the arguments are checked first (nothing happens if+ * they are refused). Returns the voxel edit's result. */+ explode(x: number, y: number, z: number, r: number, time: number): VoxelEdit | { queued: true } {+ check("Explosions.explode", [x, y, z], r, time);+ this.inWorldFrame("Explosions.explode");+ const e = voxelExplode(x, y, z, r);+ this.fire([x, y, z], r, time);+ return e;+ }++ /** Once a frame (scene time): each light set from its fireball's age (the youngest that give light have them);+ * burnt-out fireballs parked. Time going back (a restart) ends every fire. */+ step(time: number): void {+ within("Explosions.step: the time (the frame's f.time)", time, -MAX_TIME, MAX_TIME);+ if (this.disposed) return;+ if (time < this.now) for (let k = 0; k < this.fireballs.length; k++) this.park(k);+ this.now = time;+ const alive: number[] = [];+ for (let k = 0; k < this.fireballs.length; k++) {+ if (this.burning(k, time)) alive.push(k);+ else if (!Number.isNaN(this.started[k]) && time - this.started[k] >= this.life) this.park(k);+ }+ this.stats.burning = alive.length;+ this.stats.most = Math.max(this.stats.most, alive.length);+ // Lights for the youngest that give light now (a fire at age 0 gives none yet: it takes none from an older one).+ const glowing = alive.map((k) => ({ k, rgb: fireLight((time - this.started[k]) / this.life, this.sizes[k]) })).filter((g) => Math.max(...g.rgb) > 0).sort((a, b) => this.order[b.k] - this.order[a.k]);+ this.stats.unlit = Math.max(this.stats.unlit, glowing.length - this.lights.length);+ let lit = 0;+ for (let j = 0; j < this.lights.length; j++) {+ const l = this.lights[j];+ const g = glowing[j];+ if (g === undefined) {+ l.intensity = 0;+ l.distance = IDLE_REACH;+ l.position.set(...PARK);+ continue;+ }+ // (Its change each frame also caps the live view's history, which keeps the fire from ghosting: a temporary way+ // round relied on, docs/VOXEL.md "Temporary ways round on the engine's shared paths".)+ lit++;+ const { k, rgb } = g;+ const peak = Math.max(...rgb);+ l.position.set(...this.centers[k]);+ l.color.setRGB(rgb[0] / peak, rgb[1] / peak, rgb[2] / peak);+ l.intensity = peak * this.sizes[k] * this.sizes[k] * this.intensity;+ // Its reach: 25 sizes (the light group's sphere; past it the fire's light is under a thousandth of its peak).+ l.distance = 25 * this.sizes[k];+ l.radius = 0.15 * this.sizes[k];+ }+ this.stats.lit = lit;+ }++ /** Takes the pool out of the scene for good: its objects removed. A fire after it throws. */+ dispose(): void {+ this.disposed = true;+ for (const o of [...this.children]) this.remove(o);+ this.parent?.remove(this);+ }++ /** Whether fireball `k` burns at `time`. */+ private burning(k: number, time: number): boolean {+ const s = this.started[k];+ return !Number.isNaN(s) && time - s >= 0 && time - s < this.life;+ }++ private park(k: number): void {+ this.started[k] = NaN;+ this.fireballs[k].position.set(...PARK);+ this.fireballs[k].scale.setScalar(PARKED);+ }++ /** The pool's positions are the world's: it and every parent at the origin, unrotated, unscaled. */+ private inWorldFrame(what: string): void {+ if (this.disposed) throw new Error(`${what}: the pool was disposed`);+ for (let o: Object3D | null = this; o; o = o.parent) {+ const p = o.position, q = o.quaternion, sc = o.scale;+ if (p.x !== 0 || p.y !== 0 || p.z !== 0 || q.x !== 0 || q.y !== 0 || q.z !== 0 || q.w !== 1 || sc.x !== 1 || sc.y !== 1 || sc.z !== 1) {+ throw new RangeError(`${what}: the pool (and its parents) must stay at the origin, unrotated and unscaled: its positions are the world's`);+ }+ }+ }+}diff --git a/packages/voxel/src/index.ts b/packages/voxel/src/index.tsindex c6caf61..52eb16c 100644--- a/packages/voxel/src/index.ts+++ b/packages/voxel/src/index.ts@@ -4,3 +4,4 @@ export * from "./vox.ts";export * from "./materials.ts";export * from "./mesh.ts";export * from "./native.ts";+export * from "./explosions.ts";diff --git a/packages/voxel/test/explosions.test.ts b/packages/voxel/test/explosions.test.tsnew file mode 100644index 0000000..656d9ac--- /dev/null+++ b/packages/voxel/test/explosions.test.ts@@ -0,0 +1,212 @@+// An explosion's fire and smoke (ROADMAP § 6 step 10 b): a pool of fireballs, each cooling to its own smoke (no smoke+// grid: its box is a volume, and volumes must not overlap); the oldest fireball taken over, the lights over a fire's+// life, the caps and what happens past them, the arguments refused before anything changes, and that firing changes+// objects in place (no object is made or removed after setup).+import { test } from "node:test";+import assert from "node:assert/strict";+import { PerspectiveCamera, RecordingEngine, Scene, SceneBinding } from "@threert/scene";+import { Explosions, FIRE_LIGHT, FIRE_LIGHT_SIZES, MAX_FIRE_LIGHTS, MAX_MEDIA, fireLight } from "../src/index.ts";++test("the fire light: the table's rows at the measured sizes, linear in age between them, in log size between sizes, nothing before the fire or after its life", () => {+ const r9 = (v: number[]) => v.map((x) => +x.toFixed(9));+ for (const row of FIRE_LIGHT.slice(1, -1)) FIRE_LIGHT_SIZES.forEach((d, j) => assert.deepEqual(r9(fireLight(row[0], d)), r9([...(row[j + 1] as readonly number[])]), `u ${row[0]} size ${d}`));+ const [a, c] = [FIRE_LIGHT[1], FIRE_LIGHT[2]];+ const mid = fireLight((a[0] + c[0]) / 2, FIRE_LIGHT_SIZES[0]);+ assert.ok(Math.abs(mid[0] - (a[1][0] + c[1][0]) / 2) < 1e-9);+ // Between two sizes: at their geometric mean, the mean of the two.+ const [d0, d1] = [FIRE_LIGHT_SIZES[1], FIRE_LIGHT_SIZES[2]];+ const g = fireLight(c[0], Math.sqrt(d0 * d1));+ assert.ok(Math.abs(g[0] - (c[2][0] + c[3][0]) / 2) < 1e-9);+ // Past the end sizes: the end sizes'.+ assert.deepEqual(fireLight(c[0], 0.1), fireLight(c[0], FIRE_LIGHT_SIZES[0]));+ assert.deepEqual(fireLight(c[0], 40), fireLight(c[0], FIRE_LIGHT_SIZES[FIRE_LIGHT_SIZES.length - 1]));+ for (const u of [-1, 0, 1, 2, NaN, Infinity]) assert.deepEqual(fireLight(u, 2), [0, 0, 0], `u ${u}`);+ for (const d of [0, -1, NaN]) assert.deepEqual(fireLight(0.2, d), [0, 0, 0], `size ${d}`);+});++const state = (x: Explosions) => JSON.stringify([x.fireballs.map((f) => [f.position.toArray(), f.scale.toArray(), f.customData]), x.lights.map((l) => [l.position.toArray(), l.intensity, l.distance]), x.stats]);+function bound(x: Explosions) {+ const scene = new Scene();+ scene.add(x);+ const e = new RecordingEngine();+ const binding = new SceneBinding(e, scene, new PerspectiveCamera());+ binding.sync();+ return { scene, e, binding, made: e.take() };+}+/** Placed fireballs (not parked). */+const placed = (x: Explosions) => x.fireballs.filter((f) => f.position.y > -1000);++test("the pool: the next fireball each fire, the oldest taken over, lights for the youngest that give light", () => {+ const x = new Explosions({ fireballs: 3, lights: 2 });+ assert.equal(x.fire([0, 0, 0], 1, 10), 0);+ assert.equal(x.fire([10, 0, 0], 1, 10.1), 1);+ assert.equal(x.fire([20, 0, 0], 2, 10.2), 2);+ assert.equal(x.stats.reused, 0);+ // A fourth while all three burn takes the first over: it starts again, elsewhere.+ assert.equal(x.fire([30, 0, 0], 1, 10.3), 0);+ assert.equal(x.stats.reused, 1);+ assert.deepEqual(x.fireballs[0].customData, [10.3, 0, 0, 0]);+ assert.equal(x.fireballs[0].position.x, 30);+ assert.ok(Math.abs(x.fireballs[0].position.y - 0.3) < 1e-12, "a little above the explosion");+ assert.ok(Math.abs(x.fireballs[2].scale.x - 4.4) < 1e-12, "full size 2.2 r");+ // Two lights, three burning: the two youngest (fired at 10.3 and 10.2) have them.+ x.step(10.35);+ assert.equal(x.stats.burning, 3);+ assert.equal(x.stats.lit, 2);+ assert.equal(x.stats.unlit, 1, "one burning without a light");+ assert.deepEqual(x.lights.map((l) => l.position.x).sort((a, b) => a - b), [20, 30]);+ const l = x.lights.find((q) => q.position.x === 20)!;+ const rgb = fireLight(0.15 / 1.6, 4.4), peak = Math.max(...rgb);+ assert.ok(Math.abs(l.intensity - peak * 4.4 * 4.4 * 30000) < 1e-3);+ assert.ok(Math.abs(l.color.g - rgb[1] / peak) < 1e-9);+ assert.ok(Math.abs(l.distance - 25 * 4.4) < 1e-9 && Math.abs(l.radius - 0.15 * 4.4) < 1e-12, "lit: reach 25 sizes, radius 0.15 of one");+ // A new fire at age 0 gives no light yet: it takes none from the older ones.+ x.fire([40, 0, 0], 1, 10.4);+ x.step(10.4);+ assert.deepEqual(x.lights.map((q) => q.position.x).sort((a, b) => a - b), [20, 30]);+ x.step(10.45);+ assert.deepEqual(x.lights.map((q) => q.position.x).sort((a, b) => a - b), [30, 40], "a frame on, it has one");+ // Burnt out: parked, the lights off.+ x.step(20);+ assert.equal(x.stats.burning, 0);+ assert.equal(x.stats.lit, 0);+ assert.ok(x.lights.every((q) => q.intensity === 0 && q.distance > 0 && q.distance < 0.01), "off, and reaching nothing (distance 0 would be unbounded)");+ assert.equal(placed(x).length, 0);+ assert.equal(x.stats.most, 3);+});++test("no smoke grid: refused (its box is a volume a fireball in it would overlap)", () => {+ const smoke = { center: [0, 5, 0], size: [20, 10, 20], cells: [40, 20, 40] };+ assert.throws(() => new Explosions({ smoke } as never), /overlap/);+ assert.doesNotThrow(() => new Explosions({ smoke: undefined }));+ assert.equal(new Explosions().children.filter((o) => o.type === "VolumeMesh").length, 8, "8 fireballs, nothing else");+});++test("time: a fire set for later waits, is counted when taken over; time going back ends every fire", () => {+ const x = new Explosions({ fireballs: 2, lights: 2 });+ x.step(1);+ x.fire([0, 0, 0], 1, 5); // fireball 0: waits (now is 1)+ x.step(2);+ assert.equal(x.stats.burning, 0, "not before it starts");+ assert.equal(placed(x).length, 1, "placed, waiting");+ x.fire([20, 0, 0], 1, 5); // fireball 1: waits+ x.fire([40, 0, 0], 1, 5.1); // takes over fireball 0, waiting to start+ assert.equal(x.stats.reused, 1);+ x.step(5.2);+ assert.equal(x.stats.burning, 2);+ // Back to 0 (a restart): every fire ends, nothing burns again later.+ x.fire([60, 0, 0], 1, 6);+ x.step(0);+ assert.equal(x.stats.burning, 0);+ assert.equal(placed(x).length, 0);+ x.step(6.1);+ assert.equal(x.stats.burning, 0, "nothing set before the restart burns after it");+});++test("firing changes objects in place: after setup no object is made or removed", () => {+ const x = new Explosions();+ const { e, binding, made } = bound(x);+ const objects = made.filter((c) => c[0] === "object").map((c) => c[2] as { kind: string; name: string; movable?: boolean });+ assert.equal(objects.filter((o) => o.kind === "volume").length, 8, "8 fireballs");+ assert.equal(objects.filter((o) => o.kind === "light").length, 8);+ // Movable from the start: a fixed object's first move would rebuild the live scene once (280 ms on the benchmark+ // level), at each pool member's first fire.+ const pool = objects.filter((o) => /^(fireball|fire-light)-/.test(o.name));+ assert.equal(pool.length, 16);+ assert.ok(pool.every((o) => o.movable === true), "every fireball and light movable");+ for (let k = 0; k < 20; k++) {+ x.fire([10 * k, 0, 0], 1 + (k % 3), k * 0.1);+ x.step(k * 0.1 + 0.05);+ binding.sync();+ assert.deepEqual(e.take().filter((c) => c[0] === "object" || c[0] === "remove"), [], `fire ${k}`);+ }+});++test("caps: 1,000 fires in a frame keep the pool's objects, the last ones burning; sizes clamped", () => {+ for (const apart of [0, 1e-6]) {+ const x = new Explosions();+ const { e, binding } = bound(x);+ for (let k = 0; k < 1000; k++) x.fire([10 * k, 0, 0], 1, 3 + k * apart);+ x.step(3.1);+ binding.sync();+ assert.deepEqual(e.take().filter((c) => c[0] === "object" || c[0] === "remove"), []);+ assert.equal(x.stats.reused, 1000 - 8);+ assert.equal(x.stats.burning, 8);+ assert.equal(x.stats.lit, 8);+ assert.deepEqual(x.fireballs.map((f) => f.position.x).sort((a, b) => a - b), [9920, 9930, 9940, 9950, 9960, 9970, 9980, 9990], "the last 8 burn");+ }+ const z = new Explosions();+ assert.equal(z.fireballs[z.fire([0, 0, 0], 1e30, 0)].scale.x, 40, "the largest: 40 m");+ assert.equal(z.fireballs[z.fire([100, 0, 0], 1e-46, 0)].scale.x, 0.05, "the smallest: 5 cm");+});++test("32 volumes: at most 32 fireballs (the kernel draws 32 volumes; scene::build refuses more)", () => {+ assert.equal(new Explosions({ fireballs: 32 }).fireballs.length, 32);+ assert.throws(() => new Explosions({ fireballs: 33 }), RangeError);+ assert.equal(MAX_MEDIA, 32);+});++test("invalid arguments are refused before anything changes", () => {+ const x = new Explosions({ fireballs: 2 });+ const before = state(x);+ const bad: [string, () => unknown][] = [+ ["NaN x", () => x.fire([NaN, 0, 0], 1, 0)],+ ["infinite y", () => x.fire([0, Infinity, 0], 1, 0)],+ ["-infinite z", () => x.fire([0, 0, -Infinity], 1, 0)],+ ["finite past f32", () => x.fire([1e39, 0, 0], 1, 0)],+ ["past 1,000 km", () => x.fire([0, 0, 2e6], 1, 0)],+ ["NaN radius", () => x.fire([0, 0, 0], NaN, 0)],+ ["infinite radius", () => x.fire([0, 0, 0], Infinity, 0)],+ ["negative radius", () => x.fire([0, 0, 0], -1, 0)],+ ["zero radius", () => x.fire([0, 0, 0], 0, 0)],+ ["NaN time", () => x.fire([0, 0, 0], 1, NaN)],+ ["infinite time", () => x.fire([0, 0, 0], 1, Infinity)],+ ["huge time", () => x.fire([0, 0, 0], 1, 1e300)],+ ["two numbers", () => x.fire([0, 0] as unknown as [number, number, number], 1, 0)],+ ["a string", () => x.fire(["1", 0, 0] as unknown as [number, number, number], 1, 0)],+ ["explode NaN", () => x.explode(NaN, 0, 0, 1, 0)],+ ["explode past f32", () => x.explode(1e39, 0, 0, 1, 0)],+ ["explode negative", () => x.explode(0, 0, 0, -2, 0)],+ ["step NaN", () => x.step(NaN)],+ ["step huge", () => x.step(-1e300)],+ ];+ for (const [what, f] of bad) assert.throws(f, RangeError, what);+ assert.equal(state(x), before);+ // The pool moved off the world's frame: refused too.+ x.position.x = 1;+ assert.throws(() => x.fire([0, 0, 0], 1, 0), RangeError);+ x.position.x = 0;+ assert.equal(state(x), before);+ // explode's arguments are checked before the voxel call (which needs the native voxels: here there are none, so a+ // call that got that far would throw an Error, not a RangeError).+ assert.throws(() => x.explode(0, 0, 0, 1, 0), (e: Error) => !(e instanceof RangeError) && /native voxels/.test(e.message));+ for (const o of [{ fireballs: 0 }, { fireballs: 33 }, { fireballs: 2.5 }, { lights: MAX_FIRE_LIGHTS + 1 }, { fireballs: 2, lights: 3 }, { life: 0 }, { life: NaN }, { life: 61 }, { density: -1 }, { density: Infinity }, { intensity: -1 }, { intensity: 1e308 }]) {+ assert.throws(() => new Explosions(o), RangeError, JSON.stringify(o));+ }+ assert.equal(new Explosions({ lights: 0 }).lights.length, 0);+});++test("explode: the voxel explosion, then the fire; dispose takes the pool out", async () => {+ const g = globalThis as { __engine?: object };+ const before = g.__engine;+ const calls: object[] = [];+ g.__engine = { voxelEdit: (d: object) => { calls.push(d); return JSON.stringify({ removed: 12 }); } };+ try {+ const x = new Explosions();+ const scene = new Scene();+ scene.add(x);+ assert.deepEqual(x.explode(1, 2, 3, 0.5, 4), { removed: 12 });+ assert.deepEqual(calls, [{ op: "explode", sphere: [1, 2, 3, 0.5] }]);+ assert.equal(x.stats.fired, 1);+ assert.equal(x.fireballs[0].position.x, 1);+ assert.deepEqual(x.fireballs[0].customData, [4, 0, 0, 0]);+ x.dispose();+ assert.equal(x.parent, null);+ assert.equal(x.children.length, 0);+ assert.throws(() => x.fire([0, 0, 0], 1, 5), /disposed/);+ assert.throws(() => x.explode(0, 0, 0, 1, 5), /disposed/);+ assert.equal(calls.length, 1, "no voxel call after dispose");+ } finally {+ g.__engine = before;+ }+});diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 35d378c..faa7cb6 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -912,6 +912,10 @@ pub fn card_material(color: [f32; 3], intensity: f32) -> GpuMaterial {}/// Builds the GPU scene from the engine's world. Asset files (models, file textures) resolve against `assets`.+/// The most volumes a scene may show at once: the kernel loops over at most 32 media with a 32-bit mask+/// (pathtrace.wgsl `media_track`, `media_march`, `media_shadows`). A scene past it is refused, not drawn without some.+pub const MAX_MEDIA: usize = 32;+pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&serde_json::Value>) -> Result<Scene> {let t0 = web_time::Instant::now();let st = &w.settings;@@ -1593,6 +1597,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet b = &grids[k];at = [f32::from_bits(b.z0), f32::from_bits(b.dims[0] | b.dims[1] << 10 | b.dims[2] << 20)];}+ if media.len() >= MAX_MEDIA {+ return Err(anyhow!("object {}: more than {MAX_MEDIA} volumes shown at once (the kernel takes {MAX_MEDIA}; the rest would not be drawn)", n.name));+ }media.push(MediumGpu { w: medium_rows(m), a: [func, *shape, *homogeneous as u32, 0], b: [majorant.max(0.0), g.clamp(-0.99, 0.99), at[0], at[1]], c: n.custom, p });media_nodes.push(*id);}@@ -2309,4 +2316,29 @@ mod instance_tests {assert_eq!(node_ranges(&nodes, "box").collect::<Vec<_>>(), vec![12..20]);assert_eq!(node_ranges(&nodes, "none").count(), 0);}++ /// More volumes shown than the kernel takes (32): the scene is refused, not drawn without the last ones; hidden+ /// volumes do not count.+ #[test]+ fn a_scene_past_the_kernels_volumes_is_refused() {+ let build_with = |n: u32, hidden: u32| {+ let mut w = World::default();+ w.set_volume_fn("f", "o.extinction = 1.0;".into(), String::new());+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();+ w.set_object(1000, "camera".into(), None, world::Kind::Camera(cam), false, false).unwrap();+ w.set_settings(world::Settings { camera: Some(1000), ..Default::default() });+ for id in 1..=n + hidden {+ let kind = world::Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, grid: None };+ w.set_object(id, format!("v{id}"), None, kind, false, false).unwrap();+ if id > n {+ w.set_visible(id, false).unwrap();+ }+ }+ build(&w, Path::new("."), &crate::default_presets_dir(), None)+ };+ assert_eq!(build_with(MAX_MEDIA as u32, 0).unwrap().media.len(), MAX_MEDIA);+ let e = build_with(MAX_MEDIA as u32 + 1, 0).err().expect("33 volumes refused");+ assert!(format!("{e:#}").contains("more than 32 volumes"), "{e:#}");+ assert_eq!(build_with(MAX_MEDIA as u32, 4).unwrap().media.len(), MAX_MEDIA, "hidden ones do not count");+ }}diff --git a/tests/render/voxel-fire-light.ts b/tests/render/voxel-fire-light.tsnew file mode 100644index 0000000..a1c5e88--- /dev/null+++ b/tests/render/voxel-fire-light.ts@@ -0,0 +1,53 @@+// The fire light stands in for the fireball's own light (ROADMAP § 6 step 10 b; `FIRE_LIGHT` in @threert/voxel): two+// fires of 1 m (fireballs 2.2 m across) either side of a wall, 0.48 s after they start (0.3 of their life), over a grey+// floor, no sky. Left: the fireball alone, its light path traced from its emission (no fire light). Right: the fire+// light alone (the fireball there made transparent: a density of 1e-6, so it emits nothing). The floor before each+// should read the same: right / left = 1 (the table was measured this way, in tools/bench-voxel-fire.ts --only+// calibrate, over a floor and a wall; within about 10 % of each other there).+import { BoxGeometry, Mesh, type PerspectiveCamera } from "@threert/scene";+import { Explosions } from "@threert/voxel";+import { camera, lambert, plane, result, sceneWithSky, type Region, type TestMeta } from "./lib.ts";++const EYE: [number, number, number] = [0, 9, 14], AT: [number, number, number] = [0, 0, 1], FOV = 50;++/** A floor point's place in the image (u, v from the top left). */+function project(p: [number, number, number]): [number, number] {+ const f = AT.map((t, i) => t - EYE[i]), fl = Math.hypot(...f), fw = f.map((v) => v / fl);+ const r = [-fw[2], 0, fw[0]], rl = Math.hypot(...r), rt = r.map((v) => v / rl);+ const up = [rt[1] * fw[2] - rt[2] * fw[1], rt[2] * fw[0] - rt[0] * fw[2], rt[0] * fw[1] - rt[1] * fw[0]];+ const d = p.map((v, i) => v - EYE[i]);+ const z = d[0] * fw[0] + d[1] * fw[1] + d[2] * fw[2], x = d[0] * rt[0] + d[1] * rt[1] + d[2] * rt[2], y = d[0] * up[0] + d[1] * up[1] + d[2] * up[2];+ const t = Math.tan((FOV * Math.PI) / 360);+ return [0.5 + x / (z * t * (16 / 9)) / 2, 0.5 - y / (z * t) / 2];+}+/** The floor from 2 to 5 m before a fire at x, 2 m either side of it. */+function patch(x: number): Region {+ const c = [project([x - 2, 0, 2]), project([x + 2, 0, 2]), project([x - 2, 0, 5]), project([x + 2, 0, 5])];+ return [Math.min(...c.map((p) => p[0])), Math.min(...c.map((p) => p[1])), Math.max(...c.map((p) => p[0])), Math.max(...c.map((p) => p[1]))];+}++export const test: TestMeta = {+ id: "voxel/fire-light", features: ["volume", "lights"], reference: "converged", temporal: false, spp: 4096, time: 0.48,+ metric: { kind: "ratio", a: patch(5), b: patch(-5), expected: 1, tolerance: 0.15 },+ note: "the floor before a fire light alone over the floor before a fireball alone (its own emission), 0.3 of its life",+};++export default function () {+ const scene = sceneWithSky(0);+ const grey = lambert(0.5, "grey");+ const floor = plane(60, grey, "floor");+ // From z -10 to 8: between the halves (a straight line from one fire to the other side's floor crosses it), and in+ // front of the camera, not around it.+ const wall = new Mesh(new BoxGeometry(0.2, 12, 18), grey);+ wall.name = "wall";+ wall.position.set(0, 6, -1);+ // Centres 1.32 m up (0.6 of the size, as in the calibration room): the explosion's point 0.3 r below.+ const fireball = new Explosions({ fireballs: 1, lights: 0 });+ fireball.fire([-5, 1.02, 0], 1, 0);+ const light = new Explosions({ fireballs: 1, lights: 1, density: 1e-6 });+ light.fire([5, 1.02, 0], 1, 0);+ // (No frame script: the light is set for the render's time here; the fireball follows the scene time itself.)+ light.step(test.time!);+ const cam: PerspectiveCamera = camera(scene, EYE, AT, FOV);+ return result(scene, cam, [floor, wall, fireball, light]);+}diff --git a/tools/bench-voxel-fire.ts b/tools/bench-voxel-fire.tsnew file mode 100644index 0000000..7c6a2eb--- /dev/null+++ b/tools/bench-voxel-fire.ts@@ -0,0 +1,317 @@+// An explosion's fire and smoke (ROADMAP § 6 step 10 b; docs/VOXEL.md, "Fire and smoke"): what the fire light must be,+// how the live frame compares with our offline render, and what it costs on the benchmark level.+//+// calibrate games/voxel-level/level-fire.game.ts `fireRoom`: fireballs of 1.1, 2.2, 4.4 and 8.8 m burning over a grey+// floor before a grey wall, offline at ages through its life, against a 1,000 cd point light at its centre:+// per channel the floor's and the wall's radiance near it, fire over light x 1,000 cd, per m² of the+// fireball's size² and per nit of its intensity: the rows of `FIRE_LIGHT`.+// quality `fireShot`: the benchmark level by day, a 4 m explosion's fire 0.2, 0.5 and 1.0 s after it starts (at 4 s),+// the live frame (lockstep at 60 fps from the start, render scale 0.75: never 1, where the live frame has+// no edge anti-aliasing) against our offline render at that scene time (no clamps, no denoiser), which has+// the fireball's own light and no fire light. Live with the fire light and without (what it buys). ΔE (mean,+// p99) and SSIM over the image, the fireball, the street before it, and 3 x 3 regions.+// cost games/voxel-level/level-destruction{,-smoke,-fire}.game.ts at 0.75, lockstep (frames as fast as the GPU+// goes): the frame's CPU and GPU ms for 2 s before and 4 s after the 4 m explosion (`crater`); with fire,+// `sustained` (7 a second for 10 s) and `peak` (20 within a second): frame times, fireballs burning, lights.+// `--software`: instead, the fire route's crater under software traversal (THREERT_HWRT=0, loop guard 8,192).+//+// node tools/bench-voxel-fire.ts [--only calibrate,quality,cost] [--spp 2048] [--software]+//+// One renderer at a time. A step that gives no answer in its time ends this script with exit 3 and leaves the renderer+// alone (never killed). Result: out/bench/voxel-fire/<time>.json and tables on stdout.+import { execFileSync, spawn } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { createInterface } from "node:readline";+import { fireRoomView, fireShotView } from "../games/voxel-level/level-fire.game.ts";+import { FIRE_LIGHT, FIRE_LIGHT_SIZES, FIREBALL_SIZE } from "../packages/voxel/src/explosions.ts";+import { bundleGame } from "./bundle-game.ts";+import { frameStats, rendererBin, repoRoot } from "./lib/bench.ts";+import { generate } from "./voxel-level/generate.ts";++const args = process.argv.slice(2);+const opt = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);+const only = opt("--only", "calibrate,quality,cost").split(",");+const SPP = Number(opt("--spp", "2048"));+const SCALE = opt("--scale", "0.75");+const dir = join(repoRoot, "out/voxel-fire");+const truthDir = join(repoRoot, "out/cache/truth");+const outDir = join(repoRoot, "out/bench/voxel-fire");+for (const d of [dir, truthDir, outDir]) mkdirSync(d, { recursive: true });+const r2 = (v: number) => +v.toFixed(2);+const r3 = (v: number) => +v.toFixed(3);+const result: Record<string, unknown> = { at: new Date().toISOString(), spp: SPP, scale: SCALE };++/** A bundle of a game module's builder called with options. */+async function bundle(name: string, module: string, fn: string, o: object): Promise<string> {+ const entry = join(dir, `${name}.entry.ts`);+ writeFileSync(entry, `import { ${fn} } from ${JSON.stringify(join(repoRoot, module))};\nexport default ${fn}(${JSON.stringify(o)});\n`);+ return (await bundleGame(entry, join(dir, `${name}.js`))).out;+}++/** Our unbiased offline render of a bundle at a scene time (png and linear HDR), cached by content. */+function offline(name: string, b: string, time: number, spp = SPP, size?: [number, number]): { png: string; hdr: string } {+ const key = createHash("sha256").update(readFileSync(b)).update(readFileSync(rendererBin)).update(`fire ${spp} ${time} ${size}`).digest("hex").slice(0, 12);+ const png = join(truthDir, `${name}-${key}.png`), hdr = join(truthDir, `${name}-${key}.raw`);+ if (!existsSync(png) || !existsSync(hdr)) {+ const t0 = performance.now();+ execFileSync(rendererBin, ["render", b, "-o", png, "--hdr", hdr, "--assets", repoRoot, "--spp", String(spp), "--time", String(time), "--no-denoise", ...(size ? ["--width", String(size[0]), "--height", String(size[1])] : []), "--override", JSON.stringify({ native: { clampIndirect: 1e9 } })], { stdio: ["ignore", "ignore", "inherit"], timeout: 0 });+ console.log(` offline ${name} at ${time} s (${spp} spp): ${((performance.now() - t0) / 1000).toFixed(1)} s`);+ }+ return { png, hdr };+}++type M = { mean_delta_e: number; p99_delta_e: number; ssim: number; luminance_ratio: number };+const compare = (ref: string, test: string, region?: number[]): M => JSON.parse(execFileSync(rendererBin, ["compare", ref, test, ...(region ? ["--region", region.map((v) => v.toFixed(4)).join(",")] : [])]).toString().trim().split("\n").pop()!);+const fmt = (m: M) => `${m.mean_delta_e.toFixed(2)} / ${m.p99_delta_e.toFixed(1)} / ${m.ssim.toFixed(3)} / ${m.luminance_ratio.toFixed(2)}`;+const meets = (m: M) => m.mean_delta_e <= 3 && m.ssim >= 0.9;++/** A point's place in the image (u, v from the top left) for a camera at `pos` looking at `target`. */+function projector(pos: readonly number[], target: readonly number[], fovDeg: number, aspect = 16 / 9) {+ const f = target.map((t, i) => t - pos[i]), fl = Math.hypot(...f), fw = f.map((v) => v / fl);+ const r = [-fw[2], 0, fw[0]], rl = Math.hypot(...r), rt = r.map((v) => v / rl);+ const up = [rt[1] * fw[2] - rt[2] * fw[1], rt[2] * fw[0] - rt[0] * fw[2], rt[0] * fw[1] - rt[1] * fw[0]];+ const t = Math.tan((fovDeg * Math.PI) / 360);+ return (p: readonly number[]): [number, number] => {+ const d = p.map((v, i) => v - pos[i]);+ const z = d[0] * fw[0] + d[1] * fw[1] + d[2] * fw[2], x = d[0] * rt[0] + d[1] * rt[1] + d[2] * rt[2], y = d[0] * up[0] + d[1] * up[1] + d[2] * up[2];+ return [0.5 + x / (z * t * aspect) / 2, 0.5 - y / (z * t) / 2];+ };+}+const clamp01 = (v: number) => Math.min(1, Math.max(0, v));+/** The image region holding the points (their bounding box, clamped to the image). */+function box(points: [number, number][]): number[] {+ return [Math.min(...points.map((p) => p[0])), Math.min(...points.map((p) => p[1])), Math.max(...points.map((p) => p[0])), Math.max(...points.map((p) => p[1]))].map(clamp01);+}+const corners = (lo: number[], hi: number[]) => [0, 1].flatMap((i) => [0, 1].flatMap((j) => [0, 1].map((k) => [i ? hi[0] : lo[0], j ? hi[1] : lo[1], k ? hi[2] : lo[2]])));++/** Mean linear radiance (rgb) of an HDR render (RGB f32) over a region. */+function hdrMean(raw: string, [u0, v0, u1, v1]: number[], w: number, h: number): [number, number, number] {+ const px = new Float32Array(readFileSync(raw).buffer.slice(0));+ const s = [0, 0, 0];+ let n = 0;+ for (let y = Math.floor(v0 * h); y < Math.ceil(v1 * h); y++) for (let x = Math.floor(u0 * w); x < Math.ceil(u1 * w); x++) {+ for (let c = 0; c < 3; c++) s[c] += px[(y * w + x) * 3 + c];+ n++;+ }+ return s.map((v) => v / n) as [number, number, number];+}++/** One headless live session driven in lockstep; never killed (a step without an answer ends this script). */+function live(name: string, b: string, o: { env?: Record<string, string>; frameLog?: string } = {}) {+ const argv = ["live", b, "--assets", repoRoot, "--presets", join(repoRoot, "presets"), "--width", "1280", "--height", "720", "--scale", SCALE];+ if (o.frameLog) {+ rmSync(o.frameLog, { force: true });+ argv.push("--frame-log", o.frameLog);+ }+ const p = spawn(rendererBin, argv, { stdio: ["pipe", "ignore", "pipe"], env: { ...process.env, ...o.env } });+ const lines: string[] = [];+ let waiters: [(l: string) => boolean, (l: string) => void][] = [];+ createInterface({ input: p.stderr! }).on("line", (l) => {+ lines.push(l);+ waiters = waiters.filter(([pred, res]) => (pred(l) ? (res(l), false) : true));+ });+ let exited = false;+ const gone = new Promise<void>((r) => p.on("exit", () => { exited = true; r(); }));+ const send = (c: object) => p.stdin!.write(JSON.stringify(c) + "\n");+ const wait = (pred: (l: string) => boolean, what: string, ms = 180_000) => new Promise<string>((res) => {+ const hit = lines.find(pred);+ if (hit) return res(hit);+ const t = setTimeout(() => {+ console.log(`live ${name}: STUCK waiting for ${what} (${lines.slice(-3).join(" | ")}); the renderer (pid ${p.pid}) is left alone`);+ p.unref();+ process.exit(3);+ }, ms);+ waiters.push([pred, (l) => (clearTimeout(t), res(l))]);+ gone.then(() => {+ if (!lines.find(pred)) {+ console.log(`live ${name}: the renderer exited while waiting for ${what} (${lines.slice(-3).join(" | ")})`);+ process.exit(1);+ }+ });+ });+ // Lockstep from the first frame: the frame script, the grids and the shaders all step 1/60 s a frame.+ send({ cmd: "lockstep", dt: 1 / 60 });+ let frame = 0, seq = 0;+ return {+ lines,+ /** `n` frames on; with `snapshot`, the last one saved there. */+ async frames(n: number, snapshot?: string) {+ if (n <= 0 && !snapshot) return;+ const id = `s${seq++}`;+ send({ cmd: "frames", n, ...(snapshot ? { snapshot } : { sync: id }) });+ await wait((l) => (snapshot ? l.includes(snapshot) : l === `live: sync ${id}`), snapshot ? `the snapshot ${snapshot}` : `frames to ${frame + n}`);+ frame += n;+ },+ event(type: string) { send({ cmd: "event", type }); },+ /** From now on each frame steps `dt` s (the frame script, the grids and the shaders). */+ step(dt: number) { send({ cmd: "lockstep", dt }); },+ get frame() { return frame; },+ async quit() {+ send({ cmd: "quit" });+ const t = setTimeout(() => { console.log(`live ${name}: did not quit in 60 s; left alone (pid ${p.pid})`); p.unref(); process.exit(3); }, 60_000);+ await gone;+ clearTimeout(t);+ if (exited && p.exitCode !== 0) console.log(`live ${name}: exit ${p.exitCode}`);+ },+ };+}++if (only.includes("calibrate")) {+ const ages = [0.02, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], life = 1.6, intensity = 30000, W = 640, H = 360;+ const rows: Record<string, unknown>[] = [];+ console.log(`\ncalibrate: the fireball's equivalent point light (cd per m² of size² per nit; floor | wall), offline ${SPP} spp`);+ for (const d of FIRE_LIGHT_SIZES) {+ const v = fireRoomView(d);+ const proj = projector(v.pos, v.target, v.fov);+ const floor = box(corners([1.2 * d, 0, -0.4 * d], [2.0 * d, 0, 0.4 * d]).map(proj));+ const wall = box(corners([1.0 * d, 0.2 * d, v.wall], [1.8 * d, 1.0 * d, v.wall]).map(proj));+ const lb = await bundle(`room-${d}-light`, "games/voxel-level/level-fire.game.ts", "fireRoom", { size: d, light: true });+ const lt = offline(`room-${d}-light`, lb, 0.5, SPP, [W, H]);+ const ref = { floor: hdrMean(lt.hdr, floor, W, H), wall: hdrMean(lt.hdr, wall, W, H) };+ const fb = await bundle(`room-${d}-fire`, "games/voxel-level/level-fire.game.ts", "fireRoom", { size: d });+ for (const u of ages) {+ const t = offline(`room-${d}-fire`, fb, u * life, SPP, [W, H]);+ const per = (region: number[], base: number[]) => hdrMean(t.hdr, region, W, H).map((x, c) => (x / Math.max(base[c], 1e-12)) * 1000 / (d * d * intensity));+ const f = per(floor, ref.floor), w = per(wall, ref.wall);+ rows.push({ size: d, u, floor: f.map((x) => +x.toPrecision(3)), wall: w.map((x) => +x.toPrecision(3)) });+ console.log(` ${String(d).padStart(4)} m u ${u.toFixed(2)} ${f.map((x) => x.toFixed(3)).join(" ")} | ${w.map((x) => x.toFixed(3)).join(" ")}`);+ }+ }+ // The table: per age and size the mean of the floor's and the wall's.+ const table = ages.map((u) => [u, ...FIRE_LIGHT_SIZES.map((d) => {+ const r = rows.find((x) => x.u === u && x.size === d)!;+ return [0, 1, 2].map((c) => +(((r.floor as number[])[c] + (r.wall as number[])[c]) / 2).toPrecision(3));+ })]);+ result.calibrate = { rows, table, current: FIRE_LIGHT };+ console.log(` measured table (u, then rgb per size ${FIRE_LIGHT_SIZES.join(", ")} m):`);+ for (const row of table) console.log(` ${JSON.stringify(row)},`);+}++/** The fire shot's regions at the fireball's age (s; it grows as the root of age / life): the fireball's box, the+ * street below it, and 3 x 3. */+function shotRegions(age: number, r = 4, life = 1.6) {+ const v = fireShotView(1);+ const proj = projector(v.pos, v.target, v.fov);+ const c = [v.spot[0], v.spot[1] + 0.3 * r, v.spot[2]], rad = ((FIREBALL_SIZE * r) / 2) * Math.sqrt(Math.min(age / life, 1));+ const fire = box(corners([c[0] - rad, c[1] - rad, c[2] - rad], [c[0] + rad, c[1] + rad, c[2] + rad]).map(proj));+ const regions: [string, number[]][] = [["all", [0, 0, 1, 1]], ["fireball", fire], ["street", [clamp01(fire[0] - 0.15), fire[3], clamp01(fire[2] + 0.15), 1]]];+ if (fire[3] >= 0.98) regions.pop();+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) regions.push([`r${i}${j}`, [j / 3, i / 3, (j + 1) / 3, (i + 1) / 3]]);+ return regions;+}++function judge(ref: string, test: string, age: number) {+ return Object.fromEntries(shotRegions(age).map(([k, reg]) => [k, compare(ref, test, k === "all" ? undefined : reg)]));+}+function report(tag: string, j: Record<string, M>) {+ const short = ["all", "fireball", "street"].filter((k) => j[k]).map((k) => `${k} ${fmt(j[k])}${meets(j[k]) ? "" : " ✗"}`).join(" ");+ const grid = Object.entries(j).filter(([k]) => k.startsWith("r")).map(([k, m]) => `${k} ${m.mean_delta_e.toFixed(1)}/${m.p99_delta_e.toFixed(0)}/${m.ssim.toFixed(2)}`).join(" ");+ console.log(` ${tag.padEnd(26)} ${short}\n ${"".padEnd(26)} ${grid}`);+}++if (only.includes("quality")) {+ generate(1, "object");+ const at = 4, ages = [0.2, 0.5, 1.0];+ const refB = await bundle("shot-ref", "games/voxel-level/level-fire.game.ts", "fireShot", { light: false, at });+ const litB = await bundle("shot-lit", "games/voxel-level/level-fire.game.ts", "fireShot", { light: true, at });+ console.log(`\nquality: the live frame (lockstep 60 fps, scale ${SCALE}) against our offline render (${SPP} spp), the 4 m explosion's fire; ΔE mean / p99 / SSIM / luminance (✗: ΔE > 3 or SSIM < 0.9)`);+ for (const a of ages) console.log(` regions at ${a} s: ${shotRegions(a).slice(1, 3).map(([k, r]) => `${k} ${r.map((x) => x.toFixed(3)).join(",")}`).join("; ")} (cells: ΔE mean / p99 / SSIM)`);+ const truths = ages.map((a) => offline(`shot-${a}`, refB, at + a));+ const rows: Record<string, unknown>[] = [];+ // The fire light twice (the live view's run-to-run spread: its radiance cache trains in an order the GPU decides).+ const lives: string[][] = [];+ for (const [tag, b] of [["with the fire light", litB], ["with it again", litB], ["without", refB]] as const) {+ const s = live(`shot-${tag}`, b);+ const shots: string[] = [];+ for (const a of ages) {+ const png = join(dir, `shot-${tag.replace(/\W+/g, "-")}-${a}.png`);+ const target = Math.round((at + a) * 60);+ await s.frames(target - s.frame - 1);+ await s.frames(1, png);+ shots.push(png);+ }+ const fireLine = s.lines.find((l) => l.includes("] fire {"));+ await s.quit();+ for (let k = 0; k < ages.length; k++) {+ const j = judge(truths[k].png, shots[k], ages[k]);+ rows.push({ tag, age: ages[k], j });+ report(`${tag}, ${ages[k]} s`, j);+ }+ console.log(` (${fireLine ?? "no fire line"})`);+ lives.push(shots);+ }+ // Held: the same frame with time all but stopped (1e-5 s a frame) for 120 frames: the live view's own converged+ // picture of that moment. Against offline it is the live media's bias; against the real-time frame, the lag of the+ // temporal filter behind a fireball that changes every frame.+ for (let k = 0; k < ages.length; k++) {+ const s = live(`held-${ages[k]}`, litB);+ const png = join(dir, `shot-held-${ages[k]}.png`);+ // To the real-time snapshot's own frame (its age), then held there.+ await s.frames(Math.round((at + ages[k]) * 60));+ s.step(1e-5);+ await s.frames(120, png);+ await s.quit();+ const j = judge(truths[k].png, png, ages[k]), lag = judge(png, lives[0][k], ages[k]);+ rows.push({ tag: "held", age: ages[k], j }, { tag: "real-time vs held", age: ages[k], j: lag });+ report(`held, ${ages[k]} s`, j);+ report(`real-time vs held, ${ages[k]} s`, lag);+ }+ for (let k = 0; k < ages.length; k++) {+ const j = judge(lives[0][k], lives[1][k], ages[k]);+ rows.push({ tag: "live A/A", age: ages[k], j });+ report(`live run 2 vs run 1, ${ages[k]} s`, j);+ }+ // The offline reference's own noise: the same frame at half the samples.+ const half = offline(`shot-0.5-half`, refB, at + 0.5, SPP / 2);+ const own = judge(truths[1].png, half.png, 0.5);+ report(`offline ${SPP / 2} vs ${SPP} spp, 0.5 s`, own);+ result.quality = { rows, own };+}++if (only.includes("cost")) {+ generate(1, "object");+ type Frame = { interval: number; cpu: number; gpu: number; voxel?: [number, number]; guard?: number | null; rebuild: number; fallback: string | null };+ const routes: [string, string, Record<string, string>][] = [["mesh", "level-destruction.game.ts", {}], ["smoke", "level-destruction-smoke.game.ts", {}], ["fire", "level-destruction-fire.game.ts", {}]];+ if (args.includes("--software")) routes.splice(0, routes.length, ["fire, software", "level-destruction-fire.game.ts", { THREERT_HWRT: "0", THREERT_LOOP_GUARD: "8192" }]);+ const rows: Record<string, unknown>[] = [];+ console.log(`\ncost: lockstep at scale ${SCALE}, frames as fast as the GPU goes; ms p50 / p95 / max`);+ const st = (xs: number[]) => { const s = frameStats(xs); return `${s.p50.toFixed(1)} / ${s.p95.toFixed(1)} / ${Math.max(...xs).toFixed(1)}`; };+ for (const [tag, game, env] of routes) {+ const b = (await bundleGame(join(repoRoot, "games/voxel-level", game), join(dir, game.replace(".ts", ".js")))).out;+ for (const scenario of tag === "fire" && !args.includes("--crater") ? ["crater", "sustained", "peak"] : ["crater"]) {+ const log = join(dir, `cost-${tag.replace(/\W+/g, "-")}-${scenario}.jsonl`);+ const s = live(`cost-${tag}-${scenario}`, b, { env, frameLog: log });+ await s.frames(240); // warm: the level loaded, the radiance cache trained+ s.event(scenario);+ await s.frames(scenario === "sustained" ? 11 * 60 : scenario === "peak" ? 4 * 60 : 5 * 60);+ const explosions = s.lines.filter((l) => /^(\[game\] )?explosion \{/.test(l)).map((l) => JSON.parse(l.slice(l.indexOf("{"))) as { burning?: number; lit?: number });+ await s.quit();+ const F = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l) as Frame);+ const ex = F.findIndex((f, k) => k > 200 && (f.voxel?.[0] ?? 0) > 0);+ if (ex < 0) {+ console.log(` ${tag} ${scenario}: no explosion in the frame log`);+ continue;+ }+ const before = F.slice(Math.max(ex - 120, 0), ex), after = F.slice(ex, ex + (scenario === "crater" ? 240 : scenario === "sustained" ? 600 : 180));+ const row = {+ tag, scenario, explosion_frame: { cpu: r2(Math.max(F[ex].cpu, F[ex + 1]?.cpu ?? 0)), gpu: r2(Math.max(F[ex].gpu, F[ex + 1]?.gpu ?? 0)) },+ before: { cpu: frameStats(before.map((f) => f.cpu)), gpu: frameStats(before.map((f) => f.gpu)) }, after: { cpu: frameStats(after.map((f) => f.cpu)), gpu: frameStats(after.map((f) => f.gpu)), gpu_max: r2(Math.max(...after.map((f) => f.gpu))) },+ burning_max: Math.max(0, ...explosions.map((e) => e.burning ?? 0)), lit_max: Math.max(0, ...explosions.map((e) => e.lit ?? 0)), explosions: explosions.length,+ guard: Math.max(0, ...F.map((f) => f.guard ?? 0)),+ rebuilds_after: after.filter((f) => f.rebuild > 0).map((f) => `${r2(f.rebuild)} ms${f.fallback ? ` (${f.fallback})` : ""}`),+ // The GPU ms per frame over the 4 s after, in 0.25 s bins (the fire burns 1.6 s; the smoke after).+ gpu_bins: Array.from({ length: Math.ceil(after.length / 15) }, (_, k) => r2(frameStats(after.slice(k * 15, k * 15 + 15).map((f) => f.gpu)).p50)),+ };+ rows.push(row);+ console.log(` ${tag.padEnd(15)} ${scenario.padEnd(9)} before: CPU ${st(before.map((f) => f.cpu))}, GPU ${st(before.map((f) => f.gpu))}; explosion frame CPU ${row.explosion_frame.cpu}, GPU ${row.explosion_frame.gpu}; after: CPU ${st(after.map((f) => f.cpu))}, GPU ${st(after.map((f) => f.gpu))}${tag.startsWith("fire") ? `; burning at most ${row.burning_max}, lit ${row.lit_max}` : ""}${row.guard ? `; guard ${row.guard}` : ""}; rebuilds after: ${row.rebuilds_after.length ? row.rebuilds_after.join(", ") : "none"}`);+ console.log(` ${"".padEnd(25)} GPU p50 per 0.25 s after: ${row.gpu_bins.join(" ")}`);+ }+ }+ result.cost = rows;+}++const file = join(outDir, `${new Date().toISOString().replace(/[:.]/g, "-")}.json`);+writeFileSync(file, JSON.stringify(result, null, 1) + "\n");+console.log(`-> ${file}`);