| 1 | //! Auxiliary channel GPU pipelines and evaluators: |
| 2 | //! - `Merge.PerformDepthMerge` (Z-aware depth compositing) |
| 3 | //! - `Dimension.CopyAux` (Mode 0 Aux->Color with Remap, Mode 1 Color->Aux, `KillAuxChannels`) |
| 4 | //! - `ChannelBoolean.ToZBuffer` (`EnableExtraChannels` extra-channel Z copy/ops) |
| 5 | //! - `Dimension.OpticalFlow` (forward/backward dense flow into `aux.vector` / `aux.back_vector`) |
| 6 | //! - `VectorMotionBlur` GPU dispatch helper |
| 7 | //! |
| 8 | //! WebGPU safety: `R32Float` textures are ONLY bound with `TextureSampleType::Float { filterable: false }` |
| 9 | //! (read via `textureLoad`) and written via `texture_storage_2d<r32float, write>`. |
| 10 | |
| 11 | use super::*; |
| 12 | use crate::cache::{AuxChannelTex, AuxChannels, EMPTY_Z_SENTINEL}; |
| 13 | use std::num::NonZeroU64; |
| 14 | use std::sync::Arc; |
| 15 | |
| 16 | const AUX_OPS_WGSL: &str = include_str!("../shaders/aux_ops.wgsl"); |
| 17 | const AUX_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; |
| 18 | |
| 19 | fn wgsl_section(tag: &str) -> &'static str { |
| 20 | let marker = format!("// @SECTION:{tag}"); |
| 21 | let start = AUX_OPS_WGSL |
| 22 | .find(&marker) |
| 23 | .unwrap_or_else(|| panic!("missing WGSL section {tag}")) |
| 24 | + marker.len(); |
| 25 | let rest = &AUX_OPS_WGSL[start..]; |
| 26 | let end = rest.find("// @SECTION:").unwrap_or(rest.len()); |
| 27 | &rest[..end] |
| 28 | } |
| 29 | |
| 30 | fn build_aux_wgsl(section: &str, rgba_format: Option<wgpu::TextureFormat>, hdr_float: bool) -> String { |
| 31 | let common = wgsl_section("COMMON"); |
| 32 | let body = wgsl_section(section); |
| 33 | let mut src = String::with_capacity(common.len() + body.len() + 2); |
| 34 | src.push_str(common); |
| 35 | src.push('\n'); |
| 36 | src.push_str(body); |
| 37 | if let Some(fmt) = rgba_format { |
| 38 | let storage_fmt = match fmt { |
| 39 | wgpu::TextureFormat::Rgba16Float => "rgba16float", |
| 40 | wgpu::TextureFormat::Rgba32Float => "rgba32float", |
| 41 | _ => "rgba8unorm", |
| 42 | }; |
| 43 | if storage_fmt != "rgba8unorm" { |
| 44 | src = src.replace( |
| 45 | "texture_storage_2d<rgba8unorm, write>", |
| 46 | &format!("texture_storage_2d<{storage_fmt}, write>"), |
| 47 | ); |
| 48 | } |
| 49 | if hdr_float { |
| 50 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); |
| 51 | } |
| 52 | } |
| 53 | src |
| 54 | } |
| 55 | |
| 56 | fn tex_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry { |
| 57 | wgpu::BindGroupLayoutEntry { |
| 58 | binding, |
| 59 | visibility: wgpu::ShaderStages::COMPUTE, |
| 60 | ty: wgpu::BindingType::Texture { |
| 61 | sample_type: wgpu::TextureSampleType::Float { filterable }, |
| 62 | view_dimension: wgpu::TextureViewDimension::D2, |
| 63 | multisampled: false, |
| 64 | }, |
| 65 | count: None, |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { |
| 70 | wgpu::BindGroupLayoutEntry { |
| 71 | binding, |
| 72 | visibility: wgpu::ShaderStages::COMPUTE, |
| 73 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 74 | count: None, |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | fn storage_entry(binding: u32, format: wgpu::TextureFormat) -> wgpu::BindGroupLayoutEntry { |
| 79 | wgpu::BindGroupLayoutEntry { |
| 80 | binding, |
| 81 | visibility: wgpu::ShaderStages::COMPUTE, |
| 82 | ty: wgpu::BindingType::StorageTexture { |
| 83 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 84 | format, |
| 85 | view_dimension: wgpu::TextureViewDimension::D2, |
| 86 | }, |
| 87 | count: None, |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry { |
| 92 | wgpu::BindGroupLayoutEntry { |
| 93 | binding, |
| 94 | visibility: wgpu::ShaderStages::COMPUTE, |
| 95 | ty: wgpu::BindingType::Buffer { |
| 96 | ty: wgpu::BufferBindingType::Uniform, |
| 97 | has_dynamic_offset: true, |
| 98 | min_binding_size: NonZeroU64::new(size), |
| 99 | }, |
| 100 | count: None, |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | struct FormatPipelines { |
| 105 | bgl: wgpu::BindGroupLayout, |
| 106 | pipeline: wgpu::ComputePipeline, |
| 107 | } |
| 108 | |
| 109 | struct RgbaOpsPipelines { |
| 110 | bgl: wgpu::BindGroupLayout, |
| 111 | copy_aux_to_color: wgpu::ComputePipeline, |
| 112 | vector_motion_blur: wgpu::ComputePipeline, |
| 113 | } |
| 114 | |
| 115 | pub(super) struct AuxPipelines { |
| 116 | sampler: wgpu::Sampler, |
| 117 | uniform_stride: u32, |
| 118 | uniform_chunks: Vec<wgpu::Buffer>, |
| 119 | uniform_cursor: u32, |
| 120 | pub(super) dummy_z: AuxChannelTex, |
| 121 | pub(super) dummy_f16: AuxChannelTex, |
| 122 | depth_merge: HashMap<(wgpu::TextureFormat, bool), FormatPipelines>, |
| 123 | rgba_ops: HashMap<(wgpu::TextureFormat, bool), RgbaOpsPipelines>, |
| 124 | r32f_bgl: wgpu::BindGroupLayout, |
| 125 | copy_color_to_aux_z: wgpu::ComputePipeline, |
| 126 | cb_to_zbuffer: wgpu::ComputePipeline, |
| 127 | crop_r32f: wgpu::ComputePipeline, |
| 128 | f16_bgl: wgpu::BindGroupLayout, |
| 129 | copy_color_to_aux_f16: wgpu::ComputePipeline, |
| 130 | crop_f16: wgpu::ComputePipeline, |
| 131 | optflow_features: wgpu::ComputePipeline, |
| 132 | optflow_coarse: wgpu::ComputePipeline, |
| 133 | optflow_refine: wgpu::ComputePipeline, |
| 134 | } |
| 135 | |
| 136 | impl AuxPipelines { |
| 137 | pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self { |
| 138 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; |
| 139 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 140 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; |
| 141 | let u_size_u64 = u64::from(uniform_size); |
| 142 | |
| 143 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { |
| 144 | label: Some("aux-linear"), |
| 145 | address_mode_u: wgpu::AddressMode::ClampToEdge, |
| 146 | address_mode_v: wgpu::AddressMode::ClampToEdge, |
| 147 | mag_filter: wgpu::FilterMode::Linear, |
| 148 | min_filter: wgpu::FilterMode::Linear, |
| 149 | mipmap_filter: wgpu::MipmapFilterMode::Nearest, |
| 150 | ..Default::default() |
| 151 | }); |
| 152 | |
| 153 | let dummy_z = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::R32Float, "aux-dummy-z"); |
| 154 | queue.write_texture( |
| 155 | dummy_z.texture.as_image_copy(), |
| 156 | &EMPTY_Z_SENTINEL.to_le_bytes(), |
| 157 | wgpu::TexelCopyBufferLayout { |
| 158 | offset: 0, |
| 159 | bytes_per_row: Some(4), |
| 160 | rows_per_image: Some(1), |
| 161 | }, |
| 162 | wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, |
| 163 | ); |
| 164 | |
| 165 | let dummy_f16 = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::Rgba16Float, "aux-dummy-f16"); |
| 166 | queue.write_texture( |
| 167 | dummy_f16.texture.as_image_copy(), |
| 168 | &[0u8; 8], |
| 169 | wgpu::TexelCopyBufferLayout { |
| 170 | offset: 0, |
| 171 | bytes_per_row: Some(8), |
| 172 | rows_per_image: Some(1), |
| 173 | }, |
| 174 | wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, |
| 175 | ); |
| 176 | |
| 177 | // R32Float output pipelines (all texture reads unfilterable except mask_tex) |
| 178 | let r32f_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 179 | label: Some("aux-r32f-bgl"), |
| 180 | entries: &[ |
| 181 | tex_entry(0, false), |
| 182 | tex_entry(1, false), |
| 183 | tex_entry(2, false), |
| 184 | tex_entry(3, false), |
| 185 | tex_entry(4, true), |
| 186 | sampler_entry(5), |
| 187 | storage_entry(6, wgpu::TextureFormat::R32Float), |
| 188 | uniform_entry(7, u_size_u64), |
| 189 | ], |
| 190 | }); |
| 191 | let r32f_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 192 | label: Some("aux-r32f-pl"), |
| 193 | bind_group_layouts: &[Some(&r32f_bgl)], |
| 194 | immediate_size: 0, |
| 195 | }); |
| 196 | let r32f_mod = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 197 | label: Some("aux-r32f-wgsl"), |
| 198 | source: wgpu::ShaderSource::Wgsl(build_aux_wgsl("R32F_OPS", None, false).into()), |
| 199 | }); |
| 200 | let mk_pipe = |module: &wgpu::ShaderModule, pl: &wgpu::PipelineLayout, entry: &str| { |
| 201 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 202 | label: Some(entry), |
| 203 | layout: Some(pl), |
| 204 | module, |
| 205 | entry_point: Some(entry), |
| 206 | compilation_options: Default::default(), |
| 207 | cache: None, |
| 208 | }) |
| 209 | }; |
| 210 | let copy_color_to_aux_z = mk_pipe(&r32f_mod, &r32f_pl, "copy_color_to_aux_z_op"); |
| 211 | let cb_to_zbuffer = mk_pipe(&r32f_mod, &r32f_pl, "cb_to_zbuffer_op"); |
| 212 | let crop_r32f = mk_pipe(&r32f_mod, &r32f_pl, "crop_r32f_op"); |
| 213 | |
| 214 | // Rgba16Float output pipelines (CopyAux Normal/Vector/BackVector + OpticalFlow) |
| 215 | let f16_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 216 | label: Some("aux-f16-bgl"), |
| 217 | entries: &[ |
| 218 | tex_entry(0, true), |
| 219 | tex_entry(1, true), |
| 220 | tex_entry(2, true), |
| 221 | sampler_entry(3), |
| 222 | storage_entry(4, wgpu::TextureFormat::Rgba16Float), |
| 223 | uniform_entry(5, u_size_u64), |
| 224 | ], |
| 225 | }); |
| 226 | let f16_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 227 | label: Some("aux-f16-pl"), |
| 228 | bind_group_layouts: &[Some(&f16_bgl)], |
| 229 | immediate_size: 0, |
| 230 | }); |
| 231 | let f16_mod = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 232 | label: Some("aux-f16-wgsl"), |
| 233 | source: wgpu::ShaderSource::Wgsl(build_aux_wgsl("F16_OPS", None, false).into()), |
| 234 | }); |
| 235 | let copy_color_to_aux_f16 = mk_pipe(&f16_mod, &f16_pl, "copy_color_to_aux_f16_op"); |
| 236 | let crop_f16 = mk_pipe(&f16_mod, &f16_pl, "crop_f16_op"); |
| 237 | let optflow_features = mk_pipe(&f16_mod, &f16_pl, "optflow_features_op"); |
| 238 | let optflow_coarse = mk_pipe(&f16_mod, &f16_pl, "optflow_coarse_op"); |
| 239 | let optflow_refine = mk_pipe(&f16_mod, &f16_pl, "optflow_refine_op"); |
| 240 | |
| 241 | Self { |
| 242 | sampler, |
| 243 | uniform_stride, |
| 244 | uniform_chunks: Vec::new(), |
| 245 | uniform_cursor: 0, |
| 246 | dummy_z, |
| 247 | dummy_f16, |
| 248 | depth_merge: HashMap::new(), |
| 249 | rgba_ops: HashMap::new(), |
| 250 | r32f_bgl, |
| 251 | copy_color_to_aux_z, |
| 252 | cb_to_zbuffer, |
| 253 | crop_r32f, |
| 254 | f16_bgl, |
| 255 | copy_color_to_aux_f16, |
| 256 | crop_f16, |
| 257 | optflow_features, |
| 258 | optflow_coarse, |
| 259 | optflow_refine, |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | pub(super) fn reset_uniform_cursor(&mut self) { |
| 264 | self.uniform_cursor = 0; |
| 265 | } |
| 266 | |
| 267 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { |
| 268 | self.uniform_cursor = 0; |
| 269 | if self.uniform_chunks.len() > max_chunks { |
| 270 | self.uniform_chunks.truncate(max_chunks); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | fn alloc_uniform_slot( |
| 275 | &mut self, |
| 276 | device: &wgpu::Device, |
| 277 | queue: &wgpu::Queue, |
| 278 | params: &UniformParams, |
| 279 | ) -> (usize, u32) { |
| 280 | let slot_global = self.uniform_cursor; |
| 281 | let chunk_idx = (slot_global / AUX_UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 282 | let slot_in_chunk = slot_global % AUX_UNIFORM_SLOTS_PER_CHUNK; |
| 283 | while chunk_idx >= self.uniform_chunks.len() { |
| 284 | let size = u64::from(AUX_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); |
| 285 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 286 | label: Some("aux-params-ring"), |
| 287 | size, |
| 288 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 289 | mapped_at_creation: false, |
| 290 | }); |
| 291 | self.uniform_chunks.push(buf); |
| 292 | } |
| 293 | let offset = slot_in_chunk * self.uniform_stride; |
| 294 | queue.write_buffer( |
| 295 | &self.uniform_chunks[chunk_idx], |
| 296 | u64::from(offset), |
| 297 | bytemuck::bytes_of(params), |
| 298 | ); |
| 299 | self.uniform_cursor = slot_global + 1; |
| 300 | (chunk_idx, offset) |
| 301 | } |
| 302 | |
| 303 | fn ensure_depth_merge(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { |
| 304 | if self.depth_merge.contains_key(&(format, hdr_float)) { |
| 305 | return; |
| 306 | } |
| 307 | let u_size = std::mem::size_of::<UniformParams>() as u64; |
| 308 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 309 | label: Some("aux-depth-merge-bgl"), |
| 310 | entries: &[ |
| 311 | tex_entry(0, false), |
| 312 | tex_entry(1, true), |
| 313 | tex_entry(2, false), |
| 314 | tex_entry(3, false), |
| 315 | tex_entry(4, true), |
| 316 | sampler_entry(5), |
| 317 | storage_entry(6, format), |
| 318 | storage_entry(7, wgpu::TextureFormat::R32Float), |
| 319 | uniform_entry(8, u_size), |
| 320 | ], |
| 321 | }); |
| 322 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 323 | label: Some("aux-depth-merge-pl"), |
| 324 | bind_group_layouts: &[Some(&bgl)], |
| 325 | immediate_size: 0, |
| 326 | }); |
| 327 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 328 | label: Some("aux-depth-merge-wgsl"), |
| 329 | source: wgpu::ShaderSource::Wgsl(build_aux_wgsl("DEPTH_MERGE", Some(format), hdr_float).into()), |
| 330 | }); |
| 331 | let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 332 | label: Some("depth_merge_op"), |
| 333 | layout: Some(&pl), |
| 334 | module: &module, |
| 335 | entry_point: Some("depth_merge_op"), |
| 336 | compilation_options: Default::default(), |
| 337 | cache: None, |
| 338 | }); |
| 339 | self.depth_merge.insert((format, hdr_float), FormatPipelines { bgl, pipeline }); |
| 340 | } |
| 341 | |
| 342 | fn ensure_rgba_ops(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { |
| 343 | if self.rgba_ops.contains_key(&(format, hdr_float)) { |
| 344 | return; |
| 345 | } |
| 346 | let u_size = std::mem::size_of::<UniformParams>() as u64; |
| 347 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 348 | label: Some("aux-rgba-ops-bgl"), |
| 349 | entries: &[ |
| 350 | tex_entry(0, true), |
| 351 | tex_entry(1, false), |
| 352 | tex_entry(2, true), |
| 353 | sampler_entry(3), |
| 354 | storage_entry(4, format), |
| 355 | uniform_entry(5, u_size), |
| 356 | ], |
| 357 | }); |
| 358 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 359 | label: Some("aux-rgba-ops-pl"), |
| 360 | bind_group_layouts: &[Some(&bgl)], |
| 361 | immediate_size: 0, |
| 362 | }); |
| 363 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 364 | label: Some("aux-rgba-ops-wgsl"), |
| 365 | source: wgpu::ShaderSource::Wgsl(build_aux_wgsl("RGBA_OPS", Some(format), hdr_float).into()), |
| 366 | }); |
| 367 | let copy_aux_to_color = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 368 | label: Some("copy_aux_to_color_op"), |
| 369 | layout: Some(&pl), |
| 370 | module: &module, |
| 371 | entry_point: Some("copy_aux_to_color_op"), |
| 372 | compilation_options: Default::default(), |
| 373 | cache: None, |
| 374 | }); |
| 375 | let vector_motion_blur = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 376 | label: Some("vector_motion_blur_op"), |
| 377 | layout: Some(&pl), |
| 378 | module: &module, |
| 379 | entry_point: Some("vector_motion_blur_op"), |
| 380 | compilation_options: Default::default(), |
| 381 | cache: None, |
| 382 | }); |
| 383 | self.rgba_ops.insert( |
| 384 | (format, hdr_float), |
| 385 | RgbaOpsPipelines { |
| 386 | bgl, |
| 387 | copy_aux_to_color, |
| 388 | vector_motion_blur, |
| 389 | }, |
| 390 | ); |
| 391 | } |
| 392 | |
| 393 | #[allow(clippy::too_many_arguments)] |
| 394 | fn dispatch_depth_merge( |
| 395 | &mut self, |
| 396 | device: &wgpu::Device, |
| 397 | queue: &wgpu::Queue, |
| 398 | enc: &mut wgpu::CommandEncoder, |
| 399 | bg_rgba: &wgpu::TextureView, |
| 400 | fg_rgba: &wgpu::TextureView, |
| 401 | bg_z: Option<&wgpu::TextureView>, |
| 402 | fg_z: Option<&wgpu::TextureView>, |
| 403 | mask: &wgpu::TextureView, |
| 404 | dst_rgba: &CachedTexture, |
| 405 | dst_z: &AuxChannelTex, |
| 406 | params: &UniformParams, |
| 407 | ) { |
| 408 | let hdr_float = dst_rgba.depth.is_float(); |
| 409 | self.ensure_depth_merge(device, dst_rgba.format, hdr_float); |
| 410 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 411 | let entry = &self.depth_merge[&(dst_rgba.format, hdr_float)]; |
| 412 | let bg_z_view = bg_z.unwrap_or(&self.dummy_z.view); |
| 413 | let fg_z_view = fg_z.unwrap_or(&self.dummy_z.view); |
| 414 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 415 | label: Some("aux-depth-merge-bg"), |
| 416 | layout: &entry.bgl, |
| 417 | entries: &[ |
| 418 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(bg_rgba) }, |
| 419 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(fg_rgba) }, |
| 420 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(bg_z_view) }, |
| 421 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(fg_z_view) }, |
| 422 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(mask) }, |
| 423 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| 424 | wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&dst_rgba.view) }, |
| 425 | wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(&dst_z.view) }, |
| 426 | wgpu::BindGroupEntry { |
| 427 | binding: 8, |
| 428 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 429 | buffer: &self.uniform_chunks[chunk_idx], |
| 430 | offset: 0, |
| 431 | size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64), |
| 432 | }), |
| 433 | }, |
| 434 | ], |
| 435 | }); |
| 436 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 437 | label: Some("depth-merge"), |
| 438 | timestamp_writes: None, |
| 439 | }); |
| 440 | pass.set_pipeline(&entry.pipeline); |
| 441 | pass.set_bind_group(0, &bg, &[offset]); |
| 442 | pass.dispatch_workgroups(dst_rgba.size[0].div_ceil(8), dst_rgba.size[1].div_ceil(8), 1); |
| 443 | } |
| 444 | |
| 445 | #[allow(clippy::too_many_arguments)] |
| 446 | fn dispatch_rgba_op( |
| 447 | &mut self, |
| 448 | device: &wgpu::Device, |
| 449 | queue: &wgpu::Queue, |
| 450 | enc: &mut wgpu::CommandEncoder, |
| 451 | is_vmb: bool, |
| 452 | src_rgba: &wgpu::TextureView, |
| 453 | aux_tex: &wgpu::TextureView, |
| 454 | mask: &wgpu::TextureView, |
| 455 | dst_rgba: &CachedTexture, |
| 456 | params: &UniformParams, |
| 457 | ) { |
| 458 | let hdr_float = dst_rgba.depth.is_float(); |
| 459 | self.ensure_rgba_ops(device, dst_rgba.format, hdr_float); |
| 460 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 461 | let entry = &self.rgba_ops[&(dst_rgba.format, hdr_float)]; |
| 462 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 463 | label: Some(if is_vmb { "vmb-bg" } else { "copy-aux-bg" }), |
| 464 | layout: &entry.bgl, |
| 465 | entries: &[ |
| 466 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_rgba) }, |
| 467 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(aux_tex) }, |
| 468 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, |
| 469 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| 470 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst_rgba.view) }, |
| 471 | wgpu::BindGroupEntry { |
| 472 | binding: 5, |
| 473 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 474 | buffer: &self.uniform_chunks[chunk_idx], |
| 475 | offset: 0, |
| 476 | size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64), |
| 477 | }), |
| 478 | }, |
| 479 | ], |
| 480 | }); |
| 481 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 482 | label: Some(if is_vmb { "vector-motion-blur" } else { "copy-aux-to-color" }), |
| 483 | timestamp_writes: None, |
| 484 | }); |
| 485 | pass.set_pipeline(if is_vmb { &entry.vector_motion_blur } else { &entry.copy_aux_to_color }); |
| 486 | pass.set_bind_group(0, &bg, &[offset]); |
| 487 | pass.dispatch_workgroups(dst_rgba.size[0].div_ceil(8), dst_rgba.size[1].div_ceil(8), 1); |
| 488 | } |
| 489 | |
| 490 | #[allow(clippy::too_many_arguments)] |
| 491 | fn dispatch_r32f_op( |
| 492 | &mut self, |
| 493 | device: &wgpu::Device, |
| 494 | queue: &wgpu::Queue, |
| 495 | enc: &mut wgpu::CommandEncoder, |
| 496 | which: u8, // 0 = copy_color_to_aux_z, 1 = cb_to_zbuffer, 2 = crop_r32f |
| 497 | bg_rgba: &wgpu::TextureView, |
| 498 | fg_rgba: &wgpu::TextureView, |
| 499 | bg_z: Option<&wgpu::TextureView>, |
| 500 | fg_z: Option<&wgpu::TextureView>, |
| 501 | mask: &wgpu::TextureView, |
| 502 | dst_z: &AuxChannelTex, |
| 503 | params: &UniformParams, |
| 504 | ) { |
| 505 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 506 | let bg_z_view = bg_z.unwrap_or(&self.dummy_z.view); |
| 507 | let fg_z_view = fg_z.unwrap_or(&self.dummy_z.view); |
| 508 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 509 | label: Some("aux-r32f-bg"), |
| 510 | layout: &self.r32f_bgl, |
| 511 | entries: &[ |
| 512 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(bg_rgba) }, |
| 513 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(fg_rgba) }, |
| 514 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(bg_z_view) }, |
| 515 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(fg_z_view) }, |
| 516 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(mask) }, |
| 517 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| 518 | wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&dst_z.view) }, |
| 519 | wgpu::BindGroupEntry { |
| 520 | binding: 7, |
| 521 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 522 | buffer: &self.uniform_chunks[chunk_idx], |
| 523 | offset: 0, |
| 524 | size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64), |
| 525 | }), |
| 526 | }, |
| 527 | ], |
| 528 | }); |
| 529 | let pipe = match which { |
| 530 | 0 => &self.copy_color_to_aux_z, |
| 531 | 1 => &self.cb_to_zbuffer, |
| 532 | _ => &self.crop_r32f, |
| 533 | }; |
| 534 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 535 | label: Some("aux-r32f"), |
| 536 | timestamp_writes: None, |
| 537 | }); |
| 538 | pass.set_pipeline(pipe); |
| 539 | pass.set_bind_group(0, &bg, &[offset]); |
| 540 | pass.dispatch_workgroups(dst_z.size[0].div_ceil(8), dst_z.size[1].div_ceil(8), 1); |
| 541 | } |
| 542 | |
| 543 | #[allow(clippy::too_many_arguments)] |
| 544 | fn dispatch_f16_op( |
| 545 | &mut self, |
| 546 | device: &wgpu::Device, |
| 547 | queue: &wgpu::Queue, |
| 548 | enc: &mut wgpu::CommandEncoder, |
| 549 | which: u8, // 0=copy_color_to_aux_f16, 1=crop_f16, 2=optflow_features, 3=optflow_coarse, 4=optflow_refine |
| 550 | tex_a: &wgpu::TextureView, |
| 551 | tex_b: Option<&wgpu::TextureView>, |
| 552 | tex_c: Option<&wgpu::TextureView>, |
| 553 | dst_f16: &AuxChannelTex, |
| 554 | params: &UniformParams, |
| 555 | ) { |
| 556 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 557 | let vb = tex_b.unwrap_or(&self.dummy_f16.view); |
| 558 | let vc = tex_c.unwrap_or(&self.dummy_f16.view); |
| 559 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 560 | label: Some("aux-f16-bg"), |
| 561 | layout: &self.f16_bgl, |
| 562 | entries: &[ |
| 563 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(tex_a) }, |
| 564 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(vb) }, |
| 565 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(vc) }, |
| 566 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| 567 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst_f16.view) }, |
| 568 | wgpu::BindGroupEntry { |
| 569 | binding: 5, |
| 570 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 571 | buffer: &self.uniform_chunks[chunk_idx], |
| 572 | offset: 0, |
| 573 | size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64), |
| 574 | }), |
| 575 | }, |
| 576 | ], |
| 577 | }); |
| 578 | let pipe = match which { |
| 579 | 0 => &self.copy_color_to_aux_f16, |
| 580 | 1 => &self.crop_f16, |
| 581 | 2 => &self.optflow_features, |
| 582 | 3 => &self.optflow_coarse, |
| 583 | _ => &self.optflow_refine, |
| 584 | }; |
| 585 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 586 | label: Some("aux-f16"), |
| 587 | timestamp_writes: None, |
| 588 | }); |
| 589 | pass.set_pipeline(pipe); |
| 590 | pass.set_bind_group(0, &bg, &[offset]); |
| 591 | pass.dispatch_workgroups(dst_f16.size[0].div_ceil(8), dst_f16.size[1].div_ceil(8), 1); |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 596 | enum CopyAuxChannel { |
| 597 | Z, |
| 598 | Normal, |
| 599 | Vector, |
| 600 | BackVector, |
| 601 | Color, |
| 602 | } |
| 603 | |
| 604 | impl CopyAuxChannel { |
| 605 | fn from_str(s: &str) -> Self { |
| 606 | match s { |
| 607 | "Normal" | "Normals" => Self::Normal, |
| 608 | "Vector" | "Vectors" => Self::Vector, |
| 609 | "BackVector" | "Back Vector" | "BackVectors" => Self::BackVector, |
| 610 | "Color" => Self::Color, |
| 611 | _ => Self::Z, |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | fn remap_prefix(self) -> &'static str { |
| 616 | match self { |
| 617 | Self::Z => "Z", |
| 618 | Self::Normal => "Normal", |
| 619 | Self::Vector => "Vector", |
| 620 | Self::BackVector => "BackVector", |
| 621 | Self::Color => "Color", |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | fn shader_kind(self) -> f32 { |
| 626 | match self { |
| 627 | Self::Z => 0.0, |
| 628 | Self::Normal => 1.0, |
| 629 | Self::Vector | Self::BackVector => 2.0, |
| 630 | Self::Color => 3.0, |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | /// Returns `true` iff any active node in `comp` consumes optical-flow motion vectors |
| 636 | /// (`VectorMotionBlur`, or `Dimension.CopyAux` reading `Vector`/`BackVector`). |
| 637 | pub(super) fn comp_uses_optical_flow_vectors(comp: &Comp) -> bool { |
| 638 | comp.nodes.iter().any(|n| { |
| 639 | if n.bypassed { |
| 640 | return false; |
| 641 | } |
| 642 | if matches!( |
| 643 | n.kind.as_str(), |
| 644 | "VectorMotionBlur" |
| 645 | | "VectorWarp" |
| 646 | | "VectorTransform" |
| 647 | | "PropagateDepth" |
| 648 | | "SmoothMotion" |
| 649 | | "Dimension.SmoothMotion" |
| 650 | ) { |
| 651 | return true; |
| 652 | } |
| 653 | if n.kind == "Dimension.CopyAux" { |
| 654 | let ch = CopyAuxChannel::from_str(n.static_str("Channel").unwrap_or("Z")); |
| 655 | if matches!(ch, CopyAuxChannel::Vector | CopyAuxChannel::BackVector) { |
| 656 | return true; |
| 657 | } |
| 658 | } |
| 659 | false |
| 660 | }) |
| 661 | } |
| 662 | |
| 663 | impl Engine { |
| 664 | pub(super) fn aux_pipelines(&self) -> &RefCell<AuxPipelines> { |
| 665 | self.aux_pipelines |
| 666 | .get_or_init(|| RefCell::new(AuxPipelines::new(&self.device, &self.queue))) |
| 667 | } |
| 668 | |
| 669 | /// Dispatches depth-aware `Merge` (`PerformDepthMerge = 0` or `1`) when at least one of |
| 670 | /// `bg` or `fg` carries `aux.z`. Attaches `out.aux.z` whenever `bg` carried `aux.z`. |
| 671 | #[allow(clippy::too_many_arguments)] |
| 672 | pub(super) fn dispatch_depth_merge( |
| 673 | &self, |
| 674 | enc: &mut wgpu::CommandEncoder, |
| 675 | bg: &CachedTexture, |
| 676 | fg: &CachedTexture, |
| 677 | mask_view: &wgpu::TextureView, |
| 678 | dst: &mut CachedTexture, |
| 679 | params: &UniformParams, |
| 680 | ) { |
| 681 | let bg_z = bg.aux.as_ref().and_then(|a| a.z.as_ref()); |
| 682 | let fg_z = fg.aux.as_ref().and_then(|a| a.z.as_ref()); |
| 683 | let dst_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "merge-z"); |
| 684 | self.aux_pipelines().borrow_mut().dispatch_depth_merge( |
| 685 | &self.device, |
| 686 | &self.queue, |
| 687 | enc, |
| 688 | &bg.view, |
| 689 | &fg.view, |
| 690 | bg_z.map(|t| t.view.as_ref()), |
| 691 | fg_z.map(|t| t.view.as_ref()), |
| 692 | mask_view, |
| 693 | dst, |
| 694 | &dst_z, |
| 695 | params, |
| 696 | ); |
| 697 | let same_dod = dst.size == bg.size && dst.origin == bg.origin; |
| 698 | if bg_z.is_some() { |
| 699 | let mut out_aux = if same_dod { |
| 700 | bg.aux_cloned() |
| 701 | } else { |
| 702 | AuxChannels::default() |
| 703 | }; |
| 704 | out_aux.z = Some(dst_z); |
| 705 | dst.set_aux(Some(Arc::new(out_aux))); |
| 706 | } else if bg.aux.is_some() && same_dod { |
| 707 | // Preserve any non-Z aux channels on BG, keeping Z = None matching Snow Globe! |
| 708 | dst.set_aux(bg.aux.clone()); |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | /// Re-origins and resizes `src.aux` channels from `(src.origin, src.size)` to |
| 713 | /// `(dst.origin, dst.size)`, padding out-of-bounds Z with `EMPTY_Z_SENTINEL` and |
| 714 | /// out-of-bounds `Rgba16Float` channels with `0.0`. |
| 715 | pub(super) fn reorigin_aux( |
| 716 | &self, |
| 717 | enc: &mut wgpu::CommandEncoder, |
| 718 | src: &CachedTexture, |
| 719 | dst: &mut CachedTexture, |
| 720 | ) { |
| 721 | let Some(src_aux) = src.aux.as_ref() else { |
| 722 | return; |
| 723 | }; |
| 724 | if src.origin == dst.origin && src.size == dst.size { |
| 725 | dst.set_aux(Some(src_aux.clone())); |
| 726 | return; |
| 727 | } |
| 728 | let mut out_aux = AuxChannels::default(); |
| 729 | let mut u = UniformParams::default(); |
| 730 | u.p[0] = [ |
| 731 | (src.origin[0] - dst.origin[0]) as f32, |
| 732 | (src.origin[1] - dst.origin[1]) as f32, |
| 733 | dst.size[0] as f32, |
| 734 | dst.size[1] as f32, |
| 735 | ]; |
| 736 | let mut ap = self.aux_pipelines().borrow_mut(); |
| 737 | if let Some(z) = src_aux.z.as_ref() { |
| 738 | let cropped_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "crop-z"); |
| 739 | ap.dispatch_r32f_op( |
| 740 | &self.device, |
| 741 | &self.queue, |
| 742 | enc, |
| 743 | 2, |
| 744 | &self.dummy.view, |
| 745 | &self.dummy.view, |
| 746 | Some(&z.view), |
| 747 | None, |
| 748 | &self.dummy.view, |
| 749 | &cropped_z, |
| 750 | &u, |
| 751 | ); |
| 752 | out_aux.z = Some(cropped_z); |
| 753 | } |
| 754 | let mut crop_f16 = |ap: &mut AuxPipelines, tex: &AuxChannelTex, label: &str| { |
| 755 | let cropped = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::Rgba16Float, label); |
| 756 | ap.dispatch_f16_op( |
| 757 | &self.device, |
| 758 | &self.queue, |
| 759 | enc, |
| 760 | 1, |
| 761 | &tex.view, |
| 762 | None, |
| 763 | None, |
| 764 | &cropped, |
| 765 | &u, |
| 766 | ); |
| 767 | cropped |
| 768 | }; |
| 769 | if let Some(n) = src_aux.normal.as_ref() { |
| 770 | out_aux.normal = Some(crop_f16(&mut ap, n, "crop-normal")); |
| 771 | } |
| 772 | if let Some(v) = src_aux.vector.as_ref() { |
| 773 | out_aux.vector = Some(crop_f16(&mut ap, v, "crop-vector")); |
| 774 | } |
| 775 | if let Some(bv) = src_aux.back_vector.as_ref() { |
| 776 | out_aux.back_vector = Some(crop_f16(&mut ap, bv, "crop-back-vector")); |
| 777 | } |
| 778 | dst.set_aux(Some(Arc::new(out_aux))); |
| 779 | } |
| 780 | |
| 781 | /// Crops `src.aux` channels from `src.origin` / `src.size` to `src.canvas_size`. |
| 782 | pub(super) fn crop_aux_to_canvas( |
| 783 | &self, |
| 784 | enc: &mut wgpu::CommandEncoder, |
| 785 | src: &CachedTexture, |
| 786 | dst: &mut CachedTexture, |
| 787 | ) { |
| 788 | self.reorigin_aux(enc, src, dst); |
| 789 | } |
| 790 | |
| 791 | /// Evaluates `Dimension.CopyAux` (Mode 0: Aux -> Color with Remap; Mode 1: Color -> Aux). |
| 792 | #[allow(clippy::too_many_arguments)] |
| 793 | pub(super) fn eval_copy_aux( |
| 794 | &mut self, |
| 795 | comp: &Comp, |
| 796 | node: &Node, |
| 797 | time: f64, |
| 798 | frame_i: i64, |
| 799 | enc: &mut wgpu::CommandEncoder, |
| 800 | visiting: &mut HashSet<(NodeId, i64)>, |
| 801 | stats: &mut EvalStats, |
| 802 | ) -> CachedTexture { |
| 803 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 804 | return self.dummy.clone(); |
| 805 | }; |
| 806 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 807 | let mode = comp.eval_number(node, "Mode", time, 0.0, &self.expr).round() as i32; |
| 808 | let channel = CopyAuxChannel::from_str(node.static_str("Channel").unwrap_or("Z")); |
| 809 | let kill_aux = comp.eval_number(node, "KillAuxChannels", time, 0.0, &self.expr) >= 0.5; |
| 810 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 811 | let mbm = self.multiplies_by_mask(comp, node, time); |
| 812 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); |
| 813 | |
| 814 | // Early passthrough when blend == 0 (or channel == Color) |
| 815 | if (blend <= 1e-6 && !(mbm && has_mask)) || channel == CopyAuxChannel::Color { |
| 816 | if kill_aux && src.aux.is_some() { |
| 817 | let key = self.make_key(node, "CopyAuxKill", src.size, &[src.content_hash], &[1.0]); |
| 818 | let mut out = src.clone(); |
| 819 | out.content_hash = key; |
| 820 | out.set_aux(None); |
| 821 | return out; |
| 822 | } |
| 823 | return src; |
| 824 | } |
| 825 | |
| 826 | if mode == 1 { |
| 827 | // Mode 1: Color To Aux (passes RGBA through and writes selected aux channel) |
| 828 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; |
| 829 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 830 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 831 | let key = self.make_key( |
| 832 | node, |
| 833 | "CopyAuxColorToAux", |
| 834 | src.size, |
| 835 | &[src.content_hash, mask_hash], |
| 836 | &[ |
| 837 | channel.shader_kind(), |
| 838 | if kill_aux { 1.0 } else { 0.0 }, |
| 839 | blend, |
| 840 | if mask_inv { 1.0 } else { 0.0 }, |
| 841 | ], |
| 842 | ); |
| 843 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 844 | stats.cache_hits += 1; |
| 845 | return hit; |
| 846 | } |
| 847 | stats.cache_misses += 1; |
| 848 | stats.nodes_evaluated += 1; |
| 849 | |
| 850 | let mut out = src.clone(); |
| 851 | out.content_hash = key; |
| 852 | let mut out_aux = if kill_aux { |
| 853 | AuxChannels::default() |
| 854 | } else { |
| 855 | src.aux_cloned() |
| 856 | }; |
| 857 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 858 | let has_m_f = if mask.is_some() { 1.0 } else { 0.0 }; |
| 859 | let inv_f = if mask_inv { 1.0 } else { 0.0 }; |
| 860 | |
| 861 | match channel { |
| 862 | CopyAuxChannel::Z => { |
| 863 | let dst_z = AuxChannelTex::new(&self.device, src.size, wgpu::TextureFormat::R32Float, "copy-aux-z"); |
| 864 | let existing_z = out_aux.z.as_ref(); |
| 865 | let mut u = UniformParams::default(); |
| 866 | u.p[0] = [blend, has_m_f, inv_f, if existing_z.is_some() { 1.0 } else { 0.0 }]; |
| 867 | self.aux_pipelines().borrow_mut().dispatch_r32f_op( |
| 868 | &self.device, |
| 869 | &self.queue, |
| 870 | enc, |
| 871 | 0, |
| 872 | &src.view, |
| 873 | &self.dummy.view, |
| 874 | existing_z.map(|t| t.view.as_ref()), |
| 875 | None, |
| 876 | mv, |
| 877 | &dst_z, |
| 878 | &u, |
| 879 | ); |
| 880 | out_aux.z = Some(dst_z); |
| 881 | } |
| 882 | CopyAuxChannel::Normal | CopyAuxChannel::Vector | CopyAuxChannel::BackVector => { |
| 883 | let label = match channel { |
| 884 | CopyAuxChannel::Normal => "copy-aux-normal", |
| 885 | CopyAuxChannel::Vector => "copy-aux-vector", |
| 886 | _ => "copy-aux-back-vector", |
| 887 | }; |
| 888 | let dst_f16 = AuxChannelTex::new(&self.device, src.size, wgpu::TextureFormat::Rgba16Float, label); |
| 889 | let existing = match channel { |
| 890 | CopyAuxChannel::Normal => out_aux.normal.as_ref(), |
| 891 | CopyAuxChannel::Vector => out_aux.vector.as_ref(), |
| 892 | _ => out_aux.back_vector.as_ref(), |
| 893 | }; |
| 894 | let mut u = UniformParams::default(); |
| 895 | u.p[0] = [channel.shader_kind(), blend, has_m_f, inv_f]; |
| 896 | u.p[1] = [if existing.is_some() { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; |
| 897 | self.aux_pipelines().borrow_mut().dispatch_f16_op( |
| 898 | &self.device, |
| 899 | &self.queue, |
| 900 | enc, |
| 901 | 0, |
| 902 | &src.view, |
| 903 | existing.map(|t| t.view.as_ref()), |
| 904 | Some(mv), |
| 905 | &dst_f16, |
| 906 | &u, |
| 907 | ); |
| 908 | match channel { |
| 909 | CopyAuxChannel::Normal => out_aux.normal = Some(dst_f16), |
| 910 | CopyAuxChannel::Vector => out_aux.vector = Some(dst_f16), |
| 911 | _ => out_aux.back_vector = Some(dst_f16), |
| 912 | } |
| 913 | } |
| 914 | CopyAuxChannel::Color => {} |
| 915 | } |
| 916 | out.set_aux(Some(Arc::new(out_aux))); |
| 917 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 918 | return out; |
| 919 | } |
| 920 | |
| 921 | // Mode 0: Aux To Color |
| 922 | let src_has_sel = src.aux.as_ref().is_some_and(|a| match channel { |
| 923 | CopyAuxChannel::Z => a.z.is_some(), |
| 924 | CopyAuxChannel::Normal => a.normal.is_some(), |
| 925 | CopyAuxChannel::Vector => a.vector.is_some(), |
| 926 | CopyAuxChannel::BackVector => a.back_vector.is_some(), |
| 927 | CopyAuxChannel::Color => false, |
| 928 | }); |
| 929 | if !src_has_sel { |
| 930 | if kill_aux && src.aux.is_some() { |
| 931 | let key = self.make_key(node, "CopyAuxKillMissing", src.size, &[src.content_hash], &[1.0]); |
| 932 | let mut out = src.clone(); |
| 933 | out.content_hash = key; |
| 934 | out.set_aux(None); |
| 935 | return out; |
| 936 | } |
| 937 | return src; |
| 938 | } |
| 939 | |
| 940 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; |
| 941 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 942 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 943 | |
| 944 | let pfx = channel.remap_prefix(); |
| 945 | let remap_en = comp.eval_number(node, &format!("{pfx}.Remap.Enable"), time, 0.0, &self.expr) >= 0.5; |
| 946 | let fmin = comp.eval_number(node, &format!("{pfx}.Remap.From.Min"), time, 0.0, &self.expr); |
| 947 | let fmax = comp.eval_number(node, &format!("{pfx}.Remap.From.Max"), time, 1.0, &self.expr); |
| 948 | let tmin = comp.eval_number(node, &format!("{pfx}.Remap.To.Min"), time, 0.0, &self.expr); |
| 949 | let tmax = comp.eval_number(node, &format!("{pfx}.Remap.To.Max"), time, 1.0, &self.expr); |
| 950 | let inv_base = comp.eval_number(node, &format!("{pfx}.Remap.To.Invert"), time, 0.0, &self.expr); |
| 951 | |
| 952 | let (fmin_x, fmax_x, fmin_y, fmax_y, tmin_x, tmax_x, tmin_y, tmax_y, inv_x, inv_y) = |
| 953 | if matches!(channel, CopyAuxChannel::Vector | CopyAuxChannel::BackVector) { |
| 954 | ( |
| 955 | comp.eval_number(node, &format!("{pfx}.Remap.From.MinX"), time, fmin, &self.expr) as f32, |
| 956 | comp.eval_number(node, &format!("{pfx}.Remap.From.MaxX"), time, fmax, &self.expr) as f32, |
| 957 | comp.eval_number(node, &format!("{pfx}.Remap.From.MinY"), time, fmin, &self.expr) as f32, |
| 958 | comp.eval_number(node, &format!("{pfx}.Remap.From.MaxY"), time, fmax, &self.expr) as f32, |
| 959 | comp.eval_number(node, &format!("{pfx}.Remap.To.MinX"), time, tmin, &self.expr) as f32, |
| 960 | comp.eval_number(node, &format!("{pfx}.Remap.To.MaxX"), time, tmax, &self.expr) as f32, |
| 961 | comp.eval_number(node, &format!("{pfx}.Remap.To.MinY"), time, tmin, &self.expr) as f32, |
| 962 | comp.eval_number(node, &format!("{pfx}.Remap.To.MaxY"), time, tmax, &self.expr) as f32, |
| 963 | comp.eval_number(node, &format!("{pfx}.Remap.To.InvertX"), time, inv_base, &self.expr) as f32, |
| 964 | comp.eval_number(node, &format!("{pfx}.Remap.To.InvertY"), time, inv_base, &self.expr) as f32, |
| 965 | ) |
| 966 | } else { |
| 967 | ( |
| 968 | fmin as f32, |
| 969 | fmax as f32, |
| 970 | fmin as f32, |
| 971 | fmax as f32, |
| 972 | tmin as f32, |
| 973 | tmax as f32, |
| 974 | tmin as f32, |
| 975 | tmax as f32, |
| 976 | inv_base as f32, |
| 977 | inv_base as f32, |
| 978 | ) |
| 979 | }; |
| 980 | |
| 981 | let dst_depth = self.node_depth(comp, node, time, Some(src.depth)); |
| 982 | let mut u = UniformParams::default(); |
| 983 | u.p[0] = [ |
| 984 | channel.shader_kind(), |
| 985 | if remap_en { 1.0 } else { 0.0 }, |
| 986 | if inv_x >= 0.5 { 1.0 } else { 0.0 }, |
| 987 | if inv_y >= 0.5 { 1.0 } else { 0.0 }, |
| 988 | ]; |
| 989 | u.p[1] = [fmin_x, fmax_x, tmin_x, tmax_x]; |
| 990 | u.p[2] = [fmin_y, fmax_y, tmin_y, tmax_y]; |
| 991 | u.p[3] = [ |
| 992 | blend, |
| 993 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 994 | if mask_inv { 1.0 } else { 0.0 }, |
| 995 | if mbm { 1.0 } else { 0.0 }, |
| 996 | ]; |
| 997 | |
| 998 | let key = self.make_key( |
| 999 | node, |
| 1000 | "CopyAuxToColor", |
| 1001 | src.size, |
| 1002 | &[src.content_hash, mask_hash, dst_depth as u64, kill_aux as u64], |
| 1003 | bytemuck::cast_slice(&u.p[..4]), |
| 1004 | ); |
| 1005 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1006 | stats.cache_hits += 1; |
| 1007 | return hit; |
| 1008 | } |
| 1009 | stats.cache_misses += 1; |
| 1010 | stats.nodes_evaluated += 1; |
| 1011 | |
| 1012 | let aux_view = { |
| 1013 | let a = src.aux.as_ref().expect("checked src_has_sel"); |
| 1014 | match channel { |
| 1015 | CopyAuxChannel::Z => a.z.as_ref().expect("z").view.clone(), |
| 1016 | CopyAuxChannel::Normal => a.normal.as_ref().expect("normal").view.clone(), |
| 1017 | CopyAuxChannel::Vector => a.vector.as_ref().expect("vector").view.clone(), |
| 1018 | CopyAuxChannel::BackVector => a.back_vector.as_ref().expect("back_vector").view.clone(), |
| 1019 | CopyAuxChannel::Color => unreachable!(), |
| 1020 | } |
| 1021 | }; |
| 1022 | let mut dst = self.alloc_tex_like(&src, dst_depth, key); |
| 1023 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 1024 | self.aux_pipelines().borrow_mut().dispatch_rgba_op( |
| 1025 | &self.device, |
| 1026 | &self.queue, |
| 1027 | enc, |
| 1028 | false, |
| 1029 | &src.view, |
| 1030 | &aux_view, |
| 1031 | mv, |
| 1032 | &dst, |
| 1033 | &u, |
| 1034 | ); |
| 1035 | if !kill_aux { |
| 1036 | dst.set_aux(src.aux.clone()); |
| 1037 | } |
| 1038 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1039 | dst |
| 1040 | } |
| 1041 | |
| 1042 | /// Computes `ChannelBoolean`'s `ToZBuffer` extra channel and attaches it to `dst.aux.z`. |
| 1043 | #[allow(clippy::too_many_arguments)] |
| 1044 | pub(super) fn apply_channel_boolean_z( |
| 1045 | &self, |
| 1046 | enc: &mut wgpu::CommandEncoder, |
| 1047 | bg: &CachedTexture, |
| 1048 | fg: &CachedTexture, |
| 1049 | mask: Option<&CachedTexture>, |
| 1050 | mask_inv: bool, |
| 1051 | op: i32, |
| 1052 | to_z: i32, |
| 1053 | blend: f32, |
| 1054 | expand_canvas: bool, |
| 1055 | dst: &mut CachedTexture, |
| 1056 | ) { |
| 1057 | let bg_z = bg.aux.as_ref().and_then(|a| a.z.as_ref()); |
| 1058 | let fg_z = fg.aux.as_ref().and_then(|a| a.z.as_ref()); |
| 1059 | |
| 1060 | // If copying FG Z when FG has no Z, or BG Z when BG has no Z, preserve bg.aux without fabricating Z. |
| 1061 | if to_z == 18 && fg_z.is_none() { |
| 1062 | if bg.aux.is_some() && dst.size == bg.size { |
| 1063 | dst.set_aux(bg.aux.clone()); |
| 1064 | } |
| 1065 | return; |
| 1066 | } |
| 1067 | if to_z == 19 && bg_z.is_none() { |
| 1068 | if bg.aux.is_some() && dst.size == bg.size { |
| 1069 | dst.set_aux(bg.aux.clone()); |
| 1070 | } |
| 1071 | return; |
| 1072 | } |
| 1073 | |
| 1074 | // Zero-copy fast path: Op=Copy, ToZBuffer=18 (FG Z), full blend, unmasked, matching extents. |
| 1075 | if op == 0 |
| 1076 | && to_z == 18 |
| 1077 | && blend >= 0.9999 |
| 1078 | && mask.is_none() |
| 1079 | && !expand_canvas |
| 1080 | && !bg.has_dod() |
| 1081 | && !fg.has_dod() |
| 1082 | && let Some(fz) = fg_z |
| 1083 | && fz.size == dst.size |
| 1084 | { |
| 1085 | let mut out_aux = if dst.size == bg.size { bg.aux_cloned() } else { AuxChannels::default() }; |
| 1086 | out_aux.z = Some(fz.clone()); |
| 1087 | dst.set_aux(Some(Arc::new(out_aux))); |
| 1088 | return; |
| 1089 | } |
| 1090 | |
| 1091 | let dst_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "cb-zbuffer"); |
| 1092 | let mut u = UniformParams::default(); |
| 1093 | u.p[0] = [op as f32, to_z as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }]; |
| 1094 | u.p[1] = [ |
| 1095 | if mask_inv { 1.0 } else { 0.0 }, |
| 1096 | if bg_z.is_some() { 1.0 } else { 0.0 }, |
| 1097 | if fg_z.is_some() { 1.0 } else { 0.0 }, |
| 1098 | if expand_canvas { 1.0 } else { 0.0 }, |
| 1099 | ]; |
| 1100 | if fg.has_dod() { |
| 1101 | u.p[2] = [fg.origin[0] as f32, fg.origin[1] as f32, fg.canvas_size[0] as f32, fg.canvas_size[1] as f32]; |
| 1102 | } |
| 1103 | if bg.has_dod() { |
| 1104 | u.p[3] = [bg.origin[0] as f32, bg.origin[1] as f32, bg.canvas_size[0] as f32, bg.canvas_size[1] as f32]; |
| 1105 | } |
| 1106 | let mv = mask.map_or(&self.dummy.view, |m| &m.view); |
| 1107 | self.aux_pipelines().borrow_mut().dispatch_r32f_op( |
| 1108 | &self.device, |
| 1109 | &self.queue, |
| 1110 | enc, |
| 1111 | 1, |
| 1112 | &bg.view, |
| 1113 | &fg.view, |
| 1114 | bg_z.map(|t| t.view.as_ref()), |
| 1115 | fg_z.map(|t| t.view.as_ref()), |
| 1116 | mv, |
| 1117 | &dst_z, |
| 1118 | &u, |
| 1119 | ); |
| 1120 | let mut out_aux = if dst.size == bg.size { bg.aux_cloned() } else { AuxChannels::default() }; |
| 1121 | out_aux.z = Some(dst_z); |
| 1122 | dst.set_aux(Some(Arc::new(out_aux))); |
| 1123 | } |
| 1124 | |
| 1125 | /// Dispatches `VectorMotionBlur` compute pass using `vec_view` (either `src.aux.vector` |
| 1126 | /// or an external `VectorInput` texture). |
| 1127 | #[allow(clippy::too_many_arguments)] |
| 1128 | pub(super) fn dispatch_vector_motion_blur( |
| 1129 | &self, |
| 1130 | enc: &mut wgpu::CommandEncoder, |
| 1131 | src: &CachedTexture, |
| 1132 | vec_view: &wgpu::TextureView, |
| 1133 | mask_view: &wgpu::TextureView, |
| 1134 | dst: &CachedTexture, |
| 1135 | params: &UniformParams, |
| 1136 | ) { |
| 1137 | self.aux_pipelines().borrow_mut().dispatch_rgba_op( |
| 1138 | &self.device, |
| 1139 | &self.queue, |
| 1140 | enc, |
| 1141 | true, |
| 1142 | &src.view, |
| 1143 | vec_view, |
| 1144 | mask_view, |
| 1145 | dst, |
| 1146 | params, |
| 1147 | ); |
| 1148 | } |
| 1149 | |
| 1150 | /// Computes a dense motion vector texture (`Rgba16Float`, Fusion pixel units `+X` right, `+Y` up) |
| 1151 | /// from `frame_src` to `frame_dst`. |
| 1152 | pub(super) fn compute_optflow_vector_tex( |
| 1153 | &self, |
| 1154 | enc: &mut wgpu::CommandEncoder, |
| 1155 | frame_src: &CachedTexture, |
| 1156 | frame_dst: &CachedTexture, |
| 1157 | label: &str, |
| 1158 | ) -> AuxChannelTex { |
| 1159 | let size = frame_src.size; |
| 1160 | let out = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, label); |
| 1161 | let mut ap = self.aux_pipelines().borrow_mut(); |
| 1162 | |
| 1163 | // Identical static frames -> zero flow in a single trivial fill. |
| 1164 | if frame_src.content_hash != 0 && frame_src.content_hash == frame_dst.content_hash { |
| 1165 | let mut u = UniformParams::default(); |
| 1166 | u.p[0] = [3.0, 1.0, 0.0, 0.0]; // kind 3 = ZeroFill |
| 1167 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 0, &frame_src.view, None, None, &out, &u); |
| 1168 | return out; |
| 1169 | } |
| 1170 | |
| 1171 | let coarse_size = [size[0].div_ceil(4).max(1), size[1].div_ceil(4).max(1)]; |
| 1172 | let feat_a = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, "of-fa"); |
| 1173 | let feat_b = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, "of-fb"); |
| 1174 | let feat_ac = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fac"); |
| 1175 | let feat_bc = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fbc"); |
| 1176 | let flow_c = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fc"); |
| 1177 | |
| 1178 | let u0 = UniformParams::default(); |
| 1179 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_src.view, None, None, &feat_a, &u0); |
| 1180 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_dst.view, None, None, &feat_b, &u0); |
| 1181 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_src.view, None, None, &feat_ac, &u0); |
| 1182 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_dst.view, None, None, &feat_bc, &u0); |
| 1183 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 3, &feat_ac.view, Some(&feat_bc.view), None, &flow_c, &u0); |
| 1184 | |
| 1185 | let mut ur = UniformParams::default(); |
| 1186 | ur.p[0] = [ |
| 1187 | size[0] as f32 / coarse_size[0] as f32, |
| 1188 | size[1] as f32 / coarse_size[1] as f32, |
| 1189 | 1.0, // convert texture +Y-down to Fusion +Y-up |
| 1190 | 0.0, |
| 1191 | ]; |
| 1192 | ap.dispatch_f16_op( |
| 1193 | &self.device, |
| 1194 | &self.queue, |
| 1195 | enc, |
| 1196 | 4, |
| 1197 | &feat_a.view, |
| 1198 | Some(&feat_b.view), |
| 1199 | Some(&flow_c.view), |
| 1200 | &out, |
| 1201 | &ur, |
| 1202 | ); |
| 1203 | out |
| 1204 | } |
| 1205 | |
| 1206 | /// Evaluates `Dimension.OpticalFlow` / `OpticalFlow`: passes RGBA through unchanged, |
| 1207 | /// and attaches forward (`t -> t+1`) + backward (`t -> t-1`) motion vectors as |
| 1208 | /// `aux.vector` / `aux.back_vector` ONLY when a downstream consumer uses motion vectors. |
| 1209 | #[allow(clippy::too_many_arguments)] |
| 1210 | pub(super) fn eval_optical_flow( |
| 1211 | &mut self, |
| 1212 | comp: &Comp, |
| 1213 | node: &Node, |
| 1214 | time: f64, |
| 1215 | frame_i: i64, |
| 1216 | enc: &mut wgpu::CommandEncoder, |
| 1217 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1218 | stats: &mut EvalStats, |
| 1219 | ) -> CachedTexture { |
| 1220 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 1221 | return self.dummy.clone(); |
| 1222 | }; |
| 1223 | let curr = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 1224 | if !time.is_finite() || !comp_uses_optical_flow_vectors(comp) { |
| 1225 | return curr; |
| 1226 | } |
| 1227 | let next = self.eval_node(comp, src_id, time + 1.0, enc, visiting, stats); |
| 1228 | let prev = self.eval_node(comp, src_id, time - 1.0, enc, visiting, stats); |
| 1229 | let curr_c = self.crop_to_canvas(enc, curr.clone()); |
| 1230 | let next_c = self.crop_to_canvas(enc, next); |
| 1231 | let prev_c = self.crop_to_canvas(enc, prev); |
| 1232 | |
| 1233 | let key = self.make_key( |
| 1234 | node, |
| 1235 | "OpticalFlowAux", |
| 1236 | curr_c.size, |
| 1237 | &[curr_c.content_hash, next_c.content_hash, prev_c.content_hash], |
| 1238 | &[], |
| 1239 | ); |
| 1240 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1241 | stats.cache_hits += 1; |
| 1242 | return hit; |
| 1243 | } |
| 1244 | stats.cache_misses += 1; |
| 1245 | stats.nodes_evaluated += 1; |
| 1246 | |
| 1247 | let fwd = self.compute_optflow_vector_tex(enc, &curr_c, &next_c, "optflow-fwd-vec"); |
| 1248 | let bwd = self.compute_optflow_vector_tex(enc, &curr_c, &prev_c, "optflow-bwd-vec"); |
| 1249 | |
| 1250 | let mut out = curr_c; |
| 1251 | out.content_hash = key; |
| 1252 | let mut aux = out.aux_cloned(); |
| 1253 | aux.vector = Some(fwd); |
| 1254 | aux.back_vector = Some(bwd); |
| 1255 | out.set_aux(Some(Arc::new(aux))); |
| 1256 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 1257 | out |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | #[cfg(test)] |
| 1262 | mod tests { |
| 1263 | use super::*; |
| 1264 | |
| 1265 | fn readback_r32f(eng: &Engine, tex: &AuxChannelTex) -> Vec<f32> { |
| 1266 | let [w, h] = tex.size; |
| 1267 | assert_eq!(tex.format, wgpu::TextureFormat::R32Float); |
| 1268 | let unpadded_bpr = w * 4; |
| 1269 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 1270 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 1271 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { |
| 1272 | label: Some("readback-r32f"), |
| 1273 | size: u64::from(padded_bpr) * u64::from(h), |
| 1274 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 1275 | mapped_at_creation: false, |
| 1276 | }); |
| 1277 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 1278 | enc.copy_texture_to_buffer( |
| 1279 | tex.texture.as_image_copy(), |
| 1280 | wgpu::TexelCopyBufferInfo { |
| 1281 | buffer: &buf, |
| 1282 | layout: wgpu::TexelCopyBufferLayout { |
| 1283 | offset: 0, |
| 1284 | bytes_per_row: Some(padded_bpr), |
| 1285 | rows_per_image: Some(h), |
| 1286 | }, |
| 1287 | }, |
| 1288 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 1289 | ); |
| 1290 | eng.queue.submit(Some(enc.finish())); |
| 1291 | let slice = buf.slice(..); |
| 1292 | let (tx, rx) = std::sync::mpsc::channel(); |
| 1293 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 1294 | let _ = tx.send(res); |
| 1295 | }); |
| 1296 | eng.device |
| 1297 | .poll(wgpu::PollType::Wait { |
| 1298 | submission_index: None, |
| 1299 | timeout: Some(std::time::Duration::from_secs(10)), |
| 1300 | }) |
| 1301 | .unwrap(); |
| 1302 | rx.recv().unwrap().unwrap(); |
| 1303 | let data = slice.get_mapped_range().unwrap(); |
| 1304 | let mut out = Vec::with_capacity((w * h) as usize); |
| 1305 | for y in 0..h as usize { |
| 1306 | let row = &data[y * padded_bpr as usize..y * padded_bpr as usize + unpadded_bpr as usize]; |
| 1307 | for ch in row.chunks_exact(4) { |
| 1308 | out.push(f32::from_le_bytes([ch[0], ch[1], ch[2], ch[3]])); |
| 1309 | } |
| 1310 | } |
| 1311 | drop(data); |
| 1312 | buf.unmap(); |
| 1313 | out |
| 1314 | } |
| 1315 | |
| 1316 | fn f16_to_f32(bits: u16) -> f32 { |
| 1317 | let sign = ((bits & 0x8000) as u32) << 16; |
| 1318 | let exp = (bits >> 10) & 0x1F; |
| 1319 | let frac = (bits & 0x03FF) as u32; |
| 1320 | if exp == 0 { |
| 1321 | if frac == 0 { |
| 1322 | f32::from_bits(sign) |
| 1323 | } else { |
| 1324 | let mut f = frac; |
| 1325 | let mut e = -14i32; |
| 1326 | while (f & 0x0400) == 0 { |
| 1327 | f <<= 1; |
| 1328 | e -= 1; |
| 1329 | } |
| 1330 | let f_norm = f & 0x03FF; |
| 1331 | let e_f32 = ((e + 127) as u32) << 23; |
| 1332 | f32::from_bits(sign | e_f32 | (f_norm << 13)) |
| 1333 | } |
| 1334 | } else if exp == 0x1F { |
| 1335 | f32::from_bits(sign | 0x7F80_0000 | (frac << 13)) |
| 1336 | } else { |
| 1337 | let e_f32 = ((exp as u32) + 112) << 23; |
| 1338 | f32::from_bits(sign | e_f32 | (frac << 13)) |
| 1339 | } |
| 1340 | } |
| 1341 | |
| 1342 | fn readback_rgba16f(eng: &Engine, tex: &AuxChannelTex) -> Vec<[f32; 4]> { |
| 1343 | let [w, h] = tex.size; |
| 1344 | assert_eq!(tex.format, wgpu::TextureFormat::Rgba16Float); |
| 1345 | let unpadded_bpr = w * 8; |
| 1346 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 1347 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 1348 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { |
| 1349 | label: Some("readback-aux-f16"), |
| 1350 | size: u64::from(padded_bpr) * u64::from(h), |
| 1351 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 1352 | mapped_at_creation: false, |
| 1353 | }); |
| 1354 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 1355 | enc.copy_texture_to_buffer( |
| 1356 | tex.texture.as_image_copy(), |
| 1357 | wgpu::TexelCopyBufferInfo { |
| 1358 | buffer: &buf, |
| 1359 | layout: wgpu::TexelCopyBufferLayout { |
| 1360 | offset: 0, |
| 1361 | bytes_per_row: Some(padded_bpr), |
| 1362 | rows_per_image: Some(h), |
| 1363 | }, |
| 1364 | }, |
| 1365 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 1366 | ); |
| 1367 | eng.queue.submit(Some(enc.finish())); |
| 1368 | let slice = buf.slice(..); |
| 1369 | let (tx, rx) = std::sync::mpsc::channel(); |
| 1370 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 1371 | let _ = tx.send(res); |
| 1372 | }); |
| 1373 | eng.device |
| 1374 | .poll(wgpu::PollType::Wait { |
| 1375 | submission_index: None, |
| 1376 | timeout: Some(std::time::Duration::from_secs(10)), |
| 1377 | }) |
| 1378 | .unwrap(); |
| 1379 | rx.recv().unwrap().unwrap(); |
| 1380 | let data = slice.get_mapped_range().unwrap(); |
| 1381 | let mut out = Vec::with_capacity((w * h) as usize); |
| 1382 | for y in 0..h as usize { |
| 1383 | let row = &data[y * padded_bpr as usize..y * padded_bpr as usize + unpadded_bpr as usize]; |
| 1384 | for ch in row.chunks_exact(8) { |
| 1385 | out.push([ |
| 1386 | f16_to_f32(u16::from_le_bytes([ch[0], ch[1]])), |
| 1387 | f16_to_f32(u16::from_le_bytes([ch[2], ch[3]])), |
| 1388 | f16_to_f32(u16::from_le_bytes([ch[4], ch[5]])), |
| 1389 | f16_to_f32(u16::from_le_bytes([ch[6], ch[7]])), |
| 1390 | ]); |
| 1391 | } |
| 1392 | } |
| 1393 | drop(data); |
| 1394 | buf.unmap(); |
| 1395 | out |
| 1396 | } |
| 1397 | |
| 1398 | fn px_center(px: &[u8], w: u32, h: u32) -> [u8; 4] { |
| 1399 | let i = (((h / 2) * w + (w / 2)) * 4) as usize; |
| 1400 | [px[i], px[i + 1], px[i + 2], px[i + 3]] |
| 1401 | } |
| 1402 | |
| 1403 | /// Helper snippet building a 16x16 float32 image with RGBA `(r,g,b,a)` and `aux.z = z_val` |
| 1404 | /// via `CopyAux` Mode 1 + `ChannelBoolean` `ToZBuffer = 18`. |
| 1405 | fn z_layer_nodes(prefix: &str, rgba: [f32; 4], z_val: f32) -> String { |
| 1406 | format!( |
| 1407 | r#" |
| 1408 | {prefix}Col = Background {{ |
| 1409 | Inputs = {{ |
| 1410 | Width = Input {{ Value = 16, }}, |
| 1411 | Height = Input {{ Value = 16, }}, |
| 1412 | Depth = Input {{ Value = 4, }}, |
| 1413 | TopLeftRed = Input {{ Value = {r}, }}, |
| 1414 | TopLeftGreen = Input {{ Value = {g}, }}, |
| 1415 | TopLeftBlue = Input {{ Value = {b}, }}, |
| 1416 | TopLeftAlpha = Input {{ Value = {a}, }}, |
| 1417 | }}, |
| 1418 | }}, |
| 1419 | {prefix}ZSrc = Background {{ |
| 1420 | Inputs = {{ |
| 1421 | Width = Input {{ Value = 16, }}, |
| 1422 | Height = Input {{ Value = 16, }}, |
| 1423 | Depth = Input {{ Value = 4, }}, |
| 1424 | TopLeftRed = Input {{ Value = {z}, }}, |
| 1425 | TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 1426 | }}, |
| 1427 | }}, |
| 1428 | {prefix}ZAux = Dimension.CopyAux {{ |
| 1429 | Inputs = {{ |
| 1430 | Mode = Input {{ Value = 1, }}, |
| 1431 | Channel = Input {{ Value = FuID {{ "Z" }}, }}, |
| 1432 | Input = Input {{ SourceOp = "{prefix}ZSrc", Source = "Output", }}, |
| 1433 | }}, |
| 1434 | }}, |
| 1435 | {prefix} = ChannelBoolean {{ |
| 1436 | Inputs = {{ |
| 1437 | ToRed = Input {{ Value = 5, }}, |
| 1438 | ToGreen = Input {{ Value = 6, }}, |
| 1439 | ToBlue = Input {{ Value = 7, }}, |
| 1440 | ToAlpha = Input {{ Value = 8, }}, |
| 1441 | EnableExtraChannels = Input {{ Value = 1, }}, |
| 1442 | ToZBuffer = Input {{ Value = 18, }}, |
| 1443 | Background = Input {{ SourceOp = "{prefix}Col", Source = "Output", }}, |
| 1444 | Foreground = Input {{ SourceOp = "{prefix}ZAux", Source = "Output", }}, |
| 1445 | }}, |
| 1446 | }},"#, |
| 1447 | r = rgba[0], |
| 1448 | g = rgba[1], |
| 1449 | b = rgba[2], |
| 1450 | a = rgba[3], |
| 1451 | z = z_val, |
| 1452 | ) |
| 1453 | } |
| 1454 | |
| 1455 | #[test] |
| 1456 | fn merge_perform_depth_merge_all_snow_globe_cases() { |
| 1457 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1458 | let src = format!( |
| 1459 | r#"Composition {{ |
| 1460 | CurrentTime = 0, |
| 1461 | RenderRange = {{ 0, 1 }}, |
| 1462 | GlobalRange = {{ 0, 1 }}, |
| 1463 | Tools = ordered() {{ |
| 1464 | {} |
| 1465 | {} |
| 1466 | {} |
| 1467 | {} |
| 1468 | Plain2DRed = Background {{ |
| 1469 | Inputs = {{ |
| 1470 | Width = Input {{ Value = 16, }}, |
| 1471 | Height = Input {{ Value = 16, }}, |
| 1472 | Depth = Input {{ Value = 4, }}, |
| 1473 | TopLeftRed = Input {{ Value = 1.0, }}, |
| 1474 | TopLeftGreen = Input {{ Value = 0.0, }}, |
| 1475 | TopLeftBlue = Input {{ Value = 0.0, }}, |
| 1476 | TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 1477 | }}, |
| 1478 | }}, |
| 1479 | Plain2DGreen = Background {{ |
| 1480 | Inputs = {{ |
| 1481 | Width = Input {{ Value = 16, }}, |
| 1482 | Height = Input {{ Value = 16, }}, |
| 1483 | Depth = Input {{ Value = 4, }}, |
| 1484 | TopLeftRed = Input {{ Value = 0.0, }}, |
| 1485 | TopLeftGreen = Input {{ Value = 1.0, }}, |
| 1486 | TopLeftBlue = Input {{ Value = 0.0, }}, |
| 1487 | TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 1488 | }}, |
| 1489 | }}, |
| 1490 | -- 1. Opaque FG near (-2) over BG far (-5): FG wins, Z = -2 |
| 1491 | M1_FgNear = Merge {{ |
| 1492 | Inputs = {{ |
| 1493 | Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1494 | Foreground = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 1495 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1496 | }}, |
| 1497 | }}, |
| 1498 | -- 2. Opaque FG far (-5) over BG near (-2): BG wins completely, Z = -2 |
| 1499 | M2_FgFar = Merge {{ |
| 1500 | Inputs = {{ |
| 1501 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 1502 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1503 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1504 | }}, |
| 1505 | }}, |
| 1506 | -- 3. Semi-transparent FG near (-2, a=0.5) over opaque BG far (-5): FG blends over BG, Z = -2 |
| 1507 | M3_SemiFgNear = Merge {{ |
| 1508 | Inputs = {{ |
| 1509 | Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1510 | Foreground = Input {{ SourceOp = "SemiNear", Source = "Output", }}, |
| 1511 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1512 | }}, |
| 1513 | }}, |
| 1514 | -- 4. Opaque FG far (-5) over semi-transparent BG near (-2, a=0.5): BG blends OVER FG, Z = -2 |
| 1515 | M4_FgFarOverSemiBgNear = Merge {{ |
| 1516 | Inputs = {{ |
| 1517 | Background = Input {{ SourceOp = "SemiNear", Source = "Output", }}, |
| 1518 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1519 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1520 | }}, |
| 1521 | }}, |
| 1522 | -- 5. 2D FG (no Z, implicit 0.0) over Z BG (-5): FG wins, output Z = 0.0! |
| 1523 | M5_2dFgOverZBg = Merge {{ |
| 1524 | Inputs = {{ |
| 1525 | Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1526 | Foreground = Input {{ SourceOp = "Plain2DGreen", Source = "Output", }}, |
| 1527 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1528 | }}, |
| 1529 | }}, |
| 1530 | -- 6. Z FG (-5) over 2D BG (no Z, implicit 0.0): BG wins (0.0 > -5.0), output Z = None! |
| 1531 | M6_ZFgOver2dBg = Merge {{ |
| 1532 | Inputs = {{ |
| 1533 | Background = Input {{ SourceOp = "Plain2DRed", Source = "Output", }}, |
| 1534 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1535 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1536 | }}, |
| 1537 | }}, |
| 1538 | -- 7. PerformDepthMerge = 0: FG far (-5) composited OVER BG near (-2) normally, Z = -5! |
| 1539 | M7_NoDepthMerge = Merge {{ |
| 1540 | Inputs = {{ |
| 1541 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 1542 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1543 | PerformDepthMerge = Input {{ Value = 0, }}, |
| 1544 | }}, |
| 1545 | }}, |
| 1546 | -- 8. ForegroundZOffset shifts FG far (-5) by +4 -> -1 (> BG -2), so FG wins! |
| 1547 | M8_ZOffset = Merge {{ |
| 1548 | Inputs = {{ |
| 1549 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 1550 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1551 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1552 | ForegroundZOffset = Input {{ Value = 4.0, }}, |
| 1553 | }}, |
| 1554 | }}, |
| 1555 | }}, |
| 1556 | }}"#, |
| 1557 | // BgFar: opaque blue (0, 0, 1, 1) at Z = -5.0 |
| 1558 | z_layer_nodes("BgFar", [0.0, 0.0, 1.0, 1.0], -5.0), |
| 1559 | // FgNear: opaque red (1, 0, 0, 1) at Z = -2.0 |
| 1560 | z_layer_nodes("FgNear", [1.0, 0.0, 0.0, 1.0], -2.0), |
| 1561 | // SemiNear: semi-transparent premultiplied green (0, 0.5, 0, 0.5) at Z = -2.0 |
| 1562 | z_layer_nodes("SemiNear", [0.0, 0.5, 0.0, 0.5], -2.0), |
| 1563 | // Unused helper just for variety |
| 1564 | z_layer_nodes("UnusedExtra", [0.2, 0.3, 0.4, 1.0], -8.0), |
| 1565 | ); |
| 1566 | |
| 1567 | let comp = Comp::from_fusion_str(&src).expect("parse depth merge comp"); |
| 1568 | let mut eval_one = |name: &str| -> ([u8; 4], Option<f32>) { |
| 1569 | let id = comp.find_node(name).unwrap(); |
| 1570 | let (tex, stats) = eng.evaluate(&comp, id, 0.0); |
| 1571 | assert!(stats.unsupported_nodes.is_empty(), "{name}: {:?}", stats.unsupported_nodes); |
| 1572 | let px = eng.readback_rgba(&tex).unwrap(); |
| 1573 | let c = px_center(&px, tex.size[0], tex.size[1]); |
| 1574 | let z = tex.aux.as_ref().and_then(|a| a.z.as_ref()).map(|zt| { |
| 1575 | let zs = readback_r32f(&eng, zt); |
| 1576 | zs[(zt.size[1] / 2 * zt.size[0] + zt.size[0] / 2) as usize] |
| 1577 | }); |
| 1578 | (c, z) |
| 1579 | }; |
| 1580 | |
| 1581 | // 1. Opaque FG near (red, -2) over BG far (blue, -5) -> red, Z = -2 |
| 1582 | let (c1, z1) = eval_one("M1_FgNear"); |
| 1583 | assert_eq!(c1, [255, 0, 0, 255], "M1_FgNear color"); |
| 1584 | assert!((z1.unwrap() - (-2.0)).abs() < 1e-3, "M1_FgNear z={z1:?}"); |
| 1585 | |
| 1586 | // 2. Opaque FG far (blue, -5) over BG near (red, -2) -> red (BG wins!), Z = -2 |
| 1587 | let (c2, z2) = eval_one("M2_FgFar"); |
| 1588 | assert_eq!(c2, [255, 0, 0, 255], "M2_FgFar color (BG must occlude far FG)"); |
| 1589 | assert!((z2.unwrap() - (-2.0)).abs() < 1e-3, "M2_FgFar z={z2:?}"); |
| 1590 | |
| 1591 | // 3. Semi-transparent FG near (0, 0.5, 0, 0.5 @ -2) over opaque BG far (0, 0, 1, 1 @ -5) |
| 1592 | // -> (0, 0.5, 0.5, 1.0) = [0, 128, 128, 255], Z = -2 |
| 1593 | let (c3, z3) = eval_one("M3_SemiFgNear"); |
| 1594 | assert_eq!(c3[0], 0); |
| 1595 | assert!((c3[1] as i32 - 128).abs() <= 2, "M3 G={c3:?}"); |
| 1596 | assert!((c3[2] as i32 - 128).abs() <= 2, "M3 B={c3:?}"); |
| 1597 | assert_eq!(c3[3], 255); |
| 1598 | assert!((z3.unwrap() - (-2.0)).abs() < 1e-3, "M3 z={z3:?}"); |
| 1599 | |
| 1600 | // 4. Opaque FG far (0, 0, 1, 1 @ -5) over semi-transparent BG near (0, 0.5, 0, 0.5 @ -2) |
| 1601 | // -> BG over FG = (0, 0.5, 0.5, 1.0) = [0, 128, 128, 255], Z = -2! |
| 1602 | let (c4, z4) = eval_one("M4_FgFarOverSemiBgNear"); |
| 1603 | assert_eq!(c4[0], 0); |
| 1604 | assert!((c4[1] as i32 - 128).abs() <= 2, "M4 G={c4:?}"); |
| 1605 | assert!((c4[2] as i32 - 128).abs() <= 2, "M4 B={c4:?}"); |
| 1606 | assert_eq!(c4[3], 255); |
| 1607 | assert!((z4.unwrap() - (-2.0)).abs() < 1e-3, "M4 z={z4:?}"); |
| 1608 | |
| 1609 | // 5. 2D FG (green, no Z -> implicit 0.0) over Z BG (blue, -5) -> green, Z = 0.0! |
| 1610 | let (c5, z5) = eval_one("M5_2dFgOverZBg"); |
| 1611 | assert_eq!(c5, [0, 255, 0, 255], "M5 2D FG must beat -5 BG"); |
| 1612 | assert!((z5.unwrap() - 0.0).abs() < 1e-3, "M5 z={z5:?}"); |
| 1613 | |
| 1614 | // 6. Z FG (blue, -5) over 2D BG (red, no Z -> implicit 0.0) -> red (BG wins!), Z = None! |
| 1615 | let (c6, z6) = eval_one("M6_ZFgOver2dBg"); |
| 1616 | assert_eq!(c6, [255, 0, 0, 255], "M6 2D BG at 0.0 must occlude -5 FG"); |
| 1617 | assert!(z6.is_none(), "M6 output Z must be None when BG had no Z, got {z6:?}"); |
| 1618 | |
| 1619 | // 7. PerformDepthMerge = 0: FG far (blue, -5) wins over BG near (red, -2), Z = -5! |
| 1620 | let (c7, z7) = eval_one("M7_NoDepthMerge"); |
| 1621 | assert_eq!(c7, [0, 0, 255, 255], "M7 PerformDepthMerge=0 must composite FG over BG"); |
| 1622 | assert!((z7.unwrap() - (-5.0)).abs() < 1e-3, "M7 z={z7:?}"); |
| 1623 | |
| 1624 | // 8. ForegroundZOffset = +4.0 shifts FG (-5 + 4 = -1 > -2) in front of BG -> blue, Z = -1! |
| 1625 | let (c8, z8) = eval_one("M8_ZOffset"); |
| 1626 | assert_eq!(c8, [0, 0, 255, 255], "M8 ZOffset must bring FG in front of BG"); |
| 1627 | assert!((z8.unwrap() - (-1.0)).abs() < 1e-3, "M8 z={z8:?}"); |
| 1628 | } |
| 1629 | |
| 1630 | #[test] |
| 1631 | fn copy_aux_modes_remap_channels_and_kill_aux() { |
| 1632 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1633 | let src = r#"Composition { |
| 1634 | CurrentTime = 0, |
| 1635 | RenderRange = { 0, 1 }, |
| 1636 | GlobalRange = { 0, 1 }, |
| 1637 | Tools = ordered() { |
| 1638 | ZData = Background { |
| 1639 | Inputs = { |
| 1640 | Width = Input { Value = 16, }, |
| 1641 | Height = Input { Value = 16, }, |
| 1642 | Depth = Input { Value = 4, }, |
| 1643 | TopLeftRed = Input { Value = -5.0, }, |
| 1644 | TopLeftGreen = Input { Value = 0.25, }, |
| 1645 | TopLeftBlue = Input { Value = 0.75, }, |
| 1646 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1647 | }, |
| 1648 | }, |
| 1649 | -- Mode 1: Color -> Z (preserves RGBA + sets aux.z = -5.0) |
| 1650 | WriteZ = Dimension.CopyAux { |
| 1651 | Inputs = { |
| 1652 | Mode = Input { Value = 1, }, |
| 1653 | Channel = Input { Value = FuID { "Z" }, }, |
| 1654 | Input = Input { SourceOp = "ZData", Source = "Output", }, |
| 1655 | }, |
| 1656 | }, |
| 1657 | -- Mode 0: Z -> Color with Remap -10..0 -> 0..1 (-5.0 -> 0.5 -> ~128) |
| 1658 | ReadZRemap = Dimension.CopyAux { |
| 1659 | Inputs = { |
| 1660 | Mode = Input { Value = 0, }, |
| 1661 | Channel = Input { Value = FuID { "Z" }, }, |
| 1662 | ["Z.Remap.Enable"] = Input { Value = 1, }, |
| 1663 | ["Z.Remap.From.Min"] = Input { Value = -10.0, }, |
| 1664 | ["Z.Remap.From.Max"] = Input { Value = 0.0, }, |
| 1665 | ["Z.Remap.To.Min"] = Input { Value = 0.0, }, |
| 1666 | ["Z.Remap.To.Max"] = Input { Value = 1.0, }, |
| 1667 | Input = Input { SourceOp = "WriteZ", Source = "Output", }, |
| 1668 | }, |
| 1669 | }, |
| 1670 | -- Mode 0: Z -> Color with Remap + Invert + KillAuxChannels = 1 |
| 1671 | ReadZInvertKill = Dimension.CopyAux { |
| 1672 | Inputs = { |
| 1673 | Mode = Input { Value = 0, }, |
| 1674 | Channel = Input { Value = FuID { "Z" }, }, |
| 1675 | KillAuxChannels = Input { Value = 1, }, |
| 1676 | ["Z.Remap.Enable"] = Input { Value = 1, }, |
| 1677 | ["Z.Remap.From.Min"] = Input { Value = -10.0, }, |
| 1678 | ["Z.Remap.From.Max"] = Input { Value = 0.0, }, |
| 1679 | ["Z.Remap.To.Min"] = Input { Value = 0.0, }, |
| 1680 | ["Z.Remap.To.Max"] = Input { Value = 1.0, }, |
| 1681 | ["Z.Remap.To.Invert"] = Input { Value = 1, }, |
| 1682 | Input = Input { SourceOp = "WriteZ", Source = "Output", }, |
| 1683 | }, |
| 1684 | }, |
| 1685 | -- Mode 1 -> Mode 0 for Normal |
| 1686 | NormSrc = Background { |
| 1687 | Inputs = { |
| 1688 | Width = Input { Value = 16, }, |
| 1689 | Height = Input { Value = 16, }, |
| 1690 | Depth = Input { Value = 4, }, |
| 1691 | TopLeftRed = Input { Value = 0.2, }, |
| 1692 | TopLeftGreen = Input { Value = 0.6, }, |
| 1693 | TopLeftBlue = Input { Value = 0.8, }, |
| 1694 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1695 | }, |
| 1696 | }, |
| 1697 | WriteNorm = Dimension.CopyAux { |
| 1698 | Inputs = { |
| 1699 | Mode = Input { Value = 1, }, |
| 1700 | Channel = Input { Value = FuID { "Normal" }, }, |
| 1701 | Input = Input { SourceOp = "NormSrc", Source = "Output", }, |
| 1702 | }, |
| 1703 | }, |
| 1704 | ReadNorm = Dimension.CopyAux { |
| 1705 | Inputs = { |
| 1706 | Mode = Input { Value = 0, }, |
| 1707 | Channel = Input { Value = FuID { "Normal" }, }, |
| 1708 | Input = Input { SourceOp = "WriteNorm", Source = "Output", }, |
| 1709 | }, |
| 1710 | }, |
| 1711 | -- Mode 1 -> Mode 0 for Vector with MinX/MaxX/MinY/MaxY remap |
| 1712 | VecSrc = Background { |
| 1713 | Inputs = { |
| 1714 | Width = Input { Value = 16, }, |
| 1715 | Height = Input { Value = 16, }, |
| 1716 | Depth = Input { Value = 4, }, |
| 1717 | TopLeftRed = Input { Value = 4.0, }, |
| 1718 | TopLeftGreen = Input { Value = -2.0, }, |
| 1719 | TopLeftBlue = Input { Value = 0.9, }, |
| 1720 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1721 | }, |
| 1722 | }, |
| 1723 | WriteVec = Dimension.CopyAux { |
| 1724 | Inputs = { |
| 1725 | Mode = Input { Value = 1, }, |
| 1726 | Channel = Input { Value = FuID { "Vector" }, }, |
| 1727 | Input = Input { SourceOp = "VecSrc", Source = "Output", }, |
| 1728 | }, |
| 1729 | }, |
| 1730 | ReadVec = Dimension.CopyAux { |
| 1731 | Inputs = { |
| 1732 | Mode = Input { Value = 0, }, |
| 1733 | Channel = Input { Value = FuID { "Vector" }, }, |
| 1734 | ["Vector.Remap.Enable"] = Input { Value = 1, }, |
| 1735 | ["Vector.Remap.From.MinX"] = Input { Value = 0.0, }, |
| 1736 | ["Vector.Remap.From.MaxX"] = Input { Value = 8.0, }, |
| 1737 | ["Vector.Remap.From.MinY"] = Input { Value = -4.0, }, |
| 1738 | ["Vector.Remap.From.MaxY"] = Input { Value = 4.0, }, |
| 1739 | ["Vector.Remap.To.Min"] = Input { Value = 0.0, }, |
| 1740 | ["Vector.Remap.To.Max"] = Input { Value = 1.0, }, |
| 1741 | Input = Input { SourceOp = "WriteVec", Source = "Output", }, |
| 1742 | }, |
| 1743 | }, |
| 1744 | }, |
| 1745 | }"#; |
| 1746 | let comp = Comp::from_fusion_str(src).expect("parse CopyAux comp"); |
| 1747 | |
| 1748 | // Mode 1: WriteZ preserves RGBA (G=0.25~64, B=0.75~191) AND sets aux.z = -5.0 |
| 1749 | let (wz, _) = eng.evaluate(&comp, comp.find_node("WriteZ").unwrap(), 0.0); |
| 1750 | let wz_px = px_center(&eng.readback_rgba(&wz).unwrap(), wz.size[0], wz.size[1]); |
| 1751 | assert!((wz_px[1] as i32 - 64).abs() <= 2 && (wz_px[2] as i32 - 191).abs() <= 2, "WriteZ RGBA={wz_px:?}"); |
| 1752 | let wz_z = readback_r32f(&eng, wz.aux.as_ref().unwrap().z.as_ref().unwrap()); |
| 1753 | assert!((wz_z[8 * 16 + 8] - (-5.0)).abs() < 1e-3, "WriteZ aux.z={}", wz_z[8 * 16 + 8]); |
| 1754 | |
| 1755 | // Mode 0: ReadZRemap maps -5 in [-10..0] -> 0.5 (~128) and preserves aux.z |
| 1756 | let (rz, _) = eng.evaluate(&comp, comp.find_node("ReadZRemap").unwrap(), 0.0); |
| 1757 | let rz_px = px_center(&eng.readback_rgba(&rz).unwrap(), rz.size[0], rz.size[1]); |
| 1758 | assert!((rz_px[0] as i32 - 128).abs() <= 2 && rz_px[0] == rz_px[1] && rz_px[1] == rz_px[2] && rz_px[3] == 255, "ReadZRemap={rz_px:?}"); |
| 1759 | assert!(rz.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "Mode 0 preserves aux when KillAuxChannels=0"); |
| 1760 | |
| 1761 | // Mode 0 + KillAuxChannels = 1 clears aux! |
| 1762 | let (rzk, _) = eng.evaluate(&comp, comp.find_node("ReadZInvertKill").unwrap(), 0.0); |
| 1763 | assert!(rzk.aux.is_none(), "KillAuxChannels=1 must clear aux"); |
| 1764 | |
| 1765 | // Normal roundtrip: (0.2, 0.6, 0.8) -> ~(51, 153, 204, 255) |
| 1766 | let (rn, _) = eng.evaluate(&comp, comp.find_node("ReadNorm").unwrap(), 0.0); |
| 1767 | let rn_px = px_center(&eng.readback_rgba(&rn).unwrap(), rn.size[0], rn.size[1]); |
| 1768 | assert!((rn_px[0] as i32 - 51).abs() <= 2 && (rn_px[1] as i32 - 153).abs() <= 2 && (rn_px[2] as i32 - 204).abs() <= 2 && rn_px[3] == 255, "ReadNorm={rn_px:?}"); |
| 1769 | |
| 1770 | // Vector remap: vx=4 in [0..8] -> 0.5 (~128), vy=-2 in [-4..4] -> 0.25 (~64), b=0, a=1 |
| 1771 | let (rv, _) = eng.evaluate(&comp, comp.find_node("ReadVec").unwrap(), 0.0); |
| 1772 | let rv_px = px_center(&eng.readback_rgba(&rv).unwrap(), rv.size[0], rv.size[1]); |
| 1773 | assert!((rv_px[0] as i32 - 128).abs() <= 2 && (rv_px[1] as i32 - 64).abs() <= 2 && rv_px[2] == 0 && rv_px[3] == 255, "ReadVec={rv_px:?}"); |
| 1774 | } |
| 1775 | |
| 1776 | #[test] |
| 1777 | fn channel_boolean_to_zbuffer_and_color_op_aux_propagation() { |
| 1778 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1779 | let src = format!( |
| 1780 | r#"Composition {{ |
| 1781 | CurrentTime = 0, |
| 1782 | RenderRange = {{ 0, 1 }}, |
| 1783 | GlobalRange = {{ 0, 1 }}, |
| 1784 | Tools = ordered() {{ |
| 1785 | {} |
| 1786 | PlainBg = Background {{ |
| 1787 | Inputs = {{ |
| 1788 | Width = Input {{ Value = 16, }}, |
| 1789 | Height = Input {{ Value = 16, }}, |
| 1790 | Depth = Input {{ Value = 3, }}, |
| 1791 | TopLeftRed = Input {{ Value = 0.3, }}, |
| 1792 | TopLeftGreen = Input {{ Value = 0.6, }}, |
| 1793 | TopLeftBlue = Input {{ Value = 0.9, }}, |
| 1794 | TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 1795 | }}, |
| 1796 | }}, |
| 1797 | -- Copy FG's aux.z (-3.5) onto PlainBg while keeping PlainBg's RGBA |
| 1798 | CbCopyZ = ChannelBoolean {{ |
| 1799 | Inputs = {{ |
| 1800 | ToRed = Input {{ Value = 5, }}, |
| 1801 | ToGreen = Input {{ Value = 6, }}, |
| 1802 | ToBlue = Input {{ Value = 7, }}, |
| 1803 | ToAlpha = Input {{ Value = 8, }}, |
| 1804 | EnableExtraChannels = Input {{ Value = 1, }}, |
| 1805 | ToZBuffer = Input {{ Value = 18, }}, |
| 1806 | Background = Input {{ SourceOp = "PlainBg", Source = "Output", }}, |
| 1807 | Foreground = Input {{ SourceOp = "ZLayer", Source = "Output", }}, |
| 1808 | }}, |
| 1809 | }}, |
| 1810 | -- Chain every single-input color/depth op to verify aux.z propagation! |
| 1811 | N_CC = ColorCorrector {{ Inputs = {{ MasterRGBGain = Input {{ Value = 1.1, }}, Input = Input {{ SourceOp = "CbCopyZ", Source = "Output", }}, }}, }}, |
| 1812 | N_BC = BrightnessContrast {{ Inputs = {{ Gain = Input {{ Value = 0.95, }}, Input = Input {{ SourceOp = "N_CC", Source = "Output", }}, }}, }}, |
| 1813 | N_CG = ColorGain {{ Inputs = {{ GainRed = Input {{ Value = 1.05, }}, Input = Input {{ SourceOp = "N_BC", Source = "Output", }}, }}, }}, |
| 1814 | N_GC = GamutConvert {{ Inputs = {{ SourceSpace = Input {{ Value = FuID {{ "sRGB" }}, }}, OutputSpace = Input {{ Value = FuID {{ "NoChange" }}, }}, Input = Input {{ SourceOp = "N_CG", Source = "Output", }}, }}, }}, |
| 1815 | N_CD = ChangeDepth {{ Inputs = {{ Depth = Input {{ Value = 4, }}, Input = Input {{ SourceOp = "N_GC", Source = "Output", }}, }}, }}, |
| 1816 | N_INV = InvertColor {{ Inputs = {{ Input = Input {{ SourceOp = "N_CD", Source = "Output", }}, }}, }}, |
| 1817 | N_CRV = ColorCurves {{ Inputs = {{ Input = Input {{ SourceOp = "N_INV", Source = "Output", }}, }}, }}, |
| 1818 | N_HUE = HueCurves {{ Inputs = {{ Input = Input {{ SourceOp = "N_CRV", Source = "Output", }}, }}, }}, |
| 1819 | -- ChannelBoolean ToZBuffer = 0 (FG R -> Z) and 16 (White -> 1.0) |
| 1820 | CbFgRToZ = ChannelBoolean {{ |
| 1821 | Inputs = {{ |
| 1822 | ToRed = Input {{ Value = 5, }}, |
| 1823 | ToGreen = Input {{ Value = 6, }}, |
| 1824 | ToBlue = Input {{ Value = 7, }}, |
| 1825 | ToAlpha = Input {{ Value = 8, }}, |
| 1826 | EnableExtraChannels = Input {{ Value = 1, }}, |
| 1827 | ToZBuffer = Input {{ Value = 0, }}, |
| 1828 | Background = Input {{ SourceOp = "PlainBg", Source = "Output", }}, |
| 1829 | Foreground = Input {{ SourceOp = "PlainBg", Source = "Output", }}, |
| 1830 | }}, |
| 1831 | }}, |
| 1832 | CbWhiteZ = ChannelBoolean {{ |
| 1833 | Inputs = {{ |
| 1834 | ToRed = Input {{ Value = 4, }}, |
| 1835 | ToGreen = Input {{ Value = 4, }}, |
| 1836 | ToBlue = Input {{ Value = 4, }}, |
| 1837 | ToAlpha = Input {{ Value = 4, }}, |
| 1838 | EnableExtraChannels = Input {{ Value = 1, }}, |
| 1839 | ToZBuffer = Input {{ Value = 16, }}, |
| 1840 | Background = Input {{ SourceOp = "PlainBg", Source = "Output", }}, |
| 1841 | }}, |
| 1842 | }}, |
| 1843 | }}, |
| 1844 | }}"#, |
| 1845 | z_layer_nodes("ZLayer", [1.0, 0.0, 0.0, 1.0], -3.5), |
| 1846 | ); |
| 1847 | let comp = Comp::from_fusion_str(&src).expect("parse CB + propagation comp"); |
| 1848 | |
| 1849 | // Verify CbCopyZ kept PlainBg RGBA (0.3, 0.6, 0.9) and got aux.z = -3.5 |
| 1850 | let (cb_tex, _) = eng.evaluate(&comp, comp.find_node("CbCopyZ").unwrap(), 0.0); |
| 1851 | let cb_px = px_center(&eng.readback_rgba(&cb_tex).unwrap(), 16, 16); |
| 1852 | assert!((cb_px[0] as i32 - 77).abs() <= 2 && (cb_px[2] as i32 - 230).abs() <= 2, "CbCopyZ RGBA={cb_px:?}"); |
| 1853 | let cb_z = readback_r32f(&eng, cb_tex.aux.as_ref().unwrap().z.as_ref().unwrap()); |
| 1854 | assert!((cb_z[8 * 16 + 8] - (-3.5)).abs() < 1e-3); |
| 1855 | |
| 1856 | // Verify aux.z survived all 8 color/depth ops! |
| 1857 | let (end_tex, _) = eng.evaluate(&comp, comp.find_node("N_HUE").unwrap(), 0.0); |
| 1858 | let end_z = readback_r32f(&eng, end_tex.aux.as_ref().expect("aux survived 8 color ops").z.as_ref().unwrap()); |
| 1859 | assert!((end_z[8 * 16 + 8] - (-3.5)).abs() < 1e-3, "aux.z after 8 ops = {}", end_z[8 * 16 + 8]); |
| 1860 | |
| 1861 | // Verify ToZBuffer = 0 (FG R = 0.3) and ToZBuffer = 16 (White = 1.0) |
| 1862 | let (r_tex, _) = eng.evaluate(&comp, comp.find_node("CbFgRToZ").unwrap(), 0.0); |
| 1863 | let r_z = readback_r32f(&eng, r_tex.aux.as_ref().unwrap().z.as_ref().unwrap()); |
| 1864 | assert!((r_z[8 * 16 + 8] - 0.3).abs() < 0.01, "ToZBuffer=0 got {}", r_z[8 * 16 + 8]); |
| 1865 | |
| 1866 | let (w_tex, _) = eng.evaluate(&comp, comp.find_node("CbWhiteZ").unwrap(), 0.0); |
| 1867 | let w_z = readback_r32f(&eng, w_tex.aux.as_ref().unwrap().z.as_ref().unwrap()); |
| 1868 | assert!((w_z[8 * 16 + 8] - 1.0).abs() < 1e-3, "ToZBuffer=16 got {}", w_z[8 * 16 + 8]); |
| 1869 | } |
| 1870 | |
| 1871 | #[test] |
| 1872 | fn vector_motion_blur_consumes_aux_vector_and_optical_flow() { |
| 1873 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1874 | // 1. Sharp vertical white bar on black with synthetic aux.vector = (16.0, 0.0) |
| 1875 | // -> VectorMotionBlur smears horizontally into adjacent columns! |
| 1876 | let src = r#"Composition { |
| 1877 | CurrentTime = 0, |
| 1878 | RenderRange = { 0, 5 }, |
| 1879 | GlobalRange = { 0, 5 }, |
| 1880 | Tools = ordered() { |
| 1881 | Black = Background { |
| 1882 | Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftAlpha = Input { Value = 1.0, }, }, |
| 1883 | }, |
| 1884 | BarMask = RectangleMask { |
| 1885 | Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.0625, }, Height = Input { Value = 0.75, }, }, |
| 1886 | }, |
| 1887 | WhiteBar = Background { |
| 1888 | Inputs = { |
| 1889 | Width = Input { Value = 64, }, |
| 1890 | Height = Input { Value = 64, }, |
| 1891 | TopLeftRed = Input { Value = 1.0, }, |
| 1892 | TopLeftGreen = Input { Value = 1.0, }, |
| 1893 | TopLeftBlue = Input { Value = 1.0, }, |
| 1894 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1895 | EffectMask = Input { SourceOp = "BarMask", Source = "Mask", }, |
| 1896 | }, |
| 1897 | }, |
| 1898 | Scene = Merge { |
| 1899 | Inputs = { |
| 1900 | Background = Input { SourceOp = "Black", Source = "Output", }, |
| 1901 | Foreground = Input { SourceOp = "WhiteBar", Source = "Output", }, |
| 1902 | }, |
| 1903 | }, |
| 1904 | -- Put vx=20.0, vy=0.0 into aux.vector via CopyAux Mode 1 |
| 1905 | VecVal = Background { |
| 1906 | Inputs = { |
| 1907 | Width = Input { Value = 64, }, |
| 1908 | Height = Input { Value = 64, }, |
| 1909 | Depth = Input { Value = 4, }, |
| 1910 | TopLeftRed = Input { Value = 20.0, }, |
| 1911 | TopLeftGreen = Input { Value = 0.0, }, |
| 1912 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1913 | }, |
| 1914 | }, |
| 1915 | VecAux = Dimension.CopyAux { |
| 1916 | Inputs = { |
| 1917 | Mode = Input { Value = 1, }, |
| 1918 | Channel = Input { Value = FuID { "Vector" }, }, |
| 1919 | Input = Input { SourceOp = "VecVal", Source = "Output", }, |
| 1920 | }, |
| 1921 | }, |
| 1922 | -- Copy Scene RGBA onto VecAux (ChannelBoolean preserves BG's aux.vector when ToZBuffer=4) |
| 1923 | SceneWithAuxVec = ChannelBoolean { |
| 1924 | Inputs = { |
| 1925 | Background = Input { SourceOp = "VecAux", Source = "Output", }, |
| 1926 | Foreground = Input { SourceOp = "Scene", Source = "Output", }, |
| 1927 | ToRed = Input { Value = 0, }, |
| 1928 | ToGreen = Input { Value = 1, }, |
| 1929 | ToBlue = Input { Value = 2, }, |
| 1930 | ToAlpha = Input { Value = 3, }, |
| 1931 | }, |
| 1932 | }, |
| 1933 | VMB = VectorMotionBlur { |
| 1934 | Inputs = { |
| 1935 | Input = Input { SourceOp = "SceneWithAuxVec", Source = "Output", }, |
| 1936 | Scale = Input { Value = 1.0, }, |
| 1937 | }, |
| 1938 | }, |
| 1939 | -- 2. Animated moving textured rectangle -> Dimension.OpticalFlow -> VectorMotionBlur |
| 1940 | MoveMask = RectangleMask { |
| 1941 | Inputs = { |
| 1942 | MaskWidth = Input { Value = 64, }, |
| 1943 | MaskHeight = Input { Value = 64, }, |
| 1944 | Width = Input { Value = 0.35, }, |
| 1945 | Height = Input { Value = 0.35, }, |
| 1946 | Center = Input { Value = { 0.5, 0.5 }, }, |
| 1947 | }, |
| 1948 | }, |
| 1949 | MoveRect = Background { |
| 1950 | Inputs = { |
| 1951 | Width = Input { Value = 64, }, |
| 1952 | Height = Input { Value = 64, }, |
| 1953 | Type = Input { Value = FuID { "Horizontal" }, }, |
| 1954 | TopLeftRed = Input { Value = 0.1, }, |
| 1955 | TopLeftGreen = Input { Value = 0.9, }, |
| 1956 | TopLeftBlue = Input { Value = 0.2, }, |
| 1957 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1958 | TopRightRed = Input { Value = 1.0, }, |
| 1959 | TopRightGreen = Input { Value = 0.1, }, |
| 1960 | TopRightBlue = Input { Value = 0.8, }, |
| 1961 | TopRightAlpha = Input { Value = 1.0, }, |
| 1962 | EffectMask = Input { SourceOp = "MoveMask", Source = "Mask", }, |
| 1963 | }, |
| 1964 | }, |
| 1965 | MoveXf = Merge { |
| 1966 | Inputs = { |
| 1967 | Background = Input { SourceOp = "Black", Source = "Output", }, |
| 1968 | Foreground = Input { SourceOp = "MoveRect", Source = "Output", }, |
| 1969 | Center = Input { |
| 1970 | Value = { 0.5, 0.5 }, |
| 1971 | Expression = "Point(0.4 + time * 0.1, 0.5)", |
| 1972 | }, |
| 1973 | }, |
| 1974 | }, |
| 1975 | OF = Dimension.OpticalFlow { |
| 1976 | Inputs = { Input = Input { SourceOp = "MoveXf", Source = "Output", }, }, |
| 1977 | }, |
| 1978 | OF_VMB = VectorMotionBlur { |
| 1979 | Inputs = { Input = Input { SourceOp = "OF", Source = "Output", }, }, |
| 1980 | }, |
| 1981 | }, |
| 1982 | }"#; |
| 1983 | let comp = Comp::from_fusion_str(src).expect("parse VMB comp"); |
| 1984 | |
| 1985 | // Before blur: pixel at (x=38, y=32) is black (bar spans [30..34]). |
| 1986 | let (sc_tex, _) = eng.evaluate(&comp, comp.find_node("SceneWithAuxVec").unwrap(), 0.0); |
| 1987 | assert!(sc_tex.aux.as_ref().and_then(|a| a.vector.as_ref()).is_some(), "aux.vector must survive ChannelBoolean"); |
| 1988 | let sc_px = eng.readback_rgba(&sc_tex).unwrap(); |
| 1989 | assert_eq!(sc_px[(32 * 64 + 38) * 4], 0, "unblurred pixel at x=38 must be black"); |
| 1990 | |
| 1991 | // After VectorMotionBlur consuming aux.vector (vx=20px -> +-10px): |
| 1992 | // x=38 (6px right of bar center) smears bright, while y=4 (above bar) stays black! |
| 1993 | let (vmb_tex, stats) = eng.evaluate(&comp, comp.find_node("VMB").unwrap(), 0.0); |
| 1994 | assert!(stats.unsupported_nodes.is_empty(), "{:?}", stats.unsupported_nodes); |
| 1995 | let vmb_px = eng.readback_rgba(&vmb_tex).unwrap(); |
| 1996 | let smeared = vmb_px[(32 * 64 + 38) * 4]; |
| 1997 | assert!(smeared > 20, "VectorMotionBlur should smear white bar horizontally to x=38, got {smeared}"); |
| 1998 | assert_eq!(vmb_px[(4 * 64 + 32) * 4], 0, "horizontal vector should not blur vertically into y=4"); |
| 1999 | |
| 2000 | // OpticalFlow attaches both aux.vector and aux.back_vector when VectorMotionBlur is in comp |
| 2001 | let (of_tex, _) = eng.evaluate(&comp, comp.find_node("OF").unwrap(), 1.0); |
| 2002 | let of_aux = of_tex.aux.as_ref().expect("OpticalFlow must attach aux vectors when VMB exists"); |
| 2003 | let fwd = readback_rgba16f(&eng, of_aux.vector.as_ref().expect("aux.vector")); |
| 2004 | let bwd = readback_rgba16f(&eng, of_aux.back_vector.as_ref().expect("aux.back_vector")); |
| 2005 | let c_fwd = fwd[32 * 64 + 32]; |
| 2006 | let c_bwd = bwd[32 * 64 + 32]; |
| 2007 | // Box moves +0.1 * 64 = +6.4 px/frame right -> fwd.x > 0, bwd.x < 0! |
| 2008 | assert!(c_fwd[0] > 2.0, "expected positive forward flow x, got {c_fwd:?}"); |
| 2009 | assert!(c_bwd[0] < -2.0, "expected negative backward flow x, got {c_bwd:?}"); |
| 2010 | } |
| 2011 | |
| 2012 | #[test] |
| 2013 | fn depth_merge_transparent_fg_preserves_bg_z_and_non_over_modes_apply_when_bg_closer() { |
| 2014 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2015 | let src = format!( |
| 2016 | r#"Composition {{ |
| 2017 | CurrentTime = 0, |
| 2018 | RenderRange = {{ 0, 1 }}, |
| 2019 | GlobalRange = {{ 0, 1 }}, |
| 2020 | Tools = ordered() {{ |
| 2021 | {} |
| 2022 | {} |
| 2023 | {} |
| 2024 | Transparent2D = Background {{ |
| 2025 | Inputs = {{ |
| 2026 | Width = Input {{ Value = 16, }}, |
| 2027 | Height = Input {{ Value = 16, }}, |
| 2028 | TopLeftRed = Input {{ Value = 0.0, }}, |
| 2029 | TopLeftGreen = Input {{ Value = 0.0, }}, |
| 2030 | TopLeftBlue = Input {{ Value = 0.0, }}, |
| 2031 | TopLeftAlpha = Input {{ Value = 0.0, }}, |
| 2032 | }}, |
| 2033 | }}, |
| 2034 | -- Transparent 2D FG (no Z -> implicit 0.0) over BG with Z = -5.0 must keep bg_z = -5.0! |
| 2035 | M_Trans2D = Merge {{ |
| 2036 | Inputs = {{ |
| 2037 | Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 2038 | Foreground = Input {{ SourceOp = "Transparent2D", Source = "Output", }}, |
| 2039 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 2040 | }}, |
| 2041 | }}, |
| 2042 | -- Transparent 3D FG (alpha=0, Z = -2.0) over BG with Z = -5.0 must also keep bg_z = -5.0! |
| 2043 | M_Trans3D = Merge {{ |
| 2044 | Inputs = {{ |
| 2045 | Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 2046 | Foreground = Input {{ SourceOp = "TransNear", Source = "Output", }}, |
| 2047 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 2048 | }}, |
| 2049 | }}, |
| 2050 | -- fg_z (-5) < bg_z (-2) with ApplyMode = Screen: Screen(blue, red) -> magenta! |
| 2051 | M_Screen = Merge {{ |
| 2052 | Inputs = {{ |
| 2053 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 2054 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 2055 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 2056 | ApplyMode = Input {{ Value = FuID {{ "Screen" }}, }}, |
| 2057 | }}, |
| 2058 | }}, |
| 2059 | -- fg_z (-5) < bg_z (-2) with ApplyMode = Multiply: Multiply(blue, red) -> black! |
| 2060 | M_Multiply = Merge {{ |
| 2061 | Inputs = {{ |
| 2062 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 2063 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 2064 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 2065 | ApplyMode = Input {{ Value = FuID {{ "Multiply" }}, }}, |
| 2066 | }}, |
| 2067 | }}, |
| 2068 | -- fg_z (-5) < bg_z (-2) with Operator = Under: swaps BG behind FG -> blue! |
| 2069 | M_Under = Merge {{ |
| 2070 | Inputs = {{ |
| 2071 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 2072 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 2073 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 2074 | Operator = Input {{ Value = FuID {{ "Under" }}, }}, |
| 2075 | }}, |
| 2076 | }}, |
| 2077 | -- fg_z (-5) < bg_z (-2) with Operator = Held Out: bg * (1 - fg.a) -> transparent! |
| 2078 | M_HeldOut = Merge {{ |
| 2079 | Inputs = {{ |
| 2080 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 2081 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 2082 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 2083 | Operator = Input {{ Value = FuID {{ "Held Out" }}, }}, |
| 2084 | }}, |
| 2085 | }}, |
| 2086 | }}, |
| 2087 | }}"#, |
| 2088 | z_layer_nodes("BgFar", [0.0, 0.0, 1.0, 1.0], -5.0), |
| 2089 | z_layer_nodes("FgNear", [1.0, 0.0, 0.0, 1.0], -2.0), |
| 2090 | z_layer_nodes("TransNear", [0.0, 0.0, 0.0, 0.0], -2.0), |
| 2091 | ); |
| 2092 | let comp = Comp::from_fusion_str(&src).expect("parse depth merge regression comp"); |
| 2093 | let mut eval_one = |name: &str| -> ([u8; 4], f32) { |
| 2094 | let id = comp.find_node(name).unwrap(); |
| 2095 | let (tex, _) = eng.evaluate(&comp, id, 0.0); |
| 2096 | let px = eng.readback_rgba(&tex).unwrap(); |
| 2097 | let c = px_center(&px, tex.size[0], tex.size[1]); |
| 2098 | let zt = tex.aux.as_ref().unwrap().z.as_ref().unwrap(); |
| 2099 | let zs = readback_r32f(&eng, zt); |
| 2100 | (c, zs[(zt.size[1] / 2 * zt.size[0] + zt.size[0] / 2) as usize]) |
| 2101 | }; |
| 2102 | |
| 2103 | let (c_t2d, z_t2d) = eval_one("M_Trans2D"); |
| 2104 | assert_eq!(c_t2d, [0, 0, 255, 255]); |
| 2105 | assert!((z_t2d - (-5.0)).abs() < 1e-3, "transparent 2D FG must preserve bg_z=-5.0, got {z_t2d}"); |
| 2106 | |
| 2107 | let (c_t3d, z_t3d) = eval_one("M_Trans3D"); |
| 2108 | assert_eq!(c_t3d, [0, 0, 255, 255]); |
| 2109 | assert!((z_t3d - (-5.0)).abs() < 1e-3, "transparent 3D FG must preserve bg_z=-5.0, got {z_t3d}"); |
| 2110 | |
| 2111 | let (c_scr, z_scr) = eval_one("M_Screen"); |
| 2112 | assert_eq!(c_scr, [255, 0, 255, 255], "Screen when fg_z < bg_z must blend red+blue -> magenta"); |
| 2113 | assert!((z_scr - (-2.0)).abs() < 1e-3); |
| 2114 | |
| 2115 | let (c_mul, z_mul) = eval_one("M_Multiply"); |
| 2116 | assert_eq!(c_mul, [0, 0, 0, 255], "Multiply when fg_z < bg_z must yield black"); |
| 2117 | assert!((z_mul - (-2.0)).abs() < 1e-3); |
| 2118 | |
| 2119 | let (c_und, z_und) = eval_one("M_Under"); |
| 2120 | assert_eq!(c_und, [0, 0, 255, 255], "Under when fg_z < bg_z must put BG behind FG -> blue"); |
| 2121 | assert!((z_und - (-2.0)).abs() < 1e-3); |
| 2122 | |
| 2123 | let (c_ho, z_ho) = eval_one("M_HeldOut"); |
| 2124 | assert_eq!(c_ho, [0, 0, 0, 0], "Held Out when fg_z < bg_z with opaque FG must yield transparent"); |
| 2125 | assert!((z_ho - (-2.0)).abs() < 1e-3); |
| 2126 | } |
| 2127 | |
| 2128 | #[test] |
| 2129 | fn copy_aux_mode0_sanitizes_nan_and_inf_pixels() { |
| 2130 | let Ok(eng) = Engine::new_headless() else { return }; |
| 2131 | let z_tex = AuxChannelTex::new(&eng.device, [4, 1], wgpu::TextureFormat::R32Float, "nan-z"); |
| 2132 | let z_vals: [f32; 4] = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -5.0]; |
| 2133 | eng.queue.write_texture( |
| 2134 | z_tex.texture.as_image_copy(), |
| 2135 | bytemuck::cast_slice(&z_vals), |
| 2136 | wgpu::TexelCopyBufferLayout { |
| 2137 | offset: 0, |
| 2138 | bytes_per_row: Some(16), |
| 2139 | rows_per_image: Some(1), |
| 2140 | }, |
| 2141 | wgpu::Extent3d { width: 4, height: 1, depth_or_array_layers: 1 }, |
| 2142 | ); |
| 2143 | let src = eng.alloc_tex([4, 1], BitDepth::Float32, 0); |
| 2144 | let dst_remap = eng.alloc_tex([4, 1], BitDepth::Float32, 0); |
| 2145 | let dst_raw = eng.alloc_tex([4, 1], BitDepth::Float32, 0); |
| 2146 | |
| 2147 | let mut u_remap = UniformParams::default(); |
| 2148 | u_remap.p[0] = [0.0, 1.0, 0.0, 0.0]; // kind=Z, remap_en=1 |
| 2149 | 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) |
| 2150 | u_remap.p[3] = [1.0, 0.0, 0.0, 0.0]; // blend=1 |
| 2151 | |
| 2152 | let mut u_raw = UniformParams::default(); |
| 2153 | u_raw.p[0] = [0.0, 0.0, 0.0, 0.0]; // kind=Z, remap_en=0 |
| 2154 | u_raw.p[3] = [1.0, 0.0, 0.0, 0.0]; // blend=1 |
| 2155 | |
| 2156 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 2157 | eng.aux_pipelines().borrow_mut().dispatch_rgba_op( |
| 2158 | &eng.device, |
| 2159 | &eng.queue, |
| 2160 | &mut enc, |
| 2161 | false, |
| 2162 | &src.view, |
| 2163 | &z_tex.view, |
| 2164 | &eng.dummy.view, |
| 2165 | &dst_remap, |
| 2166 | &u_remap, |
| 2167 | ); |
| 2168 | eng.aux_pipelines().borrow_mut().dispatch_rgba_op( |
| 2169 | &eng.device, |
| 2170 | &eng.queue, |
| 2171 | &mut enc, |
| 2172 | false, |
| 2173 | &src.view, |
| 2174 | &z_tex.view, |
| 2175 | &eng.dummy.view, |
| 2176 | &dst_raw, |
| 2177 | &u_raw, |
| 2178 | ); |
| 2179 | eng.queue.submit(Some(enc.finish())); |
| 2180 | eng.reset_uniform_cursors(); |
| 2181 | |
| 2182 | let remapped = eng.readback_rgba_f32(&dst_remap).expect("readback remapped"); |
| 2183 | for i in 0..3 { |
| 2184 | let v = remapped[i * 4]; |
| 2185 | assert!(v.is_finite(), "pixel {i} remapped must be finite, got {v}"); |
| 2186 | assert!((v - 1.0).abs() < 1e-4, "sanitized 0.0 remapped in [-10..0]->[0..1] should be 1.0, got {v}"); |
| 2187 | } |
| 2188 | assert!((remapped[12] - 0.5).abs() < 1e-4, "valid -5.0 remapped should be 0.5, got {}", remapped[12]); |
| 2189 | |
| 2190 | let raw = eng.readback_rgba_f32(&dst_raw).expect("readback raw"); |
| 2191 | for i in 0..3 { |
| 2192 | 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]); |
| 2193 | } |
| 2194 | assert!((raw[12] - (-5.0)).abs() < 1e-4, "valid -5.0 raw should stay -5.0, got {}", raw[12]); |
| 2195 | } |
| 2196 | |
| 2197 | #[test] |
| 2198 | fn motion_blur_expanded_union_dod_pads_aux_z_with_empty_sentinel() { |
| 2199 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2200 | // BgZ and FgZ are both 16x16; MBMerge animates Center.x across 0.25..0.75 with MotionBlur=1, |
| 2201 | // Quality=3, ShutterAngle=360 so: |
| 2202 | // t=0.5 -> Center.x = 0.375 -> DoD expands left ([-2, 0], 18x16) |
| 2203 | // t=1.0 -> Center.x = 0.500 -> center DoD is ([ 0, 0], 16x16) with Z = -1.0 |
| 2204 | // t=1.5 -> Center.x = 0.625 -> DoD expands right ([ 0, 0], 18x16) |
| 2205 | // Union DoD = ([-2, 0], 20x16); center's 16x16 aux.z must be padded to 20x16 with |
| 2206 | // EMPTY_Z_SENTINEL in the 2px OOB margins on left and right. |
| 2207 | let src = format!( |
| 2208 | r#"Composition {{ |
| 2209 | CurrentTime = 1, |
| 2210 | RenderRange = {{ 0, 2 }}, |
| 2211 | GlobalRange = {{ 0, 2 }}, |
| 2212 | Tools = ordered() {{ |
| 2213 | {} |
| 2214 | {} |
| 2215 | MBMerge = Merge {{ |
| 2216 | Inputs = {{ |
| 2217 | Background = Input {{ SourceOp = "BgZ", Source = "Output", }}, |
| 2218 | Foreground = Input {{ SourceOp = "FgZ", Source = "Output", }}, |
| 2219 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 2220 | MotionBlur = Input {{ Value = 1, }}, |
| 2221 | Quality = Input {{ Value = 3, }}, |
| 2222 | ShutterAngle = Input {{ Value = 360.0, }}, |
| 2223 | Center = Input {{ |
| 2224 | Value = {{ 0.5, 0.5 }}, |
| 2225 | Expression = "Point(0.25 + time * 0.25, 0.5)", |
| 2226 | }}, |
| 2227 | }}, |
| 2228 | }}, |
| 2229 | -- Downstream zoomed-out Transform ensures Merge does not clip its expanded DoD to canvas! |
| 2230 | ZoomOut = Transform {{ |
| 2231 | Inputs = {{ |
| 2232 | Input = Input {{ SourceOp = "MBMerge", Source = "Output", }}, |
| 2233 | Size = Input {{ Value = 0.5, }}, |
| 2234 | }}, |
| 2235 | }}, |
| 2236 | }}, |
| 2237 | }}"#, |
| 2238 | z_layer_nodes("BgZ", [0.0, 0.0, 1.0, 1.0], -5.0), |
| 2239 | z_layer_nodes("FgZ", [1.0, 0.0, 0.0, 1.0], -1.0), |
| 2240 | ); |
| 2241 | let comp = Comp::from_fusion_str(&src).expect("parse MB DoD aux comp"); |
| 2242 | let id = comp.find_node("MBMerge").unwrap(); |
| 2243 | |
| 2244 | let mut visiting = eng.prepare_frame_scratch(&comp); |
| 2245 | let mut stats = EvalStats::default(); |
| 2246 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 2247 | let out = eng.eval_node(&comp, id, 1.0, &mut enc, &mut visiting, &mut stats); |
| 2248 | eng.queue.submit(Some(enc.finish())); |
| 2249 | eng.reset_uniform_cursors(); |
| 2250 | eng.finish_frame_scratch(visiting); |
| 2251 | |
| 2252 | assert!(out.size[0] > 16 && out.origin[0] < 0, "expected expanded union DoD, got origin={:?} size={:?}", out.origin, out.size); |
| 2253 | let aux_z = out |
| 2254 | .aux |
| 2255 | .as_ref() |
| 2256 | .expect("MotionBlur output must carry padded aux") |
| 2257 | .z |
| 2258 | .as_ref() |
| 2259 | .expect("MotionBlur output must carry padded aux.z"); |
| 2260 | assert_eq!(aux_z.size, out.size, "padded aux.z size must match out.size"); |
| 2261 | |
| 2262 | let zs = readback_r32f(&eng, aux_z); |
| 2263 | let w = out.size[0] as usize; |
| 2264 | let row = (out.size[1] / 2) as usize; |
| 2265 | let left_oob = zs[row * w]; |
| 2266 | let right_oob = zs[row * w + (w - 1)]; |
| 2267 | let center_z = zs[row * w + (w / 2)]; |
| 2268 | assert_eq!(left_oob, EMPTY_Z_SENTINEL, "left OOB Z must be EMPTY_Z_SENTINEL, got {left_oob}"); |
| 2269 | assert_eq!(right_oob, EMPTY_Z_SENTINEL, "right OOB Z must be EMPTY_Z_SENTINEL, got {right_oob}"); |
| 2270 | assert!((center_z - (-1.0)).abs() < 1e-3, "center Z must preserve -1.0, got {center_z}"); |
| 2271 | } |
| 2272 | } |