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.

Volumes and density grids come in place (#201)

Yujia442a975d2c91
diff --git a/docs/MATERIAL_FUNCTIONS.md b/docs/MATERIAL_FUNCTIONS.md
index 6487657..6ead6e1 100644
--- a/docs/MATERIAL_FUNCTIONS.md
+++ b/docs/MATERIAL_FUNCTIONS.md
@@ -417,7 +417,9 @@ cloud.scale.set(8, 8, 8);
- **Rendering.** As any medium: delta tracking and ratio tracking offline; live, the camera rays' march and the volume
voxels' in-scattering (above). A medium with a grid is marched in 64 steps instead of 8 (a grid has detail 8 steps
miss), and its empty steps skip the voxel lookup.
-- **Changing it from the game.** Write `grid.data`, set `grid.needsUpdate`: uploaded in place, no rebuild.
+- **Changing it from the game.** Write `grid.data`, set `grid.needsUpdate`: uploaded in place. A volume with a
+ grid the scene had not, a grid of another size or with another program, comes in place too (the scene's grids
+ are made again together; docs/RUNTIME.md "What comes in place").
- **Simulating it.** With a `GridProgram`, the grid changes on the GPU every frame (`renderer/shaders/grid_sim.wgsl`,
WGSL compute only). The grid then holds a second field B of four numbers, the program's own (a velocity, say).
- The program is a WGSL body run once per cell, with `$Name` parameters. It gets the cell's `s.a` and `s.b` and
@@ -433,8 +435,9 @@ 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 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.
+ - What the program has simulated stays while the grid is the same grid: its size and its program (new
+ parameters and a change of the program's code keep it), across the scene's grids being made again and across a
+ rebuild of the live scene. 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.
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 80fc51c..5aaac4c 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2776,7 +2776,7 @@ in-place tests' world, rows given back; two models in a shared pose posed again
(tests/render/data/arm.glb, a skinned strip of two materials); `geometry/emitter-model-live` (a model's emitting
section that is not its first, the model a unit under software traversal).
-**Textures, models, functions and lights come in place; the kernel is made beside the frames (2026-11-24).**
+**Textures, models, functions and lights come in place; the kernel is made beside the frames (2026-11-23).**
A game that brought a texture, a model, a material function or a light while it ran had the scene built again from
the world, and a feature a scene first used had the next frame wait for the driver's compile. On Bistro (2.8 M
triangles, 960 x 540, an M5 Pro), the frame the edit landed in:
@@ -2805,6 +2805,39 @@ Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too low
Found by review: a translucent particle's material given another function kept the kernel's old dispatch for the
translucency pass, which has its particles' functions alone; the kernel is made again where those are others.
+**Volumes and density grids come in place (2026-11-23, after it).** A volume that came, went or was set again
+while a game ran, a still volume's first move, a volume function, a new density grid and a grid program each had
+the scene built again. On Bistro (as above), the frame the edit landed in:
+
+| | before | now |
+|---|---|---|
+| a homogeneous volume comes (the scene's first medium) | 1.4 to 1.6 s | no long frame (18 ms at most) |
+| a volume with a 32³ density grid comes | 1.3 to 1.4 s | no long frame (27 ms) |
+| a volume whose 32³ grid a program simulates comes | 1.2 to 1.4 s | 128 ms, the program's pass compiled; 19 ms once the driver has it |
+| the first volume goes | 1.1 to 1.2 s | no long frame (21 ms) |
+| the simulated one goes | 1.2 s | no long frame (18 ms) |
+
+Before, a rebuild that needed a kernel variant the driver had not compiled took 5.1 to 5.4 s instead; now the
+variant is made beside the frames, and the volume is drawn when it is there.
+
+The media table is made whole from the world by the code the build has for it (`LiveCore::set_media`,
+`scene::MediumGpu::of`), volume functions are numbered in the order they come, and the kernel's count of media
+and its media features follow. The density grids follow the volumes that name them (`Gpu::put_grids`), stacked by
+the function the build stacks them with (`scene::grid_of`): when a grid comes, goes, or has another size or
+program, or a program's code changes, the atlas and the programs' pass are made again and what the programs had
+simulated is copied on the GPU to the grids that are the same still; new parameters, and a grid that passes to
+another of its volumes, make nothing again.
+Costs that stay: a grid program's pass is compiled in the frame it comes in (the 128 ms above), and one atlas
+holds every grid, so all are made again when one comes or goes.
+Tests: `volumes_come_and_go_in_place` and `density_grids_come_and_change_in_place`, each edit against a build of
+the edited world, state and picture, with the cells a program had simulated read back; the world's rules.
+Mutations: 23. 20 failed a test. Two had none, a media table that grew and was not bound again (the tests had
+two volumes, the table room for two) and a grid counted the same although its volume was another, and have their
+cases now. One was no fault: where a grid lies follows from the grids before it, and that comparison is gone.
+Found by review: a still volume that was moved left its grid's program running in the box where it had stood; a
+volume edit in place did not hold the lighting's histories short for the frames after it, as a rebuild did (nor
+had a volume shown or hidden in place before this).
+
**A tangent is a vertex's (2026-11-23).** A triangle had one tangent, its first corner's, and a model whose file
had none had its frame made a triangle at a time where it was hit: a normal map's detail turned at every edge of a
curved surface. Now each corner of a file's triangle carries its own through the build, corners that differ in
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 4222de3..459ba30 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -833,10 +833,16 @@ at the end. `THREERT_EDIT_LOG=1` says where a rebuild was decided, and a frame's
- **Lights.** A light that is an entry of the light table alone (not a rect light with a card, not the
atmosphere's sun) comes, goes and changes its kind or its shadow in place: the table is listed in a build's
order, sorted, grown where it is full, and the kernel's counts follow.
+- **Volumes.** The media table is made whole from the world, as a build makes it (`LiveCore::set_media`): a volume
+ that comes, goes, is set again or is moved where it stood still. A volume function that comes takes the next
+ number; the kernel's count of media and its media features follow (a scene's first volume is another variant).
+- **Density grids.** The grids follow the volumes that name them (`Gpu::put_grids`). A new grid, another size,
+ another program or a program's code has the atlas and the programs' pass made again, and what the programs had
+ simulated is copied on the GPU to the grids that are the same still; new parameters make nothing again. A
+ program's pass is compiled in the frame it comes in.
- **Groups and cameras.** A new group, and a camera that is not the scene's, draw nothing.
-Still a rebuild: particle systems, volumes and density grids that come or go, and their functions and programs; a
-geometry function; a posed model the scene has not got, and any new model under software traversal (its room does
+Still a rebuild: particle systems that come or go, and their functions and programs; a geometry function; a posed model the scene has not got, and any new model under software traversal (its room does
not grow); a material that becomes a particle's or gets vertex colours; a rect light's card; as many shadow-casting
local lights as bring the light tiles or take them away; the scene's first instance, procedural object, instance
colours or vertex colours (the kernel's data is laid out for them); the atmosphere's sun shown or hidden.
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index fa5b4ef..f40d251 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -724,27 +724,29 @@ struct GridSim {
pub struct GridsGpu {
atlas: wgpu::Texture,
pipeline: Option<wgpu::ComputePipeline>,
+ /// The grid programs the pipeline was made from (none without one).
+ programs: Vec<(String, String, String)>,
grids: Vec<GridGpu>,
step: std::cell::Cell<u32>,
}
/// grid_sim.wgsl with the scene's grid programs (`fn gp_<name>`) and their dispatch.
-fn grid_sim_source(scene: &Scene) -> String {
+fn grid_sim_source(programs: &[(String, String, String)]) -> String {
let base = include_str!("../shaders/grid_sim.wgsl");
let mut f = String::new();
let mut seen = std::collections::HashSet::new();
- for (_, _, helpers) in &scene.grid_programs {
+ for (_, _, helpers) in programs {
if !helpers.is_empty() && seen.insert(helpers.clone()) {
f.push_str(helpers);
f.push('\n');
}
}
- for (_, code, _) in &scene.grid_programs {
+ for (_, code, _) in programs {
f.push_str(code);
f.push('\n');
}
f.push_str("fn grid_program(f: u32, s: Cell, i: CIn, p: array<vec4<f32>, 8>) -> Cell {\n switch f {\n");
- for (k, (id, _, _)) in scene.grid_programs.iter().enumerate() {
+ for (k, (id, _, _)) in programs.iter().enumerate() {
f.push_str(&format!(" case {k}u {{ return gp_{id}(s, i, p); }}\n"));
}
f.push_str(" default { return s; }\n }\n}\n");
@@ -1846,6 +1848,42 @@ impl Kernel {
functions
}
+ /// A scene's volume functions and their dispatch (pathtrace.wgsl `volume_function`), as they are spliced into the
+ /// kernel: (name, code, helpers) in the order of their numbers.
+ fn volume_functions_of(fns: &[(String, String, String)]) -> String {
+ let mut volume_functions = String::new();
+ if !fns.is_empty() {
+ let mut seen = std::collections::HashSet::new();
+ for (_, _, helpers) in fns {
+ if !helpers.is_empty() && seen.insert(helpers.clone()) {
+ volume_functions.push_str(helpers);
+ volume_functions.push('\n');
+ }
+ }
+ for (_, code, _) in fns {
+ volume_functions.push_str(code);
+ volume_functions.push('\n');
+ }
+ volume_functions.push_str("fn volume_function(f: u32, i: VIn, p: array<vec4<f32>, 8>) -> VOut {\n switch f {\n");
+ for (k, (id, _, _)) in fns.iter().enumerate() {
+ volume_functions.push_str(&format!(" case {k}u {{ return vf_{id}(i, p); }}\n"));
+ }
+ volume_functions.push_str(" default { return VOut(0.0, vec3<f32>(1.0), vec3<f32>(0.0)); }\n }\n}\n");
+ }
+ volume_functions
+ }
+
+ /// This kernel with other volume functions (one that came or changed while the scene runs): another module.
+ pub fn with_volume_functions(&self, fns: &[(String, String, String)]) -> Kernel {
+ use std::hash::{Hash, Hasher};
+ let volume_functions = legacy_wgsl(Kernel::volume_functions_of(fns));
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ self.functions.hash(&mut h);
+ volume_functions.hash(&mut h);
+ self.geometry_functions.hash(&mut h);
+ Kernel { volume_functions, hash: h.finish(), ..self.clone() }
+ }
+
/// This kernel with other material functions (a function added or changed while the scene runs): another module
/// (`hash`), the volume and geometry functions as they are.
pub fn with_material_functions(&self, shaders: &[(String, String, String)], translucent: &std::collections::BTreeSet<i32>) -> Kernel {
@@ -1862,25 +1900,7 @@ impl Kernel {
// (The translucency pass's functions: those of its particles' materials.)
let used: std::collections::BTreeSet<i32> = scene.trans_attrs.iter().filter_map(|a| scene.materials.get(a.uv[3].to_bits() as usize)).map(|m| m.tex1[3] - 1).filter(|&f| f >= 0).collect();
let functions = Kernel::material_functions(&scene.shaders, &used);
- let mut volume_functions = String::new();
- if !scene.volume_fns.is_empty() {
- let mut seen = std::collections::HashSet::new();
- for (_, _, helpers) in &scene.volume_fns {
- if !helpers.is_empty() && seen.insert(helpers.clone()) {
- volume_functions.push_str(helpers);
- volume_functions.push('\n');
- }
- }
- for (_, code, _) in &scene.volume_fns {
- volume_functions.push_str(code);
- volume_functions.push('\n');
- }
- volume_functions.push_str("fn volume_function(f: u32, i: VIn, p: array<vec4<f32>, 8>) -> VOut {\n switch f {\n");
- for (k, (id, _, _)) in scene.volume_fns.iter().enumerate() {
- volume_functions.push_str(&format!(" case {k}u {{ return vf_{id}(i, p); }}\n"));
- }
- volume_functions.push_str(" default { return VOut(0.0, vec3<f32>(1.0), vec3<f32>(0.0)); }\n }\n}\n");
- }
+ let volume_functions = Kernel::volume_functions_of(&scene.volume_fns);
let mut geometry_functions = String::new();
if !scene.geometry_fns.is_empty() {
let mut seen = std::collections::HashSet::new();
@@ -2695,59 +2715,7 @@ impl Gpu {
timings.push(("tri_data_mb".into(), (ix.vertices.len() * crate::indexed::VERTEX_BYTES + ix.indices.len() * 12 + ix.gpu_rows().len() * 16 + ix.leaves.len() * crate::indexed::LEAF_BYTES + nodes.len()) as f64 / (1 << 20) as f64));
let (words, region_words, proc_room) = self.upload_words(scene, env_cdf, room.proc_words, room.tris, room.records, timings)?;
let room = EditRoom { proc_words: proc_room, ..room };
- // Density grids: field A of each in the atlas (stacked along z), their data; for a grid with a program, its
- // other textures (A', B, B'), its two half steps and its sources.
- let grids = (!scene.grids.is_empty()).then(|| {
- let dims = [scene.grids.iter().map(|g| g.dims[0]).max().unwrap(), scene.grids.iter().map(|g| g.dims[1]).max().unwrap(), scene.grids.iter().map(|g| g.dims[2]).sum()];
- let atlas = grid_texture(d, "grid atlas", dims, true);
- let atlas_view = atlas.create_view(&Default::default());
- let smp = d.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() });
- let grids = scene
- .grids
- .iter()
- .map(|g| {
- if let Some(data) = &g.data {
- self.write_grid(&atlas, g.z0, g.dims, data);
- }
- let sim = g.program.map(|program| {
- let tex = |label: &str| grid_texture(d, label, g.dims, true).create_view(&Default::default());
- 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 });
- fn tv(binding: u32, v: &wgpu::TextureView) -> wgpu::BindGroupEntry<'_> {
- wgpu::BindGroupEntry { binding, resource: wgpu::BindingResource::TextureView(v) }
- }
- let bg = d.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("grid step"),
- layout: &self.grid_layout,
- entries: &[
- wgpu::BindGroupEntry { binding: 0, resource: u.as_entire_binding() },
- tv(1, src_a),
- tv(2, src_b),
- wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&smp) },
- tv(4, dst_a),
- tv(5, dst_b),
- wgpu::BindGroupEntry { binding: 6, resource: sources.as_entire_binding() },
- ],
- });
- (u, bg)
- };
- let steps = [step(&atlas_view, &b, &a2, &b2), step(&a2, &b2, &atlas_view, &b)];
- let m = &scene.media[g.medium as usize];
- 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, made: g.made, sim }
- })
- .collect::<Vec<_>>();
- let pipeline = grids.iter().any(|g| g.sim.is_some()).then(|| {
- let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("grid sim"), source: wgpu::ShaderSource::Wgsl(grid_sim_source(scene).into()) });
- let layout = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("grid sim"), bind_group_layouts: &[Some(&self.grid_layout)], immediate_size: 0 });
- d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("grid sim"), layout: Some(&layout), module: &module, entry_point: Some("grid_sim"), compilation_options: Default::default(), cache: self.cache() })
- });
- GridsGpu { atlas, pipeline, grids, step: std::cell::Cell::new(0) }
- });
+ let grids = self.make_grids(&scene.grids, &scene.media, &scene.grid_programs);
let grid_view = grids.as_ref().map_or_else(|| self.no_grid_view.clone(), |g| g.atlas.create_view(&Default::default()));
let b_accum = accum.clone();
let b_params = d.create_buffer(&wgpu::BufferDescriptor { label: Some("params"), size: std::mem::size_of::<Params>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
@@ -3436,6 +3404,11 @@ impl Gpu {
/// 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 };
+ self.carry(from, to);
+ }
+
+ /// `carry_grids`, of the grids themselves.
+ fn carry(&self, from: &GridsGpu, to: &GridsGpu) {
let mut e = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("carry grids") });
let mut any = false;
for g in &to.grids {
@@ -3656,6 +3629,148 @@ impl Gpu {
found
}
+ /// The scene's density grids on the GPU: field A of each in the atlas (stacked along z), their data; for a grid
+ /// with a program, its other textures (A', B, B'), its two half steps and its sources; the programs' pipeline.
+ /// `media`: the media table (a grid's program runs in its volume's box); `programs`: every grid program, in the
+ /// order of their numbers. None: no grid.
+ fn make_grids(&self, grids: &[crate::scene::GridBuild], media: &[crate::scene::MediumGpu], programs: &[(String, String, String)]) -> Option<GridsGpu> {
+ if grids.is_empty() {
+ return None;
+ }
+ let d = &self.device;
+ let dims = [grids.iter().map(|g| g.dims[0]).max().unwrap(), grids.iter().map(|g| g.dims[1]).max().unwrap(), grids.iter().map(|g| g.dims[2]).sum()];
+ let atlas = grid_texture(d, "grid atlas", dims, true);
+ let atlas_view = atlas.create_view(&Default::default());
+ let smp = d.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() });
+ let made = grids
+ .iter()
+ .map(|g| {
+ if let Some(data) = &g.data {
+ self.write_grid(&atlas, g.z0, g.dims, data);
+ }
+ let sim = g.program.map(|program| {
+ let tex = |label: &str| grid_texture(d, label, g.dims, true).create_view(&Default::default());
+ 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 });
+ fn tv(binding: u32, v: &wgpu::TextureView) -> wgpu::BindGroupEntry<'_> {
+ wgpu::BindGroupEntry { binding, resource: wgpu::BindingResource::TextureView(v) }
+ }
+ let bg = d.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("grid step"),
+ layout: &self.grid_layout,
+ entries: &[
+ wgpu::BindGroupEntry { binding: 0, resource: u.as_entire_binding() },
+ tv(1, src_a),
+ tv(2, src_b),
+ wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&smp) },
+ tv(4, dst_a),
+ tv(5, dst_b),
+ wgpu::BindGroupEntry { binding: 6, resource: sources.as_entire_binding() },
+ ],
+ });
+ (u, bg)
+ };
+ let steps = [step(&atlas_view, &b, &a2, &b2), step(&a2, &b2, &atlas_view, &b)];
+ let m = &media[g.medium as usize];
+ 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, made: g.made, sim }
+ })
+ .collect::<Vec<_>>();
+ let pipeline = made.iter().any(|g| g.sim.is_some()).then(|| {
+ let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("grid sim"), source: wgpu::ShaderSource::Wgsl(grid_sim_source(programs).into()) });
+ let layout = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("grid sim"), bind_group_layouts: &[Some(&self.grid_layout)], immediate_size: 0 });
+ d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("grid sim"), layout: Some(&layout), module: &module, entry_point: Some("grid_sim"), compilation_options: Default::default(), cache: self.cache() })
+ });
+ let programs = if pipeline.is_some() { programs.to_vec() } else { vec![] };
+ Some(GridsGpu { atlas, pipeline, programs, grids: made, step: std::cell::Cell::new(0) })
+ }
+
+ /// The uploaded scene's density grids as `grids`, in place: a volume with a grid came or went, a grid has other
+ /// cells or another program, a program's code changed. Grids that are the same still take their parameters,
+ /// their volumes and the volumes' placement; else all are made again, and what the programs had simulated goes with the grids that are the same (`carry`).
+ /// Whether they were made again (the atlas is another texture: the bind groups hold the old one).
+ pub fn put_grids(&self, up: &mut Uploaded, grids: &[crate::scene::GridBuild], media: &[crate::scene::MediumGpu], programs: &[(String, String, String)]) -> bool {
+ let same = match &mut up.grids {
+ None => grids.is_empty(),
+ Some(have) => {
+ // (The same grids in the same order lie at the same places.)
+ let same = have.grids.len() == grids.len()
+ && have.grids.iter().zip(grids).all(|(h, g)| (h.id, h.dims, h.made) == (g.id, g.dims, g.made) && h.sim.as_ref().map(|s| s.program) == g.program)
+ && (have.pipeline.is_none() || have.programs == programs);
+ if same {
+ // (And its volume, with the volume's box and customData as the table has them now: its program
+ // runs there.)
+ for (h, g) in have.grids.iter_mut().zip(grids) {
+ h.node = g.node;
+ if let Some(sim) = &mut h.sim {
+ let m = &media[g.medium as usize];
+ (sim.params, sim.placed) = (g.params, std::cell::Cell::new((m.w, m.c)));
+ }
+ }
+ }
+ same
+ }
+ };
+ if same {
+ return false;
+ }
+ let made = self.make_grids(grids, media, programs);
+ if let (Some(from), Some(to)) = (&up.grids, &made) {
+ self.carry(from, to);
+ }
+ up.bg_parts.grid_view = made.as_ref().map_or_else(|| self.no_grid_view.clone(), |g| g.atlas.create_view(&Default::default()));
+ up.grids = made;
+ true
+ }
+
+ /// The scene's density grids as they are now: each one's id, volume node, cells, first layer in the atlas and
+ /// program; the atlas's size.
+ #[cfg(test)]
+ pub fn grids_state(&self, up: &Uploaded) -> (Vec<(u32, u32, [u32; 3], u32, Option<u32>)>, [u32; 3]) {
+ let Some(gs) = &up.grids else { return (vec![], [0; 3]) };
+ let size = gs.atlas.size();
+ (gs.grids.iter().map(|g| (g.id, g.node, g.dims, g.z0, g.sim.as_ref().map(|s| s.program))).collect(), [size.width, size.height, size.depth_or_array_layers])
+ }
+
+ /// Field A of one cell of density grid `id`, read back.
+ #[cfg(test)]
+ pub fn grid_cell(&self, up: &Uploaded, id: u32, cell: [u32; 3]) -> [f32; 4] {
+ let gs = up.grids.as_ref().expect("grids");
+ let g = gs.grids.iter().find(|g| g.id == id).expect("the grid");
+ let to = self.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 8, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ let mut e = self.device.create_command_encoder(&Default::default());
+ e.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo { texture: &gs.atlas, mip_level: 0, origin: wgpu::Origin3d { x: cell[0], y: cell[1], z: g.z0 + cell[2] }, aspect: wgpu::TextureAspect::All },
+ wgpu::TexelCopyBufferInfo { buffer: &to, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: None, rows_per_image: None } },
+ wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
+ );
+ self.queue.submit([e.finish()]);
+ to.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ self.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ let halves: [half::f16; 4] = bytemuck::pod_read_unaligned(&to.slice(..).get_mapped_range().unwrap());
+ halves.map(|h| h.to_f32())
+ }
+
+ /// The media table as `media` (each one's node in `nodes`), in place: volumes that came, went or were set again
+ /// while the scene runs. Whether the table is another buffer now (it grew: the bind groups hold the old one).
+ pub fn put_media(&self, up: &mut Uploaded, media: &[crate::scene::MediumGpu], nodes: Vec<u32>) -> bool {
+ let bytes: &[u8] = bytemuck::cast_slice(media);
+ let grew = bytes.len() as u64 > up.heap.cap(Table::Media);
+ if grew {
+ up.heap.grow(&self.device, &self.queue, Table::Media, bytes.len() as u64);
+ }
+ if !bytes.is_empty() {
+ up.heap.write(&self.queue, Table::Media, 0, bytes);
+ }
+ up.media_hidden = std::cell::RefCell::new(media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect());
+ up.media_nodes = nodes;
+ grew
+ }
+
pub fn set_medium(&self, up: &Uploaded, node: u32, rows: Option<[[f32; 4]; 3]>, custom: Option<[f32; 4]>) {
// (Its grid program runs in the node's box as it is now.)
for sim in up.grids.iter().flat_map(|g| g.grids.iter()).filter(|g| g.node == node).filter_map(|g| g.sim.as_ref()) {
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 0055031..d3fe450 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -761,7 +761,15 @@ impl LiveCore {
let hide = !world.shown(id);
let done = match world.objects.get(&id).map(|o| &o.kind) {
Some(crate::world::Kind::Particles { .. }) => self.g.set_particles_hidden(&self.sc.up, id, hide),
- Some(crate::world::Kind::Volume { shape, .. }) => self.g.set_medium_hidden(&self.sc.up, id, *shape, hide),
+ // (A volume the build left out, for lack of room while hidden: the media table again.)
+ Some(crate::world::Kind::Volume { shape, .. }) => {
+ if !self.g.set_medium_hidden(&self.sc.up, id, *shape, hide) {
+ changes.media = true;
+ }
+ // (What it shadows and dims changes with it: `live_lighting`.)
+ self.lit_changed = self.frame.max(1);
+ true
+ }
// (Its table entry, black while hidden: `Tables::update_light`.)
Some(crate::world::Kind::Light(_)) if self.sc.tables.light_index.contains_key(&id) => {
changes.lights.insert(id);
@@ -780,6 +788,19 @@ impl LiveCore {
if changes.functions && !changes.structural {
self.set_functions(world);
}
+ // Volume functions that came or changed, then the volumes: the media table as the world has them now.
+ if (changes.volume_functions || changes.media) && !changes.structural {
+ match self.set_media(world, changes.volume_functions) {
+ // As after a rebuild: what the volumes shadow and dim changed, the histories are held short and
+ // validated a pixel at a time (`live_lighting`).
+ Ok(()) => self.lit_changed = self.frame.max(1),
+ Err(why) => {
+ self.fallback = Some(format!("volumes that cannot be placed in the media table ({why})"));
+ self.fallbacks += 1;
+ changes.structural = true;
+ }
+ }
+ }
// The textures the new and the changed materials name: those the pages have not got are placed in them now;
// a texture that was replaced has its materials made again.
if !changes.structural && (!changes.new_materials.is_empty() || !changes.materials.is_empty() || !changes.textures.is_empty()) {
@@ -1491,6 +1512,66 @@ impl LiveCore {
self.sc.up.kernel.features = self.kernel_features();
}
+ /// The media table as the world's volumes are now, and the kernel's volume functions where one came or changed
+ /// (`functions`). The table is made whole, as the build makes it: the volumes shown, and the hidden ones while
+ /// the kernel has room for them, in the world's order; each function under the number it has, one the scene had
+ /// not under the next. The kernel's count of them and its media features follow (a first volume's passes are
+ /// made as any variant is). The density grids follow the volumes that name them (`Gpu::put_grids`). Err: a
+ /// volume or a grid a build refuses too (more volumes than the kernel takes, grids over the atlas's limits); the
+ /// caller rebuilds.
+ fn set_media(&mut self, world: &World, functions: bool) -> std::result::Result<(), String> {
+ use crate::world::Kind;
+ let sc = &mut self.sc;
+ if functions {
+ for (name, (code, helpers)) in &world.volume_fns {
+ let f = (name.clone(), code.clone(), helpers.clone());
+ match sc.volume_fns.iter().position(|(k, _, _)| k == name) {
+ Some(k) => sc.volume_fns[k] = f,
+ None => sc.volume_fns.push(f),
+ }
+ }
+ sc.up.kernel = sc.up.kernel.with_volume_functions(&sc.volume_fns);
+ }
+ let volumes: Vec<u32> = world.ordered().into_iter().filter(|id| matches!(world.objects[id].kind, Kind::Volume { .. })).collect();
+ let mut to_show = volumes.iter().filter(|id| world.shown(**id)).count();
+ // (The density grids the volumes name, as the build stacks them: `scene::grid_of`.)
+ let programs: Vec<(String, String, String)> = world.grid_programs.iter().map(|(k, (c, h))| (k.clone(), c.clone(), h.clone())).collect();
+ let (mut media, mut nodes, mut grids) = (vec![], vec![], vec![]);
+ for id in volumes {
+ let o = &world.objects[&id];
+ let Kind::Volume { function, shape, grid, .. } = &o.kind else { continue };
+ let shown = world.shown(id);
+ if !(shown || (world.hidden_built(id) && media.len() + to_show < scene::MAX_MEDIA)) {
+ continue;
+ }
+ if shown {
+ to_show -= 1;
+ }
+ let number = sc.volume_fns.iter().position(|(k, _, _)| k == function).ok_or_else(|| format!("object {}: unknown volume function {function}", o.name))? as u32;
+ let at = match grid {
+ None => [0.0; 2],
+ Some(_) if *shape != 0 => return Err(format!("object {}: a density grid needs a box volume", o.name)),
+ Some(g) => scene::grid_of(world, &mut grids, &programs, *g, id, media.len() as u32).map_err(|e| format!("object {}: {e:#}", o.name))?,
+ };
+ if media.len() >= scene::MAX_MEDIA {
+ return Err(format!("more than {} volumes shown at once", scene::MAX_MEDIA));
+ }
+ media.push(scene::MediumGpu::of(o, world.world_matrix(id), number, shown, at).expect("a volume"));
+ nodes.push(id);
+ }
+ let regridded = self.g.put_grids(&mut sc.up, &grids, &media, &programs);
+ // (As `gpu::instance_features` has them: any medium, a homogeneous one, a grid or a function that reads one.)
+ let reads_grid = !media.is_empty() && sc.volume_fns.iter().any(|(_, code, helpers)| code.contains("vgrid(") || helpers.contains("vgrid("));
+ let bits = if media.is_empty() { 0 } else { gpu::F_MEDIA } | if media.iter().any(|m| m.a[2] != 0) { gpu::F_HMEDIA } else { 0 } | if sc.up.grids.is_some() || reads_grid { gpu::F_GRID } else { 0 };
+ sc.instance_features = sc.instance_features & !(gpu::F_MEDIA | gpu::F_HMEDIA | gpu::F_GRID) | bits;
+ sc.base.time[3] = media.len() as f32;
+ if self.g.put_media(&mut sc.up, &media, nodes) | regridded {
+ self.g.rebind_scene(&mut self.sc.up);
+ }
+ self.sc.up.kernel.features = self.kernel_features();
+ Ok(())
+ }
+
/// The scene's kernel with its material functions as they are now, after the commit's materials are made: where
/// a function came or changed (`changed`), or where the functions of translucent particles' materials are
/// others than the kernel was made with (the translucency pass's dispatch has those alone: a particle's material
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index a319c7f..f1f49a9 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -4537,3 +4537,236 @@ fn a_translucent_particles_material_takes_another_function_in_place() {
w.set_material(5, glow("fc"));
check("a function that comes with the edit", &mut live, &mut w);
}
+
+/// Volumes come, change and go in place, in a scene that had none: a box of haze (a volume function the scene had
+/// not, the scene's first medium), a homogeneous glowing sphere whose function's name sorts before the first's (a
+/// build numbers them by name, the view in the order they came), a third (the table grows), the first set again
+/// with other parameters, moved where it stood still, the second hidden (the first set again beside it) and shown, each removed. After each: no
+/// rebuild, the kernel's count of media and its features are a build's of the edited world, the media are that
+/// build's nodes, and so is the picture.
+#[test]
+fn volumes_come_and_go_in_place() {
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));
+ let function = |name: &str, body: &str| format!("fn vf_{name}(i: VIn, p: array<vec4<f32>, 8>) -> VOut {{\n var o = VOut(0.0, vec3<f32>(1.0), vec3<f32>(0.0));\n {body}\n return o;\n}}\n");
+ let volume = |function: &str, shape: u32, majorant: f32, homogeneous: bool, params: Vec<f32>| Kind::Volume { function: function.into(), params, shape, majorant, g: 0.0, homogeneous, animated: false, grid: None };
+ let mut w = world();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ assert_eq!((live.sc.up.kernel.features & gpu::F_MEDIA, live.sc.base.time[3]), (0, 0.0), "a scene without a medium");
+ let last = std::cell::RefCell::new(picture(&mut live, 24));
+ let check = |what: &str, live: &mut LiveCore, w: &mut World, nodes: &[u32]| {
+ live.lit_changed = 0;
+ assert!(!live.commit(w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert!(live.live_lighting(), "{what}: the lighting changed, as after a rebuild (the histories are held short)");
+ let mut fresh = open(w).unwrap();
+ assert_eq!((&live.sc.up.media_nodes[..], live.sc.base.time[3]), (nodes, nodes.len() as f32), "{what}: the media and the kernel's count of them");
+ assert_eq!((&fresh.sc.up.media_nodes[..], fresh.sc.base.time[3]), (nodes, nodes.len() as f32), "{what}: a build's");
+ assert_eq!(*live.sc.up.media_hidden.borrow(), *fresh.sc.up.media_hidden.borrow(), "{what}: which are hidden");
+ let media = gpu::F_MEDIA | gpu::F_HMEDIA | gpu::F_GRID;
+ assert_eq!(live.sc.up.kernel.features & media, fresh.sc.up.kernel.features & media, "{what}: the kernel's media features");
+ forget(live);
+ let (a, b) = (picture(live, 48), picture(&mut fresh, 48));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ assert!(apart(&last.borrow(), &b) > 0.1, "{what}: the picture is {:.2} steps from the one before", apart(&last.borrow(), &b));
+ *last.borrow_mut() = b;
+ };
+ // The scene's first medium, of a function it had not.
+ w.set_volume_fn("haze", function("haze", "o.extinction = p[0].x; o.albedo = vec3<f32>(0.9, 0.6, 0.3);"), String::new());
+ w.set_object(40, "haze".into(), None, volume("haze", 0, 4.0, false, vec![2.5]), true, false).unwrap();
+ w.set_transform(40, Vec3::new(-0.3, 0.0, 1.2), glam::Quat::IDENTITY, Vec3::splat(0.9)).unwrap();
+ check("the scene's first volume", &mut live, &mut w, &[40]);
+ assert_ne!(live.sc.up.kernel.features & gpu::F_MEDIA, 0);
+ // A homogeneous sphere that glows; its function before the first by name.
+ w.set_volume_fn("aglow", function("aglow", "o.extinction = 1.0; o.albedo = vec3<f32>(0.2); o.emission = vec3<f32>(0.2, 1.5, 3.0);"), String::new());
+ w.set_object(41, "glow".into(), None, volume("aglow", 1, 1.0, true, vec![]), true, false).unwrap();
+ w.set_transform(41, Vec3::new(0.6, -0.3, 1.0), glam::Quat::IDENTITY, Vec3::splat(0.7)).unwrap();
+ check("a second volume, homogeneous", &mut live, &mut w, &[40, 41]);
+ assert_ne!(live.sc.up.kernel.features & gpu::F_HMEDIA, 0);
+ // A third: more than the table had room for (it is another buffer now, which the kernel reads).
+ let room = live.sc.up.heap.cap(crate::heap::Table::Media);
+ w.set_object(42, "more haze".into(), None, volume("haze", 0, 4.0, false, vec![3.0]), true, false).unwrap();
+ w.set_transform(42, Vec3::new(0.0, 0.55, 1.6), glam::Quat::IDENTITY, Vec3::splat(0.5)).unwrap();
+ check("a third volume", &mut live, &mut w, &[40, 41, 42]);
+ assert!(live.sc.up.heap.cap(crate::heap::Table::Media) > room, "the table grew");
+ w.remove(42);
+ check("the third volume removed", &mut live, &mut w, &[40, 41]);
+ // The first set again: thinner.
+ w.set_object(40, "haze".into(), None, volume("haze", 0, 4.0, false, vec![0.6]), true, false).unwrap();
+ assert!(!w.changes.structural, "a volume set again: the media table's");
+ check("the first volume set again", &mut live, &mut w, &[40, 41]);
+ // Moved, where it stood still.
+ w.set_transform(40, Vec3::new(0.2, 0.4, 1.4), glam::Quat::from_rotation_y(0.5), Vec3::splat(0.9)).unwrap();
+ assert!(!w.changes.structural && w.changes.promoted.is_empty(), "a still volume's move: the media table's");
+ check("the first volume moved", &mut live, &mut w, &[40, 41]);
+ // Hidden and shown: its entry keeps its place.
+ w.set_visible(41, false).unwrap();
+ check("the second volume hidden", &mut live, &mut w, &[40, 41]);
+ // The first set again beside it: the table is made whole, the hidden one without its shape still.
+ w.set_object(40, "haze".into(), None, volume("haze", 0, 4.0, false, vec![1.8]), true, false).unwrap();
+ check("a volume set again beside a hidden one", &mut live, &mut w, &[40, 41]);
+ w.set_visible(41, true).unwrap();
+ check("the second volume shown", &mut live, &mut w, &[40, 41]);
+ // The function's code changed.
+ w.set_volume_fn("haze", function("haze", "o.extinction = p[0].x * 3.0; o.albedo = vec3<f32>(0.3, 0.6, 0.9);"), String::new());
+ check("a volume function's code changed", &mut live, &mut w, &[40, 41]);
+ // Each removed.
+ w.remove(40);
+ check("the first volume removed", &mut live, &mut w, &[41]);
+ w.remove(41);
+ check("every volume removed", &mut live, &mut w, &[]);
+ assert_eq!(live.sc.up.kernel.features & (gpu::F_MEDIA | gpu::F_HMEDIA), 0, "no medium: the kernel without its media code");
+}
+
+/// Density grids come, change and go in place with the volumes that name them, in a scene that had none: a volume
+/// of a grid the scene had not (the atlas made), a second grid of other cells (the atlas made again, both stacked),
+/// the first with another size, new data; a grid with a program (the grids' pass made), its parameters (the same
+/// grid still: nothing is made again), another grid beside it and the program's code changed (what it had simulated
+/// stays), a program whose name comes first (the programs' numbers move), a simulated grid's volume moved (its
+/// program runs in the box as it is now), a second and a third volume of one grid and the first of them removed
+/// each time (the grid is the next one's, its program runs in that one's box), every one removed. After each: no rebuild; the
+/// grids, the atlas, the media and the kernel's media features are a build's of the edited world, and so is the
+/// picture.
+#[test]
+fn density_grids_come_and_change_in_place() {
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));
+ let volume = |grid: u32, density: f32| Kind::Volume { function: "smoke".into(), params: vec![density], shape: 0, majorant: 8.0, g: 0.0, homogeneous: false, animated: false, grid: Some(grid) };
+ let place = |w: &mut World, id: u32, grid: u32, density: f32, at: Vec3, size: f32| {
+ w.set_object(id, format!("smoke {id}"), None, volume(grid, density), true, false).unwrap();
+ w.set_transform(id, at, glam::Quat::IDENTITY, Vec3::splat(size)).unwrap();
+ };
+ let mut w = world();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ assert_eq!(live.g.grids_state(&live.sc.up).0, vec![], "a scene without a grid");
+ let last = std::cell::RefCell::new(picture(&mut live, 24));
+ // (The commit alone: what the grids hold before a frame runs their programs.)
+ let commit = |what: &str, live: &mut LiveCore, w: &mut World| {
+ // (An edit of the scene, not a grid's new data alone, which is uploaded: the lighting changed, as after a
+ // rebuild, and the histories are held short.)
+ let edit = w.changes.any();
+ live.lit_changed = 0;
+ assert!(!live.commit(w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert_eq!(live.live_lighting(), edit, "{what}: whether the lighting changed");
+ };
+ let check = |what: &str, live: &mut LiveCore, w: &mut World, nodes: &[u32]| {
+ commit(what, live, w);
+ let mut fresh = open(w).unwrap();
+ assert_eq!(live.g.grids_state(&live.sc.up), fresh.g.grids_state(&fresh.sc.up), "{what}: the grids and their atlas");
+ assert_eq!((&live.sc.up.media_nodes[..], live.sc.base.time[3]), (nodes, nodes.len() as f32), "{what}: the media and the kernel's count of them");
+ assert_eq!(&fresh.sc.up.media_nodes[..], nodes, "{what}: a build's");
+ let media = gpu::F_MEDIA | gpu::F_HMEDIA | gpu::F_GRID;
+ assert_eq!(live.sc.up.kernel.features & media, fresh.sc.up.kernel.features & media, "{what}: the kernel's media features");
+ assert_eq!(gpu::Gpu::has_grid_sim(&live.sc.up), gpu::Gpu::has_grid_sim(&fresh.sc.up), "{what}: whether the grids' pass runs");
+ // (The programs run to where they stay in both, then the pictures: a build's grids start from their data.)
+ for c in [&mut *live, &mut fresh] {
+ picture(c, 48);
+ forget(c);
+ }
+ let (a, b) = (picture(live, 48), picture(&mut fresh, 48));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ assert!(apart(&last.borrow(), &b) > 0.1, "{what}: the picture is {:.2} steps from the one before", apart(&last.borrow(), &b));
+ *last.borrow_mut() = b;
+ };
+ let program = |name: &str, body: &str| format!("fn gp_{name}(s_in: Cell, i: CIn, p: array<vec4<f32>, 8>) -> Cell {{\n var s = s_in;\n {body}\n return s;\n}}\n");
+ let cells = |dims: [u32; 3], f: &dyn Fn([u32; 3]) -> f32| -> Vec<f32> { (0..dims[2]).flat_map(|z| (0..dims[1]).flat_map(move |y| (0..dims[0]).map(move |x| [x, y, z]))).map(f).collect() };
+ // The scene's first grid: dense in its left half.
+ w.set_volume_fn("smoke", "fn vf_smoke(i: VIn, p: array<vec4<f32>, 8>) -> VOut {\n var o = VOut(0.0, vec3<f32>(0.9, 0.6, 0.3), vec3<f32>(0.0));\n o.extinction = p[0].x * vgrid(i, i.lp).x;\n return o;\n}\n".into(), String::new());
+ w.set_grid(1, [4, 4, 4], 1, Some(&cells([4, 4, 4], &|c| (c[0] < 2) as u32 as f32)), None).unwrap();
+ place(&mut w, 40, 1, 4.0, Vec3::new(-0.5, 0.0, 1.2), 0.9);
+ assert!(!w.changes.structural, "a new grid and its volume: the media table's");
+ check("the scene's first grid", &mut live, &mut w, &[40]);
+ assert_ne!(live.sc.up.kernel.features & gpu::F_GRID, 0);
+ assert_eq!(live.g.grid_cell(&live.sc.up, 1, [1, 2, 3]), [1.0, 0.0, 0.0, 0.0], "its data");
+ assert_eq!(live.g.grid_cell(&live.sc.up, 1, [2, 2, 3]), [0.0; 4]);
+ // A second, of other cells: the atlas is wider now, the first below it.
+ w.set_grid(2, [8, 2, 2], 1, Some(&[1.0; 32]), None).unwrap();
+ place(&mut w, 41, 2, 3.0, Vec3::new(0.6, -0.3, 1.0), 0.7);
+ check("a second grid", &mut live, &mut w, &[40, 41]);
+ assert_eq!(live.g.grids_state(&live.sc.up).1, [8, 4, 6], "an atlas of both");
+ assert_eq!(live.g.grid_cell(&live.sc.up, 1, [1, 2, 3]), [1.0, 0.0, 0.0, 0.0], "the first's data in the new atlas");
+ // The first with another size: dense in its upper half.
+ w.set_grid(1, [2, 6, 2], 1, Some(&cells([2, 6, 2], &|c| (c[1] >= 3) as u32 as f32)), None).unwrap();
+ check("a grid of another size", &mut live, &mut w, &[40, 41]);
+ // New data: uploaded, nothing made again.
+ w.set_grid(2, [8, 2, 2], 1, Some(&[0.1; 32]), None).unwrap();
+ assert!(!w.changes.media && w.grid_dirty.contains(&2));
+ check("new data", &mut live, &mut w, &[40, 41]);
+ // A grid with a program: it fills up to its first parameter.
+ w.set_grid_program("fill", program("fill", "s.a.x = clamp(s.a.x + 0.05, p[0].y, p[0].x);"), String::new());
+ w.set_grid(3, [4, 4, 4], 1, None, Some(("fill".into(), vec![1.0, 0.0]))).unwrap();
+ place(&mut w, 42, 3, 3.0, Vec3::new(0.1, 0.5, 1.4), 0.6);
+ check("a grid with a program", &mut live, &mut w, &[40, 41, 42]);
+ assert!(gpu::Gpu::has_grid_sim(&live.sc.up));
+ assert_eq!(live.g.grid_cell(&live.sc.up, 3, [1, 1, 1])[0], 1.0, "filled");
+ // Its parameters: the same grid still.
+ w.set_grid(3, [4, 4, 4], 1, None, Some(("fill".into(), vec![2.0, 0.0]))).unwrap();
+ commit("a program's parameters", &mut live, &mut w);
+ assert_eq!(live.g.grid_cell(&live.sc.up, 3, [1, 1, 1])[0], 1.0, "what it had simulated stays");
+ check("a program's parameters", &mut live, &mut w, &[40, 41, 42]);
+ assert_eq!(live.g.grid_cell(&live.sc.up, 3, [1, 1, 1])[0], 2.0, "filled to the new parameter");
+ // Another grid beside it: all are made again, and what the program had simulated goes with its grid.
+ w.set_grid(4, [2, 2, 2], 1, Some(&[1.0; 8]), None).unwrap();
+ place(&mut w, 43, 4, 4.0, Vec3::new(-0.6, -0.5, 1.6), 0.5);
+ commit("another grid beside a simulated one", &mut live, &mut w);
+ assert_eq!(live.g.grid_cell(&live.sc.up, 3, [1, 1, 1])[0], 2.0, "what it had simulated is in the new atlas");
+ check("another grid beside a simulated one", &mut live, &mut w, &[40, 41, 42, 43]);
+ // The program's code: it empties now (down to its second parameter).
+ w.set_grid_program("fill", program("fill", "s.a.x = clamp(s.a.x - 0.05, p[0].y, p[0].x);"), String::new());
+ assert!(!w.changes.structural, "a grid program's code: the media table's");
+ commit("a program's code", &mut live, &mut w);
+ assert_eq!(live.g.grid_cell(&live.sc.up, 3, [1, 1, 1])[0], 2.0, "what it had simulated stays");
+ check("a program's code", &mut live, &mut w, &[40, 41, 42, 43]);
+ assert_eq!(live.g.grid_cell(&live.sc.up, 3, [1, 1, 1])[0], 0.0, "emptied");
+ // A program whose name comes first (the others' numbers move), and the grid's floor raised: it is its own
+ // program that runs on it still.
+ w.set_grid_program("an_earlier", program("an_earlier", "s.a.x = 7.0;"), String::new());
+ w.set_grid(3, [4, 4, 4], 1, None, Some(("fill".into(), vec![2.0, 1.5]))).unwrap();
+ check("a program whose name comes first", &mut live, &mut w, &[40, 41, 42, 43]);
+ assert_eq!(live.g.grid_cell(&live.sc.up, 3, [1, 1, 1])[0], 1.5, "its own program");
+ // A program that reads the world (dense where x > 0.3 m), then its volume moved, where it stood still.
+ let row = |live: &LiveCore| [0, 1, 2, 3].map(|x| live.g.grid_cell(&live.sc.up, 3, [x, 1, 1])[0]);
+ w.set_grid_program("fill", program("fill", "s.a.x = select(p[0].y, p[0].x, i.p.x > 0.3);"), String::new());
+ w.set_grid(3, [4, 4, 4], 1, None, Some(("fill".into(), vec![2.0, 0.0]))).unwrap();
+ check("a program that reads the world", &mut live, &mut w, &[40, 41, 42, 43]);
+ assert_eq!(row(&live), [0.0, 0.0, 0.0, 2.0], "the box's last quarter is past x = 0.3");
+ w.set_transform(42, Vec3::new(0.6, 0.5, 1.4), glam::Quat::IDENTITY, Vec3::splat(0.6)).unwrap();
+ assert!(!w.changes.structural && w.changes.promoted.is_empty(), "a still volume's move: the media table's");
+ check("a simulated grid's volume moved", &mut live, &mut w, &[40, 41, 42, 43]);
+ assert_eq!(row(&live), [2.0; 4], "its program runs in the box as it is now");
+ // A second volume of the simulated grid, then the first of them removed: the grid is the other's now, and its
+ // program runs in the other's box (half of it past x = 0.3).
+ place(&mut w, 44, 3, 3.0, Vec3::new(0.3, -0.55, 1.8), 0.5);
+ check("a second volume of one grid", &mut live, &mut w, &[40, 41, 42, 43, 44]);
+ assert_eq!(row(&live), [2.0; 4], "the first's box still");
+ w.remove(42);
+ commit("the first volume of a grid removed", &mut live, &mut w);
+ assert_eq!(row(&live), [2.0; 4], "what it had simulated stays");
+ check("the first volume of a grid removed", &mut live, &mut w, &[40, 41, 43, 44]);
+ assert_eq!(row(&live), [0.0, 0.0, 2.0, 2.0], "the other's box");
+ // A third volume of it after the second, and the second removed: the grids lie as they did, and the grid is the
+ // third's (its box is all past x = 0.3).
+ place(&mut w, 45, 3, 3.0, Vec3::new(0.75, 0.0, 1.9), 0.4);
+ check("a third volume of one grid", &mut live, &mut w, &[40, 41, 43, 44, 45]);
+ assert_eq!(row(&live), [0.0, 0.0, 2.0, 2.0], "the second's box still");
+ w.remove(44);
+ check("a grid's volume removed, the grids lying as they did", &mut live, &mut w, &[40, 41, 43, 45]);
+ assert_eq!(row(&live), [2.0; 4], "the third's box");
+ // The simulated grid's last volume removed: no program runs.
+ w.remove(45);
+ check("the simulated grid's volume removed", &mut live, &mut w, &[40, 41, 43]);
+ assert!(!gpu::Gpu::has_grid_sim(&live.sc.up));
+ // Every one removed.
+ for id in [40, 41, 43] {
+ w.remove(id);
+ }
+ check("every volume removed", &mut live, &mut w, &[]);
+ assert_eq!((live.g.grids_state(&live.sc.up).0, live.sc.up.kernel.features & (gpu::F_MEDIA | gpu::F_GRID)), (vec![], 0), "no grid: the kernel without its media code");
+}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 5758add..f7582b5 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -65,6 +65,9 @@ pub(super) struct LoadedScene {
pub(super) translucent_mats: Vec<u32>,
/// The functions of those materials the scene's kernel was made with (`LiveCore::remake_functions`).
pub(super) translucent_used: std::collections::BTreeSet<i32>,
+ /// The scene's volume functions (name, code, helpers), each at its number: the build's by name, one that came
+ /// while the scene runs after them (`set_volume_functions`).
+ pub(super) volume_fns: Vec<(String, String, String)>,
/// Where in-place geometry edits write next (`edit_geometry`); a rebuild starts it afresh.
pub(super) edit: EditState,
/// Power edits' emitter rebuilds on a worker (`EmitterWorker`), for scenes with many emitters.
@@ -250,6 +253,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));
let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);
let shaders = sc.shaders.clone();
+ let volume_fns = sc.volume_fns.clone();
let mut translucent_mats: Vec<u32> = sc.trans_attrs.iter().map(|a| a.uv[3].to_bits()).collect();
translucent_mats.sort_unstable();
translucent_mats.dedup();
@@ -337,5 +341,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
verts: Holes::new(vertices, vertices + room.tris * 3),
free_skinned: vec![],
};
- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, dynamic, edit, emit, mat_runs, tri_order, codes_sent: vec![] }, view, env))
+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, dynamic, edit, emit, mat_runs, tri_order, codes_sent: vec![] }, view, env))
}
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index ba9457b..fd39e99 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -1020,8 +1020,8 @@ pub struct Skinned {
}
/// pathtrace.wgsl `Medium`: world -> local affine rows (the unit box / sphere's space), (function, shape or
-/// `MEDIUM_HIDDEN`, homogeneous, animated),
-/// (majorant 1/m, HG anisotropy, -, -), the node's customData, 32 parameter floats.
+/// `MEDIUM_HIDDEN`, homogeneous, animated), (majorant 1/m, HG anisotropy, its density grid's first layer in the atlas
+/// and its cells, as bits: 0 without one), the node's customData, 32 parameter floats.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct MediumGpu {
@@ -1049,6 +1049,51 @@ pub struct GridBuild {
pub made: u32,
}
+/// Where density grid `gid` lies in the atlas, as a medium's record has it (b.zw: its first layer and its cells, as
+/// bits). The first volume that names a grid has it built (`grids`: stacked along z in the order they come; `node`
+/// and `medium`: that volume's), its program by its rank among `programs`. The build and the live view's media
+/// table both come here.
+pub fn grid_of(w: &World, grids: &mut Vec<GridBuild>, programs: &[(String, String, String)], gid: u32, node: u32, medium: u32) -> Result<[f32; 2]> {
+ let k = match grids.iter().position(|b| b.id == gid) {
+ Some(k) => k,
+ None => {
+ let dg = w.grids.get(&gid).ok_or_else(|| anyhow!("unknown density grid {gid}"))?;
+ let program = match &dg.program {
+ Some((name, _)) => Some(programs.iter().position(|(k, _, _)| k == name).ok_or_else(|| anyhow!("unknown grid program {name}"))? as u32),
+ None => None,
+ };
+ let mut gp = [0.0f32; 32];
+ for (k, v) in dg.program.iter().flat_map(|(_, p)| p.iter()).take(32).enumerate() {
+ gp[k] = *v;
+ }
+ let z0 = grids.iter().map(|b| b.dims[2]).sum::<u32>();
+ let cells = grids.iter().map(|b| b.dims).chain([dg.dims]).map(|d| d.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!("the scene's density grids exceed {} cells or {} layers along z together (or differ too much in width and height)", 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, medium, made: dg.made });
+ grids.len() - 1
+ }
+ };
+ let b = &grids[k];
+ Ok([f32::from_bits(b.z0), f32::from_bits(b.dims[0] | b.dims[1] << 10 | b.dims[2] << 20)])
+}
+
+impl MediumGpu {
+ /// A volume's record: the object `o` (a `Kind::Volume`) placed by `m`, its function's number, whether it is shown
+ /// (a hidden one is built with no shape, to be shown in place), and its density grid's place (`grid`: b.zw).
+ pub fn of(o: &world::Object, m: Mat4, function: u32, shown: bool, grid: [f32; 2]) -> Option<MediumGpu> {
+ let Kind::Volume { params, shape, majorant, g, homogeneous, animated, .. } = &o.kind else { return None };
+ let mut p = [0.0f32; 32];
+ for (k, v) in params.iter().take(32).enumerate() {
+ p[k] = *v;
+ }
+ Some(MediumGpu { w: medium_rows(m), a: [function, if shown { *shape } else { MEDIUM_HIDDEN }, *homogeneous as u32, *animated as u32], b: [majorant.max(0.0), g.clamp(-0.99, 0.99), grid[0], grid[1]], c: o.custom, p })
+ }
+}
+
/// The world -> local rows of a medium whose node has world matrix `m` (pathtrace.wgsl `Medium.w0..w2`).
pub fn medium_rows(m: glam::Mat4) -> [[f32; 4]; 3] {
let inv = m.inverse();
@@ -2093,51 +2138,23 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
},
// (Hidden by its own `visible`: built while the kernel has room after the volumes shown, with no shape,
// so that showing it is in place: gpu.rs `set_medium_hidden`.)
- Kind::Volume { function, params, shape, majorant, g, homogeneous, animated, grid } if shown || (w.hidden_built(*id) && media.len() + media_to_show < MAX_MEDIA) => {
+ Kind::Volume { function, shape, grid, .. } if shown || (w.hidden_built(*id) && media.len() + media_to_show < MAX_MEDIA) => {
if shown {
media_to_show -= 1;
}
let func = volume_fns.iter().position(|(k, _, _)| k == function).ok_or_else(|| anyhow!("object {}: unknown volume function {function}", n.name))? as u32;
- let mut p = [0.0f32; 32];
- for (k, v) in params.iter().take(32).enumerate() {
- p[k] = *v;
- }
// Its density grid: where it lies in the atlas and its cells, as bits in b.zw (pathtrace.wgsl `vgrid`).
let mut at = [0.0f32; 2];
if let Some(gid) = grid {
- let dg = w.grids.get(gid).ok_or_else(|| anyhow!("object {}: unknown density grid {gid}", n.name))?;
if *shape != 0 {
return Err(anyhow!("object {}: a density grid needs a box volume", n.name));
}
- let k = match grids.iter().position(|b| b.id == *gid) {
- Some(k) => k,
- None => {
- let program = match &dg.program {
- Some((name, _)) => Some(grid_programs.iter().position(|(k, _, _)| k == name).ok_or_else(|| anyhow!("object {}: unknown grid program {name}", n.name))? as u32),
- None => None,
- };
- let mut gp = [0.0f32; 32];
- for (k, v) in dg.program.iter().flat_map(|(_, p)| p.iter()).take(32).enumerate() {
- 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, 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, made: dg.made });
- grids.len() - 1
- }
- };
- let b = &grids[k];
- at = [f32::from_bits(b.z0), f32::from_bits(b.dims[0] | b.dims[1] << 10 | b.dims[2] << 20)];
+ at = grid_of(w, &mut grids, &grid_programs, *gid, *id, media.len() as u32).with_context(|| format!("object {}", n.name))?;
}
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, if shown { *shape } else { MEDIUM_HIDDEN }, *homogeneous as u32, *animated as u32], b: [majorant.max(0.0), g.clamp(-0.99, 0.99), at[0], at[1]], c: n.custom, p });
+ media.push(MediumGpu::of(n, m, func, shown, at).expect("a volume"));
media_nodes.push(*id);
}
Kind::Procedural { .. } if shown => {
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 5dc2d94..0c16885 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -289,6 +289,10 @@ pub struct Changes {
pub textures: HashSet<u32>,
/// A material function came or changed (`World::set_shader`): the kernel's code.
pub functions: bool,
+ /// A volume function came or changed (`World::set_volume_fn`): the kernel's code.
+ pub volume_functions: bool,
+ /// A volume came, went, was set again, or moved for the first time: the media table is made again from the world.
+ pub media: bool,
/// Objects whose light parameters changed.
pub lights: HashSet<u32>,
pub powers: HashSet<u32>,
@@ -338,7 +342,7 @@ pub struct Changes {
impl Changes {
pub fn any(&self) -> bool {
- self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.textures.is_empty() || self.functions || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.view || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
+ self.structural || !self.shown.is_empty() || !self.new_materials.is_empty() || !self.materials.is_empty() || !self.textures.is_empty() || self.functions || self.volume_functions || self.media || !self.lights.is_empty() || !self.powers.is_empty() || !self.customs.is_empty() || self.environment || self.camera || self.sun || self.view || self.settings || !self.poses.is_empty() || !self.moved.is_empty() || !self.instanced.is_empty() || self.edits()
}
/// Geometry edits are pending (`geometries`, `added`, `removed`).
pub fn edits(&self) -> bool {
@@ -623,6 +627,8 @@ impl World {
// A camera, new or set again as one under the same parent: nothing is built from it; the view takes it if
// it is the scene's.
let filmed = matches!(kind, Kind::Camera(_)) && self.objects.get(&id).is_none_or(|o| matches!(o.kind, Kind::Camera(_)) && o.parent == parent);
+ // A volume, new or set again as one under the same parent: an entry of the media table, in place.
+ let misted = matches!(kind, Kind::Volume { .. }) && self.objects.get(&id).is_none_or(|o| matches!(o.kind, Kind::Volume { .. }) && o.parent == parent);
let was_parent = self.objects.get(&id).map(|o| o.parent);
if was_parent != Some(parent) {
if let Some(Some(p)) = was_parent {
@@ -648,6 +654,8 @@ impl World {
} else if grouped {
} else if filmed {
self.changes.camera |= self.settings.camera == Some(id);
+ } else if misted {
+ self.changes.media = true;
} else {
if std::env::var("THREERT_EDIT_LOG").is_ok_and(|v| v == "1") {
let o = &self.objects[&id];
@@ -776,6 +784,9 @@ impl World {
self.changes.sun = true;
} else if matches!(o.kind, Kind::Camera(_)) && self.leaf(id) {
// (A camera that is not the scene's: nothing is built from it.)
+ } else if matches!(o.kind, Kind::Volume { .. }) && self.leaf(id) {
+ // A volume is its entry of the media table: placed again.
+ self.changes.media = true;
} else {
// Fixed geometry moved: from now on it is movable. A mesh, a still model, or a group, is its instances' to move
// (`Changes::started`); anything else rebuilds once, to set its triangles apart.
@@ -1054,13 +1065,18 @@ impl World {
let alone = |o: &Object| doomed.len() == 1 && matches!(o.kind, Kind::Instanced { procedural: false, .. } | Kind::Model { .. });
// (So does a camera that is not the scene's.)
let lit: Vec<bool> = doomed.iter().map(|d| self.objects.get(d).is_some_and(|o| self.table_light(*d, &o.kind))).collect();
+ // (And a volume: its entry of the media table goes.)
let spare = |d: &u32, o: &Object| matches!(o.kind, Kind::Camera(_)) && self.settings.camera != Some(*d);
- if doomed.iter().zip(&lit).all(|(d, lit)| self.objects.get(d).is_some_and(|o| edits_in_place(&o.kind) || alone(o) || matches!(o.kind, Kind::Group) || *lit || spare(d, o))) {
+ let mist = |o: &Object| matches!(o.kind, Kind::Volume { .. });
+ if doomed.iter().zip(&lit).all(|(d, lit)| self.objects.get(d).is_some_and(|o| edits_in_place(&o.kind) || alone(o) || matches!(o.kind, Kind::Group) || *lit || spare(d, o) || mist(o))) {
for (d, lit) in doomed.iter().zip(&lit) {
self.instanced.remove(d);
if *lit {
self.objects.remove(d);
self.changes.lights.insert(*d);
+ } else if self.objects.get(d).is_some_and(mist) {
+ self.objects.remove(d);
+ self.changes.media = true;
} else if self.objects.remove(d).is_some_and(|o| !matches!(o.kind, Kind::Group | Kind::Camera(_))) && !self.changes.added.remove(d) {
self.changes.removed.insert(*d);
}
@@ -1178,7 +1194,8 @@ impl World {
return;
}
self.volume_fns.insert(name.to_string(), (code, helpers));
- mark_structural(&mut self.changes, line!());
+ // (The kernel's code, in place: as a material function's, `set_shader`.)
+ self.changes.volume_functions = true;
}
pub fn set_grid_program(&mut self, name: &str, code: String, helpers: String) {
@@ -1186,11 +1203,12 @@ impl World {
return;
}
self.grid_programs.insert(name.to_string(), (code, helpers));
- mark_structural(&mut self.changes, line!());
+ // (The grids' pass, in place: made again with the media table.)
+ self.changes.media = true;
}
/// Creates or replaces a density grid. New data for a grid of the same size and program is uploaded in place; a
- /// new grid, another size or another program rebuilds the scene.
+ /// new grid, another size or another program has the scene's grids made again with the media table.
pub fn set_grid(&mut self, id: u32, dims: [u32; 3], channels: u32, data: Option<&[f32]>, program: Option<(String, Vec<f32>)>) -> Result<()> {
let cells = dims.iter().map(|&d| d as u64).product::<u64>();
if dims.iter().any(|&d| d == 0 || d > GRID_MAX_AXIS) || cells > GRID_MAX_CELLS {
@@ -1226,12 +1244,12 @@ impl World {
self.grid_dirty.insert(id);
}
} else {
- mark_structural(&mut self.changes, line!());
+ self.changes.media = true;
}
// (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 };
- // 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).
+ // The same grid still, for what its program has simulated: its size and its program's name (with new
+ // parameters 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,
_ => {
@@ -1383,9 +1401,10 @@ mod tests {
assert!(c.poses.contains(&2) && c.moved.contains(&2) && c.shown.contains(&2), "the other's changes are kept");
}
- /// Density grids: sizes and data are checked; a new grid, another size or another program rebuilds the scene, new
- /// data for the same grid is uploaded in place (a grid sent again without data keeps what it had); sources go only
- /// to volumes with a grid, 12 finite floats each, at most GRID_MAX_SOURCES pending.
+ /// Density grids: sizes and data are checked; a new grid, another size, another program or other parameters are
+ /// the media table's change (the grids are made again in place), new data for the same grid is uploaded in place
+ /// (a grid sent again without data keeps what it had); sources go only to volumes with a grid, 12 finite floats
+ /// each, at most GRID_MAX_SOURCES pending.
#[test]
fn density_grids_are_checked_and_updated_in_place() {
let mut w = World::default();
@@ -1398,23 +1417,32 @@ mod tests {
assert!(w.grids.is_empty());
w.take_changes();
w.set_grid(1, [2, 2, 2], 1, Some(&[0.5; 8]), None).unwrap();
- assert!(w.take_changes().structural, "a new grid");
+ let media = |w: &mut World| {
+ let c = w.take_changes();
+ assert!(!c.structural, "no rebuild");
+ c.media
+ };
+ assert!(media(&mut w), "a new grid");
assert_eq!(w.grids[&1].data.as_ref().unwrap()[..5], [0.5, 0.0, 0.0, 0.0, 0.5], "one channel: A's first");
w.set_grid(1, [2, 2, 2], 4, Some(&[2.0; 32]), None).unwrap();
- assert!(!w.take_changes().structural && w.grid_dirty.contains(&1), "new data: in place");
+ assert!(!media(&mut w) && w.grid_dirty.contains(&1), "new data: uploaded in place");
w.grid_dirty.clear();
w.set_grid(1, [2, 2, 2], 1, None, None).unwrap();
- assert!(!w.take_changes().structural && w.grid_dirty.is_empty() && w.grids[&1].data.as_ref().unwrap()[1] == 2.0, "no data: kept");
+ assert!(!media(&mut w) && 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");
+ assert!(media(&mut w), "another program");
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)");
+ assert!(media(&mut w) && w.grids[&1].made == made, "new parameters; it is the same grid still (what it simulated stays)");
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");
+ assert!(media(&mut w) && w.grids[&1].made != made, "another size");
+ w.set_grid_program("q", "s.a.x = 1.0;".into(), String::new());
+ assert!(media(&mut w), "a grid program's code");
+ w.set_grid_program("q", "s.a.x = 1.0;".into(), String::new());
+ assert!(!media(&mut w), "the same code again");
// 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();