authoravatarclover caruso<git@paperclover.net>2026-12-01 22:15:27-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 22:39:16-08:00
log2e5b8bde205e44f22a927aa121e3d2020398aa72
tree4eabf43d207a64c7e00fa05697cf587ee62180f1
parentd55c5cbdd1064226377fa4510c5e47cc9647091e
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

feat(engine): emit Renderer3D Z/Normal aux channels and load EXR Z channel


9 files changed, 921 insertions(+), 56 deletions(-)

crates/engine/src/eval/io.rs+155-4
......@@ -93,12 +93,23 @@ impl Engine {
9393 data: &[u8],
9494 bytes_per_pixel: u32,
9595 size: [u32; 2],
96 ) {
97 self.upload_raw_texture(enc, &tex.texture, data, bytes_per_pixel, size);
98 }
99
100 fn upload_raw_texture(
101 &self,
102 enc: &mut wgpu::CommandEncoder,
103 texture: &wgpu::Texture,
104 data: &[u8],
105 bytes_per_pixel: u32,
106 size: [u32; 2],
96107 ) {
97108 #[cfg(target_arch = "wasm32")]
98109 {
99110 let _ = enc;
100111 self.queue.write_texture(
101 tex.texture.as_image_copy(),
112 texture.as_image_copy(),
102113 data,
103114 wgpu::TexelCopyBufferLayout {
104115 offset: 0,
......@@ -168,7 +179,7 @@ impl Engine {
168179 rows_per_image: Some(h),
169180 },
170181 },
171 tex.texture.as_image_copy(),
182 texture.as_image_copy(),
172183 wgpu::Extent3d {
173184 width: w,
174185 height: h,
......@@ -181,7 +192,7 @@ impl Engine {
181192 }
182193 }
183194 self.queue.write_texture(
184 tex.texture.as_image_copy(),
195 texture.as_image_copy(),
185196 data,
186197 wgpu::TexelCopyBufferLayout {
187198 offset: 0,
......@@ -375,7 +386,7 @@ impl Engine {
375386 } else {
376387 base_tex
377388 };
378 let tex = if need_depth_conv {
389 let mut tex = if need_depth_conv {
379390 let promoted = self.alloc_tex(target_size, dst_depth, key);
380391 let u = UniformParams::default();
381392 self.dispatch_op(enc, ShaderOp::ChangeDepth, &masked_tex.view, &self.dummy.view, &self.dummy.view, &promoted, &u);
......@@ -383,6 +394,47 @@ impl Engine {
383394 } else {
384395 masked_tex
385396 };
397 if let Some(z_vals) = img.z_f32.as_ref() {
398 let expected_len = (img.size[0] as usize).saturating_mul(img.size[1] as usize);
399 if z_vals.len() == expected_len && tex.size[0] > 0 && tex.size[1] > 0 {
400 let z_tex = crate::cache::AuxChannelTex::new(
401 &self.device,
402 tex.size,
403 wgpu::TextureFormat::R32Float,
404 "loader-aux-z",
405 );
406 if z_tex.size == img.size {
407 self.upload_raw_texture(
408 enc,
409 &z_tex.texture,
410 bytemuck::cast_slice(z_vals),
411 4,
412 img.size,
413 );
414 } else {
415 let [sw, sh] = [img.size[0] as usize, img.size[1] as usize];
416 let [dw, dh] = [z_tex.size[0] as usize, z_tex.size[1] as usize];
417 let mut resampled = Vec::with_capacity(dw * dh);
418 for dy in 0..dh {
419 let sy = ((dy * sh) / dh).min(sh.saturating_sub(1));
420 for dx in 0..dw {
421 let sx = ((dx * sw) / dw).min(sw.saturating_sub(1));
422 resampled.push(z_vals[sy * sw + sx]);
423 }
424 }
425 self.upload_raw_texture(
426 enc,
427 &z_tex.texture,
428 bytemuck::cast_slice(&resampled),
429 4,
430 z_tex.size,
431 );
432 }
433 let mut aux = tex.aux_cloned();
434 aux.z = Some(z_tex);
435 tex.set_aux(Some(std::sync::Arc::new(aux)));
436 }
437 }
386438 self.cache.insert(key, tex.clone(), node.id, frame_i);
387439 tex
388440 }
......@@ -1760,4 +1812,103 @@ Composition {{
17601812 assert_eq!(oob_loop.size, [32, 32]);
17611813 let _ = std::fs::remove_dir_all(&dir);
17621814 }
1815
1816 #[test]
1817 fn loader_attaches_exr_z_channel_to_aux_with_row_padding() {
1818 use ::exr::prelude::*;
1819
1820 let w = 13usize;
1821 let h = 7usize;
1822 let z_expected: Vec<f32> = (0..(w * h))
1823 .map(|i| if i % 5 == 0 { crate::cache::EMPTY_Z_SENTINEL } else { -1.25 - (i as f32) * 0.125 })
1824 .collect();
1825 let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
1826 channels.push(AnyChannel::new("R", FlatSamples::F32(vec![0.8; w * h])));
1827 channels.push(AnyChannel::new("G", FlatSamples::F32(vec![0.4; w * h])));
1828 channels.push(AnyChannel::new("B", FlatSamples::F32(vec![0.2; w * h])));
1829 channels.push(AnyChannel::new("A", FlatSamples::F32(vec![1.0; w * h])));
1830 channels.push(AnyChannel::new("Z", FlatSamples::F32(z_expected.clone())));
1831 let image = Image::from_layer(Layer::new(
1832 Vec2(w, h),
1833 LayerAttributes::default(),
1834 Encoding::UNCOMPRESSED,
1835 AnyChannels::sort(channels),
1836 ));
1837 let dir = std::env::temp_dir().join(format!("fission_loader_exr_z_{}", std::process::id()));
1838 let _ = std::fs::create_dir_all(&dir);
1839 let exr_path = dir.join("z_plate.exr");
1840 image.write().to_file(&exr_path).expect("write synthetic Z EXR");
1841
1842 let comp_src = format!(
1843 r#"Composition {{
1844 CurrentTime = 0,
1845 RenderRange = {{ 0, 1 }},
1846 GlobalRange = {{ 0, 1 }},
1847 Tools = ordered() {{
1848 L = Loader {{
1849 Clips = {{ Clip {{ ID = "Clip1", Filename = "{}", Length = 1, GlobalStart = 0, GlobalEnd = 0, }} }},
1850 }},
1851 }},
1852 }}"#,
1853 exr_path.display()
1854 );
1855 let comp = Comp::from_fusion_str(&comp_src).expect("parse EXR Loader comp");
1856 let Ok(mut eng) = Engine::new_headless() else {
1857 let _ = std::fs::remove_dir_all(&dir);
1858 return;
1859 };
1860 let (tex, _) = eng.evaluate(&comp, comp.find_node("L").unwrap(), 0.0);
1861 let aux = tex.aux.as_ref().expect("Loader must attach aux for EXR with Z channel");
1862 let z_tex = aux.z.as_ref().expect("aux.z must be present");
1863 assert_eq!(z_tex.size, [w as u32, h as u32]);
1864 assert_eq!(z_tex.format, wgpu::TextureFormat::R32Float);
1865
1866 let unpadded_bpr = (w as u32) * 4;
1867 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1868 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
1869 let buf = eng.device.create_buffer(&wgpu::BufferDescriptor {
1870 label: Some("readback-exr-z"),
1871 size: u64::from(padded_bpr) * u64::from(h as u32),
1872 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1873 mapped_at_creation: false,
1874 });
1875 let mut enc = eng.device.create_command_encoder(&Default::default());
1876 enc.copy_texture_to_buffer(
1877 z_tex.texture.as_image_copy(),
1878 wgpu::TexelCopyBufferInfo {
1879 buffer: &buf,
1880 layout: wgpu::TexelCopyBufferLayout {
1881 offset: 0,
1882 bytes_per_row: Some(padded_bpr),
1883 rows_per_image: Some(h as u32),
1884 },
1885 },
1886 wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 },
1887 );
1888 eng.queue.submit(Some(enc.finish()));
1889 let slice = buf.slice(..);
1890 let (tx, rx) = std::sync::mpsc::channel();
1891 slice.map_async(wgpu::MapMode::Read, move |res| {
1892 let _ = tx.send(res);
1893 });
1894 eng.device
1895 .poll(wgpu::PollType::Wait {
1896 submission_index: None,
1897 timeout: Some(std::time::Duration::from_secs(10)),
1898 })
1899 .unwrap();
1900 rx.recv().unwrap().unwrap();
1901 let data = slice.get_mapped_range().unwrap();
1902 let mut got = Vec::with_capacity(w * h);
1903 for y in 0..h {
1904 let start = y * padded_bpr as usize;
1905 let row_bytes = &data[start..start + unpadded_bpr as usize];
1906 got.extend_from_slice(bytemuck::cast_slice::<u8, f32>(row_bytes));
1907 }
1908 drop(data);
1909 buf.unmap();
1910 let _ = std::fs::remove_dir_all(&dir);
1911
1912 assert_eq!(got, z_expected, "Loader aux.z must match exact EXR float32 depth values");
1913 }
17631914}
crates/engine/src/eval/text_3d.rs+14-2
......@@ -881,9 +881,15 @@ impl Engine {
881881 let (size, tex_scale) = crate::cache::clamp_dims_to_limit(raw_size[0], raw_size[1], max_dim);
882882 let aspect = (size[0] as f32 / size[1].max(1) as f32).max(1e-4);
883883
884 let want_z = comp.eval_number(node, "RendererSoftware.Channels.Z", time, 0.0, &self.expr) >= 0.5
885 || comp.eval_number(node, "RendererOpenGL.Channels.Z", time, 0.0, &self.expr) >= 0.5;
886 let want_normal = comp.eval_number(node, "RendererSoftware.Channels.Normal", time, 0.0, &self.expr) >= 0.5
887 || comp.eval_number(node, "RendererOpenGL.Channels.Normal", time, 0.0, &self.expr) >= 0.5;
888
884889 let Some(scene_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
885890 let mut empty = create_texture(&self.device, size, 0);
886891 empty.tex_scale = tex_scale;
892 crate::scene3d::Scene3DRenderer::attach_empty_aux(&self.device, &self.queue, &mut empty, want_z, want_normal);
887893 return empty;
888894 };
889895
......@@ -921,6 +927,7 @@ impl Engine {
921927 if bad_clip {
922928 let mut empty = create_texture(&self.device, size, 0);
923929 empty.tex_scale = tex_scale;
930 crate::scene3d::Scene3DRenderer::attach_empty_aux(&self.device, &self.queue, &mut empty, want_z, want_normal);
924931 return empty;
925932 }
926933 let v = crate::scene3d::mat4_inverse(cam.world);
......@@ -962,6 +969,8 @@ impl Engine {
962969 hash_floats.extend_from_slice(&view_proj);
963970 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });
964971 hash_floats.push(if shadows_enabled { 1.0 } else { 0.0 });
972 hash_floats.push(if want_z { 1.0 } else { 0.0 });
973 hash_floats.push(if want_normal { 1.0 } else { 0.0 });
965974 hash_floats.extend_from_slice(&lights.ambient);
966975 hash_floats.push(lights.count as f32);
967976 for dl in &lights.dirs {
......@@ -1126,19 +1135,22 @@ impl Engine {
11261135
11271136 let mut dst = create_texture(&self.device, size, key);
11281137 dst.tex_scale = tex_scale;
1129 self.scene3d.render_meshes(
1138 self.scene3d.render_meshes_with_aux(
11301139 &self.device,
11311140 &self.queue,
11321141 enc,
1133 &dst,
1142 &mut dst,
11341143 &self.dummy,
11351144 view_proj,
11361145 view,
1146 proj,
11371147 cam_pos,
11381148 cam_far,
11391149 lights,
11401150 lighting_enabled,
11411151 shadows_enabled,
1152 want_z,
1153 want_normal,
11421154 &draw_meshes,
11431155 );
11441156 self.cache.insert(key, dst.clone(), node.id, frame_i);
crates/engine/src/media.rs+9-1
......@@ -53,6 +53,9 @@ pub struct DecodedImage {
5353 /// Optional unclamped linear HDR RGBA32F pixels (`[r, g, b, a, ...]`, top-down),
5454 /// populated for OpenEXR images to preserve HDR highlights `> 1.0` and negative values.
5555 pub rgba_f32: Option<Arc<Vec<f32>>>,
56 /// Optional single-channel `f32` Z-depth buffer (`[w * h]`, top-down), populated when
57 /// an OpenEXR file contains a `Z` channel (`"Z"`, `"z"`, or `"*.Z"`).
58 pub z_f32: Option<Arc<Vec<f32>>>,
5659}
5760
5861impl DecodedImage {
......@@ -66,7 +69,11 @@ impl DecodedImage {
6669 .rgba_f32
6770 .as_ref()
6871 .map_or(0, |v| (v.len() * std::mem::size_of::<f32>()) as u64);
69 u8_bytes + f16_bytes + f32_bytes
72 let z_bytes = self
73 .z_f32
74 .as_ref()
75 .map_or(0, |v| (v.len() * std::mem::size_of::<f32>()) as u64);
76 u8_bytes + f16_bytes + f32_bytes + z_bytes
7077 }
7178}
7279
......@@ -822,6 +829,7 @@ impl MediaCache {
822829 rgba: Arc::new(raw),
823830 rgba_f16: None,
824831 rgba_f32: None,
832 z_f32: None,
825833 };
826834
827835 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
crates/engine/src/media/exr.rs+132-9
......@@ -176,6 +176,47 @@ pub(super) fn find_exr_channel_loc(
176176 None
177177}
178178
179/// Finds a `Z` depth channel (`"Z"`, `"z"`, or ending in `".Z"`/`".z"`, e.g. `"depth.Z"`)
180/// in a layer matching `(w, h)`. Exact `"Z"`/`"z"` takes priority over suffixed channels.
181fn find_exr_z_loc(
182 headers: &[::exr::meta::header::Header],
183 w: usize,
184 h: usize,
185) -> Option<(usize, usize)> {
186 let valid_layer = |header: &::exr::meta::header::Header| {
187 !header.deep && header.layer_size.width() == w && header.layer_size.height() == h
188 };
189 let is_suffixed_z = |full: &str| {
190 full.contains('.')
191 && full
192 .rsplit('.')
193 .next()
194 .is_some_and(|s| s.eq_ignore_ascii_case("z"))
195 };
196 let matchers: [&dyn Fn(&str) -> bool; 2] = [
197 &|full: &str| full.eq_ignore_ascii_case("z"),
198 &is_suffixed_z,
199 ];
200 for pred in matchers {
201 for (li, header) in headers.iter().enumerate() {
202 if !valid_layer(header) {
203 continue;
204 }
205 let lname = header.own_attributes.layer_name.as_ref().map(|t| t.to_string());
206 for (ci, ch) in header.channels.list.iter().enumerate() {
207 if ch.sampling != ::exr::math::Vec2(1, 1) {
208 continue;
209 }
210 let full = full_exr_channel_name(lname.as_deref(), &ch.name.to_string());
211 if pred(&full) {
212 return Some((li, ci));
213 }
214 }
215 }
216 }
217 None
218}
219
179220/// Decodes a single-layer or multi-layer (Blender `ViewLayer.Combined.R/G/B/A`) OpenEXR
180221/// selectively for only the matched RGBA channels, producing clamped RGBA8 and linear HDR
181222/// RGBA16F/RGBA32F buffers without decoding unrelated AOV/Cryptomatte layers.
......@@ -332,15 +373,29 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
332373 let g_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, green_name, "G", "g");
333374 let b_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, blue_name, "B", "b");
334375 let a_loc = find_exr_channel_loc(chunks_reader.headers(), w, h, alpha_name, "A", "a");
376 let z_loc = find_exr_z_loc(chunks_reader.headers(), w, h);
335377
336378 let target_locs = [Some(r_loc), g_loc, b_loc, a_loc];
337 let mut needed_layers: Vec<usize> = target_locs.iter().flatten().map(|(l, _)| *l).collect();
379 let mut needed_layers: Vec<usize> = target_locs
380 .iter()
381 .chain(std::iter::once(&z_loc))
382 .flatten()
383 .map(|(l, _)| *l)
384 .collect();
338385 needed_layers.sort_unstable();
339386 needed_layers.dedup();
340387
341388 let mut raw_f32 = Vec::new();
342389 raw_f32.try_reserve_exact(elem_count).ok()?;
343390 raw_f32.resize(elem_count, 0.0_f32);
391 let mut z_raw_f32 = if z_loc.is_some() {
392 let mut v = Vec::new();
393 v.try_reserve_exact(pixel_count).ok()?;
394 v.resize(pixel_count, crate::cache::EMPTY_Z_SENTINEL);
395 Some(v)
396 } else {
397 None
398 };
344399 let mut line_f32 = Vec::<f32>::new();
345400 let mut line_f16 = Vec::<f16>::new();
346401 let mut line_u32 = Vec::<u32>::new();
......@@ -360,7 +415,8 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
360415 comp_mask[c] = true;
361416 }
362417 }
363 if !comp_mask.iter().any(|&m| m) {
418 let write_z = z_loc == Some(loc);
419 if !comp_mask.iter().any(|&m| m) && !write_z {
364420 continue;
365421 }
366422 let y = line.location.position.y();
......@@ -388,13 +444,27 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
388444 }
389445 }
390446
391 let row_base = (y * w + x0) * 4;
392 for (dx, &sample) in line_f32.iter().enumerate() {
393 let val = if sample.is_nan() { 0.0 } else { sample };
394 let px_off = row_base + dx * 4;
395 for (c, &enabled) in comp_mask.iter().enumerate() {
396 if enabled {
397 raw_f32[px_off + c] = val;
447 if comp_mask.iter().any(|&m| m) {
448 let row_base = (y * w + x0) * 4;
449 for (dx, &sample) in line_f32.iter().enumerate() {
450 let val = if sample.is_nan() { 0.0 } else { sample };
451 let px_off = row_base + dx * 4;
452 for (c, &enabled) in comp_mask.iter().enumerate() {
453 if enabled {
454 raw_f32[px_off + c] = val;
455 }
456 }
457 }
458 }
459 if write_z {
460 if let Some(ref mut z_vec) = z_raw_f32 {
461 let z_row_base = y * w + x0;
462 for (dx, &sample) in line_f32.iter().enumerate() {
463 z_vec[z_row_base + dx] = if sample.is_nan() {
464 crate::cache::EMPTY_Z_SENTINEL
465 } else {
466 sample
467 };
398468 }
399469 }
400470 }
......@@ -428,6 +498,7 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
428498 rgba: Arc::new(raw),
429499 rgba_f16: Some(Arc::new(raw_f16)),
430500 rgba_f32: Some(Arc::new(raw_f32)),
501 z_f32: z_raw_f32.map(Arc::new),
431502 })
432503}
433504
......@@ -518,4 +589,56 @@ mod tests {
518589 assert_eq!(par_bits, seq_bits, "f32 bits mismatch for ({has_g},{has_b},{has_a},{post_multiply})");
519590 }
520591 }
592
593 #[test]
594 fn exr_decodes_z_channel_and_suffixed_z_with_nan_fallback() {
595 use ::exr::prelude::*;
596
597 let write_exr = |z_chan_name: Option<&str>, z_vals: &[f32]| -> Vec<u8> {
598 let size = Vec2(3usize, 2usize);
599 let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
600 let rgba = [1.0_f32, 0.5, 0.25, 1.0];
601 for (name, val) in [("R", rgba[0]), ("G", rgba[1]), ("B", rgba[2]), ("A", rgba[3])] {
602 channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; 6])));
603 }
604 if let Some(zn) = z_chan_name {
605 channels.push(AnyChannel::new(zn, FlatSamples::F32(z_vals.to_vec())));
606 }
607 let image = Image::from_layer(Layer::new(
608 size,
609 LayerAttributes::default(),
610 Encoding::UNCOMPRESSED,
611 AnyChannels::sort(channels),
612 ));
613 let mut buf = std::io::Cursor::new(Vec::new());
614 image.write().to_buffered(&mut buf).unwrap();
615 buf.into_inner()
616 };
617
618 // 1. EXR without Z channel -> z_f32 is None.
619 let no_z = write_exr(None, &[]);
620 assert!(MediaCache::insert_virtual_bytes("vexr_z/no_z.exr", no_z));
621 let dec_no_z = decode_exr_rgba(Path::new("vexr_z/no_z.exr"), None, None, None, None, false, true).unwrap();
622 assert!(dec_no_z.z_f32.is_none());
623
624 // 2. EXR with bare "Z" channel including NaN -> NaN mapped to EMPTY_Z_SENTINEL.
625 let z_expected = [-2.5_f32, -3.0, -4.25, f32::NAN, -10.0, crate::cache::EMPTY_Z_SENTINEL];
626 let with_z = write_exr(Some("Z"), &z_expected);
627 assert!(MediaCache::insert_virtual_bytes("vexr_z/with_z.exr", with_z));
628 let dec_z = decode_exr_rgba(Path::new("vexr_z/with_z.exr"), None, None, None, None, false, true).unwrap();
629 let got_z = dec_z.z_f32.expect("z_f32 populated");
630 assert_eq!(
631 got_z.as_slice(),
632 &[-2.5_f32, -3.0, -4.25, crate::cache::EMPTY_Z_SENTINEL, -10.0, crate::cache::EMPTY_Z_SENTINEL]
633 );
634
635 // 3. EXR with suffixed "depth.Z" channel -> also decoded into z_f32.
636 let depth_z = write_exr(Some("depth.Z"), &[-1.5, -2.0, -2.5, -3.0, -3.5, -4.0]);
637 assert!(MediaCache::insert_virtual_bytes("vexr_z/depth_z.exr", depth_z));
638 let dec_dz = decode_exr_rgba(Path::new("vexr_z/depth_z.exr"), None, None, None, None, false, false).unwrap();
639 assert_eq!(
640 dec_dz.z_f32.expect("depth.Z populated").as_slice(),
641 &[-1.5, -2.0, -2.5, -3.0, -3.5, -4.0]
642 );
643 }
521644}
crates/engine/src/media/png.rs+1
......@@ -246,5 +246,6 @@ pub(super) fn decode_raster_image(
246246 rgba: Arc::new(raw),
247247 rgba_f16: None,
248248 rgba_f32: None,
249 z_f32: None,
249250 })
250251}
crates/engine/src/media/prefetch.rs+2
......@@ -282,6 +282,7 @@ impl MediaCache {
282282 rgba: Arc::new(raw),
283283 rgba_f16: None,
284284 rgba_f32: None,
285 z_f32: None,
285286 };
286287 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
287288 state.in_flight.remove(&key);
......@@ -719,6 +720,7 @@ impl MediaPrefetchHandle {
719720 rgba: Arc::new(raw),
720721 rgba_f16: None,
721722 rgba_f32: None,
723 z_f32: None,
722724 };
723725 let unthrottled = if let Ok(mut state) = shared.state.lock() {
724726 state.in_flight.remove(&key);
crates/engine/src/media/tests.rs+1
......@@ -1180,6 +1180,7 @@ Tools = ordered() {{
11801180 rgba: Arc::clone(&four_mb),
11811181 rgba_f16: None,
11821182 rgba_f32: None,
1183 z_f32: None,
11831184 };
11841185 cache.shared.insert_cached_locked(&mut state, key, img);
11851186 }
crates/engine/src/scene3d/mod.rs+512-40
......@@ -26,10 +26,13 @@ fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
2626 m.lock().unwrap_or_else(|e| e.into_inner())
2727}
2828
29use crate::cache::CachedTexture;
29use crate::cache::{AuxChannelTex, AuxChannels, CachedTexture, EMPTY_Z_SENTINEL};
3030use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};
3131use model::NodeId;
32use shader::{MeshUniform, ShadowUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER, UV_XFORM_WGSL};
32use shader::{
33 DepthToEyeZUniform, MeshUniform, ShadowUniform, DEPTH_TO_EYE_Z_SHADER, MAX_DIR_LIGHTS,
34 MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER, UV_XFORM_WGSL,
35};
3336
3437pub type Mat4 = [f32; 16]; // Column-major 4x4
3538
......@@ -38,6 +41,11 @@ pub struct Scene3DRenderer {
3841 /// `[triangles, lines][back-facing, front-facing]`; back faces draw first so translucent
3942 /// faces show the inside of closed meshes.
4043 pipelines: [[wgpu::RenderPipeline; 2]; 2],
44 /// Normal-channel pass `[triangles, lines][back-facing, front-facing]` writing `Rgba16Float`.
45 normal_pipelines: [[wgpu::RenderPipeline; 2]; 2],
46 /// Compute pass converting `Depth32Float` into eye-space `Z` (`R32Float`).
47 depth_z_bgl: wgpu::BindGroupLayout,
48 depth_z_pipeline: wgpu::ComputePipeline,
4149 sampler: wgpu::Sampler,
4250 meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>,
4351 /// Memoized CPU `Text3D` extruded meshes keyed by deterministic geometry content hash.
......@@ -708,46 +716,130 @@ impl Scene3DRenderer {
708716 wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 },
709717 ],
710718 };
711 let make_pipeline = |topology: wgpu::PrimitiveTopology, back_pass: bool| device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
712 label: Some("scene3d-mesh"),
713 layout: Some(&pl),
714 vertex: wgpu::VertexState {
715 module: &shader,
716 entry_point: Some("vs_mesh"),
717 compilation_options: Default::default(),
718 buffers: &[Some(vbuf_layout.clone())],
719 },
720 fragment: Some(wgpu::FragmentState {
721 module: &shader,
722 entry_point: Some("fs_mesh"),
723 compilation_options: wgpu::PipelineCompilationOptions {
724 constants: &[("BACK_PASS", if back_pass { 1.0 } else { 0.0 })],
719 let make_pipeline = |topology: wgpu::PrimitiveTopology,
720 back_pass: bool,
721 fs_entry: &'static str,
722 target_format: wgpu::TextureFormat,
723 blend: Option<wgpu::BlendState>| {
724 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
725 label: Some("scene3d-mesh"),
726 layout: Some(&pl),
727 vertex: wgpu::VertexState {
728 module: &shader,
729 entry_point: Some("vs_mesh"),
730 compilation_options: Default::default(),
731 buffers: &[Some(vbuf_layout.clone())],
732 },
733 fragment: Some(wgpu::FragmentState {
734 module: &shader,
735 entry_point: Some(fs_entry),
736 compilation_options: wgpu::PipelineCompilationOptions {
737 constants: &[("BACK_PASS", if back_pass { 1.0 } else { 0.0 })],
738 ..Default::default()
739 },
740 targets: &[Some(wgpu::ColorTargetState {
741 format: target_format,
742 blend,
743 write_mask: wgpu::ColorWrites::ALL,
744 })],
745 }),
746 primitive: wgpu::PrimitiveState {
747 topology,
748 cull_mode: None,
725749 ..Default::default()
726750 },
727 targets: &[Some(wgpu::ColorTargetState {
728 format: wgpu::TextureFormat::Rgba8Unorm,
729 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
730 write_mask: wgpu::ColorWrites::ALL,
731 })],
732 }),
733 primitive: wgpu::PrimitiveState {
734 topology,
735 cull_mode: None,
736 ..Default::default()
737 },
738 depth_stencil: Some(wgpu::DepthStencilState {
739 format: wgpu::TextureFormat::Depth32Float,
740 depth_write_enabled: Some(true),
741 depth_compare: Some(wgpu::CompareFunction::Less),
742 stencil: wgpu::StencilState::default(),
743 bias: wgpu::DepthBiasState::default(),
744 }),
745 multisample: wgpu::MultisampleState::default(),
746 multiview_mask: None,
751 depth_stencil: Some(wgpu::DepthStencilState {
752 format: wgpu::TextureFormat::Depth32Float,
753 depth_write_enabled: Some(true),
754 depth_compare: Some(wgpu::CompareFunction::Less),
755 stencil: wgpu::StencilState::default(),
756 bias: wgpu::DepthBiasState::default(),
757 }),
758 multisample: wgpu::MultisampleState::default(),
759 multiview_mask: None,
760 cache: None,
761 })
762 };
763 let pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList]
764 .map(|topology| {
765 [
766 make_pipeline(
767 topology,
768 true,
769 "fs_mesh",
770 wgpu::TextureFormat::Rgba8Unorm,
771 Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
772 ),
773 make_pipeline(
774 topology,
775 false,
776 "fs_mesh",
777 wgpu::TextureFormat::Rgba8Unorm,
778 Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
779 ),
780 ]
781 });
782 let normal_pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList]
783 .map(|topology| {
784 [
785 make_pipeline(topology, true, "fs_normal", wgpu::TextureFormat::Rgba16Float, None),
786 make_pipeline(topology, false, "fs_normal", wgpu::TextureFormat::Rgba16Float, None),
787 ]
788 });
789 let depth_z_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
790 label: Some("scene3d-depth-z-shader"),
791 source: wgpu::ShaderSource::Wgsl(DEPTH_TO_EYE_Z_SHADER.into()),
792 });
793 let depth_z_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
794 label: Some("scene3d-depth-z-bgl"),
795 entries: &[
796 wgpu::BindGroupLayoutEntry {
797 binding: 0,
798 visibility: wgpu::ShaderStages::COMPUTE,
799 ty: wgpu::BindingType::Texture {
800 sample_type: wgpu::TextureSampleType::Depth,
801 view_dimension: wgpu::TextureViewDimension::D2,
802 multisampled: false,
803 },
804 count: None,
805 },
806 wgpu::BindGroupLayoutEntry {
807 binding: 1,
808 visibility: wgpu::ShaderStages::COMPUTE,
809 ty: wgpu::BindingType::StorageTexture {
810 access: wgpu::StorageTextureAccess::WriteOnly,
811 format: wgpu::TextureFormat::R32Float,
812 view_dimension: wgpu::TextureViewDimension::D2,
813 },
814 count: None,
815 },
816 wgpu::BindGroupLayoutEntry {
817 binding: 2,
818 visibility: wgpu::ShaderStages::COMPUTE,
819 ty: wgpu::BindingType::Buffer {
820 ty: wgpu::BufferBindingType::Uniform,
821 has_dynamic_offset: false,
822 min_binding_size: std::num::NonZeroU64::new(
823 std::mem::size_of::<DepthToEyeZUniform>() as u64,
824 ),
825 },
826 count: None,
827 },
828 ],
829 });
830 let depth_z_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
831 label: Some("scene3d-depth-z-pl"),
832 bind_group_layouts: &[Some(&depth_z_bgl)],
833 immediate_size: 0,
834 });
835 let depth_z_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
836 label: Some("scene3d-depth-to-eye-z"),
837 layout: Some(&depth_z_pl),
838 module: &depth_z_shader,
839 entry_point: Some("depth_to_eye_z"),
840 compilation_options: Default::default(),
747841 cache: None,
748842 });
749 let pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList]
750 .map(|topology| [make_pipeline(topology, true), make_pipeline(topology, false)]);
751843 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
752844 label: Some("scene3d-linear"),
753845 address_mode_u: wgpu::AddressMode::ClampToEdge,
......@@ -849,6 +941,9 @@ impl Scene3DRenderer {
849941 Self {
850942 bgl,
851943 pipelines,
944 normal_pipelines,
945 depth_z_bgl,
946 depth_z_pipeline,
852947 sampler,
853948 meshes: Mutex::new(Lru::with_byte_cap(
854949 MAX_CACHED_MESH_BUFFERS,
......@@ -937,6 +1032,61 @@ impl Scene3DRenderer {
9371032 lock_or_recover(&self.meshes).entries.len()
9381033 }
9391034
1035 /// Attaches empty sky auxiliary channels (`EMPTY_Z_SENTINEL` for Z, `(0,0,0,0)` for Normal)
1036 /// when a `Renderer3D` exits early (e.g. disconnected `SceneInput` or invalid clip planes).
1037 pub fn attach_empty_aux(
1038 device: &wgpu::Device,
1039 queue: &wgpu::Queue,
1040 dst: &mut CachedTexture,
1041 want_z: bool,
1042 want_normal: bool,
1043 ) {
1044 if !want_z && !want_normal {
1045 return;
1046 }
1047 let size = [dst.size[0].max(1), dst.size[1].max(1)];
1048 let mut aux = dst.aux_cloned();
1049 if want_z {
1050 let z_tex = AuxChannelTex::new(device, size, wgpu::TextureFormat::R32Float, "scene3d-aux-z");
1051 let data = vec![EMPTY_Z_SENTINEL; (z_tex.size[0] as usize) * (z_tex.size[1] as usize)];
1052 queue.write_texture(
1053 z_tex.texture.as_image_copy(),
1054 bytemuck::cast_slice(&data),
1055 wgpu::TexelCopyBufferLayout {
1056 offset: 0,
1057 bytes_per_row: Some(z_tex.size[0] * 4),
1058 rows_per_image: Some(z_tex.size[1]),
1059 },
1060 wgpu::Extent3d {
1061 width: z_tex.size[0],
1062 height: z_tex.size[1],
1063 depth_or_array_layers: 1,
1064 },
1065 );
1066 aux.z = Some(z_tex);
1067 }
1068 if want_normal {
1069 let normal_tex = AuxChannelTex::new(device, size, wgpu::TextureFormat::Rgba16Float, "scene3d-aux-normal");
1070 let data = vec![0u16; (normal_tex.size[0] as usize) * (normal_tex.size[1] as usize) * 4];
1071 queue.write_texture(
1072 normal_tex.texture.as_image_copy(),
1073 bytemuck::cast_slice(&data),
1074 wgpu::TexelCopyBufferLayout {
1075 offset: 0,
1076 bytes_per_row: Some(normal_tex.size[0] * 8),
1077 rows_per_image: Some(normal_tex.size[1]),
1078 },
1079 wgpu::Extent3d {
1080 width: normal_tex.size[0],
1081 height: normal_tex.size[1],
1082 depth_or_array_layers: 1,
1083 },
1084 );
1085 aux.normal = Some(normal_tex);
1086 }
1087 dst.set_aux(Some(Arc::new(aux)));
1088 }
1089
9401090 #[allow(clippy::too_many_arguments)]
9411091 pub fn render_meshes(
9421092 &self,
......@@ -954,6 +1104,95 @@ impl Scene3DRenderer {
9541104 shadows_enabled: bool,
9551105 meshes: &[DrawMesh],
9561106 ) {
1107 let _ = self.render_meshes_inner(
1108 device,
1109 queue,
1110 enc,
1111 dst,
1112 dummy,
1113 view_proj,
1114 view,
1115 mat4_identity(),
1116 cam_pos,
1117 cam_far,
1118 lights,
1119 lighting_enabled,
1120 shadows_enabled,
1121 false,
1122 false,
1123 meshes,
1124 );
1125 }
1126
1127 #[allow(clippy::too_many_arguments)]
1128 pub fn render_meshes_with_aux(
1129 &self,
1130 device: &wgpu::Device,
1131 queue: &wgpu::Queue,
1132 enc: &mut wgpu::CommandEncoder,
1133 dst: &mut CachedTexture,
1134 dummy: &CachedTexture,
1135 view_proj: Mat4,
1136 view: Mat4,
1137 proj: Mat4,
1138 cam_pos: [f32; 3],
1139 cam_far: f32,
1140 lights: SceneLights,
1141 lighting_enabled: bool,
1142 shadows_enabled: bool,
1143 want_z: bool,
1144 want_normal: bool,
1145 meshes: &[DrawMesh],
1146 ) {
1147 if let Some(aux) = self.render_meshes_inner(
1148 device,
1149 queue,
1150 enc,
1151 dst,
1152 dummy,
1153 view_proj,
1154 view,
1155 proj,
1156 cam_pos,
1157 cam_far,
1158 lights,
1159 lighting_enabled,
1160 shadows_enabled,
1161 want_z,
1162 want_normal,
1163 meshes,
1164 ) {
1165 let mut merged = dst.aux_cloned();
1166 if aux.z.is_some() {
1167 merged.z = aux.z;
1168 }
1169 if aux.normal.is_some() {
1170 merged.normal = aux.normal;
1171 }
1172 dst.set_aux(Some(Arc::new(merged)));
1173 }
1174 }
1175
1176 #[allow(clippy::too_many_arguments)]
1177 fn render_meshes_inner(
1178 &self,
1179 device: &wgpu::Device,
1180 queue: &wgpu::Queue,
1181 enc: &mut wgpu::CommandEncoder,
1182 dst: &CachedTexture,
1183 dummy: &CachedTexture,
1184 view_proj: Mat4,
1185 view: Mat4,
1186 proj: Mat4,
1187 cam_pos: [f32; 3],
1188 cam_far: f32,
1189 lights: SceneLights,
1190 lighting_enabled: bool,
1191 shadows_enabled: bool,
1192 want_z: bool,
1193 want_normal: bool,
1194 meshes: &[DrawMesh],
1195 ) -> Option<AuxChannels> {
9571196 let depth_size = [dst.size[0].max(1), dst.size[1].max(1)];
9581197 let depth_target = lock_or_recover(&self.depth_targets).get_or_insert_with(depth_size, || {
9591198 let tex = device.create_texture(&wgpu::TextureDescriptor {
......@@ -967,7 +1206,7 @@ impl Scene3DRenderer {
9671206 sample_count: 1,
9681207 dimension: wgpu::TextureDimension::D2,
9691208 format: wgpu::TextureFormat::Depth32Float,
970 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1209 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
9711210 view_formats: &[],
9721211 });
9731212 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
......@@ -1407,7 +1646,7 @@ impl Scene3DRenderer {
14071646 view: depth_view,
14081647 depth_ops: Some(wgpu::Operations {
14091648 load: wgpu::LoadOp::Clear(1.0),
1410 store: wgpu::StoreOp::Discard,
1649 store: if want_z { wgpu::StoreOp::Store } else { wgpu::StoreOp::Discard },
14111650 }),
14121651 stencil_ops: None,
14131652 }),
......@@ -1426,6 +1665,102 @@ impl Scene3DRenderer {
14261665 }
14271666 }
14281667 }
1668 drop(pass);
1669
1670 if !want_z && !want_normal {
1671 return None;
1672 }
1673
1674 let mut aux = AuxChannels::default();
1675 if want_z {
1676 let z_tex = AuxChannelTex::new(device, depth_size, wgpu::TextureFormat::R32Float, "scene3d-aux-z");
1677 let depth_z_uni = DepthToEyeZUniform {
1678 proj_zw: [proj[10], proj[11], proj[14], proj[15]],
1679 params: [EMPTY_Z_SENTINEL, 0.0, 0.0, 0.0],
1680 };
1681 let depth_z_ubuf = cached_uniform_buffer(
1682 &self.uniform_cache,
1683 device,
1684 "scene3d-depth-z-u",
1685 bytemuck::bytes_of(&depth_z_uni),
1686 );
1687 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
1688 label: Some("scene3d-depth-z-bg"),
1689 layout: &self.depth_z_bgl,
1690 entries: &[
1691 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(depth_view) },
1692 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&z_tex.view) },
1693 wgpu::BindGroupEntry { binding: 2, resource: depth_z_ubuf.as_entire_binding() },
1694 ],
1695 });
1696 let mut cpass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
1697 label: Some("scene3d-depth-to-eye-z"),
1698 timestamp_writes: None,
1699 });
1700 cpass.set_pipeline(&self.depth_z_pipeline);
1701 cpass.set_bind_group(0, &bg, &[]);
1702 cpass.dispatch_workgroups(z_tex.size[0].div_ceil(8), z_tex.size[1].div_ceil(8), 1);
1703 aux.z = Some(z_tex);
1704 }
1705
1706 if want_normal {
1707 let normal_raw = device.create_texture(&wgpu::TextureDescriptor {
1708 label: Some("scene3d-aux-normal"),
1709 size: wgpu::Extent3d {
1710 width: depth_size[0],
1711 height: depth_size[1],
1712 depth_or_array_layers: 1,
1713 },
1714 mip_level_count: 1,
1715 sample_count: 1,
1716 dimension: wgpu::TextureDimension::D2,
1717 format: wgpu::TextureFormat::Rgba16Float,
1718 usage: wgpu::TextureUsages::RENDER_ATTACHMENT
1719 | wgpu::TextureUsages::TEXTURE_BINDING
1720 | wgpu::TextureUsages::COPY_SRC
1721 | wgpu::TextureUsages::COPY_DST,
1722 view_formats: &[],
1723 });
1724 let normal_tex = AuxChannelTex::from_texture(normal_raw, depth_size);
1725 let mut npass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
1726 label: Some("scene3d-normal-pass"),
1727 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1728 view: &normal_tex.view,
1729 depth_slice: None,
1730 resolve_target: None,
1731 ops: wgpu::Operations {
1732 load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
1733 store: wgpu::StoreOp::Store,
1734 },
1735 })],
1736 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
1737 view: depth_view,
1738 depth_ops: Some(wgpu::Operations {
1739 load: wgpu::LoadOp::Clear(1.0),
1740 store: wgpu::StoreOp::Discard,
1741 }),
1742 stencil_ops: None,
1743 }),
1744 timestamp_writes: None,
1745 occlusion_query_set: None,
1746 multiview_mask: None,
1747 });
1748 for d in &draw_items {
1749 npass.set_bind_group(0, &d.bg, &[d.uni_offset]);
1750 npass.set_vertex_buffer(0, d.vbuf.slice(..));
1751 npass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32);
1752 for (pipeline, culled) in self.normal_pipelines[d.wireframe as usize].iter().zip(d.cull) {
1753 if !culled {
1754 npass.set_pipeline(pipeline);
1755 npass.draw_indexed(0..d.idx_count, 0, 0..1);
1756 }
1757 }
1758 }
1759 drop(npass);
1760 aux.normal = Some(normal_tex);
1761 }
1762
1763 Some(aux)
14291764 }
14301765}
14311766
......@@ -2145,4 +2480,141 @@ mod tests {
21452480 assert_eq!(renderer.uniform_vram_bytes(), 0);
21462481 assert_eq!(renderer.mesh_vram_bytes(), 0);
21472482 }
2483
2484 fn readback_aux_tex(eng: &Engine, aux: &AuxChannelTex, bpp: u32) -> Vec<u8> {
2485 let [w, h] = aux.size;
2486 let unpadded_bpr = w * bpp;
2487 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
2488 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
2489 let buf = eng.device().create_buffer(&wgpu::BufferDescriptor {
2490 label: Some("readback-aux"),
2491 size: u64::from(padded_bpr) * u64::from(h),
2492 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
2493 mapped_at_creation: false,
2494 });
2495 let mut enc = eng.device().create_command_encoder(&Default::default());
2496 enc.copy_texture_to_buffer(
2497 aux.texture.as_image_copy(),
2498 wgpu::TexelCopyBufferInfo {
2499 buffer: &buf,
2500 layout: wgpu::TexelCopyBufferLayout {
2501 offset: 0,
2502 bytes_per_row: Some(padded_bpr),
2503 rows_per_image: Some(h),
2504 },
2505 },
2506 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
2507 );
2508 eng.queue().submit(Some(enc.finish()));
2509 let slice = buf.slice(..);
2510 let (tx, rx) = std::sync::mpsc::channel();
2511 slice.map_async(wgpu::MapMode::Read, move |res| {
2512 let _ = tx.send(res);
2513 });
2514 eng.device()
2515 .poll(wgpu::PollType::Wait {
2516 submission_index: None,
2517 timeout: Some(std::time::Duration::from_secs(10)),
2518 })
2519 .unwrap();
2520 rx.recv().unwrap().unwrap();
2521 let data = slice.get_mapped_range().unwrap();
2522 let mut out = Vec::with_capacity((unpadded_bpr * h) as usize);
2523 for y in 0..h as usize {
2524 let start = y * padded_bpr as usize;
2525 out.extend_from_slice(&data[start..start + unpadded_bpr as usize]);
2526 }
2527 drop(data);
2528 buf.unmap();
2529 out
2530 }
2531
2532 #[test]
2533 fn renderer3d_z_and_normal_aux_channels_match_fusion_convention() {
2534 let make_comp = |proj_type: &str, ch_z: u8, ch_n: u8| -> Comp {
2535 let src = format!(
2536 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{
2537 Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }},
2538 P = Shape3D {{ Inputs = {{
2539 ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.5, }},
2540 ["SurfacePlaneInputs.Height"] = Input {{ Value = 0.5, }},
2541 ["Transform3DOp.Translate.Z"] = Input {{ Value = -1.0, }},
2542 MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }},
2543 }}, }},
2544 Cam = Camera3D {{ Inputs = {{
2545 ProjectionType = Input {{ Value = FuID {{ "{proj_type}" }}, }},
2546 ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }},
2547 ApertureW = Input {{ Value = 1.0, }},
2548 ApertureH = Input {{ Value = 1.0, }},
2549 }}, }},
2550 M = Merge3D {{ Inputs = {{
2551 SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }},
2552 SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }},
2553 }}, }},
2554 R = Renderer3D {{ Inputs = {{
2555 Width = Input {{ Value = 64, }},
2556 Height = Input {{ Value = 64, }},
2557 ["RendererSoftware.Channels.Z"] = Input {{ Value = {ch_z}, }},
2558 ["RendererSoftware.Channels.Normal"] = Input {{ Value = {ch_n}, }},
2559 SceneInput = Input {{ SourceOp = "M", Source = "Output", }},
2560 }}, }},
2561 }} }}"#
2562 );
2563 Comp::from_fusion_str(&src).expect("parse Z/Normal comp")
2564 };
2565
2566 let Ok(mut eng) = Engine::new_headless() else { return };
2567
2568 // 1. Both channels disabled -> zero aux allocation (`aux == None`).
2569 let comp_off = make_comp("Perspective", 0, 0);
2570 let (tex_off, _) = eng.evaluate(&comp_off, comp_off.find_node("R").unwrap(), 0.0);
2571 assert!(tex_off.aux.is_none(), "aux must stay None when Z and Normal are disabled");
2572
2573 // 2. Perspective & Orthographic cameras both yield Z = -3.0 at center and EMPTY_Z_SENTINEL at corner.
2574 for proj_type in ["Perspective", "Orthographic"] {
2575 let comp = make_comp(proj_type, 1, 1);
2576 let r_id = comp.find_node("R").unwrap();
2577 let (tex, _) = eng.evaluate(&comp, r_id, 0.0);
2578 let aux = tex.aux.as_ref().expect("aux channels must be attached");
2579 let z_tex = aux.z.as_ref().expect("aux.z must be present");
2580 let n_tex = aux.normal.as_ref().expect("aux.normal must be present");
2581 assert_eq!(z_tex.format, wgpu::TextureFormat::R32Float);
2582 assert_eq!(n_tex.format, wgpu::TextureFormat::Rgba16Float);
2583
2584 let z_bytes = readback_aux_tex(&eng, z_tex, 4);
2585 let z_vals: &[f32] = bytemuck::cast_slice(&z_bytes);
2586 let center_z = z_vals[32 * 64 + 32];
2587 let corner_z = z_vals[0];
2588 assert!(
2589 (center_z - (-3.0)).abs() <= 1e-3,
2590 "{proj_type} center Z should be -3.0, got {center_z}"
2591 );
2592 assert_eq!(
2593 corner_z, EMPTY_Z_SENTINEL,
2594 "{proj_type} empty corner Z should be EMPTY_Z_SENTINEL, got {corner_z}"
2595 );
2596
2597 let n_bytes = readback_aux_tex(&eng, n_tex, 8);
2598 let read_n = |x: usize, y: usize| -> [f32; 4] {
2599 let off = (y * 64 + x) * 8;
2600 [
2601 ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off], n_bytes[off + 1]])).to_f32(),
2602 ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 2], n_bytes[off + 3]])).to_f32(),
2603 ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 4], n_bytes[off + 5]])).to_f32(),
2604 ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 6], n_bytes[off + 7]])).to_f32(),
2605 ]
2606 };
2607 let cn = read_n(32, 32);
2608 let kn = read_n(0, 0);
2609 assert!(
2610 cn[0].abs() <= 1e-3 && cn[1].abs() <= 1e-3 && (cn[2] - 1.0).abs() <= 1e-3 && cn[3].abs() <= 1e-3,
2611 "{proj_type} center normal should be (0,0,1,0), got {cn:?}"
2612 );
2613 assert_eq!(kn, [0.0, 0.0, 0.0, 0.0], "{proj_type} corner normal should be zero");
2614 }
2615
2616 // 3. Toggling Channels.Z on an existing comp updates cache key cleanly.
2617 let (tex_cached_off, _) = eng.evaluate(&make_comp("Perspective", 0, 0), comp_off.find_node("R").unwrap(), 0.0);
2618 assert!(tex_cached_off.aux.is_none());
2619 }
21482620}
crates/engine/src/scene3d/shader.rs+95
......@@ -79,6 +79,49 @@ pub(super) struct ShadowUniform {
7979 pub(super) point: [[f32; 4]; MAX_LIGHTS],
8080}
8181
82#[repr(C)]
83#[derive(Clone, Copy, Pod, Zeroable)]
84pub(super) struct DepthToEyeZUniform {
85 /// `[P[2][2], P[2][3], P[3][2], P[3][3]]` from the camera projection matrix.
86 pub(super) proj_zw: [f32; 4],
87 /// `[EMPTY_Z_SENTINEL, 0.0, 0.0, 0.0]`.
88 pub(super) params: [f32; 4],
89}
90
91/// Compute shader converting `Depth32Float` NDC depth (`[0, 1]`) into exact eye-space `Z`
92/// (`R32Float`, negative in front of camera, `EMPTY_Z_SENTINEL` on empty sky pixels).
93pub(super) const DEPTH_TO_EYE_Z_SHADER: &str = r#"
94struct DepthToEyeZParams {
95 proj_zw: vec4<f32>,
96 params: vec4<f32>,
97};
98
99@group(0) @binding(0) var depth_tex: texture_depth_2d;
100@group(0) @binding(1) var out_z: texture_storage_2d<r32float, write>;
101@group(0) @binding(2) var<uniform> u: DepthToEyeZParams;
102
103@compute @workgroup_size(8, 8, 1)
104fn depth_to_eye_z(@builtin(global_invocation_id) gid: vec3<u32>) {
105 let dims = textureDimensions(out_z);
106 if (gid.x >= dims.x || gid.y >= dims.y) {
107 return;
108 }
109 let d = textureLoad(depth_tex, vec2<i32>(gid.xy), 0);
110 var z_eye = u.params.x;
111 if (d < 1.0 - 1e-6) {
112 let p22 = u.proj_zw.x;
113 let p23 = u.proj_zw.y;
114 let p32 = u.proj_zw.z;
115 let p33 = u.proj_zw.w;
116 let denom = p22 - d * p23;
117 if (abs(denom) > 1e-12) {
118 z_eye = (d * p33 - p32) / denom;
119 }
120 }
121 textureStore(out_z, vec2<i32>(gid.xy), vec4<f32>(z_eye, 0.0, 0.0, 0.0));
122}
123"#;
124
82125/// UV affine plus wrap (`off_wrap.z`: 0 clamp, 1 wrap, 2 mirror), shared by both pipelines.
83126pub(super) const UV_XFORM_WGSL: &str = r#"
84127fn wrap_uv_only(uv_in: vec2<f32>, wrap_f: f32) -> vec2<f32> {
......@@ -517,4 +560,56 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
517560 }
518561 return col;
519562}
563
564@fragment
565fn fs_normal(in: VsOut) -> @location(0) vec4<f32> {
566 let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap);
567 let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap);
568 let dpdx_w = dpdx(in.world_pos);
569 let dpdy_w = dpdy(in.world_pos);
570 let duvdx = dpdx(uv_bump_xformed);
571 let duvdy = dpdy(uv_bump_xformed);
572 let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0;
573 if (facing_away != BACK_PASS) {
574 discard;
575 }
576
577 var col = u.diffuse_col;
578 if (u.flags.x > 0.5) {
579 var uv_samp = uv_xformed;
580 if (u.dod.z > 0.5 && u.dod.w > 0.5) {
581 let tdims = vec2<f32>(textureDimensions(mat_tex));
582 let canvas_px = vec2<f32>(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w);
583 uv_samp = (canvas_px - u.dod.xy) / tdims;
584 if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) {
585 discard;
586 }
587 }
588 let tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0);
589 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;
590 }
591 let out_alpha = col.a * u.mtl_params.x;
592 if (out_alpha <= 0.002) {
593 discard;
594 }
595
596 let nlen = length(in.world_n);
597 var n = select(vec3<f32>(0.0, 0.0, 1.0), in.world_n / nlen, nlen > 1e-5);
598 if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) {
599 n = perturb_bump_normal(
600 n,
601 dpdx_w,
602 dpdy_w,
603 duvdx,
604 duvdy,
605 uv_bump_xformed,
606 u.mat_fx.x,
607 u.mat_fx.y,
608 u.bump_off_wrap.z,
609 u.bump_params.x,
610 i32(u.bump_params.y + 0.5),
611 );
612 }
613 return vec4<f32>(n, 0.0);
614}
520615"#;