1//! GPU texture allocation, compute shader dispatch, readback, and viewer upload helpers.
2
3use std::cell::RefCell;
4#[cfg(not(target_arch = "wasm32"))]
5use std::time::Instant;
6#[cfg(target_arch = "wasm32")]
7use web_time::Instant;
8
9use bytemuck::{Pod, Zeroable};
10use model::BitDepth;
11
12use crate::cache::{AuxChannelTex, CachedTexture, EvalStats};
13
14use super::registry::{ShaderOp, ShaderRegistry};
15use super::{DisplaySettings, Engine};
16
17#[repr(C)]
18#[derive(Clone, Copy, Pod, Zeroable)]
19pub(super) struct UniformParams {
20 pub(super) p: [[f32; 4]; 16],
21}
22
23impl Default for UniformParams {
24 fn default() -> Self {
25 Self { p: [[0.0; 4]; 16] }
26 }
27}
28
29/// In-flight non-blocking GPU-to-CPU RGBA8 readback handle.
30///
31/// Created by [`Engine::begin_readback_rgba`] after submitting GPU conversion/copy commands
32/// and initiating `map_async`; completed by [`PendingReadback::finish`], which waits for
33/// mapping, copies tightly packed RGBA8 bytes, unmaps, and returns the staging buffer to the
34/// engine's reusable pool.
35pub struct PendingReadback {
36 #[cfg(not(target_arch = "wasm32"))]
37 buf: wgpu::Buffer,
38 #[cfg(not(target_arch = "wasm32"))]
39 submission_index: wgpu::SubmissionIndex,
40 #[cfg(not(target_arch = "wasm32"))]
41 rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
42 #[cfg(not(target_arch = "wasm32"))]
43 height: u32,
44 #[cfg(not(target_arch = "wasm32"))]
45 unpadded_bpr: u32,
46 #[cfg(not(target_arch = "wasm32"))]
47 padded_bpr: u32,
48 #[cfg(not(target_arch = "wasm32"))]
49 required_bytes: u64,
50}
51
52impl PendingReadback {
53 /// Waits for the in-flight GPU readback to complete, writes tightly packed RGBA8 bytes into
54 /// `dst` (reusing `dst`'s existing heap allocation), unmaps the staging buffer, and returns
55 /// it to `engine`'s reusable pool.
56 pub fn finish_into(
57 self,
58 engine: &Engine,
59 dst: &mut Vec<u8>,
60 ) -> Result<(), Box<dyn std::error::Error>> {
61 #[cfg(target_arch = "wasm32")]
62 {
63 let _ = (engine, dst);
64 Err("synchronous GPU readback is unavailable on wasm32".into())
65 }
66 #[cfg(not(target_arch = "wasm32"))]
67 {
68 // Poll non-blockingly first so already-completed readbacks fire immediately.
69 let _ = engine.device.poll(wgpu::PollType::Poll);
70 let map_res = match self.rx.try_recv() {
71 Ok(res) => res,
72 Err(std::sync::mpsc::TryRecvError::Empty) => {
73 engine.device.poll(wgpu::PollType::Wait {
74 submission_index: Some(self.submission_index),
75 timeout: Some(std::time::Duration::from_secs(10)),
76 })?;
77 self.rx.recv()?
78 }
79 Err(err @ std::sync::mpsc::TryRecvError::Disconnected) => return Err(err.into()),
80 };
81 map_res?;
82 let slice = self.buf.slice(..self.required_bytes);
83 let data = slice.get_mapped_range()?;
84 let total_bytes = (self.unpadded_bpr as usize)
85 .checked_mul(self.height as usize)
86 .ok_or("readback buffer size overflow")?;
87 dst.clear();
88 dst.reserve(total_bytes);
89 if self.padded_bpr == self.unpadded_bpr {
90 let src = data
91 .get(..total_bytes)
92 .ok_or("readback mapped buffer smaller than expected")?;
93 dst.extend_from_slice(src);
94 } else {
95 let padded_bpr = self.padded_bpr as usize;
96 let unpadded_bpr = self.unpadded_bpr as usize;
97 for row in 0..self.height as usize {
98 let start = row
99 .checked_mul(padded_bpr)
100 .ok_or("readback row offset overflow")?;
101 let end = start
102 .checked_add(unpadded_bpr)
103 .ok_or("readback row end overflow")?;
104 let src = data
105 .get(start..end)
106 .ok_or("readback mapped row out of bounds")?;
107 dst.extend_from_slice(src);
108 }
109 }
110 drop(data);
111 self.buf.unmap();
112 engine.pipelines.borrow_mut().readback_pool.return_buffer(self.buf);
113 Ok(())
114 }
115 }
116
117 /// Waits for the in-flight GPU readback to complete, reads back tightly packed RGBA8 bytes,
118 /// unmaps the staging buffer, and returns it to `engine`'s reusable pool.
119 pub fn finish(self, engine: &Engine) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
120 let mut out = Vec::new();
121 self.finish_into(engine, &mut out)?;
122 Ok(out)
123 }
124}
125
126impl Engine {
127 /// Pre-compiles core WGSL shader modules and compute pipelines (parallelized across worker
128 /// threads on native targets) so the first evaluated frame avoids synchronous shader stalls.
129 pub fn prewarm_core_pipelines(&self) {
130 self.pipelines.borrow_mut().prewarm_core(&self.device);
131 }
132
133 /// Pre-compiles core WGSL shader modules and compute pipelines for `Int8` (viewer/readback)
134 /// and `depth` when `hiq` is active (e.g. `BitDepth::Float16` for EXR/HiQ comps).
135 pub fn prewarm_for_depth(&self, depth: BitDepth) {
136 self.pipelines.borrow_mut().prewarm_core(&self.device);
137 let eff = self.effective_depth(depth);
138 if eff != BitDepth::Int8 {
139 self.pipelines_for(eff).borrow_mut().prewarm_core(&self.device);
140 }
141 }
142
143 pub(super) fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture {
144 self.alloc_tex_dod(size, [0, 0], size, depth, content_hash)
145 }
146
147 pub(super) fn alloc_tex_like(
148 &self,
149 src: &CachedTexture,
150 depth: BitDepth,
151 content_hash: u64,
152 ) -> CachedTexture {
153 let mut t = self.alloc_tex_dod(src.size, src.origin, src.canvas_size, depth, content_hash);
154 t.tex_scale = src.tex_scale;
155 t
156 }
157
158 pub(super) fn crop_to_canvas(&self, enc: &mut wgpu::CommandEncoder, tex: CachedTexture) -> CachedTexture {
159 if !tex.has_dod() {
160 return tex;
161 }
162 let mut cropped = self.alloc_tex(tex.canvas_size, tex.depth, tex.content_hash ^ 0xD0D0);
163 cropped.tex_scale = tex.tex_scale;
164 let mut params = UniformParams::default();
165 params.p[0] = [1.0, 1.0, 0.0, 0.0];
166 params.p[4] = [
167 tex.origin[0] as f32,
168 tex.origin[1] as f32,
169 tex.canvas_size[0] as f32,
170 tex.canvas_size[1] as f32,
171 ];
172 self.dispatch_op(
173 enc,
174 ShaderOp::DisplayBlit,
175 &tex.view,
176 &self.dummy.view,
177 &self.dummy.view,
178 &cropped,
179 &params,
180 );
181 if tex.aux.is_some() {
182 self.crop_aux_to_canvas(enc, &tex, &mut cropped);
183 }
184 cropped
185 }
186
187 pub(super) fn alloc_tex_dod(
188 &self,
189 size: [u32; 2],
190 origin: [i32; 2],
191 canvas_size: [u32; 2],
192 depth: BitDepth,
193 content_hash: u64,
194 ) -> CachedTexture {
195 let d = self.effective_depth(depth);
196 let fmt = self.texture_format_for(d);
197 self.cache
198 .acquire_texture_dod_fmt(&self.device, size, origin, canvas_size, d, fmt, content_hash)
199 }
200
201 pub(super) fn pipelines_for(&self, depth: BitDepth) -> &RefCell<ShaderRegistry> {
202 match depth {
203 BitDepth::Int8 => &self.pipelines,
204 BitDepth::Int16 => self.pipelines_int16.get_or_init(|| {
205 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, false))
206 }),
207 BitDepth::Float16 => self.pipelines_f16.get_or_init(|| {
208 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true))
209 }),
210 BitDepth::Float32 => {
211 if self.supports_f32_filter {
212 self.pipelines_f32.get_or_init(|| {
213 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba32Float, true))
214 })
215 } else {
216 self.pipelines_f16.get_or_init(|| {
217 RefCell::new(ShaderRegistry::new(&self.device, wgpu::TextureFormat::Rgba16Float, true))
218 })
219 }
220 }
221 }
222 }
223
224 /// Uploads a cached `RamFrame` directly into a viewer `wgpu::Texture` with full
225 /// `DisplaySettings` (exposure, gamma, channel isolate, zoom/pan) without evaluating the DAG.
226 pub fn render_ram_frame_into_viewer(
227 &self,
228 frame: &crate::ram_cache::RamFrame,
229 dst_texture: &wgpu::Texture,
230 display: DisplaySettings,
231 ) -> EvalStats {
232 let t0 = Instant::now();
233 let mut upload_slot = self.ram_upload_tex.borrow_mut();
234 let needs_alloc = upload_slot
235 .as_ref()
236 .is_none_or(|t| t.size != frame.size);
237 if needs_alloc {
238 let max_dim = self.device.limits().max_texture_dimension_2d.max(1);
239 let (clamped, _) = crate::cache::clamp_dims_to_limit(frame.size[0], frame.size[1], max_dim);
240 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
241 label: Some("ram-viewer-upload"),
242 size: wgpu::Extent3d {
243 width: clamped[0],
244 height: clamped[1],
245 depth_or_array_layers: 1,
246 },
247 mip_level_count: 1,
248 sample_count: 1,
249 dimension: wgpu::TextureDimension::D2,
250 format: wgpu::TextureFormat::Rgba8Unorm,
251 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
252 view_formats: &[],
253 });
254 *upload_slot = Some(CachedTexture::from_texture(tex, clamped, 0));
255 }
256 let src = upload_slot.as_ref().expect("ram upload texture initialized");
257 if src.size == frame.size {
258 self.queue.write_texture(
259 src.texture.as_image_copy(),
260 &frame.rgba,
261 wgpu::TexelCopyBufferLayout {
262 offset: 0,
263 bytes_per_row: Some(frame.size[0] * 4),
264 rows_per_image: Some(frame.size[1]),
265 },
266 wgpu::Extent3d {
267 width: frame.size[0],
268 height: frame.size[1],
269 depth_or_array_layers: 1,
270 },
271 );
272 }
273 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
274 label: Some("comp-ram-viewer-blit"),
275 });
276 let dst_size = [dst_texture.width(), dst_texture.height()];
277 let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default());
278 let mut params = UniformParams::default();
279 params.p[0] = [
280 2.0_f32.powf(display.exposure),
281 display.gamma,
282 display.channel as f32,
283 if display.checker_bg { 1.0 } else { 0.0 },
284 ];
285 params.p[1] = display.uv_rect;
286 params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0];
287 self.dispatch_to_view_uncached(
288 &mut encoder,
289 ShaderOp::DisplayBlit,
290 &src.view,
291 &self.dummy.view,
292 &self.dummy.view,
293 &dst_view,
294 dst_size,
295 &params,
296 );
297 self.queue.submit(Some(encoder.finish()));
298 self.reset_uniform_cursors();
299
300 EvalStats {
301 eval_ms: t0.elapsed().as_secs_f64() * 1000.0,
302 cache_hits: 1,
303 cached_entries: self.cache.entry_count(),
304 cached_vram_mb: self.vram_mb(),
305 media_entries: self.media.entry_count(),
306 media_mb: self.media.total_mb(),
307 ..EvalStats::default()
308 }
309 }
310
311 #[cfg(not(target_arch = "wasm32"))]
312 fn encode_and_submit_readback(
313 &self,
314 mut enc: wgpu::CommandEncoder,
315 texture: &wgpu::Texture,
316 size: [u32; 2],
317 bpp: u32,
318 ) -> Result<PendingReadback, Box<dyn std::error::Error>> {
319 let [w, h] = size;
320 let unpadded_bpr = w.checked_mul(bpp).ok_or("readback row size overflow")?;
321 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
322 let padded_bpr = unpadded_bpr
323 .div_ceil(align)
324 .checked_mul(align)
325 .ok_or("readback padded row size overflow")?;
326 let required_bytes = u64::from(padded_bpr)
327 .checked_mul(u64::from(h))
328 .ok_or("readback buffer size overflow")?;
329 let buf = self
330 .pipelines
331 .borrow_mut()
332 .readback_pool
333 .acquire_buffer(&self.device, required_bytes);
334
335 enc.copy_texture_to_buffer(
336 texture.as_image_copy(),
337 wgpu::TexelCopyBufferInfo {
338 buffer: &buf,
339 layout: wgpu::TexelCopyBufferLayout {
340 offset: 0,
341 bytes_per_row: Some(padded_bpr),
342 rows_per_image: Some(h),
343 },
344 },
345 wgpu::Extent3d {
346 width: w,
347 height: h,
348 depth_or_array_layers: 1,
349 },
350 );
351 let submission_index = self.queue.submit(Some(enc.finish()));
352 self.reset_uniform_cursors();
353
354 let slice = buf.slice(..required_bytes);
355 let (tx, rx) = std::sync::mpsc::channel();
356 slice.map_async(wgpu::MapMode::Read, move |res| {
357 let _ = tx.send(res);
358 });
359 Ok(PendingReadback {
360 buf,
361 submission_index,
362 rx,
363 height: h,
364 unpadded_bpr,
365 padded_bpr,
366 required_bytes,
367 })
368 }
369
370 #[cfg(not(target_arch = "wasm32"))]
371 pub(crate) fn begin_readback_raw(
372 &self,
373 texture: &wgpu::Texture,
374 size: [u32; 2],
375 bpp: u32,
376 ) -> Result<PendingReadback, Box<dyn std::error::Error>> {
377 let enc = self.device.create_command_encoder(&Default::default());
378 self.encode_and_submit_readback(enc, texture, size, bpp)
379 }
380
381 /// Starts an asynchronous GPU-to-CPU RGBA8 readback by encoding any Float16/Float32 ->
382 /// `Rgba8Unorm` conversion plus `copy_texture_to_buffer` into a pooled staging buffer,
383 /// submitting to the queue, and starting `map_async` without polling.
384 ///
385 /// Call [`PendingReadback::finish`] later to wait/read pixels and return the buffer to the pool.
386 #[allow(private_interfaces)]
387 pub fn begin_readback_rgba(&self, tex: &CachedTexture) -> Result<PendingReadback, Box<dyn std::error::Error>> {
388 #[cfg(target_arch = "wasm32")]
389 {
390 let _ = tex;
391 Err("synchronous GPU readback is unavailable on wasm32".into())
392 }
393 #[cfg(not(target_arch = "wasm32"))]
394 {
395 let needs_conv = tex.format != wgpu::TextureFormat::Rgba8Unorm;
396 let converted = if needs_conv {
397 let mut reg = self.pipelines.borrow_mut();
398 Some(reg.readback_pool.acquire_conv_tex(&self.device, tex.size))
399 } else {
400 None
401 };
402 let src_tex = converted.as_ref().unwrap_or(tex);
403 let mut enc = self.device.create_command_encoder(&Default::default());
404 if let Some(conv) = converted.as_ref() {
405 let mut params = UniformParams::default();
406 params.p[0] = [1.0, 1.0, 0.0, 0.0];
407 self.dispatch_to_view_uncached(
408 &mut enc,
409 ShaderOp::DisplayBlit,
410 &tex.view,
411 &self.dummy.view,
412 &self.dummy.view,
413 &conv.view,
414 conv.size,
415 &params,
416 );
417 }
418 self.encode_and_submit_readback(enc, &src_tex.texture, src_tex.size, 4)
419 }
420 }
421
422 /// Reads back a `CachedTexture` to CPU RGBA8 bytes (for CLI `render-check` / PNG export).
423 /// Automatically converts Float16 / Float32 working textures to clamped RGBA8 on GPU before readback.
424 /// Always `Err` on wasm32: a blocking map would trap the browser main thread.
425 pub fn readback_rgba(&self, tex: &CachedTexture) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
426 self.begin_readback_rgba(tex)?.finish(self)
427 }
428
429 #[cfg(not(target_arch = "wasm32"))]
430 pub(crate) fn rgba_f32_bpp(format: wgpu::TextureFormat) -> Result<u32, Box<dyn std::error::Error>> {
431 match format {
432 wgpu::TextureFormat::Rgba32Float => Ok(16),
433 wgpu::TextureFormat::Rgba16Float => Ok(8),
434 wgpu::TextureFormat::Rgba8Unorm => Ok(4),
435 other => Err(format!("unsupported texture format for linear f32 readback: {other:?}").into()),
436 }
437 }
438
439 #[cfg(not(target_arch = "wasm32"))]
440 pub(crate) fn decode_rgba_bytes_into_f32(
441 format: wgpu::TextureFormat,
442 size: [u32; 2],
443 raw: &[u8],
444 out: &mut Vec<f32>,
445 ) -> Result<(), Box<dyn std::error::Error>> {
446 let px_count = (size[0] as usize)
447 .checked_mul(size[1] as usize)
448 .ok_or("readback pixel count overflow")?;
449 let float_count = px_count
450 .checked_mul(4)
451 .ok_or("readback float count overflow")?;
452 out.clear();
453 out.reserve(float_count);
454 match format {
455 wgpu::TextureFormat::Rgba32Float => {
456 let expected = float_count
457 .checked_mul(4)
458 .ok_or("readback byte count overflow")?;
459 if raw.len() != expected {
460 return Err(format!(
461 "Rgba32Float readback size mismatch: expected {expected} bytes, got {}",
462 raw.len()
463 )
464 .into());
465 }
466 for c in raw.chunks_exact(4) {
467 out.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]]));
468 }
469 }
470 wgpu::TextureFormat::Rgba16Float => {
471 let expected = float_count
472 .checked_mul(2)
473 .ok_or("readback byte count overflow")?;
474 if raw.len() != expected {
475 return Err(format!(
476 "Rgba16Float readback size mismatch: expected {expected} bytes, got {}",
477 raw.len()
478 )
479 .into());
480 }
481 for c in raw.chunks_exact(2) {
482 let bits = u16::from_le_bytes([c[0], c[1]]);
483 out.push(::exr::prelude::f16::from_bits(bits).to_f32());
484 }
485 }
486 wgpu::TextureFormat::Rgba8Unorm => {
487 if raw.len() != float_count {
488 return Err(format!(
489 "Rgba8Unorm readback size mismatch: expected {float_count} bytes, got {}",
490 raw.len()
491 )
492 .into());
493 }
494 for &b in raw {
495 out.push(f32::from(b) / 255.0);
496 }
497 }
498 other => {
499 return Err(
500 format!("unsupported texture format for linear f32 readback: {other:?}").into(),
501 );
502 }
503 }
504 Ok(())
505 }
506
507 #[cfg(not(target_arch = "wasm32"))]
508 pub(crate) fn decode_z_bytes_into_f32(
509 size: [u32; 2],
510 raw: &[u8],
511 out: &mut Vec<f32>,
512 ) -> Result<(), Box<dyn std::error::Error>> {
513 let px_count = (size[0] as usize)
514 .checked_mul(size[1] as usize)
515 .ok_or("Z readback pixel count overflow")?;
516 let expected = px_count
517 .checked_mul(4)
518 .ok_or("Z readback byte count overflow")?;
519 if raw.len() != expected {
520 return Err(format!(
521 "R32Float Z readback size mismatch: expected {expected} bytes, got {}",
522 raw.len()
523 )
524 .into());
525 }
526 out.clear();
527 out.reserve(px_count);
528 for c in raw.chunks_exact(4) {
529 out.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]]));
530 }
531 Ok(())
532 }
533
534 /// Reads back a `CachedTexture` to CPU linear HDR `f32` RGBA samples (`4 floats/px`),
535 /// preserving full float precision (`> 1.0` and negatives) for `Rgba32Float` and `Rgba16Float`.
536 /// Always `Err` on wasm32: a blocking map would trap the browser main thread.
537 pub fn readback_rgba_f32(&self, tex: &CachedTexture) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
538 #[cfg(target_arch = "wasm32")]
539 {
540 let _ = tex;
541 Err("synchronous GPU readback is unavailable on wasm32".into())
542 }
543 #[cfg(not(target_arch = "wasm32"))]
544 {
545 let bpp = Self::rgba_f32_bpp(tex.format)?;
546 let raw = self.begin_readback_raw(&tex.texture, tex.size, bpp)?.finish(self)?;
547 let mut out = Vec::new();
548 Self::decode_rgba_bytes_into_f32(tex.format, tex.size, &raw, &mut out)?;
549 Ok(out)
550 }
551 }
552
553 /// Reads back an `R32Float` auxiliary `Z` texture (`4 bytes/px`) into linear `Vec<f32>`,
554 /// preserving exact `-1e30` empty-sky sentinel and negative eye-space depths.
555 /// Always `Err` on wasm32.
556 pub fn readback_aux_z_f32(
557 &self,
558 z_tex: &AuxChannelTex,
559 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
560 #[cfg(target_arch = "wasm32")]
561 {
562 let _ = z_tex;
563 Err("synchronous GPU readback is unavailable on wasm32".into())
564 }
565 #[cfg(not(target_arch = "wasm32"))]
566 {
567 if z_tex.format != wgpu::TextureFormat::R32Float {
568 return Err(format!(
569 "expected R32Float for Z aux channel, got {:?}",
570 z_tex.format
571 )
572 .into());
573 }
574 let raw = self.begin_readback_raw(&z_tex.texture, z_tex.size, 4)?.finish(self)?;
575 let mut out = Vec::new();
576 Self::decode_z_bytes_into_f32(z_tex.size, &raw, &mut out)?;
577 Ok(out)
578 }
579 }
580
581 /// Reads back an RGBA auxiliary channel texture (e.g. `Normal` / `Vector` `Rgba16Float`)
582 /// into linear `Vec<f32>` (`4 floats/px`). Always `Err` on wasm32.
583 pub fn readback_aux_rgba_f32(
584 &self,
585 aux_tex: &AuxChannelTex,
586 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
587 #[cfg(target_arch = "wasm32")]
588 {
589 let _ = aux_tex;
590 Err("synchronous GPU readback is unavailable on wasm32".into())
591 }
592 #[cfg(not(target_arch = "wasm32"))]
593 {
594 let bpp = Self::rgba_f32_bpp(aux_tex.format)?;
595 let raw = self
596 .begin_readback_raw(&aux_tex.texture, aux_tex.size, bpp)?
597 .finish(self)?;
598 let mut out = Vec::new();
599 Self::decode_rgba_bytes_into_f32(aux_tex.format, aux_tex.size, &raw, &mut out)?;
600 Ok(out)
601 }
602 }
603
604 #[allow(clippy::too_many_arguments)]
605 fn dispatch_with_registry(
606 &self,
607 reg_cell: &RefCell<ShaderRegistry>,
608 enc: &mut wgpu::CommandEncoder,
609 op: ShaderOp,
610 src_a: &wgpu::TextureView,
611 src_b: &wgpu::TextureView,
612 mask: &wgpu::TextureView,
613 dst_view: &wgpu::TextureView,
614 dst_size: [u32; 2],
615 params: &UniformParams,
616 cache_bg: bool,
617 ) {
618 let (dynamic_offset, uncached_bg, cached_key) = {
619 let mut reg = reg_cell.borrow_mut();
620 reg.ensure_pipeline(&self.device, op);
621 let (chunk_idx, dynamic_offset) = reg.alloc_uniform_slot(&self.device, &self.queue, params);
622 if cache_bg {
623 let (bg_hash, bg_idx) = reg.ensure_bind_group(
624 &self.device,
625 src_a,
626 src_b,
627 mask,
628 dst_view,
629 chunk_idx,
630 );
631 (dynamic_offset, None, Some((bg_hash, bg_idx)))
632 } else {
633 let bg = reg.create_bind_group(
634 &self.device,
635 src_a,
636 src_b,
637 mask,
638 dst_view,
639 chunk_idx,
640 );
641 (dynamic_offset, Some(bg), None)
642 }
643 };
644 let reg = reg_cell.borrow();
645 let bg = match (&uncached_bg, cached_key) {
646 (Some(bg), _) => bg,
647 (None, Some((bg_hash, bg_idx))) => reg.get_bind_group(bg_hash, bg_idx),
648 (None, None) => unreachable!(),
649 };
650
651 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
652 label: Some("comp-op"),
653 timestamp_writes: None,
654 });
655 pass.set_pipeline(&reg.pipelines[&op]);
656 pass.set_bind_group(0, bg, &[dynamic_offset]);
657 let wg = op.workgroup_size();
658 pass.dispatch_workgroups(dst_size[0].div_ceil(wg[0]), dst_size[1].div_ceil(wg[1]), 1);
659 }
660
661 #[allow(clippy::too_many_arguments)]
662 pub(super) fn dispatch_op(
663 &self,
664 enc: &mut wgpu::CommandEncoder,
665 op: ShaderOp,
666 src_a: &wgpu::TextureView,
667 src_b: &wgpu::TextureView,
668 mask: &wgpu::TextureView,
669 dst: &CachedTexture,
670 params: &UniformParams,
671 ) {
672 self.dispatch_with_registry(
673 self.pipelines_for(dst.depth),
674 enc,
675 op,
676 src_a,
677 src_b,
678 mask,
679 &dst.view,
680 dst.size,
681 params,
682 true,
683 );
684 }
685
686 /// Dispatches a compute shader into an ephemeral `TextureView` (e.g. viewer surface or
687 /// one-shot readback conversion) without inserting into `bg_cache`.
688 #[allow(clippy::too_many_arguments)]
689 pub(super) fn dispatch_to_view_uncached(
690 &self,
691 enc: &mut wgpu::CommandEncoder,
692 op: ShaderOp,
693 src_a: &wgpu::TextureView,
694 src_b: &wgpu::TextureView,
695 mask: &wgpu::TextureView,
696 dst_view: &wgpu::TextureView,
697 dst_size: [u32; 2],
698 params: &UniformParams,
699 ) {
700 self.dispatch_with_registry(
701 &self.pipelines,
702 enc,
703 op,
704 src_a,
705 src_b,
706 mask,
707 dst_view,
708 dst_size,
709 params,
710 false,
711 );
712 }
713}
714
715pub fn create_texture(device: &wgpu::Device, size: [u32; 2], content_hash: u64) -> CachedTexture {
716 create_texture_dod(device, size, [0, 0], size, content_hash)
717}
718
719pub fn create_texture_dod(
720 device: &wgpu::Device,
721 size: [u32; 2],
722 origin: [i32; 2],
723 canvas_size: [u32; 2],
724 content_hash: u64,
725) -> CachedTexture {
726 create_texture_dod_fmt(
727 device,
728 size,
729 origin,
730 canvas_size,
731 BitDepth::Int8,
732 wgpu::TextureFormat::Rgba8Unorm,
733 content_hash,
734 )
735}
736
737pub fn create_texture_dod_fmt(
738 device: &wgpu::Device,
739 size: [u32; 2],
740 origin: [i32; 2],
741 canvas_size: [u32; 2],
742 depth: BitDepth,
743 format: wgpu::TextureFormat,
744 content_hash: u64,
745) -> CachedTexture {
746 let max_dim = device.limits().max_texture_dimension_2d.max(1);
747 let (clamped, tex_scale) = crate::cache::clamp_dims_to_limit(size[0], size[1], max_dim);
748 let eff_origin = if tex_scale < 1.0 {
749 [
750 (origin[0] as f32 * tex_scale).round() as i32,
751 (origin[1] as f32 * tex_scale).round() as i32,
752 ]
753 } else {
754 origin
755 };
756 let eff_canvas = if size == canvas_size {
757 clamped
758 } else if tex_scale < 1.0 {
759 [
760 ((canvas_size[0].max(1) as f32 * tex_scale).round() as u32).max(1),
761 ((canvas_size[1].max(1) as f32 * tex_scale).round() as u32).max(1),
762 ]
763 } else {
764 [canvas_size[0].max(1), canvas_size[1].max(1)]
765 };
766 let tex = device.create_texture(&wgpu::TextureDescriptor {
767 label: Some("comp-tex"),
768 size: wgpu::Extent3d {
769 width: clamped[0],
770 height: clamped[1],
771 depth_or_array_layers: 1,
772 },
773 mip_level_count: 1,
774 sample_count: 1,
775 dimension: wgpu::TextureDimension::D2,
776 format,
777 usage: wgpu::TextureUsages::TEXTURE_BINDING
778 | wgpu::TextureUsages::STORAGE_BINDING
779 | wgpu::TextureUsages::COPY_SRC
780 | wgpu::TextureUsages::COPY_DST
781 | wgpu::TextureUsages::RENDER_ATTACHMENT,
782 view_formats: &[],
783 });
784 let mut cached = CachedTexture::from_texture_dod_depth(
785 tex,
786 clamped,
787 eff_origin,
788 eff_canvas,
789 depth,
790 content_hash,
791 );
792 cached.tex_scale = tex_scale;
793 cached
794}
795
796#[cfg(test)]
797mod tests {
798 use super::*;
799 use crate::Engine;
800
801 #[test]
802 fn dynamic_uniform_ring_handles_over_1024_dispatches_in_single_encoder() {
803 let Ok(eng) = Engine::new_headless() else {
804 return;
805 };
806 let min_align = eng.device.limits().min_uniform_buffer_offset_alignment.max(1);
807 let stride = eng.pipelines.borrow().uniform_stride;
808 assert!(stride >= std::mem::size_of::<UniformParams>() as u32);
809 assert_eq!(stride % min_align, 0);
810
811 let out_first = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
812 let out_1023 = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
813 let out_1024 = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
814 let out_last = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
815 let scratch = eng.alloc_tex([4, 4], BitDepth::Int8, 0);
816
817 let bg_params = |rgba: [f32; 4]| {
818 let mut u = UniformParams::default();
819 u.p[0] = rgba;
820 u.p[1] = rgba;
821 u.p[2] = rgba;
822 u.p[3] = rgba;
823 u
824 };
825
826 let mut enc = eng.device.create_command_encoder(&Default::default());
827 let total = 1100usize;
828 for i in 0..total {
829 let (target, rgba) = match i {
830 0 => (&out_first, [0.2, 0.4, 0.6, 1.0]),
831 1023 => (&out_1023, [0.3, 0.7, 0.2, 1.0]),
832 1024 => (&out_1024, [0.8, 0.5, 0.1, 1.0]),
833 1099 => (&out_last, [0.1, 0.2, 0.9, 1.0]),
834 _ => (&scratch, [0.9, 0.1, 0.1, 1.0]),
835 };
836 eng.dispatch_op(
837 &mut enc,
838 ShaderOp::Bg,
839 &eng.dummy.view,
840 &eng.dummy.view,
841 &eng.dummy.view,
842 target,
843 &bg_params(rgba),
844 );
845 }
846 eng.queue.submit(Some(enc.finish()));
847 assert!(
848 eng.pipelines.borrow().uniform_chunks.len() >= 2,
849 "1,100 dispatches should allocate at least 2 uniform chunks"
850 );
851
852 let check = |tex: &CachedTexture, expected: [u8; 4], label: &str| {
853 let px = eng.readback_rgba(tex).expect("readback");
854 for (c, &want) in expected.iter().enumerate() {
855 assert!(
856 (px[c] as i32 - want as i32).abs() <= 1,
857 "{label} channel {c}: got {} expected {want}",
858 px[c]
859 );
860 }
861 };
862 check(&out_first, [51, 102, 153, 255], "dispatch 0");
863 check(&out_1023, [77, 179, 51, 255], "dispatch 1023");
864 check(&out_1024, [204, 128, 26, 255], "dispatch 1024");
865 check(&out_last, [26, 51, 230, 255], "dispatch 1099");
866 }
867
868 #[test]
869 fn begin_readback_rgba_matches_sync_and_reuses_pooled_resources() {
870 let Ok(eng) = Engine::new_headless() else {
871 return;
872 };
873 let fill = |tex: &CachedTexture, rgba: [f32; 4]| {
874 let mut enc = eng.device.create_command_encoder(&Default::default());
875 let mut u = UniformParams::default();
876 u.p[0] = rgba;
877 u.p[1] = rgba;
878 u.p[2] = rgba;
879 u.p[3] = rgba;
880 eng.dispatch_op(
881 &mut enc,
882 ShaderOp::Bg,
883 &eng.dummy.view,
884 &eng.dummy.view,
885 &eng.dummy.view,
886 tex,
887 &u,
888 );
889 eng.queue.submit(Some(enc.finish()));
890 };
891
892 // 1. Non-256B-aligned RGBA8 + aligned RGBA8
893 let tex_unaligned = eng.alloc_tex([13, 7], BitDepth::Int8, 0);
894 fill(&tex_unaligned, [0.2, 0.4, 0.6, 1.0]);
895 let sync_unaligned = eng.readback_rgba(&tex_unaligned).expect("sync unaligned");
896 let async_unaligned = eng
897 .begin_readback_rgba(&tex_unaligned)
898 .expect("begin unaligned")
899 .finish(&eng)
900 .expect("finish unaligned");
901 assert_eq!(sync_unaligned, async_unaligned);
902
903 let tex_aligned = eng.alloc_tex([64, 8], BitDepth::Int8, 0);
904 fill(&tex_aligned, [0.8, 0.1, 0.3, 0.9]);
905 let sync_aligned = eng.readback_rgba(&tex_aligned).expect("sync aligned");
906 let async_aligned = eng
907 .begin_readback_rgba(&tex_aligned)
908 .expect("begin aligned")
909 .finish(&eng)
910 .expect("finish aligned");
911 assert_eq!(sync_aligned, async_aligned);
912
913 // 2. Float16 conversion texture reuse + double-buffered overlapping readbacks
914 let f16_a = eng.alloc_tex([19, 11], BitDepth::Float16, 0);
915 let f16_b = eng.alloc_tex([19, 11], BitDepth::Float16, 0);
916 fill(&f16_a, [0.15, 0.55, 0.85, 1.0]);
917 fill(&f16_b, [0.95, 0.25, 0.10, 0.75]);
918
919 let expected_a = eng.readback_rgba(&f16_a).expect("sync f16 a");
920 let conv_ptr_1 = eng
921 .pipelines
922 .borrow()
923 .readback_pool
924 .conv_tex_ptr()
925 .expect("conv tex initialized");
926 let expected_b = eng.readback_rgba(&f16_b).expect("sync f16 b");
927 let conv_ptr_2 = eng
928 .pipelines
929 .borrow()
930 .readback_pool
931 .conv_tex_ptr()
932 .expect("conv tex retained");
933 assert_eq!(conv_ptr_1, conv_ptr_2, "conversion texture should be reused for matching size");
934
935 // Overlapping double-buffered async readbacks: start both before finishing either!
936 let pend_a = eng.begin_readback_rgba(&f16_a).expect("begin f16 a");
937 let pend_b = eng.begin_readback_rgba(&f16_b).expect("begin f16 b");
938 let got_a = pend_a.finish(&eng).expect("finish f16 a");
939 let got_b = pend_b.finish(&eng).expect("finish f16 b");
940 assert_eq!(got_a, expected_a);
941 assert_eq!(got_b, expected_b);
942
943 // Pool stays bounded at <= 3 buffers.
944 assert!(eng.pipelines.borrow().readback_pool.buffer_count() <= 3);
945 assert!(eng.pipelines.borrow().readback_pool.buffer_count() >= 1);
946 }
947
948 #[test]
949 fn bind_group_cache_hits_and_stays_bounded() {
950 let Ok(eng) = Engine::new_headless() else {
951 return;
952 };
953 let texs: Vec<CachedTexture> = (0..140)
954 .map(|_| eng.alloc_tex([4, 4], BitDepth::Int8, 0))
955 .collect();
956 let mut enc = eng.device.create_command_encoder(&Default::default());
957 let mut u = UniformParams::default();
958 u.p[0] = [0.25, 0.5, 0.75, 1.0];
959
960 // Dispatch twice to texs[0]: 1 miss, 1 hit.
961 for _ in 0..2 {
962 eng.dispatch_op(
963 &mut enc,
964 ShaderOp::Bg,
965 &eng.dummy.view,
966 &eng.dummy.view,
967 &eng.dummy.view,
968 &texs[0],
969 &u,
970 );
971 }
972 assert_eq!(eng.pipelines.borrow().bg_misses, 1);
973 assert_eq!(eng.pipelines.borrow().bg_hits, 1);
974
975 // Dispatch across 140 distinct textures: cache must remain capped at 128.
976 for t in &texs[1..] {
977 eng.dispatch_op(
978 &mut enc,
979 ShaderOp::Bg,
980 &eng.dummy.view,
981 &eng.dummy.view,
982 &eng.dummy.view,
983 t,
984 &u,
985 );
986 }
987 eng.queue.submit(Some(enc.finish()));
988 assert!(eng.pipelines.borrow().bg_entry_count() <= 128);
989
990 eng.pipelines.borrow_mut().clear_bind_group_cache();
991 assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0);
992 }
993
994 #[test]
995 fn pending_readback_tracks_submission_index_and_bypasses_bg_cache() {
996 let Ok(eng) = Engine::new_headless() else {
997 return;
998 };
999 let fill = |tex: &CachedTexture, rgba: [f32; 4]| {
1000 let mut enc = eng.device.create_command_encoder(&Default::default());
1001 let mut u = UniformParams::default();
1002 u.p[0] = rgba;
1003 u.p[1] = rgba;
1004 u.p[2] = rgba;
1005 u.p[3] = rgba;
1006 eng.dispatch_op(
1007 &mut enc,
1008 ShaderOp::Bg,
1009 &eng.dummy.view,
1010 &eng.dummy.view,
1011 &eng.dummy.view,
1012 tex,
1013 &u,
1014 );
1015 eng.queue.submit(Some(enc.finish()));
1016 eng.reset_uniform_cursors();
1017 };
1018
1019 let f16_a = eng.alloc_tex([16, 16], BitDepth::Float16, 0);
1020 let f16_b = eng.alloc_tex([16, 16], BitDepth::Float16, 0);
1021 fill(&f16_a, [0.2, 0.4, 0.8, 1.0]);
1022 fill(&f16_b, [0.9, 0.1, 0.5, 1.0]);
1023
1024 eng.pipelines.borrow_mut().clear_bind_group_cache();
1025 let misses_before = eng.pipelines.borrow().bg_misses;
1026
1027 // Overlapping double-buffered readbacks: finish out of order (b then a) via SubmissionIndex.
1028 let pend_a = eng.begin_readback_rgba(&f16_a).expect("begin a");
1029 let pend_b = eng.begin_readback_rgba(&f16_b).expect("begin b");
1030 assert_ne!(
1031 format!("{:?}", pend_a.submission_index),
1032 format!("{:?}", pend_b.submission_index)
1033 );
1034 assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0);
1035 assert_eq!(eng.pipelines.borrow().bg_misses, misses_before);
1036
1037 let px_b = pend_b.finish(&eng).expect("finish b");
1038 let px_a = pend_a.finish(&eng).expect("finish a");
1039 assert!((px_a[0] as i32 - 51).abs() <= 2);
1040 assert!((px_b[0] as i32 - 230).abs() <= 2);
1041
1042 // render_ram_frame_into_viewer must also bypass bg_cache and reset uniform cursors.
1043 let dst = eng.alloc_tex([16, 16], BitDepth::Int8, 0);
1044 let ram_frame = crate::ram_cache::RamFrame {
1045 size: [16, 16],
1046 rgba: std::sync::Arc::new(vec![128u8; 16 * 16 * 4]),
1047 eval_ms: 0.0,
1048 };
1049 let _ = eng.render_ram_frame_into_viewer(&ram_frame, &dst.texture, DisplaySettings::default());
1050 assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0);
1051 assert_eq!(eng.pipelines.borrow().bg_misses, misses_before);
1052 }
1053
1054 #[test]
1055 fn pending_readback_finish_into_reuses_allocation_and_matches_finish() {
1056 let Ok(eng) = Engine::new_headless() else {
1057 return;
1058 };
1059 let fill = |tex: &CachedTexture, rgba: [f32; 4]| {
1060 let mut enc = eng.device.create_command_encoder(&Default::default());
1061 let mut u = UniformParams::default();
1062 u.p[0] = rgba;
1063 u.p[1] = rgba;
1064 u.p[2] = rgba;
1065 u.p[3] = rgba;
1066 eng.dispatch_op(
1067 &mut enc,
1068 ShaderOp::Bg,
1069 &eng.dummy.view,
1070 &eng.dummy.view,
1071 &eng.dummy.view,
1072 tex,
1073 &u,
1074 );
1075 eng.queue.submit(Some(enc.finish()));
1076 eng.reset_uniform_cursors();
1077 };
1078
1079 // Test both padded (unaligned width 37) and unpadded (aligned width 64) readbacks.
1080 let tex_a = eng.alloc_tex([37, 13], BitDepth::Int8, 0);
1081 let tex_b = eng.alloc_tex([37, 13], BitDepth::Int8, 0);
1082 let tex_c = eng.alloc_tex([64, 16], BitDepth::Float16, 0);
1083 fill(&tex_a, [0.25, 0.5, 0.75, 1.0]);
1084 fill(&tex_b, [0.8, 0.2, 0.4, 0.9]);
1085 fill(&tex_c, [0.1, 0.6, 0.3, 1.0]);
1086
1087 let expected_a = eng.readback_rgba(&tex_a).expect("finish a");
1088 let expected_b = eng.readback_rgba(&tex_b).expect("finish b");
1089 let expected_c = eng.readback_rgba(&tex_c).expect("finish c");
1090
1091 let mut dst = Vec::with_capacity(64 * 16 * 4);
1092 let ptr_initial = dst.as_ptr();
1093 let cap_initial = dst.capacity();
1094
1095 for _ in 0..3 {
1096 eng.begin_readback_rgba(&tex_a)
1097 .expect("begin a")
1098 .finish_into(&eng, &mut dst)
1099 .expect("finish_into a");
1100 assert_eq!(dst.as_ptr(), ptr_initial, "dst must not reallocate");
1101 assert_eq!(dst.capacity(), cap_initial);
1102 assert_eq!(dst, expected_a);
1103
1104 eng.begin_readback_rgba(&tex_b)
1105 .expect("begin b")
1106 .finish_into(&eng, &mut dst)
1107 .expect("finish_into b");
1108 assert_eq!(dst.as_ptr(), ptr_initial, "dst must not reallocate");
1109 assert_eq!(dst.capacity(), cap_initial);
1110 assert_eq!(dst, expected_b);
1111
1112 eng.begin_readback_rgba(&tex_c)
1113 .expect("begin c")
1114 .finish_into(&eng, &mut dst)
1115 .expect("finish_into c");
1116 assert_eq!(dst.as_ptr(), ptr_initial, "dst must not reallocate");
1117 assert_eq!(dst.capacity(), cap_initial);
1118 assert_eq!(dst, expected_c);
1119 }
1120 }
1121}