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.

An instanced object's emitting copies are instances, their emitters in the light list (#159)

Yujia8cfb017ff0fc
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index f94b494..d51c8b3 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2700,6 +2700,20 @@ its own measured step, not taking emitters out of their meshes again.
Tests: `geometry/emitter-model` (a model's emitters, analytic; tests/render/data/panel.glb), the readback test
with a model still, movable and posed. Still flattened: an instanced object's copies (the next part).
+**An instanced object's emitters (2026-11-18).** The copies of an instanced mesh whose material only emits are
+instances of its one mesh, as any other copies are, each with its run of the light list (the capacity's, shown or
+not). A copy not shown (past `count`, or scaled to 0) has no power in its object entry: its emitters stay in the
+list and in the light tree at no weight, at their mesh's own area, so showing it needs no new entry; while hidden
+it bounds nothing there (the refit of the tree's moving subtree skips a hidden instance's emitters). A change in
+place (`update_instanced`) takes the copies' triangles again on the GPU and refits the tree's moving subtree; when a
+copy changed size or power, or was shown or hidden, the emitters are weighed again in the same commit (the CDF and
+the tree's powers whole, on the CPU, as a power edit without the worker: a scene with such copies has none).
+Removed in place, its emitters go as an instance's do. Still a rebuild: an emitting instanced object added in
+place. Still flattened: glass, material functions, mirrored copies (the next parts).
+Tests: `geometry/emitter-instanced` (analytic), `geometry/emitter-instanced-live` (copies moved, scaled up and
+shown in place), the build's, and the edits in place against a build (a copy moved, larger, shown, hidden two ways,
+the node's power, the object removed; with and without a light tree).
+
**An emitter's probability is what the picker used (2026-11-18).** An emitter that changed size in place (a movable
model or mesh scaled, a skinned one) kept the weight it was loaded with, while the kernel took its probability from
formulas that assumed the weight was the triangle's: scaled three times larger as a scene's main light it read 3 to
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index bd09423..e5c45d9 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1625,7 +1625,9 @@ over a polished floor, the camera still):
![Before and after: a dragged device's edge lines and text copies, a thrown light's trail and its streak in the floor's reflection](images/object-ghosting.jpg)
Not covered: the specular clip also cuts a right history where the lighting is live all the time (a crowd's
-reflections are darker than offline's: it wants a short-term history to clip against, as the diffuse has); a fast
+reflections are darker than offline's). A short-term specular history to clip against is no answer: at one sample
+a pixel it is noise (tried and dropped: `dtemporal`'s anti-lag note). The clip is transitional: it goes when a
+change in the lighting can be told from noise (last frame's path traced again with its random numbers). A fast
light's effect on diffuse lighting (a shadow it casts) still lags by a few frames (the diffuse
history and its anti-lag), and the band just uncovered starts from this frame's samples (more aliased for a frame or
two, as any disocclusion).
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 667b0fc..afac931 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -181,20 +181,30 @@ impl GpuEmitterTri {
/// The emitters of an instance of a mesh that emits (`scene::InstMesh::emitters`, `count` of them): one a numbered
/// triangle, in the numbers' order, each with its triangle as the instance places it. `tris`: the mesh's, in model
/// space; `first`: its first triangle in the triangles' table; `numbered(k)`: triangle k's number and material, if
-/// it emits; `record`: the instance's. A hidden instance's, and a triangle of no area: no weight (area 0).
+/// it emits; `record`: the instance's. A triangle of no area: no weight (area 0). A hidden instance's (an instanced
+/// object's copy not shown) keep their mesh's own area: its object has no power, so they weigh nothing, and the light
+/// tree has them (`switchable_power`) for when the copy is shown.
pub fn instance_emitters(inst: &scene::Instance, record: u32, tris: &[[glam::Vec3A; 3]], first: u32, numbered: &dyn Fn(usize) -> Option<(usize, u32)>, count: usize, materials: &[scene::GpuMaterial], moves: bool) -> Vec<(EmitterTri, [glam::Vec3A; 3])> {
let dead = EmitterTri { tri: first, mat: 0, obj: inst.object, area: 0.0, c: [0.0; 3], moves, nominal: false, in_tree: false, inst: record };
let mut out = vec![(dead, [glam::Vec3A::ZERO; 3]); count];
for (k, t) in tris.iter().enumerate() {
let Some((slot, mat)) = numbered(k) else { continue };
- let w = t.map(|v| glam::Vec3A::from(inst.world.transform_point3(v.into())));
- let emits = materials.get(mat as usize).is_some_and(|m| 0.2126 * m.emissive[0] + 0.7152 * m.emissive[1] + 0.0722 * m.emissive[2] > 0.0);
- let area = if emits && !inst.hidden { 0.5 * (w[1] - w[0]).cross(w[2] - w[0]).length() } else { 0.0 };
- out[slot] = (EmitterTri { tri: first + k as u32, mat, area, c: ((w[0] + w[1] + w[2]) / 3.0).to_array(), ..dead }, w);
+ let (area, c, w) = placed_emitter(inst, t, mat, materials);
+ out[slot] = (EmitterTri { tri: first + k as u32, mat, area, c, ..dead }, w);
}
out
}
+/// An instance's emitter of its mesh's triangle `t` (material `mat`): its area, its centre and the triangle as the
+/// instance places it (`instance_emitters` has which area).
+pub fn placed_emitter(inst: &scene::Instance, t: &[glam::Vec3A; 3], mat: u32, materials: &[scene::GpuMaterial]) -> (f32, [f32; 3], [glam::Vec3A; 3]) {
+ let w = t.map(|v| glam::Vec3A::from(inst.world.transform_point3(v.into())));
+ let emits = materials.get(mat as usize).is_some_and(|m| 0.2126 * m.emissive[0] + 0.7152 * m.emissive[1] + 0.0722 * m.emissive[2] > 0.0);
+ let shape = if inst.hidden { *t } else { w };
+ let area = if emits { 0.5 * (shape[1] - shape[0]).cross(shape[2] - shape[0]).length() } else { 0.0 };
+ (area, ((w[0] + w[1] + w[2]) / 3.0).to_array(), w)
+}
+
/// Runs of the light list (first emitter, count) whose triangles something moves after the load; the GPU takes them
/// again from where the triangles are (gpu.rs `EmitterFill`): the emitters of the triangles the CPU reposes, and the
/// particles', which their passes place. (An instance that moves has its run filled when it does: live/edits.rs.)
@@ -703,10 +713,12 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
let n = scene::number_emitters(&mut sc.attrs[pool_first + m.first as usize..pool_first + (m.first + m.count) as usize], &sc.materials);
assert_eq!(n, m.emitters, "a mesh's emitters as the build counted them");
}
- // (The instances an edit moves in place: a body's, a movable model's, a posed rigid model's nodes'.)
+ // (The instances an edit moves in place: a body's, a movable model's, a posed rigid model's nodes', an instanced
+ // object's copies.)
let moving: std::collections::HashSet<u32> = sc.retained.proxies.values().flat_map(|p| match &p.draw {
scene::Draw::Instance(i) if i.moves => 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![],
}).collect();
for r in 0..sc.instances.len() {
@@ -749,7 +761,13 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// (Switched-off objects at full power: `switchable_power`.)
let all_power: f32 = emitter_tris.iter().map(|e| switchable_power(e, &sc.materials, &sc.objects, sc.object_stride())).sum();
let use_tree = std::env::var("THREERT_LTREE").map_or(true, |v| v != "0");
- let light_tree = if use_tree { light_tree_of(&emitter_tris, &|i| gpu_emitter_tris[i].vertices(), &sc.materials, &sc.objects, sc.object_stride(), sc.emitter_slot) } else { None };
+ let mut light_tree = if use_tree { light_tree_of(&emitter_tris, &|i| gpu_emitter_tris[i].vertices(), &sc.materials, &sc.objects, sc.object_stride(), sc.emitter_slot) } else { None };
+ // (A hidden instance's emitters, an instanced object's copies not shown, bound nothing: the moving subtree's
+ // spheres without them, as an edit leaves them.)
+ let gone = |i: usize| sc.instances.get(emitter_tris[i].inst as usize).is_some_and(|x| x.hidden);
+ if let Some(t) = light_tree.as_mut().filter(|_| (0..emitter_tris.len()).any(gone)) {
+ t.refit_moving(&|i| (!gone(i)).then(|| gpu_emitter_tris[i].vertices()));
+ }
// The list keeps its own order (the tree and the CDF name its emitters: `emitter_order`); each emitter carries
// where the kernel finds its weight (`emitter_codes`).
if let Some(t) = &light_tree {
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index c27cdd7..43c1f41 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -576,7 +576,7 @@ impl LiveCore {
if d.objects {
up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
}
- if d.materials || d.emitters {
+ if d.materials || d.emitters || std::mem::take(&mut self.emitters_reweigh) {
let new = self.add_material_emitters();
self.write_emitters(&new);
} else if d.deferred {
@@ -1043,7 +1043,9 @@ impl LiveCore {
/// kernel records (the old transforms kept as the previous frame's, for motion vectors), object entries (pivot,
/// bounds, power, data, colour), TLAS transforms and masks (`scene::instance_world`: a hidden instance 0), each
/// object's records and entries written as one range; the commit builds what is above them. No triangles or
- /// BLASes change. Returns how many objects it updated; Err: why it cannot (software traversal, an object the build
+ /// 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`).
+ /// Returns how many objects it updated; Err: why it cannot (software traversal, an object the build
/// flattened or did not place this way, an instance now mirrored), 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> {
@@ -1057,6 +1059,7 @@ impl LiveCore {
let sc = &mut self.sc;
let Some(mut top) = gpu::Top::of(&mut sc.up.accel, &mut sc.up.units) else { return Err("software traversal".into()) };
let mut done = 0;
+ let (mut emitting, mut reweigh): (Vec<u32>, bool) = (vec![], false);
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 };
@@ -1083,6 +1086,7 @@ impl LiveCore {
return Err("an instance is mirrored".into());
}
let old = sc.gpu_instances[rec0 + i];
+ let mut emits = false;
let (mut rec, entry) = if procedural {
let p = &mut sc.procs[first + i];
(p.world, p.hidden) = (wm, hidden);
@@ -1093,8 +1097,23 @@ impl LiveCore {
return Err("an instanced mesh that is no unit (software traversal)".into());
}
(inst.world, inst.hidden) = (wm, hidden);
- let (lo, hi) = sc.meshes[inst.mesh as usize].placed_bounds(wm);
- (top.record(inst.gpu(old.info[0], old.info[3]), inst.mesh, n.cast_shadow), scene::object_row(wm.transform_point3(glam::Vec3::ZERO), n.power, hi - lo, t.custom(i, n.custom), t.color(i)))
+ let im = sc.meshes[inst.mesh as usize];
+ emits = im.emitters > 0;
+ let (lo, hi) = im.placed_bounds(wm);
+ let row = scene::object_row(wm.transform_point3(glam::Vec3::ZERO), n.power, hi - lo, t.custom(i, n.custom), t.color(i));
+ if emits {
+ // Its emitters as it is placed now (their triangles on the GPU: `fill_moved` below).
+ let run = emitter_run(&sc.tables.emitter_tris, &sc.instances, (rec0 + i) as u32);
+ let inst = &sc.instances[first + i];
+ for e in &mut sc.tables.emitter_tris[run] {
+ let (area, c, _) = crate::placed_emitter(inst, &sc.pool_tris[e.tri as usize - sc.edit.pool_first], e.mat, &sc.tables.materials);
+ reweigh |= (area - e.area).abs() > 1e-5 * area.max(e.area);
+ (e.area, e.c) = (area, c);
+ }
+ emitting.push((rec0 + i) as u32);
+ }
+ let inst = &sc.instances[first + i];
+ (top.record(inst.gpu(old.info[0], old.info[3]), inst.mesh, n.cast_shadow), scene::copy_row(row, emits && hidden))
};
rec.p = old.m;
sc.gpu_instances[rec0 + i] = rec;
@@ -1102,6 +1121,7 @@ impl LiveCore {
let st = sc.tables.stride;
let at = (place.object as usize + i) * st;
let e = &mut sc.tables.objects[at..at + st];
+ reweigh |= emits && e[0][3] != entry[0][3];
let edited = if e[0][3] != entry[0][3] { now } else { e[1][3] };
e.copy_from_slice(&entry[..st]);
e[1][3] = edited;
@@ -1122,6 +1142,8 @@ impl LiveCore {
self.inst_moved = true;
build.instances = true;
}
+ self.fill_moved(emitting.into_iter());
+ self.emitters_reweigh |= reweigh;
Ok(done)
}
@@ -1390,7 +1412,14 @@ impl LiveCore {
/// The emitters of instances that moved (those of a mesh that emits): their runs of the light list taken again on
/// the GPU, through the records just queued; the light tree's moving subtree after (`move_emitters`).
pub(super) fn fill_moved(&mut self, records: impl Iterator<Item = u32>) {
- let runs: Vec<[u32; 2]> = records.map(|i| emitter_run(&self.sc.tables.emitter_tris, &self.sc.instances, i)).filter(|r| !r.is_empty()).map(|r| [r.start as u32, r.len() as u32]).collect();
+ // (Runs that follow each other as one: an instanced object's copies'.)
+ let mut runs: Vec<[u32; 2]> = vec![];
+ for r in records.map(|i| emitter_run(&self.sc.tables.emitter_tris, &self.sc.instances, i)).filter(|r| !r.is_empty()) {
+ match runs.last_mut() {
+ Some(l) if l[0] + l[1] == r.start as u32 => l[1] += r.len() as u32,
+ _ => runs.push([r.start as u32, r.len() as u32]),
+ }
+ }
if !runs.is_empty() {
self.g.fill_emitter_runs(&self.sc.up, &runs);
self.emitters_moved = true;
@@ -1414,13 +1443,13 @@ impl LiveCore {
let (instances, pool_tris, pool_first) = (&self.sc.instances, &self.sc.pool_tris, self.sc.edit.pool_first);
t.refit_moving(&|e| {
let x = &tris[e];
- // (An instance's: its mesh's triangle, placed.)
+ // (An instance's: its mesh's triangle, placed; none while the instance is hidden.)
if x.inst != crate::NO_INST {
- let w = instances[x.inst as usize].world;
- return pool_tris[x.tri as usize - pool_first].map(|v| w.transform_point3(v.into()).to_array());
+ let i = &instances[x.inst as usize];
+ return (!i.hidden).then(|| pool_tris[x.tri as usize - pool_first].map(|v| i.world.transform_point3(v.into()).to_array()));
}
let r = (x.tri as usize - first) * 3;
- crate::ltree::tri_vertices(&verts[r..r + 3])
+ Some(crate::ltree::tri_vertices(&verts[r..r + 3]))
});
heap.write(q, Table::LightTree, 0, bytemuck::cast_slice(&t.nodes[..1]));
heap.write(q, Table::LightTree, 2 * 16, bytemuck::cast_slice(&t.nodes[2..3]));
@@ -1608,6 +1637,10 @@ impl LiveCore {
let (r0, cap) = (place.first as usize, place.capacity as usize);
for r in r0..r0 + cap {
top.clear(inst_base + r);
+ // (A copy's emitters go as an instance's do.)
+ let run = emitter_run(&tables.emitter_tris, instances, r as u32);
+ emitters_changed |= !run.is_empty();
+ tables.emitter_tris[run].iter_mut().for_each(|e| e.area = 0.0);
if let Some(i) = instances.get_mut(r) {
i.hidden = true;
}
@@ -2132,6 +2165,8 @@ impl LiveCore {
self.edit_split.add(&split);
if emitters_changed {
self.write_emitters(&new_emitters);
+ // (Instances' emitters came or went: the tree's moving subtree around those there, at the commit's end.)
+ self.emitters_moved = true;
}
Ok(())
}
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 3986918..3d0eac8 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -433,10 +433,98 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
assert!(alive > 0, "{what}: the list has emitters");
}
-/// The light list's copies of its emitters' triangles follow them: as loaded, after an emitter the CPU moves has
-/// moved (in the light tree's moving subtree, and without a tree), after an emitting mesh a body drives has moved,
-/// after a model's placement or its clip has moved its emitters, after a particle's pass has placed it, and after
-/// the edits that make emitters in place (a mesh added, given other triangles and removed, with the tree's slot for
+/// An instanced object's copies that emit, changed in place, are lit as a build lights them: a copy moved, made
+/// larger, shown by the count, hidden by a matrix scaled to 0 and by the count, the node's power changed, the object
+/// removed; with and without a light tree. After each: no rebuild, the light list is its triangles, the emitters'
+/// weights are a build's, and so is the picture; and the tree's moving subtree is no wider for a copy that is not
+/// shown (one waits 300 m away), nor for an object that was removed.
+#[test]
+fn emitting_copies_changed_in_place_are_lit_as_a_build_lights_them() {
+ 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));
+ for tree in [false, true] {
+ let mut w = world();
+ // (The sun and the lamp away: the copies light the scene.)
+ w.set_visible(20, false).unwrap();
+ w.set_visible(12, false).unwrap();
+ w.set_object(15, "copies".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![5], capacity: 3 }, true, false).unwrap();
+ let at = |x: f32, y: f32, z: f32, s: f32| glam::Mat4::from_scale_rotation_translation(Vec3::splat(s), glam::Quat::from_rotation_y(0.3), Vec3::new(x, y, z)).to_cols_array();
+ let set = |w: &mut World, count: u32, m: [[f32; 16]; 3]| w.set_instances(15, count, Some(m.concat()), None, None).unwrap();
+ // (The third copy waits far away, past the count.)
+ let (b, c, far) = (at(0.5, 0.5, 1.0, 0.4), at(0.0, 0.0, 1.4, 0.4), at(300.0, 0.0, 1.4, 0.4));
+ set(&mut w, 2, [at(-0.6, -0.4, 0.8, 0.4), b, far]);
+ // (Another such object, one copy, stays: what is left in the tree's moving subtree when the first is removed.)
+ w.set_object(16, "another".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![5], capacity: 1 }, true, false).unwrap();
+ w.set_instances(16, 1, Some(at(0.7, -0.6, 0.9, 0.3).to_vec()), None, None).unwrap();
+ if tree {
+ strip(&mut w);
+ }
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ if !live.g.hwrt {
+ return;
+ }
+ assert!(live.sc.tables.retained.instanced(15).is_some_and(|p| p.mesh.is_some()), "the copies are instances");
+ assert_eq!(live.sc.tables.light_tree.as_ref().is_some_and(|t| t.moving_count > 0), tree, "the copies' emitters are in the tree's moving subtree");
+ list_is_its_triangles("emitting copies, as loaded", &live);
+ // A copy that is not shown bounds nothing in the tree: the moving subtree holds the shown ones (within 2 m).
+ let reach = |c: &LiveCore| c.sc.tables.light_tree.as_ref().and_then(|t| t.moving_sphere()).map_or(0.0, |s| s.1);
+ assert!(reach(&live) < 10.0, "as loaded: the moving subtree reaches {} m", reach(&live));
+ picture(&mut live, 4);
+ type Edit = (&'static str, Box<dyn Fn(&mut World)>);
+ let zero = glam::Mat4::from_scale(Vec3::ZERO).to_cols_array();
+ let edits: Vec<Edit> = vec![
+ ("a copy moved", Box::new(move |w| set(w, 2, [at(-0.2, -0.5, 1.1, 0.4), b, far]))),
+ ("a copy three times larger", Box::new(move |w| set(w, 2, [at(-0.2, -0.5, 1.1, 1.2), b, far]))),
+ ("a third copy shown", Box::new(move |w| set(w, 3, [at(-0.2, -0.5, 1.1, 1.2), b, c]))),
+ ("a copy scaled to 0", Box::new(move |w| set(w, 3, [zero, b, c]))),
+ ("two copies past the count", Box::new(move |w| set(w, 1, [at(-0.6, 0.4, 0.9, 0.8), b, c]))),
+ ("the node's power", Box::new(move |w| w.set_power(15, 0.25).unwrap())),
+ (
+ "the object removed",
+ Box::new(move |w| {
+ w.remove(15);
+ }),
+ ),
+ ];
+ // The emitters that weigh something: each one's weight and where it is.
+ let weights = |c: &LiveCore| {
+ let t = &c.sc.tables;
+ let mut v: Vec<(f32, [f32; 3])> = t.emitter_tris.iter().map(|e| (crate::emitter_power(e, &t.materials, &t.objects, t.stride), e.c)).filter(|(p, _)| *p > 0.0).collect();
+ v.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ v
+ };
+ for (what, edit) in &edits {
+ let what = format!("{what}, {} a light tree", if tree { "with" } else { "without" });
+ edit(&mut w);
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ // (Removed without a tree's strip: no emitter is left to hold.)
+ if live.sc.tables.emitter_tris.iter().any(|e| e.area > 0.0) {
+ list_is_its_triangles(&what, &live);
+ }
+ // (The two objects' copies are a metre apart; the one left when the first is removed is 0.1 m wide.)
+ if tree {
+ let alone = what.starts_with("the object removed");
+ assert!(reach(&live) < if alone { 0.3 } else { 10.0 } && (alone || reach(&live) > 0.3), "{what}: the moving subtree reaches {} m", reach(&live));
+ }
+ let mut fresh = open(&w).unwrap();
+ let (wl, wf) = (weights(&live), weights(&fresh));
+ assert_eq!(wl.len(), wf.len(), "{what}: as many emitters weigh something as in a build");
+ for (l, f) in wl.iter().zip(&wf) {
+ assert!((l.0 - f.0).abs() <= 1e-5 * f.0 && (Vec3::from(l.1) - Vec3::from(f.1)).length() <= 1e-4, "{what}: an emitter weighs {l:?}, a build's {f:?}");
+ }
+ let (tl, tf) = (live.sc.base.misc[1], fresh.sc.base.misc[1]);
+ assert!((tl - tf).abs() <= 1e-4 * tf.abs(), "{what}: the kernel's total weight {tl}, a build's {tf}");
+ 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));
+ }
+ }
+}
+
/// 300 small emitting triangles: enough for a light tree.
fn strip(w: &mut World) {
let (mut positions, mut indices) = (vec![], vec![]);
@@ -494,6 +582,10 @@ fn an_emitter_scaled_in_place_is_lit_as_a_build_lights_it() {
}
}
+/// The light list's copies of its emitters' triangles follow them: as loaded, after an emitter the CPU moves has
+/// moved (in the light tree's moving subtree, and without a tree), after an emitting mesh a body drives has moved,
+/// after a model's placement or its clip has moved its emitters, after a particle's pass has placed it, and after
+/// the edits that make emitters in place (a mesh added, given other triangles and removed, with the tree's slot for
/// them; a material that starts emitting): the moves and edits also against a build's picture.
#[test]
fn the_light_list_holds_its_triangles() {
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index ef434fc..e27ceb2 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -161,7 +161,9 @@ impl EmitterWorker {
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn new(e: &tables::Tables, device: &wgpu::Device) -> Option<EmitterWorker> {
- let changing = e.light_tree.as_ref().is_some_and(|t| t.dynamic.is_some() || t.moving_count > 0);
+ // (Nor where an instance's emitters change in place, an instanced object's copies: the worker weighs its own
+ // copy of the list.)
+ let changing = e.light_tree.as_ref().is_some_and(|t| t.dynamic.is_some() || t.moving_count > 0) || e.emitter_tris.iter().any(|t| t.moves && t.inst != crate::NO_INST);
if e.emitter_tris.len() < ASYNC_EMITTERS || changing {
return None;
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index de290f6..177960d 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -336,6 +336,9 @@ pub struct LiveCore {
reposed: bool,
/// Dynamic triangles moved in this commit: the light tree's moving subtree is refit once at its end.
emitters_moved: bool,
+ /// An instanced object's emitting copies changed size or were shown or hidden in this commit: the emitters are
+ /// weighed again once at its end.
+ emitters_reweigh: bool,
/// Likewise for the deforming meshes of shared poses (`repose_groups`): the span they took (relative to the dynamic
/// tail, past its end) and whether this frame re-skinned any.
pose_span: Option<(usize, usize)>,
@@ -535,7 +538,7 @@ impl LiveCore {
// brings it, `gpu::loop_guard_of`.)
let guard_read = (gpu::loop_guard_of(!g.hwrt).is_some() && targets.kernel.guard.is_some())
.then(|| (g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::new(AtomicU32::new(0))));
- let mut core = LiveCore { top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
+ let mut core = LiveCore { top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, motion_blur_off: false, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_span: None, pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);
core.apply_post();
Ok(core)
@@ -600,6 +603,7 @@ impl LiveCore {
self.prev_span = None;
self.pose_span = None;
self.emitters_moved = false;
+ self.emitters_reweigh = false;
self.lit_changed = self.frame.max(1);
Ok(())
}
diff --git a/renderer/src/ltree.rs b/renderer/src/ltree.rs
index 5712972..3e8f5ea 100644
--- a/renderer/src/ltree.rs
+++ b/renderer/src/ltree.rs
@@ -239,35 +239,51 @@ impl LightTree {
self.checked();
}
- /// The moving emitters moved: their leaves' spheres from their triangles now (`verts(e)`: emitter e's vertices),
- /// then each moving node's and the root's from its children's, bottom-up (children come after their parent). The
- /// topology, codes and powers stay.
- pub fn refit_moving(&mut self, verts: &dyn Fn(usize) -> [[f32; 3]; 3]) {
+ /// The moving emitters moved: their leaves' spheres from their triangles now (`verts(e)`: emitter e's vertices;
+ /// None: it is not there now, a hidden instance's), then each moving node's and the root's from its children's,
+ /// bottom-up (children come after their parent). What is not there bounds nothing: its leaf keeps its sphere and
+ /// widens no node above it. The topology, codes and powers stay.
+ pub fn refit_moving(&mut self, verts: &dyn Fn(usize) -> Option<[[f32; 3]; 3]>) {
if self.moving_count == 0 {
return;
}
+ let mut empty = vec![false; self.nodes.len()];
for i in (self.moving_nodes..self.nodes.len()).rev().chain([2, 0]) {
let w = self.nodes[i][3].to_bits();
let s = if w & LEAF != 0 {
let (a, b) = self.ranges[i];
let (mut lo, mut hi) = ([f32::MAX; 3], [f32::MIN; 3]);
- for k in a..b {
- let (l, h) = bounds(&verts(self.order[k as usize] as usize));
+ for v in (a..b).filter_map(|k| verts(self.order[k as usize] as usize)) {
+ let (l, h) = bounds(&v);
for j in 0..3 {
lo[j] = lo[j].min(l[j]);
hi[j] = hi[j].max(h[j]);
}
}
- box_sphere(lo, hi)
+ (lo[0] <= hi[0]).then(|| box_sphere(lo, hi))
} else {
- union_sphere(sphere_of(&self.nodes[w as usize]), sphere_of(&self.nodes[w as usize + 1]))
+ let (l, r) = (w as usize, w as usize + 1);
+ match (empty[l], empty[r]) {
+ (false, false) => Some(union_sphere(sphere_of(&self.nodes[l]), sphere_of(&self.nodes[r]))),
+ (false, true) => Some([self.nodes[l][0], self.nodes[l][1]]),
+ (true, false) => Some([self.nodes[r][0], self.nodes[r][1]]),
+ (true, true) => None,
+ }
};
- self.nodes[i][0] = s[0];
- self.nodes[i][1] = s[1];
+ match s {
+ Some(s) => (self.nodes[i][0], self.nodes[i][1]) = (s[0], s[1]),
+ None => empty[i] = true,
+ }
}
self.checked();
}
+ /// The moving subtree's sphere (centre, radius), if there is one.
+ #[cfg(test)]
+ pub(crate) fn moving_sphere(&self) -> Option<([f32; 3], f32)> {
+ (self.moving_count > 0).then(|| sphere_of(&self.nodes[2]))
+ }
+
/// `check` in tests and debug builds (bvh.rs `build_tris` says why not always).
fn checked(&self) {
#[cfg(any(test, debug_assertions))]
@@ -554,7 +570,7 @@ mod tests {
let codes = t.code.clone();
let moved = |e: usize| tri_vertices(&verts[e * 3..e * 3 + 3]).map(|v| [v[0], v[1] + 50.0, v[2]]);
let vs: Vec<[[f32; 3]; 3]> = (0..n as usize).map(|e| if tris[e].moves { moved(e) } else { [[0.0; 3]; 3] }).collect();
- t.refit_moving(&|e| vs[e]);
+ t.refit_moving(&|e| Some(vs[e]));
assert_eq!(t.code, codes);
for k in t.moving_first as usize..n as usize {
let mut node = 0usize;
@@ -570,5 +586,14 @@ mod tests {
}
}
}
+ // One of them far away and not there (a hidden instance's): the moving subtree is no wider for it.
+ let (_, r) = sphere_of(&t.nodes[2]);
+ let far = |e: usize| vs[e].map(|v| [v[0], v[1] + 5000.0, v[2]]);
+ t.refit_moving(&|e| if e == 350 { Some(far(e)) } else { Some(vs[e]) });
+ assert!(sphere_of(&t.nodes[2]).1 > 2000.0, "there: the subtree reaches it");
+ t.refit_moving(&|e| (e != 350).then(|| vs[e]));
+ assert!(sphere_of(&t.nodes[2]).1 <= r * 1.001, "not there: the subtree is as wide as without it ({} for {r})", sphere_of(&t.nodes[2]).1);
+ t.refit_moving(&|e| (!tris[e].moves).then(|| vs[e]));
+ assert!(sphere_of(&t.nodes[2]).1 <= r * 1.001, "none there: the spheres stay");
}
}
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index b0e7da4..eda7657 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -42,6 +42,15 @@ pub fn object_row(pivot: Vec3, power: f32, size: impl Into<Vec3>, custom: [f32;
[[pivot.x, pivot.y, pivot.z, power.max(0.0)], [size.x, size.y, size.z, -1.0e9], custom, [color[0], color[1], color[2], 0.0]]
}
+/// An instanced object's copy's entry: without power when the copy emits and is hidden (its emitters stay in the light
+/// list, at no weight until it is shown).
+pub fn copy_row(mut row: ObjectRow, dark: bool) -> ObjectRow {
+ if dark {
+ row[0][3] = 0.0;
+ }
+ row
+}
+
/// A glTF mesh placed by several static instances (hardware RT): its triangles once, in model space, in the `pool_*`
/// arrays; one BLAS, one TLAS instance per placement.
#[derive(Clone, Copy, Debug)]
@@ -1363,8 +1372,10 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
Kind::Instanced { geometry, procedural, materials: mats, capacity } if shown => {
// Copies of one geometry: one shared mesh (one BLAS), an instance and an object entry per copy, the
// copies' records and entries contiguous (live/edits.rs `update_instanced` rewrites them in place).
- // Glass, emissive and function materials and mirrored copies are flattened instead, each copy its
- // own triangles, as `own_blas` meshes are; changing their instances rebuilds.
+ // A material that only emits is such a mesh too: each copy has its emitters in the light list
+ // (`InstMesh::emitters`), a hidden copy's at no weight (its object has no power). Glass and function
+ // materials and mirrored copies are flattened instead, each copy its own triangles, as `own_blas`
+ // meshes are; changing their instances rebuilds.
let empty = world::InstanceTable::default();
let t = w.instanced.get(id).unwrap_or(&empty);
let placed: Vec<(Mat4, bool)> = (0..*capacity as usize).map(|i| instance_world(m, t, i)).collect();
@@ -1384,7 +1395,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let g = w.geometries.get(geometry).ok_or_else(|| anyhow!("object {}: unknown geometry {geometry}", n.name))?;
let material = mats.first().ok_or_else(|| anyhow!("object {}: an instanced mesh needs a material", n.name))?;
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
- let class = material_class(&materials[mat as usize]);
+ let class = mesh_class(&materials[mat as usize]);
+ let emits = emits_only(&materials[mat as usize]);
let vc = colored(g, &mut std::iter::once(material));
let mirrored = placed.iter().any(|(wm, hidden)| !hidden && wm.determinant() < 0.0);
if instancing && class < 2 && !mirrored {
@@ -1393,7 +1405,11 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
None => {
let (tr, a) = own_mesh_tris(g, mat);
(!tr.is_empty()).then(|| {
- meshes.push(own_inst_mesh(&tr, pool_tris.len() as u32, class));
+ let mut im = own_inst_mesh(&tr, pool_tris.len() as u32, class);
+ if emits {
+ im.emitters = tr.len() as u32;
+ }
+ meshes.push(im);
put_colors(&mut pool_vcolors, pool_tris.len(), vc.then(|| tri_colors(g, false, None)));
pool_tris.extend(tr);
pool_attrs.extend(a);
@@ -1408,7 +1424,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
retained.proxy(*id).draw = Draw::Instanced(InstancedPlace { first: instances.len() as u32, capacity: *capacity, object, mesh: Some(mesh), drawn: t.count });
for (i, &(wm, hidden)) in placed.iter().enumerate() {
let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);
- objects.extend_from_slice(&entry(i, wm, Vec3::from(hi - lo))[..stride]);
+ objects.extend_from_slice(&copy_row(entry(i, wm, Vec3::from(hi - lo)), emits && hidden)[..stride]);
instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: Some(i as u32), hidden, first_emitter: 0 });
}
}
@@ -2167,8 +2183,8 @@ fn pool_emitters(classed: &[Vec<(usize, u32)>; 3], emitting: &std::collections::
}
/// Instancing class of a GPU material: 0 opaque, 1 cutout (any-hit), 2 flattened per placement (glass: shadow rays pass;
-/// material functions; emissive, where the light list does not follow the mesh: one that deforms, an instanced
-/// object's copies. Elsewhere `mesh_class`).
+/// material functions; emissive, where the light list does not follow the mesh: one that deforms. Elsewhere
+/// `mesh_class`).
pub fn material_class(g: &GpuMaterial) -> u32 {
let flat = g.layer[0] > 0.0 || g.tex1[3] != 0 || g.emissive[..3].iter().any(|e| *e > 0.0);
if flat {
@@ -2229,7 +2245,7 @@ pub fn emits_only(g: &GpuMaterial) -> bool {
}
/// `material_class` in a mesh whose instances have their emitters in the light list (an `own_blas` mesh, a model's
-/// that does not deform): a material that only emits is opaque or cutout there, not flattened.
+/// that does not deform, an instanced object's): a material that only emits is opaque or cutout there, not flattened.
pub fn mesh_class(g: &GpuMaterial) -> u32 {
if emits_only(g) { u32::from(g.uv2[3] > 0.0) } else { material_class(g) }
}
@@ -2500,6 +2516,35 @@ mod instance_tests {
assert_eq!((sc.instances.len(), sc.tris.len(), sc.tri_instances.iter().map(|r| r.2).collect::<Vec<_>>()), (0, 2, vec![0, 1]), "mirrored: the drawn copies flattened");
}
+ /// An instanced object whose material only emits is placed as any other: one shared mesh, which has the emitters,
+ /// an instance a copy; a hidden copy's entry has no power. `prepare` gives every copy, the hidden too, its run of
+ /// the light list, of emitters that move: a hidden copy's at its mesh's own area and no weight.
+ #[test]
+ fn an_emitting_instanced_object_is_instances() {
+ let mut w = World::default();
+ w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0, 0, 0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": 5, "doubleSided": false })).unwrap());
+ let g = world::Geometry { positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], normals: vec![0.0, 0.0, 1.0].repeat(3), uvs: vec![0.0; 6], indices: vec![0, 1, 2], groups: vec![], colors: vec![] };
+ w.set_geometry(1, g).unwrap();
+ w.set_object(2, "lamps".into(), None, Kind::Instanced { geometry: 1, procedural: false, materials: vec![1], capacity: 4 }, true, false).unwrap();
+ w.set_power(2, 2.0).unwrap();
+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();
+ w.set_object(9, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();
+ w.set_settings(world::Settings { camera: Some(9), ..Default::default() });
+ let m = [Mat4::from_scale(Vec3::splat(2.0)), Mat4::from_translation(Vec3::X), Mat4::from_scale(Vec3::ZERO), Mat4::from_translation(Vec3::Y)];
+ w.set_instances(2, 3, Some(m.iter().flat_map(|m| m.to_cols_array()).collect()), None, None).unwrap();
+ let mut sc = build(&w, Path::new("."), &crate::default_presets_dir(), None).unwrap();
+ assert_eq!((sc.meshes.len(), sc.meshes[0].emitters, sc.instances.len(), sc.tris.len()), (1, 1, 4, 0));
+ let (st, first) = (sc.object_stride(), sc.retained.instanced(2).unwrap().object as usize);
+ assert_eq!((0..4).map(|i| sc.objects[(first + i) * st][3]).collect::<Vec<_>>(), [2.0, 2.0, 0.0, 0.0], "a hidden copy's entry has no power");
+ let prep = crate::prepare_as(true, false, &mut sc, &mut vec![]);
+ let e = &prep.emitter_tris;
+ assert_eq!(e.iter().map(|e| (e.inst, e.obj as usize - first, e.moves, e.area)).collect::<Vec<_>>(), [(0, 0, true, 2.0), (1, 1, true, 0.5), (2, 2, true, 0.5), (3, 3, true, 0.5)]);
+ assert_eq!(sc.instances.iter().map(|i| i.first_emitter).collect::<Vec<_>>(), [0, 1, 2, 3]);
+ let power = |i: usize| crate::emitter_power(&e[i], &sc.materials, &sc.objects, st);
+ assert_eq!([power(0), power(1), power(2), power(3)], [4.0 * power(1), power(1), 0.0, 0.0], "weights: by size, none when hidden");
+ assert!(power(1) > 0.0 && crate::switchable_power(&e[2], &sc.materials, &sc.objects, st) > 0.0, "a hidden copy's emitter is one the light tree would have");
+ }
+
/// A cutout on exactly an emitter's vertices leaves the mesh with it (`flatten_coincident`), in a model that stays
/// and in a rigid model's moving node (tests/render/data/panel-decal.glb: panel.glb, a grey quad and an emitting
/// one, with a masked quad on the emitting one's vertices): each mesh keeps the grey quad alone.
diff --git a/tests/render/geometry-emitter-instanced-live.ts b/tests/render/geometry-emitter-instanced-live.ts
new file mode 100644
index 0000000..c61af06
--- /dev/null
+++ b/tests/render/geometry-emitter-instanced-live.ts
@@ -0,0 +1,49 @@
+// An emitting instanced mesh's copies changed in place (live/edits.rs `update_instanced`; ROADMAP § 6 step 3): the
+// panel of geometry/emitter-instanced starts with one quad in place, one far away, one scaled to 0 and one past
+// `count`. After a few frames the frame script puts all four in place: their emitters follow in the light list and
+// are weighed again, no rebuild, and the floor below the centre reads the same analytic value.
+import { InstancedMesh, Matrix4, Mesh, PlaneGeometry } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { E, glow, tile } from "./geometry-emitter-instanced.ts";
+
+export const test: TestMeta = {
+ id: "geometry/emitter-instanced-live", features: ["emitters", "instancing", "instanced-mesh", "edits"], reference: "analytic", temporal: true,
+ metric: { kind: "radiance", region: [0.48, 0.47, 0.52, 0.53], expected: (0.5 / Math.PI) * E, tolerance: 0.03 },
+ live: 90,
+ note: "four emitting copies moved, scaled up and shown in place tile an 8 x 8 m panel of 1 nit, 1 m above a Lambert 0.5 floor",
+};
+
+let elapsed = 0;
+let edited = false;
+export default defineGame<Record<string, never>>({
+ state: {},
+ setup: () => {
+ elapsed = 0;
+ edited = false;
+ const scene = sceneWithSky(0);
+ const material = glow();
+ const speck = new Mesh(new PlaneGeometry(0.01, 0.01), material);
+ speck.name = "speck";
+ speck.dynamicGeometry = true;
+ speck.position.set(900, -50, 0);
+ const panel = new InstancedMesh(new PlaneGeometry(4, 4), material, 4);
+ panel.name = "panel";
+ panel.setMatrixAt(0, tile(0));
+ panel.setMatrixAt(1, tile(1).setPosition(300, 1, 0));
+ panel.setMatrixAt(2, new Matrix4().makeScale(0, 0, 0));
+ panel.setMatrixAt(3, tile(3));
+ panel.count = 3;
+ return result(scene, camera(scene, [3, 0.8, 0], [0, 0, 0]), [plane(40, lambert(0.5), "floor"), speck, panel]);
+ },
+ frame(f) {
+ elapsed += f.dt;
+ if (edited || elapsed <= 3 / 60) return;
+ edited = true;
+ const panel = f.scene.getObjectByName("panel") as InstancedMesh;
+ for (let i = 0; i < 4; i++) panel.setMatrixAt(i, tile(i));
+ panel.instanceMatrix.needsUpdate = true;
+ panel.count = 4;
+ },
+ handlers: {},
+});
diff --git a/tests/render/geometry-emitter-instanced.ts b/tests/render/geometry-emitter-instanced.ts
new file mode 100644
index 0000000..7681cb1
--- /dev/null
+++ b/tests/render/geometry-emitter-instanced.ts
@@ -0,0 +1,37 @@
+// An instanced mesh that emits: each copy is an instance of one mesh, its emitters a run of the light list
+// (ROADMAP § 6 step 3). Four copies of a 4 x 4 m quad of 1 nit tile an 8 x 8 m panel 1 m above a Lambert 0.5 floor; a
+// fifth is hidden by a matrix scaled to 0, a sixth by `count`: both stay in the list at no weight. As
+// geometry/emitter-instance: the floor below the centre reads 0.5 / pi x 2.989 only when light sampling and the BSDF
+// rays weigh the same entries. A speck of the same material, far away, holds the list's first entries.
+import { Color, InstancedMesh, Matrix4, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+const corner = (x: number, y: number) => (x / Math.sqrt(1 + x * x)) * Math.atan(y / Math.sqrt(1 + x * x)) + (y / Math.sqrt(1 + y * y)) * Math.atan(x / Math.sqrt(1 + y * y));
+export const E = 4 * (1 / 2) * corner(4, 4);
+
+export const test: TestMeta = {
+ id: "geometry/emitter-instanced", features: ["emitters", "lambert", "instancing", "instanced-mesh"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: [0.48, 0.47, 0.52, 0.53], expected: (0.5 / Math.PI) * E, tolerance: 0.03 },
+ spp: 256,
+ note: "camera under the panel at (3, 0.8, 0) looking at the floor point below its centre",
+};
+
+export const glow = () => new MeshStandardMaterial({ name: "glow", color: new Color(0, 0, 0), emissive: new Color(1, 1, 1), emissiveIntensity: 1, roughness: 1 });
+/** Copy `i` of the panel's four quads, facing down at 1 m. */
+export const tile = (i: number) => new Matrix4().makeRotationX(Math.PI / 2).setPosition(i % 2 ? 2 : -2, 1, i < 2 ? -2 : 2);
+
+export default () => {
+ const scene = sceneWithSky(0);
+ const material = glow();
+ const speck = new Mesh(new PlaneGeometry(0.01, 0.01), material);
+ speck.name = "speck";
+ speck.dynamicGeometry = true;
+ speck.position.set(900, -50, 0);
+ const panel = new InstancedMesh(new PlaneGeometry(4, 4), material, 6);
+ panel.name = "panel";
+ for (let i = 0; i < 4; i++) panel.setMatrixAt(i, tile(i));
+ panel.setMatrixAt(4, new Matrix4().makeScale(0, 0, 0));
+ panel.setMatrixAt(5, new Matrix4().makeTranslation(0, 0.5, 0));
+ panel.count = 5;
+ return result(scene, camera(scene, [3, 0.8, 0], [0, 0, 0]), [plane(40, lambert(0.5), "floor"), speck, panel]);
+};