From e806e197f100eeffb4114bcdfab9122c31fc59e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Fri, 6 Nov 2026 16:42:47 +0100 Subject: [PATCH] perf: compile pipelines on first use and prewarm them in parallel Renderer::new created every pipeline of every feature up front, one after another: 57 pipelines and 10.8 s on an M1 Max with a cold Metal shader cache (first launch after install or an OS/driver update), of which a game at the Medium preset used 16. Path tracing, hardware-RT probes, the GPU-driven renderer and the rest compiled whether or not they ever ran. - renderer/lazy_pipeline.rs: LazyRenderPipeline / LazyComputePipeline keep an owned copy of the descriptor (modules and layouts are refcounted handles) and compile on first Deref. Creation sites change one call; use sites deref-coerce. Correctness doesn't depend on any list: whatever a frame draws is built on first use. - Renderer::prewarm_pipelines: when the settings that select pipelines change (first frame, a quality preset, a feature toggled at runtime), the pipelines those settings use compile on background threads; a draw waits only for the one it needs. Conditions measured per preset with a pipeline-use trace. No-op on wasm (wgpu objects aren't Send there). - BLOOM_PIPELINE_LOG=1 prints each compile, its time and whether it ran on a prewarm thread or made a frame wait. Measured (M1 Max, MTL_SHADER_CACHE_SIZE=0 for cold): cold initWindow 11.4 s -> 0.5 s, then ~0.9 s in the first 3D frame warm initWindow 0.6-0.9 s -> 0.33 s tuichess 3D at Medium and High: every pipeline it draws is prewarmed, none compiles on the render thread BRDF LUT at build time: build.rs includes brdf_lut.rs and writes the 256x256 table to OUT_DIR once per build (1.7 s, only when the generator changes); the renderer embeds it. Computing it at startup took ~0.4 s on an M1 Max at every launch, more on phones and the single-threaded web build. A test checks the embedded table against the generator. Profiler: a label can cover several passes (the bloom mip chain), and on tile-based GPUs consecutive passes overlap (the next pass's vertex work starts while the previous pass's fragments run), so summing their intervals counted the same GPU time several times: bloom read 5.4 ms for 0.8 ms of work, 49 ms inside a 13 ms frame in a real scene. Per-label GPU time and the frame totals are now the union of the intervals; CPU frame totals too (phases nest: queue_submit runs inside render_total). --- native/shared/Cargo.toml | 2 + native/shared/build.rs | 14 + native/shared/src/profiler.rs | 127 ++++- native/shared/src/renderer/brdf_lut.rs | 30 +- native/shared/src/renderer/froxel.rs | 5 +- native/shared/src/renderer/gpu_driven.rs | 39 +- native/shared/src/renderer/impulse_field.rs | 5 +- native/shared/src/renderer/lazy_pipeline.rs | 526 ++++++++++++++++++ native/shared/src/renderer/mod.rs | 210 +++---- native/shared/src/renderer/occlusion.rs | 12 +- native/shared/src/renderer/scene_pass.rs | 4 +- .../src/renderer/sorted_transparency.rs | 8 +- native/shared/src/renderer/ssr_pass.rs | 2 +- native/shared/src/shadows.rs | 13 +- 14 files changed, 844 insertions(+), 153 deletions(-) create mode 100644 native/shared/src/renderer/lazy_pipeline.rs diff --git a/native/shared/Cargo.toml b/native/shared/Cargo.toml index 76e2b9d8..aaf0d66d 100644 --- a/native/shared/Cargo.toml +++ b/native/shared/Cargo.toml @@ -43,6 +43,8 @@ image-extras = [ [build-dependencies] cmake = "0.1" +# build.rs generates the BRDF table with the renderer's own generator +half = "2" [dependencies] bloom-geometry-format = { path = "../../crates/bloom-geometry-format", optional = true } diff --git a/native/shared/build.rs b/native/shared/build.rs index b4e6bb35..ee21730e 100644 --- a/native/shared/build.rs +++ b/native/shared/build.rs @@ -4,9 +4,23 @@ //! the `bloom_jolt` C++ shim (and JoltPhysics, via its own CMakeLists) via the //! `cmake` crate and emits link directives so rustc picks up both archives. +// The split-sum BRDF table is a constant: generate it here, once per build, +// instead of in every app's startup (see src/renderer/brdf_lut.rs). +#[path = "src/renderer/brdf_lut.rs"] +mod brdf_lut; + +fn write_brdf_lut() { + println!("cargo:rerun-if-changed=src/renderer/brdf_lut.rs"); + let texels = brdf_lut::build_brdf_lut(brdf_lut::BRDF_LUT_SIZE); + let bytes: Vec = texels.iter().flat_map(|t| t.to_le_bytes()).collect(); + let out = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("brdf_lut.bin"); + std::fs::write(&out, bytes).expect("write brdf_lut.bin"); +} + fn main() { // Always re-run when these change. println!("cargo:rerun-if-changed=build.rs"); + write_brdf_lut(); println!("cargo:rerun-if-env-changed=CARGO_FEATURE_JOLT"); // SH-055 — `fold_scene_inputs` cfg. GPUs that cap `maxBindGroups` at 4 — diff --git a/native/shared/src/profiler.rs b/native/shared/src/profiler.rs index e0009cba..920d0f10 100644 --- a/native/shared/src/profiler.rs +++ b/native/shared/src/profiler.rs @@ -69,6 +69,39 @@ pub struct Profiler { frame_total_gpu_us: [f64; ROLLING_FRAMES], histogram_idx: usize, histogram_filled: usize, + + /// This frame's CPU phase spans (start, end), for the frame total: + /// phases nest (`queue_submit` runs inside `render_total`), so the + /// total is the time covered by any phase, not the sum of them. + cpu_spans: Vec<(Instant, Instant)>, + /// This frame's GPU busy time: the union of every pass interval. + /// Passes overlap on tile-based GPUs (the next pass's vertex work + /// starts while the previous pass's fragments run), so a sum + /// counts the same GPU time several times. + gpu_union_us: Option, +} + +/// Total length covered by a set of (start, end) intervals, overlaps +/// counted once. +fn union_length(mut spans: Vec<(u64, u64)>) -> u64 { + spans.retain(|(b, e)| e > b); + spans.sort_unstable(); + let mut total = 0; + let mut current: Option<(u64, u64)> = None; + for (b, e) in spans { + match current { + Some((cb, ce)) if b <= ce => current = Some((cb, ce.max(e))), + Some((cb, ce)) => { + total += ce - cb; + current = Some((b, e)); + } + None => current = Some((b, e)), + } + } + if let Some((cb, ce)) = current { + total += ce - cb; + } + total } struct RollingStats { @@ -193,6 +226,8 @@ impl Profiler { frame_total_gpu_us: [0.0; ROLLING_FRAMES], histogram_idx: 0, histogram_filled: 0, + cpu_spans: Vec::new(), + gpu_union_us: None, } } @@ -264,7 +299,9 @@ impl Profiler { return; } if let Some(s) = self.open_cpu.remove(label) { - let us = s.start.elapsed().as_secs_f64() * 1_000_000.0; + let now = Instant::now(); + let us = now.duration_since(s.start).as_secs_f64() * 1_000_000.0; + self.cpu_spans.push((s.start, now)); self.frame.push(FrameSample { label, cpu_us: us, @@ -358,6 +395,8 @@ impl Profiler { if !self.enabled { self.frame.clear(); self.open_cpu.clear(); + self.cpu_spans.clear(); + self.gpu_union_us = None; self.next_query = 0; self.pending_gpu.clear(); return; @@ -375,7 +414,12 @@ impl Profiler { let data = slice.get_mapped_range().to_vec(); readback.unmap(); let period = self.timestamp_period_ns as f64; - let mut by_label: HashMap<&'static str, f64> = HashMap::new(); + // A label can cover several passes (the bloom mip chain), and + // on tile-based GPUs consecutive passes overlap: each label + // reports the time covered by its intervals, and the frame the + // time covered by all of them, not their sums. + let mut spans: HashMap<&'static str, Vec<(u64, u64)>> = HashMap::new(); + let mut all = Vec::with_capacity(self.pending_gpu.len()); for (label, b, e) in &self.pending_gpu { let bo = (*b as usize) * 8; let eo = (*e as usize) * 8; @@ -384,11 +428,20 @@ impl Profiler { } let bt = u64::from_le_bytes(data[bo..bo + 8].try_into().unwrap()); let et = u64::from_le_bytes(data[eo..eo + 8].try_into().unwrap()); + // an unwritten end (an empty pass on some drivers) reads 0 if et <= bt { continue; } - let us = (et - bt) as f64 * period / 1000.0; - *by_label.entry(*label).or_insert(0.0) += us; + spans.entry(*label).or_default().push((bt, et)); + all.push((bt, et)); + } + let ticks_to_us = |t: u64| t as f64 * period / 1000.0; + let mut by_label: HashMap<&'static str, f64> = spans + .into_iter() + .map(|(label, v)| (label, ticks_to_us(union_length(v)))) + .collect(); + if !all.is_empty() { + self.gpu_union_us = Some(ticks_to_us(union_length(all))); } for s in self.frame.iter_mut() { if let Some(us) = by_label.remove(s.label) { @@ -417,6 +470,8 @@ impl Profiler { // Phase 8 — sum the per-pass samples into a per-frame total // for the histogram before draining. CPU sums every sample; // GPU sums only those with timestamps (rest have None). + // Totals are the time covered by the frame's phases and passes + // (they nest and overlap); samples without spans (tests) add up. let mut frame_cpu = 0.0; let mut frame_gpu = 0.0; for s in &self.frame { @@ -425,6 +480,14 @@ impl Profiler { frame_gpu += g; } } + if let Some(origin) = self.cpu_spans.iter().map(|(b, _)| *b).min() { + let ns = |t: Instant| t.duration_since(origin).as_nanos() as u64; + let spans = self.cpu_spans.drain(..).map(|(b, e)| (ns(b), ns(e))).collect(); + frame_cpu = union_length(spans) as f64 / 1000.0; + } + if let Some(g) = self.gpu_union_us.take() { + frame_gpu = g; + } self.frame_total_cpu_us[self.histogram_idx] = frame_cpu; self.frame_total_gpu_us[self.histogram_idx] = frame_gpu; self.histogram_idx = (self.histogram_idx + 1) % ROLLING_FRAMES; @@ -509,25 +572,24 @@ impl Profiler { out } - /// Average total CPU frame time across the rolling window (sum of - /// all phases). Useful for a single headline number. + /// Average CPU frame time across the rolling window: the time + /// covered by the frame's profiled phases (nested phases once). pub fn avg_frame_cpu_us(&self) -> f64 { - let fc = self.frame_count; - self.rolling - .values() - .filter(|s| fc.saturating_sub(s.last_frame) <= ROLLING_FRAMES as u64) - .map(|s| s.avg_cpu()) - .sum() + self.avg_history(|(cpu, _)| cpu) } - /// Average total GPU frame time where available. + /// Average GPU frame time where available: the time the frame's + /// timed passes kept the GPU busy (overlapping passes once). pub fn avg_frame_gpu_us(&self) -> f64 { - let fc = self.frame_count; - self.rolling - .values() - .filter(|s| fc.saturating_sub(s.last_frame) <= ROLLING_FRAMES as u64) - .filter_map(|s| s.avg_gpu()) - .sum() + self.avg_history(|(_, gpu)| gpu) + } + + fn avg_history(&self, pick: impl Fn((f64, f64)) -> f64) -> f64 { + let h = self.frame_history(); + if h.is_empty() { + return 0.0; + } + h.iter().map(|&f| pick(f)).sum::() / h.len() as f64 } /// Snapshot the rolling averages in a stable, CPU-time-descending @@ -662,6 +724,33 @@ mod tests { p.frame_end_cpu(); } + #[test] + fn union_length_counts_overlaps_once() { + assert_eq!(union_length(vec![]), 0); + assert_eq!(union_length(vec![(10, 20)]), 10); + // nine overlapping bloom mips spanning 270..1080 (as measured on M1 Max) + let bloom = vec![(270, 941), (369, 972), (386, 988), (471, 1003), (473, 1019), (512, 1027), (532, 1035), (551, 1047), (553, 1077)]; + assert_eq!(union_length(bloom), 1077 - 270); + // disjoint, nested and empty/inverted spans + assert_eq!(union_length(vec![(0, 10), (20, 30), (22, 25), (40, 40), (50, 45)]), 20); + } + + #[test] + fn nested_cpu_phases_count_once_in_frame_total() { + let mut p = Profiler::new(); + p.set_enabled(true); + p.begin("outer"); + p.begin("inner"); + std::thread::sleep(std::time::Duration::from_millis(5)); + p.end("inner"); + p.end("outer"); + p.frame_end_cpu(); + let (cpu, _) = p.frame_history()[0]; + let outer = p.snapshot().iter().find(|(l, _, _)| *l == "outer").unwrap().1; + assert!((cpu - outer).abs() < 1.0, "frame total {cpu} us must equal the outer phase {outer} us, not outer + inner"); + assert!((p.avg_frame_cpu_us() - cpu).abs() < 1e-9); + } + #[test] fn frame_history_empty_before_any_frames() { let mut p = Profiler::new(); diff --git a/native/shared/src/renderer/brdf_lut.rs b/native/shared/src/renderer/brdf_lut.rs index c5094767..2dc39c24 100644 --- a/native/shared/src/renderer/brdf_lut.rs +++ b/native/shared/src/renderer/brdf_lut.rs @@ -2,9 +2,10 @@ //! //! Pre-integrates the GGX BRDF into a 2D `Rg16Float` table indexed by //! `(NdotV, roughness)` that the PBR shader samples at runtime via -//! the Karis-2013 split-sum approximation. Entirely CPU-side — -//! builds once at startup via `build_brdf_lut(size)` and hands the -//! result to `queue.write_texture` in `Renderer::new`. +//! the Karis-2013 split-sum approximation. The table is a constant: +//! `build.rs` includes this file and runs `build_brdf_lut(BRDF_LUT_SIZE)` +//! once per build, and `Renderer::new` uploads the embedded bytes +//! (computing it at startup took ~0.4 s on an M1 Max, every launch). //! //! Private helpers (Hammersley, GGX importance sampling, Smith //! geometry) stay module-scoped; only `build_brdf_lut` is `pub` so @@ -24,6 +25,9 @@ // × Fresnel(VdotH) part. The Fresnel split into scale (F0) and bias // (1) lets us factor F0 out of the integral. +/// Width and height of the table, in texels. +pub const BRDF_LUT_SIZE: usize = 256; + const BRDF_LUT_SAMPLES: u32 = 1024; fn radical_inverse_vdc(mut bits: u32) -> f32 { @@ -128,7 +132,8 @@ fn build_brdf_lut_row(y: usize, size: usize) -> Vec { /// row is constant `roughness` (v axis), each column constant `NdotV` /// (u axis). Output is row-major suitable for write_texture. Splits /// across `available_parallelism()` threads since cells are -/// independent — keeps startup latency manageable even at 1024 spp. +/// independent. Runs in `build.rs`; the renderer only calls it in tests. +#[cfg_attr(not(test), allow(dead_code))] pub fn build_brdf_lut(size: usize) -> Vec { #[cfg(not(target_arch = "wasm32"))] { @@ -162,3 +167,20 @@ pub fn build_brdf_lut(size: usize) -> Vec { .collect() } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The table the renderer embeds is the generator's output, row-major. + #[test] + fn baked_table_matches_generator() { + let baked = super::super::BRDF_LUT_BAKED; + assert_eq!(baked.len(), BRDF_LUT_SIZE * BRDF_LUT_SIZE * 2 * 2); + for y in [0, BRDF_LUT_SIZE / 2, BRDF_LUT_SIZE - 1] { + let row: Vec = build_brdf_lut_row(y, BRDF_LUT_SIZE).iter().flat_map(|t| t.to_le_bytes()).collect(); + let start = y * BRDF_LUT_SIZE * 4; + assert_eq!(&baked[start..start + row.len()], row.as_slice(), "row {y}"); + } + } +} diff --git a/native/shared/src/renderer/froxel.rs b/native/shared/src/renderer/froxel.rs index 62d20215..8446bf2e 100644 --- a/native/shared/src/renderer/froxel.rs +++ b/native/shared/src/renderer/froxel.rs @@ -17,6 +17,7 @@ //! (256 = worst-case every light in one froxel — exact parity with the //! reference loop, no truncation). +use super::lazy_pipeline::LazyComputePipeline; use wgpu::util::DeviceExt; pub(super) const GRID_X: u32 = 16; @@ -243,7 +244,7 @@ pub(super) fn extra_lighting_layout_entries() -> [wgpu::BindGroupLayoutEntry; 3] } pub struct FroxelPass { - pub assign_pipeline: wgpu::ComputePipeline, + pub assign_pipeline: LazyComputePipeline, pub assign_layout: wgpu::BindGroupLayout, pub params_buffer: wgpu::Buffer, /// Compact point-light UBO for the compute pass (count + 256 lights). @@ -323,7 +324,7 @@ impl FroxelPass { bind_group_layouts: &[Some(&assign_layout)], ..Default::default() }); - let assign_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let assign_pipeline = LazyComputePipeline::new(device, &wgpu::ComputePipelineDescriptor { label: Some("froxel_assign_pipeline"), layout: Some(&pl), module: &shader, diff --git a/native/shared/src/renderer/gpu_driven.rs b/native/shared/src/renderer/gpu_driven.rs index b01b1a20..b3b46252 100644 --- a/native/shared/src/renderer/gpu_driven.rs +++ b/native/shared/src/renderer/gpu_driven.rs @@ -7,6 +7,7 @@ //! `instance_count` for culled draws. Keeping command slots ordered avoids the //! alpha/cutout ordering changes caused by atomic append compaction. +use super::lazy_pipeline::{LazyComputePipeline, LazyRenderPipeline}; use super::{ material_indirection::GpuCompletionTracker, MeshDrawRef, Renderer, Uniforms3D, Vertex3D, DEPTH_FORMAT, HDR_FORMAT, MATERIAL_FORMAT, VELOCITY_FORMAT, @@ -368,17 +369,33 @@ pub struct GpuDrivenRenderer { cull_bind_group: wgpu::BindGroup, draw_layout: wgpu::BindGroupLayout, draw_bind_group: wgpu::BindGroup, - cull_pipeline: Option, - depth_pipeline: Option, - main_pipeline: Option, - main_prepassed_pipeline: Option, - main_visibility_compat_pipeline: Option, - main_visibility_compat_prepassed_pipeline: Option, + cull_pipeline: Option, + depth_pipeline: Option, + main_pipeline: Option, + main_prepassed_pipeline: Option, + main_visibility_compat_pipeline: Option, + main_visibility_compat_prepassed_pipeline: Option, visibility: super::visibility_buffer::VisibilityBufferRuntime, pub(super) draw_scratch: Vec, pub stats: SubmissionStats, } +impl GpuDrivenRenderer { + /// The pipelines a frame with GPU-driven draws uses, for `Renderer::prewarm_pipelines`. + pub(crate) fn warm_handles(&self) -> Vec { + [ + self.depth_pipeline.as_ref(), + self.main_pipeline.as_ref(), + self.main_prepassed_pipeline.as_ref(), + ] + .into_iter() + .flatten() + .map(|p| p.warm_handle()) + .chain(self.cull_pipeline.as_ref().map(|p| p.warm_handle())) + .collect() + } +} + impl GpuDrivenRenderer { pub fn new( device: &wgpu::Device, @@ -454,7 +471,7 @@ impl GpuDrivenRenderer { bind_group_layouts: &[Some(&cull_layout)], immediate_size: 0, }); - let cull_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let cull_pipeline = LazyComputePipeline::new(device, &wgpu::ComputePipelineDescriptor { label: Some("gpu_driven_cull_pipeline"), layout: Some(&cull_pipeline_layout), module: &cull_shader, @@ -1358,7 +1375,7 @@ fn create_depth_pipeline( layout: &wgpu::PipelineLayout, shader: &wgpu::ShaderModule, visibility_target: bool, -) -> wgpu::RenderPipeline { +) -> LazyRenderPipeline { let targets = [visibility_target.then_some(wgpu::ColorTargetState { format: super::visibility_buffer::VISIBILITY_FORMAT, blend: None, @@ -1366,7 +1383,7 @@ fn create_depth_pipeline( // priming depth; the ordinary path has no color target at all. write_mask: wgpu::ColorWrites::ALL, })]; - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(device, &wgpu::RenderPipelineDescriptor { label: Some("gpu_driven_depth_pipeline"), layout: Some(layout), vertex: wgpu::VertexState { @@ -1406,7 +1423,7 @@ fn create_main_pipeline( vertex_shader: &wgpu::ShaderModule, fragment_shader: &wgpu::ShaderModule, prepassed: bool, -) -> wgpu::RenderPipeline { +) -> LazyRenderPipeline { #[cfg(lean_mrt)] let targets = &[ Some(wgpu::ColorTargetState { @@ -1445,7 +1462,7 @@ fn create_main_pipeline( write_mask: wgpu::ColorWrites::ALL, }), ]; - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(device, &wgpu::RenderPipelineDescriptor { label: Some(if prepassed { "gpu_driven_main_prepassed_pipeline" } else { diff --git a/native/shared/src/renderer/impulse_field.rs b/native/shared/src/renderer/impulse_field.rs index 65b9675d..11342141 100644 --- a/native/shared/src/renderer/impulse_field.rs +++ b/native/shared/src/renderer/impulse_field.rs @@ -16,6 +16,7 @@ //! World footprint is a hardcoded 128 m square centred on origin at //! 256×256 texels = 0.5 m/texel for now. A later phase can replace //! that with a per-game descriptor. +use super::lazy_pipeline::LazyComputePipeline; use crate::renderer::shader_include::ShaderSource; use crate::renderer::shader_library::library; @@ -55,7 +56,7 @@ struct InfoUniforms { } pub struct ImpulseField { - pipeline: wgpu::ComputePipeline, + pipeline: LazyComputePipeline, bg_layout: wgpu::BindGroupLayout, info_buf: wgpu::Buffer, /// Backing textures for view_a/view_b — kept alive so the views @@ -127,7 +128,7 @@ impl ImpulseField { label: Some("impulse_field"), source: wgpu::ShaderSource::Wgsl(shader_src.into()), }); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let pipeline = LazyComputePipeline::new(device, &wgpu::ComputePipelineDescriptor { label: Some("impulse_field_pipeline"), layout: Some(&pipeline_layout), module: &module, diff --git a/native/shared/src/renderer/lazy_pipeline.rs b/native/shared/src/renderer/lazy_pipeline.rs new file mode 100644 index 00000000..2067a602 --- /dev/null +++ b/native/shared/src/renderer/lazy_pipeline.rs @@ -0,0 +1,526 @@ +//! Pipelines that compile when they are first used, or ahead of that on +//! background threads. +//! +//! Creating a pipeline compiles its shaders for the GPU (on Metal: WGSL -> +//! MSL -> `newLibraryWithSource`, synchronously). `Renderer::new` used to +//! create every pipeline of every feature up front, one after another: 57 +//! pipelines and ~10.8 s on an M1 Max with a cold shader cache, of which a +//! game at the Medium preset used 16. A `LazyRenderPipeline` keeps an owned +//! copy of its descriptor (shader modules and layouts are reference-counted +//! handles) and compiles on the first `Deref`, so a feature that never runs +//! never compiles. `prewarm` compiles a set of pipelines in parallel on +//! background threads; a draw that needs one of them waits for that one only. +//! +//! Correctness never depends on prewarming: whatever path a frame takes, its +//! pipelines are built on first use. Prewarming (`Renderer::prewarm_pipelines`) +//! only decides when. +//! +//! `BLOOM_PIPELINE_LOG=1` prints each compile with its time and thread, so a +//! compile on the render thread (a hitch) shows up. + +use std::ops::Deref; +use std::sync::{Arc, Mutex, OnceLock}; + +#[cfg(not(target_arch = "wasm32"))] +type Init

= Box P + Send>; +// wgpu objects are not Send on the web; nothing is built off-thread there. +#[cfg(target_arch = "wasm32")] +type Init

= Box P>; + +struct Inner

{ + label: String, + cell: OnceLock

, + init: Mutex>>, +} + +/// A pipeline built on first use. Derefs to the wgpu pipeline; cloning shares it. +pub struct Lazy

(Arc>); + +impl

Clone for Lazy

{ + fn clone(&self) -> Self { + Lazy(self.0.clone()) + } +} + +pub type LazyRenderPipeline = Lazy; +pub type LazyComputePipeline = Lazy; + +impl

Lazy

{ + fn from_init(label: String, init: Init

) -> Self { + Lazy(Arc::new(Inner { + label, + cell: OnceLock::new(), + init: Mutex::new(Some(init)), + })) + } + + /// An already-built pipeline (one created at runtime, where it is needed at once). + pub fn ready(pipeline: P) -> Self { + let cell = OnceLock::new(); + let _ = cell.set(pipeline); + Lazy(Arc::new(Inner { + label: String::new(), + cell, + init: Mutex::new(None), + })) + } + + /// The pipeline, compiling it on this thread unless it is built or being built. + pub fn get(&self) -> &P { + self.0.cell.get_or_init(|| { + let init = self + .0 + .init + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + .expect("lazy pipeline initializer already taken"); + let started = log_enabled().then(std::time::Instant::now); + let pipeline = init(); + if let Some(t) = started { + let thread = std::thread::current(); + eprintln!( + "bloom: pipeline {} compiled in {:.1} ms, {}", + self.0.label, + t.elapsed().as_secs_f64() * 1000.0, + match thread.name() { + Some("bloom-pipeline-warm") => "a prewarm thread", + _ => "first use (the thread waited)", + } + ); + } + pipeline + }) + } + + pub fn is_built(&self) -> bool { + self.0.cell.get().is_some() + } + + pub fn label(&self) -> &str { + &self.0.label + } +} + +impl

Deref for Lazy

{ + type Target = P; + fn deref(&self) -> &P { + self.get() + } +} + +fn log_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("BLOOM_PIPELINE_LOG").is_some()) +} + +// ------------------------------------------------------------ owned descriptors + +struct OwnedCompilation { + constants: Vec<(String, f64)>, + zero_initialize_workgroup_memory: bool, +} + +impl OwnedCompilation { + fn new(o: &wgpu::PipelineCompilationOptions<'_>) -> Self { + OwnedCompilation { + constants: o.constants.iter().map(|(k, v)| (k.to_string(), *v)).collect(), + zero_initialize_workgroup_memory: o.zero_initialize_workgroup_memory, + } + } +} + +struct OwnedVertexBuffer { + array_stride: wgpu::BufferAddress, + step_mode: wgpu::VertexStepMode, + attributes: Vec, +} + +struct OwnedFragment { + module: wgpu::ShaderModule, + entry_point: Option, + compilation: OwnedCompilation, + targets: Vec>, +} + +impl LazyRenderPipeline { + /// Records `desc` and compiles it on first use (see the module docs). + pub fn new(device: &wgpu::Device, desc: &wgpu::RenderPipelineDescriptor<'_>) -> Self { + let device = device.clone(); + let label = desc.label.map(str::to_owned); + let layout = desc.layout.cloned(); + let vs_module = desc.vertex.module.clone(); + let vs_entry = desc.vertex.entry_point.map(str::to_owned); + let vs_compilation = OwnedCompilation::new(&desc.vertex.compilation_options); + let buffers: Vec = desc + .vertex + .buffers + .iter() + .map(|b| OwnedVertexBuffer { + array_stride: b.array_stride, + step_mode: b.step_mode, + attributes: b.attributes.to_vec(), + }) + .collect(); + let primitive = desc.primitive; + let depth_stencil = desc.depth_stencil.clone(); + let multisample = desc.multisample; + let fragment = desc.fragment.as_ref().map(|f| OwnedFragment { + module: f.module.clone(), + entry_point: f.entry_point.map(str::to_owned), + compilation: OwnedCompilation::new(&f.compilation_options), + targets: f.targets.to_vec(), + }); + let multiview_mask = desc.multiview_mask; + let cache = desc.cache.cloned(); + let name = label.clone().unwrap_or_else(|| "(unlabeled)".to_owned()); + Lazy::from_init( + name, + Box::new(move || { + let vs_constants: Vec<(&str, f64)> = + vs_compilation.constants.iter().map(|(k, v)| (k.as_str(), *v)).collect(); + let vertex_buffers: Vec> = buffers + .iter() + .map(|b| wgpu::VertexBufferLayout { + array_stride: b.array_stride, + step_mode: b.step_mode, + attributes: &b.attributes, + }) + .collect(); + let fs_constants: Vec<(&str, f64)> = fragment + .as_ref() + .map(|f| f.compilation.constants.iter().map(|(k, v)| (k.as_str(), *v)).collect()) + .unwrap_or_default(); + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: label.as_deref(), + layout: layout.as_ref(), + vertex: wgpu::VertexState { + module: &vs_module, + entry_point: vs_entry.as_deref(), + compilation_options: wgpu::PipelineCompilationOptions { + constants: &vs_constants, + zero_initialize_workgroup_memory: vs_compilation.zero_initialize_workgroup_memory, + }, + buffers: &vertex_buffers, + }, + primitive, + depth_stencil, + multisample, + fragment: fragment.as_ref().map(|f| wgpu::FragmentState { + module: &f.module, + entry_point: f.entry_point.as_deref(), + compilation_options: wgpu::PipelineCompilationOptions { + constants: &fs_constants, + zero_initialize_workgroup_memory: f.compilation.zero_initialize_workgroup_memory, + }, + targets: &f.targets, + }), + multiview_mask, + cache: cache.as_ref(), + }) + }), + ) + } +} + +impl LazyComputePipeline { + /// Records `desc` and compiles it on first use (see the module docs). + pub fn new(device: &wgpu::Device, desc: &wgpu::ComputePipelineDescriptor<'_>) -> Self { + let device = device.clone(); + let label = desc.label.map(str::to_owned); + let layout = desc.layout.cloned(); + let module = desc.module.clone(); + let entry_point = desc.entry_point.map(str::to_owned); + let compilation = OwnedCompilation::new(&desc.compilation_options); + let cache = desc.cache.cloned(); + let name = label.clone().unwrap_or_else(|| "(unlabeled)".to_owned()); + Lazy::from_init( + name, + Box::new(move || { + let constants: Vec<(&str, f64)> = + compilation.constants.iter().map(|(k, v)| (k.as_str(), *v)).collect(); + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: label.as_deref(), + layout: layout.as_ref(), + module: &module, + entry_point: entry_point.as_deref(), + compilation_options: wgpu::PipelineCompilationOptions { + constants: &constants, + zero_initialize_workgroup_memory: compilation.zero_initialize_workgroup_memory, + }, + cache: cache.as_ref(), + }) + }), + ) + } +} + +// ------------------------------------------------------------ prewarming + +/// Something `prewarm` can build: a lazy pipeline of either kind. +pub trait Warm { + fn build(&self); + fn is_built(&self) -> bool; +} + +impl

Warm for Lazy

{ + fn build(&self) { + let _ = self.get(); + } + fn is_built(&self) -> bool { + Lazy::is_built(self) + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub type WarmHandle = Arc; +#[cfg(target_arch = "wasm32")] +pub type WarmHandle = Arc; + +#[cfg(not(target_arch = "wasm32"))] +impl Lazy

{ + pub fn warm_handle(&self) -> WarmHandle { + Arc::new(self.clone()) + } +} + +#[cfg(target_arch = "wasm32")] +impl Lazy

{ + pub fn warm_handle(&self) -> WarmHandle { + Arc::new(self.clone()) + } +} + +/// Compile these pipelines in parallel on background threads (a few at a +/// time: the GPU driver compiles in its own processes). Returns at once. +/// On the web this does nothing; pipelines build on first use there. +#[cfg(not(target_arch = "wasm32"))] +pub fn prewarm(pipelines: Vec) { + use std::collections::VecDeque; + let queue: VecDeque = pipelines.into_iter().filter(|p| !p.is_built()).collect(); + if queue.is_empty() { + return; + } + let workers = std::thread::available_parallelism() + .map(|n| n.get()) + .unwrap_or(4) + .clamp(1, 8) + .min(queue.len()); + let queue = Arc::new(Mutex::new(queue)); + for _ in 0..workers { + let queue = queue.clone(); + let spawned = std::thread::Builder::new() + .name("bloom-pipeline-warm".to_owned()) + .spawn(move || loop { + let next = queue.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); + match next { + Some(p) => p.build(), + None => break, + } + }); + // no thread: the pipelines build on first use instead + if spawned.is_err() { + break; + } + } +} + +#[cfg(target_arch = "wasm32")] +pub fn prewarm(_pipelines: Vec) {} + +// ------------------------------------------------------------ what a frame needs + +impl super::Renderer { + /// Starts compiling, in the background, the pipelines the current + /// settings draw with, whenever those settings change (the first frame, + /// a quality preset, a feature toggled at runtime). Called at the start + /// of each frame; cheap when nothing changed. + /// + /// The conditions mirror the frame code (measured per quality preset with + /// a pipeline-use trace). If they drift, a frame compiles what it misses + /// on first use: slower, never wrong. + pub(super) fn prewarm_pipelines(&mut self, scene_3d: bool) { + // the previous frame queued GPU-driven draws (meshes that qualify: not + // skinned-compat, blended, refractive or layered); the first such frame + // starts these, later ones find them built + let gpu_driven_draws = scene_3d && self.gpu_driven.enabled() && !self.gpu_driven.draw_scratch.is_empty(); + let upscale = self.render_scale < 0.999 && !self.taa_enabled; + let flags = [ + scene_3d, + gpu_driven_draws, + self.shadow_map.enabled, + self.taa_enabled, + self.ssao_enabled, + self.bloom_enabled, + self.auto_exposure, + self.cas_strength > 0.0, + upscale, + self.ssr_enabled, + self.ssgi_enabled, + self.dof_enabled, + self.motion_blur_enabled, + self.sss_enabled, + self.pt_mode > 0, + ]; + let signature = flags.iter().enumerate().fold(0u64, |acc, (i, on)| acc | ((*on as u64) << i)); + if signature == self.prewarm_signature { + return; + } + self.prewarm_signature = signature; + + let mut wanted: Vec = vec![self.pipeline_2d.warm_handle()]; + if scene_3d { + wanted.extend([ + self.scene_depth_pipeline.warm_handle(), + self.scene_pipeline_prepassed.warm_handle(), + self.scene_pipeline.warm_handle(), + self.scene_compose_pipeline.warm_handle(), + self.composite_pipeline.warm_handle(), + ]); + if let Some(froxel) = &self.froxel { + wanted.push(froxel.assign_pipeline.warm_handle()); + } + if self.shadow_map.enabled { + wanted.push(self.shadow_map.pipeline.warm_handle()); + wanted.push(self.shadow_map.pipeline_skinned.warm_handle()); + } + if gpu_driven_draws { + wanted.extend(self.gpu_driven.warm_handles()); + } + if self.taa_enabled { + wanted.push(self.taa_pipeline.warm_handle()); + } + if upscale { + wanted.push(self.upscale_pipeline.warm_handle()); + } + if self.ssao_enabled { + // SSAO reads the Hi-Z pyramid, which the occlusion culler reduces too + wanted.extend([ + self.hiz_linearize_pipeline.warm_handle(), + self.hiz_downsample_pipeline.warm_handle(), + self.ssao_pipeline.warm_handle(), + self.ssao_blur_pipeline.warm_handle(), + self.occlusion.warm_handle(), + ]); + } + if self.bloom_enabled { + wanted.extend([ + self.bloom_pipeline_threshold_downsample.warm_handle(), + self.bloom_pipeline_downsample.warm_handle(), + self.bloom_pipeline_upsample.warm_handle(), + ]); + } + if self.auto_exposure { + wanted.push(self.exposure_pipeline.warm_handle()); + } + if self.cas_strength > 0.0 { + wanted.push(self.cas_pipeline.warm_handle()); + } + if self.ssr_enabled { + wanted.push(self.ssr_pipeline.warm_handle()); + wanted.push(self.ssr_temporal_pipeline.warm_handle()); + } + if self.ssgi_enabled { + wanted.extend([ + self.probe_place_pipeline.warm_handle(), + self.probe_temporal_pipeline.warm_handle(), + self.probe_spatial_pipeline.warm_handle(), + self.probe_resolve_pipeline.warm_handle(), + self.card_capture_pipeline.warm_handle(), + ]); + // hardware ray queries where the device has them, else the SDF tracers + match &self.probe_trace_hw_pipeline { + Some(hw) => wanted.push(hw.warm_handle()), + None => wanted.push(self.probe_trace_pipeline.warm_handle()), + } + match &self.card_light_hw_pipeline { + Some(hw) => wanted.push(hw.warm_handle()), + None => wanted.push(self.card_light_pipeline.warm_handle()), + } + match &self.wsrc_bake_hw_pipeline { + Some(hw) => wanted.push(hw.warm_handle()), + None => wanted.push(self.wsrc_bake_pipeline.warm_handle()), + } + } + if self.dof_enabled { + wanted.push(self.dof_pipeline.warm_handle()); + } + if self.motion_blur_enabled { + wanted.push(self.motion_blur_pipeline.warm_handle()); + } + if self.sss_enabled { + wanted.push(self.sss_pipeline.warm_handle()); + } + if self.pt_mode > 0 { + wanted.extend( + [&self.pt_pipeline, &self.pt_atrous_mid_pipeline, &self.pt_atrous_final_pipeline] + .into_iter() + .flatten() + .map(|p| p.warm_handle()), + ); + } + } + prewarm(wanted); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn counting(label: &str, counter: Arc) -> Lazy { + Lazy::from_init( + label.to_owned(), + Box::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + 7 + }), + ) + } + + #[test] + fn builds_once_on_first_use() { + let n = Arc::new(AtomicUsize::new(0)); + let p = counting("p", n.clone()); + assert!(!p.is_built()); + assert_eq!(n.load(Ordering::SeqCst), 0, "creating a lazy pipeline must not build it"); + assert_eq!(*p, 7); + let q = p.clone(); + assert_eq!(*q, 7); + assert_eq!(n.load(Ordering::SeqCst), 1); + assert!(q.is_built()); + } + + #[test] + fn ready_is_built() { + assert!(Lazy::ready(3u32).is_built()); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn prewarm_builds_in_background_and_first_use_waits() { + let n = Arc::new(AtomicUsize::new(0)); + let slow: Lazy = { + let n = n.clone(); + Lazy::from_init( + "slow".to_owned(), + Box::new(move || { + std::thread::sleep(std::time::Duration::from_millis(50)); + n.fetch_add(1, Ordering::SeqCst); + 9 + }), + ) + }; + let others: Vec> = (0..6).map(|i| counting(&format!("p{i}"), n.clone())).collect(); + let mut handles = vec![slow.warm_handle()]; + handles.extend(others.iter().map(|p| p.warm_handle())); + prewarm(handles); + // racing the warm thread: either way it is built exactly once + assert_eq!(*slow, 9); + for p in &others { + assert_eq!(**p, 7); + } + assert_eq!(n.load(Ordering::SeqCst), 7); + } +} diff --git a/native/shared/src/renderer/mod.rs b/native/shared/src/renderer/mod.rs index 1ff4c236..7aea22c1 100644 --- a/native/shared/src/renderer/mod.rs +++ b/native/shared/src/renderer/mod.rs @@ -70,6 +70,7 @@ mod gi_bake; mod glsl_render_target; pub mod gpu_driven; mod hiz; +pub(crate) mod lazy_pipeline; mod immediate_draw3d; mod immediate_motion; mod layered_pbr; @@ -155,7 +156,10 @@ pub use util::{ }; mod brdf_lut; -use brdf_lut::build_brdf_lut; +use lazy_pipeline::{LazyComputePipeline, LazyRenderPipeline}; + +/// The split-sum BRDF table, generated at build time (build.rs). +const BRDF_LUT_BAKED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/brdf_lut.bin")); mod atmosphere_lut; pub mod capabilities; pub mod device_negotiation; @@ -507,8 +511,8 @@ pub struct Renderer { pub logical_width: u32, pub logical_height: u32, - pipeline_2d: wgpu::RenderPipeline, - pipeline_3d: wgpu::RenderPipeline, + pipeline_2d: LazyRenderPipeline, + pipeline_3d: LazyRenderPipeline, custom_pipelines: Vec, // 2D uniforms (multiple slots for mode switching) @@ -592,7 +596,7 @@ pub struct Renderer { /// TAA-off source) so atmospherics stay consistent across paths. pub composed_rt_texture: wgpu::Texture, pub composed_rt_view: wgpu::TextureView, - pub scene_compose_pipeline: wgpu::RenderPipeline, + pub scene_compose_pipeline: LazyRenderPipeline, pub scene_compose_layout: wgpu::BindGroupLayout, pub scene_compose_uniform_buffer: wgpu::Buffer, scene_compose_bind_group_cache: @@ -602,7 +606,7 @@ pub struct Renderer { /// linear-rgb (sRGB hardware encode handles the transfer fn). /// Now also samples bloom_chain[0] and additively merges before /// the tonemap. - pub composite_pipeline: wgpu::RenderPipeline, + pub composite_pipeline: LazyRenderPipeline, pub composite_layout: wgpu::BindGroupLayout, pub composite_sampler: wgpu::Sampler, composite_bind_group_cache: [Option; postfx_chain::CompositeSource::COUNT * 2], @@ -645,7 +649,7 @@ pub struct Renderer { pub exposure_history_valid: bool, /// Per-frame producer bit; only written exposure may advance ping-pong. exposure_history_written: bool, - pub exposure_pipeline: wgpu::RenderPipeline, + pub exposure_pipeline: LazyRenderPipeline, pub exposure_layout: wgpu::BindGroupLayout, pub exposure_uniform_buffer: wgpu::Buffer, exposure_bind_group_cache: [Option; postfx_chain::CompositeSource::COUNT * 2], @@ -659,9 +663,9 @@ pub struct Renderer { pub bloom_chain_textures: Vec, pub bloom_mip_views: Vec, pub bloom_full_view: wgpu::TextureView, - pub bloom_pipeline_threshold_downsample: wgpu::RenderPipeline, - pub bloom_pipeline_downsample: wgpu::RenderPipeline, - pub bloom_pipeline_upsample: wgpu::RenderPipeline, + pub bloom_pipeline_threshold_downsample: LazyRenderPipeline, + pub bloom_pipeline_downsample: LazyRenderPipeline, + pub bloom_pipeline_upsample: LazyRenderPipeline, pub bloom_layout: wgpu::BindGroupLayout, /// One stable uniform buffer and bind group per bloom pass. Keeping /// these persistent avoids allocating Metal buffers/argument tables on @@ -688,7 +692,7 @@ pub struct Renderer { /// crevices. pub ssao_rt_texture: wgpu::Texture, pub ssao_rt_view: wgpu::TextureView, - pub ssao_pipeline: wgpu::ComputePipeline, + pub ssao_pipeline: LazyComputePipeline, pub ssao_layout: wgpu::BindGroupLayout, pub ssao_uniform_buffer: wgpu::Buffer, pub ssao_depth_sampler: wgpu::Sampler, @@ -701,10 +705,10 @@ pub struct Renderer { pub hiz_textures: Vec, pub hiz_views: Vec, pub hiz_sampler: wgpu::Sampler, - pub hiz_linearize_pipeline: wgpu::ComputePipeline, + pub hiz_linearize_pipeline: LazyComputePipeline, pub hiz_linearize_layout: wgpu::BindGroupLayout, pub hiz_linearize_uniform_buffer: wgpu::Buffer, - pub hiz_downsample_pipeline: wgpu::ComputePipeline, + pub hiz_downsample_pipeline: LazyComputePipeline, pub hiz_downsample_layout: wgpu::BindGroupLayout, pub hiz_downsample_uniform_buffers: Vec, hiz_linearize_bg_cache: Option, @@ -717,7 +721,7 @@ pub struct Renderer { /// The TAA pass then samples ssao_blur_rt instead of ssao_rt. pub ssao_blur_rt_texture: wgpu::Texture, pub ssao_blur_rt_view: wgpu::TextureView, - pub ssao_blur_pipeline: wgpu::RenderPipeline, + pub ssao_blur_pipeline: LazyRenderPipeline, pub ssao_blur_layout: wgpu::BindGroupLayout, pub ssao_blur_uniform_buffer: wgpu::Buffer, /// Strength multiplier for SSAO (0 = off, 1 = full). Default 1.0. @@ -774,7 +778,7 @@ pub struct Renderer { pub taa_depth_history_textures: [wgpu::Texture; 2], pub taa_depth_history_views: [wgpu::TextureView; 2], pub taa_current_idx: usize, - pub taa_pipeline: wgpu::RenderPipeline, + pub taa_pipeline: LazyRenderPipeline, pub taa_layout: wgpu::BindGroupLayout, pub taa_uniform_buffer: wgpu::Buffer, taa_bind_group_cache: [Option; 2], @@ -889,7 +893,7 @@ pub struct Renderer { /// Half-res HDR SSR output, composited into the final image by TAA. pub ssr_rt_texture: wgpu::Texture, pub ssr_rt_view: wgpu::TextureView, - pub ssr_pipeline: wgpu::RenderPipeline, + pub ssr_pipeline: LazyRenderPipeline, pub ssr_layout: wgpu::BindGroupLayout, pub ssr_uniform_buffer: wgpu::Buffer, /// SSR strength (0 = off, 1 = full). The conservative 0.5 default avoids @@ -906,7 +910,7 @@ pub struct Renderer { /// False after resize, feature/mode transitions, or parameter changes. /// The next temporal pass then replaces history instead of blending it. pub ssr_history_valid: bool, - pub ssr_temporal_pipeline: wgpu::RenderPipeline, + pub ssr_temporal_pipeline: LazyRenderPipeline, pub ssr_temporal_layout: wgpu::BindGroupLayout, pub ssr_temporal_uniform_buffer: wgpu::Buffer, ssr_temporal_bind_group_cache: [Option; 2], @@ -1002,12 +1006,12 @@ pub struct Renderer { /// glass/card metadata. tlas_instance_data_count: u32, - pub probe_place_pipeline: wgpu::ComputePipeline, + pub probe_place_pipeline: LazyComputePipeline, pub probe_place_layout: wgpu::BindGroupLayout, pub probe_place_uniform: wgpu::Buffer, probe_place_bg_cache: Option, - pub probe_trace_pipeline: wgpu::ComputePipeline, + pub probe_trace_pipeline: LazyComputePipeline, pub probe_trace_layout: wgpu::BindGroupLayout, pub probe_trace_uniform: wgpu::Buffer, probe_trace_bg_cache: [Option; 2], @@ -1016,7 +1020,7 @@ pub struct Renderer { /// (includes the TLAS + instance_data buffer bindings that the SW /// layout doesn't carry). `Some` only when `hw_rt_enabled`; `None` /// otherwise so the shader module isn't even compiled. - pub probe_trace_hw_pipeline: Option, + pub probe_trace_hw_pipeline: Option, /// Lazily compiled specialization. It is absent until an SSGI frame /// actually contains imported physical transmission. pub probe_trace_hw_transparent_pipeline: Option, @@ -1027,7 +1031,7 @@ pub struct Renderer { probe_trace_hw_bg_cache: [Option; 2], // --- Path tracing (PT-1, docs/pt/pt-roadmap.md) --- /// Base megakernel; None when the adapter lacks ray query. - pub pt_pipeline: Option, + pub pt_pipeline: Option, pub pt_layout: Option, /// Lazy group-2 specialization. Base-only PT never creates or binds it. pt_layered: layered_pbr_pt::PtLayeredRuntimeState, @@ -1082,8 +1086,8 @@ pub struct Renderer { /// PT-3b — SVGF wavelet filter (realtime mode): four à-trous /// iterations (steps 1/2/4/8) on the trace grid, then a full-res /// upsample+modulate pass. - pt_atrous_mid_pipeline: Option, - pt_atrous_final_pipeline: Option, + pt_atrous_mid_pipeline: Option, + pt_atrous_final_pipeline: Option, pt_atrous_layout: Option, /// Per-iteration uniform (step size + first-iteration flag + extent). pt_atrous_params_bufs: [wgpu::Buffer; 6], @@ -1106,7 +1110,7 @@ pub struct Renderer { /// Ticket 014 V3 — SW SDF sphere-trace pipeline + layout. /// Active whenever the scene clipmap has been baked; chosen at /// dispatch time over the Hi-Z SW fallback when available. - pub probe_trace_sdf_pipeline: wgpu::ComputePipeline, + pub probe_trace_sdf_pipeline: LazyComputePipeline, /// SW counterpart of `probe_trace_hw_transparent_pipeline`. pub probe_trace_sdf_transparent_pipeline: Option, pub probe_trace_sdf_layout: wgpu::BindGroupLayout, @@ -1131,7 +1135,7 @@ pub struct Renderer { /// captures land; consumed by the card-lighting pass for NdotL. pub card_slot_meta_buffer: wgpu::Buffer, - pub card_capture_pipeline: wgpu::RenderPipeline, + pub card_capture_pipeline: LazyRenderPipeline, pub card_capture_uniform_layout: wgpu::BindGroupLayout, pub card_capture_texture_layout: wgpu::BindGroupLayout, pub card_capture_uniform: wgpu::Buffer, @@ -1146,10 +1150,10 @@ pub struct Renderer { pub card_capture_fallback_tex: wgpu::Texture, pub card_capture_fallback_view: wgpu::TextureView, - pub card_light_pipeline: wgpu::ComputePipeline, + pub card_light_pipeline: LazyComputePipeline, pub card_light_layout: wgpu::BindGroupLayout, /// RT-capable coherent relight; absent on adapters without ray queries. - card_light_hw_pipeline: Option, + card_light_hw_pipeline: Option, card_light_hw_layout: Option, pub card_light_uniform: wgpu::Buffer, card_light_bg_cache: Option, @@ -1171,7 +1175,7 @@ pub struct Renderer { card_content_version: u64, // --- Ticket 014: per-mesh UDF bake --- - pub sdf_bake_pipeline: wgpu::ComputePipeline, + pub sdf_bake_pipeline: LazyComputePipeline, pub sdf_bake_layout: wgpu::BindGroupLayout, pub sdf_bake_uniform: wgpu::Buffer, /// Ticket 022 — staging buffers awaiting readback so freshly-baked @@ -1200,7 +1204,7 @@ pub struct Renderer { /// Fullscreen-lag fix — dedicated binned+sliced clipmap bake /// pipeline (the per-mesh `sdf_bake_pipeline` stays brute-force; /// its 32³ per-mesh volumes are already rate-limited). - sdf_clipmap_bake_pipeline: wgpu::ComputePipeline, + sdf_clipmap_bake_pipeline: LazyComputePipeline, sdf_clipmap_bake_layout: wgpu::BindGroupLayout, scene_sdf_clipmap_staging_tex: wgpu::Texture, scene_sdf_clipmap_staging_view: wgpu::TextureView, @@ -1217,7 +1221,7 @@ pub struct Renderer { /// to the baked borders so the miss-path lookup stays well- /// defined at probe seams. pub wsrc_atlas_sampler: wgpu::Sampler, - pub wsrc_bake_pipeline: wgpu::ComputePipeline, + pub wsrc_bake_pipeline: LazyComputePipeline, pub wsrc_bake_layout: wgpu::BindGroupLayout, pub wsrc_bake_uniform: wgpu::Buffer, wsrc_bake_bg_cache: Option, @@ -1226,7 +1230,7 @@ pub struct Renderer { /// bake; extra bindings carry the TLAS + per-instance GI data /// + card atlas so probe-octel rays can sample pre-lit Mesh /// Cards radiance at hit points. - pub wsrc_bake_hw_pipeline: Option, + pub wsrc_bake_hw_pipeline: Option, /// Lazy one-layer transmission specialization of the HW WSRC bake. pub wsrc_bake_hw_transparent_pipeline: Option, pub wsrc_bake_hw_layout: Option, @@ -1247,13 +1251,13 @@ pub struct Renderer { pub wsrc_last_sun_color: [[f32; 3]; 3], pub wsrc_last_sky_color: [[f32; 3]; 3], - pub probe_temporal_pipeline: wgpu::ComputePipeline, - pub probe_spatial_pipeline: wgpu::ComputePipeline, + pub probe_temporal_pipeline: LazyComputePipeline, + pub probe_spatial_pipeline: LazyComputePipeline, pub probe_temporal_layout: wgpu::BindGroupLayout, pub probe_temporal_uniform: wgpu::Buffer, probe_temporal_bg_cache: [Option; 2], - pub probe_resolve_pipeline: wgpu::RenderPipeline, + pub probe_resolve_pipeline: LazyRenderPipeline, pub probe_resolve_layout: wgpu::BindGroupLayout, pub probe_resolve_uniform: wgpu::Buffer, probe_resolve_bg_cache: [Option; 2], @@ -1263,7 +1267,7 @@ pub struct Renderer { /// here. Composite reads this instead of TAA when DoF is on. pub dof_rt_texture: wgpu::Texture, pub dof_rt_view: wgpu::TextureView, - pub dof_pipeline: wgpu::RenderPipeline, + pub dof_pipeline: LazyRenderPipeline, pub dof_layout: wgpu::BindGroupLayout, pub dof_uniform_buffer: wgpu::Buffer, dof_bind_group_cache: [Option; postfx_chain::PostFxSource::COUNT], @@ -1292,7 +1296,7 @@ pub struct Renderer { /// when motion blur is enabled. pub motion_blur_rt_texture: wgpu::Texture, pub motion_blur_rt_view: wgpu::TextureView, - pub motion_blur_pipeline: wgpu::RenderPipeline, + pub motion_blur_pipeline: LazyRenderPipeline, pub motion_blur_layout: wgpu::BindGroupLayout, pub motion_blur_uniform_buffer: wgpu::Buffer, motion_blur_bind_group_cache: [Option; postfx_chain::PostFxSource::COUNT], @@ -1311,7 +1315,7 @@ pub struct Renderer { /// instead of the upstream source when SSS is on. pub sss_rt_texture: wgpu::Texture, pub sss_rt_view: wgpu::TextureView, - pub sss_pipeline: wgpu::RenderPipeline, + pub sss_pipeline: LazyRenderPipeline, pub sss_layout: wgpu::BindGroupLayout, pub sss_uniform_buffer: wgpu::Buffer, sss_bind_group_cache: [Option; postfx_chain::PostFxSource::COUNT], @@ -1330,7 +1334,7 @@ pub struct Renderer { /// pass handles upscaling itself and this pass is skipped. pub upscale_rt_texture: wgpu::Texture, pub upscale_rt_view: wgpu::TextureView, - pub upscale_pipeline: wgpu::RenderPipeline, + pub upscale_pipeline: LazyRenderPipeline, pub upscale_layout: wgpu::BindGroupLayout, pub upscale_uniform_buffer: wgpu::Buffer, upscale_bind_group_cache: Option, @@ -1345,7 +1349,7 @@ pub struct Renderer { /// then consumes. pub cas_rt_texture: wgpu::Texture, pub cas_rt_view: wgpu::TextureView, - pub cas_pipeline: wgpu::RenderPipeline, + pub cas_pipeline: LazyRenderPipeline, pub cas_layout: wgpu::BindGroupLayout, pub cas_uniform_buffer: wgpu::Buffer, cas_bind_group_cache: [Option; postfx_chain::PostFxSource::COUNT], @@ -1524,7 +1528,7 @@ pub struct Renderer { sky_texture: Option, sky_bind_group: Option, sky_uniform_buffer: wgpu::Buffer, - sky_pipeline: wgpu::RenderPipeline, + sky_pipeline: LazyRenderPipeline, sky_bind_group_layout: wgpu::BindGroupLayout, sky_sampler: wgpu::Sampler, @@ -1542,11 +1546,11 @@ pub struct Renderer { sky_view_dirty: bool, _sky_view_lut_texture: wgpu::Texture, _sky_view_lut_view: wgpu::TextureView, - sky_view_compute_pipeline: wgpu::ComputePipeline, + sky_view_compute_pipeline: LazyComputePipeline, _sky_view_compute_bgl: wgpu::BindGroupLayout, sky_view_uniform_buffer: wgpu::Buffer, sky_view_compute_bind_group: wgpu::BindGroup, - procedural_sky_pipeline: wgpu::RenderPipeline, + procedural_sky_pipeline: LazyRenderPipeline, _procedural_sky_bgl: wgpu::BindGroupLayout, procedural_sun_uniform_buffer: wgpu::Buffer, procedural_sky_bind_group: wgpu::BindGroup, @@ -1558,7 +1562,7 @@ pub struct Renderer { // `bake_procedural_ibl`. Mip 0 holds the un-prefiltered sky // (sampled by anything that wants raw radiance); mips 1..N are // GGX-roughness-stratified for split-sum specular IBL. - procedural_ibl_pipeline: wgpu::RenderPipeline, + procedural_ibl_pipeline: LazyRenderPipeline, _procedural_ibl_bgl: wgpu::BindGroupLayout, procedural_ibl_uniform_buffer: wgpu::Buffer, procedural_ibl_bind_group: wgpu::BindGroup, @@ -1580,7 +1584,7 @@ pub struct Renderer { // frame (camera moves) when procedural sky is active. Replaces // scene_compose's 16-step volumetric fog march with a single // 3D-tex sample per fragment. - aerial_perspective_pipeline: wgpu::ComputePipeline, + aerial_perspective_pipeline: LazyComputePipeline, _aerial_perspective_bgl: wgpu::BindGroupLayout, aerial_perspective_uniform_buffer: wgpu::Buffer, aerial_perspective_bind_group: wgpu::BindGroup, @@ -1598,9 +1602,11 @@ pub struct Renderer { // Scene pipeline (retained scene graph rendering with normal // mapping). Distinct from pipeline_3d so immediate-mode draws // don't have to carry tangent vertex data or normal-map bindings. - pub scene_pipeline: wgpu::RenderPipeline, - scene_transparent_pipeline: wgpu::RenderPipeline, - scene_transparent_double_sided_pipeline: wgpu::RenderPipeline, + pub scene_pipeline: LazyRenderPipeline, + /// The settings the pipelines were last prewarmed for (lazy_pipeline.rs). + prewarm_signature: u64, + scene_transparent_pipeline: LazyRenderPipeline, + scene_transparent_double_sided_pipeline: LazyRenderPipeline, scene_transparent_reactive_pipeline: Option, scene_transparent_reactive_double_sided_pipeline: Option, scene_weighted_transparent_pipeline: Option, @@ -1636,13 +1642,13 @@ pub struct Renderer { scene_refractive_reflection_params_buffer: Option, refractive_reflections_active: bool, /// EN-044 — depth-only prepass over the same cached-model draws. - pub scene_depth_pipeline: wgpu::RenderPipeline, + pub scene_depth_pipeline: LazyRenderPipeline, /// Shade-mode depth-only variant whose inert color slot makes it /// compatible with the inline packed visibility attachment. #[cfg(not(target_arch = "wasm32"))] - scene_depth_visibility_pipeline: Option, + scene_depth_visibility_pipeline: Option, /// EN-044 — cached-model pipeline for the prepassed path (no depth write, Equal). - pub scene_pipeline_prepassed: wgpu::RenderPipeline, + pub scene_pipeline_prepassed: LazyRenderPipeline, pub scene_material_layout: wgpu::BindGroupLayout, scene_sheen_albedo_lut: Option, scene_layered_pbr_resources: Option, @@ -1687,11 +1693,11 @@ pub struct Renderer { /// GGX prefilter pipeline. Run once per env load to convolve the /// HDR env into roughness-weighted mips, replacing the box filter /// stand-in. Matches Karis 2013's split-sum specular prefilter. - pub prefilter_pipeline: wgpu::RenderPipeline, + pub prefilter_pipeline: LazyRenderPipeline, /// Diffuse irradiance prefilter pipeline (cosine-weighted env /// convolution). Run on the smallest mip so the scene shader's /// diffuse IBL sample is properly Lambertian, not GGX-with-rough. - pub prefilter_diffuse_pipeline: wgpu::RenderPipeline, + pub prefilter_diffuse_pipeline: LazyRenderPipeline, pub prefilter_layout: wgpu::BindGroupLayout, pub prefilter_uniform_buffer: wgpu::Buffer, /// Default flat-normal (tangent-space +Z) 1x1 texture view — used @@ -2238,8 +2244,9 @@ impl Renderer { // matching Karis 2013 ('Real Shading in UE4'). 1024 samples // per cell × 65536 cells ≈ 67M ops — runs in well under a // second on a modern CPU. - let brdf_lut_size: u32 = 256; - let brdf_lut_pixels = build_brdf_lut(brdf_lut_size as usize); + // generated by build.rs (brdf_lut.rs): Rg16Float texels, little-endian + let brdf_lut_size = brdf_lut::BRDF_LUT_SIZE as u32; + let brdf_lut_bytes: &[u8] = BRDF_LUT_BAKED; let brdf_lut_texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("brdf_lut"), size: wgpu::Extent3d { @@ -2261,7 +2268,7 @@ impl Renderer { origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All, }, - bytemuck::cast_slice(&brdf_lut_pixels), + brdf_lut_bytes, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(brdf_lut_size * 4), // 2 channels × 2 bytes @@ -2585,7 +2592,7 @@ impl Renderer { immediate_size: 0, }); - let pipeline_2d = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let pipeline_2d = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("pipeline_2d"), layout: Some(&pipeline_layout_2d), vertex: wgpu::VertexState { @@ -2689,7 +2696,7 @@ impl Renderer { immediate_size: 0, }); - let pipeline_3d = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let pipeline_3d = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("pipeline_3d"), layout: Some(&pipeline_layout_3d), vertex: wgpu::VertexState { @@ -2852,7 +2859,7 @@ impl Renderer { bind_group_layouts: &[Some(&sky_bind_group_layout)], immediate_size: 0, }); - let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let sky_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("sky_pipeline"), layout: Some(&sky_pipeline_layout), vertex: wgpu::VertexState { @@ -3026,7 +3033,7 @@ impl Renderer { immediate_size: 0, }); let sky_view_compute_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("sky_view_compute_pipeline"), layout: Some(&sky_view_compute_pl_layout), module: &sky_view_compute_shader, @@ -3137,7 +3144,7 @@ impl Renderer { immediate_size: 0, }); let procedural_sky_pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("procedural_sky_pipeline"), layout: Some(&procedural_sky_pl_layout), vertex: wgpu::VertexState { @@ -3348,7 +3355,7 @@ impl Renderer { immediate_size: 0, }); let procedural_ibl_pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("procedural_ibl_pipeline"), layout: Some(&procedural_ibl_pl_layout), vertex: wgpu::VertexState { @@ -3551,7 +3558,7 @@ impl Renderer { bind_group_layouts: &[Some(&prefilter_layout)], immediate_size: 0, }); - let prefilter_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let prefilter_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("prefilter_pipeline"), layout: Some(&prefilter_pl_layout), vertex: wgpu::VertexState { @@ -3596,7 +3603,7 @@ impl Renderer { // bind group layout (so we don't need to rebuild bind groups // when switching pipelines mid-encoder). let prefilter_diffuse_pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("prefilter_diffuse_pipeline"), layout: Some(&prefilter_pl_layout), vertex: wgpu::VertexState { @@ -3763,7 +3770,7 @@ impl Renderer { immediate_size: 0, }); let aerial_perspective_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("aerial_perspective_pipeline"), layout: Some(&aerial_perspective_pl_layout), module: &aerial_perspective_shader, @@ -3809,7 +3816,7 @@ impl Renderer { ], immediate_size: 0, }); - let scene_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let scene_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("scene_pipeline"), layout: Some(&scene_pipeline_layout), vertex: wgpu::VertexState { @@ -3887,7 +3894,7 @@ impl Renderer { let create_scene_transparent_pipeline = |label: &'static str, cull_mode: Option| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(&scene_pipeline_layout), vertex: wgpu::VertexState { @@ -3962,7 +3969,7 @@ impl Renderer { // scene_pipeline (Less, write) stays for the retained scene-graph nodes, // which are not in the prepass. let scene_pipeline_prepassed = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("scene_pipeline_prepassed"), layout: Some(&scene_pipeline_layout), vertex: wgpu::VertexState { @@ -4163,7 +4170,7 @@ impl Renderer { bind_group_layouts: &[Some(&composite_layout)], immediate_size: 0, }); - let composite_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let composite_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("composite_pipeline"), layout: Some(&composite_pl_layout), vertex: wgpu::VertexState { @@ -4260,8 +4267,8 @@ impl Renderer { // would alias to the last write at submit. let make_bloom_pipeline = - |entry: &str, blend: Option| -> wgpu::RenderPipeline { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + |entry: &str, blend: Option| -> LazyRenderPipeline { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("bloom_pipeline"), layout: Some(&bloom_pl_layout), vertex: wgpu::VertexState { @@ -4364,7 +4371,7 @@ impl Renderer { immediate_size: 0, }); let hiz_linearize_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("hiz_linearize_pipeline"), layout: Some(&hiz_linearize_pl_layout), module: &hiz_linearize_shader, @@ -4425,7 +4432,7 @@ impl Renderer { immediate_size: 0, }); let hiz_downsample_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("hiz_downsample_pipeline"), layout: Some(&hiz_downsample_pl_layout), module: &hiz_downsample_shader, @@ -4588,7 +4595,7 @@ impl Renderer { bind_group_layouts: &[Some(&ssao_layout)], immediate_size: 0, }); - let ssao_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let ssao_pipeline = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("ssao_pipeline"), layout: Some(&ssao_pl_layout), module: &ssao_shader, @@ -4672,7 +4679,7 @@ impl Renderer { bind_group_layouts: &[Some(&ssao_blur_layout)], immediate_size: 0, }); - let ssao_blur_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let ssao_blur_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("ssao_blur_pipeline"), layout: Some(&ssao_blur_pl_layout), vertex: wgpu::VertexState { @@ -4726,7 +4733,7 @@ impl Renderer { bind_group_layouts: &[Some(&taa_layout)], immediate_size: 0, }); - let taa_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let taa_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("taa_pipeline"), layout: Some(&taa_pl_layout), vertex: wgpu::VertexState { @@ -4816,7 +4823,7 @@ impl Renderer { bind_group_layouts: &[Some(&upscale_layout)], immediate_size: 0, }); - let upscale_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let upscale_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("upscale_pipeline"), layout: Some(&upscale_pl_layout), vertex: wgpu::VertexState { @@ -4902,7 +4909,7 @@ impl Renderer { bind_group_layouts: &[Some(&cas_layout)], immediate_size: 0, }); - let cas_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let cas_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("cas_pipeline"), layout: Some(&cas_pl_layout), vertex: wgpu::VertexState { @@ -5050,7 +5057,7 @@ impl Renderer { bind_group_layouts: &[Some(&ssr_layout)], immediate_size: 0, }); - let ssr_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let ssr_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("ssr_pipeline"), layout: Some(&ssr_pl_layout), vertex: wgpu::VertexState { @@ -5181,7 +5188,7 @@ impl Renderer { immediate_size: 0, }); let ssr_temporal_pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("ssr_temporal_pipeline"), layout: Some(&ssr_temporal_pl_layout), vertex: wgpu::VertexState { @@ -5288,7 +5295,7 @@ impl Renderer { immediate_size: 0, }); let probe_place_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("probe_place_pipeline"), layout: Some(&probe_place_pl_layout), module: &probe_place_shader, @@ -5434,7 +5441,7 @@ impl Renderer { immediate_size: 0, }); let probe_trace_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("probe_trace_pipeline"), layout: Some(&probe_trace_pl_layout), module: &probe_trace_shader, @@ -5628,7 +5635,7 @@ impl Renderer { bind_group_layouts: &[Some(&hw_layout)], immediate_size: 0, }); - let hw_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let hw_pipeline = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("probe_trace_hw_pipeline"), layout: Some(&hw_pl_layout), module: &hw_shader, @@ -5941,7 +5948,7 @@ impl Renderer { bind_group_layouts: &pl_groups, immediate_size: 0, }); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let pipeline = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("pt_pipeline"), layout: Some(&pl), module: &pt_shader, @@ -6049,7 +6056,7 @@ impl Renderer { bind_group_layouts: &[Some(&layout)], immediate_size: 0, }); - let mid = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let mid = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("pt_atrous_mid"), layout: Some(&pl), module: &shader, @@ -6057,7 +6064,7 @@ impl Renderer { compilation_options: Default::default(), cache: None, }); - let fin = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let fin = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("pt_atrous_final"), layout: Some(&pl), module: &shader, @@ -6232,7 +6239,7 @@ impl Renderer { immediate_size: 0, }); let probe_trace_sdf_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("probe_trace_sdf_pipeline"), layout: Some(&probe_trace_sdf_pl_layout), module: &sdf_trace_shader, @@ -6316,7 +6323,7 @@ impl Renderer { immediate_size: 0, }); let probe_temporal_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("probe_temporal_pipeline"), layout: Some(&probe_temporal_pl_layout), module: &probe_temporal_shader, @@ -6325,7 +6332,7 @@ impl Renderer { cache: None, }); let probe_spatial_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("probe_spatial_pipeline"), layout: Some(&probe_temporal_pl_layout), module: &probe_temporal_shader, @@ -6425,7 +6432,7 @@ impl Renderer { immediate_size: 0, }); let probe_resolve_pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("probe_resolve_pipeline"), layout: Some(&probe_resolve_pl_layout), vertex: wgpu::VertexState { @@ -6548,7 +6555,7 @@ impl Renderer { immediate_size: 0, }); let card_capture_pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("card_capture_pipeline"), layout: Some(&card_capture_pl_layout), vertex: wgpu::VertexState { @@ -6793,7 +6800,7 @@ impl Renderer { immediate_size: 0, }); let card_light_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("card_light_pipeline"), layout: Some(&card_light_pl_layout), module: &card_light_shader, @@ -6901,7 +6908,7 @@ impl Renderer { bind_group_layouts: &[Some(&layout)], immediate_size: 0, }); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let pipeline = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("card_light_hw_pipeline"), layout: Some(&pipeline_layout), module: &shader, @@ -6969,7 +6976,7 @@ impl Renderer { bind_group_layouts: &[Some(&sdf_bake_layout)], immediate_size: 0, }); - let sdf_bake_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let sdf_bake_pipeline = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("sdf_bake_pipeline"), layout: Some(&sdf_bake_pl_layout), module: &sdf_bake_shader, @@ -7038,7 +7045,7 @@ impl Renderer { immediate_size: 0, }); let sdf_clipmap_bake_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("sdf_clipmap_bake_pipeline"), layout: Some(&sdf_clipmap_bake_pl_layout), module: &sdf_clipmap_bake_shader, @@ -7134,7 +7141,7 @@ impl Renderer { bind_group_layouts: &[Some(&wsrc_bake_layout)], immediate_size: 0, }); - let wsrc_bake_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let wsrc_bake_pipeline = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("wsrc_bake_pipeline"), layout: Some(&wsrc_bake_pl_layout), module: &wsrc_bake_shader, @@ -7275,7 +7282,7 @@ impl Renderer { bind_group_layouts: &[Some(&hw_layout)], immediate_size: 0, }); - let hw_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let hw_pipeline = LazyComputePipeline::new(&device, &wgpu::ComputePipelineDescriptor { label: Some("wsrc_bake_hw_pipeline"), layout: Some(&hw_pl_layout), module: &hw_shader, @@ -7438,7 +7445,7 @@ impl Renderer { immediate_size: 0, }); let scene_compose_pipeline = - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("scene_compose_pipeline"), layout: Some(&scene_compose_pl_layout), vertex: wgpu::VertexState { @@ -7540,7 +7547,7 @@ impl Renderer { bind_group_layouts: &[Some(&dof_layout)], immediate_size: 0, }); - let dof_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let dof_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("dof_pipeline"), layout: Some(&dof_pl_layout), vertex: wgpu::VertexState { @@ -7644,7 +7651,7 @@ impl Renderer { bind_group_layouts: &[Some(&motion_blur_layout)], immediate_size: 0, }); - let motion_blur_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let motion_blur_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("motion_blur_pipeline"), layout: Some(&motion_blur_pl_layout), vertex: wgpu::VertexState { @@ -7746,7 +7753,7 @@ impl Renderer { bind_group_layouts: &[Some(&sss_layout)], immediate_size: 0, }); - let sss_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let sss_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("sss_pipeline"), layout: Some(&sss_pl_layout), vertex: wgpu::VertexState { @@ -7843,7 +7850,7 @@ impl Renderer { bind_group_layouts: &[Some(&exposure_layout)], immediate_size: 0, }); - let exposure_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let exposure_pipeline = LazyRenderPipeline::new(&device, &wgpu::RenderPipelineDescriptor { label: Some("exposure_pipeline"), layout: Some(&exposure_pl_layout), vertex: wgpu::VertexState { @@ -8517,6 +8524,7 @@ impl Renderer { aerial_perspective_sampler, env_diffuse_texture: None, scene_pipeline, + prewarm_signature: u64::MAX, scene_transparent_pipeline, scene_transparent_double_sided_pipeline, scene_transparent_reactive_pipeline: None, @@ -12712,6 +12720,7 @@ impl Renderer { } pub fn end_frame(&mut self) { + self.prewarm_pipelines(false); if !self.material_per_view_bg_live { self.refresh_material_per_view_bg(); } @@ -12968,6 +12977,7 @@ impl Renderer { scene: &mut crate::scene::SceneGraph, profiler: &mut crate::profiler::Profiler, ) { + self.prewarm_pipelines(true); self.has_refractive_scene_nodes = self.imported_refraction_enabled && scene.has_refractive_nodes(); ( diff --git a/native/shared/src/renderer/occlusion.rs b/native/shared/src/renderer/occlusion.rs index 01c290fd..e07e0fd8 100644 --- a/native/shared/src/renderer/occlusion.rs +++ b/native/shared/src/renderer/occlusion.rs @@ -18,6 +18,7 @@ //! `bloom_set_occlusion_culling(0/1)` exposes the kill switch to games; //! default on. +use super::lazy_pipeline::LazyComputePipeline; use wgpu::util::DeviceExt; pub(super) const GRID_W: u32 = 64; @@ -69,7 +70,7 @@ struct Readback { } pub struct OcclusionCuller { - pipeline: wgpu::ComputePipeline, + pipeline: LazyComputePipeline, layout: wgpu::BindGroupLayout, uniform: wgpu::Buffer, grid_tex: wgpu::Texture, @@ -94,6 +95,13 @@ pub struct OcclusionCuller { recorded_this_frame: bool, } +impl OcclusionCuller { + /// The reduce pipeline, for `Renderer::prewarm_pipelines`. + pub(crate) fn warm_handle(&self) -> super::lazy_pipeline::WarmHandle { + self.pipeline.warm_handle() + } +} + impl OcclusionCuller { pub fn new(device: &wgpu::Device) -> Self { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { @@ -140,7 +148,7 @@ impl OcclusionCuller { bind_group_layouts: &[Some(&layout)], ..Default::default() }); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + let pipeline = LazyComputePipeline::new(device, &wgpu::ComputePipelineDescriptor { label: Some("occlusion_reduce_pipeline"), layout: Some(&pl), module: &shader, diff --git a/native/shared/src/renderer/scene_pass.rs b/native/shared/src/renderer/scene_pass.rs index 2b8722d0..639eaec6 100644 --- a/native/shared/src/renderer/scene_pass.rs +++ b/native/shared/src/renderer/scene_pass.rs @@ -13,14 +13,14 @@ pub(super) fn create_scene_depth_pipeline( shader: &wgpu::ShaderModule, label: &'static str, visibility_target: bool, -) -> wgpu::RenderPipeline { +) -> super::lazy_pipeline::LazyRenderPipeline { let targets = [visibility_target.then_some(wgpu::ColorTargetState { format: visibility_buffer::VISIBILITY_FORMAT, blend: None, // Cached-model depth draws do not own packed visibility IDs. write_mask: wgpu::ColorWrites::empty(), })]; - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + super::lazy_pipeline::LazyRenderPipeline::new(device, &wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(layout), vertex: wgpu::VertexState { diff --git a/native/shared/src/renderer/sorted_transparency.rs b/native/shared/src/renderer/sorted_transparency.rs index 5e118d33..4b1be79f 100644 --- a/native/shared/src/renderer/sorted_transparency.rs +++ b/native/shared/src/renderer/sorted_transparency.rs @@ -281,8 +281,8 @@ impl Renderer { ) } else { ( - &self.scene_transparent_pipeline, - &self.scene_transparent_double_sided_pipeline, + self.scene_transparent_pipeline.get(), + self.scene_transparent_double_sided_pipeline.get(), ) }; pass.set_bind_group(1, &self.lighting_bind_group, &[]); @@ -354,8 +354,8 @@ impl Renderer { ) } else { ( - &self.scene_transparent_pipeline, - &self.scene_transparent_double_sided_pipeline, + self.scene_transparent_pipeline.get(), + self.scene_transparent_double_sided_pipeline.get(), ) }; let mut current_pipeline = None; diff --git a/native/shared/src/renderer/ssr_pass.rs b/native/shared/src/renderer/ssr_pass.rs index f316bfc9..775ade84 100644 --- a/native/shared/src/renderer/ssr_pass.rs +++ b/native/shared/src/renderer/ssr_pass.rs @@ -193,7 +193,7 @@ impl Renderer { ) } else { ( - &self.ssr_pipeline, + self.ssr_pipeline.get(), self.ssr_bg_cache .as_ref() .expect("base SSR bind group initialized"), diff --git a/native/shared/src/shadows.rs b/native/shared/src/shadows.rs index af896b88..fc13c065 100644 --- a/native/shared/src/shadows.rs +++ b/native/shared/src/shadows.rs @@ -7,6 +7,7 @@ //! for each fragment, giving high shadow resolution near the camera and //! coverage out to the far plane. +use crate::renderer::lazy_pipeline::LazyRenderPipeline; use crate::renderer::IDENTITY_MAT4; /// Number of shadow cascades. @@ -300,14 +301,14 @@ pub struct ShadowMap { pub sampler: wgpu::Sampler, pub bind_group_layout: wgpu::BindGroupLayout, pub bind_group: wgpu::BindGroup, - pub pipeline: wgpu::RenderPipeline, + pub pipeline: LazyRenderPipeline, /// Alpha-tested variant for cutout foliage casters. Opaque casters keep /// using `pipeline` (byte-identical to before this was added). - pub pipeline_cutout: wgpu::RenderPipeline, + pub pipeline_cutout: LazyRenderPipeline, /// Skinning-aware variant for the immediate-mode batch (animated /// characters). Binds the joint-matrix buffer at group 1 and skins /// per-vertex so player/enemies cast a real posed shadow. - pub pipeline_skinned: wgpu::RenderPipeline, + pub pipeline_skinned: LazyRenderPipeline, /// Group-1 layout for `pipeline_cutout`: base-colour tex + sampler + a /// cutoff uniform. Per-mesh bind groups are built against this in /// `cache_model_if_static`. @@ -609,7 +610,7 @@ impl ShadowMap { immediate_size: 0, }); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let pipeline = LazyRenderPipeline::new(device, &wgpu::RenderPipelineDescriptor { label: Some("shadow_pipeline"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { @@ -685,7 +686,7 @@ impl ShadowMap { bind_group_layouts: &[Some(&uniform_layout), Some(&cutout_tex_layout)], immediate_size: 0, }); - let pipeline_cutout = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let pipeline_cutout = LazyRenderPipeline::new(device, &wgpu::RenderPipelineDescriptor { label: Some("shadow_pipeline_cutout"), layout: Some(&cutout_pl_layout), vertex: wgpu::VertexState { @@ -734,7 +735,7 @@ impl ShadowMap { bind_group_layouts: &[Some(&uniform_layout), Some(joint_layout)], immediate_size: 0, }); - let pipeline_skinned = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let pipeline_skinned = LazyRenderPipeline::new(device, &wgpu::RenderPipelineDescriptor { label: Some("shadow_pipeline_skinned"), layout: Some(&skinned_pl_layout), vertex: wgpu::VertexState {