1//! Shader domains, GPU op enum, lazy WGSL pipeline cache, dynamic uniform ring,
2//! and tiny LUT/curve texture LRU cache.
3
4use std::collections::HashMap;
5use std::num::NonZeroU64;
6
7use crate::cache::CachedTexture;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub(super) enum ShaderDomain {
11 Composite,
12 Color,
13 BlurGlow,
14 Transform,
15 Masks,
16 KeyersGen,
17 ArchiveFx,
18}
19
20impl ShaderDomain {
21 pub(super) fn source(self) -> &'static str {
22 match self {
23 Self::Composite => include_str!("../shaders/composite.wgsl"),
24 Self::Color => include_str!("../shaders/color.wgsl"),
25 Self::BlurGlow => include_str!("../shaders/blur_glow.wgsl"),
26 Self::Transform => include_str!("../shaders/transform.wgsl"),
27 Self::Masks => include_str!("../shaders/masks.wgsl"),
28 Self::KeyersGen => include_str!("../shaders/keyers_gen.wgsl"),
29 Self::ArchiveFx => include_str!("../shaders/archive_fx.wgsl"),
30 }
31 }
32
33 pub(super) fn label(self) -> &'static str {
34 match self {
35 Self::Composite => "compositor-shaders-composite",
36 Self::Color => "compositor-shaders-color",
37 Self::BlurGlow => "compositor-shaders-blur-glow",
38 Self::Transform => "compositor-shaders-transform",
39 Self::Masks => "compositor-shaders-masks",
40 Self::KeyersGen => "compositor-shaders-keyers-gen",
41 Self::ArchiveFx => "compositor-shaders-archive-fx",
42 }
43 }
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47pub(super) enum ShaderOp {
48 Bg,
49 Merge,
50 Transform,
51 Bc,
52 Cc,
53 ColorGain,
54 LumaKey,
55 Blur,
56 BlurH,
57 BlurV,
58 DirBlur,
59 FastNoise,
60 Displace,
61 MaskShape,
62 MaskCombine,
63 MaskApply,
64 BitmapMask,
65 Colorize,
66 ColorCurves,
67 XfChroma,
68 GamutConvert,
69 VariBlur,
70 OutlineTint,
71 OutlineComposite,
72 #[allow(dead_code)]
73 CustomWave,
74 Crop,
75 GlowAdd,
76 XGlowPrep,
77 XGlowAccum,
78 DisplayBlit,
79 Invert,
80 ChannelBoolean,
81 Filter,
82 HueCurves,
83 UltraKeyer,
84 Dissolve,
85 Homography,
86 ShadowComp,
87 Plasma,
88 FilmGrain,
89 SetDomain,
90 ChangeDepth,
91 Vortex,
92 KScope,
93 Drip,
94 Dent,
95 PerspectivePos,
96 DaySky,
97 GridWarp,
98 CheckerPiece,
99 AlphaWeightedNoise,
100 Crystallize,
101 HexagonTiles,
102 RemoveNoise,
103 DeltaKeyer,
104}
105
106impl ShaderOp {
107 pub(super) fn domain(self) -> ShaderDomain {
108 match self {
109 Self::Bg
110 | Self::Merge
111 | Self::DisplayBlit
112 | Self::ChannelBoolean
113 | Self::Dissolve
114 | Self::ShadowComp
115 | Self::SetDomain
116 | Self::ChangeDepth => ShaderDomain::Composite,
117
118 Self::Bc
119 | Self::Cc
120 | Self::ColorGain
121 | Self::Colorize
122 | Self::ColorCurves
123 | Self::GamutConvert
124 | Self::Invert
125 | Self::HueCurves
126 | Self::DeltaKeyer => ShaderDomain::Color,
127
128 Self::Blur
129 | Self::BlurH
130 | Self::BlurV
131 | Self::DirBlur
132 | Self::VariBlur
133 | Self::GlowAdd
134 | Self::XGlowPrep
135 | Self::XGlowAccum
136 | Self::Filter
137 | Self::FilmGrain
138 | Self::RemoveNoise => ShaderDomain::BlurGlow,
139
140 Self::Transform
141 | Self::Displace
142 | Self::XfChroma
143 | Self::Crop
144 | Self::Homography
145 | Self::Vortex
146 | Self::KScope => ShaderDomain::Transform,
147
148 Self::MaskShape
149 | Self::MaskCombine
150 | Self::MaskApply
151 | Self::BitmapMask => ShaderDomain::Masks,
152
153 Self::LumaKey
154 | Self::FastNoise
155 | Self::OutlineTint
156 | Self::OutlineComposite
157 | Self::CustomWave
158 | Self::UltraKeyer
159 | Self::Plasma => ShaderDomain::KeyersGen,
160
161 Self::Drip
162 | Self::Dent
163 | Self::PerspectivePos
164 | Self::DaySky
165 | Self::GridWarp
166 | Self::CheckerPiece
167 | Self::AlphaWeightedNoise
168 | Self::Crystallize
169 | Self::HexagonTiles => ShaderDomain::ArchiveFx,
170 }
171 }
172
173 pub(super) fn entry_point(self) -> &'static str {
174 match self {
175 Self::Bg => "bg_op",
176 Self::Merge => "merge_op",
177 Self::Transform => "transform_op",
178 Self::Bc => "bc_op",
179 Self::Cc => "cc_op",
180 Self::ColorGain => "color_gain_op",
181 Self::LumaKey => "luma_key_op",
182 Self::Blur => "blur_op",
183 Self::BlurH => "blur_h_op",
184 Self::BlurV => "blur_v_op",
185 Self::DirBlur => "dir_blur_op",
186 Self::FastNoise => "fast_noise_op",
187 Self::Displace => "displace_op",
188 Self::MaskShape => "mask_shape_op",
189 Self::MaskCombine => "mask_combine_op",
190 Self::MaskApply => "mask_apply_op",
191 Self::BitmapMask => "bitmap_mask_op",
192 Self::Colorize => "colorize_op",
193 Self::ColorCurves => "color_curves_op",
194 Self::XfChroma => "xf_chroma_op",
195 Self::GamutConvert => "gamut_convert_op",
196 Self::VariBlur => "vari_blur_op",
197 Self::OutlineTint => "outline_tint",
198 Self::OutlineComposite => "outline_composite",
199 Self::CustomWave => "custom_wave_op",
200 Self::Crop => "crop_op",
201 Self::GlowAdd => "glow_add_op",
202 Self::XGlowPrep => "xglow_prep_op",
203 Self::XGlowAccum => "xglow_accum_op",
204 Self::DisplayBlit => "display_blit_op",
205 Self::Invert => "invert_op",
206 Self::ChannelBoolean => "channel_boolean_op",
207 Self::Filter => "filter_op",
208 Self::HueCurves => "hue_curves_op",
209 Self::UltraKeyer => "ultra_keyer_op",
210 Self::Dissolve => "dissolve_op",
211 Self::Homography => "homography_op",
212 Self::ShadowComp => "shadow_comp_op",
213 Self::Plasma => "plasma_op",
214 Self::FilmGrain => "film_grain_op",
215 Self::SetDomain => "set_domain_op",
216 Self::ChangeDepth => "change_depth_op",
217 Self::Vortex => "vortex_op",
218 Self::KScope => "kscope_op",
219 Self::Drip => "drip_op",
220 Self::Dent => "dent_op",
221 Self::PerspectivePos => "perspective_pos_op",
222 Self::DaySky => "day_sky_op",
223 Self::GridWarp => "grid_warp_op",
224 Self::CheckerPiece => "checker_piece_op",
225 Self::AlphaWeightedNoise => "alpha_weighted_noise_op",
226 Self::Crystallize => "crystallize_op",
227 Self::HexagonTiles => "hexagon_tiles_op",
228 Self::RemoveNoise => "remove_noise_op",
229 Self::DeltaKeyer => "delta_keyer_op",
230 }
231 }
232
233 pub(super) fn workgroup_size(self) -> [u32; 2] {
234 match self {
235 Self::BlurH => [32, 4],
236 Self::BlurV => [4, 32],
237 _ => [8, 8],
238 }
239 }
240}
241
242const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl");
243const UNIFORM_SLOTS_PER_CHUNK: u32 = 1024;
244const LUT_CACHE_CAPACITY: usize = 64;
245#[cfg(not(target_arch = "wasm32"))]
246const MAX_READBACK_BUFFERS: usize = 3;
247const BIND_GROUP_CACHE_CAPACITY: usize = 128;
248
249/// Core compositor ops present in virtually every comp, pre-warmed by `prewarm_core`.
250const CORE_PREWARM_OPS: &[ShaderOp] = &[
251 ShaderOp::Bg,
252 ShaderOp::Merge,
253 ShaderOp::DisplayBlit,
254 ShaderOp::ChannelBoolean,
255 ShaderOp::Dissolve,
256 ShaderOp::ShadowComp,
257 ShaderOp::SetDomain,
258 ShaderOp::ChangeDepth,
259 ShaderOp::Bc,
260 ShaderOp::Cc,
261 ShaderOp::ColorGain,
262 ShaderOp::Colorize,
263 ShaderOp::ColorCurves,
264 ShaderOp::GamutConvert,
265 ShaderOp::Invert,
266 ShaderOp::Blur,
267 ShaderOp::BlurH,
268 ShaderOp::BlurV,
269 ShaderOp::DirBlur,
270 ShaderOp::GlowAdd,
271 ShaderOp::XGlowPrep,
272 ShaderOp::XGlowAccum,
273 ShaderOp::Transform,
274 ShaderOp::Displace,
275 ShaderOp::Crop,
276 ShaderOp::MaskShape,
277 ShaderOp::MaskCombine,
278 ShaderOp::MaskApply,
279 ShaderOp::BitmapMask,
280 ShaderOp::LumaKey,
281 ShaderOp::FastNoise,
282];
283
284fn build_domain_wgsl(domain: ShaderDomain, format: wgpu::TextureFormat, hdr_float: bool) -> String {
285 let domain_src = domain.source();
286 let mut src = String::with_capacity(COMMON_WGSL.len() + domain_src.len() + 1);
287 src.push_str(COMMON_WGSL);
288 src.push('\n');
289 src.push_str(domain_src);
290 let storage_fmt = match format {
291 wgpu::TextureFormat::Rgba16Float => "rgba16float",
292 wgpu::TextureFormat::Rgba32Float => "rgba32float",
293 _ => "rgba8unorm",
294 };
295 if storage_fmt != "rgba8unorm" {
296 src = src.replace(
297 "texture_storage_2d<rgba8unorm, write>",
298 &format!("texture_storage_2d<{storage_fmt}, write>"),
299 );
300 }
301 if hdr_float {
302 src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;");
303 }
304 src
305}
306
307struct BindGroupKey {
308 src_a: wgpu::TextureView,
309 src_b: wgpu::TextureView,
310 mask: wgpu::TextureView,
311 dst_view: wgpu::TextureView,
312 chunk_idx: usize,
313}
314
315impl BindGroupKey {
316 fn matches(
317 &self,
318 src_a: &wgpu::TextureView,
319 src_b: &wgpu::TextureView,
320 mask: &wgpu::TextureView,
321 dst_view: &wgpu::TextureView,
322 chunk_idx: usize,
323 ) -> bool {
324 self.chunk_idx == chunk_idx
325 && &self.src_a == src_a
326 && &self.src_b == src_b
327 && &self.mask == mask
328 && &self.dst_view == dst_view
329 }
330}
331
332pub(super) struct BindGroupEntry {
333 key: BindGroupKey,
334 pub(super) bg: wgpu::BindGroup,
335 last_used: u64,
336}
337
338fn hash_bind_group_key(
339 src_a: &wgpu::TextureView,
340 src_b: &wgpu::TextureView,
341 mask: &wgpu::TextureView,
342 dst_view: &wgpu::TextureView,
343 chunk_idx: usize,
344) -> u64 {
345 use std::hash::{Hash, Hasher};
346 let mut h = std::collections::hash_map::DefaultHasher::new();
347 src_a.hash(&mut h);
348 src_b.hash(&mut h);
349 mask.hash(&mut h);
350 dst_view.hash(&mut h);
351 chunk_idx.hash(&mut h);
352 h.finish()
353}
354
355#[cfg(not(target_arch = "wasm32"))]
356#[derive(Default)]
357pub(super) struct ReadbackPool {
358 buffers: Vec<wgpu::Buffer>,
359 conv_tex: Option<CachedTexture>,
360}
361
362#[cfg(not(target_arch = "wasm32"))]
363impl ReadbackPool {
364 pub(super) fn acquire_buffer(&mut self, device: &wgpu::Device, required_bytes: u64) -> wgpu::Buffer {
365 let max_reuse_bytes = required_bytes.saturating_mul(2).max(64 * 1024);
366 if let Some((idx, _)) = self
367 .buffers
368 .iter()
369 .enumerate()
370 .filter(|(_, b)| {
371 let sz = b.size();
372 sz >= required_bytes && sz <= max_reuse_bytes
373 })
374 .min_by_key(|(_, b)| b.size())
375 {
376 return self.buffers.remove(idx);
377 }
378 device.create_buffer(&wgpu::BufferDescriptor {
379 label: Some("readback"),
380 size: required_bytes.max(4),
381 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
382 mapped_at_creation: false,
383 })
384 }
385
386 pub(super) fn return_buffer(&mut self, buf: wgpu::Buffer) {
387 if self.buffers.len() >= MAX_READBACK_BUFFERS {
388 self.buffers.remove(0);
389 }
390 self.buffers.push(buf);
391 }
392
393 pub(super) fn acquire_conv_tex(&mut self, device: &wgpu::Device, size: [u32; 2]) -> CachedTexture {
394 let max_dim = device.limits().max_texture_dimension_2d.max(1);
395 let (clamped, _) = crate::cache::clamp_dims_to_limit(size[0], size[1], max_dim);
396 if let Some(tex) = &self.conv_tex
397 && tex.size == clamped
398 {
399 return tex.clone();
400 }
401 let tex = super::dispatch::create_texture(device, clamped, 0);
402 self.conv_tex = Some(tex.clone());
403 tex
404 }
405
406 pub(super) fn clear(&mut self) {
407 self.buffers.clear();
408 self.conv_tex = None;
409 }
410
411 #[cfg(test)]
412 pub(super) fn buffer_count(&self) -> usize {
413 self.buffers.len()
414 }
415
416 #[cfg(test)]
417 pub(super) fn conv_tex_ptr(&self) -> Option<*const wgpu::Texture> {
418 self.conv_tex
419 .as_ref()
420 .map(|t| std::sync::Arc::as_ptr(&t.texture))
421 }
422}
423
424struct LutCacheEntry {
425 size: [u32; 2],
426 format: wgpu::TextureFormat,
427 hash: u64,
428 bytes: Vec<u8>,
429 tex: CachedTexture,
430 last_used: u64,
431}
432
433pub(super) struct ShaderRegistry {
434 format: wgpu::TextureFormat,
435 hdr_float: bool,
436 pub(super) bgl: wgpu::BindGroupLayout,
437 pl: wgpu::PipelineLayout,
438 pub(super) sampler: wgpu::Sampler,
439 pub(super) modules: HashMap<ShaderDomain, wgpu::ShaderModule>,
440 pub(super) pipelines: HashMap<ShaderOp, wgpu::ComputePipeline>,
441 pub(super) uniform_stride: u32,
442 pub(super) uniform_chunks: Vec<wgpu::Buffer>,
443 uniform_cursor: u32,
444 lut_cache: Vec<LutCacheEntry>,
445 lut_tick: u64,
446 pub(super) lut_hits: u64,
447 pub(super) lut_misses: u64,
448 bg_cache: HashMap<u64, Vec<BindGroupEntry>>,
449 bg_count: usize,
450 bg_tick: u64,
451 pub(super) bg_hits: u64,
452 pub(super) bg_misses: u64,
453 #[cfg(not(target_arch = "wasm32"))]
454 pub(super) readback_pool: ReadbackPool,
455}
456
457impl ShaderRegistry {
458 pub(super) fn new(device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) -> Self {
459 let uniform_size = std::mem::size_of::<super::dispatch::UniformParams>() as u32;
460 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
461 let uniform_stride = uniform_size.div_ceil(min_align) * min_align;
462
463 let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
464 binding,
465 visibility: wgpu::ShaderStages::COMPUTE,
466 ty: wgpu::BindingType::Texture {
467 sample_type: wgpu::TextureSampleType::Float { filterable: true },
468 view_dimension: wgpu::TextureViewDimension::D2,
469 multisampled: false,
470 },
471 count: None,
472 };
473 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
474 label: Some("compositor-bgl"),
475 entries: &[
476 tex_entry(0),
477 tex_entry(1),
478 tex_entry(2),
479 wgpu::BindGroupLayoutEntry {
480 binding: 3,
481 visibility: wgpu::ShaderStages::COMPUTE,
482 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
483 count: None,
484 },
485 wgpu::BindGroupLayoutEntry {
486 binding: 4,
487 visibility: wgpu::ShaderStages::COMPUTE,
488 ty: wgpu::BindingType::StorageTexture {
489 access: wgpu::StorageTextureAccess::WriteOnly,
490 format,
491 view_dimension: wgpu::TextureViewDimension::D2,
492 },
493 count: None,
494 },
495 wgpu::BindGroupLayoutEntry {
496 binding: 5,
497 visibility: wgpu::ShaderStages::COMPUTE,
498 ty: wgpu::BindingType::Buffer {
499 ty: wgpu::BufferBindingType::Uniform,
500 has_dynamic_offset: true,
501 min_binding_size: NonZeroU64::new(u64::from(uniform_size)),
502 },
503 count: None,
504 },
505 ],
506 });
507
508 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
509 label: Some("compositor-pl"),
510 bind_group_layouts: &[Some(&bgl)],
511 immediate_size: 0,
512 });
513
514 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
515 label: Some("compositor-linear"),
516 address_mode_u: wgpu::AddressMode::ClampToEdge,
517 address_mode_v: wgpu::AddressMode::ClampToEdge,
518 mag_filter: wgpu::FilterMode::Linear,
519 min_filter: wgpu::FilterMode::Linear,
520 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
521 ..Default::default()
522 });
523
524 Self {
525 format,
526 hdr_float,
527 bgl,
528 pl,
529 sampler,
530 modules: HashMap::new(),
531 pipelines: HashMap::new(),
532 uniform_stride,
533 uniform_chunks: Vec::new(),
534 uniform_cursor: 0,
535 lut_cache: Vec::new(),
536 lut_tick: 0,
537 lut_hits: 0,
538 lut_misses: 0,
539 bg_cache: HashMap::with_capacity(BIND_GROUP_CACHE_CAPACITY),
540 bg_count: 0,
541 bg_tick: 0,
542 bg_hits: 0,
543 bg_misses: 0,
544 #[cfg(not(target_arch = "wasm32"))]
545 readback_pool: ReadbackPool::default(),
546 }
547 }
548
549 /// Writes `params` into the next aligned slot in the chunked dynamic uniform ring
550 /// and returns `(chunk_index, dynamic_byte_offset)`.
551 ///
552 /// Lazily allocates 1,024-slot chunks without wrapping mid-encoder; callers reset the
553 /// cursor back to `0` after each `queue.submit` so normal frames stay in chunk `0`.
554 pub(super) fn alloc_uniform_slot(
555 &mut self,
556 device: &wgpu::Device,
557 queue: &wgpu::Queue,
558 params: &super::dispatch::UniformParams,
559 ) -> (usize, u32) {
560 let slot_global = self.uniform_cursor;
561 let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize;
562 let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK;
563 while chunk_idx >= self.uniform_chunks.len() {
564 let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
565 let buf = device.create_buffer(&wgpu::BufferDescriptor {
566 label: Some("op-params-ring"),
567 size,
568 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
569 mapped_at_creation: false,
570 });
571 self.uniform_chunks.push(buf);
572 }
573 let offset = slot_in_chunk * self.uniform_stride;
574 queue.write_buffer(
575 &self.uniform_chunks[chunk_idx],
576 u64::from(offset),
577 bytemuck::bytes_of(params),
578 );
579 self.uniform_cursor = slot_global + 1;
580 (chunk_idx, offset)
581 }
582
583 pub(super) fn reset_uniform_cursor(&mut self) {
584 self.uniform_cursor = 0;
585 }
586
587 pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
588 self.uniform_cursor = 0;
589 if self.uniform_chunks.len() > max_chunks {
590 self.uniform_chunks.truncate(max_chunks);
591 }
592 }
593
594 /// Returns a cached tiny LUT/curve texture for `(size, format, bytes)` or uploads and
595 /// inserts one into the bounded 64-entry LRU cache.
596 #[allow(clippy::too_many_arguments)]
597 pub(super) fn get_or_upload_lut_tex(
598 &mut self,
599 device: &wgpu::Device,
600 queue: &wgpu::Queue,
601 size: [u32; 2],
602 depth: model::BitDepth,
603 format: wgpu::TextureFormat,
604 bytes_per_row: u32,
605 bytes: &[u8],
606 ) -> CachedTexture {
607 use std::hash::{Hash, Hasher};
608 let mut hasher = std::collections::hash_map::DefaultHasher::new();
609 size.hash(&mut hasher);
610 format.hash(&mut hasher);
611 bytes.hash(&mut hasher);
612 let hash = hasher.finish();
613 self.lut_tick = self.lut_tick.wrapping_add(1);
614 let tick = self.lut_tick;
615
616 if let Some(entry) = self.lut_cache.iter_mut().find(|e| {
617 e.hash == hash && e.size == size && e.format == format && e.bytes.as_slice() == bytes
618 }) {
619 entry.last_used = tick;
620 self.lut_hits += 1;
621 return entry.tex.clone();
622 }
623
624 self.lut_misses += 1;
625 let tex = super::dispatch::create_texture_dod_fmt(
626 device,
627 size,
628 [0, 0],
629 size,
630 depth,
631 format,
632 hash,
633 );
634 queue.write_texture(
635 tex.texture.as_image_copy(),
636 bytes,
637 wgpu::TexelCopyBufferLayout {
638 offset: 0,
639 bytes_per_row: Some(bytes_per_row),
640 rows_per_image: Some(size[1]),
641 },
642 wgpu::Extent3d {
643 width: size[0],
644 height: size[1],
645 depth_or_array_layers: 1,
646 },
647 );
648 if self.lut_cache.len() >= LUT_CACHE_CAPACITY {
649 if let Some((evict_idx, _)) = self
650 .lut_cache
651 .iter()
652 .enumerate()
653 .min_by_key(|(_, e)| e.last_used)
654 {
655 self.lut_cache.swap_remove(evict_idx);
656 }
657 }
658 self.lut_cache.push(LutCacheEntry {
659 size,
660 format,
661 hash,
662 bytes: bytes.to_vec(),
663 tex: tex.clone(),
664 last_used: tick,
665 });
666 tex
667 }
668
669 /// Builds a `wgpu::BindGroup` for the four `TextureView` bindings and uniform `chunk_idx`
670 /// without inserting into `bg_cache` (used for ephemeral viewer/readback targets).
671 pub(super) fn create_bind_group(
672 &self,
673 device: &wgpu::Device,
674 src_a: &wgpu::TextureView,
675 src_b: &wgpu::TextureView,
676 mask: &wgpu::TextureView,
677 dst_view: &wgpu::TextureView,
678 chunk_idx: usize,
679 ) -> wgpu::BindGroup {
680 device.create_bind_group(&wgpu::BindGroupDescriptor {
681 label: Some("op-bg"),
682 layout: &self.bgl,
683 entries: &[
684 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
685 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
686 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
687 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) },
688 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) },
689 wgpu::BindGroupEntry {
690 binding: 5,
691 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
692 buffer: &self.uniform_chunks[chunk_idx],
693 offset: 0,
694 size: NonZeroU64::new(std::mem::size_of::<super::dispatch::UniformParams>() as u64),
695 }),
696 },
697 ],
698 })
699 }
700
701 /// Looks up or creates a cached `wgpu::BindGroup` keyed by the four `TextureView`
702 /// handles and dynamic-uniform `chunk_idx`. Holding cloned `TextureView` handles inside
703 /// cached entries keeps their underlying resources alive while cached, preventing ABA reuse.
704 pub(super) fn ensure_bind_group(
705 &mut self,
706 device: &wgpu::Device,
707 src_a: &wgpu::TextureView,
708 src_b: &wgpu::TextureView,
709 mask: &wgpu::TextureView,
710 dst_view: &wgpu::TextureView,
711 chunk_idx: usize,
712 ) -> (u64, usize) {
713 let hash = hash_bind_group_key(src_a, src_b, mask, dst_view, chunk_idx);
714 self.bg_tick = self.bg_tick.wrapping_add(1);
715 let tick = self.bg_tick;
716
717 if let Some(bucket) = self.bg_cache.get_mut(&hash)
718 && let Some((idx, entry)) = bucket
719 .iter_mut()
720 .enumerate()
721 .find(|(_, e)| e.key.matches(src_a, src_b, mask, dst_view, chunk_idx))
722 {
723 entry.last_used = tick;
724 self.bg_hits += 1;
725 return (hash, idx);
726 }
727
728 self.bg_misses += 1;
729 if self.bg_count >= BIND_GROUP_CACHE_CAPACITY {
730 let mut oldest_hash = None;
731 let mut oldest_idx = 0usize;
732 let mut oldest_tick = u64::MAX;
733 for (&h, bucket) in &self.bg_cache {
734 for (idx, entry) in bucket.iter().enumerate() {
735 if entry.last_used < oldest_tick {
736 oldest_tick = entry.last_used;
737 oldest_hash = Some(h);
738 oldest_idx = idx;
739 }
740 }
741 }
742 if let Some(h) = oldest_hash {
743 let empty = if let Some(bucket) = self.bg_cache.get_mut(&h) {
744 bucket.swap_remove(oldest_idx);
745 self.bg_count -= 1;
746 bucket.is_empty()
747 } else {
748 false
749 };
750 if empty {
751 self.bg_cache.remove(&h);
752 }
753 }
754 }
755
756 let bg = self.create_bind_group(device, src_a, src_b, mask, dst_view, chunk_idx);
757
758 let bucket = self.bg_cache.entry(hash).or_default();
759 let idx = bucket.len();
760 bucket.push(BindGroupEntry {
761 key: BindGroupKey {
762 src_a: src_a.clone(),
763 src_b: src_b.clone(),
764 mask: mask.clone(),
765 dst_view: dst_view.clone(),
766 chunk_idx,
767 },
768 bg,
769 last_used: tick,
770 });
771 self.bg_count += 1;
772 (hash, idx)
773 }
774
775 pub(super) fn get_bind_group(&self, hash: u64, idx: usize) -> &wgpu::BindGroup {
776 &self.bg_cache[&hash][idx].bg
777 }
778
779 pub(super) fn clear_bind_group_cache(&mut self) {
780 self.bg_cache.clear();
781 self.bg_count = 0;
782 }
783
784 #[cfg(test)]
785 pub(super) fn bg_entry_count(&self) -> usize {
786 self.bg_count
787 }
788
789 pub(super) fn ensure_pipeline(&mut self, device: &wgpu::Device, op: ShaderOp) {
790 if self.pipelines.contains_key(&op) {
791 return;
792 }
793 let domain = op.domain();
794 let format = self.format;
795 let hdr_float = self.hdr_float;
796 let module = self.modules.entry(domain).or_insert_with(|| {
797 let src = build_domain_wgsl(domain, format, hdr_float);
798 device.create_shader_module(wgpu::ShaderModuleDescriptor {
799 label: Some(domain.label()),
800 source: wgpu::ShaderSource::Wgsl(src.into()),
801 })
802 });
803
804 let entry = op.entry_point();
805 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
806 label: Some(entry),
807 layout: Some(&self.pl),
808 module,
809 entry_point: Some(entry),
810 compilation_options: Default::default(),
811 cache: None,
812 });
813 self.pipelines.insert(op, pipeline);
814 }
815
816 /// Pre-compiles core shader modules and compute pipelines (in parallel on native targets)
817 /// so initial frame evaluation does not stall on synchronous shader compilation.
818 pub(super) fn prewarm_core(&mut self, device: &wgpu::Device) {
819 #[cfg(target_arch = "wasm32")]
820 {
821 for &op in CORE_PREWARM_OPS {
822 self.ensure_pipeline(device, op);
823 }
824 }
825 #[cfg(not(target_arch = "wasm32"))]
826 {
827 let mut missing_domains = Vec::new();
828 for &op in CORE_PREWARM_OPS {
829 let d = op.domain();
830 if !self.modules.contains_key(&d) && !missing_domains.contains(&d) {
831 missing_domains.push(d);
832 }
833 }
834 if !missing_domains.is_empty() {
835 let format = self.format;
836 let hdr_float = self.hdr_float;
837 let built_modules: Vec<(ShaderDomain, wgpu::ShaderModule)> =
838 std::thread::scope(|s| {
839 let handles: Vec<_> = missing_domains
840 .into_iter()
841 .map(|domain| {
842 s.spawn(move || {
843 let src = build_domain_wgsl(domain, format, hdr_float);
844 let module = device.create_shader_module(
845 wgpu::ShaderModuleDescriptor {
846 label: Some(domain.label()),
847 source: wgpu::ShaderSource::Wgsl(src.into()),
848 },
849 );
850 (domain, module)
851 })
852 })
853 .collect();
854 handles
855 .into_iter()
856 .map(|h| h.join().expect("shader module compile thread panicked"))
857 .collect()
858 });
859 for (domain, module) in built_modules {
860 self.modules.insert(domain, module);
861 }
862 }
863
864 let missing_ops: Vec<ShaderOp> = CORE_PREWARM_OPS
865 .iter()
866 .copied()
867 .filter(|op| !self.pipelines.contains_key(op))
868 .collect();
869 if !missing_ops.is_empty() {
870 let pl = &self.pl;
871 let modules = &self.modules;
872 let n_workers = std::thread::available_parallelism()
873 .map(|n| n.get())
874 .unwrap_or(4)
875 .clamp(1, 8)
876 .min(missing_ops.len());
877 let chunk_size = missing_ops.len().div_ceil(n_workers);
878 let built_pipelines: Vec<(ShaderOp, wgpu::ComputePipeline)> =
879 std::thread::scope(|s| {
880 let handles: Vec<_> = missing_ops
881 .chunks(chunk_size)
882 .map(|chunk| {
883 s.spawn(move || {
884 chunk
885 .iter()
886 .map(|&op| {
887 let module = &modules[&op.domain()];
888 let entry = op.entry_point();
889 let pipe = device.create_compute_pipeline(
890 &wgpu::ComputePipelineDescriptor {
891 label: Some(entry),
892 layout: Some(pl),
893 module,
894 entry_point: Some(entry),
895 compilation_options: Default::default(),
896 cache: None,
897 },
898 );
899 (op, pipe)
900 })
901 .collect::<Vec<_>>()
902 })
903 })
904 .collect();
905 handles
906 .into_iter()
907 .flat_map(|h| h.join().expect("pipeline compile thread panicked"))
908 .collect()
909 });
910 for (op, pipe) in built_pipelines {
911 self.pipelines.insert(op, pipe);
912 }
913 }
914 }
915 }
916}
917
918#[cfg(test)]
919mod tests {
920 use super::*;
921 use crate::Engine;
922
923 #[test]
924 fn prewarm_core_pipelines_populates_core_ops_and_keeps_new_lazy() {
925 let Ok(eng) = Engine::new_headless() else {
926 return;
927 };
928 assert_eq!(eng.pipelines.borrow().modules.len(), 0);
929 assert_eq!(eng.pipelines.borrow().pipelines.len(), 0);
930
931 let t0 = std::time::Instant::now();
932 eng.prewarm_core_pipelines();
933 let prewarm_ms = t0.elapsed().as_secs_f64() * 1000.0;
934
935 let reg = eng.pipelines.borrow();
936 assert!(reg.modules.len() >= 6);
937 assert_eq!(reg.pipelines.len(), CORE_PREWARM_OPS.len());
938 for &op in CORE_PREWARM_OPS {
939 assert!(reg.pipelines.contains_key(&op));
940 }
941 let _ = prewarm_ms;
942 }
943
944 #[test]
945 fn uniform_ring_grows_past_16_chunks_without_wrapping_and_resets() {
946 let Ok(eng) = Engine::new_headless() else {
947 return;
948 };
949 let params = super::super::dispatch::UniformParams::default();
950 let mut reg = eng.pipelines.borrow_mut();
951
952 let total = 16 * UNIFORM_SLOTS_PER_CHUNK + 5;
953 let mut last = (0usize, 0u32);
954 for _ in 0..total {
955 last = reg.alloc_uniform_slot(&eng.device, &eng.queue, &params);
956 }
957 assert_eq!(last.0, 16, "cursor must grow to chunk 16 instead of wrapping to 0");
958 assert_eq!(last.1, 4 * reg.uniform_stride);
959 assert_eq!(reg.uniform_chunks.len(), 17);
960
961 reg.reset_uniform_cursor();
962 let after_reset = reg.alloc_uniform_slot(&eng.device, &eng.queue, &params);
963 assert_eq!(after_reset, (0, 0));
964
965 reg.trim_uniform_chunks(2);
966 assert_eq!(reg.uniform_chunks.len(), 2);
967 assert_eq!(reg.uniform_cursor, 0);
968 }
969
970 #[test]
971 fn prewarm_for_depth_warms_float16_in_hiq_only() {
972 let Ok(mut eng) = Engine::new_headless() else {
973 return;
974 };
975 eng.hiq = false;
976 eng.prewarm_for_depth(model::BitDepth::Float16);
977 assert_eq!(eng.pipelines.borrow().pipelines.len(), CORE_PREWARM_OPS.len());
978 assert!(eng.pipelines_f16.get().is_none());
979
980 eng.hiq = true;
981 eng.prewarm_for_depth(model::BitDepth::Float16);
982 let f16 = eng.pipelines_f16.get().expect("f16 registry initialized");
983 assert_eq!(f16.borrow().pipelines.len(), CORE_PREWARM_OPS.len());
984 }
985}