Skip to content

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.

What a grid program has simulated is carried across a rebuild of the live scene (ROADMAP § 1a) (#42)

Yujiacd54c70d0f12
diff --git a/docs/MATERIAL_FUNCTIONS.md b/docs/MATERIAL_FUNCTIONS.md
index e2c4ad5..7359d4a 100644
--- a/docs/MATERIAL_FUNCTIONS.md
+++ b/docs/MATERIAL_FUNCTIONS.md
@@ -432,7 +432,8 @@ cloud.scale.set(8, 8, 8);
a program that adds what a source gives adds it once). At most 64 a frame.
- Offline, a still at scene time t runs the program for round(t × 60) frames (at most 36,000) from the setup's
sources, then renders.
- - A rebuild of the scene starts the grid again from its data.
+ - A rebuild of the live scene keeps what the program has simulated, while the grid is the same grid: its size and
+ its program (new parameters keep it). A new size or another program starts it again from its data.
```ts
// The whole of an advection: each cell takes what was upstream of it.
@@ -471,8 +472,7 @@ 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). A live rebuild (any structural change) starts every
-simulated grid again from its data: the smoke there vanishes (ROADMAP § 6 step 10 b, Open).
+rays through grid media live (as for every medium but the homogeneous ones).
### Water
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 14cbfd6..4e094d7 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -1927,6 +1927,16 @@ A rect light's card and the sun still rebuild (geometry; the sky's bake).
is hidden a faint ring stays where its edge was (the upscaler's history: nothing says a medium went).
- Not done: `Explosions` still parks (the voxel line's to change); a mesh hidden by its own `visible` still rebuilds.
+**Simulated grids across a rebuild (2026-11-13, after it).** A rebuild of the live scene made new grid textures, so
+any structural change in a game (an object hidden, a texture, an edit's fallback) started every simulated grid again
+from its data: the smoke vanished (§ 6 step 10 b kept its pool movable and parked for that). Now the scene before
+hands what its grid programs had simulated to the scene after (`Gpu::carry_grids`): per grid that is the same grid
+still (`world::DensityGrid::made`: its size and its program's name; new parameters keep it), field A (its layers of
+the atlas) and field B are copied texture to texture, and the programs' step count goes with them.
+`volume/grid-rebuild-live`: a grid filled at 1.5 a second for 24 frames, the scene rebuilt after 12, reads 0.6075 of
+0.6024 (as without the rebuild); main 0.90. test-render 187 pass. Not carried: GPU particles (a rebuild still starts
+them afresh), and a grid whose size or program changed.
+
Not done here: filters sized by hit distance, which is what would let a short history stand without noise; the
Playground and the page still open a 1280 × 720 view; the live buffers are sized by the output (about 1.7 GB at
2560 × 1440), though the traced grid rarely fills it.
diff --git a/docs/VOXEL.md b/docs/VOXEL.md
index 55756d2..c18990c 100644
--- a/docs/VOXEL.md
+++ b/docs/VOXEL.md
@@ -773,7 +773,7 @@ above.)
| 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 | **now** (2026-11-13: a volume or a light hidden by its own `visible` keeps its place in the build, in place; no media pass runs while every medium is hidden; `volume/hidden-in-place-live`, `light/hidden-in-place-live` and the two `shown`). What is left is `Explosions`' own | `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) | **now** (2026-11-13: black lights are in no group's sphere and are skipped first; a hidden light's entry is black; the groups are sorted again when a local light moves or goes dark or lit). What is left is `Explosions`' own | distance 0 on idle lights; the fire route's GPU time before any explosion within 0.1 ms of the smoke route's |
-| 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 |
+| 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 | **now** (2026-11-13: a rebuild copies fields A and B of every simulated grid that is the same grid still into the new scene's textures, `Gpu::carry_grids`; `volume/grid-rebuild-live`). What is left is `Explosions`' own | 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 | **now** (2026-11-13: the kernel takes the ray a stretch at a time and sums the coefficients of the media it is in, offline and live; `volume/overlap-emission`, `-live`). What is left is `Explosions`' own: taking a grid again, in a PR of the voxel line's | 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 dependencies
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 2a3b542..f4dcd7d 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -368,7 +368,7 @@ fn grid_texture(d: &wgpu::Device, label: &str, dims: [u32; 3], written: bool) ->
sample_count: 1,
dimension: wgpu::TextureDimension::D3,
format: GRID_FORMAT,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | if written { wgpu::TextureUsages::STORAGE_BINDING } else { wgpu::TextureUsages::empty() },
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC | if written { wgpu::TextureUsages::STORAGE_BINDING } else { wgpu::TextureUsages::empty() },
view_formats: &[],
})
}
@@ -394,10 +394,14 @@ struct GridGpu {
node: u32,
dims: [u32; 3],
z0: u32,
+ /// `world::DensityGrid::made`: the grid it was built from.
+ made: u32,
sim: Option<GridSim>,
}
struct GridSim {
+ /// Field B, the program's own (its state with field A in the atlas; A' and B' are each frame's scratch).
+ b: wgpu::Texture,
program: u32,
params: [f32; 32],
steps: [(wgpu::Buffer, wgpu::BindGroup); 2],
@@ -1670,7 +1674,8 @@ impl Gpu {
}
let sim = g.program.map(|program| {
let tex = |label: &str| grid_texture(d, label, g.dims, true).create_view(&Default::default());
- let (a2, b, b2) = (tex("grid A'"), tex("grid B"), tex("grid B'"));
+ let field_b = grid_texture(d, "grid B", g.dims, true);
+ let (a2, b, b2) = (tex("grid A'"), field_b.create_view(&Default::default()), tex("grid B'"));
let sources = d.create_buffer(&wgpu::BufferDescriptor { label: Some("grid sources"), size: (crate::world::GRID_MAX_SOURCES * 48) as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let step = |src_a: &wgpu::TextureView, src_b: &wgpu::TextureView, dst_a: &wgpu::TextureView, dst_b: &wgpu::TextureView| {
let u = d.create_buffer(&wgpu::BufferDescriptor { label: Some("grid step"), size: std::mem::size_of::<GridStepGpu>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
@@ -1694,9 +1699,9 @@ impl Gpu {
};
let steps = [step(&atlas_view, &b, &a2, &b2), step(&a2, &b2, &atlas_view, &b)];
let m = &scene.media[g.medium as usize];
- GridSim { program, params: g.params, steps, sources, placed: std::cell::Cell::new((m.w, m.c)) }
+ GridSim { b: field_b, program, params: g.params, steps, sources, placed: std::cell::Cell::new((m.w, m.c)) }
});
- GridGpu { id: g.id, node: g.node, dims: g.dims, z0: g.z0, sim }
+ GridGpu { id: g.id, node: g.node, dims: g.dims, z0: g.z0, made: g.made, sim }
})
.collect::<Vec<_>>();
let pipeline = grids.iter().any(|g| g.sim.is_some()).then(|| {
@@ -2326,6 +2331,29 @@ impl Gpu {
);
}
+ /// What the grid programs have simulated, from the scene before a rebuild into the one after: for each grid with a
+ /// program that is the same grid still (`world::DensityGrid::made`, its size), its field A (the atlas's layers)
+ /// and field B copied on the GPU, and the programs' step count. Without it a rebuild started every simulated grid
+ /// again from its data: any structural change in a game (an object hidden, a texture) wiped its smoke.
+ pub fn carry_grids(&self, old: &Uploaded, new: &Uploaded) {
+ let (Some(from), Some(to)) = (&old.grids, &new.grids) else { return };
+ let mut e = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("carry grids") });
+ let mut any = false;
+ for g in &to.grids {
+ let Some(sim) = &g.sim else { continue };
+ let Some((o, osim)) = from.grids.iter().find(|o| o.id == g.id && o.made == g.made && o.dims == g.dims).and_then(|o| o.sim.as_ref().map(|s| (o, s))) else { continue };
+ let size = wgpu::Extent3d { width: g.dims[0], height: g.dims[1], depth_or_array_layers: g.dims[2] };
+ let at = |texture, z| wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d { x: 0, y: 0, z }, aspect: wgpu::TextureAspect::All };
+ e.copy_texture_to_texture(at(&from.atlas, o.z0), at(&to.atlas, g.z0), size);
+ e.copy_texture_to_texture(at(&osim.b, 0), at(&sim.b, 0), size);
+ any = true;
+ }
+ if any {
+ to.step.set(from.step.get());
+ self.queue.submit([e.finish()]);
+ }
+ }
+
/// A density grid's new data (the game's: `World::set_grid`), uploaded in place.
pub fn upload_grid(&self, up: &Uploaded, id: u32, data: &[f32]) {
let Some(gs) = &up.grids else { return };
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index 8ed3447..3b8b30b 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -3516,6 +3516,8 @@ impl LiveCore {
if s.scene_camera != self.sc.scene_camera {
self.cam = s.scene_camera;
}
+ // What the grid programs had simulated goes with the grids that are still the same.
+ self.g.carry_grids(&self.sc.up, &s.up);
self.sc = s;
self.spark_lights = self.sc.tables.emitter_tris.iter().any(|e| e.nominal);
self.restir_prev = None;
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 53e2b03..5227909 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -626,6 +626,8 @@ pub struct GridBuild {
pub params: [f32; 32],
pub node: u32,
pub medium: u32,
+ /// `world::DensityGrid::made`.
+ pub made: u32,
}
/// The world -> local rows of a medium whose node has world matrix `m` (pathtrace.wgsl `Medium.w0..w2`).
@@ -1605,13 +1607,13 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
gp[k] = *v;
}
let z0 = grids.iter().map(|b| b.dims[2]).sum::<u32>();
- let cells = grids.iter().chain([&GridBuild { id: 0, dims: dg.dims, z0, data: None, program: None, params: [0.0; 32], node: 0, medium: 0 }]).map(|b| b.dims.iter().map(|&d| d as u64).product::<u64>()).sum::<u64>();
+ let cells = grids.iter().chain([&GridBuild { id: 0, dims: dg.dims, z0, data: None, program: None, params: [0.0; 32], node: 0, medium: 0, made: 0 }]).map(|b| b.dims.iter().map(|&d| d as u64).product::<u64>()).sum::<u64>();
// (The atlas is as wide and high as the widest and highest grid: its texels count too.)
let atlas = grids.iter().map(|b| b.dims[0]).chain([dg.dims[0]]).max().unwrap() as u64 * grids.iter().map(|b| b.dims[1]).chain([dg.dims[1]]).max().unwrap() as u64 * (z0 + dg.dims[2]) as u64;
if cells > world::GRID_MAX_SCENE_CELLS || atlas > 2 * world::GRID_MAX_SCENE_CELLS || z0 + dg.dims[2] > world::GRID_MAX_LAYERS {
return Err(anyhow!("object {}: the scene's density grids exceed {} cells or {} layers along z together (or differ too much in width and height)", n.name, world::GRID_MAX_SCENE_CELLS, world::GRID_MAX_LAYERS));
}
- grids.push(GridBuild { id: *gid, dims: dg.dims, z0, data: dg.data.clone(), program, params: gp, node: *id, medium: media.len() as u32 });
+ grids.push(GridBuild { id: *gid, dims: dg.dims, z0, data: dg.data.clone(), program, params: gp, node: *id, medium: media.len() as u32, made: dg.made });
grids.len() - 1
}
};
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 958c35a..5697d23 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -66,6 +66,9 @@ pub struct DensityGrid {
pub data: Option<Arc<Vec<f32>>>,
/// The grid program (by name) and its 32 parameter floats.
pub program: Option<(String, Vec<f32>)>,
+ /// A number of its own for the grid as it was made: another when it is made again with another size or another
+ /// program. What a program has simulated in it is carried across a rebuild while this stays (gpu.rs `carry_grids`).
+ pub made: u32,
}
/// A grid's most cells per axis (pathtrace.wgsl `vgrid` packs them in 10 bits each) and in all (8 bytes a cell and
@@ -358,6 +361,8 @@ pub struct World {
/// live view last took them: per volume object, (x, y, z, radius, a rgba, b rgba) each.
pub grids: HashMap<u32, DensityGrid>,
pub grid_dirty: BTreeSet<u32>,
+ /// The last `DensityGrid::made` given.
+ pub grids_made: u32,
pub grid_programs: BTreeMap<String, (String, String)>,
pub grid_sources: BTreeMap<u32, Vec<f32>>,
/// Volume functions by name: (WGSL code, helpers) (pathtrace.wgsl `vf_<name>`).
@@ -386,6 +391,7 @@ impl Default for World {
voxel_occupancy: None,
grids: HashMap::new(),
grid_dirty: BTreeSet::new(),
+ grids_made: 0,
grid_programs: BTreeMap::new(),
grid_sources: BTreeMap::new(),
volume_fns: BTreeMap::new(),
@@ -1067,7 +1073,16 @@ impl World {
}
// (No data with a same grid: its contents stay, e.g. a simulated grid whose parameters were sent again.)
let keep = if same && data.is_none() { self.grids.get(&id).and_then(|g| g.data.clone()) } else { None };
- self.grids.insert(id, DensityGrid { dims, data: data.or(keep), program });
+ // The same grid still, for what its program has simulated: its size and its program's name (new parameters
+ // rebuild the scene, and the smoke stays).
+ let made = match self.grids.get(&id) {
+ Some(g) if g.dims == dims && g.program.as_ref().map(|p| &p.0) == program.as_ref().map(|p| &p.0) => g.made,
+ _ => {
+ self.grids_made = self.grids_made.wrapping_add(1);
+ self.grids_made
+ }
+ };
+ self.grids.insert(id, DensityGrid { dims, data: data.or(keep), program, made });
Ok(())
}
@@ -1183,8 +1198,14 @@ mod tests {
assert!(!w.take_changes().structural && w.grid_dirty.is_empty() && w.grids[&1].data.as_ref().unwrap()[1] == 2.0, "no data: kept");
w.set_grid(1, [2, 2, 2], 1, None, Some(("p".into(), vec![1.0]))).unwrap();
assert!(w.take_changes().structural, "another program");
- w.set_grid(1, [2, 2, 4], 1, None, Some(("p".into(), vec![1.0]))).unwrap();
- assert!(w.take_changes().structural, "another size");
+ let made = w.grids[&1].made;
+ w.set_grid(1, [2, 2, 2], 1, None, Some(("p".into(), vec![2.0]))).unwrap();
+ assert!(w.take_changes().structural && w.grids[&1].made == made, "new parameters rebuild; it is the same grid still (what it simulated is carried)");
+ w.set_grid(1, [2, 2, 2], 1, None, Some(("q".into(), vec![2.0]))).unwrap();
+ assert!(w.grids[&1].made != made, "another program: another grid");
+ let made = w.grids[&1].made;
+ w.set_grid(1, [2, 2, 4], 1, None, Some(("q".into(), vec![2.0]))).unwrap();
+ assert!(w.take_changes().structural && w.grids[&1].made != made, "another size");
// Sources.
let volume = |grid| Kind::Volume { function: "f".into(), params: vec![], shape: 0, majorant: 1.0, g: 0.0, homogeneous: false, animated: false, grid };
w.set_object(5, "plain".into(), None, volume(None), false, false).unwrap();
diff --git a/tests/render/volume-grid-rebuild-live.ts b/tests/render/volume-grid-rebuild-live.ts
new file mode 100644
index 0000000..5af03f2
--- /dev/null
+++ b/tests/render/volume-grid-rebuild-live.ts
@@ -0,0 +1,42 @@
+// What a grid program has simulated survives a rebuild of the live scene (gpu.rs `carry_grids`): volume/grid-program's
+// grid, 1.5 a second into every cell, in the real-time renderer for 24 frames; after 12 the frame script hides a mesh
+// out of view, a structural change (the scene is built again). The grid holds 0.6 as if nothing had happened, and the
+// wall behind the absorber reads 2 e^-1.2 = 0.6024. (Started again at the rebuild it held 0.3: 1.098.)
+import { BoxGeometry, DensityGrid, GridProgram, Mesh, MeshStandardMaterial, VolumeMesh } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { CENTER, camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { GRID_MEDIUM } from "./volume-grid-uniform.ts";
+
+export const test: TestMeta = {
+ id: "volume/grid-rebuild-live", features: ["volume", "density-grid", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "radiance", region: CENTER, expected: 2 * Math.exp(-1.2), tolerance: 0.03 },
+ live: 24,
+ note: "as volume/grid-program; a mesh behind the camera hidden at frame 12 rebuilds the scene",
+};
+
+const FILL = new GridProgram("test_fill_rebuild", {
+ params: { Rate: 1 },
+ code: `
+ s.a.x += $Rate * i.dt;`,
+});
+
+let frames = 0;
+let extra: Mesh;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ frames = 0;
+ const scene = sceneWithSky(0);
+ const wall = new Mesh(new BoxGeometry(8, 8, 0.1), new MeshStandardMaterial({ name: "wall", color: 0x000000, emissive: 0xffffff, emissiveIntensity: 2 }));
+ wall.position.set(0, 0, -2);
+ const box = new VolumeMesh({ volume: GRID_MEDIUM.with({ Density: 2 }), majorant: 2, grid: new DensityGrid({ size: [16, 16, 8], program: FILL.with({ Rate: 1.5 }) }) });
+ box.scale.set(2, 2, 1);
+ extra = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ name: "extra", color: 0x808080 }));
+ extra.position.set(0, 0, 20);
+ return result(scene, camera(scene, [0, 0, 5], [0, 0, 0]), [wall, box, extra]);
+ },
+ frame() {
+ if (++frames === 12) extra.visible = false;
+ },
+ handlers: {},
+});