authoravatarclover caruso<git@paperclover.net>2026-12-01 23:23:20-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 23:45:58-08:00
log106dd8015f89db1985fbef6fe8c726da1057838b
treeb34d494cc22a4272f4978dfb75570200bfa1ef6b
parent5a3cb3e5d6dd4e95bdeb25236fe84dc2fcc13c06
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): resolve Review Pass #8 findings (NV12 ring/VRAM/wasm32, TexturePool aux_bytes, DepthMerge, MotionBlur aux, HexagonTiles proxy, CopyAux NaN, Saver format precedence, av_decode padding)


14 files changed, 816 insertions(+), 202 deletions(-)

crates/engine/src/av_decode.m+7-7
......@@ -517,21 +517,21 @@ static int copy_nv12_planes(
517517
518518 int ok = 0;
519519 if (yBase && uvBase &&
520 yW == expectedW && yH == expectedH &&
521 uvW == expectedUvW && uvH == expectedUvH &&
522 yBpr >= yW && uvBpr >= uvRowBytes &&
520 yW >= (size_t)expectedW && yH >= (size_t)expectedH &&
521 uvW >= expectedUvW && uvH >= expectedUvH &&
522 yBpr >= (size_t)expectedW && uvBpr >= uvRowBytes &&
523523 outYLen >= yRequired && outUvLen >= uvRequired) {
524 if (yBpr == yW) {
524 if (yBpr == (size_t)expectedW) {
525525 memcpy(outY, yBase, yRequired);
526526 } else {
527 for (size_t r = 0; r < yH; r++) {
528 memcpy(outY + r * yW, yBase + r * yBpr, yW);
527 for (size_t r = 0; r < (size_t)expectedH; r++) {
528 memcpy(outY + r * (size_t)expectedW, yBase + r * yBpr, (size_t)expectedW);
529529 }
530530 }
531531 if (uvBpr == uvRowBytes) {
532532 memcpy(outUv, uvBase, uvRequired);
533533 } else {
534 for (size_t r = 0; r < uvH; r++) {
534 for (size_t r = 0; r < expectedUvH; r++) {
535535 memcpy(outUv + r * uvRowBytes, uvBase + r * uvBpr, uvRowBytes);
536536 }
537537 }
crates/engine/src/cache.rs+101-22
......@@ -153,6 +153,14 @@ fn texture_bytes(size: [u32; 2], format: wgpu::TextureFormat) -> u64 {
153153 .saturating_mul(bytes_per_pixel(format))
154154}
155155
156fn base_texture_bytes(tex: &CachedTexture) -> u64 {
157 if tex.bytes == 0 || tex.size[0] == 0 || tex.size[1] == 0 {
158 0
159 } else {
160 texture_bytes(tex.size, tex.format)
161 }
162}
163
156164/// Clamps `(width, height)` to at least 1 and at most `max_dim` while preserving aspect ratio.
157165/// Returns `(clamped_size, tex_scale)` where `tex_scale = physical / logical` (`1.0` if unclamped).
158166pub(crate) fn clamp_dims_to_limit(width: u32, height: u32, max_dim: u32) -> ([u32; 2], f32) {
......@@ -372,7 +380,8 @@ impl TexturePool {
372380 }
373381
374382 fn push(&mut self, tex: &CachedTexture) {
375 if tex.bytes == 0 || tex.size[0] == 0 || tex.size[1] == 0 {
383 let base_bytes = base_texture_bytes(tex);
384 if base_bytes == 0 {
376385 return;
377386 }
378387 let key = TexturePoolKey {
......@@ -382,13 +391,13 @@ impl TexturePool {
382391 usage: tex.texture.usage(),
383392 };
384393 self.tick += 1;
385 self.total_bytes = self.total_bytes.saturating_add(tex.bytes);
394 self.total_bytes = self.total_bytes.saturating_add(base_bytes);
386395 self.pooled_count += 1;
387396 self.returns += 1;
388397 self.buckets.entry(key).or_default().push_back(PooledTexture {
389398 texture: Arc::clone(&tex.texture),
390399 view: Arc::clone(&tex.view),
391 bytes: tex.bytes,
400 bytes: base_bytes,
392401 last_returned: self.tick,
393402 });
394403 }
......@@ -853,18 +862,22 @@ impl NodeCache {
853862 self.trim_pool_to_budget();
854863 }
855864
856 fn defer_to_pool(&mut self, tex: CachedTexture) {
857 if tex.bytes == 0 || tex.bytes > self.budget_bytes {
858 if tex.bytes > 0 {
865 fn defer_to_pool(&mut self, mut tex: CachedTexture) {
866 let base_bytes = base_texture_bytes(&tex);
867 if base_bytes == 0 || base_bytes > self.budget_bytes {
868 if base_bytes > 0 {
859869 self.vram_drops.fetch_add(1, Ordering::Relaxed);
860870 }
861871 return;
862872 }
863 let mut pending_bytes: u64 = self.pending_pool.iter().map(|t| t.bytes).sum();
873 // Aux channels are not pooled; drop them immediately so deferred pool entries
874 // only account for base RGBA texture bytes.
875 tex.set_aux(None);
876 let mut pending_bytes: u64 = self.pending_pool.iter().map(base_texture_bytes).sum();
864877 if self
865878 .total_bytes
866879 .saturating_add(pending_bytes)
867 .saturating_add(tex.bytes)
880 .saturating_add(base_bytes)
868881 <= self.budget_bytes
869882 {
870883 self.pending_pool.push_back(tex);
......@@ -874,19 +887,19 @@ impl NodeCache {
874887 if self
875888 .total_bytes
876889 .saturating_add(pending_bytes)
877 .saturating_add(tex.bytes)
890 .saturating_add(base_bytes)
878891 <= self.budget_bytes
879892 {
880893 break;
881894 }
882 pending_bytes = pending_bytes.saturating_sub(dropped.bytes);
895 pending_bytes = pending_bytes.saturating_sub(base_texture_bytes(dropped));
883896 self.pending_pool.pop_front();
884897 self.vram_drops.fetch_add(1, Ordering::Relaxed);
885898 }
886899 if self
887900 .total_bytes
888901 .saturating_add(pending_bytes)
889 .saturating_add(tex.bytes)
902 .saturating_add(base_bytes)
890903 <= self.budget_bytes
891904 {
892905 self.pending_pool.push_back(tex);
......@@ -930,8 +943,9 @@ impl NodeCache {
930943 }
931944
932945 fn return_to_pool(&self, tex: &CachedTexture) {
933 if tex.bytes == 0 || tex.bytes > self.budget_bytes {
934 if tex.bytes > 0 {
946 let base_bytes = base_texture_bytes(tex);
947 if base_bytes == 0 || base_bytes > self.budget_bytes {
948 if base_bytes > 0 {
935949 self.vram_drops.fetch_add(1, Ordering::Relaxed);
936950 }
937951 return;
......@@ -995,31 +1009,34 @@ impl NodeCache {
9951009 drained.sort_by_key(|e| e.eviction_priority());
9961010 let mut pool = self.pool.lock().expect("texture pool lock");
9971011 for tex in recycle_scratch {
998 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {
1012 let base_bytes = base_texture_bytes(&tex);
1013 if base_bytes > 0 && base_bytes <= self.budget_bytes {
9991014 pool.push(&tex);
1000 } else if tex.bytes > 0 {
1015 } else if base_bytes > 0 {
10011016 self.vram_drops.fetch_add(1, Ordering::Relaxed);
10021017 }
10031018 }
10041019 for tex in pending {
1005 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {
1020 let base_bytes = base_texture_bytes(&tex);
1021 if base_bytes > 0 && base_bytes <= self.budget_bytes {
10061022 pool.push(&tex);
1007 } else if tex.bytes > 0 {
1023 } else if base_bytes > 0 {
10081024 self.vram_drops.fetch_add(1, Ordering::Relaxed);
10091025 }
10101026 }
10111027 for entry in drained {
1012 if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes {
1028 let base_bytes = base_texture_bytes(&entry.tex);
1029 if base_bytes > 0 && base_bytes <= self.budget_bytes {
10131030 pool.push(&entry.tex);
1014 } else if entry.tex.bytes > 0 {
1031 } else if base_bytes > 0 {
10151032 self.vram_drops.fetch_add(1, Ordering::Relaxed);
10161033 }
10171034 }
10181035 self.trim_pool_locked(&mut pool, 0);
10191036 } else {
1020 let dropped = drained.iter().filter(|e| e.tex.bytes > 0).count()
1021 + pending.iter().filter(|t| t.bytes > 0).count()
1022 + recycle_scratch.iter().filter(|t| t.bytes > 0).count();
1037 let dropped = drained.iter().filter(|e| base_texture_bytes(&e.tex) > 0).count()
1038 + pending.iter().filter(|t| base_texture_bytes(t) > 0).count()
1039 + recycle_scratch.iter().filter(|t| base_texture_bytes(t) > 0).count();
10231040 if dropped > 0 {
10241041 self.vram_drops.fetch_add(dropped as u64, Ordering::Relaxed);
10251042 }
......@@ -1402,4 +1419,66 @@ mod tests {
14021419 cache.bust_all();
14031420 assert!(cache.vram_drops() > before_bust);
14041421 }
1422
1423 #[test]
1424 fn pooled_texture_with_aux_drops_aux_bytes_without_phantom_vram_inflation() {
1425 let eng = Engine::new_headless().expect("gpu");
1426 let device = eng.device();
1427 let usage = NodeCache::default_texture_usage();
1428 let mut cache = NodeCache::new(16);
1429
1430 // 512x512 RGBA8 = 1 MiB base; Z (R32F = 1 MiB) + Normal (RGBA16F = 2 MiB) = 3 MiB aux.
1431 let base_bytes: u64 = 512 * 512 * 4;
1432 let aux_bytes: u64 = 512 * 512 * 4 + 512 * 512 * 8;
1433 let mut t1 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1434 let ptr1 = Arc::as_ptr(&t1.texture);
1435 assert_eq!(t1.bytes, base_bytes);
1436 let make_aux = || {
1437 Arc::new(AuxChannels {
1438 z: Some(AuxChannelTex::new(device, [512, 512], wgpu::TextureFormat::R32Float, "test-z")),
1439 normal: Some(AuxChannelTex::new(device, [512, 512], wgpu::TextureFormat::Rgba16Float, "test-n")),
1440 ..Default::default()
1441 })
1442 };
1443 t1.set_aux(Some(make_aux()));
1444 assert_eq!(t1.bytes, base_bytes + aux_bytes);
1445
1446 // Live cache includes aux_bytes.
1447 cache.insert(1, t1, NodeId(0), 0);
1448 assert_eq!(cache.live_bytes(), base_bytes + aux_bytes);
1449 assert_eq!(cache.pooled_bytes(), 0);
1450 assert_eq!(cache.total_vram_bytes(), base_bytes + aux_bytes);
1451
1452 // clear_dynamic drops aux and pools ONLY base RGBA bytes.
1453 assert_eq!(cache.clear_dynamic(), 1);
1454 assert_eq!(cache.live_bytes(), 0);
1455 assert_eq!(cache.pooled_bytes(), base_bytes);
1456 assert_eq!(cache.total_vram_bytes(), base_bytes);
1457
1458 // Re-acquiring from pool returns exact base RGBA bytes with no aux.
1459 let mut t2 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1460 assert_eq!(Arc::as_ptr(&t2.texture), ptr1);
1461 assert!(t2.aux.is_none());
1462 assert_eq!(t2.bytes, base_bytes);
1463 assert_eq!(cache.pooled_bytes(), 0);
1464 assert_eq!(cache.live_bytes(), 0);
1465 assert_eq!(cache.total_vram_bytes(), 0);
1466
1467 // Re-attach aux, insert, and evict via overwrite (defer_to_pool -> flush_pending_pool).
1468 t2.set_aux(Some(make_aux()));
1469 cache.insert(2, t2, NodeId(1), 0);
1470 let t3 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1471 cache.insert(2, t3, NodeId(1), 0);
1472 assert_eq!(cache.live_bytes(), base_bytes);
1473 cache.flush_pending_pool();
1474 assert_eq!(cache.pooled_bytes(), base_bytes);
1475 assert_eq!(cache.total_vram_bytes(), base_bytes * 2);
1476
1477 // Re-acquire the deferred texture and verify base bytes again.
1478 let t4 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1479 assert_eq!(t4.bytes, base_bytes);
1480 assert_eq!(cache.pooled_bytes(), 0);
1481 assert_eq!(cache.live_bytes(), base_bytes);
1482 assert_eq!(cache.total_vram_bytes(), base_bytes);
1483 }
14051484}
crates/engine/src/eval/aux_ops.rs+290-8
......@@ -686,18 +686,25 @@ impl Engine {
686686 &dst_z,
687687 params,
688688 );
689 let same_dod = dst.size == bg.size && dst.origin == bg.origin;
689690 if bg_z.is_some() {
690 let mut out_aux = bg.aux_cloned();
691 let mut out_aux = if same_dod {
692 bg.aux_cloned()
693 } else {
694 AuxChannels::default()
695 };
691696 out_aux.z = Some(dst_z);
692697 dst.set_aux(Some(Arc::new(out_aux)));
693 } else if bg.aux.is_some() {
698 } else if bg.aux.is_some() && same_dod {
694699 // Preserve any non-Z aux channels on BG, keeping Z = None matching Snow Globe!
695700 dst.set_aux(bg.aux.clone());
696701 }
697702 }
698703
699 /// Crops `src.aux` channels from `src.origin` / `src.size` to `src.canvas_size`.
700 pub(super) fn crop_aux_to_canvas(
704 /// Re-origins and resizes `src.aux` channels from `(src.origin, src.size)` to
705 /// `(dst.origin, dst.size)`, padding out-of-bounds Z with `EMPTY_Z_SENTINEL` and
706 /// out-of-bounds `Rgba16Float` channels with `0.0`.
707 pub(super) fn reorigin_aux(
701708 &self,
702709 enc: &mut wgpu::CommandEncoder,
703710 src: &CachedTexture,
......@@ -706,13 +713,17 @@ impl Engine {
706713 let Some(src_aux) = src.aux.as_ref() else {
707714 return;
708715 };
716 if src.origin == dst.origin && src.size == dst.size {
717 dst.set_aux(Some(src_aux.clone()));
718 return;
719 }
709720 let mut out_aux = AuxChannels::default();
710721 let mut u = UniformParams::default();
711722 u.p[0] = [
712 src.origin[0] as f32,
713 src.origin[1] as f32,
714 src.canvas_size[0] as f32,
715 src.canvas_size[1] as f32,
723 (src.origin[0] - dst.origin[0]) as f32,
724 (src.origin[1] - dst.origin[1]) as f32,
725 dst.size[0] as f32,
726 dst.size[1] as f32,
716727 ];
717728 let mut ap = self.aux_pipelines().borrow_mut();
718729 if let Some(z) = src_aux.z.as_ref() {
......@@ -759,6 +770,16 @@ impl Engine {
759770 dst.set_aux(Some(Arc::new(out_aux)));
760771 }
761772
773 /// Crops `src.aux` channels from `src.origin` / `src.size` to `src.canvas_size`.
774 pub(super) fn crop_aux_to_canvas(
775 &self,
776 enc: &mut wgpu::CommandEncoder,
777 src: &CachedTexture,
778 dst: &mut CachedTexture,
779 ) {
780 self.reorigin_aux(enc, src, dst);
781 }
782
762783 /// Evaluates `Dimension.CopyAux` (Mode 0: Aux -> Color with Remap; Mode 1: Color -> Aux).
763784 #[allow(clippy::too_many_arguments)]
764785 pub(super) fn eval_copy_aux(
......@@ -1979,4 +2000,265 @@ mod tests {
19792000 assert!(c_fwd[0] > 2.0, "expected positive forward flow x, got {c_fwd:?}");
19802001 assert!(c_bwd[0] < -2.0, "expected negative backward flow x, got {c_bwd:?}");
19812002 }
2003
2004 #[test]
2005 fn depth_merge_transparent_fg_preserves_bg_z_and_non_over_modes_apply_when_bg_closer() {
2006 let Ok(mut eng) = Engine::new_headless() else { return };
2007 let src = format!(
2008 r#"Composition {{
2009 CurrentTime = 0,
2010 RenderRange = {{ 0, 1 }},
2011 GlobalRange = {{ 0, 1 }},
2012 Tools = ordered() {{
2013 {}
2014 {}
2015 {}
2016 Transparent2D = Background {{
2017 Inputs = {{
2018 Width = Input {{ Value = 16, }},
2019 Height = Input {{ Value = 16, }},
2020 TopLeftRed = Input {{ Value = 0.0, }},
2021 TopLeftGreen = Input {{ Value = 0.0, }},
2022 TopLeftBlue = Input {{ Value = 0.0, }},
2023 TopLeftAlpha = Input {{ Value = 0.0, }},
2024 }},
2025 }},
2026 -- Transparent 2D FG (no Z -> implicit 0.0) over BG with Z = -5.0 must keep bg_z = -5.0!
2027 M_Trans2D = Merge {{
2028 Inputs = {{
2029 Background = Input {{ SourceOp = "BgFar", Source = "Output", }},
2030 Foreground = Input {{ SourceOp = "Transparent2D", Source = "Output", }},
2031 PerformDepthMerge = Input {{ Value = 1, }},
2032 }},
2033 }},
2034 -- Transparent 3D FG (alpha=0, Z = -2.0) over BG with Z = -5.0 must also keep bg_z = -5.0!
2035 M_Trans3D = Merge {{
2036 Inputs = {{
2037 Background = Input {{ SourceOp = "BgFar", Source = "Output", }},
2038 Foreground = Input {{ SourceOp = "TransNear", Source = "Output", }},
2039 PerformDepthMerge = Input {{ Value = 1, }},
2040 }},
2041 }},
2042 -- fg_z (-5) < bg_z (-2) with ApplyMode = Screen: Screen(blue, red) -> magenta!
2043 M_Screen = Merge {{
2044 Inputs = {{
2045 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
2046 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
2047 PerformDepthMerge = Input {{ Value = 1, }},
2048 ApplyMode = Input {{ Value = FuID {{ "Screen" }}, }},
2049 }},
2050 }},
2051 -- fg_z (-5) < bg_z (-2) with ApplyMode = Multiply: Multiply(blue, red) -> black!
2052 M_Multiply = Merge {{
2053 Inputs = {{
2054 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
2055 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
2056 PerformDepthMerge = Input {{ Value = 1, }},
2057 ApplyMode = Input {{ Value = FuID {{ "Multiply" }}, }},
2058 }},
2059 }},
2060 -- fg_z (-5) < bg_z (-2) with Operator = Under: swaps BG behind FG -> blue!
2061 M_Under = Merge {{
2062 Inputs = {{
2063 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
2064 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
2065 PerformDepthMerge = Input {{ Value = 1, }},
2066 Operator = Input {{ Value = FuID {{ "Under" }}, }},
2067 }},
2068 }},
2069 -- fg_z (-5) < bg_z (-2) with Operator = Held Out: bg * (1 - fg.a) -> transparent!
2070 M_HeldOut = Merge {{
2071 Inputs = {{
2072 Background = Input {{ SourceOp = "FgNear", Source = "Output", }},
2073 Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }},
2074 PerformDepthMerge = Input {{ Value = 1, }},
2075 Operator = Input {{ Value = FuID {{ "Held Out" }}, }},
2076 }},
2077 }},
2078 }},
2079 }}"#,
2080 z_layer_nodes("BgFar", [0.0, 0.0, 1.0, 1.0], -5.0),
2081 z_layer_nodes("FgNear", [1.0, 0.0, 0.0, 1.0], -2.0),
2082 z_layer_nodes("TransNear", [0.0, 0.0, 0.0, 0.0], -2.0),
2083 );
2084 let comp = Comp::from_fusion_str(&src).expect("parse depth merge regression comp");
2085 let mut eval_one = |name: &str| -> ([u8; 4], f32) {
2086 let id = comp.find_node(name).unwrap();
2087 let (tex, _) = eng.evaluate(&comp, id, 0.0);
2088 let px = eng.readback_rgba(&tex).unwrap();
2089 let c = px_center(&px, tex.size[0], tex.size[1]);
2090 let zt = tex.aux.as_ref().unwrap().z.as_ref().unwrap();
2091 let zs = readback_r32f(&eng, zt);
2092 (c, zs[(zt.size[1] / 2 * zt.size[0] + zt.size[0] / 2) as usize])
2093 };
2094
2095 let (c_t2d, z_t2d) = eval_one("M_Trans2D");
2096 assert_eq!(c_t2d, [0, 0, 255, 255]);
2097 assert!((z_t2d - (-5.0)).abs() < 1e-3, "transparent 2D FG must preserve bg_z=-5.0, got {z_t2d}");
2098
2099 let (c_t3d, z_t3d) = eval_one("M_Trans3D");
2100 assert_eq!(c_t3d, [0, 0, 255, 255]);
2101 assert!((z_t3d - (-5.0)).abs() < 1e-3, "transparent 3D FG must preserve bg_z=-5.0, got {z_t3d}");
2102
2103 let (c_scr, z_scr) = eval_one("M_Screen");
2104 assert_eq!(c_scr, [255, 0, 255, 255], "Screen when fg_z < bg_z must blend red+blue -> magenta");
2105 assert!((z_scr - (-2.0)).abs() < 1e-3);
2106
2107 let (c_mul, z_mul) = eval_one("M_Multiply");
2108 assert_eq!(c_mul, [0, 0, 0, 255], "Multiply when fg_z < bg_z must yield black");
2109 assert!((z_mul - (-2.0)).abs() < 1e-3);
2110
2111 let (c_und, z_und) = eval_one("M_Under");
2112 assert_eq!(c_und, [0, 0, 255, 255], "Under when fg_z < bg_z must put BG behind FG -> blue");
2113 assert!((z_und - (-2.0)).abs() < 1e-3);
2114
2115 let (c_ho, z_ho) = eval_one("M_HeldOut");
2116 assert_eq!(c_ho, [0, 0, 0, 0], "Held Out when fg_z < bg_z with opaque FG must yield transparent");
2117 assert!((z_ho - (-2.0)).abs() < 1e-3);
2118 }
2119
2120 #[test]
2121 fn copy_aux_mode0_sanitizes_nan_and_inf_pixels() {
2122 let Ok(eng) = Engine::new_headless() else { return };
2123 let z_tex = AuxChannelTex::new(&eng.device, [4, 1], wgpu::TextureFormat::R32Float, "nan-z");
2124 let z_vals: [f32; 4] = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -5.0];
2125 eng.queue.write_texture(
2126 z_tex.texture.as_image_copy(),
2127 bytemuck::cast_slice(&z_vals),
2128 wgpu::TexelCopyBufferLayout {
2129 offset: 0,
2130 bytes_per_row: Some(16),
2131 rows_per_image: Some(1),
2132 },
2133 wgpu::Extent3d { width: 4, height: 1, depth_or_array_layers: 1 },
2134 );
2135 let src = eng.alloc_tex([4, 1], BitDepth::Float32, 0);
2136 let dst_remap = eng.alloc_tex([4, 1], BitDepth::Float32, 0);
2137 let dst_raw = eng.alloc_tex([4, 1], BitDepth::Float32, 0);
2138
2139 let mut u_remap = UniformParams::default();
2140 u_remap.p[0] = [0.0, 1.0, 0.0, 0.0]; // kind=Z, remap_en=1
2141 u_remap.p[1] = [-10.0, 0.0, 0.0, 1.0]; // -10..0 -> 0..1 (so 0.0 -> 1.0, -5.0 -> 0.5)
2142 u_remap.p[3] = [1.0, 0.0, 0.0, 0.0]; // blend=1
2143
2144 let mut u_raw = UniformParams::default();
2145 u_raw.p[0] = [0.0, 0.0, 0.0, 0.0]; // kind=Z, remap_en=0
2146 u_raw.p[3] = [1.0, 0.0, 0.0, 0.0]; // blend=1
2147
2148 let mut enc = eng.device.create_command_encoder(&Default::default());
2149 eng.aux_pipelines().borrow_mut().dispatch_rgba_op(
2150 &eng.device,
2151 &eng.queue,
2152 &mut enc,
2153 false,
2154 &src.view,
2155 &z_tex.view,
2156 &eng.dummy.view,
2157 &dst_remap,
2158 &u_remap,
2159 );
2160 eng.aux_pipelines().borrow_mut().dispatch_rgba_op(
2161 &eng.device,
2162 &eng.queue,
2163 &mut enc,
2164 false,
2165 &src.view,
2166 &z_tex.view,
2167 &eng.dummy.view,
2168 &dst_raw,
2169 &u_raw,
2170 );
2171 eng.queue.submit(Some(enc.finish()));
2172 eng.reset_uniform_cursors();
2173
2174 let remapped = eng.readback_rgba_f32(&dst_remap).expect("readback remapped");
2175 for i in 0..3 {
2176 let v = remapped[i * 4];
2177 assert!(v.is_finite(), "pixel {i} remapped must be finite, got {v}");
2178 assert!((v - 1.0).abs() < 1e-4, "sanitized 0.0 remapped in [-10..0]->[0..1] should be 1.0, got {v}");
2179 }
2180 assert!((remapped[12] - 0.5).abs() < 1e-4, "valid -5.0 remapped should be 0.5, got {}", remapped[12]);
2181
2182 let raw = eng.readback_rgba_f32(&dst_raw).expect("readback raw");
2183 for i in 0..3 {
2184 assert!(raw[i * 4].is_finite() && raw[i * 4] == 0.0, "pixel {i} raw NaN/Inf must sanitize to 0.0, got {}", raw[i * 4]);
2185 }
2186 assert!((raw[12] - (-5.0)).abs() < 1e-4, "valid -5.0 raw should stay -5.0, got {}", raw[12]);
2187 }
2188
2189 #[test]
2190 fn motion_blur_expanded_union_dod_pads_aux_z_with_empty_sentinel() {
2191 let Ok(mut eng) = Engine::new_headless() else { return };
2192 // BgZ and FgZ are both 16x16; MBMerge animates Center.x across 0.25..0.75 with MotionBlur=1,
2193 // Quality=3, ShutterAngle=360 so:
2194 // t=0.5 -> Center.x = 0.375 -> DoD expands left ([-2, 0], 18x16)
2195 // t=1.0 -> Center.x = 0.500 -> center DoD is ([ 0, 0], 16x16) with Z = -1.0
2196 // t=1.5 -> Center.x = 0.625 -> DoD expands right ([ 0, 0], 18x16)
2197 // Union DoD = ([-2, 0], 20x16); center's 16x16 aux.z must be padded to 20x16 with
2198 // EMPTY_Z_SENTINEL in the 2px OOB margins on left and right.
2199 let src = format!(
2200 r#"Composition {{
2201 CurrentTime = 1,
2202 RenderRange = {{ 0, 2 }},
2203 GlobalRange = {{ 0, 2 }},
2204 Tools = ordered() {{
2205 {}
2206 {}
2207 MBMerge = Merge {{
2208 Inputs = {{
2209 Background = Input {{ SourceOp = "BgZ", Source = "Output", }},
2210 Foreground = Input {{ SourceOp = "FgZ", Source = "Output", }},
2211 PerformDepthMerge = Input {{ Value = 1, }},
2212 MotionBlur = Input {{ Value = 1, }},
2213 Quality = Input {{ Value = 3, }},
2214 ShutterAngle = Input {{ Value = 360.0, }},
2215 Center = Input {{
2216 Value = {{ 0.5, 0.5 }},
2217 Expression = "Point(0.25 + time * 0.25, 0.5)",
2218 }},
2219 }},
2220 }},
2221 -- Downstream zoomed-out Transform ensures Merge does not clip its expanded DoD to canvas!
2222 ZoomOut = Transform {{
2223 Inputs = {{
2224 Input = Input {{ SourceOp = "MBMerge", Source = "Output", }},
2225 Size = Input {{ Value = 0.5, }},
2226 }},
2227 }},
2228 }},
2229 }}"#,
2230 z_layer_nodes("BgZ", [0.0, 0.0, 1.0, 1.0], -5.0),
2231 z_layer_nodes("FgZ", [1.0, 0.0, 0.0, 1.0], -1.0),
2232 );
2233 let comp = Comp::from_fusion_str(&src).expect("parse MB DoD aux comp");
2234 let id = comp.find_node("MBMerge").unwrap();
2235
2236 let mut visiting = eng.prepare_frame_scratch(&comp);
2237 let mut stats = EvalStats::default();
2238 let mut enc = eng.device.create_command_encoder(&Default::default());
2239 let out = eng.eval_node(&comp, id, 1.0, &mut enc, &mut visiting, &mut stats);
2240 eng.queue.submit(Some(enc.finish()));
2241 eng.reset_uniform_cursors();
2242 eng.finish_frame_scratch(visiting);
2243
2244 assert!(out.size[0] > 16 && out.origin[0] < 0, "expected expanded union DoD, got origin={:?} size={:?}", out.origin, out.size);
2245 let aux_z = out
2246 .aux
2247 .as_ref()
2248 .expect("MotionBlur output must carry padded aux")
2249 .z
2250 .as_ref()
2251 .expect("MotionBlur output must carry padded aux.z");
2252 assert_eq!(aux_z.size, out.size, "padded aux.z size must match out.size");
2253
2254 let zs = readback_r32f(&eng, aux_z);
2255 let w = out.size[0] as usize;
2256 let row = (out.size[1] / 2) as usize;
2257 let left_oob = zs[row * w];
2258 let right_oob = zs[row * w + (w - 1)];
2259 let center_z = zs[row * w + (w / 2)];
2260 assert_eq!(left_oob, EMPTY_Z_SENTINEL, "left OOB Z must be EMPTY_Z_SENTINEL, got {left_oob}");
2261 assert_eq!(right_oob, EMPTY_Z_SENTINEL, "right OOB Z must be EMPTY_Z_SENTINEL, got {right_oob}");
2262 assert!((center_z - (-1.0)).abs() < 1e-3, "center Z must preserve -1.0, got {center_z}");
2263 }
19822264}
crates/engine/src/eval/composite.rs+1-1
......@@ -1166,7 +1166,7 @@ impl Engine {
11661166 };
11671167 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
11681168 self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &fg.view, mv, &dst, &u);
1169 if bg.aux.is_some() && dst.size == bg.size {
1169 if bg.aux.is_some() && dst.size == bg.size && dst.origin == bg.origin {
11701170 dst.set_aux(bg.aux.clone());
11711171 }
11721172 self.cache.insert(key, dst.clone(), node.id, frame_i);
crates/engine/src/eval/fuses.rs+61-3
......@@ -178,10 +178,11 @@ impl Engine {
178178 let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) };
179179 let depth = self.node_depth(comp, node, time, None);
180180
181 let proxy = self.proxy_scale.max(1) as f32;
181182 let hex_size = comp.eval_number(node, "Size", time, 5.0, &self.expr) as f32;
182183 let border = comp.eval_number(node, "BorderSize", time, 2.0, &self.expr) as f32;
183 let xoff = comp.eval_number(node, "XOff", time, 0.0, &self.expr).round() as f32;
184 let yoff = comp.eval_number(node, "YOff", time, 0.0, &self.expr).round() as f32;
184 let xoff = comp.eval_number(node, "XOff", time, 0.0, &self.expr).round() as f32 / proxy;
185 let yoff = comp.eval_number(node, "YOff", time, 0.0, &self.expr).round() as f32 / proxy;
185186 let r1 = comp.eval_number(node, "Red1", time, 0.2, &self.expr) as f32;
186187 let g1 = comp.eval_number(node, "Green1", time, 0.2, &self.expr) as f32;
187188 let b1 = comp.eval_number(node, "Blue1", time, 0.8, &self.expr) as f32;
......@@ -573,6 +574,52 @@ mod tests {
573574 assert!(mask_px.chunks(4).all(|p| p[3] == 128), "Blend=0.5 scales alpha to 0.5");
574575 }
575576
577 #[test]
578 fn hexagon_tiles_proxy_scale_scales_xoff_and_yoff_to_match_downsampled_full_res() {
579 let c = comp(
580 r#"OffsetHex = Fuse.HexagonTiles { Inputs = {
581 Width = Input { Value = 192, },
582 Height = Input { Value = 108, },
583 Size = Input { Value = 16.56, },
584 BorderSize = Input { Value = 2.0, },
585 XOff = Input { Value = -148, },
586 YOff = Input { Value = -37, },
587 Red1 = Input { Value = 0, },
588 Green1 = Input { Value = 0.495, },
589 Blue1 = Input { Value = 0.8, },
590 Red2 = Input { Value = 0, },
591 Green2 = Input { Value = 0.2, },
592 Blue2 = Input { Value = 0.2, },
593 }, },"#,
594 );
595 let Ok(mut eng) = Engine::new_headless() else { return };
596 let id = c.find_node("OffsetHex").unwrap();
597
598 eng.proxy_scale = 1;
599 let (full_tex, _) = eng.evaluate(&c, id, 0.0);
600 assert_eq!(full_tex.size, [192, 108]);
601 let full_px = eng.readback_rgba(&full_tex).unwrap();
602
603 eng.proxy_scale = 2;
604 let (half_tex, _) = eng.evaluate(&c, id, 0.0);
605 assert_eq!(half_tex.size, [96, 54]);
606 let half_px = eng.readback_rgba(&half_tex).unwrap();
607
608 // Fusion Y-up coordinate fy_half = (54 - 1 - row) maps to fy_full = 2 * fy_half,
609 // which in top-down rows is row_full = 108 - 1 - 2*(53 - row) = 2*row + 1, col_full = 2*col.
610 let mut diffs = 0usize;
611 for row in 0..54u32 {
612 for col in 0..96u32 {
613 let h_idx = ((row * 96 + col) * 4) as usize;
614 let f_idx = (((row * 2 + 1) * 192 + col * 2) * 4) as usize;
615 if half_px[h_idx..h_idx + 4] != full_px[f_idx..f_idx + 4] {
616 diffs += 1;
617 }
618 }
619 }
620 assert!(diffs <= 2, "HexagonTiles proxy_scale=2 diverged from downsampled full-res: {diffs} diffs");
621 }
622
576623 #[test]
577624 fn hexagon_tiles_in_30_ground_is_crazy005_evaluates_with_no_unsupported_nodes() {
578625 let path = std::path::Path::new("/Volumes/Project/trees/fusion/30_ground_is_crazy005.comp");
......@@ -586,12 +633,23 @@ mod tests {
586633 assert!(stats.unsupported_nodes.is_empty(), "unexpected unsupported_nodes: {:?}", stats.unsupported_nodes);
587634 assert_eq!(tex.size, [1920, 1080]);
588635 let gpu_px = eng.readback_rgba(&tex).unwrap();
636 let hex_node = comp.node(hex_id);
637 let c1 = [
638 comp.eval_number(hex_node, "Red1", 3107.0, 0.2, &eng.expr),
639 comp.eval_number(hex_node, "Green1", 3107.0, 0.2, &eng.expr),
640 comp.eval_number(hex_node, "Blue1", 3107.0, 0.8, &eng.expr),
641 ];
642 let c2 = [
643 comp.eval_number(hex_node, "Red2", 3107.0, 0.8, &eng.expr),
644 comp.eval_number(hex_node, "Green2", 3107.0, 0.2, &eng.expr),
645 comp.eval_number(hex_node, "Blue2", 3107.0, 0.2, &eng.expr),
646 ];
589647 let mut diffs = 0usize;
590648 for row in 0..1080u32 {
591649 for col in 0..1920u32 {
592650 let idx = ((row * 1920 + col) * 4) as usize;
593651 let g = &gpu_px[idx..idx + 4];
594 let (r, h_val) = hexagon_tiles_f64_eval(1920, 1080, col, row, 16.56, 2.0, -148.0, 0.0, [0.0, 0.495, 0.8], [0.0, 0.2, 0.2]);
652 let (r, h_val) = hexagon_tiles_f64_eval(1920, 1080, col, row, 16.56, 2.0, -148.0, 0.0, c1, c2);
595653 if g != r {
596654 assert!((h_val - 0.1).abs() < 1e-6, "non-boundary mismatch at ({col}, {row}): h={h_val}, gpu={g:?}, ref={r:?}");
597655 diffs += 1;
crates/engine/src/eval/io.rs+1
......@@ -4,6 +4,7 @@ use std::sync::{Mutex, OnceLock};
44
55#[path = "nv12.rs"]
66mod nv12;
7pub(crate) use nv12::Nv12Pipelines;
78
89static DIMS_CACHE: OnceLock<Mutex<HashMap<PathBuf, Option<[u32; 2]>>>> = OnceLock::new();
910
crates/engine/src/eval/mod.rs+13-3
......@@ -32,6 +32,7 @@ mod output_cache;
3232
3333use dispatch::UniformParams;
3434pub use dispatch::{PendingReadback, create_texture, create_texture_dod, create_texture_dod_fmt};
35pub(crate) use io::Nv12Pipelines;
3536use output_cache::OutputCache;
3637use registry::{ShaderOp, ShaderRegistry};
3738
......@@ -317,6 +318,7 @@ impl Engine {
317318 if let Some(of) = self.optflow.get() {
318319 of.reset_uniform_cursor();
319320 }
321 self.media.reset_nv12_uniform_cursor();
320322 }
321323
322324 fn trim_uniform_chunks(&self) {
......@@ -324,6 +326,7 @@ impl Engine {
324326 if let Some(ap) = self.aux_pipelines.get() {
325327 ap.borrow_mut().trim_uniform_chunks(2);
326328 }
329 self.media.trim_nv12_uniform_chunks(2);
327330 }
328331
329332 pub(super) fn sync_bg_cache_with_vram_drops(&mut self) {
......@@ -368,6 +371,7 @@ impl Engine {
368371 if let Some(of) = self.optflow.get() {
369372 of.clear_scratch();
370373 }
374 self.media.clear_nv12_gpu_state();
371375 #[cfg(not(target_arch = "wasm32"))]
372376 self.pipelines.borrow_mut().readback_pool.clear();
373377 self.sprite_cache.clear();
......@@ -638,11 +642,15 @@ impl Engine {
638642 {
639643 return samples.swap_remove(center_idx);
640644 }
645 let center = &samples[center_idx];
641646 let mut hasher = std::collections::hash_map::DefaultHasher::new();
642647 "motion_blur".hash(&mut hasher);
643648 id.0.hash(&mut hasher);
649 self.cache.gpu_salt.hash(&mut hasher);
650 self.cache.node_salt(id).hash(&mut hasher);
644651 cfg.cache_key_bits().hash(&mut hasher);
645 first.format.hash(&mut hasher);
652 center.format.hash(&mut hasher);
653 center.depth.hash(&mut hasher);
646654 for s in &samples {
647655 s.content_hash.hash(&mut hasher);
648656 s.origin.hash(&mut hasher);
......@@ -653,8 +661,7 @@ impl Engine {
653661 stats.cache_hits += 1;
654662 return hit;
655663 }
656 let center = &samples[center_idx];
657 let out = self.motion_blur.accumulate_samples(
664 let mut out = self.motion_blur.accumulate_samples(
658665 &self.device,
659666 &self.queue,
660667 enc,
......@@ -663,6 +670,9 @@ impl Engine {
663670 center.format,
664671 mb_key,
665672 );
673 if center.aux.is_some() && (center.origin != out.origin || center.size != out.size) {
674 self.reorigin_aux(enc, center, &mut out);
675 }
666676 self.cache.insert(mb_key, out.clone(), id, frame_i);
667677 out
668678 }
crates/engine/src/eval/nv12.rs+191-105
......@@ -9,7 +9,7 @@ use std::collections::HashMap;
99use std::num::NonZeroU64;
1010
1111const NV12_WGSL: &str = include_str!("../shaders/nv12_to_rgba.wgsl");
12const NV12_UNIFORM_SLOTS: u32 = 512;
12const NV12_UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
1313#[cfg(not(target_arch = "wasm32"))]
1414const MAX_POOLED_PLANE_SIZES: usize = 8;
1515
......@@ -37,6 +37,8 @@ struct Nv12PlanePair {
3737 uv_tex: wgpu::Texture,
3838 uv_view: wgpu::TextureView,
3939 #[cfg(not(target_arch = "wasm32"))]
40 bytes: u64,
41 #[cfg(not(target_arch = "wasm32"))]
4042 last_used: u64,
4143}
4244
......@@ -75,6 +77,10 @@ impl Nv12PlanePair {
7577 view_formats: &[],
7678 });
7779 let uv_view = uv_tex.create_view(&wgpu::TextureViewDescriptor::default());
80 #[cfg(not(target_arch = "wasm32"))]
81 let bytes = u64::from(raw_w)
82 .saturating_mul(u64::from(raw_h))
83 .saturating_add(u64::from(uv_w).saturating_mul(u64::from(uv_h)).saturating_mul(2));
7884
7985 Self {
8086 y_tex,
......@@ -82,14 +88,16 @@ impl Nv12PlanePair {
8288 uv_tex,
8389 uv_view,
8490 #[cfg(not(target_arch = "wasm32"))]
91 bytes,
92 #[cfg(not(target_arch = "wasm32"))]
8593 last_used: 0,
8694 }
8795 }
8896}
8997
90pub(super) struct Nv12Pipelines {
98pub(crate) struct Nv12Pipelines {
9199 sampler: wgpu::Sampler,
92 uniform_buf: wgpu::Buffer,
100 uniform_chunks: Vec<wgpu::Buffer>,
93101 uniform_stride: u32,
94102 uniform_cursor: u32,
95103 pipelines: HashMap<wgpu::TextureFormat, Nv12FormatPipeline>,
......@@ -115,16 +123,10 @@ impl Nv12Pipelines {
115123 let align = device.limits().min_uniform_buffer_offset_alignment.max(32);
116124 let raw_size = std::mem::size_of::<Nv12UniformParams>() as u32;
117125 let uniform_stride = raw_size.div_ceil(align) * align;
118 let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
119 label: Some("nv12-uniform-ring"),
120 size: u64::from(uniform_stride) * u64::from(NV12_UNIFORM_SLOTS),
121 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
122 mapped_at_creation: false,
123 });
124126
125127 Self {
126128 sampler,
127 uniform_buf,
129 uniform_chunks: Vec::new(),
128130 uniform_stride,
129131 uniform_cursor: 0,
130132 pipelines: HashMap::new(),
......@@ -135,6 +137,63 @@ impl Nv12Pipelines {
135137 }
136138 }
137139
140 pub(crate) fn reset_uniform_cursor(&mut self) {
141 self.uniform_cursor = 0;
142 }
143
144 pub(crate) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
145 self.uniform_cursor = 0;
146 if self.uniform_chunks.len() > max_chunks {
147 self.uniform_chunks.truncate(max_chunks);
148 }
149 }
150
151 pub(crate) fn vram_bytes(&self) -> u64 {
152 let uniform_bytes: u64 = self.uniform_chunks.iter().map(wgpu::Buffer::size).sum();
153 #[cfg(not(target_arch = "wasm32"))]
154 let plane_bytes: u64 = self.plane_pool.values().map(|p| p.bytes).sum();
155 #[cfg(target_arch = "wasm32")]
156 let plane_bytes: u64 = 0;
157 uniform_bytes.saturating_add(plane_bytes)
158 }
159
160 pub(crate) fn clear_plane_pool(&mut self) {
161 #[cfg(not(target_arch = "wasm32"))]
162 {
163 self.plane_pool.clear();
164 self.tick = 0;
165 }
166 }
167
168 fn alloc_uniform_slot(
169 &mut self,
170 device: &wgpu::Device,
171 queue: &wgpu::Queue,
172 params: &Nv12UniformParams,
173 ) -> (usize, u32) {
174 let slot_global = self.uniform_cursor;
175 let chunk_idx = (slot_global / NV12_UNIFORM_SLOTS_PER_CHUNK) as usize;
176 let slot_in_chunk = slot_global % NV12_UNIFORM_SLOTS_PER_CHUNK;
177 while chunk_idx >= self.uniform_chunks.len() {
178 let size = u64::from(NV12_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
179 let buf = device.create_buffer(&wgpu::BufferDescriptor {
180 label: Some("nv12-uniform-ring"),
181 size,
182 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
183 mapped_at_creation: false,
184 });
185 self.uniform_chunks.push(buf);
186 }
187 let dyn_offset = slot_in_chunk * self.uniform_stride;
188 queue.write_buffer(
189 &self.uniform_chunks[chunk_idx],
190 u64::from(dyn_offset),
191 bytemuck::bytes_of(params),
192 );
193 self.uniform_cursor = slot_global + 1;
194 (chunk_idx, dyn_offset)
195 }
196
138197 fn ensure_pipeline(&mut self, device: &wgpu::Device, dst_format: wgpu::TextureFormat) {
139198 if self.pipelines.contains_key(&dst_format) {
140199 return;
......@@ -271,9 +330,6 @@ impl Nv12Pipelines {
271330 dst: &CachedTexture,
272331 ) {
273332 self.ensure_pipeline(device, dst.format);
274 let slot = self.uniform_cursor;
275 self.uniform_cursor = (self.uniform_cursor + 1) % NV12_UNIFORM_SLOTS;
276 let dyn_offset = slot * self.uniform_stride;
277333
278334 let params = Nv12UniformParams {
279335 raw_w: nv12.raw_size[0],
......@@ -285,11 +341,7 @@ impl Nv12Pipelines {
285341 full_range: u32::from(nv12.is_full_range),
286342 _pad: 0,
287343 };
288 queue.write_buffer(
289 &self.uniform_buf,
290 u64::from(dyn_offset),
291 bytemuck::bytes_of(&params),
292 );
344 let (chunk_idx, dyn_offset) = self.alloc_uniform_slot(device, queue, &params);
293345
294346 let fp = &self.pipelines[&dst.format];
295347 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
......@@ -315,7 +367,7 @@ impl Nv12Pipelines {
315367 wgpu::BindGroupEntry {
316368 binding: 4,
317369 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
318 buffer: &self.uniform_buf,
370 buffer: &self.uniform_chunks[chunk_idx],
319371 offset: 0,
320372 size: NonZeroU64::new(std::mem::size_of::<Nv12UniformParams>() as u64),
321373 }),
......@@ -333,12 +385,6 @@ impl Nv12Pipelines {
333385 }
334386}
335387
336#[cfg(target_arch = "wasm32")]
337thread_local! {
338 static WASM_NV12_PIPELINES: std::cell::RefCell<Option<Nv12Pipelines>> =
339 const { std::cell::RefCell::new(None) };
340}
341
342388#[cfg(not(target_arch = "wasm32"))]
343389fn stage_plane_into_buffer(
344390 media: &crate::media::MediaCache,
......@@ -483,87 +529,42 @@ pub(super) fn upload_and_convert_nv12(
483529 _ => {}
484530 }
485531
486 // Fallback when staging pool is temporarily exhausted: use fresh textures with
532 // Fallback when staging pool is temporarily exhausted (or on wasm32): use fresh textures with
487533 // `queue.write_texture` so multiple dispatches in one encoder cannot overwrite each other.
488 let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h);
489 engine.queue.write_texture(
490 fresh.y_tex.as_image_copy(),
491 &nv12.y,
492 wgpu::TexelCopyBufferLayout {
493 offset: 0,
494 bytes_per_row: Some(raw_w),
495 rows_per_image: Some(raw_h),
496 },
497 wgpu::Extent3d {
498 width: raw_w,
499 height: raw_h,
500 depth_or_array_layers: 1,
501 },
502 );
503 engine.queue.write_texture(
504 fresh.uv_tex.as_image_copy(),
505 &nv12.uv,
506 wgpu::TexelCopyBufferLayout {
507 offset: 0,
508 bytes_per_row: Some(uv_w * 2),
509 rows_per_image: Some(uv_h),
510 },
511 wgpu::Extent3d {
512 width: uv_w,
513 height: uv_h,
514 depth_or_array_layers: 1,
515 },
516 );
517 engine.media.with_nv12_gpu_state(
518 || Nv12Pipelines::new(&engine.device),
519 |pipe| {
520 pipe.encode_dispatch(
521 &engine.device,
522 &engine.queue,
523 enc,
524 &fresh.y_view,
525 &fresh.uv_view,
526 nv12,
527 dst,
528 );
529 },
530 );
531534 }
532535
533 #[cfg(target_arch = "wasm32")]
534 {
535 let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h);
536 engine.queue.write_texture(
537 fresh.y_tex.as_image_copy(),
538 &nv12.y,
539 wgpu::TexelCopyBufferLayout {
540 offset: 0,
541 bytes_per_row: Some(raw_w),
542 rows_per_image: Some(raw_h),
543 },
544 wgpu::Extent3d {
545 width: raw_w,
546 height: raw_h,
547 depth_or_array_layers: 1,
548 },
549 );
550 engine.queue.write_texture(
551 fresh.uv_tex.as_image_copy(),
552 &nv12.uv,
553 wgpu::TexelCopyBufferLayout {
554 offset: 0,
555 bytes_per_row: Some(uv_w * 2),
556 rows_per_image: Some(uv_h),
557 },
558 wgpu::Extent3d {
559 width: uv_w,
560 height: uv_h,
561 depth_or_array_layers: 1,
562 },
563 );
564 WASM_NV12_PIPELINES.with(|cell| {
565 let mut slot = cell.borrow_mut();
566 let pipe = slot.get_or_insert_with(|| Nv12Pipelines::new(&engine.device));
536 let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h);
537 engine.queue.write_texture(
538 fresh.y_tex.as_image_copy(),
539 &nv12.y,
540 wgpu::TexelCopyBufferLayout {
541 offset: 0,
542 bytes_per_row: Some(raw_w),
543 rows_per_image: Some(raw_h),
544 },
545 wgpu::Extent3d {
546 width: raw_w,
547 height: raw_h,
548 depth_or_array_layers: 1,
549 },
550 );
551 engine.queue.write_texture(
552 fresh.uv_tex.as_image_copy(),
553 &nv12.uv,
554 wgpu::TexelCopyBufferLayout {
555 offset: 0,
556 bytes_per_row: Some(uv_w * 2),
557 rows_per_image: Some(uv_h),
558 },
559 wgpu::Extent3d {
560 width: uv_w,
561 height: uv_h,
562 depth_or_array_layers: 1,
563 },
564 );
565 engine.media.with_nv12_gpu_state(
566 || Nv12Pipelines::new(&engine.device),
567 |pipe| {
567568 pipe.encode_dispatch(
568569 &engine.device,
569570 &engine.queue,
......@@ -573,8 +574,8 @@ pub(super) fn upload_and_convert_nv12(
573574 nv12,
574575 dst,
575576 );
576 });
577 }
577 },
578 );
578579}
579580
580581#[cfg(all(test, not(target_arch = "wasm32")))]
......@@ -823,6 +824,91 @@ mod tests {
823824 assert!(b_px[2] > 220 && b_px[0] < 20 && b_px[1] < 20, "second dispatch corrupted: {:?}", &b_px[..4]);
824825 }
825826
827 #[test]
828 fn nv12_uniform_chunk_ring_grows_past_512_resets_trims_and_tracks_vram() {
829 let mut engine = Engine::new_headless().expect("headless engine");
830 let red_0 = Nv12Frame {
831 raw_size: [8, 8],
832 display_size: [8, 8],
833 rot_deg: 0,
834 matrix: YuvMatrix::Bt709,
835 is_full_range: false,
836 y: vec![63u8; 8 * 8],
837 uv: [102u8, 240u8].repeat(4 * 4),
838 };
839 let blue_180 = Nv12Frame {
840 raw_size: [8, 8],
841 display_size: [8, 8],
842 rot_deg: 180,
843 matrix: YuvMatrix::Bt709,
844 is_full_range: false,
845 y: vec![32u8; 8 * 8],
846 uv: [240u8, 118u8].repeat(4 * 4),
847 };
848
849 let mut enc = engine
850 .device
851 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
852 label: Some("nv12-ring-growth-test"),
853 });
854 let dst_first = engine.alloc_tex([8, 8], BitDepth::Int8, 0);
855 let dst_mid = engine.alloc_tex([8, 8], BitDepth::Int8, 0);
856 let dst_last = engine.alloc_tex([8, 8], BitDepth::Int8, 0);
857
858 // Dispatch >512 times in a single CommandEncoder so the uniform ring must grow to a 2nd chunk
859 // without wrapping and clobbering slot 0!
860 upload_and_convert_nv12(&engine, &mut enc, &red_0, &dst_first);
861 for _ in 1..NV12_UNIFORM_SLOTS_PER_CHUNK {
862 upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_mid);
863 }
864 // Slot 512 (index 0 of chunk 1) + slot 513 (index 1 of chunk 1)
865 upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_mid);
866 upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_last);
867
868 let (chunks_before_trim, cursor_before_reset, vram_before_bust) =
869 engine.media.with_nv12_gpu_state(
870 || unreachable!("already initialized"),
871 |pipe| (pipe.uniform_chunks.len(), pipe.uniform_cursor, pipe.vram_bytes()),
872 );
873 assert_eq!(chunks_before_trim, 2, "expected 2 uniform chunks for 514 dispatches");
874 assert_eq!(cursor_before_reset, NV12_UNIFORM_SLOTS_PER_CHUNK + 2);
875 assert!(vram_before_bust > 0);
876 assert!(engine.vram_bytes() >= vram_before_bust);
877
878 engine.queue.submit(Some(enc.finish()));
879 engine.reset_uniform_cursors();
880 engine.media.flush_upload_staging_after_submit(&engine.device);
881
882 // Verify slot 0 (red) was NOT clobbered by slot 512 (blue) and slot 513 (blue) is intact!
883 let first_px = engine.readback_rgba(&dst_first).expect("readback first");
884 let last_px = engine.readback_rgba(&dst_last).expect("readback last");
885 assert!(first_px[0] > 220 && first_px[2] < 20, "slot 0 clobbered: {:?}", &first_px[..4]);
886 assert!(last_px[2] > 220 && last_px[0] < 20, "slot 513 corrupted: {:?}", &last_px[..4]);
887
888 let cursor_after_reset = engine.media.with_nv12_gpu_state(
889 || unreachable!("already initialized"),
890 |pipe| pipe.uniform_cursor,
891 );
892 assert_eq!(cursor_after_reset, 0);
893
894 // Trim chunks to 1 and verify VRAM drops cleanly; then bust_gpu_cache clears plane pool.
895 engine.media.trim_nv12_uniform_chunks(1);
896 let chunks_after_trim = engine.media.with_nv12_gpu_state(
897 || unreachable!("already initialized"),
898 |pipe| pipe.uniform_chunks.len(),
899 );
900 assert_eq!(chunks_after_trim, 1);
901
902 let vram_before_clear = engine.media.nv12_vram_bytes();
903 engine.bust_gpu_cache();
904 let (planes_after_bust, vram_after_bust) = engine.media.with_nv12_gpu_state(
905 || unreachable!("already initialized"),
906 |pipe| (pipe.plane_pool.len(), pipe.vram_bytes()),
907 );
908 assert_eq!(planes_after_bust, 0);
909 assert!(vram_after_bust < vram_before_clear);
910 }
911
826912 #[cfg(target_os = "macos")]
827913 #[test]
828914 fn nv12_synthetic_mp4_decode_and_eval_loader() {
crates/engine/src/eval/output_cache.rs+1
......@@ -155,6 +155,7 @@ impl Engine {
155155 .saturating_add(self.scene3d.mesh_vram_bytes())
156156 .saturating_add(self.scene3d.uniform_vram_bytes())
157157 .saturating_add(self.optflow.get().map_or(0, |of| of.vram_bytes()))
158 .saturating_add(self.media.nv12_vram_bytes())
158159 }
159160
160161 pub fn vram_mb(&self) -> f64 {
crates/engine/src/export.rs+8-6
......@@ -227,21 +227,23 @@ pub(super) fn ensure_parent_dir(
227227
228228fn saver_targets_exr(comp: &Comp, saver: &SaverSpec, out_dir_override: Option<&Path>) -> bool {
229229 let node = comp.node(saver.node_id);
230 if node
230 if let Some(fmt) = node
231231 .static_str("OutputFormat")
232 .is_some_and(|s| s.eq_ignore_ascii_case("OpenEXRFormat"))
232 .map(str::trim)
233 .filter(|s| !s.is_empty())
233234 {
234 return true;
235 return fmt.eq_ignore_ascii_case("OpenEXRFormat");
235236 }
236 if node
237 if let Some(fmt) = node
237238 .raw
238239 .get_table("Inputs")
239240 .and_then(|i| i.get_table("Clip"))
240241 .and_then(|c| c.get_table("Value"))
241242 .and_then(|v| v.get_str("FormatID"))
242 .is_some_and(|s| s.eq_ignore_ascii_case("OpenEXRFormat"))
243 .map(str::trim)
244 .filter(|s| !s.is_empty())
243245 {
244 return true;
246 return fmt.eq_ignore_ascii_case("OpenEXRFormat");
245247 }
246248 resolve_output_path_with_ext(saver, saver.range[0], out_dir_override, "png").is_ok_and(|p| {
247249 p.extension()
crates/engine/src/export/tests.rs+48
......@@ -1790,3 +1790,51 @@ fn exports_exr_saver_sequence_and_stops_cleanly_on_cancel() {
17901790
17911791 let _ = std::fs::remove_dir_all(&tmp_dir);
17921792}
1793
1794#[test]
1795fn saver_output_format_takes_precedence_over_exr_extension() {
1796 let check = |output_format: Option<&str>, format_id: Option<&str>, filename: &str| -> bool {
1797 let of_line = output_format
1798 .map(|f| format!(r#"OutputFormat = Input {{ Value = FuID {{ "{f}" }}, }},"#))
1799 .unwrap_or_default();
1800 let fid_line = format_id
1801 .map(|f| format!(r#"FormatID = "{f}","#))
1802 .unwrap_or_default();
1803 let src = format!(
1804 r#"Composition {{
1805 CurrentTime = 0,
1806 RenderRange = {{ 0, 0 }},
1807 GlobalRange = {{ 0, 0 }},
1808 Tools = ordered() {{
1809 Saver1 = Saver {{
1810 Inputs = {{
1811 {of_line}
1812 Clip = Input {{
1813 Value = Clip {{
1814 Filename = "{filename}",
1815 {fid_line}
1816 Saving = true,
1817 }},
1818 }},
1819 }},
1820 }},
1821 }},
1822 }}"#
1823 );
1824 let comp = Comp::from_fusion_str(&src).expect("parse saver comp");
1825 let saver = select_saver(&comp, None).expect("select saver");
1826 saver_targets_exr(&comp, &saver, None)
1827 };
1828
1829 // Explicit non-EXR OutputFormat overrides .exr filename and even Clip.Value.FormatID.
1830 assert!(!check(Some("PNGFormat"), None, "/tmp/out_0000.exr"));
1831 assert!(!check(Some("PNGFormat"), Some("OpenEXRFormat"), "/tmp/out_0000.exr"));
1832 // Explicit OpenEXRFormat overrides .png filename.
1833 assert!(check(Some("OpenEXRFormat"), None, "/tmp/out_0000.png"));
1834 // Unset OutputFormat with explicit non-EXR FormatID overrides .exr extension.
1835 assert!(!check(None, Some("PNGFormat"), "/tmp/out_0000.exr"));
1836 // Empty OutputFormat and empty/unset FormatID fall back to .exr extension.
1837 assert!(check(None, None, "/tmp/out_0000.exr"));
1838 assert!(check(Some(""), Some(""), "/tmp/out_0000.exr"));
1839 assert!(!check(None, None, "/tmp/out_0000.png"));
1840}
crates/engine/src/media.rs+38-12
......@@ -683,8 +683,7 @@ pub struct MediaCache {
683683 shared: Arc<MediaShared>,
684684 #[cfg(not(target_arch = "wasm32"))]
685685 staging_pool: Mutex<UploadStagingPool>,
686 #[cfg(not(target_arch = "wasm32"))]
687 nv12_gpu_state: Mutex<Option<Box<dyn std::any::Any + Send>>>,
686 nv12_gpu_state: Mutex<Option<crate::eval::Nv12Pipelines>>,
688687}
689688
690689impl Default for MediaCache {
......@@ -699,7 +698,6 @@ impl MediaCache {
699698 shared: Arc::new(MediaShared::new(budget_mb.saturating_mul(1024 * 1024))),
700699 #[cfg(not(target_arch = "wasm32"))]
701700 staging_pool: Mutex::new(UploadStagingPool::new(320 * 1024 * 1024)),
702 #[cfg(not(target_arch = "wasm32"))]
703701 nv12_gpu_state: Mutex::new(None),
704702 }
705703 }
......@@ -749,26 +747,54 @@ impl MediaCache {
749747 if let Ok(mut pool) = self.staging_pool.lock() {
750748 pool.clear();
751749 }
752 #[cfg(not(target_arch = "wasm32"))]
753750 if let Ok(mut slot) = self.nv12_gpu_state.lock() {
754751 *slot = None;
755752 }
756753 }
757754
758 #[cfg(not(target_arch = "wasm32"))]
759 pub(crate) fn with_nv12_gpu_state<T: Send + 'static, R>(
755 pub(crate) fn with_nv12_gpu_state<R>(
760756 &self,
761 init: impl FnOnce() -> T,
762 f: impl FnOnce(&mut T) -> R,
757 init: impl FnOnce() -> crate::eval::Nv12Pipelines,
758 f: impl FnOnce(&mut crate::eval::Nv12Pipelines) -> R,
763759 ) -> R {
764760 let mut slot = self.nv12_gpu_state.lock().unwrap_or_else(|e| e.into_inner());
765 let any = slot.get_or_insert_with(|| Box::new(init()));
766 let state = any
767 .downcast_mut::<T>()
768 .expect("nv12_gpu_state type mismatch");
761 let state = slot.get_or_insert_with(init);
769762 f(state)
770763 }
771764
765 pub(crate) fn reset_nv12_uniform_cursor(&self) {
766 if let Ok(mut slot) = self.nv12_gpu_state.lock() {
767 if let Some(pipe) = slot.as_mut() {
768 pipe.reset_uniform_cursor();
769 }
770 }
771 }
772
773 pub(crate) fn trim_nv12_uniform_chunks(&self, max_chunks: usize) {
774 if let Ok(mut slot) = self.nv12_gpu_state.lock() {
775 if let Some(pipe) = slot.as_mut() {
776 pipe.trim_uniform_chunks(max_chunks);
777 }
778 }
779 }
780
781 pub(crate) fn nv12_vram_bytes(&self) -> u64 {
782 self.nv12_gpu_state
783 .lock()
784 .ok()
785 .and_then(|slot| slot.as_ref().map(|pipe| pipe.vram_bytes()))
786 .unwrap_or(0)
787 }
788
789 pub(crate) fn clear_nv12_gpu_state(&self) {
790 if let Ok(mut slot) = self.nv12_gpu_state.lock() {
791 if let Some(pipe) = slot.as_mut() {
792 pipe.clear_plane_pool();
793 pipe.trim_uniform_chunks(2);
794 }
795 }
796 }
797
772798 #[cfg(not(target_arch = "wasm32"))]
773799 pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option<wgpu::Buffer> {
774800 self.staging_pool
crates/engine/src/motion_blur.rs+9-3
......@@ -596,8 +596,12 @@ impl MotionBlurPipelines {
596596 );
597597 out.tex_scale = center.tex_scale;
598598 out.edge_mode = center.edge_mode;
599 if let Some(aux) = &center.aux {
600 out.set_aux(Some(aux.clone()));
599 // Only attach `center.aux` verbatim when the union DoD matches the center sample's DoD;
600 // otherwise the caller pads/re-origins `center.aux` to `(union_origin, [uw, uh])`.
601 if center.origin == union_origin && center.size == [uw, uh] {
602 if let Some(aux) = &center.aux {
603 out.set_aux(Some(aux.clone()));
604 }
601605 }
602606
603607 let final_accum_view = if samples.len() % 2 == 1 {
......@@ -1067,7 +1071,9 @@ mod tests {
10671071 assert_eq!(tex.canvas_size, [64, 64]);
10681072 assert_eq!(tex.format, fmt);
10691073 assert_eq!(tex.depth, depth);
1070 assert!(tex.aux.as_ref().is_some_and(|a| a.z.is_some()));
1074 // Center sample had DoD [0,0] 64x64 != union [-4,-2] 72x68, so `accumulate_samples`
1075 // must NOT attach misaligned aux verbatim (caller pads/re-origins via aux_pipelines).
1076 assert!(tex.aux.is_none());
10711077 }
10721078
10731079 // Readback Rgba32Float at row y=32 (local row 32 - (-2) = 34) and verify Snow Globe
crates/engine/src/shaders/aux_ops.wgsl+47-32
......@@ -153,11 +153,17 @@ fn aux_cb_apply_op(op: i32, bg_v: f32, fg_v: f32) -> f32 {
153153 }
154154}
155155
156fn sanitize_finite(x: f32) -> f32 {
157 return select(0.0, x, x >= -1e38 && x <= 1e38);
158}
159
156160fn aux_remap(x: f32, fmin: f32, fmax: f32, tmin: f32, tmax: f32, inv: bool) -> f32 {
161 let sx = sanitize_finite(x);
157162 let denom = fmax - fmin;
158 let t = select(0.0, (x - fmin) / denom, abs(denom) > 1e-12);
163 let t = select(0.0, (sx - fmin) / denom, abs(denom) > 1e-12);
159164 let mapped = t * (tmax - tmin) + tmin;
160 return select(mapped, tmax + tmin - mapped, inv);
165 let res = select(mapped, tmax + tmin - mapped, inv);
166 return sanitize_finite(res);
161167}
162168
163169// @SECTION:DEPTH_MERGE
......@@ -192,7 +198,7 @@ fn dm_read_mask_uv(uv: vec2<f32>, has_mask: f32, invert: f32) -> f32 {
192198 return select(m, 1.0 - m, invert > 0.5);
193199}
194200
195fn dm_merge_fg_over_bg(
201fn dm_composite(
196202 bg: vec4<f32>,
197203 fg: vec4<f32>,
198204 mode: i32,
......@@ -200,53 +206,50 @@ fn dm_merge_fg_over_bg(
200206 gain: f32,
201207 burn_in: f32,
202208 sub_add: f32,
203 eff_blend: f32,
204209) -> vec4<f32> {
205210 if (mode == 0) {
206211 let fg_rgb = fg.rgb * mix(fg.a, 1.0, sub_add);
207212 let fg_a_eff = fg.a * gain;
208213 let fg_occ = fg_a_eff * (1.0 - burn_in);
209 var comp: vec4<f32>;
210214 if (op == 1) {
211215 let bg_occ = bg.a;
212 comp = vec4<f32>(bg.rgb + fg_rgb * (1.0 - bg_occ), bg.a + fg_a_eff * (1.0 - bg_occ));
216 return vec4<f32>(bg.rgb + fg_rgb * (1.0 - bg_occ), bg.a + fg_a_eff * (1.0 - bg_occ));
213217 } else if (op == 2) {
214 comp = vec4<f32>(fg_rgb, fg_a_eff) * bg.a;
218 return vec4<f32>(fg_rgb, fg_a_eff) * bg.a;
215219 } else if (op == 3) {
216 comp = vec4<f32>(fg_rgb, fg_a_eff) * (1.0 - bg.a);
220 return vec4<f32>(fg_rgb, fg_a_eff) * (1.0 - bg.a);
217221 } else if (op == 4) {
218 comp = vec4<f32>(fg_rgb * bg.a + bg.rgb * (1.0 - fg_occ), bg.a);
222 return vec4<f32>(fg_rgb * bg.a + bg.rgb * (1.0 - fg_occ), bg.a);
219223 } else if (op == 5) {
220 comp = vec4<f32>(fg_rgb, fg_a_eff) * (1.0 - bg.a) + bg * (1.0 - fg_occ);
224 return vec4<f32>(fg_rgb, fg_a_eff) * (1.0 - bg.a) + bg * (1.0 - fg_occ);
221225 } else {
222226 let over_rgb = fg_rgb + bg.rgb * (1.0 - fg_occ);
223227 let over_a = fg_a_eff + bg.a * (1.0 - fg_a_eff);
224 comp = vec4<f32>(over_rgb, over_a);
228 return vec4<f32>(over_rgb, over_a);
225229 }
226 return mix(bg, comp, eff_blend);
227230 } else if (mode == 5) {
228231 let fg_ap = fg.a * gain;
229232 let comp_rgb = abs(bg.rgb - fg.rgb * gain);
230233 let comp_a = bg.a + fg_ap * (1.0 - bg.a);
231 return mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
234 return vec4<f32>(comp_rgb, comp_a);
232235 } else if (mode == 11) {
233236 let fg_p = fg.rgb * gain;
234237 let fg_ap = fg.a * gain;
235238 let comp_rgb = clamp(bg.rgb / max(1.0 - fg_p, vec3<f32>(1e-5)), vec3<f32>(0.0), vec3<f32>(1.0));
236239 let comp_a = bg.a + fg_ap * (1.0 - bg.a);
237 return mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
240 return vec4<f32>(comp_rgb, comp_a);
238241 } else if (mode == 18) {
239242 let fg_p = fg.rgb * gain;
240243 let fg_ap = fg.a * gain;
241244 let comp_rgb = clamp(1.0 - (1.0 - bg.rgb) / max(1.0 - fg_ap + fg_p, vec3<f32>(1e-5)), vec3<f32>(0.0), vec3<f32>(1.0));
242245 let comp_a = bg.a + fg_ap * (1.0 - bg.a);
243 return mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
246 return vec4<f32>(comp_rgb, comp_a);
244247 } else if (mode == 14) {
245248 let fg_p = fg.rgb * gain;
246249 let fg_ap = fg.a * gain;
247250 let comp_rgb = sqrt(max(bg.rgb * bg.rgb + fg_p * fg_p, vec3<f32>(0.0)));
248251 let comp_a = sqrt(max(bg.a * bg.a + fg_ap * fg_ap, 0.0));
249 return mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
252 return vec4<f32>(comp_rgb, comp_a);
250253 } else if (mode == 20) {
251254 let fg_p = fg.rgb * gain;
252255 let fg_ap = fg.a * gain;
......@@ -255,7 +258,7 @@ fn dm_merge_fg_over_bg(
255258 let comp_rgb = select(vec3<f32>(0.0), (2.0 * bg.rgb * fg_p) / safe_d, denom > vec3<f32>(1e-5));
256259 let denom_a = bg.a + fg_ap;
257260 let comp_a = select(0.0, (2.0 * bg.a * fg_ap) / max(denom_a, 1e-5), denom_a > 1e-5);
258 return mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
261 return vec4<f32>(comp_rgb, comp_a);
259262 } else if (mode == 15 || mode == 16) {
260263 let fg_a_eff = fg.a * gain;
261264 let over_rgb = fg.rgb + bg.rgb * (1.0 - fg_a_eff);
......@@ -267,7 +270,7 @@ fn dm_merge_fg_over_bg(
267270 );
268271 let comp_rgb = select(bg_branch, over_rgb, pick_over);
269272 let comp_a = bg.a + fg_a_eff * (1.0 - bg.a);
270 return mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
273 return vec4<f32>(comp_rgb, comp_a);
271274 } else if (mode == 19) {
272275 let bg_u = select(vec3<f32>(0.0), bg.rgb / max(bg.a, 1e-5), bg.a > 1e-5);
273276 let fg_u = select(vec3<f32>(0.0), fg.rgb / max(fg.a, 1e-5), fg.a > 1e-5);
......@@ -275,14 +278,14 @@ fn dm_merge_fg_over_bg(
275278 let fg_eff = fg.a * gain;
276279 let comp_rgb = fg_eff * bg.a * blended + fg_eff * (1.0 - bg.a) * fg_u + (1.0 - fg_eff) * bg.rgb;
277280 let comp_a = bg.a + fg_eff * (1.0 - bg.a);
278 return mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
281 return vec4<f32>(comp_rgb, comp_a);
279282 } else {
280283 let fg_u = select(vec3<f32>(0.0), fg.rgb / max(fg.a, 1e-5), fg.a > 1e-5);
281284 let blended = aux_apply_blend_mode(bg.rgb, fg_u, mode);
282285 let fg_eff = fg.a * gain;
283286 let comp_rgb = fg_eff * blended + (1.0 - fg_eff) * bg.rgb;
284287 let comp_a = bg.a + fg_eff * (1.0 - bg.a);
285 return mix(bg, vec4<f32>(comp_rgb, comp_a), eff_blend);
288 return vec4<f32>(comp_rgb, comp_a);
286289 }
287290}
288291
......@@ -414,23 +417,26 @@ fn depth_merge_op(@builtin(global_invocation_id) gid: vec3<u32>) {
414417 var out_z: f32;
415418 if (perform_depth) {
416419 if (fg_z >= bg_z) {
417 out_col = dm_merge_fg_over_bg(bg, fg, mode, op, gain, burn_in, sub_add, eff_blend);
418 let fg_has_cov = fg_z > EMPTY_Z_THRESH && eff_blend > 0.0;
420 let comp = dm_composite(bg, fg, mode, op, gain, burn_in, sub_add);
421 out_col = mix(bg, comp, eff_blend);
422 let fg_has_cov = fg.a > 0.0 && fg_z > EMPTY_Z_THRESH && eff_blend > 0.0;
419423 out_z = select(bg_z, fg_z, fg_has_cov);
420424 } else {
421 // BG is closer than FG: composite BG over FG!
422 let fg_rgb = fg.rgb * mix(fg.a, 1.0, sub_add);
423 let fg_a_eff = fg.a * gain;
424 let bg_over_fg = vec4<f32>(
425 bg.rgb + fg_rgb * (1.0 - bg.a),
426 bg.a + fg_a_eff * (1.0 - bg.a),
427 );
428 out_col = mix(bg, bg_over_fg, eff_blend);
425 // BG is closer than FG: swap front/back roles so Operator and ApplyMode apply consistently.
426 let fg_pre = vec4<f32>(fg.rgb * mix(fg.a, 1.0, sub_add), fg.a * gain);
427 var comp: vec4<f32>;
428 if (mode != 0 && fg_pre.a <= 0.0 && all(fg_pre.rgb == vec3<f32>(0.0))) {
429 comp = bg;
430 } else {
431 comp = dm_composite(fg_pre, bg, mode, op, 1.0, burn_in, 1.0);
432 }
433 out_col = mix(bg, comp, eff_blend);
429434 out_z = bg_z;
430435 }
431436 } else {
432 out_col = dm_merge_fg_over_bg(bg, fg, mode, op, gain, burn_in, sub_add, eff_blend);
433 out_z = select(bg_z, fg_z, fg.a > 0.0 && eff_blend > 0.0);
437 let comp = dm_composite(bg, fg, mode, op, gain, burn_in, sub_add);
438 out_col = mix(bg, comp, eff_blend);
439 out_z = select(bg_z, fg_z, fg.a > 0.0 && fg_z > EMPTY_Z_THRESH && eff_blend > 0.0);
434440 }
435441
436442 if (mbm) {
......@@ -497,6 +503,8 @@ fn copy_aux_to_color_op(@builtin(global_invocation_id) gid: vec3<u32>) {
497503 var v = aux_v.r;
498504 if (remap_en) {
499505 v = aux_remap(v, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x);
506 } else {
507 v = sanitize_finite(v);
500508 }
501509 res = vec4<f32>(v, v, v, 1.0);
502510 } else if (kind == 1) {
......@@ -507,6 +515,10 @@ fn copy_aux_to_color_op(@builtin(global_invocation_id) gid: vec3<u32>) {
507515 nx = aux_remap(nx, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x);
508516 ny = aux_remap(ny, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x);
509517 nz = aux_remap(nz, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x);
518 } else {
519 nx = sanitize_finite(nx);
520 ny = sanitize_finite(ny);
521 nz = sanitize_finite(nz);
510522 }
511523 res = vec4<f32>(nx, ny, nz, 1.0);
512524 } else {
......@@ -515,6 +527,9 @@ fn copy_aux_to_color_op(@builtin(global_invocation_id) gid: vec3<u32>) {
515527 if (remap_en) {
516528 vx = aux_remap(vx, u.p[1].x, u.p[1].y, u.p[1].z, u.p[1].w, inv_x);
517529 vy = aux_remap(vy, u.p[2].x, u.p[2].y, u.p[2].z, u.p[2].w, inv_y);
530 } else {
531 vx = sanitize_finite(vx);
532 vy = sanitize_finite(vy);
518533 }
519534 res = vec4<f32>(vx, vy, 0.0, 1.0);
520535 }