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.

Scene step D, second part: the light list is filled on the GPU (#150)

Yujia2a9b67cce66f
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 89870cb..b1270f3 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2646,6 +2646,17 @@ difference; of the suite's 239 outputs, 26 that repeat themselves differ from ma
3e-5). That is Metal's compiler rounding the new kernel otherwise: on Vulkan (RTX 5090) every one of the 26 is
byte-identical to main's, natively and under software traversal.
+**The light list is filled on the GPU (2026-11-17, scene step D, second part).** What moves an emitter after the
+list was written is copied into it by a pass (`emitter_fill.wgsl`, what real-time engines call preparing the
+lights): a run of the list an invocation row, each emitter's rows taken again from its triangle. Two sets of runs a
+scene (`EmitterRuns`, `gpu::EmitterFills`): the emitters of the triangles the CPU reposes, filled after a commit that
+moved them, in place of the CPU's rewrite (the crowd's commit back at main's: 4.5 ms in a guarded run, 4.9 to 5.0
+with the rewrite); and the particles', filled after their passes, so the kernel reads every emitter from the list
+and its particle case is gone. Pictures: against the first part, 217 of the suite's 239 outputs byte-identical, 19
+within their own spread, the two light-sampled particle tests in their last bits (their kernel variant reads
+other code); Bistro and the crowd within main's own run-to-run difference. Next: emitters on instances, their runs
+filled by the same pass through the instance's matrix.
+
## 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/docs/RUNTIME.md b/docs/RUNTIME.md
index 428deae..d769323 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1486,7 +1486,8 @@ The kernel's read-only scene data other than triangles is two storage buffers, e
- `tables` (group 0, binding 4), vec4s (`Table`): the light tree's nodes, materials, lights, the light groups'
spheres, the emitter CDF with its guide table, the texture pages' rects, objects, instance records, media, the
GGX and glass energy tables, and the emitters' triangles (`GpuEmitterTri`: the light list's own world-space
- copies, so a light sample reads no placement).
+ copies, so a light sample reads no placement; what moves an emitter after the load is copied again on the GPU,
+ `emitter_fill.wgsl`).
- `words` (binding 5), 32-bit words (`Stream`): the environment's CDF, the procedural geometry's data, the vertex
colours (`env_cdf_at`, `pword`, `vcolor_word`). Integers are read as integers, not through a float's bits.
diff --git a/renderer/shaders/emitter_fill.wgsl b/renderer/shaders/emitter_fill.wgsl
new file mode 100644
index 0000000..d20803c
--- /dev/null
+++ b/renderer/shaders/emitter_fill.wgsl
@@ -0,0 +1,19 @@
+// The light list's triangles (lib.rs `GpuEmitterTri`) taken again from where their triangles are now: what real-time
+// engines' "prepare lights" pass does. One run of the list an invocation row (gpu.rs `EmitterFill`): the emitters
+// something has moved since the list was written (the triangles the CPU reposed, the particles their passes place).
+struct Run { first: u32, count: u32 };
+@group(0) @binding(0) var<storage, read> runs: array<Run>;
+@group(0) @binding(1) var<storage, read> verts: array<vec4<f32>>;
+// Three vec4s an emitter: (v0, its triangle), (e1, its object), (e2, its path code). The words stay.
+@group(0) @binding(2) var<storage, read_write> list: array<vec4<u32>>;
+
+@compute @workgroup_size(64)
+fn fill(@builtin(global_invocation_id) id: vec3<u32>) {
+ let run = runs[id.y];
+ if (id.x >= run.count) { return; }
+ let r = (run.first + id.x) * 3u;
+ let t = list[r].w * 3u;
+ for (var k = 0u; k < 3u; k++) {
+ list[r + k] = vec4<u32>(bitcast<vec3<u32>>(verts[t + k].xyz), list[r + k].w);
+ }
+}
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index bac702f..0e8b1ab 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -186,8 +186,9 @@ fn light_group_at(i: u32) -> vec4<f32> { return table_f(P.table_first[0].w + i);
fn energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].y + i); }
fn glass_energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].z + i); }
// An emitter's triangle (lib.rs `GpuEmitterTri`): in world space, the light list's own copy, so a light sample reads
-// no placement; `tri`: its triangle in the triangles' table (attributes), `obj`: its object-table index (power),
-// `code`: the light tree's path code (0: not one of the tree's), EMITTER_MOVES if it moves.
+// no placement (what moves it is copied again: emitter_fill.wgsl); `tri`: its triangle in the triangles' table
+// (attributes), `obj`: its object-table index (power), `code`: the light tree's path code (0: not one of the
+// tree's), EMITTER_MOVES if it moves.
struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, obj: u32, e2: vec3<f32>, code: u32 };
const EMITTER_TRI_VEC4: u32 = 3u;
const EMITTER_MOVES: u32 = 0x80000000u;
@@ -1818,18 +1819,6 @@ fn sun_disks(d: vec3<f32>, pdf: f32) -> vec3<f32> {
return c;
}
-// The triangle of emitter `i`. (F_PEMIT, `placed`: a particle's is where its pass puts it each frame, in the
-// triangles' table: the list has no copy of it yet.)
-fn emitter_tri_of(i: u32, placed: bool) -> EmitterTri {
- var em = emitter_tri_at(i);
- if (has(F_PEMIT) && placed) {
- em.v0 = tri_verts[em.tri * 3u].xyz;
- em.e1 = tri_verts[em.tri * 3u + 1u].xyz;
- em.e2 = tri_verts[em.tri * 3u + 2u].xyz;
- }
- return em;
-}
-
// 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).
@@ -1840,7 +1829,7 @@ fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
let ha = attrs[hit.tri];
let entry = bitcast<u32>(ha.x.w);
if (entry == 0u) { return 1.0; }
- let em = emitter_tri_of(entry - 1u, ha.x.z != 0.0);
+ let em = emitter_tri_at(entry - 1u);
let cr = cross(em.e1, em.e2);
let area = 0.5 * length(cr);
let cos_l = abs(dot(normalize(cr), d));
@@ -2142,7 +2131,6 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
var pick_b = vec2<f32>(0.0);
var pick_ph = 0.0;
var pick_e = vec4<f32>(0.0);
- var pick_placed = false;
var pick_sel = 0.0;
for (var k = 0u; k < m; k++) {
let dk = rng_sub(rd, k);
@@ -2153,7 +2141,7 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
var b2 = bb.y;
if (pk.p <= 0.0) { continue; }
if (b1 + b2 > 1.0) { b1 = 1.0 - b1; b2 = 1.0 - b2; }
- let em = emitter_tri_of(bitcast<u32>(e.x), e.w < 0.0);
+ let em = emitter_tri_at(bitcast<u32>(e.x));
let e1 = em.e1;
let e2 = em.e2;
let lp = em.v0 + e1 * b1 + e2 * b2;
@@ -2180,12 +2168,11 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
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_placed = e.w < 0.0;
pick_sel = pk.p;
}
}
if (pick_ph <= 0.0) { return r; }
- let em = emitter_tri_of(bitcast<u32>(pick_e.x), pick_placed);
+ let em = emitter_tri_at(bitcast<u32>(pick_e.x));
let e1 = em.e1;
let e2 = em.e2;
let lp = em.v0 + e1 * pick_b.x + e2 * pick_b.y;
@@ -2214,7 +2201,7 @@ fn sample_emitter(x: vec3<f32>, n: vec3<f32>, rd: u32) -> ES {
let pk = emitter_draw(x, n, rd);
let e = pk.e;
if (pk.p <= 0.0) { return r; } // switched off (power 0)
- let em = emitter_tri_of(bitcast<u32>(e.x), e.w < 0.0);
+ let em = emitter_tri_at(bitcast<u32>(e.x));
let v0 = em.v0;
let e1 = em.e1;
let e2 = em.e2;
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 7af8eed..f0c1a7c 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -64,6 +64,8 @@ pub struct Gpu {
/// Binding 19 of scenes without density grids (one cell), and the grid pass's bind group layout (grid_sim.wgsl).
no_grid_view: wgpu::TextureView,
grid_layout: wgpu::BindGroupLayout,
+ /// The pass that fills runs of the light list from their triangles (emitter_fill.wgsl), made when first needed.
+ fill: std::sync::OnceLock<wgpu::ComputePipeline>,
/// Hardware ray queries (Metal / Vulkan RT). Software BVH traversal otherwise.
pub hwrt: bool,
/// Last uploaded texture pages, reused while the scene's texture set is unchanged (live edits re-upload often).
@@ -466,6 +468,7 @@ pub struct Uploaded {
/// The particle pass, when the scene has particle systems (hardware RT).
pub particles: Option<ParticleGpu>,
pub gpu_particles: Option<GpuParticlesGpu>,
+ pub fills: EmitterFills,
/// The density grids (the atlas the kernel reads, the grid programs' pass), when the scene has any.
pub grids: Option<GridsGpu>,
/// Each medium's node (the media table's order).
@@ -487,6 +490,23 @@ pub struct Uploaded {
pub translucent: Option<Translucent>,
}
+/// Runs of the light list the GPU takes again from their triangles (emitter_fill.wgsl; lib.rs `EmitterRuns`): the
+/// runs, the pass's bind group, and its dispatch (the runs' count, the longest's length).
+pub struct EmitterFill {
+ runs: wgpu::Buffer,
+ bg: wgpu::BindGroup,
+ count: u32,
+ longest: u32,
+}
+
+/// A scene's fills: of the emitters the CPU moves (after a commit that moved them), and of the particles' (after
+/// their passes). None where the scene has no such emitters.
+#[derive(Default)]
+pub struct EmitterFills {
+ pub moved: Option<EmitterFill>,
+ pub particles: Option<EmitterFill>,
+}
+
/// The particle pass of a scene (shaders/particles.wgsl with its particle functions): pipeline, bind group, the
/// per-frame parameters and the system table's size.
pub struct ParticleGpu {
@@ -1919,7 +1939,7 @@ impl Gpu {
} else {
(None, None, None, None)
};
- Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })
+ Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })
}
/// Whether this device's kernel buffers have the loop guard's count (`guard_room`; always in the merged layout).
@@ -2183,7 +2203,7 @@ impl Gpu {
/// Uploads a prepared scene (geometry, materials, textures, environment, acceleration structures) and returns the
/// bind group used by both the offline and the live kernels. `accum` holds one 80-byte Pixel per output pixel.
#[allow(clippy::too_many_arguments)]
- pub fn upload(&self, scene: &Scene, accum: &wgpu::Buffer, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {
+ pub fn upload(&self, scene: &Scene, accum: &wgpu::Buffer, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], emitter_runs: &crate::EmitterRuns, light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {
let d = &self.device;
let t0 = Instant::now();
// (The vertices too: the kernel's tree over no triangle is a leaf of triangle 0, which these zeros make a
@@ -2622,7 +2642,12 @@ impl Gpu {
timings.push(("upload_ms".into(), t0.elapsed().as_secs_f64() * 1000.0));
// (The scene's own pipelines, made above: particles, grid programs.)
self.save_pipeline_cache();
- Ok(Uploaded { bg, bg_parts, heap, uniform, accum: b_accum, params: b_params, kernel, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })
+ // (What moves emitters after the load needs hardware ray tracing: triangles reposed in place, the particle passes.)
+ let fills = match &accel {
+ Some(_) => EmitterFills { moved: self.emitter_fill(&emitter_runs.moved, &b_verts, &heap), particles: self.emitter_fill(&emitter_runs.particles, &b_verts, &heap) },
+ None => EmitterFills::default(),
+ };
+ Ok(Uploaded { bg, bg_parts, heap, uniform, accum: b_accum, params: b_params, kernel, verts: b_verts, attrs: b_attrs, prev_verts: b_prev, dynamic_first, accel, units: scene.units.clone(), particles, gpu_particles, fills, grids, translucent, vcolors: !scene.gpu_vcolors.is_empty(), media_nodes: scene.media_nodes.clone(), media_hidden: std::cell::RefCell::new(scene.media.iter().map(|m| m.a[1] == crate::scene::MEDIUM_HIDDEN).collect()), room, words, cdf_words: env_cdf.len(), region_words, env_tex })
}
/// Bytes Metal allocates for an AABB BLAS over `count` boxes in `boxes` (its own size query through wgpu-hal; None
@@ -2805,6 +2830,35 @@ impl Gpu {
}
}
+ fn emitter_fill_bind_group(&self, runs: &wgpu::Buffer, verts: &wgpu::Buffer, heap: &Heap<Table>) -> wgpu::BindGroup {
+ let entries = [buffer_entry(0, runs), buffer_entry(1, verts), wgpu::BindGroupEntry { binding: 2, resource: heap.binding(Table::EmitterTris) }];
+ self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("emitter fill"), layout: &self.emitter_fill_pipeline().get_bind_group_layout(0), entries: &entries })
+ }
+
+ fn emitter_fill_pipeline(&self) -> &wgpu::ComputePipeline {
+ self.fill.get_or_init(|| {
+ let module = self.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("emitter fill"), source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/emitter_fill.wgsl").into()) });
+ self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("emitter fill"), layout: None, module: &module, entry_point: Some("fill"), compilation_options: Default::default(), cache: self.cache() })
+ })
+ }
+
+ /// The fill of `runs` of the light list (none: no fill).
+ fn emitter_fill(&self, runs: &[[u32; 2]], verts: &wgpu::Buffer, heap: &Heap<Table>) -> Option<EmitterFill> {
+ let longest = runs.iter().map(|r| r[1]).max()?;
+ let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("emitter runs"), size: (runs.len() * 8) as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ self.queue.write_buffer(&buffer, 0, bytemuck::cast_slice(runs));
+ Some(EmitterFill { bg: self.emitter_fill_bind_group(&buffer, verts, heap), runs: buffer, count: runs.len() as u32, longest })
+ }
+
+ /// The runs of `f` taken again from their triangles as the encoder's earlier commands, and the writes queued
+ /// before it is submitted, leave them.
+ pub fn fill_emitters(&self, f: &EmitterFill, e: &mut wgpu::CommandEncoder) {
+ let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("emitter fill"), timestamp_writes: None });
+ pass.set_pipeline(self.emitter_fill_pipeline());
+ pass.set_bind_group(0, &f.bg, &[]);
+ pass.dispatch_workgroups(f.longest.div_ceil(64), f.count, 1);
+ }
+
/// One frame of the stateful GPU particles (gpu_particles.wgsl): each system's emissions (its rate over `dt`, and the
/// game's spawns, `spawns` per node, 8 floats each), the update, collision and retirement of the rest, their quads;
/// with `rebuild`, the dynamic BLASes after (else the stateless pass that follows rebuilds them).
@@ -3245,8 +3299,11 @@ impl Gpu {
}
/// The bind groups that hold the scene's buffers again, from `up`'s as they are now (one that grew: the tables,
- /// live/edits.rs): the kernel's, and the particle passes'.
+ /// live/edits.rs): the kernel's, the light list's fills' and the particle passes'.
pub fn rebind_scene(&self, up: &mut Uploaded) {
+ for f in [&mut up.fills.moved, &mut up.fills.particles].into_iter().flatten() {
+ f.bg = self.emitter_fill_bind_group(&f.runs, &up.verts, &up.heap);
+ }
up.bg = self.scene_bind_group(&SceneBuffers { params: &up.params, verts: &up.verts, attrs: &up.attrs, heap: &up.heap, words: &up.words, prev_verts: &up.prev_verts, accum: &up.accum, parts: &up.bg_parts, accel: up.accel.as_ref(), uniform: up.uniform.as_ref() });
let Some(a) = &up.accel else { return };
let written = ParticleTargets { verts: &up.verts, prev_verts: &up.prev_verts, blas_verts: &a.verts, heap: &up.heap, attrs: &up.attrs };
@@ -3410,10 +3467,10 @@ impl Gpu {
#[cfg(not(target_arch = "wasm32"))]
/// Render `spp` samples. `base` holds everything except the per-dispatch sample index.
#[allow(clippy::too_many_arguments)]
- pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {
+ pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], emitter_runs: &crate::EmitterRuns, light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {
let d = &self.device;
let (w, h) = (scene.width, scene.height);
- let up = self.upload(scene, &self.accum_buffer(w, h), tri_verts, groups, nodes, emitters, emitter_tris, light_tree, env, env_cdf, energy, timings)?;
+ let up = self.upload(scene, &self.accum_buffer(w, h), tri_verts, groups, nodes, emitters, emitter_tris, emitter_runs, light_tree, env, env_cdf, energy, timings)?;
let pipeline = self.pipeline(&up.kernel, false);
// Particles: placed once, at the scene time and camera.
if up.particles.is_some() {
@@ -3441,6 +3498,12 @@ impl Gpu {
self.queue.submit([e.finish()]);
}
}
+ // The particles' emitters, where the passes above placed them.
+ if let Some(f) = &up.fills.particles {
+ let mut e = d.create_command_encoder(&Default::default());
+ self.fill_emitters(f, &mut e);
+ self.queue.submit([e.finish()]);
+ }
// Grid programs: run from the scene's start to its time at 60 frames a second (the sources of the game's setup at
// the first), then rendered.
if Self::has_grid_sim(&up) {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 7575006..e52ccee 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -72,6 +72,8 @@ pub struct Prepared {
pub emitters: Vec<[f32; 4]>,
/// The emitters' triangles as light sampling reads them, one per `emitter_tris`.
pub gpu_emitter_tris: Vec<GpuEmitterTri>,
+ /// The runs of the list that follow their triangles after the load.
+ pub emitter_runs: EmitterRuns,
pub env: gpu::EnvMap,
pub env_cdf: Vec<f32>,
pub params: gpu::Params,
@@ -164,6 +166,31 @@ impl GpuEmitterTri {
}
}
+/// 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.
+#[derive(Default)]
+pub struct EmitterRuns {
+ pub moved: Vec<[u32; 2]>,
+ pub particles: Vec<[u32; 2]>,
+}
+
+impl EmitterRuns {
+ pub fn of(tris: &[EmitterTri]) -> EmitterRuns {
+ let runs = |which: &dyn Fn(&EmitterTri) -> bool| {
+ let mut out: Vec<[u32; 2]> = vec![];
+ for (i, _) in tris.iter().enumerate().filter(|(_, e)| which(e)) {
+ match out.last_mut() {
+ Some(r) if r[0] + r[1] == i as u32 => r[1] += 1,
+ _ => out.push([i as u32, 1]),
+ }
+ }
+ out
+ };
+ EmitterRuns { moved: runs(&|e| e.moves && !e.nominal), particles: runs(&|e| e.nominal) }
+ }
+}
+
/// An emitter triangle's power: area x emissive-factor luminance x object power (its CDF weight without light LOD).
pub fn emitter_power(e: &EmitterTri, materials: &[scene::GpuMaterial], objects: &[[f32; 4]], stride: usize) -> f32 {
let m = &materials[e.mat as usize];
@@ -658,6 +685,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
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());
// 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]);
@@ -749,7 +777,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, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, fixed_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, fixed_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 bf33b13..95bd9f8 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -1381,26 +1381,19 @@ impl LiveCore {
Ok(true)
}
- /// The moving emitters moved (`LoadedScene::moving_emitters`): their triangles in the list as they are now (the CPU
- /// copy of the dynamic tail), each run of consecutive ones in one write; and the light tree's moving subtree refit
- /// around them, its nodes and the root uploaded (`ltree::LightTree::refit_moving`).
+ /// The emitters the CPU moves moved: their triangles in the list taken again on the GPU, from the triangles this
+ /// commit uploaded (`gpu::EmitterFills::moved`); and the light tree's moving subtree refit around them (the CPU copy
+ /// of the dynamic tail), its nodes and the root uploaded (`ltree::LightTree::refit_moving`).
pub(super) fn move_emitters(&mut self) {
+ if let Some(f) = &self.sc.up.fills.moved {
+ let mut e = self.g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("emitter fill") });
+ self.g.fill_emitters(f, &mut e);
+ self.g.queue.submit([e.finish()]);
+ }
let first = self.sc.dynamic.0;
let (verts, tables) = (&self.sc.dynamic.1, &mut self.sc.tables);
let tris = &tables.emitter_tris;
let (q, heap) = (&self.g.queue, &self.sc.up.heap);
- let size = std::mem::size_of::<crate::GpuEmitterTri>() as u64;
- for run in self.sc.moving_emitters.chunk_by(|a, b| b.0 == a.0 + 1) {
- let now: Vec<crate::GpuEmitterTri> = run
- .iter()
- .map(|&(i, code)| {
- let e = &tris[i as usize];
- let r = (e.tri as usize - first) * 3;
- crate::GpuEmitterTri::new(e, &verts[r..r + 3], code)
- })
- .collect();
- heap.write(q, Table::EmitterTris, run[0].0 as u64 * size, bytemuck::cast_slice(&now));
- }
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;
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 7fde36d..de28339 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -442,6 +442,10 @@ impl LiveCore {
let blas_ts = self.profile.as_ref().map(|p| (&p.queries, n * 2 + 2));
g.run_particles(&self.sc.up, cam.pos.to_array(), cam.fwd.to_array(), shader_time(self.time), self.frame_dt, b.time[2], b.time[1], &mut e, pass_ts, blas_ts);
}
+ // The particles' emitters in the light list, where the passes above placed them.
+ if let (Some(f), 0) = (&self.sc.up.fills.particles, k) {
+ g.fill_emitters(f, &mut e);
+ }
// (The uniform tables: their sections as this frame's edits and the particle passes above left them, where
// the kernel reads them; merged.rs.)
if k == 0 {
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 1bbb8a6..411ffd1 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -380,8 +380,8 @@ fn an_instanced_object_added_in_place_keeps_its_copies_data() {
}
/// What the kernel's light sampling reads against the triangles it stands for, on the GPU: every emitter of the list
-/// (a particle's is placed by its pass) has the light tree's path code for it, and one that is alive its triangle's
-/// rows, object and moving flag, and its triangle's attributes name it back.
+/// has the light tree's path code for it, and one that is alive its triangle's rows, object and moving flag, and its
+/// triangle's attributes name it back.
fn list_is_its_triangles(what: &str, c: &LiveCore) {
let read = |b: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<u8> {
let to = c.g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
@@ -399,7 +399,7 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
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 mut alive = 0;
- for (i, e) in tables.emitter_tris.iter().enumerate().filter(|(_, e)| !e.nominal) {
+ 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");
@@ -416,8 +416,9 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
}
/// 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), 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).
+/// moved (in the light tree's moving subtree, and without a tree), 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).
#[test]
fn the_light_list_holds_its_triangles() {
let presets = crate::default_presets_dir();
@@ -447,13 +448,37 @@ fn the_light_list_holds_its_triangles() {
};
w.take_changes();
assert_eq!(live.sc.tables.light_tree.as_ref().is_some_and(|t| t.moving_count > 0), tree, "the mover is in the tree's moving subtree");
- assert!(!live.sc.moving_emitters.is_empty());
+ assert_eq!(live.sc.up.fills.moved.is_some(), live.g.hwrt, "the mover's emitters are filled on the GPU");
list_is_its_triangles("a moving emitter, as loaded", &live);
w.set_transform(13, Vec3::new(0.1, -0.3, 0.9), glam::Quat::from_rotation_z(0.5), Vec3::ONE).unwrap();
let rebuilt = live.commit(&mut w).unwrap();
assert!(!(rebuilt && live.g.hwrt), "the mover moved in place ({:?})", live.fallback);
list_is_its_triangles("a moving emitter, moved", &live);
}
+ // A light-sampled particle: collapsed as loaded, placed by its pass in the first frame.
+ let mut w = world();
+ 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: 5, emitter_area: 0.01 }, true, false).unwrap();
+ let mut live = open(&w).unwrap();
+ if live.g.hwrt {
+ let spark = live.sc.tables.emitter_tris.iter().position(|e| e.nominal).expect("the particles are emitters");
+ let side = |c: &LiveCore| {
+ let at = c.sc.up.heap.at(Table::EmitterTris) + (spark * std::mem::size_of::<crate::GpuEmitterTri>()) as u64;
+ let to = c.g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 48, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ let mut e = c.g.device.create_command_encoder(&Default::default());
+ e.copy_buffer_to_buffer(&c.sc.up.heap.buffer, at, &to, 0, 48);
+ c.g.queue.submit([e.finish()]);
+ to.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ c.g.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ let r: crate::GpuEmitterTri = bytemuck::pod_read_unaligned(&to.slice(..).get_mapped_range().unwrap());
+ Vec3::from(r.e1).length()
+ };
+ list_is_its_triangles("a particle, as loaded", &live);
+ assert_eq!(side(&live), 0.0, "a particle is collapsed until its pass places it");
+ picture(&mut live, 1);
+ list_is_its_triangles("a particle, placed", &live);
+ assert!(side(&live) > 0.01, "the list has the particle where its pass placed it ({})", side(&live));
+ }
// Emitters made in place, in a scene with the tree's slot for them (one that has a mesh of its own: its geometry
// can be edited).
let mut w = world();
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 03f32d3..eb849c9 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -25,10 +25,6 @@ pub(super) struct LoadedScene {
/// Some object's move is an instance's transform (`Retained::moves_instances`: kept where the proxies change,
/// here and in a geometry edit): the frame's kernel then writes motion vectors.
pub(super) moving_instances: bool,
- /// The emitters of the dynamic tail (`EmitterTri::moves`, particles apart: their pass places them), in the list's
- /// order, each with its path code (the light tree's moving subtree keeps its shape): the list's copies of their
- /// triangles follow them (edits.rs `move_emitters`).
- pub(super) moving_emitters: Vec<(u32, u32)>,
/// The scene has instanced meshes or procedural geometry (the raster experiment draws only flattened triangles:
/// primary visibility is traced).
pub(super) instanced: bool,
@@ -223,7 +219,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));
let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);
// (The light tree is the tables' by now: its nodes from there.)
- let up = g.upload(&sc, &targets.accum, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;
+ let up = g.upload(&sc, &targets.accum, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;
let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first frame
if !g.merged {
let _ = g.kernel_pass(&up.kernel, "finish");
@@ -289,10 +285,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
pool_first: prep.groups.iter().sum(),
blobs,
};
- let codes: std::collections::HashMap<u32, u32> = tables.light_tree.as_ref().map_or_else(Default::default, |t| {
- let moving = t.moving_first as usize..(t.moving_first + t.moving_count) as usize;
- t.order[moving.clone()].iter().copied().zip(t.code[moving].iter().copied()).collect()
- });
- let moving_emitters = tables.emitter_tris.iter().enumerate().filter(|(_, e)| e.moves && !e.nominal).map(|(i, _)| (i as u32, codes.get(&(i as u32)).copied().unwrap_or(0))).collect();
- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), moving_emitters, 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, meshes, instances, 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/live/mod.rs b/renderer/src/live/mod.rs
index 3d5b3cd..0f9ca7a 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -1263,7 +1263,7 @@ mod instanced_tests {
let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();
(sc.width, sc.height) = (64, 36);
let prep = crate::prepare(g, &mut sc, &mut vec![]);
- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()
};
let (a, b) = (offline(&views), offline(&whole));
@@ -1312,7 +1312,7 @@ mod instanced_tests {
let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();
(sc.width, sc.height) = (64, 36);
let prep = crate::prepare(g, &mut sc, &mut vec![]);
- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()
};
let (a, b) = (offline(&plain), offline(&uniform));
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index 957331f..21f8f32 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -483,7 +483,7 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hos
if job.signals.is_some() {
params.motion[1] = 1.0;
}
- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, threert_render::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, params, spp, &mut timings)?;
+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, threert_render::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, params, spp, &mut timings)?;
if let Some(prefix) = &job.signals {
// The raw (undenoised) means: diffuse = color less specular and emission.
let diffuse: Vec<f32> = frame.color.iter().zip(&frame.specular).zip(&frame.emission).flat_map(|((c, s), e)| [0, 1, 2].map(|k| (c[k] - s[k] - e[k]).max(0.0))).collect();