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.

Materials are edited in place through the rows (#172)

Yujia0f2da2734ab6
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 428650e..460e214 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2776,6 +2776,35 @@ 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).
+**Materials are edited through the rows (2026-11-19, the material on the instance, third part).** With a
+material on its instances' rows, what changes one is no longer the triangles' business. In place now, each a
+rebuild before:
+- a mesh of several materials added, re-created, given another geometry or other materials: its mesh made with its
+ geometry's sections, placed by the code that places a mesh of one material (`edit_geometry`);
+- a material that turns glass or stops being glass, becomes a cutout or stops being one: the rows, the record's
+ bits and the shadow mask of every instance with a row of it (`Tables::reclassed`, live/edits.rs
+ `remake_classes`);
+- a material of any class made after the build (`Tables::add_materials`);
+- a material that starts emitting on any instance, a mesh's or an instanced object's copies, one made after the
+ build too (`add_material_emitters`, by the instances' rows);
+- an instanced object given another material: its copies' rows (`update_instanced`);
+- a mesh an edit places while it is hidden or has no size: an instance no ray sees, as the build has it.
+The sets that said which materials were triangles' go (`fixed_mats`, `mesh_mats`). Software traversal keeps each
+pool triangle's section and its index in it (`LoadedScene::pool_place`: a unit's tree orders them), where an edit
+made the mesh again to find them. A geometry rewritten where it lies needs the same sections, not only as many
+triangles (a BLAS's geometries keep their sizes).
+Still a rebuild: a class change or emission starting for a material of world-space triangles (still ones are
+grouped by whether they are cutouts, dynamic ones as particles' carry their class); the scene's first cutout, first material function on an instance, first vertex colours, first shadow caster with glass
+among its sections (kernel features); a texture or a material function that comes or goes. An instanced object is
+drawn with its first material only.
+Tests, each against a build's light list, weights and picture, natively and under software traversal: a mesh of
+three materials added, given others, shared, its geometry changed with and without its sections, removed; an alpha
+test that comes and goes on a mesh, a mesh of two materials and an instanced object's copies, and the scene's first
+cutout; a material turned glass and plain again; materials of every class made after the build; emission starting
+on an instanced object's material, with a copy that is not shown; an instanced object given a material that emits,
+a cutout, glass, a plain one; a material turned glass that takes its instance's shadow with it; what still
+rebuilds. (A model's materials are the file's: no edit names them.)
+
**Meshes are edited in place (2026-11-18, scene step E, second part).** With every mesh an instance, what the
scene does to one is a change of its instance, not a rebuild. Hidden or shown (itself, or a group above it): the
instance's mask; a hidden mesh is built as an instance no ray sees, its row without power (`Instance::masked`,
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 8e1e44e..35f846f 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -82,12 +82,11 @@ pub struct Prepared {
pub emitter_tris: Vec<EmitterTri>,
/// The light tree over the static emitters (`ltree`).
pub light_tree: Option<ltree::LightTree>,
- /// Material -> runs of its flattened static triangles (first, end in the traversal order, object), and the
- /// materials that also cover pool or dynamic triangles: a material that starts emitting gets emitter entries in
- /// place from its runs (live/edits.rs `add_material_emitters`), unless fixed.
+ /// Material -> runs of its flattened static triangles (first, end in the traversal order, object): a material
+ /// that starts emitting gets emitter entries in place from its runs (live/edits.rs `add_material_emitters`).
+ /// `moving_mats`: the materials of dynamic world-space triangles (`Tables::moving_mats`).
pub mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>>,
- pub fixed_mats: std::collections::HashSet<u32>,
- pub mesh_mats: std::collections::HashSet<u32>,
+ pub moving_mats: std::collections::HashSet<u32>,
/// The flattened triangles' build indices in traversal order (`Scene::tris` order: positions for new entries).
pub tri_order: Vec<u32>,
/// The brightest sky texel (luminance) from which the environment is light-sampled (`Params::counts2[1]`): 0 when
@@ -745,25 +744,15 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
}
// Where each material's flattened static triangles are (runs of the traversal order, with their object), for a
// material that starts emitting in the live view (tables.rs `apply`): its emitter entries are made from them in
- // place. Materials of pool or dynamic triangles are `fixed_mats`; of those, `mesh_mats` are the ones whose pool
- // triangles are meshes' alone (`Retained::own_mesh`: no model's, no instanced object's) and that no dynamic
- // triangle has: each instance of such a mesh gets its emitters in place too (live/edits.rs
- // `add_material_emitters`).
+ // place, as each instance with a row of it gets its own (live/edits.rs `add_material_emitters`). Not the
+ // materials of dynamic world-space triangles: `moving_mats`. (A mesh that deforms is a model's, whose materials
+ // are the file's: no edit names them.)
let mut mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>> = std::collections::HashMap::new();
- // (The materials are in the instances' rows; a model's instance and an instanced object's copies are not a
- // mesh's instance here.)
- let own: std::collections::HashSet<u32> = sc.retained.own_mesh.values().copied().collect();
- let (mut mesh_mats, mut others): (std::collections::HashSet<u32>, std::collections::HashSet<u32>) = Default::default();
- for i in &sc.instances {
- let mats = sc.rows[i.rows as usize..][..sc.meshes[i.mesh as usize].sect_count as usize].iter().map(scene::row_material);
- if i.sub.is_none() && own.contains(&i.mesh) { mesh_mats.extend(mats) } else { others.extend(mats) }
- }
- let mut fixed_mats: std::collections::HashSet<u32> = mesh_mats.union(&others).copied().collect();
+ let mut moving_mats: std::collections::HashSet<u32> = Default::default();
for (k, a) in sc.attrs[..pool_first].iter().enumerate() {
let (mat, obj) = (a.uv[3].to_bits(), a.x[1].to_bits());
if tri_verts[k * 3][3].to_bits() & scene::TRI_DYNAMIC != 0 {
- fixed_mats.insert(mat);
- others.insert(mat);
+ moving_mats.insert(mat);
continue;
}
let runs = mat_runs.entry(mat).or_default();
@@ -772,7 +761,6 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
_ => runs.push([k as u32, k as u32 + 1, obj]),
}
}
- mesh_mats.retain(|m| !others.contains(m));
let tri_order = bvh.order[..pool_first.min(bvh.order.len())].to_vec();
// Many static emitters: a light tree samples them by importance at the shading point (`ltree`); each one's path
// code with its triangle in the list (emit_mis). THREERT_LTREE=0: the CDF alone (A/B).
@@ -894,7 +882,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
first += u32::try_from(count).expect("more than 2^32 triangles");
}
let energy = energy_lut();
- Prepared { tri_verts, groups, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, fixed_mats, mesh_mats, tri_order }
+ Prepared { tri_verts, groups, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, moving_mats, tri_order }
}
/// Instances as world-space triangles (software traversal), appended to the flattened ones with their objects.
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 2304593..123b49a 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -213,7 +213,24 @@ impl Holes {
/// of a mesh.
pub(super) enum Placed {
Proc(wgpu::Blas, scene::ProcObject),
- Mesh(scene::Instance),
+ /// An instance and its rows (its mesh's sections' materials, classes and emitters).
+ Mesh(scene::Instance, Vec<scene::Row>),
+}
+
+/// Each of a mesh's pool triangles' section and its index in it: as they lie (a section after another), or, where a
+/// unit's tree ordered them (software traversal), as kept (`LoadedScene::pool_place`).
+pub(super) fn mesh_places(im: &scene::InstMesh, sections: &[scene::Section], pool_place: &[[u32; 2]]) -> Vec<(u32, u32)> {
+ let (a, b) = (im.first as usize, (im.first + im.count) as usize);
+ if let Some(kept) = pool_place.get(a..b).filter(|_| !pool_place.is_empty()) {
+ return kept.iter().map(|p| (p[0], p[1])).collect();
+ }
+ let mut out = vec![(0, 0); im.count as usize];
+ for (s, x) in im.sections(sections).iter().enumerate() {
+ for i in 0..x.count {
+ out[(x.first + i) as usize] = (s as u32, i);
+ }
+ }
+ out
}
/// One object fewer draws instanced mesh `k`: a mesh edits manage that none draws any more is freed (its triangles a
@@ -628,6 +645,15 @@ impl LiveCore {
// The tables' edits, then what the edits above left to build, once. Either may say the scene is to be rebuilt,
// and the rebuild builds all of it.
let mut applied = self.sc.tables.apply(world, &changes, now).ok().flatten();
+ // (Materials whose class changed: their instances' rows, bits and masks, before the build that reads the masks.)
+ if applied.is_some_and(|d| d.reclassed) {
+ if let Err(why) = self.remake_classes(world, &mut top) {
+ self.fallback = Some(why);
+ self.fallbacks += 1;
+ applied = None;
+ }
+ }
+ self.sc.tables.reclassed.clear();
if applied.is_some() && !self.build_top(top) {
applied = None;
}
@@ -655,7 +681,7 @@ impl LiveCore {
up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
}
if d.materials || d.emitters || std::mem::take(&mut self.emitters_reweigh) {
- let mut new = self.add_material_emitters(world);
+ let mut new = self.add_material_emitters();
new.append(&mut self.pending_emitters);
self.write_emitters(&new);
} else if d.deferred {
@@ -896,6 +922,8 @@ impl LiveCore {
for k in world.subtree_with(id, &children) {
match &world.objects[&k].kind {
crate::world::Kind::Group | crate::world::Kind::Camera(_) => {}
+ // (One this commit adds is placed as it is, shown or not: `edit_geometry`.)
+ crate::world::Kind::Mesh { .. } | crate::world::Kind::Model { animation: None, .. } if changes.added.contains(&k) => {}
crate::world::Kind::Mesh { .. } | crate::world::Kind::Model { animation: None, .. } => {
let Some(r) = self.sc.tables.retained.instance(k).filter(|i| whole(i, &self.sc.instances, &self.sc.meshes)).map(|i| i.instance as usize) else { return false };
let Some(inst) = self.sc.instances.get_mut(r) else { return false };
@@ -1022,11 +1050,66 @@ impl LiveCore {
}
}
+ /// Materials whose class changed (`Tables::reclassed`: glass or not, a cutout or not, with a function or not):
+ /// each instance with a row of one has its rows' classes again, its record's bits, and whether it casts a shadow
+ /// (its mask above the triangles; the commit builds what is above them after). Err: the kernel lacks what the
+ /// class needs (the scene's first cutout, its first caster with glass among its sections, its first function
+ /// on an instance); the caller rebuilds.
+ fn remake_classes(&mut self, world: &World, build: &mut gpu::TopBuild) -> std::result::Result<(), String> {
+ let mats: std::collections::HashSet<u32> = self.sc.tables.reclassed.iter().copied().collect();
+ let (features, q) = (self.sc.up.kernel.features, &self.g.queue);
+ let LoadedScene { up, tables, meshes, instances, gpu_instances, rows, .. } = &mut self.sc;
+ // Each drawn record with whether its object casts a shadow.
+ let mut records: Vec<(usize, bool)> = vec![];
+ for (id, p) in &tables.retained.proxies {
+ let Some(o) = world.objects.get(id) else { continue };
+ let of: Vec<u32> = match &p.draw {
+ scene::Draw::Instance(i) => vec![i.instance],
+ scene::Draw::Rigid(r) => r.instances.iter().map(|&(_, i)| i).collect(),
+ scene::Draw::Instanced(c) if c.mesh.is_some() => (c.first..c.first + c.capacity).collect(),
+ _ => vec![],
+ };
+ records.extend(of.into_iter().map(|r| (r as usize, o.cast_shadow)));
+ }
+ let mut top = gpu::Top::of(&mut up.accel, &mut up.units);
+ let size = std::mem::size_of::<scene::GpuInstance>() as u64;
+ for (r, casts) in records {
+ let Some(inst) = instances.get_mut(r) else { continue };
+ let (at, n) = (inst.rows as usize, meshes[inst.mesh as usize].sect_count as usize);
+ let Some(mine) = rows.get_mut(at..at + n).filter(|x| x.iter().any(|row| mats.contains(&scene::row_material(row)))) else { continue };
+ for row in mine.iter_mut() {
+ let mat = scene::row_material(row);
+ row[0] = scene::row_of(mat, &tables.materials)[0];
+ if tables.materials.get(mat as usize).is_some_and(|m| m.tex1[3] != 0) && features & gpu::F_IFUNC == 0 {
+ return Err("the scene's first material function on an instance (kernel feature)".into());
+ }
+ }
+ let (bits, cast) = (scene::rows_bits(mine), scene::rows_cast(mine, casts));
+ if bits & scene::INST_CUTOUT != 0 && features & gpu::F_MASKED == 0 {
+ return Err("the scene's first cutout (kernel feature)".into());
+ }
+ if bits & scene::INST_GLASS != 0 && cast && features & gpu::F_IGLASS == 0 {
+ return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());
+ }
+ let Some(top) = top.as_mut() else { return Err("software traversal".into()) };
+ (inst.bits, inst.cast_shadow) = (bits, cast);
+ up.words.write(q, Stream::Rows, (at * 16) as u64, bytemuck::cast_slice(mine));
+ let old = gpu_instances[r];
+ let mut rec = top.record(inst.gpu(old.info[0]), inst.mesh, cast);
+ rec.p = old.p;
+ gpu_instances[r] = rec;
+ up.heap.write(q, Table::Instances, r as u64 * size, bytemuck::bytes_of(&rec));
+ top.moved(top.inst_base() + r, inst.world, Some((cast, inst.hidden)));
+ build.instances = true;
+ }
+ Ok(())
+ }
+
/// Emitter entries for the materials that started emitting (`Tables::started_emitting`): their flattened static
/// triangles (`mat_runs`), positions from `tris`, in the power-share part of the CDF (path code 0, as the light
/// tree's moving emitters; ROADMAP § 6 step 3). Returns them (each one's index and triangle) for `write_emitters`.
- pub(super) fn add_material_emitters(&mut self, world: &World) -> Vec<(u32, crate::GpuEmitterTri)> {
- let (hwrt, q) = (self.g.hwrt, &self.g.queue);
+ pub(super) fn add_material_emitters(&mut self) -> Vec<(u32, crate::GpuEmitterTri)> {
+ let q = &self.g.queue;
let sc = &mut self.sc;
let mut new = vec![];
let started = std::mem::take(&mut sc.tables.started_emitting);
@@ -1044,42 +1127,43 @@ impl LiveCore {
}
}
}
- // The meshes' instances with a row of one of them (`Tables::mesh_mats`): each gets its emitters as a new run
- // at the list's end, the sections that emit now one after another, where each starts in its row and the
- // run's first in the instance's record; the run it had, of fewer, stays at no weight.
+ // The instances with a row of one of them (a mesh's, a model's, an instanced object's copies): each gets its
+ // emitters as a new run at the list's end, the sections that emit now one after another, where each starts
+ // in its row and the run's first in the instance's record; the run it had, of fewer, stays at no weight.
if !started.is_empty() && !sc.meshes.is_empty() {
- let LoadedScene { tables, instances, meshes, pool_tris, sections, rows, edit, up, .. } = sc;
+ let LoadedScene { tables, instances, meshes, pool_tris, pool_place, sections, rows, edit, up, .. } = sc;
let moving = tables.retained.moving_records();
- // Each mesh's triangles as the pool has them: their section and their index in it (`rank_in_sections`).
+ let mut records: Vec<usize> = tables
+ .retained
+ .proxies
+ .values()
+ .flat_map(|p| match &p.draw {
+ scene::Draw::Instance(i) => vec![i.instance],
+ scene::Draw::Rigid(r) => r.instances.iter().map(|&(_, i)| i).collect(),
+ scene::Draw::Instanced(c) if c.mesh.is_some() => (c.first..c.first + c.capacity).collect(),
+ _ => vec![],
+ })
+ .map(|r| r as usize)
+ .collect();
+ records.sort_unstable();
+ // Each mesh's triangles as the pool has them: their section and their index in it (`mesh_places`).
let mut places: std::collections::HashMap<u32, Vec<(u32, u32)>> = Default::default();
- for (id, o) in &world.objects {
- let crate::world::Kind::Mesh { geometry, material, materials: mesh_mats, .. } = &o.kind else { continue };
- let gpu_of = |k: &u32| tables.retained.materials.get(k).copied();
- if !std::iter::once(material).chain(mesh_mats).any(|k| gpu_of(k).is_some_and(|m| started.contains(&m))) {
- continue;
- }
- let Some(r) = tables.retained.instance(*id).filter(|i| i.mesh.own()).map(|i| i.instance as usize) else { continue };
- // (A record no object draws any more has none; one hidden by its object's visibility has.)
- let Some(inst) = instances.get(r).filter(|i| !i.hidden || i.masked).cloned() else { continue };
+ let (st, mut dark) = (tables.stride, false);
+ for r in records {
+ // (A record no object draws any more has none; one hidden by its object's visibility has, and a copy
+ // that is not shown.)
+ let Some(inst) = instances.get(r).filter(|i| !i.hidden || i.masked || i.sub.is_some()).cloned() else { continue };
let (k, im) = (inst.mesh, meshes[inst.mesh as usize]);
let sects = im.sections(sections);
- if sects.is_empty() {
+ let at = inst.rows as usize;
+ if sects.is_empty() || !rows.get(at..at + sects.len()).is_some_and(|x| x.iter().any(|row| started.contains(&scene::row_material(row)))) {
continue;
}
- if !places.contains_key(&k) {
- let Some(g) = world.geometries.get(geometry) else { continue };
- let mut d = scene::section_mesh(g, scene::by_groups(g, mesh_mats.len()), 0, 0, false);
- // (Software traversal: a unit's triangles lie in its tree's order.)
- if !hwrt {
- let Ok(tree) = crate::units::mesh_tree(&d.tris) else { continue };
- d.attrs = tree.order.iter().map(|&i| d.attrs[i as usize]).collect();
- scene::rank_in_sections(&mut d.attrs);
- }
- if d.attrs.len() != im.count as usize {
- debug_assert!(false, "mesh {k}: {} triangles made again, {} in the pool", d.attrs.len(), im.count);
- continue;
- }
- places.insert(k, d.attrs.iter().map(|a| (a.uv[3].to_bits(), a.x[3].to_bits())).collect());
+ places.entry(k).or_insert_with(|| mesh_places(&im, sections, pool_place));
+ // (A copy that is not shown: its emitters at no weight by its object's entry, `scene::copy_row`.)
+ if inst.sub.is_some() && inst.hidden {
+ tables.objects[inst.object as usize * st][3] = 0.0;
+ dark = true;
}
let place = &places[&k];
let at = inst.rows as usize;
@@ -1107,6 +1191,9 @@ impl LiveCore {
tables.emitter_tris.push(e);
}
}
+ if dark {
+ up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&tables.objects));
+ }
}
new
}
@@ -1309,8 +1396,10 @@ impl LiveCore {
/// object's records and entries written as one range; the commit builds what is above them. No triangles or
/// BLASes change. Copies that emit: their emitters in the light list follow (`fill_moved`), a hidden copy's object
/// without power, and the emitters are weighed again when a copy's size or power changed (`emitters_reweigh`).
+ /// An object given another material (`World::set_object`): every copy's row names it, with its class, and the
+ /// copies' emitters go or are made with it.
/// Returns how many objects it updated; Err: why it cannot (software traversal, an object the build
- /// flattened or did not place this way), and the caller rebuilds.
+ /// flattened or did not place this way, a kernel feature the material needs), and the caller rebuilds.
/// `THREERT_EDIT_REBUILD=1` always rebuilds (A/B).
pub(super) fn update_instanced(&mut self, world: &World, ids: &[u32], build: &mut gpu::TopBuild) -> std::result::Result<usize, String> {
use crate::world::Kind;
@@ -1327,7 +1416,8 @@ impl LiveCore {
for &id in ids {
// (Removed or hidden: nothing is drawn; a structural change rebuilds.)
let Some(n) = world.objects.get(&id).filter(|_| world.shown(id)) else { continue };
- let Kind::Instanced { capacity, procedural, .. } = n.kind else { continue };
+ let Kind::Instanced { capacity, procedural, materials, .. } = &n.kind else { continue };
+ let (capacity, procedural) = (*capacity, *procedural);
let Some(&place) = sc.tables.retained.instanced(id) else { return Err("an instanced mesh the build flattened".into()) };
if place.capacity != capacity || place.mesh.is_none() != procedural {
return Err("an instanced mesh the build placed otherwise".into());
@@ -1341,6 +1431,52 @@ impl LiveCore {
if procedural && top.sw() {
return Err("a procedural instanced mesh (software traversal)".into());
}
+ // Another material: every copy's row (a copy that is not shown too: it is shown without its rows made
+ // again), its record's bits with it below; the emitters the copies had at no weight, those of a material
+ // that emits a run each at the list's end.
+ let mut cap = cap;
+ let mat = if procedural { None } else { materials.first().and_then(|k| sc.tables.retained.materials.get(k)).copied() };
+ if let Some(mat) = mat.filter(|&mat| sc.instances.get(first).is_some_and(|i| scene::row_material(&sc.rows[i.rows as usize]) != mat)) {
+ let (gm, features) = (sc.tables.materials[mat as usize], sc.up.kernel.features);
+ if gm.tex1[3] != 0 && features & gpu::F_IFUNC == 0 {
+ return Err("the scene's first material function on an instance (kernel feature)".into());
+ }
+ if scene::mesh_class(&gm) == 1 && features & gpu::F_MASKED == 0 {
+ return Err("the scene's first cutout (kernel feature)".into());
+ }
+ let emits = scene::emissive(&gm);
+ let mut w_rows = Gather::default();
+ for r in first..first + capacity as usize {
+ let run = emitter_run(&sc.tables.emitter_tris, &sc.instances, r as u32);
+ reweigh |= !run.is_empty();
+ sc.tables.emitter_tris[run].iter_mut().for_each(|e| e.area = 0.0);
+ let inst = &mut sc.instances[r];
+ let mesh = sc.meshes[inst.mesh as usize];
+ let mut row = scene::row_of(mat, &sc.tables.materials);
+ row[1] = sc.rows[inst.rows as usize][1];
+ (inst.bits, inst.first_emitter) = (scene::rows_bits(&[row]), 0);
+ // (Where this update places the copy: its emitters are made there, as the records below have it.)
+ (inst.world, inst.hidden) = scene::instance_world(m, t, r - first);
+ if emits {
+ let at = sc.tables.emitter_tris.len();
+ (inst.first_emitter, row[2]) = (at as u32, at as u32);
+ let (a, b) = (mesh.first as usize, (mesh.first + mesh.count) as usize);
+ let made = crate::instance_emitters(inst, r as u32, &sc.pool_tris[a..b], (sc.edit.pool_first + a) as u32, &|k| Some((k, mat)), mesh.count as usize, &sc.tables.materials, true);
+ for (j, (e, w)) in made.into_iter().enumerate() {
+ self.pending_emitters.push(((at + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));
+ sc.tables.emitter_tris.push(e);
+ }
+ reweigh = true;
+ }
+ sc.rows[inst.rows as usize] = row;
+ w_rows.put(inst.rows as u64 * 16, bytemuck::bytes_of(&row));
+ }
+ if emits {
+ sc.tables.emissive.insert(mat);
+ }
+ w_rows.flush_section(&self.g.queue, &sc.up.words, Stream::Rows);
+ cap = capacity as usize;
+ }
// (A record's slot is `inst_base` + it, a procedural copy's record the first procedural one + its index.)
let rec0 = if procedural { sc.proc_first + first } else { first };
let slot0 = top.inst_base() + rec0;
@@ -1837,14 +1973,14 @@ impl LiveCore {
/// (gpu.rs `EditRoom`) as the build would make it (`scene::proc_object`, `scene::own_mesh_tris`), new BLASes are
/// built for new geometry only, its TLAS instance is set (cleared for a removed or hidden object) and the TLAS
/// rebuilt, one submit. Nothing is moved: what an edit replaces stays behind until the next rebuild. Err: why it
- /// cannot (software traversal, the room is full, a kernel feature the scene lacks, an emitting / glass / function
- /// material, ...); the caller rebuilds the scene then. `THREERT_EDIT_REBUILD=1` always rebuilds (A/B).
+ /// cannot (software traversal without units, the room is full, a kernel feature the scene lacks, ...); the caller
+ /// rebuilds the scene then. `THREERT_EDIT_REBUILD=1` always rebuilds (A/B).
pub(super) fn edit_geometry(&mut self, world: &World, ch: &crate::world::Changes, build: &mut gpu::TopBuild) -> std::result::Result<(), String> {
use crate::world::Kind;
if std::env::var("THREERT_EDIT_REBUILD").is_ok_and(|v| v == "1") {
return Err("THREERT_EDIT_REBUILD=1".into());
}
- let LoadedScene { up, tables, edit, meshes, pool_tris, instances, gpu_instances, sections, rows, procs, proc_first, moving_instances, .. } = &mut self.sc;
+ let LoadedScene { up, tables, edit, meshes, pool_tris, pool_place, instances, gpu_instances, sections, rows, procs, proc_first, moving_instances, .. } = &mut self.sc;
let (g, assets) = (&self.g, &self.assets);
let features = up.kernel.features;
let grow = Grow { g: &self.g, ok: up.particles.is_none() && up.gpu_particles.is_none() };
@@ -1954,7 +2090,9 @@ impl LiveCore {
let Some(o) = world.objects.get(&id) else { continue };
let at = slot_of(id, edit, tables);
emitters_changed |= release(id, tables, instances);
- if !world.shown(id) {
+ // (A mesh that is hidden is placed all the same, as an instance no ray sees: below.)
+ let is_mesh = matches!(o.kind, Kind::Mesh { .. });
+ if !world.shown(id) && !is_mesh {
if let Some((slot, _)) = at {
top.clear(slot);
}
@@ -1967,12 +2105,16 @@ impl LiveCore {
continue;
}
// The mesh it draws now, as an instance at its record: a user fewer once it is placed again (below).
- let was = at.and_then(|(_, r)| instances.get(r)).filter(|i| !i.hidden).map(|i| i.mesh);
+ let was = at.and_then(|(_, r)| instances.get(r)).filter(|i| !i.hidden || i.masked).map(|i| i.mesh);
// Drawn but not by a TLAS instance of its own: the build flattened it (movable, or a material instances skip).
if at.is_none() && tables.retained.proxies.contains_key(&id) {
return Err("an object the build flattened".into());
}
let m = world.world_matrix(id);
+ // A mesh that is hidden, or placed without size, is an instance no ray sees, at a point if it has no size
+ // (`Instance::masked`, as the build places it): it comes back in place.
+ let (m, gone) = if is_mesh { scene::placed_world(m, glam::Vec3::ZERO) } else { (m, false) };
+ let unseen = is_mesh && (gone || !world.shown(id));
let object = match tables.retained.object(id) {
Some(k) => k as usize,
None => match edit.objects.take(1) {
@@ -2041,7 +2183,6 @@ impl LiveCore {
let gpu = p.gpu(header as u32);
(at.map(|(_, r)| r), gpu, Placed::Proc(blas, p), entry)
}
- Kind::Mesh { materials, .. } if materials.len() > 1 => return Err("a mesh with several materials".into()),
Kind::Model { uri, nodes, animation, functions } => {
// A static model already in the scene: another instance of its mesh (one not in it brings materials
// and textures, which load with a rebuild).
@@ -2075,59 +2216,59 @@ impl LiveCore {
let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first), mesh, inst.cast_shadow);
let (lo, hi) = im.placed_bounds(m);
let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);
- (at.map(|(_, r)| r), gpu, Placed::Mesh(inst), entry)
+ (at.map(|(_, r)| r), gpu, Placed::Mesh(inst, mine.clone()), entry)
}
Kind::Mesh { .. } | Kind::Instanced { procedural: false, .. } => {
- // An own-BLAS mesh, or (added in place) an instanced mesh: their mesh made alike.
- let (geometry, material, capacity) = match &o.kind {
- Kind::Mesh { geometry, material, .. } => (*geometry, *material, None),
- Kind::Instanced { geometry, materials, capacity, .. } => (*geometry, *materials.first().ok_or("an instanced mesh without a material")?, Some(*capacity as usize)),
+ // A mesh, or (added in place) an instanced mesh: their mesh made alike. A mesh with several
+ // materials has a geometry group's triangles with each (`scene::by_groups`); an instanced mesh
+ // its first.
+ let (geometry, ids, capacity) = match &o.kind {
+ Kind::Mesh { geometry, material, materials, .. } => (*geometry, if materials.len() > 1 { materials.clone() } else { vec![*material] }, None),
+ Kind::Instanced { geometry, materials, capacity, .. } => (*geometry, vec![*materials.first().ok_or("an instanced mesh without a material")?], Some(*capacity as usize)),
_ => unreachable!(),
};
- let (geometry, material) = (&geometry, &material);
+ let geo = world.geometries.get(&geometry).ok_or("unknown geometry")?;
+ let grouped = scene::by_groups(geo, ids.len());
+ let ids = if grouped { ids } else { ids[..1].to_vec() };
+ let geometry = &geometry;
if features & gpu::F_INST == 0 {
return Err("the scene's first instanced mesh (kernel feature)".into());
}
- // A placement without size (a build places it, unseen at a point), or instancing off (it flattens).
- if m.determinant() == 0.0 || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {
- return Err("a mesh without size, or instancing off".into());
+ // An instanced object placed without size, or instancing off (the build flattens).
+ if (capacity.is_some() && m.determinant() == 0.0) || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {
+ return Err("an instanced object without size, or instancing off".into());
}
- let mat = *tables.retained.materials.get(material).ok_or("unknown material")?;
- let gm = tables.materials[mat as usize];
- // (It covers instances' triangles from here on, `Tables::fixed_mats`: meshes' alone, `mesh_mats`,
- // if it covered none before or was theirs alone, and this is a mesh.)
- if !matches!(o.kind, Kind::Mesh { .. }) {
- tables.mesh_mats.remove(&mat);
- } else if !tables.fixed_mats.contains(&mat) {
- tables.mesh_mats.insert(mat);
+ let mats = ids.iter().map(|k| tables.retained.materials.get(k).copied().ok_or("unknown material")).collect::<std::result::Result<Vec<u32>, _>>()?;
+ let mat = mats[0];
+ for &mat in &mats {
+ let gm = tables.materials[mat as usize];
+ if gm.tex1[3] != 0 && features & gpu::F_IFUNC == 0 {
+ return Err("the scene's first material function on an instance (kernel feature)".into());
+ }
+ if scene::mesh_class(&gm) == 1 && features & gpu::F_MASKED == 0 {
+ return Err("the scene's first cutout (kernel feature)".into());
+ }
}
- tables.fixed_mats.insert(mat);
// An emitting material: a mesh as any other, each instance's emitters in the light list (given
// below, where its record is known; scene.rs; ROADMAP § 6 step 3).
- let emits = scene::emissive(&gm);
- let class = scene::mesh_class(&gm);
- if gm.tex1[3] != 0 && features & gpu::F_IFUNC == 0 {
- return Err("the scene's first material function on an instance (kernel feature)".into());
- }
- if class == 1 && features & gpu::F_MASKED == 0 {
- return Err("the scene's first cutout (kernel feature)".into());
- }
- let colored = world.materials.get(material).is_some_and(|m| m.vertex_colors) && world.geometries.get(geometry).is_some_and(|g| !g.colors.is_empty());
+ let emits = scene::emissive(&tables.materials[mat as usize]);
+ let colored = ids.iter().any(|k| world.materials.get(k).is_some_and(|m| m.vertex_colors)) && !geo.colors.is_empty();
if colored && !vcolors {
return Err("the scene's first vertex colours (kernel feature)".into());
}
- // (The geometry whole, with one material: the mesh every such object of the geometry shares; its
- // material is this instance's row.)
- let key = (*geometry, false);
+ // (The mesh every such object of the geometry shares, by section: the geometry whole, or its groups.
+ // Its materials are this instance's rows.)
+ let key = (*geometry, grouped);
let kept = (!ch.geometries.contains(geometry)).then(|| tables.retained.own_mesh.get(&key).copied()).flatten();
let mesh = match fresh.get(&key).copied().or(kept) {
// (A mesh made without its geometry's colours, for objects that read none.)
Some(k) if colored && !meshes[k as usize].colored => return Err("vertex colours on a mesh made without them".into()),
Some(k) => k,
None => {
- let geo = world.geometries.get(geometry).ok_or("unknown geometry")?;
let t0 = Instant::now();
- let scene::MeshData { tris: mut t, attrs: mut a, .. } = scene::section_mesh(geo, false, 0, 0, false);
+ // (With its colours where an object of it reads them: this one, or one that shares the mesh.)
+ let had = tables.retained.own_mesh.get(&key).is_some_and(|&k| meshes[k as usize].colored);
+ let scene::MeshData { tris: mut t, attrs: mut a, colors: mut c, sections: sects, .. } = scene::section_mesh(geo, grouped, 0, 0, colored || had);
if t.is_empty() {
if let Some((slot, _)) = at {
top.clear(slot);
@@ -2146,6 +2287,7 @@ impl LiveCore {
let tree = crate::units::mesh_tree(&t)?;
t = tree.order.iter().map(|&i| t[i as usize]).collect();
a = tree.order.iter().map(|&i| a[i as usize]).collect();
+ c = c.map(|c| tree.order.iter().map(|&i| c[i as usize]).collect());
scene::rank_in_sections(&mut a);
Some(tree)
}
@@ -2156,10 +2298,11 @@ impl LiveCore {
let verts: Vec<[f32; 4]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z, flags], [b.x - a.x, b.y - a.y, b.z - a.z, 0.0], [c.x - a.x, c.y - a.y, c.z - a.z, 0.0]]).collect();
let blas_verts: Vec<[f32; 3]> = t.iter().flat_map(|&[a, b, c]| [[a.x, a.y, a.z], [b.x, b.y, b.z], [c.x, c.y, c.z]]).collect();
split.tris += t0.elapsed().as_secs_f64() * 1e3;
- // The same triangle count as the mesh it replaces: rewritten where it is, its BLAS rebuilt (no
- // room used; a geometry that moves every frame, three.js's dynamic draw usage). Otherwise new
- // triangles in the room and a new BLAS.
- let same = tables.retained.own_mesh.get(&key).copied().filter(|&k| meshes[k as usize].count as usize == t.len() );
+ // The same sections as the mesh it replaces (as many triangles in each: a BLAS's geometries keep
+ // their sizes): rewritten where it is, its BLAS rebuilt (no room used; a geometry that moves
+ // every frame, three.js's dynamic draw usage). Otherwise new triangles in the room and a new
+ // BLAS.
+ let same = tables.retained.own_mesh.get(&key).copied().filter(|&k| meshes[k as usize].sections(sections) == sects.as_slice());
let (k, first, im) = match same {
Some(k) => {
// (Its colours stay its own while another object of it reads them.)
@@ -2190,17 +2333,18 @@ impl LiveCore {
None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: triangles (software traversal's does not grow)" } else { "edit room: triangles (particles, or the device's limits)" }.into()),
};
let t1 = Instant::now();
- // A freed mesh's slot (and its section's), else a new one.
+ // A freed mesh's slot (and its sections', where they are as many at least), else new ones.
let dead = edit.dead_meshes.pop();
- let sect_first = match dead.map(|k| meshes[k as usize]).filter(|m| m.sect_count > 0) {
+ let n = sects.len();
+ let sect_first = match dead.map(|k| meshes[k as usize]).filter(|m| m.sect_count as usize >= n) {
Some(m) => m.sect_first,
None => {
- sections.push(scene::Section { first: 0, count: 0, slot: 0 });
- sections.len() as u32 - 1
+ sections.resize(sections.len() + n, scene::Section { first: 0, count: 0, slot: 0 });
+ (sections.len() - n) as u32
}
};
- sections[sect_first as usize] = scene::Section { first: 0, count: t.len() as u32, slot: 0 };
- let im = scene::InstMesh { sect_first, sect_count: 1, colored, ..scene::own_inst_mesh(&t, (first - edit.pool_first) as u32) };
+ sections[sect_first as usize..][..n].copy_from_slice(&sects);
+ let im = scene::InstMesh { sect_first, sect_count: n as u32, colored, ..scene::own_inst_mesh(&t, (first - edit.pool_first) as u32) };
let k = match &mut top {
gpu::Top::Hw(accel) => match dead {
Some(k) => {
@@ -2244,11 +2388,7 @@ impl LiveCore {
}
if vcolors {
// White where it has none: the room's slots may hold an earlier mesh's.
- let colored = im.colored;
- let mut c = if colored { scene::tri_colors(geo, false, None) } else { vec![scene::WHITE; t.len()] };
- if let (Some(tree), true) = (&tree, colored) {
- c = tree.order.iter().map(|&i| c[i as usize]).collect();
- }
+ let c = c.filter(|_| im.colored).unwrap_or_else(|| vec![scene::WHITE; t.len()]);
w_colors.put((first * 12) as u64, bytemuck::cast_slice(&c));
}
split.upload += t2.elapsed().as_secs_f64() * 1e3;
@@ -2257,6 +2397,15 @@ impl LiveCore {
pool_tris.resize(rel + t.len(), [glam::Vec3A::ZERO; 3]);
}
pool_tris[rel..rel + t.len()].copy_from_slice(&t);
+ // (Software traversal: where its tree left each triangle of its sections, `mesh_places`.)
+ if top.sw() {
+ if pool_place.len() < rel + t.len() {
+ pool_place.resize(rel + t.len(), [0; 2]);
+ }
+ for (j, x) in a.iter().enumerate() {
+ pool_place[rel + j] = [x.uv[3].to_bits(), x.x[3].to_bits()];
+ }
+ }
let _ = im;
new_meshes.push(k);
fresh.insert(key.clone(), k);
@@ -2349,14 +2498,18 @@ impl LiveCore {
*tables.retained.proxy(id) = scene::Proxy { object: None, card: None, draw: scene::Draw::Instanced(scene::InstancedPlace { first: r0 as u32, capacity: cap as u32, object: o0 as u32, mesh: Some(mesh), drawn: t.count }) };
continue;
}
- // (Its row, which says its material, is placed with its record below; its bits and whether it
- // casts are the row's.)
- let row = [scene::row_of(mat, &tables.materials)];
- let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&row, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&row) };
+ // (Its rows, which say its materials, are placed with its record below; its bits and whether it casts
+ // are theirs.)
+ let mine = scene::section_rows(im.sections(sections), &mats, &tables.materials);
+ // (Shadow rays pass the glass among a caster's other sections under a kernel feature.)
+ if scene::rows_bits(&mine) & scene::INST_GLASS != 0 && scene::rows_cast(&mine, o.cast_shadow) && features & gpu::F_IGLASS == 0 {
+ return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into());
+ }
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine) };
let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first), mesh, inst.cast_shadow);
let (lo, hi) = im.placed_bounds(m);
- let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]);
- (at.map(|(_, r)| r), gpu, Placed::Mesh(inst), entry)
+ let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), if unseen { 0.0 } else { o.power }, hi - lo, o.custom, [1.0; 3]);
+ (at.map(|(_, r)| r), gpu, Placed::Mesh(inst, mine), entry)
}
_ => return Err("not an object an edit places".into()),
};
@@ -2380,32 +2533,34 @@ impl LiveCore {
// has as many and none is the light tree's (those keep their place there, at no weight); else a new one at
// the list's end. Its first goes in its record.
let (mut gpu, mut blas) = (gpu, blas);
- if let Placed::Mesh(inst) = &mut blas {
+ if let Placed::Mesh(inst, mine) = &mut blas {
let im = meshes[inst.mesh as usize];
- // Its rows: a mesh's one (the geometry whole, with the object's material), a model's as its mesh has
- // them; each with where its section's triangles start.
- let material = match &o.kind {
- Kind::Mesh { material, .. } => Some(*tables.retained.materials.get(material).ok_or("unknown material")?),
- _ => None,
- };
- let mut mine: Vec<scene::Row> = match material {
- Some(mat) => vec![scene::row_of(mat, &tables.materials)],
- None => tables.retained.mesh_rows.get(&inst.mesh).cloned().ok_or("a model's mesh without its rows")?,
- };
- for (s, row) in im.sections(sections).iter().zip(&mut mine) {
+ let sects = im.sections(sections);
+ // Its rows, each with where its section's triangles start.
+ for (s, row) in sects.iter().zip(mine.iter_mut()) {
row[1] = edit.pool_first as u32 + im.first + s.first;
}
let row_at = rows_for(edit, &grow, &mut up.words, instances, meshes, record, mine.len())?;
(inst.rows, gpu.info[3]) = (row_at as u32, row_at as u32);
- // A mesh whose material emits: its emitters, a run of the light list. The run its record had, if that
- // has as many and none is the light tree's (those keep their place there, at no weight); else a new
- // one at the list's end. Its first goes in its row. (A model placed here has none: `model_mesh`.)
- if let Some(mat) = material.filter(|&mat| tables.materials.get(mat as usize).is_some_and(scene::emissive)) {
+ // Its sections whose material emits: its emitters, a run of the light list, a section after another.
+ // The run its record had, if that has as many and none is the light tree's (those keep their place
+ // there, at no weight); else a new one at the list's end. A section's start goes in its row.
+ let n = scene::rows_emitters(sects, mine, &tables.materials) as usize;
+ if n > 0 {
+ let starts = scene::section_emitters(sects, mine, &tables.materials);
let old = emitter_run(&tables.emitter_tris, instances, record as u32);
- let first = if old.len() == im.count as usize && tables.emitter_tris[old.clone()].iter().all(|e| !e.in_tree) { old.start } else { tables.emitter_tris.len() };
- (inst.first_emitter, mine[0][2]) = (first as u32, first as u32);
+ let first = if old.len() == n && tables.emitter_tris[old.clone()].iter().all(|e| !e.in_tree) { old.start } else { tables.emitter_tris.len() };
+ inst.first_emitter = first as u32;
+ for (row, start) in mine.iter_mut().zip(&starts) {
+ row[2] = start.map_or(scene::NO_EMITTER, |x| first as u32 + x);
+ }
+ let (place, of) = (mesh_places(&im, sections, pool_place), mine.iter().map(scene::row_material).collect::<Vec<u32>>());
+ let numbered = |j: usize| {
+ let (s, i) = place[j];
+ starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, of[s as usize]))
+ };
let (a, b) = (im.first as usize, (im.first + im.count) as usize);
- let made = crate::instance_emitters(inst, record as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &|k| Some((k, mat)), im.count as usize, &tables.materials, o.driven || world.movable(id));
+ let made = crate::instance_emitters(inst, record as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &numbered, n, &tables.materials, o.driven || world.movable(id));
for (j, (e, w)) in made.into_iter().enumerate() {
new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0)));
match tables.emitter_tris.get_mut(first + j) {
@@ -2413,14 +2568,18 @@ impl LiveCore {
None => tables.emitter_tris.push(e),
}
}
- tables.emissive.insert(mat);
+ for (&mat, start) in of.iter().zip(&starts) {
+ if start.is_some() {
+ tables.emissive.insert(mat);
+ }
+ }
emitters_changed = true;
}
- w_rows.put((row_at * 16) as u64, bytemuck::cast_slice(&mine));
+ w_rows.put((row_at * 16) as u64, bytemuck::cast_slice(mine));
if rows.len() < row_at + mine.len() {
rows.resize(row_at + mine.len(), [0; 4]);
}
- rows[row_at..row_at + mine.len()].copy_from_slice(&mine);
+ rows[row_at..row_at + mine.len()].copy_from_slice(mine);
}
w_records.put((record * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(&gpu));
if record >= gpu_instances.len() {
@@ -2439,8 +2598,8 @@ impl LiveCore {
procs[j] = p;
scene::Draw::Procedural(j as u32)
}
- Placed::Mesh(inst) => {
- top.place(slot, inst.mesh, m, gpu::INSTANCE_BIT | record as u32, inst.cast_shadow, false);
+ Placed::Mesh(inst, _) => {
+ top.place(slot, inst.mesh, m, gpu::INSTANCE_BIT | record as u32, inst.cast_shadow, inst.hidden);
if instances.len() <= record {
instances.resize(record + 1, scene::Instance { name: String::new(), hidden: true, ..inst.clone() });
}
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 41bf2d9..233706e 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -504,14 +504,25 @@ fn a_glass_mesh_added_is_drawn_as_a_build_draws_it() {
let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
assert!(apart(&before, &b) > 0.5, "the pane is in the picture ({:.2} steps)", apart(&before, &b));
assert!(apart(&a, &b) < 0.5, "glass on an instance already: {has}: the picture is {:.2} steps from a build's", apart(&a, &b));
- // A material of an instance's triangles that turns glass (the mesh of its own, and the wall): by a rebuild, its
- // instances' masks and its mesh's geometries being the build's.
+ // A material of instances' triangles that turns glass (the mesh of its own, and the wall), and is plain
+ // again: their rows and their masks say so, in place.
w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.8, 0.4, 0.8], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": 0, "doubleSided": true, "transmission": 1, "ior": 1.5 })).unwrap());
- assert!(live.commit(&mut w).unwrap(), "a material of an instance's triangles turned glass: a rebuild");
+ assert!(!live.commit(&mut w).unwrap(), "a material of instances' triangles turned glass: in place ({:?})", live.fallback);
+ let wall = live.sc.instances.iter().find(|i| i.name == "wall").expect("the wall is an instance");
+ assert!(!wall.cast_shadow && wall.bits & scene::INST_GLASS != 0, "the wall is glass: it casts no shadow");
let mut fresh = open(&w).unwrap();
forget(&mut live);
let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
assert!(apart(&a, &b) < 0.5, "a material turned glass: the picture is {:.2} steps from a build's", apart(&a, &b));
+ w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.8, 0.4, 0.8], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": 0, "doubleSided": true })).unwrap());
+ assert!(!live.commit(&mut w).unwrap(), "the material plain again: in place ({:?})", live.fallback);
+ let wall = live.sc.instances.iter().find(|i| i.name == "wall").expect("the wall is an instance");
+ assert!(wall.cast_shadow && wall.bits & scene::INST_GLASS == 0, "the wall casts its shadow again");
+ let mut fresh = open(&w).unwrap();
+ forget(&mut live);
+ let (c, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
+ assert!(apart(&c, &b) < 0.5, "the material plain again: the picture is {:.2} steps from a build's", apart(&c, &b));
+ assert!(apart(&a, &c) > 0.5, "glass or not is in the picture ({:.2} steps)", apart(&a, &c));
}
}
@@ -660,12 +671,8 @@ fn an_emitting_instanced_object_added_in_place_is_lit_as_a_build_lights_it() {
let mut run = 0;
for (what, edit) in &edits {
let what = format!("an emitting instanced object {what} in place, {} a light tree", if tree { "with" } else { "without" });
- // (Its material covers instances' triangles once it is added: `Tables::fixed_mats`.)
- let covers = |c: &LiveCore| c.sc.tables.fixed_mats.contains(&c.sc.tables.retained.materials[&5]);
- let before = covers(&live);
edit(&mut w);
assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
- assert!(covers(&live) && (before || what.contains("added")), "{what}: its material is among those of instances' triangles");
// Its copies' rows: a run of the room's, the room's again once it is removed.
match live.sc.tables.retained.instanced(15) {
Some(place) => {
@@ -1004,6 +1011,23 @@ fn a_material_that_starts_emitting_lights_its_meshes_instances_as_a_build_does()
assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
list_is_its_triangles(&what, &live);
lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ // A material an instanced object added in place has too: its copy's emitters, as the meshes'.
+ if live.g.hwrt {
+ w.set_object(31, "more".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![9], capacity: 1 }, true, false).unwrap();
+ w.set_instances(31, 1, Some(glam::Mat4::from_translation(Vec3::new(0.4, 0.2, 1.1)).to_cols_array().to_vec()), None, None).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "an instanced object added, {with} a light tree: in place ({:?})", live.fallback);
+ w.set_material(9, late(30.0));
+ let what = format!("a material an instanced object added in place has too started emitting, {with} a light tree");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(&what, &live);
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ }
+ // One an instanced object of the build has too: its copies', a copy that is not shown at no weight.
+ w.set_material(7, late(30.0));
+ let what = format!("a material an instanced object has too started emitting, {with} a light tree");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(&what, &live);
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
w.set_transform(14, Vec3::new(0.2, -0.3, 1.2), glam::Quat::from_rotation_z(0.6), Vec3::ONE).unwrap();
let what = format!("the movable one of them moved, {with} a light tree");
assert!(!(live.commit(&mut w).unwrap() && live.g.hwrt), "{what}: in place ({:?})", live.fallback);
@@ -1012,24 +1036,14 @@ fn a_material_that_starts_emitting_lights_its_meshes_instances_as_a_build_does()
forget(&mut live);
let (a, b) = (picture(&mut live, 64), picture(&mut open(&w).unwrap(), 64));
assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
- // A material meshes had alone, until an instanced object of it is added in place: a rebuild from then on.
- if live.g.hwrt {
- w.set_object(31, "more".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![9], capacity: 1 }, true, false).unwrap();
- w.set_instances(31, 1, Some(glam::Mat4::from_translation(Vec3::new(0.4, 0.2, 1.1)).to_cols_array().to_vec()), None, None).unwrap();
- assert!(!live.commit(&mut w).unwrap(), "an instanced object added, {with} a light tree: in place ({:?})", live.fallback);
- w.set_material(9, late(30.0));
- assert!(live.commit(&mut w).unwrap(), "a material an instanced object added in place has too started emitting, {with} a light tree: a rebuild");
- }
- // (Its copies' emitters are a build's to make.)
- w.set_material(7, late(30.0));
- assert!(live.commit(&mut w).unwrap(), "a material an instanced object has too started emitting, {with} a light tree: a rebuild");
}
}
/// A mesh hidden or shown by its `visible` is drawn and lit as a build draws it, in place: a still mesh, one that
/// emits, one hidden when the scene was built, a group of two, a movable one moved while it was hidden. With and
/// without a light tree. After each: no rebuild, the light list is its triangles, the weights and the picture are a
-/// build's. A mesh whose geometry changed while it was hidden is drawn again by a rebuild.
+/// build's. So for what an edit places unseen: a mesh whose geometry changed while it was hidden, one added hidden,
+/// one added without size.
#[test]
fn meshes_hidden_and_shown_in_place_are_drawn_as_a_build_draws_them() {
let presets = crate::default_presets_dir();
@@ -1109,18 +1123,47 @@ fn meshes_hidden_and_shown_in_place_are_drawn_as_a_build_draws_them() {
lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
}
assert_eq!((hidden(&live, 13), hidden(&live, 11), hidden(&live, 21)), ((true, true), (false, false), (false, false)), "{with} a light tree: as the world has them");
- // Its geometry changed while it was hidden: the instance an edit took out is no longer its own to show.
+ // An edit places a mesh that is hidden, or has no size, as the build does: an instance no ray sees. Its geometry
+ // changed while it was hidden (its old mesh is left without a user), a mesh added hidden, one added without size:
+ // each comes back in place. A hidden mesh removed takes its mesh's user with it.
if live.g.hwrt {
+ let mesh_of = |c: &LiveCore, id: u32| c.sc.instances[c.sc.tables.retained.instance(id).unwrap().instance as usize].mesh;
w.set_visible(22, false).unwrap();
assert!(!live.commit(&mut w).unwrap(), "a mesh the scene edits hidden, {with} a light tree: in place ({:?})", live.fallback);
- let its = live.sc.instances[live.sc.tables.retained.instance(22).unwrap().instance as usize].mesh;
+ let its = mesh_of(&live, 22);
w.set_geometry(8, quad(0.35)).unwrap();
- assert!(!live.commit(&mut w).unwrap(), "its geometry changed while hidden, {with} a light tree: in place ({:?})", live.fallback);
- assert_eq!(hidden(&live, 22), (true, false), "taken out by the edit");
- assert_eq!(live.sc.edit.users.get(&its).copied().unwrap_or(0), 0, "and its mesh has no user left");
- w.set_visible(22, true).unwrap();
- assert!(live.commit(&mut w).unwrap(), "shown after its geometry changed, {with} a light tree: a rebuild");
- let what = format!("a mesh shown after its geometry changed while hidden, {with} a light tree");
+ place(&mut w, 23, "added hidden", None, mesh(3, 5, false), false, [0.3, 0.6, 1.0]);
+ w.set_visible(23, false).unwrap();
+ w.set_object(24, "added without size".into(), None, mesh(3, 1, false), true, false).unwrap();
+ w.set_transform(24, Vec3::new(0.6, -0.1, 0.8), glam::Quat::IDENTITY, Vec3::ZERO).unwrap();
+ let what = format!("a hidden mesh's geometry changed, a mesh added hidden, one added without size, {with} a light tree");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert_eq!((hidden(&live, 22), hidden(&live, 23), hidden(&live, 24)), ((true, true), (true, true), (true, true)), "{what}: instances no ray sees");
+ // (As many triangles as before: the mesh is written again where it was, and has its one user.)
+ assert_eq!((mesh_of(&live, 22), live.sc.edit.users.get(&its).copied().unwrap_or(0)), (its, 1), "{what}: its mesh has its one user");
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ let back: Vec<Edit> = vec![
+ ("a mesh shown after its geometry changed while hidden", show(22, true)),
+ ("a mesh added hidden shown", show(23, true)),
+ ("a mesh added without size given one", Box::new(|w| w.set_transform(24, Vec3::new(0.6, -0.1, 0.8), glam::Quat::from_rotation_y(-0.3), Vec3::ONE).unwrap())),
+ ("the added lamp hidden again", show(23, false)),
+ ];
+ for (what, edit) in &back {
+ let what = format!("{what}, {with} a light tree");
+ edit(&mut w);
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ if live.sc.tables.emitter_tris.iter().any(|e| e.area > 0.0) {
+ list_is_its_triangles(&what, &live);
+ }
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ }
+ let its = mesh_of(&live, 22);
+ w.set_visible(22, false).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "hidden once more, {with} a light tree: in place ({:?})", live.fallback);
+ w.remove(22);
+ let what = format!("a hidden mesh removed, {with} a light tree");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert_eq!(live.sc.edit.users.get(&its).copied().unwrap_or(0), 0, "{what}: its mesh has no user left");
lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
}
}
@@ -1608,6 +1651,355 @@ fn the_first_caster_with_glass_among_its_sections_is_a_rebuilds() {
let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from a build's", apart(&a, &b));
assert_ne!(live.sc.up.kernel.features & gpu::F_IGLASS, 0, "the kernel passes its glass");
+ // So for a mesh of several materials, glass one of them, added where none like it cast a shadow.
+ let mut w = world();
+ w.set_material(65, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.5, 0.9, 0.5], "opacity": 1, "metalness": 0, "roughness": 0, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true, "transmission": 1, "ior": 1.5 })).unwrap());
+ w.set_object(28, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(28, Vec3::new(0.9, -0.1, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = open(&w).unwrap();
+ w.take_changes();
+ assert_eq!(live.sc.up.kernel.features & gpu::F_IGLASS, 0, "no caster has glass among its sections");
+ w.set_geometry(30, Geometry { positions: vec![-1.0, -0.5, 0.0, 0.0, -0.5, 0.0, 1.0, -0.5, 0.0, -1.0, 0.5, 0.0, 0.0, 0.5, 0.0, 1.0, 0.5, 0.0], normals: [0.0, 0.0, 1.0].repeat(6), uvs: vec![0.0; 12], indices: vec![0, 1, 4, 0, 4, 3, 1, 2, 5, 1, 5, 4], groups: vec![[0, 6, 0], [6, 6, 1]], colors: vec![] }).unwrap();
+ w.set_object(31, "pane".into(), None, Kind::Mesh { geometry: 30, material: 1, own_blas: false, materials: vec![1, 65] }, true, false).unwrap();
+ w.set_transform(31, Vec3::new(0.0, 0.0, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ live.commit(&mut w).unwrap();
+ let mut fresh = open(&w).unwrap();
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "a mesh with glass among its sections: the picture is {:.2} steps from a build's", apart(&a, &b));
+ assert_ne!(live.sc.up.kernel.features & gpu::F_IGLASS, 0, "the kernel passes its glass");
+}
+
+/// A mesh of several materials (a geometry group each) is edited in place as one of a single material is: added
+/// (its mesh made with its sections), given other materials (its rows: nothing made), another of its geometry added
+/// (the mesh shared), its geometry changed (the same sections: where it lies; others: a new mesh), removed (its rows
+/// the room's again). Each time the light list, the weights and the picture are a build's.
+#[test]
+fn a_mesh_of_several_materials_is_edited_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 plain = |extra: serde_json::Value| {
+ let mut m = serde_json::json!({ "name": "m", "color": [0.9, 0.9, 0.9], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });
+ m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ serde_json::from_value::<crate::desc::Material>(m).unwrap()
+ };
+ // Bands side by side, `w` wide each, a group for each run of `groups` of them.
+ let bands = |w: f32, groups: &[u32]| {
+ let n: u32 = groups.iter().sum();
+ let positions: Vec<f32> = (0..=n).flat_map(|i| { let x = (i as f32 - n as f32 / 2.0) * w; [x, -0.4, 0.0, x, 0.4, 0.0] }).collect();
+ let indices: Vec<u32> = (0..n).flat_map(|i| [2 * i, 2 * i + 2, 2 * i + 3, 2 * i, 2 * i + 3, 2 * i + 1]).collect();
+ let mut at = 0;
+ let groups = groups.iter().enumerate().map(|(k, &g)| { at += g * 6; [at - g * 6, g * 6, k as u32] }).collect();
+ Geometry { normals: [0.0, 0.0, 1.0].repeat(2 * (n as usize + 1)), uvs: vec![0.0; 4 * (n as usize + 1)], positions, indices, groups, colors: vec![] }
+ };
+ let mut w = world();
+ w.set_material(62, plain(serde_json::json!({})));
+ w.set_material(63, plain(serde_json::json!({ "opacity": 0.3, "alphaTest": 0.5 })));
+ w.set_material(64, plain(serde_json::json!({ "opacity": 0.9, "alphaTest": 0.5, "color": [0.2, 0.6, 0.9] })));
+ w.set_material(65, plain(serde_json::json!({ "color": [0.5, 0.9, 0.5], "roughness": 0, "transmission": 1, "ior": 1.5 })));
+ // (At the build: a caster with a cutout and glass among its sections, so the kernel has both; a mesh the scene
+ // says it edits, for the room.)
+ w.set_geometry(30, bands(0.3, &[1, 1, 1])).unwrap();
+ w.set_object(40, "bands".into(), None, Kind::Mesh { geometry: 30, material: 62, own_blas: true, materials: vec![62, 63, 65] }, true, false).unwrap();
+ w.set_transform(40, Vec3::new(-0.9, 0.6, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let placed = |c: &LiveCore, id: u32| c.sc.instances[c.sc.tables.retained.instance(id).expect("a mesh is an instance").instance as usize].clone();
+ let rows_of = |c: &LiveCore, id: u32| { let i = placed(c, id); c.sc.rows[i.rows as usize..][..c.sc.meshes[i.mesh as usize].sect_count as usize].to_vec() };
+ let materials = |c: &LiveCore, id: u32| rows_of(c, id).iter().map(scene::row_material).collect::<Vec<u32>>();
+ let of = |c: &LiveCore, ids: &[u32]| ids.iter().map(|k| c.sc.tables.retained.materials[k]).collect::<Vec<u32>>();
+ let against_a_build = |what: &str, live: &mut LiveCore, w: &World| {
+ list_is_its_triangles(what, live);
+ let mut fresh = open(w).unwrap();
+ lit_as_a_build(what, live, &mut fresh);
+ };
+ let place = |w: &mut World, id: u32, geometry: u32, materials: &[u32], at: Vec3| {
+ w.set_object(id, format!("bands{id}"), None, Kind::Mesh { geometry, material: materials[0], own_blas: false, materials: materials.to_vec() }, true, false).unwrap();
+ w.set_transform(id, at, glam::Quat::from_rotation_y(0.2), Vec3::ONE).unwrap();
+ };
+ // Added: an emitter, a cutout, a plain band.
+ w.set_geometry(31, bands(0.25, &[1, 1, 1])).unwrap();
+ place(&mut w, 41, 31, &[5, 64, 62], Vec3::new(0.3, -0.5, 0.9));
+ assert!(!live.commit(&mut w).unwrap(), "a mesh of three materials added: in place ({:?})", live.fallback);
+ let (mesh, first) = (placed(&live, 41).mesh, placed(&live, 41).rows);
+ assert_eq!((live.sc.meshes[mesh as usize].sect_count, materials(&live, 41)), (3, of(&live, &[5, 64, 62])), "its mesh has three sections, its rows their materials");
+ against_a_build("a mesh of three materials added in place", &mut live, &w);
+ // Other materials: its rows where they are, no mesh made, no triangle written. The emitter is another section's.
+ let (meshes, triangles) = (live.sc.meshes.len(), live.sc.pool_tris.len());
+ place(&mut w, 41, 31, &[62, 65, 5], Vec3::new(0.3, -0.5, 0.9));
+ assert!(!live.commit(&mut w).unwrap(), "its materials changed: in place ({:?})", live.fallback);
+ assert_eq!((placed(&live, 41).mesh, placed(&live, 41).rows, live.sc.meshes.len(), live.sc.pool_tris.len()), (mesh, first, meshes, triangles), "it keeps its mesh and its rows: nothing made");
+ assert_eq!(materials(&live, 41), of(&live, &[62, 65, 5]));
+ against_a_build("a mesh of three materials given others", &mut live, &w);
+ // Another object of the geometry, with its own materials: the mesh shared.
+ place(&mut w, 42, 31, &[64, 5, 62], Vec3::new(-0.2, 0.55, 1.2));
+ assert!(!live.commit(&mut w).unwrap(), "another of the geometry: in place ({:?})", live.fallback);
+ assert_eq!((placed(&live, 42).mesh, live.sc.meshes.len()), (mesh, meshes), "it shares the mesh");
+ against_a_build("another object of a geometry of three materials", &mut live, &w);
+ // The geometry changed, its sections as they were: the mesh rewritten where it lies.
+ w.set_geometry(31, bands(0.2, &[1, 1, 1])).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "its geometry changed: in place ({:?})", live.fallback);
+ assert_eq!((placed(&live, 41).mesh, placed(&live, 42).mesh, live.sc.meshes.len()), (mesh, mesh, meshes), "the same sections: the mesh where it lies");
+ against_a_build("a geometry of three materials changed, its sections as they were", &mut live, &w);
+ // Other sections (two groups, the first of two bands): a new mesh, the rows as many as it has now.
+ w.set_geometry(31, bands(0.2, &[2, 1])).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "its geometry's groups changed: in place ({:?})", live.fallback);
+ let mesh = placed(&live, 41).mesh;
+ assert_eq!((live.sc.meshes[mesh as usize].sect_count, placed(&live, 42).mesh, materials(&live, 41), materials(&live, 42)), (2, mesh, of(&live, &[62, 65]), of(&live, &[64, 5])), "two sections: two rows an object");
+ against_a_build("a geometry whose groups changed", &mut live, &w);
+ // Three sections again, then four: a freed mesh's sections are the next one's only where they are as many.
+ for groups in [&[1, 1, 1][..], &[1, 1, 1, 1]] {
+ w.set_geometry(31, bands(0.2, groups)).unwrap();
+ let what = format!("a geometry of {} groups after one of fewer", groups.len());
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert_eq!(live.sc.meshes[placed(&live, 41).mesh as usize].sect_count as usize, groups.len(), "{what}: as many sections");
+ against_a_build(&what, &mut live, &w);
+ }
+ // Removed: their rows are the room's again.
+ let (a, b) = (placed(&live, 41).rows, placed(&live, 42).rows);
+ w.remove(41);
+ w.remove(42);
+ assert!(!live.commit(&mut w).unwrap(), "the two removed: in place ({:?})", live.fallback);
+ assert!(rows_free(&live, a, 4) && rows_free(&live, b, 4), "their rows are the room's again");
+ against_a_build("meshes of several materials removed", &mut live, &w);
+}
+
+/// A material that becomes a cutout, or stops being one, in place: the instances with a row of it say so (a mesh, a
+/// mesh of several materials, an instanced object's copies), and the picture is a build's. In a scene without a
+/// cutout the kernel has no alpha test: the first one is a rebuild's. A material created after the build, of any
+/// class (a cutout, glass, one that emits), is added in place with the mesh that is drawn with it.
+#[test]
+fn a_materials_alpha_test_comes_and_goes_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 plain = |extra: serde_json::Value| {
+ let mut m = serde_json::json!({ "name": "m", "color": [0.9, 0.9, 0.9], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });
+ m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ serde_json::from_value::<crate::desc::Material>(m).unwrap()
+ };
+ let two = || Geometry { positions: vec![-0.5, -0.3, 0.0, 0.0, -0.3, 0.0, 0.5, -0.3, 0.0, -0.5, 0.3, 0.0, 0.0, 0.3, 0.0, 0.5, 0.3, 0.0], normals: [0.0, 0.0, 1.0].repeat(6), uvs: vec![0.0; 12], indices: vec![0, 1, 4, 0, 4, 3, 1, 2, 5, 1, 5, 4], groups: vec![[0, 6, 0], [6, 6, 1]], colors: vec![] };
+ // (`cutout`: a material of the scene is a cutout at the build, so the kernel has the alpha test.)
+ let scene = |cutout: bool| {
+ let mut w = world();
+ // (Opacity 0.3: with an alpha test at 0.5, nothing of it is there.)
+ w.set_material(61, plain(serde_json::json!({ "opacity": 0.3, "color": [0.2, 0.6, 0.9] })));
+ w.set_material(62, plain(serde_json::json!({})));
+ w.set_material(63, plain(serde_json::json!({ "opacity": 0.9, "alphaTest": if cutout { 0.5 } else { 0.0 } })));
+ w.set_object(40, "tile".into(), None, Kind::Mesh { geometry: 3, material: 61, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(40, Vec3::new(-0.6, 0.5, 0.6), glam::Quat::IDENTITY, Vec3::splat(1.6)).unwrap();
+ w.set_geometry(30, two()).unwrap();
+ w.set_object(41, "pair".into(), None, Kind::Mesh { geometry: 30, material: 62, own_blas: false, materials: vec![62, 61] }, true, false).unwrap();
+ w.set_transform(41, Vec3::new(0.5, 0.5, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_object(42, "copies".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![61], capacity: 2 }, true, false).unwrap();
+ let at = |x: f32| glam::Mat4::from_translation(Vec3::new(x, -0.5, 0.8)).to_cols_array();
+ w.set_instances(42, 2, Some([at(-0.4), at(0.4)].concat()), None, None).unwrap();
+ w.set_object(43, "other".into(), None, Kind::Mesh { geometry: 3, material: 63, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(43, Vec3::new(1.2, -0.5, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w
+ };
+ let against_a_build = |what: &str, live: &mut LiveCore, w: &World| -> Vec<u8> {
+ let mut fresh = open(w).unwrap();
+ forget(live);
+ let (a, b) = (picture(live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ a
+ };
+ let mut w = scene(true);
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let bits = |c: &LiveCore, name: &str| c.sc.instances.iter().filter(|i| i.name == name && (!i.hidden || i.masked)).map(|i| i.bits & scene::INST_CUTOUT).collect::<Vec<u32>>();
+ let before = picture(&mut live, 64);
+ w.set_material(61, plain(serde_json::json!({ "opacity": 0.3, "color": [0.2, 0.6, 0.9], "alphaTest": 0.5 })));
+ assert!(!live.commit(&mut w).unwrap(), "a material becomes a cutout: in place ({:?})", live.fallback);
+ assert_eq!((bits(&live, "tile"), bits(&live, "pair"), bits(&live, "copies")), (vec![scene::INST_CUTOUT], vec![scene::INST_CUTOUT], vec![scene::INST_CUTOUT; 2]), "their records say they have a cutout");
+ let holes = against_a_build("a material becomes a cutout", &mut live, &w);
+ assert!(apart(&before, &holes) > 0.5, "what was drawn with it is gone ({:.2} steps)", apart(&before, &holes));
+ w.set_material(61, plain(serde_json::json!({ "opacity": 0.3, "color": [0.2, 0.6, 0.9] })));
+ assert!(!live.commit(&mut w).unwrap(), "it stops being one: in place ({:?})", live.fallback);
+ assert_eq!((bits(&live, "tile"), bits(&live, "pair"), bits(&live, "copies")), (vec![0], vec![0], vec![0; 2]), "their records say they have none");
+ let back = against_a_build("a material stops being a cutout", &mut live, &w);
+ assert!(apart(&before, &back) < 0.5, "it is drawn again ({:.2} steps)", apart(&before, &back));
+ // Materials made after the build, of every class, and a mesh drawn with them.
+ w.set_material(71, plain(serde_json::json!({ "opacity": 0.3, "alphaTest": 0.5 })));
+ w.set_material(72, plain(serde_json::json!({ "color": [0.5, 0.9, 0.5], "roughness": 0, "transmission": 1, "ior": 1.5 })));
+ w.set_material(73, plain(serde_json::json!({ "color": [0.0, 0.0, 0.0], "emissive": [1.0, 0.6, 0.2], "emissiveIntensity": 30 })));
+ for (i, material) in [71, 72, 73].into_iter().enumerate() {
+ w.set_object(50 + i as u32, format!("late{i}"), None, Kind::Mesh { geometry: 3, material, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(50 + i as u32, Vec3::new(-1.0 + i as f32, 0.0, 1.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ }
+ assert!(!live.commit(&mut w).unwrap(), "materials of every class made after the build, and meshes of them: in place ({:?})", live.fallback);
+ list_is_its_triangles("a material that emits, made after the build", &live);
+ lit_as_a_build("materials of every class made after the build", &mut live, &mut open(&w).unwrap());
+ // Without a cutout at the build, the first is a rebuild's.
+ let mut w = scene(false);
+ let mut live = open(&w).unwrap();
+ w.take_changes();
+ assert_eq!(live.sc.up.kernel.features & gpu::F_MASKED, 0, "no cutout: the kernel has no alpha test");
+ w.set_material(61, plain(serde_json::json!({ "opacity": 0.3, "color": [0.2, 0.6, 0.9], "alphaTest": 0.5 })));
+ live.commit(&mut w).unwrap();
+ against_a_build("the scene's first cutout", &mut live, &w);
+ assert_ne!(live.sc.up.kernel.features & gpu::F_MASKED, 0, "the kernel has it now");
+}
+
+/// An instanced object given another material, in place: every copy's row names it (a copy that is not shown too),
+/// with its class, and the copies' emitters go or are made with it. Plain, then one that emits, a third copy shown,
+/// a cutout, glass, plain again: each time the light list, the weights and the picture are a build's.
+#[test]
+fn an_instanced_object_given_another_material_has_it_in_its_copies_rows() {
+ 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 plain = |extra: serde_json::Value| {
+ let mut m = serde_json::json!({ "name": "m", "color": [0.9, 0.9, 0.9], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });
+ m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ serde_json::from_value::<crate::desc::Material>(m).unwrap()
+ };
+ let mut w = world();
+ w.set_material(62, plain(serde_json::json!({ "color": [0.2, 0.6, 0.9] })));
+ w.set_material(63, plain(serde_json::json!({ "opacity": 0.3, "alphaTest": 0.5 })));
+ w.set_material(65, plain(serde_json::json!({ "color": [0.5, 0.9, 0.5], "roughness": 0, "transmission": 1, "ior": 1.5 })));
+ let copies = |w: &mut World, material: u32| w.set_object(42, "copies".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![material], capacity: 3 }, true, false).unwrap();
+ let at = |x: f32, y: f32| glam::Mat4::from_translation(Vec3::new(x, y, 0.8)).to_cols_array();
+ // (`by`: the copies moved that far along x.)
+ let placed = |w: &mut World, count: u32, by: f32| w.set_instances(42, count, Some([at(-0.5 + by, -0.5), at(0.4 + by, -0.5), at(by, 0.5)].concat()), None, None).unwrap();
+ let shown = |w: &mut World, count: u32| placed(w, count, 0.0);
+ copies(&mut w, 62);
+ shown(&mut w, 2);
+ // (A cutout at the build: the kernel has the alpha test.)
+ w.set_object(43, "other".into(), None, Kind::Mesh { geometry: 3, material: 63, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(43, Vec3::new(1.3, 0.6, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let named = |c: &LiveCore, material: u32| {
+ let place = *c.sc.tables.retained.instanced(42).expect("the copies are instances");
+ (0..3).all(|i| scene::row_material(&c.sc.rows[c.sc.instances[place.first as usize + i].rows as usize]) == c.sc.tables.retained.materials[&material])
+ };
+ let mut last = picture(&mut live, 64);
+ for (material, count, what) in [(5, 2, "one that emits"), (5, 3, "the third copy shown"), (63, 3, "a cutout"), (65, 3, "glass"), (62, 3, "a plain one again")] {
+ copies(&mut w, material);
+ shown(&mut w, count);
+ let what = format!("an instanced object given {what}");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert!(named(&live, material), "{what}: its copies' rows name it, the one not shown too");
+ if live.sc.tables.emitter_tris.iter().any(|e| e.area > 0.0) {
+ list_is_its_triangles(&what, &live);
+ }
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ let now = picture(&mut live, 64);
+ assert!(apart(&last, &now) > 0.5, "{what}: it is in the picture ({:.2} steps)", apart(&last, &now));
+ last = now;
+ }
+ // Another material and another place in one commit: the emitters are where the copies are now.
+ copies(&mut w, 5);
+ placed(&mut w, 3, 0.35);
+ let what = "an instanced object given a material that emits and moved at once";
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(what, &live);
+ lit_as_a_build(what, &mut live, &mut open(&w).unwrap());
+ copies(&mut w, 62);
+ assert!(!live.commit(&mut w).unwrap(), "plain again: in place ({:?})", live.fallback);
+ // Its material starts emitting while a copy is not shown: that copy's emitters weigh nothing.
+ shown(&mut w, 2);
+ assert!(!live.commit(&mut w).unwrap(), "a copy hidden: in place ({:?})", live.fallback);
+ w.set_material(62, plain(serde_json::json!({ "color": [0.2, 0.6, 0.9], "emissive": [1.0, 0.7, 0.4], "emissiveIntensity": 25 })));
+ let what = "the copies' material starts emitting, a copy not shown";
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(what, &live);
+ lit_as_a_build(what, &mut live, &mut open(&w).unwrap());
+}
+
+/// What still changes by a rebuild: a material of world-space triangles. Particles' (dynamic triangles: their class
+/// is theirs, and they get no emitters in place) when it starts emitting or becomes a cutout; one that still
+/// triangles have (the build groups them by whether they are cutouts) when it becomes a cutout. The same change of
+/// a material that only instances' rows name is in place.
+#[test]
+fn a_material_of_world_space_triangles_changes_by_a_rebuild() {
+ 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 plain = |extra: serde_json::Value| {
+ let mut m = serde_json::json!({ "name": "m", "color": [0.9, 0.9, 0.9], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });
+ m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ serde_json::from_value::<crate::desc::Material>(m).unwrap()
+ };
+ let mut w = world();
+ w.set_material(62, plain(serde_json::json!({})));
+ w.set_material(63, plain(serde_json::json!({ "opacity": 0.9, "alphaTest": 0.5 })));
+ w.set_material(64, plain(serde_json::json!({ "opacity": 0.9 })));
+ w.set_particle_fn("spark", "fn pf_spark(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(vec3<f32>(0.3, 0.2, 1.0), vec3<f32>(0.05, 0.0, 0.0), vec3<f32>(0.0, 0.05, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());
+ w.set_object(18, "sparks".into(), None, Kind::Particles { count: 3, emitter: "spark".into(), params: vec![], material: 62, emitter_area: 0.01 }, true, false).unwrap();
+ // (A cutout at the build: the kernel has the alpha test. And a mesh of a material of its own.)
+ w.set_object(43, "cut".into(), None, Kind::Mesh { geometry: 3, material: 63, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(43, Vec3::new(1.2, -0.5, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_object(44, "tile".into(), None, Kind::Mesh { geometry: 3, material: 64, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(44, Vec3::new(-1.0, -0.5, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let index = |c: &LiveCore, id: u32| c.sc.tables.retained.materials[&id];
+ assert!(live.sc.tables.moving_mats.contains(&index(&live, 62)) && !live.sc.tables.moving_mats.contains(&index(&live, 64)), "the particles' material is dynamic triangles', the tile's is not");
+ // The tile's material, which rows alone name: a cutout and back, in place.
+ for (test, what) in [(0.5, "becomes a cutout"), (0.0, "is none again")] {
+ w.set_material(64, plain(serde_json::json!({ "opacity": 0.9, "alphaTest": test })));
+ assert!(!live.commit(&mut w).unwrap(), "a material of rows {what}: in place ({:?})", live.fallback);
+ }
+ // The same, were it still triangles' too: a rebuild.
+ let k = index(&live, 64);
+ live.sc.tables.static_mats.insert(k);
+ w.set_material(64, plain(serde_json::json!({ "opacity": 0.9, "alphaTest": 0.5 })));
+ assert!(live.commit(&mut w).unwrap(), "a material of still triangles becomes a cutout: a rebuild");
+ // The particles' material: it starts emitting, it becomes a cutout.
+ w.set_material(62, plain(serde_json::json!({ "emissive": [1.0, 0.8, 0.6], "emissiveIntensity": 20 })));
+ assert!(live.commit(&mut w).unwrap(), "the particles' material starts emitting: a rebuild");
+ w.set_material(62, plain(serde_json::json!({ "emissive": [1.0, 0.8, 0.6], "emissiveIntensity": 20, "opacity": 0.9, "alphaTest": 0.5 })));
+ assert!(live.commit(&mut w).unwrap(), "the particles' material becomes a cutout: a rebuild");
+}
+
+/// A material that turns glass takes its instances' shadows with it, in place, and gives them back when it is
+/// plain again: a screen before the wall in the sun, of a material of its own. The picture is a build's each time.
+#[test]
+fn a_material_turned_glass_stops_casting_its_shadow_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 screen = |glass: bool| {
+ let mut m = serde_json::json!({ "name": "m", "color": [0.9, 0.9, 0.9], "opacity": 1, "metalness": 0, "roughness": if glass { 0.0 } else { 1.0 }, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true });
+ if glass {
+ m.as_object_mut().unwrap().extend(serde_json::json!({ "transmission": 1, "ior": 1.5 }).as_object().unwrap().clone());
+ }
+ serde_json::from_value::<crate::desc::Material>(m).unwrap()
+ };
+ let mut w = world();
+ w.set_material(66, screen(false));
+ w.set_object(45, "screen".into(), None, Kind::Mesh { geometry: 2, material: 66, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(45, Vec3::new(0.3, 0.0, 0.5), glam::Quat::IDENTITY, Vec3::splat(0.5)).unwrap();
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ let casts = |c: &LiveCore| c.sc.instances.iter().find(|i| i.name == "screen").expect("the screen is an instance").cast_shadow;
+ let mut last = picture(&mut live, 64);
+ for glass in [true, false, true] {
+ w.set_material(66, screen(glass));
+ let what = if glass { "the screen's material turns glass" } else { "it is plain again" };
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert_eq!(casts(&live), !glass, "{what}: whether it casts a shadow");
+ let mut fresh = open(&w).unwrap();
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ assert!(apart(&last, &a) > 0.5, "{what}: it is in the picture ({:.2} steps)", apart(&last, &a));
+ last = a;
+ }
}
/// Models in a shared pose posed again in place (tests/render/data/arm.glb: a skinned strip, a dark half and a light
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 0fcb945..a762808 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -13,6 +13,9 @@ pub(super) struct LoadedScene {
/// Flattened instances of instanced objects: (first, end, instance index), for picking.
pub(super) tri_instances: Vec<(u32, u32, u32)>,
pub(super) pool_tris: Vec<[glam::Vec3A; 3]>,
+ /// Software traversal: each pool triangle's section and its index in it (a unit's tree orders its mesh's
+ /// triangles; live/edits.rs `mesh_places`). Empty under hardware traversal, where they lie by section.
+ pub(super) pool_place: Vec<[u32; 2]>,
pub(super) meshes: Vec<scene::InstMesh>,
pub(super) instances: Vec<scene::Instance>,
/// The meshes' sections and the instances' rows as the GPU has them (`scene::Scene::sections`, `rows`); what an
@@ -220,8 +223,8 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let mut tables = tables::Tables::new(&sc, std::mem::take(&mut prep.emitter_tris), prep.light_tree.take());
// (THREERT_EDIT_REBUILD=1: every edit rebuilds, a material that starts emitting too: the A/B.)
tables.emit_in_place = std::env::var("THREERT_EDIT_REBUILD").map_or(true, |v| v != "1");
- tables.fixed_mats = std::mem::take(&mut prep.fixed_mats);
- tables.mesh_mats = std::mem::take(&mut prep.mesh_mats);
+ tables.static_mats = prep.mat_runs.keys().copied().collect();
+ tables.moving_mats = std::mem::take(&mut prep.moving_mats);
let emit = EmitterWorker::new(&tables, &g.device);
tables.defer_powers = emit.is_some();
let (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));
@@ -253,6 +256,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let (tris, tri_nodes, tri_instances) = (std::mem::take(&mut sc.tris), std::mem::take(&mut sc.tri_nodes), std::mem::take(&mut sc.tri_instances));
let instanced = !sc.gpu_instances.is_empty() || !sc.procs.is_empty();
let instance_features = gpu::instance_features(&sc);
+ let pool_place: Vec<[u32; 2]> = if up.units.is_some() { sc.pool_attrs.iter().map(|a| [a.uv[3].to_bits(), a.x[3].to_bits()]).collect() } else { vec![] };
let (pool_tris, meshes, instances) = (std::mem::take(&mut sc.pool_tris), std::mem::take(&mut sc.meshes), std::mem::take(&mut sc.instances));
let (sections, rows) = (std::mem::take(&mut sc.sections), std::mem::take(&mut sc.rows));
let mut gpu_instances = std::mem::take(&mut sc.gpu_instances);
@@ -298,5 +302,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
pool_first: prep.groups.iter().sum(),
blobs,
};
- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, 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, dynamic, edit, emit, mat_runs, tri_order }, view, env))
+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, 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, dynamic, edit, emit, mat_runs, tri_order }, view, env))
}
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index 56c7a42..e91a8d7 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -22,6 +22,9 @@ pub struct Dirty {
/// Power edits held back (`Tables::defer_powers`): the live view's emitter worker rebuilds the CDF and the tree's
/// powers for them, and they land together.
pub deferred: bool,
+ /// A material's class changed (glass or not, a cutout or not): the instances with a row of one have their rows
+ /// remade (live/edits.rs `remake_classes`).
+ pub reclassed: bool,
}
impl Dirty {
@@ -40,15 +43,19 @@ pub struct Tables {
pub light_tree: Option<crate::ltree::LightTree>,
/// Materials that have emitter triangles (others cannot start emitting without a rebuild).
pub(crate) emissive: HashSet<u32>,
- /// A material that starts emitting gets emitter entries in place (the live view sets these up, `prepare`'s
- /// `mat_runs` / `fixed_mats`): it is queued in `started_emitting` for live/edits.rs `add_material_emitters`, unless its
- /// triangles include a model's, an instanced object's or dynamic ones (`fixed_mats` less `mesh_mats`, the materials
- /// whose pool triangles are meshes' alone). Off: such a material rebuilds. `fixed_mats` are also the materials of
- /// instances' triangles, whose class a rebuild sorts by (`apply`).
+ /// A material that starts emitting gets emitter entries in place (the live view sets this up): it is queued in
+ /// `started_emitting` for live/edits.rs `add_material_emitters`, which gives them to its still world-space
+ /// triangles (`prepare`'s `mat_runs`) and to the instances with a row of it. Off: such a material rebuilds.
pub emit_in_place: bool,
- pub fixed_mats: HashSet<u32>,
- pub mesh_mats: HashSet<u32>,
+ /// Materials of still world-space triangles (what the build flattened): whether one is a cutout decides its
+ /// triangles' traversal group, so that changing is a rebuild's.
+ pub static_mats: HashSet<u32>,
+ /// Materials of dynamic world-space triangles (particles'): their class is the triangle's, and they get no
+ /// emitters in place. One that starts emitting, or whose class changes, rebuilds.
+ pub moving_mats: HashSet<u32>,
pub started_emitting: Vec<u32>,
+ /// Materials whose class changed in the last `apply` (`Dirty::reclassed`).
+ pub reclassed: Vec<u32>,
/// Object -> its entries in `lights`.
pub light_index: HashMap<u32, Vec<usize>>,
/// vec4s an object in `objects` (`scene::object_stride`).
@@ -75,9 +82,10 @@ impl Tables {
emitter_tris,
light_tree,
emit_in_place: false,
- fixed_mats: HashSet::new(),
- mesh_mats: HashSet::new(),
+ static_mats: HashSet::new(),
+ moving_mats: HashSet::new(),
started_emitting: vec![],
+ reclassed: vec![],
light_index,
stride: sc.object_stride(),
defer_powers: false,
@@ -154,14 +162,20 @@ impl Tables {
if !self.can_emit(mi, &gm) {
return Ok(None);
}
- // (A material of instances' triangles that gets a function, or loses it: the kernel's variant goes by
- // whether there is one, `gpu::F_IFUNC`, which the build decides. One that turns glass, or stops being
- // glass: an instance's row and mask say so, a model's mesh has its triangles in a geometry apart by it. One
- // whose alpha test changes never comes here: that is structural, world.rs `same_texture_refs`.)
+ // A material whose class changes (it turns glass or stops being glass, becomes a cutout or stops being
+ // one, gets a function or loses it): the instances with a row of it say so again, in place
+ // (`Dirty::reclassed`). Its world-space triangles cannot: still ones are in a traversal group by whether
+ // they are cutouts, dynamic ones carry their class.
let old = &self.materials[mi as usize];
- if ((gm.tex1[3] != 0) != (old.tex1[3] != 0) || (gm.layer[0] > 0.0) != (old.layer[0] > 0.0)) && self.fixed_mats.contains(&mi) {
+ let cutout = (gm.uv2[3] > 0.0) != (old.uv2[3] > 0.0);
+ let other = (gm.tex1[3] != 0) != (old.tex1[3] != 0) || (gm.layer[0] > 0.0) != (old.layer[0] > 0.0);
+ if (cutout && self.static_mats.contains(&mi)) || ((cutout || other) && self.moving_mats.contains(&mi)) {
return Ok(None);
}
+ if cutout || other {
+ self.reclassed.push(mi);
+ d.reclassed = true;
+ }
self.materials[mi as usize] = gm;
d.materials = true;
}
@@ -226,8 +240,8 @@ impl Tables {
/// Whether a material may emit without a rebuild: it already has emitter entries, or (`emit_in_place`) its
/// triangles can get them in place, queued in `started_emitting` (ROADMAP § 6 step 3).
/// Materials created since the build (`Changes::new_materials`: no texture, no function), as entries after the
- /// scene's. False, and nothing added, if one of them cannot be: it emits, is glass or layered, or a cutout (the
- /// build sorts triangles by those; the caller rebuilds).
+ /// scene's, whatever their class: what an edit draws with one is an instance, whose rows say it. False, and
+ /// nothing added, if one of them cannot be made.
pub fn add_materials(&mut self, w: &World, ids: &std::collections::BTreeSet<u32>) -> bool {
let mut fresh = vec![];
for id in ids {
@@ -236,17 +250,12 @@ impl Tables {
}
let Some(m) = w.materials.get(id) else { return false };
let Ok(gm) = scene::build_material(*id, m, &w.textures, &self.retained.shaders, &mut |_, _| Err(anyhow!("a texture"))) else { return false };
- if scene::material_class(&gm) != 0 {
- return false;
- }
fresh.push((*id, gm));
}
for (id, gm) in fresh {
let mi = self.materials.len() as u32;
self.retained.materials.insert(id, mi);
self.materials.push(gm);
- // (What is drawn with it are instances' triangles: it cannot start emitting in place, `can_emit`.)
- self.fixed_mats.insert(mi);
}
true
}
@@ -256,7 +265,7 @@ impl Tables {
if lum <= 0.0 || self.emissive.contains(&mi) {
return true;
}
- if !self.emit_in_place || (self.fixed_mats.contains(&mi) && !self.mesh_mats.contains(&mi)) {
+ if !self.emit_in_place || self.moving_mats.contains(&mi) {
return false;
}
self.emissive.insert(mi);
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 3992024..9db491a 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -418,7 +418,7 @@ impl Default for World {
fn same_texture_refs(a: &desc::Material, b: &desc::Material) -> bool {
let maps = |m: &desc::Material| [m.map, m.normal_map, m.roughness_map, m.metalness_map, m.ao_map, m.emissive_map, m.transmission_map];
let func = |m: &desc::Material| m.shader.as_ref().map(|s| (s.id.clone(), s.textures.clone()));
- maps(a) == maps(b) && func(a) == func(b) && a.alpha_test.unwrap_or(0.0) == b.alpha_test.unwrap_or(0.0)
+ maps(a) == maps(b) && func(a) == func(b)
}
fn light_class(l: &desc::Light) -> (u8, bool, bool) {
@@ -550,7 +550,7 @@ impl World {
let static_parent = parent.is_none_or(|p| !self.objects.contains_key(&p) || !self.movable(p));
let mesh = matches!(kind, Kind::Mesh { .. });
// A new instanced mesh or static model is placed in place too (ROADMAP § 6 step 5; live/edits.rs `edit_geometry`
- // says when it cannot); changing one still rebuilds.
+ // says when it cannot); changing one still rebuilds, but for an instanced mesh's materials (`rematerialed`).
let placed_new = !self.objects.contains_key(&id) && matches!(kind, Kind::Instanced { procedural: false, .. } | Kind::Model { animation: None, .. });
let fresh = (edits_in_place(&kind) || placed_new)
&& (mesh || (!movable && static_parent))
@@ -558,6 +558,14 @@ impl World {
None => true,
Some(o) => (mesh || !self.movable(id)) && o.parent == parent && o.cast_shadow == cast_shadow && std::mem::discriminant(&o.kind) == std::mem::discriminant(&kind) && edits_in_place(&o.kind),
};
+ // An instanced mesh given other materials (the same geometry and capacity, the same parent and shadow flag): its
+ // copies' rows say them, in place (live/edits.rs `update_instanced`).
+ let rematerialed = match (self.objects.get(&id), &kind) {
+ (Some(o), Kind::Instanced { geometry, procedural: false, capacity, .. }) => {
+ matches!(&o.kind, Kind::Instanced { geometry: g, procedural: false, capacity: c, .. } if g == geometry && c == capacity) && o.parent == parent && o.cast_shadow == cast_shadow && (o.movable || !movable)
+ }
+ _ => false,
+ };
match &kind {
Kind::Instanced { capacity, .. } => {
if self.instanced.get(&id).is_some_and(|t| t.matrices.len() != *capacity as usize * 16) {
@@ -575,6 +583,8 @@ impl World {
self.objects.insert(id, o);
if fresh {
self.changes.added.insert(id);
+ } else if rematerialed {
+ self.changes.instanced.insert(id);
} else {
self.changes.structural = true;
}
@@ -1618,12 +1628,13 @@ mod tests {
w.set_transform(2, Vec3::X, Quat::IDENTITY, Vec3::ONE).unwrap();
let c = w.take_changes();
assert!(!c.structural && c.materials.contains(&1) && c.powers.contains(&1) && c.camera);
- // An alpha test that comes, changes or goes: a rebuild (an instance's row says whether its material is a
- // cutout's, and the kernel's variant goes by whether there is one).
+ // An alpha test that comes, changes or goes is the material's change (the tables say whether its triangles
+ // can follow in place: tables.rs `apply`).
for (test, what) in [(Some(0.5), "an alpha test"), (Some(0.3), "another threshold"), (None, "no alpha test again")] {
m.alpha_test = test;
w.set_material(1, m.clone());
- assert!(w.take_changes().structural, "{what}: structural");
+ let c = w.take_changes();
+ assert!(!c.structural && c.materials.contains(&1), "{what}: the material's change");
}
m.map = Some(7);
w.set_material(1, m);