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.

The light list keeps its own order: the tree and the CDF name its emitters (#151)

Yujia2f47e9a14daa
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index e52ccee..fcaebe0 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -378,22 +378,35 @@ pub fn light_groups(lights: &[scene::GpuLight]) -> Vec<[f32; 4]> {
/// Buckets of the emitter CDF's guide table (pathtrace.wgsl `EMITTER_GUIDE`, a power of two).
pub const EMITTER_GUIDE: usize = 65536;
-/// Emitter CDF entries (its emitter's index in `emitter_tris`: bits, normalized cumulative weight, weight, area), one
-/// per `entries` item (an emitter and its index), in their order; then the guide table; the total weight and the total
-/// without light LOD (Params::emit_power). Weight = area x emissive luminance x object power (x light LOD). Triangles
-/// switched off keep a zero-weight entry.
+/// The order of a scene's emitters in the CDF: the light tree's in its leaf order (a node covers a run of entries),
+/// then the rest as the list has them. The list itself keeps its order.
+pub fn emitter_order(tris: &[EmitterTri], tree: Option<&ltree::LightTree>) -> Vec<u32> {
+ let all = 0..tris.len() as u32;
+ let Some(t) = tree else { return all.collect() };
+ let mut placed = vec![false; tris.len()];
+ for &i in &t.order {
+ placed[i as usize] = true;
+ }
+ t.order.iter().copied().chain(all.filter(|&i| !placed[i as usize])).collect()
+}
+
+/// Emitter CDF entries (its emitter's index in `tris`: bits, normalized cumulative weight, weight, area), one per
+/// emitter in `order` (`emitter_order`); then the guide table; the total weight and the total without light LOD
+/// (Params::emit_power). Weight = area x emissive luminance x object power (x light LOD). Triangles switched off
+/// keep a zero-weight entry.
/// Guide table (the cutpoint method): EMITTER_GUIDE + 1 indices, four per vec4 (bits); index k is where the kernel's
/// binary search lands for u = k / EMITTER_GUIDE, so a draw u only searches between the indices of its bucket and the
/// next, and finds the same entry as a search over the whole CDF.
-pub fn emitter_cdf<'a>(entries: impl ExactSizeIterator<Item = (usize, &'a EmitterTri)>, materials: &[scene::GpuMaterial], objects: &[[f32; 4]], stride: usize, lod: [f32; 4], cull: EmitterCull) -> (Vec<[f32; 4]>, f32, f32) {
+pub fn emitter_cdf(tris: &[EmitterTri], order: &[u32], materials: &[scene::GpuMaterial], objects: &[[f32; 4]], stride: usize, lod: [f32; 4], cull: EmitterCull) -> (Vec<[f32; 4]>, f32, f32) {
let (mut total, mut power) = (0.0f32, 0.0f32);
- let mut out = Vec::with_capacity(entries.len());
- for (i, e) in entries {
+ let mut out = Vec::with_capacity(order.len());
+ for &i in order {
+ let e = &tris[i as usize];
let lod_k = if e.moves { 1.0 } else { emitter_lod(e.c, lod, cull) };
let p = emitter_power(e, materials, objects, stride);
power += p;
total += p * lod_k;
- out.push([f32::from_bits(i as u32), total, p * lod_k, if e.nominal { -e.area } else { e.area }]);
+ out.push([f32::from_bits(i), total, p * lod_k, if e.nominal { -e.area } else { e.area }]);
}
if total > 0.0 {
for e in &mut out {
@@ -662,31 +675,23 @@ 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 mut light_tree = if use_tree { light_tree_of(&emitter_tris, &tri_verts, &sc.materials, &sc.objects, sc.object_stride(), sc.emitter_slot) } else { None };
- if let Some(t) = &mut light_tree {
- // The tree's emitters first, in leaf order (each node covers a range of entries), then the rest as they were.
- let mut taken = vec![false; emitter_tris.len()];
- let mut ordered: Vec<EmitterTri> = Vec::with_capacity(emitter_tris.len());
- for &i in &t.order {
- taken[i as usize] = true;
- let mut e = emitter_tris[i as usize];
- e.in_tree = true;
- ordered.push(e);
+ let light_tree = if use_tree { light_tree_of(&emitter_tris, &tri_verts, &sc.materials, &sc.objects, sc.object_stride(), sc.emitter_slot) } else { None };
+ // The list keeps its own order (the tree and the CDF name its emitters: `emitter_order`).
+ let mut codes = vec![0u32; emitter_tris.len()];
+ if let Some(t) = &light_tree {
+ for (k, &i) in t.order.iter().enumerate() {
+ emitter_tris[i as usize].in_tree = true;
+ codes[i as usize] = t.code[k];
}
- ordered.extend(emitter_tris.iter().zip(&taken).filter(|(_, t)| !**t).map(|(e, _)| *e));
- emitter_tris = ordered;
- // From here on an entry of the tree is its position in `emitter_tris` (the live view's refits read it so).
- t.order = (0..t.order.len() as u32).collect();
- }
- // The list's triangles (the tree's entries are the first, each with its code), and each triangle's entry + 1 in
- // its attributes (x.w), for the rays that hit it (emit_mis).
- let code = |i: usize| light_tree.as_ref().and_then(|t| t.code.get(i)).copied().unwrap_or(0);
- let gpu_emitter_tris: Vec<GpuEmitterTri> = emitter_tris.iter().enumerate().map(|(i, e)| GpuEmitterTri::new(e, &tri_verts[e.tri as usize * 3..][..3], code(i))).collect();
+ }
+ // The list's triangles (the tree's with their codes), and each triangle's entry + 1 in its attributes (x.w), for
+ // the rays that hit it (emit_mis).
+ let gpu_emitter_tris: Vec<GpuEmitterTri> = emitter_tris.iter().zip(&codes).map(|(e, &code)| GpuEmitterTri::new(e, &tri_verts[e.tri as usize * 3..][..3], code)).collect();
for (i, e) in emitter_tris.iter().enumerate() {
sc.attrs[e.tri as usize].x[3] = f32::from_bits(i as u32 + 1);
}
let emitter_runs = EmitterRuns::of(&emitter_tris);
- let (emitters, total, _) = emitter_cdf(emitter_tris.iter().enumerate(), &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());
+ let (emitters, total, _) = emitter_cdf(&emitter_tris, &emitter_order(&emitter_tris, light_tree.as_ref()), &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());
// The moving emitters (after the tree's in the CDF) are picked with the probability of their share of power.
let ltree_param = light_tree.as_ref().map_or([0.0; 4], |t| [0.0, f32::from_bits(t.order.len() as u32), if total > 0.0 { ((total - t.power) / total).max(0.0) } else { 0.0 }, ltree::RIS_OFFLINE as f32]);
@@ -1301,7 +1306,7 @@ mod light_lod_tests {
let tris: Vec<EmitterTri> = (0..3000)
.map(|i| EmitterTri { tri: i, mat: if i % 9 == 0 { 0 } else { 1 + i % 3 }, obj: 0, area: 10f32.powf(-6.0 * unit()), c: [300.0 * unit(), 5.0, 100.0 * unit()], moves: i % 50 == 0, nominal: false, in_tree: false })
.collect();
- let (t, total, _) = emitter_cdf(tris.iter().enumerate(), &mats, &[], 3, [20.0, 0.0, 30.0, 10.0], EmitterCull::default());
+ let (t, total, _) = emitter_cdf(&tris, &emitter_order(&tris, None), &mats, &[], 3, [20.0, 0.0, 30.0, 10.0], EmitterCull::default());
let n = tris.len() as u32;
assert!(total > 0.0);
assert_eq!(t.len(), tris.len() + (EMITTER_GUIDE + 1).div_ceil(4));
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 95bd9f8..8dba1b2 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -860,16 +860,15 @@ impl LiveCore {
}
w_attrs.flush(&g.queue, &up.attrs);
// Emitters added in place, with the tree's slot for them (`ltree::build_slotted`): its subtree grown again over
- // those alive, their entries right after the static ones in the CDF (in its leaf order: each leaf's entry is its
- // position) and their path codes with their triangles in the list (written over the code 0 they were made with).
- let mut perm: Option<Vec<usize>> = None;
+ // those alive, their entries right after the static ones in the CDF (the tree's order: `emitter_order`) and
+ // their path codes with their triangles in the list (written over the code 0 they were made with).
if let Some(t) = e.light_tree.as_mut() {
if let Some((_, ns)) = t.dynamic {
let ns = ns as usize;
let (mats, objs, st, pf) = (&e.materials, &e.objects, e.stride, edit.pool_first);
let verts = |k: usize| if k >= pf { pool_tris.get(k - pf).copied() } else { tri_order.get(k).and_then(|&i| flat.get(i as usize)).copied() };
let mut items = vec![];
- for (i, x) in e.emitter_tris.iter().enumerate().skip(ns) {
+ for (i, x) in e.emitter_tris.iter().enumerate() {
let w = crate::emitter_power(x, mats, objs, st);
let Some([va, vb, vc]) = verts(x.tri as usize).filter(|_| !x.in_tree && !x.nominal && !x.moves && w > 0.0) else { continue };
items.push(crate::ltree::DynItem { e: i as u32, lo: va.min(vb).min(vc).to_array(), hi: va.max(vb).max(vc).to_array(), c: x.c, w });
@@ -877,26 +876,17 @@ impl LiveCore {
let was = t.order[ns..].to_vec();
t.set_dynamic(items);
let at = std::mem::offset_of!(crate::GpuEmitterTri, code);
- let mut placed = vec![false; e.emitter_tris.len()];
- let mut p: Vec<usize> = (0..ns).collect();
- for k in ns..t.order.len() {
- let i = t.order[k] as usize;
- w_tris.put((i * size + at) as u64, bytemuck::bytes_of(&t.code[k]));
- placed[i] = true;
- p.push(i);
- }
- // (One the subtree no longer holds: no code.)
- for i in was.into_iter().filter(|&i| !placed[i as usize]) {
+ // (One the subtree no longer holds: no code. Those it holds: theirs, written after.)
+ for i in was {
w_tris.put((i as usize * size + at) as u64, bytemuck::bytes_of(&0u32));
}
- p.extend((ns..e.emitter_tris.len()).filter(|&i| !placed[i]));
- perm = Some(p);
+ for k in ns..t.order.len() {
+ w_tris.put((t.order[k] as usize * size + at) as u64, bytemuck::bytes_of(&t.code[k]));
+ }
}
}
- let (em, total, power) = match &perm {
- Some(p) => crate::emitter_cdf(p.iter().map(|&i| (i, &e.emitter_tris[i])), &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b)),
- None => crate::emitter_cdf(e.emitter_tris.iter().enumerate(), &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b)),
- };
+ let order = crate::emitter_order(&e.emitter_tris, e.light_tree.as_ref());
+ let (em, total, power) = crate::emitter_cdf(&e.emitter_tris, &order, &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b));
if let Some(t) = e.light_tree.as_mut() {
let (tris, mats, objs, st) = (&e.emitter_tris, &e.materials, &e.objects, e.stride);
let w: Vec<f32> = t.order.iter().map(|&i| crate::emitter_power(&tris[i as usize], mats, objs, st)).collect();
@@ -1395,8 +1385,8 @@ impl LiveCore {
let tris = &tables.emitter_tris;
let (q, heap) = (&self.g.queue, &self.sc.up.heap);
let Some(t) = tables.light_tree.as_mut().filter(|t| t.moving_count > 0) else { return };
- t.refit_moving(&|k| {
- let r = (tris[k].tri as usize - first) * 3;
+ t.refit_moving(&|e| {
+ let r = (tris[e].tri as usize - first) * 3;
crate::ltree::tri_vertices(&verts[r..r + 3])
});
heap.write(q, Table::LightTree, 0, bytemuck::cast_slice(&t.nodes[..1]));
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index de28339..d8bcebe 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -244,7 +244,7 @@ impl LiveCore {
// dropped), so the CDF built here has the powers the objects hold and the reference the kernel reads.
self.land_powers_now();
let (e, b) = (&self.sc.tables, &mut self.sc.base);
- let (em, total, power) = crate::emitter_cdf(e.emitter_tris.iter().enumerate(), &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b));
+ let (em, total, power) = crate::emitter_cdf(&e.emitter_tris, &crate::emitter_order(&e.emitter_tris, e.light_tree.as_ref()), &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b));
self.sc.up.heap.write(&self.g.queue, Table::Emitters, 0, bytemuck::cast_slice(&em));
b.misc[1] = total;
b.emit_power[0] = power;
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index eb849c9..b030165 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -167,13 +167,14 @@ impl EmitterWorker {
}
let device = device.clone();
let (tris, mut tree, stride) = (e.emitter_tris.clone(), e.light_tree.clone(), e.stride);
+ let order = crate::emitter_order(&tris, tree.as_ref());
let (ask, asked) = mpsc::channel::<EmitterJob>();
let (tx, done) = mpsc::channel();
std::thread::Builder::new()
.name("emitters".into())
.spawn(move || {
while let Ok(j) = asked.recv() {
- let (em, total, power) = crate::emitter_cdf(tris.iter().enumerate(), &j.materials, &j.objects, stride, j.lod, j.cull);
+ let (em, total, power) = crate::emitter_cdf(&tris, &order, &j.materials, &j.objects, stride, j.lod, j.cull);
let node_powers = tree.as_mut().map_or(vec![], |t| {
let w: Vec<f32> = t.order.iter().map(|&i| crate::emitter_power(&tris[i as usize], &j.materials, &j.objects, stride)).collect();
t.refit(&|k| w[k]);
diff --git a/renderer/src/ltree.rs b/renderer/src/ltree.rs
index c8d336e..9e2ee2f 100644
--- a/renderer/src/ltree.rs
+++ b/renderer/src/ltree.rs
@@ -239,7 +239,7 @@ impl LightTree {
self.checked();
}
- /// The moving emitters moved: their leaves' spheres from their triangles now (`verts(k)`: entry k's vertices),
+ /// 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]) {
@@ -252,7 +252,7 @@ impl LightTree {
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(k as usize));
+ let (l, h) = bounds(&verts(self.order[k as usize] as usize));
for j in 0..3 {
lo[j] = lo[j].min(l[j]);
hi[j] = hi[j].max(h[j]);
@@ -536,13 +536,15 @@ mod tests {
#[test]
fn moving_emitters_get_a_subtree_that_refits() {
let n = 400u32;
- let (mut tris, verts): (Vec<EmitterTri>, Vec<[[f32; 4]; 3]>) = (0..n).map(|i| tri(i, i as f32 * 2.0)).unzip();
+ // (The movers are not along x in the list's order: their leaf order is another, so an entry is not its emitter.)
+ let (mut tris, verts): (Vec<EmitterTri>, Vec<[[f32; 4]; 3]>) = (0..n).map(|i| tri(i, if i < 300 { i as f32 * 2.0 } else { 600.0 + (i * 37 % 100) as f32 * 2.0 })).unzip();
for t in tris.iter_mut().skip(300) {
t.moves = true;
}
let verts: Vec<[f32; 4]> = verts.into_iter().flatten().collect();
let mut t = build(&tris, &verts, &|_| 1.0).unwrap();
assert_eq!((t.moving_first, t.moving_count), (300, 100));
+ assert!((300..400).any(|k| t.order[k] != k as u32), "the movers' leaf order is not the list's");
assert!((t.power - n as f32).abs() < 1e-3);
for k in 0..n as usize {
let moving = tris[t.order[k] as usize].moves;
@@ -551,20 +553,16 @@ mod tests {
}
// The moving ones move 50 m up: every leaf and its ancestors hold them there.
let codes = t.code.clone();
- let moved = |k: usize| {
- let i = t.order[k] as usize * 3;
- tri_vertices(&verts[i..i + 3]).map(|v| [v[0], v[1] + 50.0, v[2]])
- };
- let order = t.order.clone();
- let vs: Vec<[[f32; 3]; 3]> = (0..n as usize).map(|k| if tris[order[k] as usize].moves { moved(k) } else { [[0.0; 3]; 3] }).collect();
- t.refit_moving(&|k| vs[k]);
+ 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]);
assert_eq!(t.code, codes);
for k in t.moving_first as usize..n as usize {
let mut node = 0usize;
let depth = (t.code[k] >> PATH_BITS) - 1;
for l in 0..=depth {
let (c, r) = sphere_of(&t.nodes[node]);
- for v in vs[k] {
+ for v in vs[t.order[k] as usize] {
let d = ((v[0] - c[0]).powi(2) + (v[1] - c[1]).powi(2) + (v[2] - c[2]).powi(2)).sqrt();
assert!(d <= r * 1.001 + 1e-3, "entry {k} outside node {node} at level {l}: {d} > {r}");
}
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index 21f8f32..d89642f 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -276,7 +276,7 @@ fn main() -> Result<()> {
// entries are compared (each by its emitter's triangle: its index differs with them), not the guide table
// after them (indices into the entries).
let bits = |v: &[[f32; 4]], tris: &[threert_render::EmitterTri]| v[..tris.len()].iter().filter(|e| e[2] > 0.0).flat_map(|e| [tris[e[0].to_bits() as usize].tri, e[1].to_bits(), e[2].to_bits(), e[3].to_bits()]).collect::<Vec<_>>();
- let (ea, _, _) = threert_render::emitter_cdf(e.emitter_tris.iter().enumerate(), &e.materials, &e.objects, e.stride, [0.0; 4], threert_render::EmitterCull::default());
+ let (ea, _, _) = threert_render::emitter_cdf(&e.emitter_tris, &threert_render::emitter_order(&e.emitter_tris, e.light_tree.as_ref()), &e.materials, &e.objects, e.stride, [0.0; 4], threert_render::EmitterCull::default());
let power = |o: &[[f32; 4]]| o.iter().step_by(e.stride).map(|p| p[3].to_bits()).collect::<Vec<_>>();
let checks = [
("materials", bytemuck::cast_slice::<_, u8>(&e.materials) == bytemuck::cast_slice::<_, u8>(&b.materials)),