Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/RUNTIME.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
19 changes: 19 additions & 0 deletions renderer/shaders/emitter_fill.wgsl
Original file line number Diff line number Diff line change
@@ -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);
}
}
27 changes: 7 additions & 20 deletions renderer/shaders/pathtrace.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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).
Expand All @@ -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));
Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
75 changes: 69 additions & 6 deletions renderer/src/gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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).
Expand All @@ -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 {
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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) {
Expand Down
Loading