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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
//! One frame of the live view (`LiveCore::render`): the trace, the live passes, the radiance cache's and the media's
//! training, and the GPU timing and profile.
use super::*;
/// GPU time per frame from timestamp queries (start of the first trace pass .. end of the post pass), read back a few
/// frames later without waiting, so measuring never drains the pipeline.
pub(super) struct FrameTimer {
pub(super) queries: wgpu::QuerySet,
pub(super) resolve: wgpu::Buffer,
/// Per slot: readback buffer and its state (0 free, 1 mapping, 2 mapped, 3 its frame's stamps written and not
/// yet resolved).
pub(super) reads: Vec<(wgpu::Buffer, Arc<AtomicU32>)>,
/// Per slot: the frame it timed, and that frame's samples per pixel (its traces; only the first is timestamped).
pub(super) frames: [u32; TIMER_SLOTS],
pub(super) spps: [u32; TIMER_SLOTS],
/// Per slot: the pairs its frame wrote (bit a pair).
pub(super) ran: [u8; TIMER_SLOTS],
pub(super) slot: usize,
}
/// (A frame holds its slot for about three frames: written, resolved in the next one, read after that.)
pub(super) const TIMER_SLOTS: usize = 6;
/// Stamps a slot, a pair a pass: the trace, the post pass, the emitter weights', the particles', and the post pass
/// after a reconstruction provider.
pub(super) const TIMER_QUERIES: u32 = 10;
/// Gap (ms) between a frame's trace and its post pass past which the wait is not counted (`frame_gpu_ms`).
pub(super) const TIMER_GAP_MS: f32 = 2.0;
/// A frame's GPU time (ms) from its slot's timestamps (a pair a pass: trace, post, the emitter weights', the
/// particles', the post pass after a reconstruction provider; zero: not run): from its first pass (particles, the
/// emitters' weights or trace) to the end of its last. With a provider the post pass is two, the passes before it and
/// those after it, the provider's work between them. The post pass follows the trace's command buffer within
/// ~0.2 ms, after the frame's further samples (`spp` - 1 more traces, untimed, each about as long as the first). A
/// post pass that begins more than TIMER_GAP_MS past where those traces would end (twice their length) did not
/// follow them: the frame is counted as its passes, the further traces at the first one's length.
///
/// The stamps are resolved a frame after their passes (`FrameTimer::resolve_written`). Resolved in the command
/// buffer that wrote them, Metal returned the slot's previous use, four frames old, and now and then a mix of the two
/// uses: 2–3 % of the crowd scene's frames read 70–80 ms. A pass that writes one stamp of a pair is not timed at all
/// (its begin alone read 10 ms late).
pub(super) fn frame_gpu_ms(t: &[u64; 10], spp: u32, period_ns: f32) -> Option<f32> {
let start = [t[6], t[4], t[0]].into_iter().filter(|&v| v > 0).min()?;
let end = t[3].max(t[9]);
if end <= start {
return None;
}
let ms = |ticks: u64| ticks as f32 * period_ns * 1e-6;
let (trace, more) = (ms(t[1].saturating_sub(t[0])), spp.max(1) - 1);
if t[2] >= t[1] && ms(t[2] - t[1]) > TIMER_GAP_MS + 2.0 * more as f32 * trace {
return Some(ms(t[1] - start) + more as f32 * trace + ms(end.saturating_sub(t[2])));
}
Some(ms(end - start))
}
impl FrameTimer {
pub(super) fn new(d: &wgpu::Device) -> FrameTimer {
let n = TIMER_SLOTS as u64;
FrameTimer {
// Per slot, begin / end: the trace, the post pass, the emitter weights', the particles', the post pass after
// a provider (Metal writes a pass's timestamps in pairs).
queries: d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("frame timer"), ty: wgpu::QueryType::Timestamp, count: n as u32 * TIMER_QUERIES }),
resolve: d.create_buffer(&wgpu::BufferDescriptor { label: None, size: n * (TIMER_QUERIES as u64 / 2) * wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),
reads: (0..n).map(|_| (d.create_buffer(&wgpu::BufferDescriptor { label: None, size: TIMER_QUERIES as u64 * 8, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::default())).collect(),
frames: [0; TIMER_SLOTS],
spps: [1; TIMER_SLOTS],
ran: [0; TIMER_SLOTS],
slot: 0,
}
}
/// Latest finished measurement (frame ms, the frame it timed, its trace pass ms), and a free slot for this frame
/// (None: all readbacks still pending, skip).
pub(super) fn harvest(&mut self, period_ns: f32) -> (Option<(f32, u32, f32)>, Option<usize>) {
let mut latest: Option<(f32, u32, f32)> = None;
for (k, (buf, state)) in self.reads.iter().enumerate() {
if state.load(Ordering::Acquire) == 2 {
let t: [u64; 10] = bytemuck::pod_read_unaligned(&buf.slice(..).get_mapped_range().unwrap()[..80]);
buf.unmap();
state.store(0, Ordering::Release);
let frame = self.frames[k];
if let Some(ms) = frame_gpu_ms(&t, self.spps[k], period_ns).filter(|_| latest.is_none_or(|(_, f, _)| frame.wrapping_sub(f) as i32 > 0)) {
latest = Some((ms, frame, t[1].saturating_sub(t[0]) as f32 * period_ns * 1e-6));
}
}
}
let slot = (0..TIMER_SLOTS).map(|k| (self.slot + k) % TIMER_SLOTS).find(|&k| self.reads[k].1.load(Ordering::Acquire) == 0);
if let Some(k) = slot {
self.slot = (k + 1) % TIMER_SLOTS;
}
(latest, slot)
}
/// The slots whose frames are over (state 3) resolved into their readbacks, a frame after their passes: the
/// slots to map once this encoder is submitted.
pub(super) fn resolve_written(&self, e: &mut wgpu::CommandEncoder) -> Vec<usize> {
let mut out = vec![];
for k in 0..TIMER_SLOTS {
if self.reads[k].1.load(Ordering::Acquire) == 3 {
for pair in 0..TIMER_QUERIES / 2 {
self.resolve_pair(e, k, pair, self.ran[k] >> pair & 1 != 0);
}
out.push(k);
}
}
out
}
/// Pair `pair` of `slot` into the slot's readback; `ran` false: zeros.
fn resolve_pair(&self, e: &mut wgpu::CommandEncoder, slot: usize, pair: u32, ran: bool) {
let at = (slot as u64 * (TIMER_QUERIES as u64 / 2) + pair as u64) * wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
if ran {
let q = slot as u32 * TIMER_QUERIES + pair * 2;
e.resolve_query_set(&self.queries, q..q + 2, &self.resolve, at);
} else {
e.clear_buffer(&self.resolve, at, Some(16));
}
e.copy_buffer_to_buffer(&self.resolve, at, &self.reads[slot].0, pair as u64 * 16, 16);
}
}
/// The live kernel's world-space radiance cache (docs/ROADMAP.md § 1, step 1): its buffers and per-frame resolve.
pub(super) struct RadianceCache {
pub(super) bufs: gpu::CacheBuffers,
pub(super) resolve: wgpu::ComputePipeline,
}
/// Share of the pixels showing translucent particles whose nearest hit trains the volume voxels (up to
/// gpu::VOLUME_TRAIN_CAP points per frame).
pub(super) const VOLUME_TRAIN_SHARE: f32 = 1.0 / 8.0;
/// Media voxel training points per frame (pathtrace.wgsl MEDIA_TRAIN_POINTS).
pub(super) const MEDIA_TRAIN_POINTS: u32 = 4096;
pub(super) struct Profile {
pub(super) queries: wgpu::QuerySet,
pub(super) resolve: wgpu::Buffer,
pub(super) read: wgpu::Buffer,
pub(super) sums: Vec<f64>,
pub(super) frames: u32,
/// Timed apart from the slots above: the grid programs' two passes (`gridsim`, queries 0..4) and the media passes
/// (`media`, queries 4..6: the camera rays' march and, at one sample a frame, the volume voxels' training, which
/// are otherwise in the trace's pass). Their queries, the resolve and read buffers, the sums.
pub(super) grid: (wgpu::QuerySet, wgpu::Buffer, wgpu::Buffer),
pub(super) grid_sum: f64,
pub(super) media_sum: f64,
/// The trace's parts (`KERNEL_STAGES`): while profiling, each of the kernel's dispatches of a frame's first sample
/// is a pass of its own with a pair of stamps, and the trace's time is from the first one's begin to the last
/// one's end. Their queries, the resolve and read buffers, the sums.
pub(super) kernel: (wgpu::QuerySet, wgpu::Buffer, wgpu::Buffer),
pub(super) kernel_sums: [f64; KERNEL_STAGES.len()],
}
/// The kernel's dispatches a profile times apart, in the order a frame runs them: the output's guides, the camera
/// hits, the paths, the radiance cache's ends (`finish`), the lights a camera hit resamples, and what else the
/// trace's pass holds (the surface guides of a reconstruction that asks for them, the media's training).
pub(super) const KERNEL_STAGES: [&str; 6] = ["guides", "first_hit", "paths", "finish", "direct", "rest"];
/// A compute pass of the kernel's: its two bind groups set.
fn kernel_compute_pass<'e>(e: &'e mut wgpu::CommandEncoder, label: &str, tw: Option<wgpu::ComputePassTimestampWrites>, scene: &wgpu::BindGroup, targets: &wgpu::BindGroup) -> wgpu::ComputePass<'e> {
let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(label), timestamp_writes: tw });
pass.set_bind_group(0, scene, &[]);
pass.set_bind_group(1, targets, &[]);
pass
}
/// Whether pass `name` runs: the passes that compose the output from its own guides only where it is (`decoupled`), and
/// there not the ones they stand in for.
fn decoupled_runs(decoupled: bool, name: &str) -> bool {
if decoupled { !layout::DECOUPLED_SKIPS.contains(&name) } else { !layout::DECOUPLED_PASSES.contains(&name) }
}
impl LiveCore {
/// The kernel this frame runs. The scene's (`up.kernel`: an edit that brings a feature or a function changes it)
/// where what a frame asks of it is made; else the one the view has, while the scene's is made on another thread
/// (`Gpu::warm_kernel`): the frame does not wait for a compile, and what the new kernel draws (fog, a clear
/// coat, a function) comes when it is ready. A view's first kernel is its load's. In lockstep a frame is its
/// world's alone, and a browser has no other thread: there the frame makes its kernel itself.
fn choose_kernel(&mut self, guides: bool, out_guides: bool) {
let wanted = &self.sc.up.kernel;
let key = |k: &gpu::Kernel| (k.features, k.hash, k.approx);
if self.kernel.as_ref().is_some_and(|k| key(k) == key(wanted)) {
return;
}
// (What a frame asks: as the load makes them, and the guides and the translucency pass where it has them.)
let mut passes: Vec<&'static str> = vec!["first_hit", "direct"];
if !self.g.merged {
passes.push("finish");
}
if guides {
passes.push("surface_guides");
}
if out_guides {
passes.push("guides");
}
if wanted.features & gpu::F_MEDIA != 0 {
passes.extend(["media_train", "media_composite"]);
}
let translucent = self.sc.up.translucent.is_some();
if self.kernel.is_none() || self.fixed_dt.is_some() || cfg!(target_arch = "wasm32") || self.g.kernel_ready(wanted, &passes, translucent) {
self.kernel = Some(wanted.clone());
} else {
self.g.warm_kernel(wanted, &passes, translucent);
}
}
/// Profile slots after the cache resolve that this scene writes: particle pass + BLAS rebuild (2; stateless or GPU
/// particles), translucency + volume training (2 more).
pub(super) fn profile_extra(&self) -> u32 {
if self.sc.up.translucent.is_some() {
4
} else if self.sc.up.particles.is_some() || self.sc.up.gpu_particles.is_some() {
2
} else {
0
}
}
/// Light LOD: the emitter CDF weighted by distance to the camera (`emitter_lod`) and the emitter cull with its view
/// cone (`EmitterCull`), rebuilt when the camera is 15 m from where it was last built, has turned LIGHT_LOD_TURN
/// from that direction, or sees another cone (its lens, the view's shape): the kernel's emitter pdfs read the same
/// reference from the parameters.
pub(super) fn update_light_lod(&mut self) {
let d0 = LIGHT_LOD_D0;
let (w, h) = (self.w, self.h);
let b = &mut self.sc.base;
// The light tree weighs emitters by their distance to each shading point itself: no light LOD, no cull.
if d0 <= 0.0 || self.sc.tables.emitter_tris.is_empty() || b.ltree[3] > 0.5 {
return;
}
let r = glam::Vec3::new(b.light_lod[0], b.light_lod[1], b.light_lod[2]);
let dir = glam::Vec3::new(b.lod_view[0], b.lod_view[1], b.lod_view[2]);
let turned = b.emit_power[2] > 0.0 && dir.dot(self.cam.fwd) < LIGHT_LOD_TURN.to_radians().cos();
// The frustum's half-diagonal: tan = tan(fov / 2) x sqrt(1 + aspect^2).
let half = (self.cam.tan_half_fov * (1.0 + (w as f32 / h as f32).powi(2)).sqrt()).atan() + EMITTER_CULL_MARGIN.to_radians();
let cone = half.min(std::f32::consts::PI).cos();
if b.light_lod[3] > 0.0 && r.distance(self.cam.pos) < 15.0 && !turned && b.lod_view[3] == cone {
return;
}
b.light_lod = [self.cam.pos.x, self.cam.pos.y, self.cam.pos.z, d0];
// (A_FAR_EMITTERS: the cull is the scenes' without a light tree; without it every emitter is proposed.)
let cull = if self.sc.up.kernel.approx & gpu::A_FAR_EMITTERS != 0 { EMITTER_CULL } else { 0.0 };
b.emit_power[1] = cull;
b.emit_power[2] = cull * EMITTER_CULL_VIEW;
b.lod_view = [self.cam.fwd.x, self.cam.fwd.y, self.cam.fwd.z, cone];
// The weights carry the factor: made again from the new reference.
self.weights_dirty = true;
}
pub fn render(&mut self, spp: u32, extra: impl FnOnce(&mut wgpu::CommandEncoder, &wgpu::Buffer)) {
// A dynamic sky's bake that finished since the last frame (time of day).
self.take_sky();
// Runs of the light list retired since the last frame: their records say so, and the weights follow.
self.weights_dirty |= self.flush_retired();
// Settings a game or page requested since the last frame.
if let Some(r) = self.rendering_control.as_ref().and_then(|c| c.take()) { self.set_rendering(r); }
let (w, h) = (self.w, self.h);
let (iw, ih) = self.internal_size();
let size = ReconstructionSize { input: [iw, ih], output: [w, h], dynamic: self.dynamic_res };
self.reset |= self.reconstructor.prepare(&self.g, &self.targets, size, self.view_mode != 0);
let reconstruction = self.reconstructor.active;
// The output composed from guides of its own (`builtin` where the traced grid is coarser than the output; not
// in a view mode, which shows the traced grid's buffers): the camera's rays for every OUTPUT pixel each frame,
// jittered (pathtrace.wgsl `guides`), the lighting on the traced grid at fixed places, and the output
// composed from both and kept in a history of its own (live.wgsl `gcompose`, `gupscale`).
let decoupled = reconstruction.composes_output() && (iw, ih) != (w, h) && self.view_mode == 0;
if decoupled {
self.ensure_guides(self.sc.up.kernel.features & gpu::F_MEDIA != 0);
}
self.ensure_first(iw as u64 * ih as u64);
self.ensure_deferred(iw as u64 * ih as u64);
if self.sc.up.translucent.is_some() {
self.targets.translucent_low(&self.g);
}
let now = Instant::now();
// Lockstep (benchmarks) renders at a fixed frame time, whatever the wall clock says.
self.frame_dt = self.fixed_dt.unwrap_or_else(|| now.duration_since(self.last_frame).as_secs_f32());
self.last_frame = now;
let moved = self.cam != self.prev_cam;
self.update_light_lod();
// A camera cut (a jump no camera makes in one frame: 2 m or 30 degrees) is not motion: no blur (UE: bCameraCut).
let cut = (self.cam.pos - self.prev_cam.pos).length() > 2.0 || self.cam.fwd.dot(self.prev_cam.fwd) < 0.866;
// (Objects moved this frame: re-posed triangles or moved instances, e.g. a crowd's walkers.)
let blur = self.blur.0 > 0.0 && (moved || self.pose_reposed || self.inst_moved) && !cut;
// Camera motion is reprojected exactly (disocclusions are rejected per pixel), so history survives motion;
// the cap only bounds smearing of view-dependent shading (glossy reflections).
// Diffuse lighting reprojects exactly with the camera; view-dependent specular is handled per pixel (temporal pass).
// The most frames a pixel's history holds: HISTORY_LIVE while the scene's lighting changes, HISTORY_FRAMES once
// it has settled. Within it the length is each pixel's own (live.wgsl "The response of the histories": less
// where it moves, cut by its change chart where its lighting changes, restarted where its surface is new). No edit cuts it: until 2026-11-12 a
// lighting edit left every pixel 16 frames and a geometry edit 4, the whole frame for a change in one corner.
let cap = if self.reset { 1.0 } else if self.live_lighting() { HISTORY_LIVE } else { HISTORY_FRAMES };
self.history_len = if self.reset { 1.0 } else { (self.history_len + 1.0).min(cap) };
let cam = self.cam;
let g = &self.g;
// At most two frames in flight: beyond that the CPU waits, so latency stays bounded when GPU-bound.
// Wait for the oldest frame only (waiting for all work would leave the GPU idle while this frame records).
let t_wait = Instant::now();
while self.inflight.len() >= self.frames_in_flight() {
let oldest = self.inflight.pop_front().unwrap();
let _ = g.device.poll(wgpu::PollType::Wait { submission_index: Some(oldest), timeout: None });
}
let waited = t_wait.elapsed().as_secs_f32() * 1000.0;
// The loop guard's count, read back since an earlier frame.
let mut guard_free = false;
if let Some((read, state)) = &self.guard_read {
if state.load(Ordering::Acquire) == 2 {
let n = u32::from_le_bytes(read.slice(..).get_mapped_range().unwrap()[..4].try_into().expect("four bytes"));
read.unmap();
state.store(0, Ordering::Release);
if self.guard_trips != Some(n) {
eprintln!("live: the loop guard has stopped {n} of the kernel's invocations: frames with wrong pixels (a traversal that does not end on this scene's data)");
}
self.guard_trips = Some(n);
}
guard_free = state.load(Ordering::Acquire) == 0;
}
// GPU time drives adaptive resolution / samples per frame: timestamps when available (no stall), else twice a
// second a frame timed in isolation (idle GPU -> submit -> wait).
let period = g.queue.get_timestamp_period();
let timed = match &mut self.timer {
Some(t) => {
let (latest, slot) = t.harvest(period);
if let Some((ms, frame, trace)) = latest {
(self.gpu_ms, self.gpu_frame, self.gpu_trace_ms) = (ms, frame, trace);
}
if let Some(k) = slot {
t.frames[k] = self.frame;
t.spps[k] = spp.max(1);
}
slot
}
None => None,
};
let measure = self.timer.is_none() && self.frame % 30 == 0;
if measure {
let _ = g.device.poll(wgpu::PollType::wait_indefinitely());
}
if !self.pose_reposed && !self.pose_spans.is_empty() {
let spans = std::mem::take(&mut self.pose_spans);
self.keep_prev_spans(&spans);
}
self.pose_reposed = false;
// Likewise the instances the last update moved: their previous-frame rows become the current ones.
if !self.inst_moved && !self.inst_moving.is_empty() {
let size = std::mem::size_of::<scene::GpuInstance>() as u64;
for i in std::mem::take(&mut self.inst_moving) {
let r = &mut self.sc.gpu_instances[i as usize];
r.p = r.m;
self.sc.up.heap.write(&self.g.queue, Table::Instances, i as u64 * size, bytemuck::bytes_of(r));
}
}
self.inst_moved = false;
self.choose_kernel(reconstruction.guides(), decoupled);
let g = &self.g;
let kernel = self.kernel.as_ref().unwrap_or(&self.sc.up.kernel);
let t_submit = Instant::now();
let pipeline = g.pipeline(kernel, true);
let guides = reconstruction.guides().then(|| g.kernel_pass(kernel, "surface_guides"));
// (No media pass while every medium is hidden: a pool of idle fireballs costs the frame nothing.)
let media = kernel.features & gpu::F_MEDIA != 0 && self.sc.up.media_hidden.borrow().iter().any(|h| !h);
let media_train = (media && self.cache.is_some()).then(|| g.kernel_pass(kernel, "media_train"));
let media_composite = media.then(|| g.kernel_pass(kernel, "media_composite"));
// The pixels a sample's trace leaves at the radiance cache (pathtrace.wgsl `finish`).
let finish = self.targets.kernel.deferred.as_ref().filter(|_| self.cache.is_some()).map(|d| (g.kernel_pass(kernel, "finish"), d));
// The frame's camera rays, before its paths (pathtrace.wgsl `first_hit`).
let first = g.kernel_pass(kernel, "first_hit");
// The output grid's guides (pathtrace.wgsl `guides`), where the output is composed from them.
let out_guides = g.kernel_pass(kernel, if decoupled { "guides" } else { "first_hit" });
// The lights a camera hit resamples, after a sample's paths (pathtrace.wgsl `direct`).
let direct = g.kernel_pass(kernel, "direct");
// This frame's sub-pixel jitter (Halton 2, 3), every camera ray's: 8 phases at
// full resolution, as many more as an output pixel has fewer traced ones (8 / scale^2: the upscaler needs each
// output pixel visited), in the 12 bits a side the samples carry it in.
let guide_jitter = {
let quant = |v: f32| (v * 4095.0).round() / 4095.0;
(quant(halton(self.frame % 8 + 1, 2)), quant(halton(self.frame % 8 + 1, 3)))
};
// (The traced samples stay at their pixels' centres where the output has guides of its own: a sample that
// moves over its pixel changes surface at an edge and texel under a normal map, and its history starts
// again each time. Measured 2026-12-04: with the frame's jitter kept, the output's composition gains the
// same detail in motion and none of the steadiness at rest.)
let jitter = if reconstruction.unjittered() || decoupled {
(0.5, 0.5)
} else {
let phases = ((8.0 * (w as f32 / iw as f32) * (h as f32 / ih as f32)).round() as u32).clamp(8, 512);
let quant = |v: f32| (v * 4095.0).round() / 4095.0;
(quant(halton(self.frame % phases + 1, 2)), quant(halton(self.frame % phases + 1, 3)))
};
// The light tiles (pathtrace.wgsl "Light tiles"), in a scene whose local lights are resampled (gpu::F_LISTS):
// the lists the last frame built, for this frame's paths (none after a reset: its reports were another
// view's), and this frame's grid offset, a pixel of 8 x 8.
let tiles_on = kernel.features & gpu::F_LISTS != 0;
if self.reset || !tiles_on {
self.light_tiles = None;
}
let tile_at = (((halton(self.frame % 64 + 1, 2) * 8.0) as u32).min(7), ((halton(self.frame % 64 + 1, 3) * 8.0) as u32).min(7));
// Something moves (triangles re-transformed, instances' transforms): the kernel writes motion vectors.
let moving = self.sc.moving_instances || gpu::Gpu::particle_meshes(&self.sc.up);
// (Whether this frame's first sample ran the emitter weight passes with their timestamps.)
let mut weighed = false;
// (The trace's parts a profile timed this frame: a bit a stage of KERNEL_STAGES.)
let mut staged = 0u32;
for k in 0..spp.max(1) {
let mut p = self.sc.base;
p.motion[1] = reconstruction.raw_signal() as u32 as f32;
if let Some((row, at, size, cam)) = self.light_tiles {
(p.ltile[0], p.ltile[1], p.ltile[2]) = (1, row, at);
p.ltile2 = [size.0, size.1, 0, 0];
p.lt_cam = cam;
}
// Software traversal's units as edits left them: the top tree's root and how many it holds (trace_units.wgsl).
// (The output's pixels: where its guides start in the direct light's buffer, pathtrace.wgsl `guide_at`.)
p.ltile2[2] = w * h;
if let Some(u) = &self.sc.up.units {
(p.motion[2], p.motion[3]) = (f32::from_bits(u.layout.top_first), f32::from_bits(u.count));
}
// The lights a camera hit resamples, in a pass of their own after the paths: where the scene has such
// lights (emitters; more shadow-casting local lights than a camera hit sums exactly: pathtrace.wgsl
// `local_lights`). The kernel's paths leave their surfaces for it when told so.
let (local, casting) = (p.counts[0] - p.counts2[0], p.counts[0] - p.counts2[3]);
let apart = self.direct_pass && (p.counts[1] > 0 || local.min(casting) as usize > gpu::RIS_EXACT);
p.jitter = [jitter.0, jitter.1, if self.rays { 0.0 } else { 1.0 }, apart as u32 as f32];
if moving {
p.motion[0] = 1.0;
}
if self.cache.is_some() {
// Light-sampled particles (sparks: Particles emitterArea) move their light every frame: the cache and
// the temporal pass keep the short history of a lighting edit while the scene has them.
let lit = self.live_lighting();
p.cache = [1.0, CACHE_SAMPLES, if lit { CACHE_FRAMES_LIT } else { CACHE_FRAMES }, 0.0];
}
p.cache[3] = decoupled as u32 as f32;
p.time[0] = shader_time(self.time);
p.cam_pos = [cam.pos.x, cam.pos.y, cam.pos.z, cam.tan_half_fov];
p.cam_fwd = [cam.fwd.x, cam.fwd.y, cam.fwd.z, self.aspect];
p.cam_right = [cam.right.x, cam.right.y, cam.right.z, 0.0];
p.cam_up = [cam.up.x, cam.up.y, cam.up.z, 1.0];
p.size = [iw, ih, self.frame.wrapping_mul(16).wrapping_add(k), crate::rng_seed()];
p.counts2[2] = if ih < h { h } else { 0 };
p.misc[3] = k as f32;
p.counts[2] = p.counts[2].min(self.bounces);
p.counts[3] = p.counts[3].min(2);
self.sc.up.place(&mut p);
self.targets.kernel.place(&mut p);
// (The guides' pass has the parameters first: it runs after what the frame prepares, before the paths.)
let gp = (decoupled && k == 0).then(|| {
let mut gp = p;
gp.jitter = [guide_jitter.0, guide_jitter.1, 0.0, 0.0];
gp.size = [w, h, p.size[2], p.size[3]];
gp.counts2[2] = 0;
gp.ltile[0] = 0;
self.sc.up.place(&mut gp);
self.targets.kernel.place(&mut gp);
gp
});
g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(gp.as_ref().unwrap_or(&p)));
let mut e = g.device.create_command_encoder(&Default::default());
// Particles: placed for this frame's time and camera, then their BLASes built again (before the trace).
// The grid programs (density grids changed on the GPU), before anything reads the grids.
if k == 0 && gpu::Gpu::has_grid_sim(&self.sc.up) {
let sources = std::mem::take(&mut self.grid_sources);
g.run_grids(&self.sc.up, shader_time(self.time), self.frame_dt, &sources, &mut e, self.profile.as_ref().map(|p| (&p.grid.0, 0)));
if let Some(p) = &self.profile {
e.resolve_query_set(&p.grid.0, 0..4, &p.grid.1, 0);
e.copy_buffer_to_buffer(&p.grid.1, 0, &p.grid.2, 0, 32);
}
}
// Stateful GPU particles first (their emissions, the game's spawns): with stateless ones the pass below
// rebuilds the systems' BLASes for both, else this one does.
if let (Some(_), 0) = (&self.sc.up.gpu_particles, k) {
let n = self.passes.pipes.len() as u32 + 2;
let stateless = self.sc.up.particles.is_some();
let (pass_ts, blas_ts) = match (&self.profile, &self.timer, timed, stateless) {
(Some(p), _, _, false) => (Some((&p.queries, n * 2)), Some((&p.queries, n * 2 + 2))),
(None, Some(t), Some(slot), false) => (Some((&t.queries, slot as u32 * TIMER_QUERIES + 6)), None),
_ => (None, None),
};
let spawns = std::mem::take(&mut self.particle_spawns);
g.run_gpu_particles(&self.sc.up, cam.pos.to_array(), cam.fwd.to_array(), shader_time(self.time), self.frame_dt, &spawns, !stateless, &mut e, pass_ts, blas_ts);
}
if let (Some(_), 0) = (&self.sc.up.particles, k) {
let b = &self.sc.base;
let n = self.passes.pipes.len() as u32 + 2;
let pass_ts = match (&self.profile, &self.timer, timed) {
(Some(p), _, _) => Some((&p.queries, n * 2)),
(None, Some(t), Some(slot)) => Some((&t.queries, slot as u32 * TIMER_QUERIES + 6)),
_ => None,
};
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 emitters' weights again, when something they are made of changed.
if k == 0 && std::mem::take(&mut self.weights_dirty) && !self.sc.tables.emitter_tris.is_empty() {
let (t, b) = (&self.sc.tables, &self.sc.base);
let ts = match (&self.profile, &self.timer, timed) {
(None, Some(t), Some(slot)) => Some((&t.queries, slot as u32 * TIMER_QUERIES + 4)),
_ => None,
};
weighed = ts.is_some();
g.weigh_emitters(&self.sc.up, &mut self.weights, t.emitter_tris.len() as u32, t.light_tree.as_ref(), t.stride as u32, b.light_lod, crate::EmitterCull::of(b), &mut e, ts);
}
// Profiled, the first sample's dispatches are a pass each, with a pair of stamps (KERNEL_STAGES).
let stage = |i: usize| self.profile.as_ref().filter(|_| k == 0).map(|p| wgpu::ComputePassTimestampWrites { query_set: &p.kernel.0, beginning_of_pass_write_index: Some(i as u32 * 2), end_of_pass_write_index: Some(i as u32 * 2 + 1) });
let split = self.profile.is_some() && k == 0;
if gp.is_some() {
{
// (The trace's time begins here: its stamps' first, the paths' pass below writing the second.)
let tw = match (&self.profile, &self.timer, timed) {
(Some(_), _, _) => stage(0),
(None, Some(t), Some(slot)) => Some(wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES), end_of_pass_write_index: None }),
_ => None,
};
staged |= split as u32;
let mut pass = kernel_compute_pass(&mut e, "live guides", tw, &self.sc.up.bg, &self.kernel_bg);
pass.set_pipeline(&out_guides);
pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);
}
g.queue.submit([e.finish()]);
g.queue.write_buffer(&self.sc.up.params, 0, bytemuck::bytes_of(&p));
e = g.device.create_command_encoder(&Default::default());
}
{
let begin = |i: u32| (!decoupled).then_some(i);
let tw = match (&self.profile, &self.timer, timed) {
(Some(_), _, _) => stage(1),
(None, Some(t), Some(slot)) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: begin(slot as u32 * TIMER_QUERIES), end_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES + 1) }),
_ => None,
};
if let Some((_, d)) = &finish {
e.clear_buffer(&d.buffer, d.offset, Some(4));
}
let (scene, targets) = (&self.sc.up.bg, &self.kernel_bg);
let mut pass = kernel_compute_pass(&mut e, "live trace", tw, scene, targets);
// (The frame's samples share its camera hits.)
if k == 0 {
staged |= (split as u32) << 1;
pass.set_pipeline(&first);
pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
}
if split {
drop(pass);
staged |= 1 << 2;
pass = kernel_compute_pass(&mut e, "paths", stage(2), scene, targets);
}
pass.set_pipeline(&pipeline);
pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
// (Rows over every traced pixel: the invocations past the records' count leave at once.)
if let Some((f, _)) = &finish {
if split {
drop(pass);
staged |= 1 << 3;
pass = kernel_compute_pass(&mut e, "finish", stage(3), scene, targets);
}
pass.set_pipeline(f);
pass.dispatch_workgroups(gpu::DEFERRED_ROW / 64, (iw * ih).div_ceil(gpu::DEFERRED_ROW), 1);
}
if apart {
if split {
drop(pass);
staged |= 1 << 4;
pass = kernel_compute_pass(&mut e, "direct", stage(4), scene, targets);
}
pass.set_pipeline(&direct);
pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
}
// Participating media: their volume voxels trained after the trace (pathtrace.wgsl media_train), and
// camera rays through media once the frame's samples are traced (media_composite). In the trace's pass
// and timing; profiled, the frame's last sample's media passes are a pass of their own (`media`).
let last = k + 1 == spp.max(1);
if let (Some(p), true, true) = (&self.profile, last, media_composite.is_some()) {
drop(pass);
pass = kernel_compute_pass(&mut e, "media", Some(wgpu::ComputePassTimestampWrites { query_set: &p.grid.0, beginning_of_pass_write_index: Some(4), end_of_pass_write_index: Some(5) }), scene, targets);
} else if split && ((guides.is_some() && last) || media_train.is_some()) {
drop(pass);
staged |= 1 << 5;
pass = kernel_compute_pass(&mut e, "trace rest", stage(5), scene, targets);
}
if let (Some(guides), true) = (&guides, last) {
pass.set_pipeline(guides);
pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
}
if let (Some(mt), 0) = (&media_train, k) {
pass.set_pipeline(mt);
pass.dispatch_workgroups(MEDIA_TRAIN_POINTS.div_ceil(64), 1, 1);
}
if let (Some(mc), true) = (&media_composite, last) {
pass.set_pipeline(mc);
pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
}
}
if let (Some(p), true, true) = (&self.profile, k + 1 == spp.max(1), media_composite.is_some()) {
e.resolve_query_set(&p.grid.0, 4..6, &p.grid.1, wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT);
e.copy_buffer_to_buffer(&p.grid.1, wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT, &p.grid.2, 32, 16);
}
g.queue.submit([e.finish()]);
}
let b = &self.bloom;
// Motion blur's length over this frame's motion: the shutter is open `amount` of a frame; with a target
// frame rate, of a frame at that rate (the blur is as long at any real rate: a frame twice as short moves
// half as far and is blurred twice its motion). 0 while nothing moves (the pass then costs nothing).
let dt = self.frame_dt.clamp(1.0 / 240.0, 0.25);
let shutter = if !blur { 0.0 } else if self.blur.1 > 0.0 { self.blur.0 / (self.blur.1 * dt) } else { self.blur.0 };
let lp = LiveParams {
cur: cam.uniform(self.aspect),
prev: self.prev_cam.uniform(self.aspect),
size: [w, h, self.frame, (self.reset || reconstruction.history_free()) as u32],
misc: [self.view.exposure, cap, self.vignette, b.on as u32 as f32],
misc2: [1.0, SAMPLE_CEILING, shutter, spp.max(1) as f32],
mode: [self.view_mode, self.reconstructor.white_units() as u32, self.live_lighting() as u32, reconstruction.raw_signal() as u32],
post: self.post,
ae: self.view.exposure_settings.ae,
ae2: self.view.exposure_settings.ae2,
ae3: [self.view.exposure_settings.speed[0], self.view.exposure_settings.speed[1], self.frame_dt.clamp(1.0 / 240.0, 0.25), (self.reset || self.frame == 0 || exposure_snap()) as u32 as f32],
lx: self.view.exposure_settings.lx,
isz: [iw, ih, self.prev_isz.0, self.prev_isz.1],
bl: [b.level[0], b.level[1], b.level[2], b.level[3]],
bl2: [b.level[4], b.level[5], if b.has_wide() { b.radius as f32 } else { 0.0 }, b.fine],
bw: [[b.wide[0][0], b.wide[0][1], b.wide[1][0], b.wide[1][1]], [b.wide[2][0], b.wide[2][1], b.wide[3][0], b.wide[3][1]], [b.wide[4][0], b.wide[4][1], b.wide[5][0], b.wide[5][1]]],
lb: [b.base_level[0], b.base_level[1], b.base_level[2], b.base_level[3]],
lb2: [b.base_level[4], b.base_level[5], b.base_wide[0], b.base_wide[1]],
dof: dof_params(self.view.dof.as_ref(), cam.tan_half_fov, w, h),
jit: [jitter.0, jitter.1, guide_jitter.0, guide_jitter.1],
state: [1 - self.frame % 2, decoupled as u32, media as u32, (decoupled && self.prev_decoupled) as u32],
lt: [tile_at.0, tile_at.1, 0, layout::light_tiles(iw)],
};
g.queue.write_buffer(&self.targets.params, 0, bytemuck::bytes_of(&lp));
// Translucent particles: drawn over the upscaled image right after `upscale` (in sb when depth of field / motion
// blur follow, else fa: they have no motion vectors, so they are no part of the colour history; UE draws its
// translucency after the upscaler the same way), then their volume voxels trained.
// (Nothing to draw while every translucent particle system is hidden in place.)
let tl = self.sc.up.translucent.as_ref().filter(|_| g.translucent_particles_live(&self.sc.up)).map(|t| {
let pipes = g.translucent_pipelines(kernel, true);
let target = if lp.misc2[2] > 0.0 || lp.dof[0] > 0.0 { &self.targets.buf("sb").buffer } else { &self.targets.buf("fa").buffer };
// Below full resolution the particles are drawn per traced pixel, then laid over the output (`translucent_up`).
let low = (iw, ih) != (w, h);
let tp = gpu::TranslucentParams { size: [w, h, 0, 1], view: [iw, ih, gpu::VOLUME_TRAIN_CAP, low as u32], misc: [VOLUME_TRAIN_SHARE, 0.0, 0.0, 0.0] };
g.queue.write_buffer(&t.params, 0, bytemuck::bytes_of(&tp));
(pipes, g.translucent_bind_group(t, target, self.targets.translucent_low.as_ref().expect("made at the frame's start")), &t.count)
});
// The pass (train = false) or the volume training (train = true).
let tl_dispatch = |pass: &mut wgpu::ComputePass, train: bool| {
if let Some((pipes, tbg, _)) = &tl {
pass.set_bind_group(0, &self.sc.up.bg, &[]);
pass.set_bind_group(1, self.tl_kernel_bg.as_ref().unwrap(), &[]);
pass.set_bind_group(2, tbg, &[]);
if train {
pass.set_pipeline(&pipes.train);
pass.dispatch_workgroups(gpu::VOLUME_TRAIN_CAP / 64, 1, 1);
} else if (iw, ih) != (w, h) {
pass.set_pipeline(&pipes.draw);
pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
pass.set_pipeline(&pipes.up);
pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);
} else {
pass.set_pipeline(&pipes.draw);
pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);
}
}
};
let mut e = g.device.create_command_encoder(&Default::default());
if let Some((_, _, count)) = &tl {
e.clear_buffer(count, 0, None);
}
if let Some(c) = &self.cache {
let n = self.passes.pipes.len() as u32 + 1;
let tw = self.profile.as_ref().map(|p| wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(n * 2), end_of_pass_write_index: Some(n * 2 + 1) });
let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("cache resolve"), timestamp_writes: tw });
pass.set_pipeline(&c.resolve);
pass.set_bind_group(0, &self.sc.up.bg, &[]);
pass.set_bind_group(1, &self.kernel_bg, &[]);
pass.dispatch_workgroups((gpu::CACHE_SIZE / 256) as u32, 1, 1);
}
let mut before_post: Option<[wgpu::CommandBuffer; 2]> = None;
let mut mapping: Vec<usize> = vec![];
let use_provider = reconstruction.external();
let mut provider_failed = false;
let mut reconstruct = |e: &mut wgpu::CommandEncoder| {
match self.reconstructor.encode(g, e, size, cam, self.aspect, jitter, self.view.exposure, self.reset || cut) {
Ok(buffers) => buffers,
Err(_) => {
provider_failed = true;
// Start fresh rather than read a built-in history from before the switch. With reset, lock_carry
// does no work. (A joint denoiser's frame has no denoising: this one frame shows its raw signal.)
let at = (std::mem::offset_of!(LiveParams, size) + 3 * std::mem::size_of::<u32>()) as u64;
g.queue.write_buffer(&self.targets.params, at, bytemuck::bytes_of(&1u32));
let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("builtin reconstruction fallback"), ..Default::default() });
for (k, (name, grid, pipe)) in self.passes.pipes.iter().enumerate() {
if !matches!(*name, "track" | "judge" | "reject" | "upscale") { continue; }
pass.set_pipeline(pipe);
pass.set_bind_group(0, &self.targets.bgs[k], &[]);
let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz);
pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1);
}
None
}
}
};
if let Some(p) = &self.profile {
// One compute pass per stage, each timed.
for (k, (name, grid, pipe)) in self.passes.pipes.iter().enumerate() {
let q = (k as u32 + 1) * 2;
let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(name), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(q), end_of_pass_write_index: (!(use_provider && *name == "upscale")).then_some(q + 1) }) });
if !reconstruction.skips(name) && (self.view_mode != 0 || !layout::VIEW_MODE_PASSES.contains(name)) && (tiles_on || *name != layout::LIGHT_TILES_PASS) && decoupled_runs(decoupled, name) {
pass.set_pipeline(pipe);
pass.set_bind_group(0, &self.targets.bgs[k], &[]);
let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz);
pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1);
}
drop(pass);
if use_provider && *name == "upscale" {
before_post = reconstruct(&mut e);
drop(e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("reconstruction end"), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: None, end_of_pass_write_index: Some(q + 1) }) }));
}
if *name == "upscale" && tl.is_some() {
for (j, train) in [(0u32, false), (1, true)] {
let q = (self.passes.pipes.len() as u32 + 4 + j) * 2;
let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(if train { "vtrain" } else { "translucent" }), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(q), end_of_pass_write_index: Some(q + 1) }) });
tl_dispatch(&mut pass, train);
}
}
}
let n = self.passes.pipes.len() as u32 + 2 + self.profile_extra();
e.resolve_query_set(&p.queries, 0..n * 2, &p.resolve, 0);
e.copy_buffer_to_buffer(&p.resolve, 0, &p.read, 0, p.read.size());
e.resolve_query_set(&p.kernel.0, 0..KERNEL_STAGES.len() as u32 * 2, &p.kernel.1, 0);
e.copy_buffer_to_buffer(&p.kernel.1, 0, &p.kernel.2, 0, p.kernel.2.size());
} else {
// A pass is timed by a pair of stamps of its own: with a provider, the passes before it (the second pair)
// and those after it (the fifth).
let pair = |k: u32| self.timer.as_ref().zip(timed).map(|(t, slot)| wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES + k), end_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES + k + 1) });
let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("live post"), timestamp_writes: pair(2) });
for (k, (name, grid, pipe)) in self.passes.pipes.iter().enumerate() {
if use_provider && *name == "upscale" {
drop(pass);
before_post = reconstruct(&mut e);
pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("post after reconstruction"), timestamp_writes: pair(8) });
tl_dispatch(&mut pass, false);
tl_dispatch(&mut pass, true);
continue;
}
if reconstruction.skips(name) || (self.view_mode == 0 && layout::VIEW_MODE_PASSES.contains(name)) || (!tiles_on && *name == layout::LIGHT_TILES_PASS) || (!decoupled && layout::DECOUPLED_PASSES.contains(name)) {
continue;
}
// (The decoupled picture's own stage has run by `upscale`'s turn: what follows the upscaler follows it.)
if decoupled_runs(decoupled, name) {
pass.set_pipeline(pipe);
pass.set_bind_group(0, &self.targets.bgs[k], &[]);
let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz);
pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1);
}
if *name == "upscale" {
tl_dispatch(&mut pass, false);
tl_dispatch(&mut pass, true);
}
}
drop(pass);
if let Some(t) = &self.timer {
mapping = t.resolve_written(&mut e);
}
}
if let (Some((read, _)), Some(count), true) = (&self.guard_read, &self.targets.kernel.guard, guard_free) {
e.copy_buffer_to_buffer(&count.buffer, count.offset, read, 0, 4);
}
extra(&mut e, &self.targets.out);
let done = g.queue.submit(before_post.into_iter().flatten().chain([e.finish()]));
if provider_failed { self.history_len = 1.0; }
if let Some(c) = &self.rendering_control { c.publish(self.rendering_status()); }
self.inflight.push_back(done);
self.cpu_wait_ms = waited;
if let (Some((read, state)), true) = (&self.guard_read, guard_free) {
let state = state.clone();
state.store(1, Ordering::Release);
read.slice(..).map_async(wgpu::MapMode::Read, move |r| state.store(if r.is_ok() { 2 } else { 0 }, Ordering::Release));
}
let particles = self.sc.up.particles.is_some() || self.sc.up.gpu_particles.is_some();
if let Some(t) = &mut self.timer {
for k in mapping {
let state = t.reads[k].1.clone();
state.store(1, Ordering::Release);
t.reads[k].0.slice(..).map_async(wgpu::MapMode::Read, move |r| state.store(if r.is_ok() { 2 } else { 0 }, Ordering::Release));
}
// This frame's stamps are written: resolved in the next frame (bits: the pairs that ran).
if let Some(slot) = timed {
t.ran[slot] = 0b11 | (weighed as u8) << 2 | (particles as u8) << 3 | (use_provider as u8) << 4;
t.reads[slot].1.store(3, Ordering::Release);
}
}
// Without timestamps: GPU time ~ submit -> completion (the queue is idle at submit when the frame fits the budget).
if measure {
let _ = g.device.poll(wgpu::PollType::wait_indefinitely());
(self.gpu_ms, self.gpu_frame) = (t_submit.elapsed().as_secs_f32() * 1000.0, self.frame);
}
let extra = self.profile_extra() as usize;
if let Some(p) = &mut self.profile {
let _ = g.device.poll(wgpu::PollType::wait_indefinitely());
p.read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
let _ = g.device.poll(wgpu::PollType::wait_indefinitely());
let t: Vec<u64> = bytemuck::cast_slice::<u8, u64>(&p.read.slice(..).get_mapped_range().unwrap()).to_vec();
p.read.unmap();
let period = g.queue.get_timestamp_period() as f64 * 1e-6;
// The particle, BLAS, translucency and volume training slots (the last four) are written only when the scene
// has particles / translucent ones.
let n = self.passes.pipes.len() + 2 + extra;
for (k, s) in p.sums.iter_mut().enumerate().take(n).skip(1) {
*s += t[k * 2 + 1].saturating_sub(t[k * 2]) as f64 * period;
}
// The trace: its stages' own times, and from the first one's begin to the last one's end.
p.kernel.2.slice(..).map_async(wgpu::MapMode::Read, |_| {});
let _ = g.device.poll(wgpu::PollType::wait_indefinitely());
let t: Vec<u64> = bytemuck::cast_slice::<u8, u64>(&p.kernel.2.slice(..).get_mapped_range().unwrap()).to_vec();
p.kernel.2.unmap();
let ran = (0..KERNEL_STAGES.len()).filter(|k| staged >> k & 1 != 0);
for k in ran.clone() {
p.kernel_sums[k] += t[k * 2 + 1].saturating_sub(t[k * 2]) as f64 * period;
}
if let (Some(begin), Some(end)) = (ran.clone().map(|k| t[k * 2]).min(), ran.map(|k| t[k * 2 + 1]).max()) {
p.sums[0] += end.saturating_sub(begin) as f64 * period;
}
let (sim, media) = (gpu::Gpu::has_grid_sim(&self.sc.up), media_composite.is_some());
if sim || media {
p.grid.2.slice(..).map_async(wgpu::MapMode::Read, |_| {});
let _ = g.device.poll(wgpu::PollType::wait_indefinitely());
let t: Vec<u64> = bytemuck::cast_slice::<u8, u64>(&p.grid.2.slice(..).get_mapped_range().unwrap()).to_vec();
p.grid.2.unmap();
if sim {
p.grid_sum += (t[1].saturating_sub(t[0]) + t[3].saturating_sub(t[2])) as f64 * period;
}
if media {
p.media_sum += t[5].saturating_sub(t[4]) as f64 * period;
}
}
p.frames += 1;
if p.frames == 120 {
let names: Vec<&str> = std::iter::once("trace").chain(self.passes.pipes.iter().map(|(n, ..)| *n)).chain(["cache", "particles", "blas", "translucent", "vtrain"]).collect();
let mut rows: Vec<String> = names.iter().zip(&p.sums).map(|(n, s)| format!("{n} {:.2}", s / p.frames as f64)).collect();
// (The trace's parts after it; they are within its time, not beside it.)
rows.splice(1..1, KERNEL_STAGES.iter().zip(&p.kernel_sums).map(|(n, s)| format!("trace.{n} {:.2}", s / p.frames as f64)));
p.kernel_sums = [0.0; KERNEL_STAGES.len()];
rows.push(format!("gridsim {:.2}", p.grid_sum / p.frames as f64));
rows.push(format!("media {:.2}", p.media_sum / p.frames as f64));
rows.retain(|r| !r.ends_with(" 0.00"));
eprintln!("profile ms/frame: total {:.2} | {}", (p.sums.iter().sum::<f64>() + p.grid_sum + p.media_sum) / p.frames as f64, rows.join(", "));
(p.grid_sum, p.media_sum) = (0.0, 0.0);
p.sums.iter_mut().for_each(|s| *s = 0.0);
p.frames = 0;
}
}
self.prev_cam = cam;
self.shown_spp = spp.max(1);
self.prev_isz = (iw, ih);
self.prev_decoupled = decoupled;
let cu = cam.uniform(self.aspect);
self.light_tiles = tiles_on.then_some((layout::light_tiles(iw), tile_at.0 | tile_at.1 << 16, (iw, ih), [cu.pos, cu.fwd, cu.right, cu.up]));
self.reset = false;
self.frame = self.frame.wrapping_add(1);
}
}