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 emitter's probability is what the picker used (#156)

Yujiae37ed6cc91fb
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 192074d..f94b494 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2700,6 +2700,16 @@ 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 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
+8 % dark, three times smaller 12 % bright (a move alone was right; older than step D). Now a candidate is weighed by
+the density it was drawn with (its pick's probability over the triangle's own area), and a BSDF ray's hit takes the
+same probability from where the picker reads it: the tree's path, or the emitter's entry in the CDF, which its code
+names (`emitter_codes`). A weight that is out of date costs noise, not light. Gone with the formulas: the particles'
+case apart (a nominal area), the cull test at a hit, "MIS by power alone". Test: an emitter scaled in place, a model
+and a mesh, with and without a light tree, against a build's picture.
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index d322c5c..feea075 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -80,7 +80,7 @@ const F_COAT: u32 = 4096u;
const F_HUGE: u32 = 8192u;
const F_INST: u32 = 16384u;
const F_MEDIA: u32 = 32768u;
-const F_PEMIT: u32 = 65536u; // opaque particles: their emitter handling (nominal areas, not light-sampled ones)
+const F_PEMIT: u32 = 65536u; // opaque particles' emitters (one not shown has no area)
const F_HMEDIA: u32 = 131072u; // homogeneous media (water): live attenuation of paths and shadow rays (media_homogeneous)
const F_AERIAL: u32 = 16777216u; // the sky's aerial perspective (aerial_tr) on segments ending on a surface
const F_PROC: u32 = 262144u; // procedural geometry (ProceduralMesh): AABB candidates in every query, `surface_proc`
@@ -113,7 +113,7 @@ struct Params {
motion: vec4<f32>, // live motion vectors: 1 = on, -, -, - (first dynamic triangle: group_first[1].x)
group_first: array<vec4<u32>, 2>, // first global triangle of each traversal group ([1].x = the first dynamic one)
light_lod: vec4<f32>, // live light LOD (lib.rs emitter_lod): reference position, d0 (0 = off)
- emit_power: vec4<f32>, // x: the emitter CDF's total without light LOD (= misc.y when it is off); y: emitter cull radius (0 = off); z: its reach in the view cone
+ emit_power: vec4<f32>, // the emitter CDF's power and cull as the CPU built it (lib.rs `EmitterCull`); not read here
lod_view: vec4<f32>, // emitter cull's view cone (lib.rs EmitterCull): forward direction, cos of the half-angle
ltree: vec4<f32>, // light tree (ltree.rs): -, its entry count (bits: the moving emitters' first), P(pick a moving one), candidates at camera hits (0 = off)
procs: vec4<u32>, // procedural geometry (F_PROC): -, object count, first record in `instances`, -
@@ -458,16 +458,13 @@ fn emitter_draw(x: vec3<f32>, n: vec3<f32>, rd: u32) -> EPick {
return EPick(e, p * e.z / wsum, e.z);
}
-// With the tree: the probability that emitter_draw(x, n) picks emitter `ei` (`em`; `a`: its attributes,
-// `emitter_attrs`), the same choices down its path (its code; 0: picked by its share of power).
-fn emitter_sel(ei: u32, em: EmitterTri, a: TriAttr, x: vec3<f32>, n: vec3<f32>) -> f32 {
+// The probability that emitter_draw(x, n) picks emitter `ei` (`em`), from what the draw reads: one of the tree's
+// (its code names its path) by the same choices down the path and its weight in its leaf; any other (its code is its
+// entry in the CDF) by its entry's weight.
+fn emitter_pmf(ei: u32, em: EmitterTri, x: vec3<f32>, n: vec3<f32>) -> f32 {
+ if (P.misc.y <= 0.0) { return 0.0; }
let code = em.code & ~EMITTER_MOVES;
- if (code == 0u) {
- if (P.misc.y <= 0.0) { return 0.0; }
- var area = 0.5 * length(cross(em.e1, em.e2));
- if (has(F_PEMIT) && a.x.z > 0.0) { area = a.x.z; }
- return luminance(material_at(bitcast<u32>(a.uv.w)).emissive.rgb) * obj_power(a) * area / P.misc.y;
- }
+ if ((code >> LT_PATH_BITS) == 0u) { return emitter_at(code).z / P.misc.y; }
let depth = (code >> LT_PATH_BITS) - 1u;
var p = 1.0 - P.ltree.z;
var w = bitcast<u32>(lt_node(0u).w);
@@ -1832,11 +1829,11 @@ fn emitter_attrs(em: EmitterTri) -> TriAttr {
return a;
}
-// MIS weight of emission that a BSDF-sampled ray (pdf `pdf`) hit, against emitter sampling in `direct_light`.
-// Without sampled emitters (only material functions emit, e.g. facade windows) the BSDF ray is the only estimator.
-// It weighs by emitted power alone, as emitter sampling's MIS does with or without light LOD (sample_emitter_ris).
+// The MIS weight of a BSDF ray's (pdf `pdf`) hit on an emitter against light sampling in `direct_light`: by the
+// density light sampling has for the point, the probability it picks the emitter (`emitter_pmf`, at the vertex the
+// ray left) over the triangle's area. One it never picks (no entry, no weight: switched off, culled, a procedural
+// surface) is the BSDF ray's alone.
fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
- // Procedural surfaces are not light-sampled (no emitter entries): the BSDF ray is the only estimator.
if (is_proc(hit) || P.counts.y == 0u) { return 1.0; }
// The hit triangle's emitter: its attributes' x.w is the entry + 1 (0: it is not light-sampled), counted from its
// instance's first entry (the record's n2.w) when an instance places it.
@@ -1844,24 +1841,12 @@ fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
if (entry == 0u) { return 1.0; }
if (has(F_INST) && hit.inst != NO_INST) { entry += bitcast<u32>(instance_at(hit.inst).n2.w); }
let em = emitter_tri_at(entry - 1u);
- let ha = emitter_attrs(em);
let cr = cross(em.e1, em.e2);
let area = 0.5 * length(cr);
let cos_l = abs(dot(normalize(cr), d));
- if (lt_on()) {
- // The light tree's pmf where the ray left (the vertex that sampled emitters), per area of the hit triangle.
- let sel = emitter_sel(entry - 1u, em, ha, mis_x, mis_n);
- if (!(sel > 0.0)) { return 1.0; }
- return power_heuristic(pdf, sel / max(area, 1e-12) * hit.t * hit.t / max(cos_l, 1e-6));
- }
- if (P.misc.y <= 0.0 || emitter_culled(em)) { return 1.0; }
- let mat = material_at(bitcast<u32>(ha.uv.w));
- let pdf_a = luminance(mat.emissive.rgb) * obj_power(ha) / P.emit_power.x;
- let pdf_w = pdf_a * hit.t * hit.t / max(cos_l, 1e-6);
- if (!has(F_PEMIT) || ha.x.z == 0.0) { return power_heuristic(pdf, pdf_w); }
- // Particles (x.z > 0): a nominal area is what the CDF weighed them by, the point is uniform over the actual area.
- // (Those without one, x.z < 0, are not light-sampled: no entry.)
- return power_heuristic(pdf, pdf_w * ha.x.z / max(area, 1e-12));
+ let sel = emitter_pmf(entry - 1u, em, mis_x, mis_n);
+ if (!(sel > 0.0)) { return 1.0; }
+ return power_heuristic(pdf, sel / max(area, 1e-12) * hit.t * hit.t / max(cos_l, 1e-6));
}
// Light LOD factor of an emitter (lib.rs emitter_lod): the emitter CDF's weights carry it, so every pdf of an
@@ -1873,18 +1858,6 @@ fn emitter_lod(em: EmitterTri) -> f32 {
return k * k;
}
-// Live: emitters farther than P.emit_power.y from the light LOD's reference are never proposed (lib.rs emitter_lod),
-// so BSDF rays that hit them keep their whole light (emit_mis), unless they lie in the view cone (P.lod_view) within
-// P.emit_power.z: those light what the camera sees. The same centroid and test as lib.rs EmitterCull::culls.
-fn emitter_culled(em: EmitterTri) -> bool {
- if (P.emit_power.y <= 0.0 || P.light_lod.w <= 0.0) { return false; }
- if ((em.code & EMITTER_MOVES) != 0u) { return false; }
- let c = em.v0 + (em.e1 + em.e2) / 3.0;
- let d = distance(c, P.light_lod.xyz);
- if (d <= P.emit_power.y) { return false; }
- return !(d <= P.emit_power.z && dot(c - P.light_lod.xyz, P.lod_view.xyz) >= P.lod_view.w * d);
-}
-
// ------------------------------------------------------------------------------------------------
// Direct lighting (NEE)
@@ -2135,18 +2108,18 @@ fn emitter_radiance(em: EmitterTri, b1: f32, b2: f32, l: vec3<f32>) -> vec3<f32>
// Bistro 3.47 -> 3.34. The target is free to choose: the estimate stays unbiased, tools/unbiased-check.ts within 0.1 %)
// (the CDF knows emitted power, and with light LOD the distance to the camera; without it, it mostly proposes signs
// far down the street). The target leaves the light LOD out, so the light LOD only changes which candidates are
-// proposed. MIS against the BSDF rays weighs by power alone, the CDF's pdf without light LOD (emit_mis): the weights
-// m_nee + m_bsdf still sum to one, so the combination stays unbiased, and which of the two carries which light is the
-// same with or without light LOD. With light LOD every surface vertex samples this way (deeper ones with 2
-// candidates): a single draw from the LOD'd CDF would make far emitters rare and heavy, which the radiance cache's
-// clamps cut.
+// proposed. A candidate's weight and the MIS against the BSDF rays (emit_mis) are by the density the point was drawn
+// with: the probability of its emitter's pick over the triangle's own area, whatever the CDF weighed the emitter by
+// (a triangle that changed size since, a particle's nominal area). With light LOD every surface vertex samples this
+// way (deeper ones with 2 candidates): a single draw from the LOD'd CDF would make far emitters rare and heavy, which
+// the radiance cache's clamps cut.
fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes, v: vec3<f32>, rd: u32) -> ES {
var r = ES(vec3<f32>(0.0), vec3<f32>(0.0, 1.0, 0.0), 0.0, 0.0, 0.0);
var wsum = 0.0;
var pick_b = vec2<f32>(0.0);
var pick_ph = 0.0;
- var pick_e = vec4<f32>(0.0);
- var pick_sel = 0.0;
+ var pick_i = 0u;
+ var pick_pdf = 0.0;
for (var k = 0u; k < m; k++) {
let dk = rng_sub(rd, k);
let pk = emitter_draw(x, n, dk);
@@ -2160,34 +2133,32 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
let e1 = em.e1;
let e2 = em.e2;
let lp = em.v0 + e1 * b1 + e2 * b2;
- let ln = normalize(cross(e1, e2));
+ let cr = cross(e1, e2);
+ // Twice the triangle's own area (none: a particle not shown).
+ let a2 = length(cr);
+ if (!(a2 > 0.0)) { continue; }
+ let ln = cr / a2;
let dl = lp - x;
let d2 = max(dot(dl, dl), 1e-8);
let l = dl * inverseSqrt(d2);
var g = abs(dot(ln, l)) * select(max(dot(n, l), 0.0), 1.0, dot(n, n) == 0.0) / d2;
if (m > 1u) { g = abs(dot(ln, l)) * luminance(eval_bsdf(sf, lb, v, l)) / d2; }
- // target (emitted luminance x G) over source pdf (luminance x light LOD / total, per area) = total x G / LOD;
- // with the tree the source pdf is its selection probability / area (weight / area = luminance x power)
- let lk = emitter_lod(em);
- var w = select(P.misc.y * g / lk, pk.w * g / pk.p, lt_on());
- // Particle emitters (e.w < 0): weighed by a nominal area -e.w, sampled over the actual one (0 when not shown).
- var ae = e.w;
- if (has(F_PEMIT) && e.w < 0.0) {
- ae = 0.5 * length(cross(e1, e2));
- if (ae <= 0.0) { continue; }
- w *= ae / -e.w;
- }
- if (w <= 0.0) { continue; }
+ // The target: emitted luminance x power (the entry's weight over the area and the light LOD it was weighed
+ // with) x G. The weight: the target over the density of the point.
+ let ph = pk.w / (e.w * emitter_lod(em)) * g;
+ let pdf_a = pk.p / (0.5 * a2);
+ let w = ph / pdf_a;
+ if (!(w > 0.0)) { continue; }
wsum += w;
if (bb.z * wsum < w) {
pick_b = vec2<f32>(b1, b2);
- pick_ph = pk.w / (abs(e.w) * lk) * g;
- pick_e = vec4<f32>(e.x, e.y, e.z / lk, ae);
- pick_sel = pk.p;
+ pick_ph = ph;
+ pick_i = bitcast<u32>(e.x);
+ pick_pdf = pdf_a;
}
}
if (pick_ph <= 0.0) { return r; }
- let em = emitter_tri_at(bitcast<u32>(pick_e.x));
+ let em = emitter_tri_at(pick_i);
let e1 = em.e1;
let e2 = em.e2;
let lp = em.v0 + e1 * pick_b.x + e2 * pick_b.y;
@@ -2203,8 +2174,7 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
r.le = emitter_radiance(em, pick_b.x, pick_b.y, l);
r.l = l;
r.dist = dist;
- // MIS by the source pdf: power alone without the tree (emit_mis), the tree's pmf with it
- r.pdf_w = select(pick_e.z / P.emit_power.x / pick_e.w * d2 / cos_l, pick_sel / pick_e.w * d2 / cos_l, lt_on());
+ r.pdf_w = pick_pdf * d2 / cos_l;
r.w = (wsum / f32(m)) / pick_ph * cos_l / d2;
return r;
}
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 8cb8474..667b0fc 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -126,8 +126,8 @@ pub struct EmitterTri {
pub c: [f32; 3],
/// On a moving object (TRI_DYNAMIC): no light LOD, its centroid would go stale (the kernel skips it too).
pub moves: bool,
- /// A particle's: `area` is the nominal one (Particles emitterArea); its CDF entry carries it negated so the kernel
- /// samples the actual area (pathtrace.wgsl sample_emitter_ris, emit_mis).
+ /// A particle's: `area` is the nominal one (Particles emitterArea), what the CDF weighs it by; its pass places
+ /// its triangle, of whatever size.
pub nominal: bool,
/// One of the light tree's (`ltree`): its CDF entry is in the tree's range, at the start of the CDF.
pub in_tree: bool,
@@ -146,7 +146,7 @@ const _: () = assert!((ltree::PATH_BITS + 2) << ltree::PATH_BITS <= EMITTER_MOVE
/// An emitter's triangle as the kernel's light sampling reads it (pathtrace.wgsl `EmitterTri`; `Table::EmitterTris`,
/// entry i for `emitter_tris[i]`): in world space, the light list's own copy, so a sample reads no placement. v0, e1,
/// e2 in world space; its triangle in the triangles' table (attributes); the instance that places it (`NO_INST`: the
-/// triangle is in world space there too); the light tree's path code (0: not one of the tree's) with `EMITTER_MOVES`.
+/// triangle is in world space there too); where its weight is (`emitter_codes`) with `EMITTER_MOVES`.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct GpuEmitterTri {
@@ -419,6 +419,20 @@ pub fn emitter_order(tris: &[EmitterTri], tree: Option<&ltree::LightTree>) -> Ve
t.order.iter().copied().chain(all.filter(|&i| !placed[i as usize])).collect()
}
+/// What each emitter of the list carries for the kernel to find its weight by (`GpuEmitterTri::code`), for the CDF's
+/// `order`: one of the tree's its path code, any other its entry in the CDF (no depth bits: `emit_mis` reads the
+/// entry's weight); with `EMITTER_MOVES`.
+pub fn emitter_codes(tris: &[EmitterTri], order: &[u32], tree: Option<&ltree::LightTree>) -> Vec<u32> {
+ let in_tree = tree.map_or(0, |t| t.order.len());
+ assert!(order.len() < 1 << ltree::PATH_BITS, "an entry of the CDF is named in a code's path bits");
+ let mut out = vec![0; tris.len()];
+ for (k, &i) in order.iter().enumerate() {
+ let code = if k < in_tree { tree.unwrap().code[k] } else { k as u32 };
+ out[i as usize] = code | if tris[i as usize].moves { EMITTER_MOVES } else { 0 };
+ }
+ out
+}
+
/// 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
@@ -435,7 +449,7 @@ pub fn emitter_cdf(tris: &[EmitterTri], order: &[u32], materials: &[scene::GpuMa
let p = emitter_power(e, materials, objects, stride);
power += p;
total += p * lod_k;
- out.push([f32::from_bits(i), total, p * lod_k, if e.nominal { -e.area } else { e.area }]);
+ out.push([f32::from_bits(i), total, p * lod_k, e.area]);
}
if total > 0.0 {
for e in &mut out {
@@ -736,21 +750,24 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
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 };
- // The list keeps its own order (the tree and the CDF name its emitters: `emitter_order`); the tree's have their
- // codes.
+ // 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 {
- for (k, &i) in t.order.iter().enumerate() {
+ for &i in &t.order {
emitter_tris[i as usize].in_tree = true;
- gpu_emitter_tris[i as usize].code |= t.code[k];
}
}
+ let order = emitter_order(&emitter_tris, light_tree.as_ref());
+ for (g, code) in gpu_emitter_tris.iter_mut().zip(emitter_codes(&emitter_tris, &order, light_tree.as_ref())) {
+ g.code = code;
+ }
// A triangle in world space names its emitter in its attributes (x.w = the entry + 1), for the rays that hit it
// (emit_mis); a mesh's triangle is numbered among its mesh's, and its instance has the first.
for (i, e) in emitter_tris.iter().enumerate().filter(|(_, e)| e.inst == NO_INST) {
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, &emitter_order(&emitter_tris, light_tree.as_ref()), &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());
+ let (emitters, total, _) = emitter_cdf(&emitter_tris, &order, &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]);
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 1709269..c27cdd7 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -873,8 +873,7 @@ impl LiveCore {
// 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;
+ if t.dynamic.is_some() {
let (mats, objs, st, pf) = (&e.materials, &e.objects, e.stride, edit.pool_first);
// (An emitter's triangle in world space: an instance's is its mesh's, placed.)
let verts = |x: &crate::EmitterTri| {
@@ -891,19 +890,17 @@ impl LiveCore {
let Some([va, vb, vc]) = verts(x).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 });
}
- let was = t.order[ns..].to_vec();
t.set_dynamic(items);
- let at = std::mem::offset_of!(crate::GpuEmitterTri, code);
- // (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));
- }
- 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 order = crate::emitter_order(&e.emitter_tris, e.light_tree.as_ref());
+ // Where each emitter's weight is now (`emitter_codes`), for all but the tree's static ones (theirs stay):
+ // written over the code the new ones were made with.
+ let codes = crate::emitter_codes(&e.emitter_tris, &order, e.light_tree.as_ref());
+ let fixed = e.light_tree.as_ref().map_or(0, |t| t.dynamic.map_or(t.order.len(), |(_, ns)| ns as usize));
+ for &i in &order[fixed.min(order.len())..] {
+ w_tris.put((i as usize * size + std::mem::offset_of!(crate::GpuEmitterTri, code)) as u64, bytemuck::bytes_of(&codes[i as usize]));
+ }
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);
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 1ec7375..3986918 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -398,19 +398,25 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
let size = std::mem::size_of::<crate::GpuEmitterTri>();
let list = read(&up.heap.buffer, up.heap.at(Table::EmitterTris), (tables.emitter_tris.len() * size) as u64);
let (verts, attrs) = (read(&up.verts, 0, up.verts.size()), read(&up.attrs, 0, up.attrs.size()));
- let codes: std::collections::HashMap<u32, u32> = tables.light_tree.as_ref().map_or_else(Default::default, |t| t.order.iter().copied().zip(t.code.iter().copied()).collect());
+ let codes = crate::emitter_codes(&tables.emitter_tris, &crate::emitter_order(&tables.emitter_tris, tables.light_tree.as_ref()), tables.light_tree.as_ref());
+ // (The CDF as the kernel reads it: an emitter that is not the tree's is found by the entry its code names.)
+ let cdf = read(&up.heap.buffer, up.heap.at(Table::Emitters), (tables.emitter_tris.len() * 16) as u64);
let mut alive = 0;
for (i, e) in tables.emitter_tris.iter().enumerate() {
let r: crate::GpuEmitterTri = bytemuck::pod_read_unaligned(&list[i * size..][..size]);
- let code = codes.get(&(i as u32)).copied().unwrap_or(0) | if e.moves { crate::EMITTER_MOVES } else { 0 };
- assert_eq!(r.code, code, "{what}: emitter {i}'s path code");
+ let code = codes[i];
+ assert_eq!(r.code, code, "{what}: emitter {i}'s code (its path in the tree, or its entry in the CDF)");
+ if code & !crate::EMITTER_MOVES < 1 << crate::ltree::PATH_BITS {
+ let entry: [u32; 4] = bytemuck::pod_read_unaligned(&cdf[(code & !crate::EMITTER_MOVES) as usize * 16..][..16]);
+ assert_eq!(entry[0], i as u32, "{what}: the CDF entry emitter {i}'s code names is its own");
+ }
if e.area <= 0.0 {
continue;
}
let rows: Vec<[f32; 4]> = (0..3).map(|k| bytemuck::pod_read_unaligned(&verts[(e.tri as usize * 3 + k) * 16..][..16])).collect();
let a: scene::GpuTriAttr = bytemuck::pod_read_unaligned(&attrs[e.tri as usize * 96..][..96]);
if e.inst == crate::NO_INST {
- assert_eq!(r, crate::GpuEmitterTri::new(e, &rows, code), "{what}: emitter {i} of the list against its triangle {}", e.tri);
+ assert_eq!(r, crate::GpuEmitterTri::new(e, &rows, code & !crate::EMITTER_MOVES), "{what}: emitter {i} of the list against its triangle {}", e.tri);
assert_eq!(a.x[3].to_bits(), i as u32 + 1, "{what}: triangle {} names its emitter", e.tri);
} else {
let (inst, record) = (&c.sc.instances[e.inst as usize], &c.sc.gpu_instances[e.inst as usize]);
@@ -431,22 +437,68 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
/// 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
+/// 300 small emitting triangles: enough for a light tree.
+fn strip(w: &mut World) {
+ let (mut positions, mut indices) = (vec![], vec![]);
+ for q in 0..150u32 {
+ let x = -1.5 + q as f32 * 0.02;
+ positions.extend([x, -0.9, 0.2, x + 0.008, -0.9, 0.2, x + 0.008, -0.892, 0.2, x, -0.892, 0.2]);
+ indices.extend([0, 1, 2, 0, 2, 3].map(|k| q * 4 + k));
+ }
+ w.set_geometry(6, Geometry { normals: [0.0, 0.0, 1.0].repeat(600), uvs: vec![0.0; 1200], positions, indices, groups: vec![], colors: vec![] }).unwrap();
+ w.set_object(17, "strip".into(), None, Kind::Mesh { geometry: 6, material: 5, own_blas: false, materials: vec![] }, true, false).unwrap();
+}
+
+/// An emitter that changes size in place is lit as a build lights it: a movable model (its instance is scaled) and a
+/// movable mesh (the CPU moves its triangles), the scene's main light, three times larger and three times smaller,
+/// with and without a light tree. The weights it was given at load are not what its triangles are now.
+#[test]
+fn an_emitter_scaled_in_place_is_lit_as_a_build_lights_it() {
+ 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 (is_model, tree, grow) in [(true, false, true), (true, true, true), (false, false, true), (false, true, true), (true, false, false), (false, false, false)] {
+ let what = format!("a movable {} {} in place, {} a light tree", if is_model { "model" } else { "mesh" }, if grow { "three times larger" } else { "three times smaller" }, if tree { "with" } else { "without" });
+ let mut w = world();
+ // (The sun and the lamp away: the emitter lights the scene.)
+ w.set_visible(20, false).unwrap();
+ w.set_visible(12, false).unwrap();
+ let (small, large) = if is_model { (0.05f32, 0.15f32) } else { (0.4, 1.2) };
+ let (from, to) = if grow { (small, large) } else { (large, small) };
+ if is_model {
+ w.set_object(31, "movable".into(), None, Kind::Model { uri: "tests/render/data/panel.glb".into(), nodes: None, animation: None, functions: vec![] }, true, true).unwrap();
+ w.set_power(31, 60.0).unwrap();
+ } else {
+ w.set_object(31, "movable".into(), None, Kind::Mesh { geometry: 3, material: 5, own_blas: false, materials: vec![] }, true, true).unwrap();
+ w.set_power(31, 1.5).unwrap();
+ }
+ w.set_transform(31, Vec3::new(0.5, -0.5, 0.6), glam::Quat::IDENTITY, Vec3::splat(from)).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_eq!(live.sc.tables.light_tree.is_some(), tree, "{what}");
+ picture(&mut live, 4);
+ w.set_transform(31, Vec3::new(0.2, -0.2, 0.9), glam::Quat::from_rotation_z(0.5), Vec3::splat(to)).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ 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));
+ }
+}
+
/// them; a material that starts emitting): the moves and edits also against a build's picture.
#[test]
fn the_light_list_holds_its_triangles() {
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));
- // 300 small emitting triangles: enough for a light tree.
- let strip = |w: &mut World| {
- let (mut positions, mut indices) = (vec![], vec![]);
- for q in 0..150u32 {
- let x = -1.5 + q as f32 * 0.02;
- positions.extend([x, -0.9, 0.2, x + 0.008, -0.9, 0.2, x + 0.008, -0.892, 0.2, x, -0.892, 0.2]);
- indices.extend([0, 1, 2, 0, 2, 3].map(|k| q * 4 + k));
- }
- w.set_geometry(6, Geometry { normals: [0.0, 0.0, 1.0].repeat(600), uvs: vec![0.0; 1200], positions, indices, groups: vec![], colors: vec![] }).unwrap();
- w.set_object(17, "strip".into(), None, Kind::Mesh { geometry: 6, material: 5, own_blas: false, materials: vec![] }, true, false).unwrap();
- };
// An emitter the CPU moves.
for tree in [true, false] {
let mut w = world();