diff --git a/.cargo/config.toml b/.cargo/config.toml index 5592118f6c..11a0baa22e 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,14 @@ [alias] xtask = "run -p xtask --" + +# wgpu's GL backend (glutin_wgl_sys) imports opengl32.dll, so every binary that links wgpu loads +# it at start, and a process that has loaded it takes about 60 ms longer to exit (#15444): every +# test process and every app exit on DX12 or Vulkan. Delay-loaded, it loads on the first WGL +# call, which only the GL backend makes. Here rather than in a build script, because a link +# argument from a build script reaches only its own package's binaries, and every package whose +# binaries link wgpu would need one. Cargo joins these with `CARGO_TARGET__RUSTFLAGS` +# (CI, packaging); only `RUSTFLAGS` replaces them. The print DLLs' delay-loads stay in the app's +# and CLI's build.rs: without those the exe doesn't start on some Windows images (#5884), so +# they must hold for any cargo invocation, also one that never reads this file. +[target.'cfg(all(windows, target_env = "msvc"))'] +rustflags = ["-Clink-arg=/DELAYLOAD:opengl32.dll", "-Clink-arg=delayimp.lib"] diff --git a/crates/gpu/src/cells.rs b/crates/gpu/src/cells.rs index de858046d5..14ea29481d 100644 --- a/crates/gpu/src/cells.rs +++ b/crates/gpu/src/cells.rs @@ -115,9 +115,9 @@ impl Compositor { sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), // The previous intermediate submit, when this refresh may submit in between. batch: &mut Option<&mut Option>, - ) { + ) -> Result<(), Unsupported> { if chunks.is_empty() { - return; + return Ok(()); } // Chunks may hold different checkpoints: bind from the lowest one any of them resumes at. let first_pass = checkpoint @@ -126,7 +126,7 @@ impl Compositor { let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats); // A page couldn't be created: draw nothing with the pages missing (the caller ends the refresh). if self.layer_alloc.is_some() { - return; + return Ok(()); } // Chunk pool. @@ -233,7 +233,7 @@ impl Compositor { self.recorded = 0; stats.flushes += 1; if self.fault().is_some() { - return; + return Ok(()); } } // Also after resuming from a lower checkpoint: the chunk moves up to this one. @@ -294,8 +294,9 @@ impl Compositor { } _ => (p.kernel, p.dst), }; - let target = &self.pool[dst as usize].1; let clear = p.kernel == Kernel::Clear; + let pipeline = if clear { None } else { Some(self.kit.pipelines.get(device, kernel, self.acc_format)?) }; + let target = &self.pool[dst as usize].1; let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("pc_compose_pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { @@ -312,10 +313,8 @@ impl Compositor { occlusion_query_set: None, multiview_mask: None, }); - if clear { - continue; - } - pass.set_pipeline(&self.kit.pipelines[&(kernel, self.acc_format)]); + let Some(pipeline) = pipeline else { continue }; + pass.set_pipeline(pipeline); pass.set_scissor_rect(scissor.x0 as u32, scissor.y0 as u32, scissor.width(), scissor.height()); pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]); pass.set_bind_group(1, bg1[i].as_ref(), &[]); @@ -330,6 +329,7 @@ impl Compositor { let (t, v) = &self.pool[plan.root as usize]; sink(encoder, ChunkOut { rect: *c, texture: t, view: v }); } + Ok(()) } /// Upload changed tiles of `surface` within `region` (its tile area inside one page cell); diff --git a/crates/gpu/src/encode.rs b/crates/gpu/src/encode.rs index e704208bd0..8fc93d1440 100644 --- a/crates/gpu/src/encode.rs +++ b/crates/gpu/src/encode.rs @@ -217,7 +217,7 @@ impl Compositor { stats.chunks += chunks.len(); work += part.width() as u64 * part.height() as u64 * plan.passes.len() as u64; let mut batch = flush.then_some(&mut last_submit); - self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); + self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch)?; // The device was lost in a submit inside the cell: issue no more work. if let Some(f) = self.fault() { return Err(Unsupported(f.to_string())); @@ -251,7 +251,7 @@ impl Compositor { return Err(Unsupported(f.to_string())); } let mut batch = Some(&mut last_submit); - self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); + self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch)?; if let Some(f) = self.fault() { return Err(Unsupported(f.to_string())); } diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index dbc61d0853..615677d840 100644 --- a/crates/gpu/src/fx_passes.rs +++ b/crates/gpu/src/fx_passes.rs @@ -258,8 +258,7 @@ impl Compositor { lut: s.lut.clone(), }); } - self.kit.run(device, queue, encoder, &draws); - Ok(()) + self.kit.run(device, queue, encoder, &draws) } } diff --git a/crates/gpu/src/kit.rs b/crates/gpu/src/kit.rs index 12755b2dbf..9a916ccb14 100644 --- a/crates/gpu/src/kit.rs +++ b/crates/gpu/src/kit.rs @@ -1,12 +1,14 @@ -use super::consts::{CHUNK_UNIFORM, MAP16, MAP32, OP_UNIFORM, STRIDE}; +use super::consts::{CHUNK_UNIFORM, OP_UNIFORM, STRIDE}; use super::convert::{lut_texture, words}; +use super::pipelines::Pipelines; use super::textures::{ResKey, ResidentRef}; -use super::{Arc, HashMap, I, Kernel, NonZeroU64, Rect}; +use super::{Arc, I, Kernel, NonZeroU64, Rect, Unsupported}; -/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted). +/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted; a sibling +/// compositor uses the pipelines any of them built). #[derive(Clone)] pub(crate) struct Kit { - pub(crate) pipelines: HashMap<(Kernel, wgpu::TextureFormat), wgpu::RenderPipeline>, + pub(crate) pipelines: Arc, pub(crate) bgl0: wgpu::BindGroupLayout, pub(crate) bgl1: wgpu::BindGroupLayout, pub(crate) dummy: wgpu::TextureView, @@ -28,9 +30,9 @@ pub(crate) struct MapDraw { impl Kit { /// Record `draws` (each its own render pass) into `encoder`. - pub(crate) fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) { + pub(crate) fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) -> Result<(), Unsupported> { if draws.is_empty() { - return; + return Ok(()); } let mut data = vec![0u8; draws.len() * 2 * STRIDE as usize]; for (i, d) in draws.iter().enumerate() { @@ -47,6 +49,7 @@ impl Kit { queue.write_buffer(&ubuf, 0, &data); let bg0 = uniform_group(device, &self.bgl0, &ubuf); for (i, d) in draws.iter().enumerate() { + let pipeline = self.pipelines.get(device, d.kernel, d.format)?; let lut = d.lut.as_ref().map(|l| { let mut row = [0.0f32; 4096]; row[..l.len().min(4096)].copy_from_slice(&l[..l.len().min(4096)]); @@ -70,12 +73,13 @@ impl Kit { occlusion_query_set: None, multiview_mask: None, }); - pass.set_pipeline(&self.pipelines[&(d.kernel, d.format)]); + pass.set_pipeline(pipeline); pass.set_scissor_rect(d.scissor[0], d.scissor[1], d.scissor[2], d.scissor[3]); pass.set_bind_group(0, &bg0, &[(2 * i as u64 * STRIDE) as u32, ((2 * i + 1) as u64 * STRIDE) as u32]); pass.set_bind_group(1, &bg1, &[]); pass.draw(0..3, 0..1); } + Ok(()) } } @@ -127,48 +131,6 @@ pub(crate) fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEnt /// The compositor's WGSL source (exposed for validation in tests). pub const SHADER: &str = include_str!("compose.wgsl"); -/// One thread's share of the compositor's pipelines: the vertex entry point (in -/// [`vertex_shader`]) and the (kernel, target format) pairs it builds. -pub(crate) struct BuildJob { - pub(crate) vertex: String, - pub(crate) keys: Vec<(Kernel, wgpu::TextureFormat)>, -} - -/// The compositor's pipelines, grouped by the thread that builds them: one job per kernel, and -/// an effect-map kernel's R32F and R16F pipelines in the same job. Each job has its own vertex -/// entry point, so no two jobs share a shader (see `Compositor::build`). -pub(crate) fn build_jobs(acc_format: wgpu::TextureFormat) -> Vec { - let one = |k: Kernel| if k.is_map() { vec![(k, MAP32), (k, MAP16)] } else { vec![(k, acc_format)] }; - let (plain, maps): (Vec, Vec) = Kernel::DRAWN.iter().partition(|k| !k.is_map()); - plain.into_iter().chain(maps).enumerate().map(|(job, k)| BuildJob { vertex: format!("vs_{job}"), keys: one(k) }).collect() -} - -/// The full-chunk triangle's vertex stage, once per build job under that job's name (`vs_0`, -/// `vs_1`, ...): the same code under distinct names, so each job compiles its own vertex shader. -/// -/// A workaround, not a design: wgpu-hal's D3D12 shader cache shares a compiled FXC blob between -/// threads, and FXC's blobs don't count references atomically, so a shared one can be freed -/// while still cached (gfx-rs/wgpu#10547, #9173). Each copy costs one compile of a three-line -/// shader. Once a wgpu release fixes the cache, go back to one `vs` in `compose.wgsl` and let -/// `build_jobs` split map kernels by format again. -pub(crate) fn vertex_shader(jobs: &[BuildJob]) -> String { - let mut s = String::from( - "struct VOut { @builtin(position) pos: vec4 }; -", - ); - for job in jobs { - s.push_str(&format!( - "@vertex fn {}(@builtin(vertex_index) vi: u32) -> VOut {{ - let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); - return VOut(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0)); -}} -", - job.vertex - )); - } - s -} - /// Pass-level resources resolved for one page cell: resident pages (texture, mask) and effect /// maps (view and region) per pass. pub(crate) struct Bound { diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 2beaedc233..8ba9d09a5f 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -118,9 +118,6 @@ pub struct Compositor { /// out of memory. fail_allocs: u32, acc_format: wgpu::TextureFormat, - /// Whether the effect-map pipelines could be built (else documents with layer effects are - /// [`Unsupported`] and use the CPU compositor). - effect_maps: bool, /// `CmykSpace::id` of the document being encoded (0: built-in coated CMYK). cmyk: u64, /// The device's health (see [`Compositor::set_health`]); `None` = assumed healthy. @@ -141,6 +138,7 @@ mod encode; mod fx_passes; mod kit; mod paging; +mod pipelines; #[cfg(not(target_arch = "wasm32"))] pub mod readback; mod setup; diff --git a/crates/gpu/src/pipelines.rs b/crates/gpu/src/pipelines.rs new file mode 100644 index 0000000000..8331f90946 --- /dev/null +++ b/crates/gpu/src/pipelines.rs @@ -0,0 +1,203 @@ +//! The compositor's render pipelines: one table per compositor and its siblings, each pipeline +//! built the first time a draw needs it, or all of them at once where a caller wants every +//! shader compiled up front (the app's background build). +//! +//! On DX12 the shader compiler is FXC, which compiles one shader at a time; the ~30 pipelines +//! took about 8 s on one core (#6419), and 3 to 7.5 s per test process on the Windows CI +//! runners' software adapter (#15439). A compositor that draws one plain layer needs two or three. + +use std::sync::OnceLock; + +use super::consts::{MAP16, MAP32}; +use super::kit::SHADER; +use super::{Kernel, Unsupported, first_error}; + +/// Why documents with layer effects can't use the GPU compositor on this device. +pub(crate) const NO_EFFECT_MAPS: &str = "layer effects need float effect-map render targets, which this GPU lacks"; + +/// Every pipeline of one compositor, shared by its siblings. +/// +/// No shader is used by two threads at once (#9173): wgpu-hal's D3D12 backend caches each +/// compiled shader and hands every pipeline a reference to it, but FXC's blobs count references +/// without atomics (gfx-rs/wgpu#10547), so threads sharing one could free it while the cache still +/// held it, and dropping the device then aborted the process. So each kernel has its own vertex +/// entry point ([`vertex_shader`]), a kernel's pipelines for its target formats are built +/// together on one thread, and every build in the process holds [`building`]: the tables of +/// several compositors on one device compile the same shaders. +pub(crate) struct Pipelines { + module: wgpu::ShaderModule, + vertex: wgpu::ShaderModule, + layout: wgpu::PipelineLayout, + kernels: Vec, +} + +/// One kernel's pipelines, one per target format, built together. +pub(crate) struct KernelPipelines { + pub(crate) kernel: Kernel, + entry: &'static str, + /// Its own vertex entry point in [`Pipelines::vertex`]. + pub(crate) vertex: String, + pub(crate) formats: Vec, + /// Per format, the pipeline or the error building it raised. + built: OnceLock>>, +} + +/// Held by every pipeline build in the process (see [`Pipelines`]). +fn building() -> std::sync::MutexGuard<'static, ()> { + static BUILDING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +impl Pipelines { + /// The shaders and layout of every pipeline of [`table`]. Builds no pipeline. + pub(crate) fn new(device: &wgpu::Device, acc_format: wgpu::TextureFormat, bgl0: &wgpu::BindGroupLayout, bgl1: &wgpu::BindGroupLayout) -> Self { + let kernels = table(acc_format); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let vertex = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("pc_compose_vertex"), + source: wgpu::ShaderSource::Wgsl(vertex_shader(kernels.iter().map(|k| k.vertex.as_str())).into()), + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_compose"), + bind_group_layouts: &[Some(bgl0), Some(bgl1)], + immediate_size: 0, + }); + Self { module, vertex, layout, kernels } + } + + /// The pipeline drawing `kernel` into `format`, built now if no draw needed it before. A + /// pipeline the device can't build is an [`Unsupported`] for every draw that needs it, so + /// that refresh uses the CPU compositor. + pub(crate) fn get(&self, device: &wgpu::Device, kernel: Kernel, format: wgpu::TextureFormat) -> Result<&wgpu::RenderPipeline, Unsupported> { + let missing = || Unsupported(format!("the compositor has no {kernel:?} pipeline for {format:?}")); + let k = self.kernels.iter().find(|k| k.kernel == kernel).ok_or_else(missing)?; + let i = k.formats.iter().position(|&f| f == format).ok_or_else(missing)?; + let built = match k.built.get() { + Some(built) => built, + None => { + let _building = building(); + k.built.get_or_init(|| self.build(device, k)) + } + }; + built[i].as_ref().map_err(|e| { + Unsupported(if kernel.is_map() { + format!("{NO_EFFECT_MAPS} ({e})") + } else { + format!("couldn't build the compositor's `{}` pipeline: {e}", k.entry) + }) + }) + } + + /// Build every pipeline no draw has built yet, one kernel per thread of the current Rayon + /// pool (or one after another), and return the first error a non-map pipeline raised. Effect + /// maps render to R32Float / R16Float, which some adapters (e.g. GL without float render + /// targets) can't: a failed map pipeline only turns layer effects to the CPU compositor + /// ([`Self::effect_maps`]). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn build_all(&self, device: &wgpu::Device, sequential: bool) -> Option { + let _building = building(); + let missing: Vec<&KernelPipelines> = self.kernels.iter().filter(|k| k.built.get().is_none()).collect(); + let build = |k: &KernelPipelines| { + k.built.get_or_init(|| self.build(device, k)); + }; + if sequential { + missing.into_iter().for_each(build); + } else { + super::fx::par_map(missing, build); + } + let first_error = |maps: bool| { + self.kernels.iter().filter(|k| k.kernel.is_map() == maps).flat_map(|k| k.built.get().into_iter().flatten()).find_map(|b| b.as_ref().err().cloned()) + }; + if let Some(e) = first_error(true) { + log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU"); + } + first_error(false) + } + + /// `k`'s pipelines, each inside its own error scope on the calling thread (wgpu's scopes are + /// per thread). The caller holds [`building`]. + fn build(&self, device: &wgpu::Device, k: &KernelPipelines) -> Vec> { + k.formats + .iter() + .map(|&format| { + let (pipeline, error) = first_error(device, || { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(k.entry), + layout: Some(&self.layout), + vertex: wgpu::VertexState { module: &self.vertex, entry_point: Some(&k.vertex), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &self.module, + entry_point: Some(k.entry), + targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }); + match error { + Some(e) => Err(e.to_string()), + None => Ok(pipeline), + } + }) + .collect() + } + + /// Whether no effect-map pipeline has failed to build (one not built yet is assumed to work). + pub(crate) fn effect_maps(&self) -> bool { + self.kernels.iter().filter(|k| k.kernel.is_map()).all(|k| k.built.get().is_none_or(|b| b.iter().all(Result::is_ok))) + } + + /// How many pipelines have been built (or failed to build) so far, and how many there are. + pub(crate) fn counts(&self) -> (usize, usize) { + let built = self.kernels.iter().filter(|k| k.built.get().is_some()).map(|k| k.formats.len()).sum(); + (built, self.kernels.iter().map(|k| k.formats.len()).sum()) + } +} + +/// Every drawn kernel, none built yet: plain kernels draw into `acc_format`, effect-map kernels +/// into R32F and R16F maps. +pub(crate) fn table(acc_format: wgpu::TextureFormat) -> Vec { + let (plain, maps): (Vec, Vec) = Kernel::DRAWN.iter().partition(|k| !k.is_map()); + plain + .into_iter() + .chain(maps) + .filter_map(|kernel| Some((kernel, kernel.entry()?))) + .enumerate() + .map(|(i, (kernel, entry))| KernelPipelines { + kernel, + entry, + vertex: format!("vs_{i}"), + formats: if kernel.is_map() { vec![MAP32, MAP16] } else { vec![acc_format] }, + built: OnceLock::new(), + }) + .collect() +} + +/// The full-chunk triangle's vertex stage, once under each of `names` (`vs_0`, `vs_1`, ...): the +/// same code under distinct names, so each kernel compiles its own vertex shader. +/// +/// A workaround, not a design: wgpu-hal's D3D12 shader cache shares a compiled FXC blob between +/// threads, and FXC's blobs don't count references atomically, so a shared one can be freed +/// while still cached (gfx-rs/wgpu#10547, #9173). Each copy costs one compile of a three-line +/// shader. Once a wgpu release fixes the cache, go back to one `vs` in `compose.wgsl` and build +/// each pipeline on its own. +pub(crate) fn vertex_shader<'a>(names: impl Iterator) -> String { + let mut s = String::from( + "struct VOut { @builtin(position) pos: vec4 }; +", + ); + for name in names { + s.push_str(&format!( + "@vertex fn {name}(@builtin(vertex_index) vi: u32) -> VOut {{ + let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); + return VOut(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0)); +}} +" + )); + } + s +} diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs index e84b2571e4..9f4d44ac43 100644 --- a/crates/gpu/src/setup.rs +++ b/crates/gpu/src/setup.rs @@ -1,11 +1,10 @@ use super::batch::tile_grid; use super::consts::{ACC_FORMAT, CHUNK, CHUNK_UNIFORM, FX_BUDGET, MAX_PATTERN_TEXTURE_BYTES, OP_UNIFORM, PAGE, PATTERN_BUDGET, RESIDENT_BUDGET}; -use super::kit::{Kit, SHADER, build_jobs, tex_entry, uniform_entry, vertex_shader}; +use super::kit::{Kit, tex_entry, uniform_entry}; use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; +use super::pipelines::{NO_EFFECT_MAPS, Pipelines}; use super::textures::{FxEntry, Resident, Tex, TexKind}; -use super::{ - Compositor, DeviceHealth, DocId, Document, Fault, HashMap, Kernel, LayerContent, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing, -}; +use super::{Compositor, DeviceHealth, DocId, Document, Fault, HashMap, LayerContent, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing}; /// Classification of a synchronous compositor pipeline build failure. /// @@ -55,84 +54,61 @@ impl Compositor { if feats.allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { wgpu::TextureFormat::Rgba32Float } else { wgpu::TextureFormat::Rgba16Float } } - /// [`Compositor::new_with_format`], but a shader or pipeline the driver can't build (e.g. a - /// D3D12 shader-compiler failure) is an `Err` instead of a panic, so the caller can fall back - /// to the CPU compositor. Where errors only arrive asynchronously (WebGPU), creation is assumed - /// to have worked. + /// [`Compositor::new_with_format`], but a shader the driver can't take is an `Err` instead of + /// a panic. Pipelines are built by the first draw that needs each one; one the driver can't + /// build (e.g. a D3D12 shader-compiler failure) makes that render [`Unsupported`], so the + /// caller falls back to the CPU compositor. Where errors only arrive asynchronously (WebGPU), + /// creation is assumed to have worked. pub fn try_new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Result { - match first_error(device, || Self::build(device, acc_format, false)) { - ((comp, None), None) => Ok(comp), - ((_, Some(e)), _) | (_, Some(e)) => Err(Unsupported(format!("couldn't build the compositor's pipelines: {e}"))), + match first_error(device, || Self::build(device, acc_format)) { + (comp, None) => Ok(comp), + (_, Some(e)) => Err(Unsupported(format!("couldn't create the compositor: {e}"))), } } - /// Build pipelines using a dedicated Rayon pool instead of the process-wide pool. + /// [`Compositor::try_new_with_format`] that also builds every pipeline now, on a dedicated + /// Rayon pool of `threads` instead of the process-wide pool, so a failing one is an `Err` + /// here rather than on a later draw. /// - /// This keeps shader compilation from occupying workers needed by CPU compositing. - /// If the pool cannot be created, pipeline enumeration runs sequentially on the calling - /// thread. The outer and per-pipeline wgpu error scopes are kept on their respective - /// build threads. + /// The dedicated pool keeps shader compilation from occupying workers needed by CPU + /// compositing. If the pool cannot be created, the pipelines are built one after another on + /// the calling thread. #[cfg(not(target_arch = "wasm32"))] pub fn try_new_with_format_threads(device: &wgpu::Device, acc_format: wgpu::TextureFormat, threads: usize) -> Result { Self::try_new_with_format_threads_classified(device, acc_format, threads).map_err(|e| Unsupported(e.message)) } - /// Build the compositor pipelines with an explicit failure classification for callers - /// that cache deterministic failures across launches. Only recognized shader compiler + /// [`Compositor::try_new_with_format_threads`] with an explicit failure classification for + /// callers that cache deterministic failures across launches. Only recognized shader compiler /// diagnostics are marked deterministic; all other wgpu errors are transient or unknown. #[cfg(not(target_arch = "wasm32"))] pub fn try_new_with_format_threads_classified(device: &wgpu::Device, acc_format: wgpu::TextureFormat, threads: usize) -> Result { + let comp = Self::try_new_with_format(device, acc_format).map_err(|e| BuildFailure { kind: BuildFailureKind::TransientOrUnknown, message: e.0 })?; + let pipelines = &comp.kit.pipelines; let pool = rayon::ThreadPoolBuilder::new().num_threads(threads.max(1)).thread_name(|index| format!("photocraft-gpu-build-{index}")).build(); - let built = match pool { - Ok(pool) => pool.install(|| first_error(device, || Self::build(device, acc_format, false))), + let error = match pool { + Ok(pool) => pool.install(|| pipelines.build_all(device, false)), Err(e) => { log::warn!("GPU compositor: couldn't create dedicated build pool; building sequentially: {e}"); - first_error(device, || Self::build(device, acc_format, true)) + pipelines.build_all(device, true) } }; - match built { - ((comp, None), None) => Ok(comp), - ((_, Some(e)), None) => { - let kind = classify_build_diagnostic(&e.to_string()); - Err(BuildFailure { kind, message: format!("couldn't build the compositor's pipelines: {e}") }) - } - (_, Some(e)) => { - Err(BuildFailure { kind: BuildFailureKind::TransientOrUnknown, message: format!("couldn't build the compositor's pipelines: {e}") }) - } + match error { + None => Ok(comp), + Some(e) => Err(BuildFailure { kind: classify_build_diagnostic(&e), message: format!("couldn't build the compositor's pipelines: {e}") }), } } /// Create a compositor whose accumulation/render-target format is `acc_format`. Pass /// `Rgba16Float` on adapters that can't render to `Rgba32Float` (e.g. some Intel Vulkan drivers), - /// which otherwise panics at render-pipeline creation. See `Compositor::preferred_acc_format`. + /// which otherwise fails at render-pipeline creation. See `Compositor::preferred_acc_format`. + /// Pipelines are built on first use (see [`Compositor::try_new_with_format`]). pub fn new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self { - let (comp, error) = Self::build(device, acc_format, false); - if let Some(e) = error { - log::error!("GPU compositor: couldn't build its pipelines: {e}"); - } - comp + Self::build(device, acc_format) } - /// The compositor and the first error raised building its (non-map) pipelines. They are - /// built in parallel, each inside its own error scope on the thread that builds it (wgpu's - /// scopes are per thread): on DX12, FXC compiles one shader at a time and the ~30 pipelines - /// took about 8 s on one core (#6419). - /// - /// No shader is used by two threads at once (#9173): wgpu-hal's D3D12 backend caches each - /// compiled shader and hands every pipeline a reference to it, but FXC's blobs count - /// references without atomics (gfx-rs/wgpu#10547), so threads sharing one could free it - /// while the cache still held it, and dropping the device then aborted the process. So each - /// job has its own vertex entry point and fragment shaders ([`build_jobs`]), and builds of - /// several compositors take turns. - fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat, sequential: bool) -> (Self, Option) { - static BUILDING: std::sync::Mutex<()> = std::sync::Mutex::new(()); - let _building = BUILDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); - let jobs = build_jobs(acc_format); - let vertex = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("pc_compose_vertex"), - source: wgpu::ShaderSource::Wgsl(vertex_shader(&jobs).into()), - }); + /// The compositor's shaders, layouts and pipeline table ([`Pipelines`]); no pipeline yet. + fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self { let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_compose_uniforms"), entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)], @@ -141,86 +117,29 @@ impl Compositor { label: Some("pc_compose_textures"), entries: &(0..8).map(tex_entry).collect::>(), }); - let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("pc_compose"), - bind_group_layouts: &[Some(&bgl0), Some(&bgl1)], - immediate_size: 0, - }); - // `None` only for kernels without a fragment entry point, which are never drawn. - let pipeline = |k: Kernel, format: wgpu::TextureFormat, vs: &str| { - let entry = k.entry()?; - Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(entry), - layout: Some(&layout), - vertex: wgpu::VertexState { module: &vertex, entry_point: Some(vs), buffers: &[], compilation_options: Default::default() }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: None, - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some(entry), - targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - })) - }; - // Effect maps render to R32Float / R16Float, which some adapters (e.g. GL without float - // render targets) can't: then layer effects use the CPU compositor and the rest stays here. - let build_one = |job: super::kit::BuildJob| { - job.keys - .into_iter() - .map(|key| { - let (built, error) = first_error(device, || pipeline(key.0, key.1, &job.vertex)); - (key, built, error) - }) - .collect::>() - }; - let built: Vec<_> = if sequential { jobs.into_iter().map(build_one).collect() } else { fx::par_map(jobs, build_one) }; - let built = built.into_iter().flatten(); - let (mut pipelines, mut maps) = (HashMap::new(), Vec::new()); - let (mut error, mut map_error) = (None, None); - for (key, built, e) in built { - let map = key.0.is_map(); - // A failed map pipeline turns all effect maps off below. A failed non-map pipeline - // keeps its (invalid) handle: draws look pipelines up by key, so dropping it would - // turn a validation error into a missing-key panic on the first draw. - if let Some(e) = e { - if map { - map_error.get_or_insert(e); - continue; - } - error.get_or_insert(e); - } - let Some(p) = built else { continue }; - if map { - maps.push((key, p)); - } else { - pipelines.insert(key, p); - } - } - if let Some(e) = &map_error { - log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU"); - } else { - pipelines.extend(maps); - } + let pipelines = std::sync::Arc::new(Pipelines::new(device, acc_format, &bgl0, &bgl1)); let dummy = Tex::new(device, "pc_compose_dummy", 1, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING).view; let kit = Kit { pipelines, bgl0, bgl1, dummy }; - let comp = Self::from_kit(kit, device.limits().max_texture_dimension_2d, acc_format, map_error.is_none()); - (comp, error) + Self::from_kit(kit, device.limits().max_texture_dimension_2d, acc_format) + } + + /// Test hook: how many of the compositor's pipelines have been built so far (shared with its + /// siblings), and how many it has. + #[doc(hidden)] + pub fn pipeline_counts(&self) -> (usize, usize) { + self.kit.pipelines.counts() } /// Create an independent compositor on the same device, reusing compiled pipelines. /// Texture caches, budgets, focus and timing start at their defaults; no document state is /// shared. Render with the same device and queue as this compositor. pub fn sibling(&self) -> Self { - let mut sibling = Self::from_kit(self.kit.clone(), self.device_max, self.acc_format, self.effect_maps); + let mut sibling = Self::from_kit(self.kit.clone(), self.device_max, self.acc_format); sibling.health = self.health.clone(); sibling } - fn from_kit(kit: Kit, device_max: u32, acc_format: wgpu::TextureFormat, effect_maps: bool) -> Self { + fn from_kit(kit: Kit, device_max: u32, acc_format: wgpu::TextureFormat) -> Self { Self { kit, pool: Vec::new(), @@ -250,7 +169,6 @@ impl Compositor { admit_freed: 0, fail_allocs: 0, acc_format, - effect_maps, cmyk: 0, health: None, timer: None, @@ -455,8 +373,8 @@ impl Compositor { /// Effect maps must fit in textures (per page cell when the region exceeds the limit), and /// patterns in one texture. pub(crate) fn check_fx(&self, doc: &Document, p: &Plan<'_>) -> Result<(), Unsupported> { - if !self.effect_maps && !p.fx.is_empty() { - return Err(Unsupported("layer effects need float effect-map render targets, which this GPU lacks".into())); + if !p.fx.is_empty() && !self.kit.pipelines.effect_maps() { + return Err(Unsupported(NO_EFFECT_MAPS.into())); } for f in &p.fx { if self.fx_paged(f.region) { diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 50b8fdb6b5..62a69033a5 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -132,31 +132,26 @@ fn half_roundtrip() { } } -/// #9173: no two pipeline build jobs share a shader, so no FXC blob is shared across threads. +/// #9173: no two kernels' pipelines share a shader, so no FXC blob is shared across threads. #[test] -fn build_jobs_share_no_shader() { +fn kernel_pipelines_share_no_shader() { use super::consts::{MAP16, MAP32}; - use super::kit::{build_jobs, vertex_shader}; - let jobs = build_jobs(wgpu::TextureFormat::Rgba32Float); + use super::pipelines::{table, vertex_shader}; + let jobs = table(wgpu::TextureFormat::Rgba32Float); let mut seen = std::collections::HashSet::new(); for job in &jobs { - let fragments: std::collections::HashSet<_> = job.keys.iter().filter_map(|k| k.0.entry()).collect(); - for f in fragments { - assert!(seen.insert(f.to_string()), "fragment shader {f} is built by two jobs"); - } + let f = job.kernel.entry().expect("a drawn kernel"); + assert!(seen.insert(f.to_string()), "fragment shader {f} is built by two kernels"); assert!(seen.insert(job.vertex.clone()), "vertex entry {} is shared", job.vertex); } - // Every drawn pipeline is still built, in the same formats. - let keys: Vec<_> = jobs.iter().flat_map(|job| job.keys.iter().copied()).collect(); - let plain = Kernel::DRAWN.iter().filter(|k| !k.is_map()).count(); - assert_eq!(keys.len(), plain + 2 * (Kernel::DRAWN.len() - plain)); + // Every drawn kernel has its pipelines, in the same formats. for k in Kernel::DRAWN { - let formats: Vec<_> = keys.iter().filter(|key| key.0 == k).map(|key| key.1).collect(); + let formats: Vec<_> = jobs.iter().filter(|job| job.kernel == k).flat_map(|job| job.formats.iter().copied()).collect(); let want = if k.is_map() { vec![MAP32, MAP16] } else { vec![wgpu::TextureFormat::Rgba32Float] }; assert_eq!(formats, want, "{k:?}"); } - // The vertex module validates and has every job's entry point. - let src = vertex_shader(&jobs); + // The vertex module validates and has every kernel's entry point. + let src = vertex_shader(jobs.iter().map(|job| job.vertex.as_str())); let module = wgpu::naga::front::wgsl::parse_str(&src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src))); wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()) .validate(&module) @@ -167,7 +162,7 @@ fn build_jobs_share_no_shader() { // The fragment module has no vertex stage, so the build can't fall back to one shared `vs`. let compose = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER))); let shared: Vec<_> = compose.entry_points.iter().filter(|ep| ep.stage == wgpu::naga::ShaderStage::Vertex).map(|ep| ep.name.as_str()).collect(); - assert!(shared.is_empty(), "compose.wgsl has a vertex entry point every job would share: {shared:?}"); + assert!(shared.is_empty(), "compose.wgsl has a vertex entry point every kernel would share: {shared:?}"); } #[test] diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 5301c49da7..9b4e2b62f8 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -135,7 +135,7 @@ fn gpu() -> Option { None } }; - let comp = timed("pipeline creation", compositor)?; + let comp = timed("compositor creation", compositor)?; let mut paged = comp.sibling(); paged.set_texture_limit(PAGED_LIMIT); Some(Gpu { device, queue, comp, paged, _lock: lock }) @@ -3067,15 +3067,16 @@ fn rgba16f_fallback_path_renders() { #[test] fn unbuildable_pipelines_are_an_error_not_a_panic() { - // The app falls back to the CPU compositor on Err; a panic here would crash it (as FXC once - // did on D3D12). A depth format can't be a colour target, so its pipelines fail to build. + // The app builds every pipeline up front and falls back to the CPU compositor on Err; a panic + // here would crash it (as FXC once did on D3D12). A depth format can't be a colour target, so + // its pipelines fail to build. let Some((adapter, device, _, _lock)) = any_device() else { return }; - let e = Compositor::try_new_with_format(&device, wgpu::TextureFormat::Depth32Float).err().expect("depth target must fail"); + let e = Compositor::try_new_with_format_threads(&device, wgpu::TextureFormat::Depth32Float, 4).err().expect("depth target must fail"); assert!(e.0.contains("pipelines"), "{e}"); // The format the app picks builds (effect maps the adapter can't render are left out, not fatal). let f = Compositor::preferred_acc_format(&adapter); if adapter.get_texture_format_features(f).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { - assert!(Compositor::try_new_with_format(&device, f).is_ok()); + assert!(Compositor::try_new_with_format_threads(&device, f, 4).is_ok()); } } diff --git a/crates/gpu/tests/it/pipeline_errors.rs b/crates/gpu/tests/it/pipeline_errors.rs index e4cd97c52b..56b93b020d 100644 --- a/crates/gpu/tests/it/pipeline_errors.rs +++ b/crates/gpu/tests/it/pipeline_errors.rs @@ -1,6 +1,7 @@ -//! #6419: the compositor's pipelines are built on several threads. A pipeline the device can't -//! build is still an `Err` from `try_new_with_format`, not a panic from wgpu's default error -//! handler (error scopes are per thread). Skips when no GPU adapter exists. +//! #6419: the compositor's pipelines are built on several threads, or one by one on first use +//! (#15439). A pipeline the device can't build is an `Err` from the build or the draw, not a panic +//! from wgpu's default error handler (error scopes are per thread). Skips when no GPU adapter +//! exists. use std::sync::Arc; @@ -26,17 +27,16 @@ fn a_pipeline_built_on_another_thread_fails_as_an_error() { let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some((adapter, device, _queue)) = device() else { return }; // Never a render target, so every accumulation pipeline fails validation. - let Err(e) = Compositor::try_new_with_format(&device, wgpu::TextureFormat::Rgb9e5Ufloat) else { + let Err(e) = Compositor::try_new_with_format_threads(&device, wgpu::TextureFormat::Rgb9e5Ufloat, 4) else { panic!("a compositor accumulating into Rgb9e5Ufloat"); }; assert!(e.0.contains("couldn't build the compositor's pipelines"), "{e:?}"); // The device is still usable for a compositor it can build. - assert!(Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).is_ok()); + assert!(Compositor::try_new_with_format_threads(&device, Compositor::preferred_acc_format(&adapter), 4).is_ok()); } -/// `new_with_format` on a device whose errors go to the caller's handler: a pipeline that failed -/// to build stays in the compositor as an invalid handle, so a draw reports GPU errors instead of -/// panicking on a missing pipeline. +/// A compositor whose pipelines fail to build on first use, on a device whose errors go to the +/// caller's handler: the draw is an `Err`, not a panic. #[test] fn a_compositor_with_failed_pipelines_draws_without_panicking() { let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -46,10 +46,10 @@ fn a_compositor_with_failed_pipelines_draws_without_panicking() { let mut comp = Compositor::new_with_format(&device, wgpu::TextureFormat::Rgb9e5Ufloat); let doc = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::rgba(0.5, 0.5, 0.5, 1.0)); // Drawing into an unrenderable format can't succeed, but must not panic. - let _ = render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()); + assert!(render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).is_err()); } -/// #9173: the compositor builds its pipelines on several threads (#6419). On Direct3D 12 with FXC, +/// #9173: the threaded build builds the compositor's pipelines on several threads (#6419). On Direct3D 12 with FXC, /// wgpu-hal caches each compiled shader as an `ID3DBlob` whose reference count isn't atomic /// (gfx-rs/wgpu#10547), so two threads building pipelines from the same shader could free a blob /// the cache still holds; dropping the device then aborted the process (`null reference @@ -83,12 +83,12 @@ fn parallel_compositor_builds_leave_the_shader_cache_intact() { let format = Compositor::preferred_acc_format(&adapter); // The first build compiles every shader; the rest are cache hits, so their threads take // and release references to the cached shaders densely. The builds start together, so - // overlapping `Compositor::build` calls are exercised too (the process-wide lock). + // overlapping builds are exercised too (the process-wide lock). std::thread::scope(|scope| { let handles: Vec<_> = (0..builds) .map(|_| { scope.spawn(|| { - let built = Compositor::try_new_with_format(&device, format); + let built = Compositor::try_new_with_format_threads(&device, format, 4); assert!(built.is_ok(), "round {round}: {:?}", built.err()); }) }) diff --git a/crates/gpu/tests/it/pipelines.rs b/crates/gpu/tests/it/pipelines.rs index 119ace7d72..fa4b684ad9 100644 --- a/crates/gpu/tests/it/pipelines.rs +++ b/crates/gpu/tests/it/pipelines.rs @@ -9,6 +9,11 @@ //! //! The Windows CI runners have no GPU: their adapter is WARP over DX12, so this runs FXC there. +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::Document; +use photocraft_geom::Size; +use photocraft_gpu::{Compositor, render_to_vec}; + use crate::GPU_LOCK; #[test] @@ -45,10 +50,42 @@ fn every_compositor_pipeline_builds() { continue; }; let info = adapter.get_info(); - let format = photocraft_gpu::Compositor::preferred_acc_format(&adapter); - if let Err(e) = photocraft_gpu::Compositor::try_new_with_format(&device, format) { + let format = Compositor::preferred_acc_format(&adapter); + // Draws build only the pipelines they use; this builds every one. + let threads = std::thread::available_parallelism().map_or(1, std::num::NonZero::get); + if let Err(e) = Compositor::try_new_with_format_threads(&device, format, threads) { panic!("{:?} adapter {} (driver {}): {e}", info.backend, info.name, info.driver_info); } } } } + +/// #15439: a compositor builds a pipeline when a draw first needs it, so a process that draws one +/// layer compiles a few shaders, not all of them (FXC on the Windows runners' WARP adapter took +/// 3 to 7.5 s per process for all of them). Siblings share what any of them built. +#[test] +fn a_draw_builds_only_the_pipelines_it_uses() { + let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let instance = crate::instance(); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { + return eprintln!("skipping: no adapter"); + }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) else { + return eprintln!("skipping: no device"); + }; + let mut comp = match Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)) { + Ok(c) => c, + Err(e) => return eprintln!("skipping: {e}"), + }; + let (built, all) = comp.pipeline_counts(); + assert_eq!(built, 0, "creating a compositor builds no pipeline"); + let doc = Document::with_background("one layer", Size::new(16, 16), ColorMode::Rgb, SampleType::U8, Color::rgba(0.25, 0.5, 0.75, 1.0)); + render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).expect("one layer renders on the GPU"); + let (one_layer, _) = comp.pipeline_counts(); + assert!(one_layer > 0 && one_layer * 4 < all, "one layer built {one_layer} of {all} pipelines"); + // Drawing it again, or from a sibling, builds nothing new. + render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).expect("second render"); + let mut sibling = comp.sibling(); + render_to_vec(&mut sibling, &device, &queue, &doc, doc.bounds()).expect("sibling render"); + assert_eq!(sibling.pipeline_counts(), (one_layer, all)); +}