| ... | ... | @@ -0,0 +1,1982 @@ |
| 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 n.kind == "VectorMotionBlur" { |
| 643 | return true; |
| 644 | } |
| 645 | if n.kind == "Dimension.CopyAux" { |
| 646 | let ch = CopyAuxChannel::from_str(n.static_str("Channel").unwrap_or("Z")); |
| 647 | if matches!(ch, CopyAuxChannel::Vector | CopyAuxChannel::BackVector) { |
| 648 | return true; |
| 649 | } |
| 650 | } |
| 651 | false |
| 652 | }) |
| 653 | } |
| 654 | |
| 655 | impl Engine { |
| 656 | pub(super) fn aux_pipelines(&self) -> &RefCell<AuxPipelines> { |
| 657 | self.aux_pipelines |
| 658 | .get_or_init(|| RefCell::new(AuxPipelines::new(&self.device, &self.queue))) |
| 659 | } |
| 660 | |
| 661 | /// Dispatches depth-aware `Merge` (`PerformDepthMerge = 0` or `1`) when at least one of |
| 662 | /// `bg` or `fg` carries `aux.z`. Attaches `out.aux.z` whenever `bg` carried `aux.z`. |
| 663 | #[allow(clippy::too_many_arguments)] |
| 664 | pub(super) fn dispatch_depth_merge( |
| 665 | &self, |
| 666 | enc: &mut wgpu::CommandEncoder, |
| 667 | bg: &CachedTexture, |
| 668 | fg: &CachedTexture, |
| 669 | mask_view: &wgpu::TextureView, |
| 670 | dst: &mut CachedTexture, |
| 671 | params: &UniformParams, |
| 672 | ) { |
| 673 | let bg_z = bg.aux.as_ref().and_then(|a| a.z.as_ref()); |
| 674 | let fg_z = fg.aux.as_ref().and_then(|a| a.z.as_ref()); |
| 675 | let dst_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "merge-z"); |
| 676 | self.aux_pipelines().borrow_mut().dispatch_depth_merge( |
| 677 | &self.device, |
| 678 | &self.queue, |
| 679 | enc, |
| 680 | &bg.view, |
| 681 | &fg.view, |
| 682 | bg_z.map(|t| t.view.as_ref()), |
| 683 | fg_z.map(|t| t.view.as_ref()), |
| 684 | mask_view, |
| 685 | dst, |
| 686 | &dst_z, |
| 687 | params, |
| 688 | ); |
| 689 | if bg_z.is_some() { |
| 690 | let mut out_aux = bg.aux_cloned(); |
| 691 | out_aux.z = Some(dst_z); |
| 692 | dst.set_aux(Some(Arc::new(out_aux))); |
| 693 | } else if bg.aux.is_some() { |
| 694 | // Preserve any non-Z aux channels on BG, keeping Z = None matching Snow Globe! |
| 695 | dst.set_aux(bg.aux.clone()); |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | /// Crops `src.aux` channels from `src.origin` / `src.size` to `src.canvas_size`. |
| 700 | pub(super) fn crop_aux_to_canvas( |
| 701 | &self, |
| 702 | enc: &mut wgpu::CommandEncoder, |
| 703 | src: &CachedTexture, |
| 704 | dst: &mut CachedTexture, |
| 705 | ) { |
| 706 | let Some(src_aux) = src.aux.as_ref() else { |
| 707 | return; |
| 708 | }; |
| 709 | let mut out_aux = AuxChannels::default(); |
| 710 | let mut u = UniformParams::default(); |
| 711 | u.p[0] = [ |
| 712 | src.origin[0] as f32, |
| 713 | src.origin[1] as f32, |
| 714 | src.canvas_size[0] as f32, |
| 715 | src.canvas_size[1] as f32, |
| 716 | ]; |
| 717 | let mut ap = self.aux_pipelines().borrow_mut(); |
| 718 | if let Some(z) = src_aux.z.as_ref() { |
| 719 | let cropped_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "crop-z"); |
| 720 | ap.dispatch_r32f_op( |
| 721 | &self.device, |
| 722 | &self.queue, |
| 723 | enc, |
| 724 | 2, |
| 725 | &self.dummy.view, |
| 726 | &self.dummy.view, |
| 727 | Some(&z.view), |
| 728 | None, |
| 729 | &self.dummy.view, |
| 730 | &cropped_z, |
| 731 | &u, |
| 732 | ); |
| 733 | out_aux.z = Some(cropped_z); |
| 734 | } |
| 735 | let mut crop_f16 = |ap: &mut AuxPipelines, tex: &AuxChannelTex, label: &str| { |
| 736 | let cropped = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::Rgba16Float, label); |
| 737 | ap.dispatch_f16_op( |
| 738 | &self.device, |
| 739 | &self.queue, |
| 740 | enc, |
| 741 | 1, |
| 742 | &tex.view, |
| 743 | None, |
| 744 | None, |
| 745 | &cropped, |
| 746 | &u, |
| 747 | ); |
| 748 | cropped |
| 749 | }; |
| 750 | if let Some(n) = src_aux.normal.as_ref() { |
| 751 | out_aux.normal = Some(crop_f16(&mut ap, n, "crop-normal")); |
| 752 | } |
| 753 | if let Some(v) = src_aux.vector.as_ref() { |
| 754 | out_aux.vector = Some(crop_f16(&mut ap, v, "crop-vector")); |
| 755 | } |
| 756 | if let Some(bv) = src_aux.back_vector.as_ref() { |
| 757 | out_aux.back_vector = Some(crop_f16(&mut ap, bv, "crop-back-vector")); |
| 758 | } |
| 759 | dst.set_aux(Some(Arc::new(out_aux))); |
| 760 | } |
| 761 | |
| 762 | /// Evaluates `Dimension.CopyAux` (Mode 0: Aux -> Color with Remap; Mode 1: Color -> Aux). |
| 763 | #[allow(clippy::too_many_arguments)] |
| 764 | pub(super) fn eval_copy_aux( |
| 765 | &mut self, |
| 766 | comp: &Comp, |
| 767 | node: &Node, |
| 768 | time: f64, |
| 769 | frame_i: i64, |
| 770 | enc: &mut wgpu::CommandEncoder, |
| 771 | visiting: &mut HashSet<(NodeId, i64)>, |
| 772 | stats: &mut EvalStats, |
| 773 | ) -> CachedTexture { |
| 774 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 775 | return self.dummy.clone(); |
| 776 | }; |
| 777 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 778 | let mode = comp.eval_number(node, "Mode", time, 0.0, &self.expr).round() as i32; |
| 779 | let channel = CopyAuxChannel::from_str(node.static_str("Channel").unwrap_or("Z")); |
| 780 | let kill_aux = comp.eval_number(node, "KillAuxChannels", time, 0.0, &self.expr) >= 0.5; |
| 781 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 782 | let mbm = self.multiplies_by_mask(comp, node, time); |
| 783 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); |
| 784 | |
| 785 | // Early passthrough when blend == 0 (or channel == Color) |
| 786 | if (blend <= 1e-6 && !(mbm && has_mask)) || channel == CopyAuxChannel::Color { |
| 787 | if kill_aux && src.aux.is_some() { |
| 788 | let key = self.make_key(node, "CopyAuxKill", src.size, &[src.content_hash], &[1.0]); |
| 789 | let mut out = src.clone(); |
| 790 | out.content_hash = key; |
| 791 | out.set_aux(None); |
| 792 | return out; |
| 793 | } |
| 794 | return src; |
| 795 | } |
| 796 | |
| 797 | if mode == 1 { |
| 798 | // Mode 1: Color To Aux (passes RGBA through and writes selected aux channel) |
| 799 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; |
| 800 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 801 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 802 | let key = self.make_key( |
| 803 | node, |
| 804 | "CopyAuxColorToAux", |
| 805 | src.size, |
| 806 | &[src.content_hash, mask_hash], |
| 807 | &[ |
| 808 | channel.shader_kind(), |
| 809 | if kill_aux { 1.0 } else { 0.0 }, |
| 810 | blend, |
| 811 | if mask_inv { 1.0 } else { 0.0 }, |
| 812 | ], |
| 813 | ); |
| 814 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 815 | stats.cache_hits += 1; |
| 816 | return hit; |
| 817 | } |
| 818 | stats.cache_misses += 1; |
| 819 | stats.nodes_evaluated += 1; |
| 820 | |
| 821 | let mut out = src.clone(); |
| 822 | out.content_hash = key; |
| 823 | let mut out_aux = if kill_aux { |
| 824 | AuxChannels::default() |
| 825 | } else { |
| 826 | src.aux_cloned() |
| 827 | }; |
| 828 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 829 | let has_m_f = if mask.is_some() { 1.0 } else { 0.0 }; |
| 830 | let inv_f = if mask_inv { 1.0 } else { 0.0 }; |
| 831 | |
| 832 | match channel { |
| 833 | CopyAuxChannel::Z => { |
| 834 | let dst_z = AuxChannelTex::new(&self.device, src.size, wgpu::TextureFormat::R32Float, "copy-aux-z"); |
| 835 | let existing_z = out_aux.z.as_ref(); |
| 836 | let mut u = UniformParams::default(); |
| 837 | u.p[0] = [blend, has_m_f, inv_f, if existing_z.is_some() { 1.0 } else { 0.0 }]; |
| 838 | self.aux_pipelines().borrow_mut().dispatch_r32f_op( |
| 839 | &self.device, |
| 840 | &self.queue, |
| 841 | enc, |
| 842 | 0, |
| 843 | &src.view, |
| 844 | &self.dummy.view, |
| 845 | existing_z.map(|t| t.view.as_ref()), |
| 846 | None, |
| 847 | mv, |
| 848 | &dst_z, |
| 849 | &u, |
| 850 | ); |
| 851 | out_aux.z = Some(dst_z); |
| 852 | } |
| 853 | CopyAuxChannel::Normal | CopyAuxChannel::Vector | CopyAuxChannel::BackVector => { |
| 854 | let label = match channel { |
| 855 | CopyAuxChannel::Normal => "copy-aux-normal", |
| 856 | CopyAuxChannel::Vector => "copy-aux-vector", |
| 857 | _ => "copy-aux-back-vector", |
| 858 | }; |
| 859 | let dst_f16 = AuxChannelTex::new(&self.device, src.size, wgpu::TextureFormat::Rgba16Float, label); |
| 860 | let existing = match channel { |
| 861 | CopyAuxChannel::Normal => out_aux.normal.as_ref(), |
| 862 | CopyAuxChannel::Vector => out_aux.vector.as_ref(), |
| 863 | _ => out_aux.back_vector.as_ref(), |
| 864 | }; |
| 865 | let mut u = UniformParams::default(); |
| 866 | u.p[0] = [channel.shader_kind(), blend, has_m_f, inv_f]; |
| 867 | u.p[1] = [if existing.is_some() { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; |
| 868 | self.aux_pipelines().borrow_mut().dispatch_f16_op( |
| 869 | &self.device, |
| 870 | &self.queue, |
| 871 | enc, |
| 872 | 0, |
| 873 | &src.view, |
| 874 | existing.map(|t| t.view.as_ref()), |
| 875 | Some(mv), |
| 876 | &dst_f16, |
| 877 | &u, |
| 878 | ); |
| 879 | match channel { |
| 880 | CopyAuxChannel::Normal => out_aux.normal = Some(dst_f16), |
| 881 | CopyAuxChannel::Vector => out_aux.vector = Some(dst_f16), |
| 882 | _ => out_aux.back_vector = Some(dst_f16), |
| 883 | } |
| 884 | } |
| 885 | CopyAuxChannel::Color => {} |
| 886 | } |
| 887 | out.set_aux(Some(Arc::new(out_aux))); |
| 888 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 889 | return out; |
| 890 | } |
| 891 | |
| 892 | // Mode 0: Aux To Color |
| 893 | let src_has_sel = src.aux.as_ref().is_some_and(|a| match channel { |
| 894 | CopyAuxChannel::Z => a.z.is_some(), |
| 895 | CopyAuxChannel::Normal => a.normal.is_some(), |
| 896 | CopyAuxChannel::Vector => a.vector.is_some(), |
| 897 | CopyAuxChannel::BackVector => a.back_vector.is_some(), |
| 898 | CopyAuxChannel::Color => false, |
| 899 | }); |
| 900 | if !src_has_sel { |
| 901 | if kill_aux && src.aux.is_some() { |
| 902 | let key = self.make_key(node, "CopyAuxKillMissing", src.size, &[src.content_hash], &[1.0]); |
| 903 | let mut out = src.clone(); |
| 904 | out.content_hash = key; |
| 905 | out.set_aux(None); |
| 906 | return out; |
| 907 | } |
| 908 | return src; |
| 909 | } |
| 910 | |
| 911 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; |
| 912 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 913 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 914 | |
| 915 | let pfx = channel.remap_prefix(); |
| 916 | let remap_en = comp.eval_number(node, &format!("{pfx}.Remap.Enable"), time, 0.0, &self.expr) >= 0.5; |
| 917 | let fmin = comp.eval_number(node, &format!("{pfx}.Remap.From.Min"), time, 0.0, &self.expr); |
| 918 | let fmax = comp.eval_number(node, &format!("{pfx}.Remap.From.Max"), time, 1.0, &self.expr); |
| 919 | let tmin = comp.eval_number(node, &format!("{pfx}.Remap.To.Min"), time, 0.0, &self.expr); |
| 920 | let tmax = comp.eval_number(node, &format!("{pfx}.Remap.To.Max"), time, 1.0, &self.expr); |
| 921 | let inv_base = comp.eval_number(node, &format!("{pfx}.Remap.To.Invert"), time, 0.0, &self.expr); |
| 922 | |
| 923 | let (fmin_x, fmax_x, fmin_y, fmax_y, tmin_x, tmax_x, tmin_y, tmax_y, inv_x, inv_y) = |
| 924 | if matches!(channel, CopyAuxChannel::Vector | CopyAuxChannel::BackVector) { |
| 925 | ( |
| 926 | comp.eval_number(node, &format!("{pfx}.Remap.From.MinX"), time, fmin, &self.expr) as f32, |
| 927 | comp.eval_number(node, &format!("{pfx}.Remap.From.MaxX"), time, fmax, &self.expr) as f32, |
| 928 | comp.eval_number(node, &format!("{pfx}.Remap.From.MinY"), time, fmin, &self.expr) as f32, |
| 929 | comp.eval_number(node, &format!("{pfx}.Remap.From.MaxY"), time, fmax, &self.expr) as f32, |
| 930 | comp.eval_number(node, &format!("{pfx}.Remap.To.MinX"), time, tmin, &self.expr) as f32, |
| 931 | comp.eval_number(node, &format!("{pfx}.Remap.To.MaxX"), time, tmax, &self.expr) as f32, |
| 932 | comp.eval_number(node, &format!("{pfx}.Remap.To.MinY"), time, tmin, &self.expr) as f32, |
| 933 | comp.eval_number(node, &format!("{pfx}.Remap.To.MaxY"), time, tmax, &self.expr) as f32, |
| 934 | comp.eval_number(node, &format!("{pfx}.Remap.To.InvertX"), time, inv_base, &self.expr) as f32, |
| 935 | comp.eval_number(node, &format!("{pfx}.Remap.To.InvertY"), time, inv_base, &self.expr) as f32, |
| 936 | ) |
| 937 | } else { |
| 938 | ( |
| 939 | fmin as f32, |
| 940 | fmax as f32, |
| 941 | fmin as f32, |
| 942 | fmax as f32, |
| 943 | tmin as f32, |
| 944 | tmax as f32, |
| 945 | tmin as f32, |
| 946 | tmax as f32, |
| 947 | inv_base as f32, |
| 948 | inv_base as f32, |
| 949 | ) |
| 950 | }; |
| 951 | |
| 952 | let dst_depth = self.node_depth(comp, node, time, Some(src.depth)); |
| 953 | let mut u = UniformParams::default(); |
| 954 | u.p[0] = [ |
| 955 | channel.shader_kind(), |
| 956 | if remap_en { 1.0 } else { 0.0 }, |
| 957 | if inv_x >= 0.5 { 1.0 } else { 0.0 }, |
| 958 | if inv_y >= 0.5 { 1.0 } else { 0.0 }, |
| 959 | ]; |
| 960 | u.p[1] = [fmin_x, fmax_x, tmin_x, tmax_x]; |
| 961 | u.p[2] = [fmin_y, fmax_y, tmin_y, tmax_y]; |
| 962 | u.p[3] = [ |
| 963 | blend, |
| 964 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 965 | if mask_inv { 1.0 } else { 0.0 }, |
| 966 | if mbm { 1.0 } else { 0.0 }, |
| 967 | ]; |
| 968 | |
| 969 | let key = self.make_key( |
| 970 | node, |
| 971 | "CopyAuxToColor", |
| 972 | src.size, |
| 973 | &[src.content_hash, mask_hash, dst_depth as u64, kill_aux as u64], |
| 974 | bytemuck::cast_slice(&u.p[..4]), |
| 975 | ); |
| 976 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 977 | stats.cache_hits += 1; |
| 978 | return hit; |
| 979 | } |
| 980 | stats.cache_misses += 1; |
| 981 | stats.nodes_evaluated += 1; |
| 982 | |
| 983 | let aux_view = { |
| 984 | let a = src.aux.as_ref().expect("checked src_has_sel"); |
| 985 | match channel { |
| 986 | CopyAuxChannel::Z => a.z.as_ref().expect("z").view.clone(), |
| 987 | CopyAuxChannel::Normal => a.normal.as_ref().expect("normal").view.clone(), |
| 988 | CopyAuxChannel::Vector => a.vector.as_ref().expect("vector").view.clone(), |
| 989 | CopyAuxChannel::BackVector => a.back_vector.as_ref().expect("back_vector").view.clone(), |
| 990 | CopyAuxChannel::Color => unreachable!(), |
| 991 | } |
| 992 | }; |
| 993 | let mut dst = self.alloc_tex_like(&src, dst_depth, key); |
| 994 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 995 | self.aux_pipelines().borrow_mut().dispatch_rgba_op( |
| 996 | &self.device, |
| 997 | &self.queue, |
| 998 | enc, |
| 999 | false, |
| 1000 | &src.view, |
| 1001 | &aux_view, |
| 1002 | mv, |
| 1003 | &dst, |
| 1004 | &u, |
| 1005 | ); |
| 1006 | if !kill_aux { |
| 1007 | dst.set_aux(src.aux.clone()); |
| 1008 | } |
| 1009 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1010 | dst |
| 1011 | } |
| 1012 | |
| 1013 | /// Computes `ChannelBoolean`'s `ToZBuffer` extra channel and attaches it to `dst.aux.z`. |
| 1014 | #[allow(clippy::too_many_arguments)] |
| 1015 | pub(super) fn apply_channel_boolean_z( |
| 1016 | &self, |
| 1017 | enc: &mut wgpu::CommandEncoder, |
| 1018 | bg: &CachedTexture, |
| 1019 | fg: &CachedTexture, |
| 1020 | mask: Option<&CachedTexture>, |
| 1021 | mask_inv: bool, |
| 1022 | op: i32, |
| 1023 | to_z: i32, |
| 1024 | blend: f32, |
| 1025 | expand_canvas: bool, |
| 1026 | dst: &mut CachedTexture, |
| 1027 | ) { |
| 1028 | let bg_z = bg.aux.as_ref().and_then(|a| a.z.as_ref()); |
| 1029 | let fg_z = fg.aux.as_ref().and_then(|a| a.z.as_ref()); |
| 1030 | |
| 1031 | // If copying FG Z when FG has no Z, or BG Z when BG has no Z, preserve bg.aux without fabricating Z. |
| 1032 | if to_z == 18 && fg_z.is_none() { |
| 1033 | if bg.aux.is_some() && dst.size == bg.size { |
| 1034 | dst.set_aux(bg.aux.clone()); |
| 1035 | } |
| 1036 | return; |
| 1037 | } |
| 1038 | if to_z == 19 && bg_z.is_none() { |
| 1039 | if bg.aux.is_some() && dst.size == bg.size { |
| 1040 | dst.set_aux(bg.aux.clone()); |
| 1041 | } |
| 1042 | return; |
| 1043 | } |
| 1044 | |
| 1045 | // Zero-copy fast path: Op=Copy, ToZBuffer=18 (FG Z), full blend, unmasked, matching extents. |
| 1046 | if op == 0 |
| 1047 | && to_z == 18 |
| 1048 | && blend >= 0.9999 |
| 1049 | && mask.is_none() |
| 1050 | && !expand_canvas |
| 1051 | && !bg.has_dod() |
| 1052 | && !fg.has_dod() |
| 1053 | && let Some(fz) = fg_z |
| 1054 | && fz.size == dst.size |
| 1055 | { |
| 1056 | let mut out_aux = if dst.size == bg.size { bg.aux_cloned() } else { AuxChannels::default() }; |
| 1057 | out_aux.z = Some(fz.clone()); |
| 1058 | dst.set_aux(Some(Arc::new(out_aux))); |
| 1059 | return; |
| 1060 | } |
| 1061 | |
| 1062 | let dst_z = AuxChannelTex::new(&self.device, dst.size, wgpu::TextureFormat::R32Float, "cb-zbuffer"); |
| 1063 | let mut u = UniformParams::default(); |
| 1064 | u.p[0] = [op as f32, to_z as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }]; |
| 1065 | u.p[1] = [ |
| 1066 | if mask_inv { 1.0 } else { 0.0 }, |
| 1067 | if bg_z.is_some() { 1.0 } else { 0.0 }, |
| 1068 | if fg_z.is_some() { 1.0 } else { 0.0 }, |
| 1069 | if expand_canvas { 1.0 } else { 0.0 }, |
| 1070 | ]; |
| 1071 | if fg.has_dod() { |
| 1072 | 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]; |
| 1073 | } |
| 1074 | if bg.has_dod() { |
| 1075 | 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]; |
| 1076 | } |
| 1077 | let mv = mask.map_or(&self.dummy.view, |m| &m.view); |
| 1078 | self.aux_pipelines().borrow_mut().dispatch_r32f_op( |
| 1079 | &self.device, |
| 1080 | &self.queue, |
| 1081 | enc, |
| 1082 | 1, |
| 1083 | &bg.view, |
| 1084 | &fg.view, |
| 1085 | bg_z.map(|t| t.view.as_ref()), |
| 1086 | fg_z.map(|t| t.view.as_ref()), |
| 1087 | mv, |
| 1088 | &dst_z, |
| 1089 | &u, |
| 1090 | ); |
| 1091 | let mut out_aux = if dst.size == bg.size { bg.aux_cloned() } else { AuxChannels::default() }; |
| 1092 | out_aux.z = Some(dst_z); |
| 1093 | dst.set_aux(Some(Arc::new(out_aux))); |
| 1094 | } |
| 1095 | |
| 1096 | /// Dispatches `VectorMotionBlur` compute pass using `vec_view` (either `src.aux.vector` |
| 1097 | /// or an external `VectorInput` texture). |
| 1098 | #[allow(clippy::too_many_arguments)] |
| 1099 | pub(super) fn dispatch_vector_motion_blur( |
| 1100 | &self, |
| 1101 | enc: &mut wgpu::CommandEncoder, |
| 1102 | src: &CachedTexture, |
| 1103 | vec_view: &wgpu::TextureView, |
| 1104 | mask_view: &wgpu::TextureView, |
| 1105 | dst: &CachedTexture, |
| 1106 | params: &UniformParams, |
| 1107 | ) { |
| 1108 | self.aux_pipelines().borrow_mut().dispatch_rgba_op( |
| 1109 | &self.device, |
| 1110 | &self.queue, |
| 1111 | enc, |
| 1112 | true, |
| 1113 | &src.view, |
| 1114 | vec_view, |
| 1115 | mask_view, |
| 1116 | dst, |
| 1117 | params, |
| 1118 | ); |
| 1119 | } |
| 1120 | |
| 1121 | /// Computes a dense motion vector texture (`Rgba16Float`, Fusion pixel units `+X` right, `+Y` up) |
| 1122 | /// from `frame_src` to `frame_dst`. |
| 1123 | fn compute_optflow_vector_tex( |
| 1124 | &self, |
| 1125 | enc: &mut wgpu::CommandEncoder, |
| 1126 | frame_src: &CachedTexture, |
| 1127 | frame_dst: &CachedTexture, |
| 1128 | label: &str, |
| 1129 | ) -> AuxChannelTex { |
| 1130 | let size = frame_src.size; |
| 1131 | let out = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, label); |
| 1132 | let mut ap = self.aux_pipelines().borrow_mut(); |
| 1133 | |
| 1134 | // Identical static frames -> zero flow in a single trivial fill. |
| 1135 | if frame_src.content_hash != 0 && frame_src.content_hash == frame_dst.content_hash { |
| 1136 | let mut u = UniformParams::default(); |
| 1137 | u.p[0] = [3.0, 1.0, 0.0, 0.0]; // kind 3 = ZeroFill |
| 1138 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 0, &frame_src.view, None, None, &out, &u); |
| 1139 | return out; |
| 1140 | } |
| 1141 | |
| 1142 | let coarse_size = [size[0].div_ceil(4).max(1), size[1].div_ceil(4).max(1)]; |
| 1143 | let feat_a = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, "of-fa"); |
| 1144 | let feat_b = AuxChannelTex::new(&self.device, size, wgpu::TextureFormat::Rgba16Float, "of-fb"); |
| 1145 | let feat_ac = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fac"); |
| 1146 | let feat_bc = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fbc"); |
| 1147 | let flow_c = AuxChannelTex::new(&self.device, coarse_size, wgpu::TextureFormat::Rgba16Float, "of-fc"); |
| 1148 | |
| 1149 | let u0 = UniformParams::default(); |
| 1150 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_src.view, None, None, &feat_a, &u0); |
| 1151 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_dst.view, None, None, &feat_b, &u0); |
| 1152 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_src.view, None, None, &feat_ac, &u0); |
| 1153 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 2, &frame_dst.view, None, None, &feat_bc, &u0); |
| 1154 | ap.dispatch_f16_op(&self.device, &self.queue, enc, 3, &feat_ac.view, Some(&feat_bc.view), None, &flow_c, &u0); |
| 1155 | |
| 1156 | let mut ur = UniformParams::default(); |
| 1157 | ur.p[0] = [ |
| 1158 | size[0] as f32 / coarse_size[0] as f32, |
| 1159 | size[1] as f32 / coarse_size[1] as f32, |
| 1160 | 1.0, // convert texture +Y-down to Fusion +Y-up |
| 1161 | 0.0, |
| 1162 | ]; |
| 1163 | ap.dispatch_f16_op( |
| 1164 | &self.device, |
| 1165 | &self.queue, |
| 1166 | enc, |
| 1167 | 4, |
| 1168 | &feat_a.view, |
| 1169 | Some(&feat_b.view), |
| 1170 | Some(&flow_c.view), |
| 1171 | &out, |
| 1172 | &ur, |
| 1173 | ); |
| 1174 | out |
| 1175 | } |
| 1176 | |
| 1177 | /// Evaluates `Dimension.OpticalFlow` / `OpticalFlow`: passes RGBA through unchanged, |
| 1178 | /// and attaches forward (`t -> t+1`) + backward (`t -> t-1`) motion vectors as |
| 1179 | /// `aux.vector` / `aux.back_vector` ONLY when a downstream consumer uses motion vectors. |
| 1180 | #[allow(clippy::too_many_arguments)] |
| 1181 | pub(super) fn eval_optical_flow( |
| 1182 | &mut self, |
| 1183 | comp: &Comp, |
| 1184 | node: &Node, |
| 1185 | time: f64, |
| 1186 | frame_i: i64, |
| 1187 | enc: &mut wgpu::CommandEncoder, |
| 1188 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1189 | stats: &mut EvalStats, |
| 1190 | ) -> CachedTexture { |
| 1191 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 1192 | return self.dummy.clone(); |
| 1193 | }; |
| 1194 | let curr = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 1195 | if !time.is_finite() || !comp_uses_optical_flow_vectors(comp) { |
| 1196 | return curr; |
| 1197 | } |
| 1198 | let next = self.eval_node(comp, src_id, time + 1.0, enc, visiting, stats); |
| 1199 | let prev = self.eval_node(comp, src_id, time - 1.0, enc, visiting, stats); |
| 1200 | let curr_c = self.crop_to_canvas(enc, curr.clone()); |
| 1201 | let next_c = self.crop_to_canvas(enc, next); |
| 1202 | let prev_c = self.crop_to_canvas(enc, prev); |
| 1203 | |
| 1204 | let key = self.make_key( |
| 1205 | node, |
| 1206 | "OpticalFlowAux", |
| 1207 | curr_c.size, |
| 1208 | &[curr_c.content_hash, next_c.content_hash, prev_c.content_hash], |
| 1209 | &[], |
| 1210 | ); |
| 1211 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1212 | stats.cache_hits += 1; |
| 1213 | return hit; |
| 1214 | } |
| 1215 | stats.cache_misses += 1; |
| 1216 | stats.nodes_evaluated += 1; |
| 1217 | |
| 1218 | let fwd = self.compute_optflow_vector_tex(enc, &curr_c, &next_c, "optflow-fwd-vec"); |
| 1219 | let bwd = self.compute_optflow_vector_tex(enc, &curr_c, &prev_c, "optflow-bwd-vec"); |
| 1220 | |
| 1221 | let mut out = curr_c; |
| 1222 | out.content_hash = key; |
| 1223 | let mut aux = out.aux_cloned(); |
| 1224 | aux.vector = Some(fwd); |
| 1225 | aux.back_vector = Some(bwd); |
| 1226 | out.set_aux(Some(Arc::new(aux))); |
| 1227 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 1228 | out |
| 1229 | } |
| 1230 | } |
| 1231 | |
| 1232 | #[cfg(test)] |
| 1233 | mod tests { |
| 1234 | use super::*; |
| 1235 | |
| 1236 | fn readback_r32f(eng: &Engine, tex: &AuxChannelTex) -> Vec<f32> { |
| 1237 | let [w, h] = tex.size; |
| 1238 | assert_eq!(tex.format, wgpu::TextureFormat::R32Float); |
| 1239 | let unpadded_bpr = w * 4; |
| 1240 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 1241 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 1242 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { |
| 1243 | label: Some("readback-r32f"), |
| 1244 | size: u64::from(padded_bpr) * u64::from(h), |
| 1245 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 1246 | mapped_at_creation: false, |
| 1247 | }); |
| 1248 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 1249 | enc.copy_texture_to_buffer( |
| 1250 | tex.texture.as_image_copy(), |
| 1251 | wgpu::TexelCopyBufferInfo { |
| 1252 | buffer: &buf, |
| 1253 | layout: wgpu::TexelCopyBufferLayout { |
| 1254 | offset: 0, |
| 1255 | bytes_per_row: Some(padded_bpr), |
| 1256 | rows_per_image: Some(h), |
| 1257 | }, |
| 1258 | }, |
| 1259 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 1260 | ); |
| 1261 | eng.queue.submit(Some(enc.finish())); |
| 1262 | let slice = buf.slice(..); |
| 1263 | let (tx, rx) = std::sync::mpsc::channel(); |
| 1264 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 1265 | let _ = tx.send(res); |
| 1266 | }); |
| 1267 | eng.device |
| 1268 | .poll(wgpu::PollType::Wait { |
| 1269 | submission_index: None, |
| 1270 | timeout: Some(std::time::Duration::from_secs(10)), |
| 1271 | }) |
| 1272 | .unwrap(); |
| 1273 | rx.recv().unwrap().unwrap(); |
| 1274 | let data = slice.get_mapped_range().unwrap(); |
| 1275 | let mut out = Vec::with_capacity((w * h) as usize); |
| 1276 | for y in 0..h as usize { |
| 1277 | let row = &data[y * padded_bpr as usize..y * padded_bpr as usize + unpadded_bpr as usize]; |
| 1278 | for ch in row.chunks_exact(4) { |
| 1279 | out.push(f32::from_le_bytes([ch[0], ch[1], ch[2], ch[3]])); |
| 1280 | } |
| 1281 | } |
| 1282 | drop(data); |
| 1283 | buf.unmap(); |
| 1284 | out |
| 1285 | } |
| 1286 | |
| 1287 | fn f16_to_f32(bits: u16) -> f32 { |
| 1288 | let sign = ((bits & 0x8000) as u32) << 16; |
| 1289 | let exp = (bits >> 10) & 0x1F; |
| 1290 | let frac = (bits & 0x03FF) as u32; |
| 1291 | if exp == 0 { |
| 1292 | if frac == 0 { |
| 1293 | f32::from_bits(sign) |
| 1294 | } else { |
| 1295 | let mut f = frac; |
| 1296 | let mut e = -14i32; |
| 1297 | while (f & 0x0400) == 0 { |
| 1298 | f <<= 1; |
| 1299 | e -= 1; |
| 1300 | } |
| 1301 | let f_norm = f & 0x03FF; |
| 1302 | let e_f32 = ((e + 127) as u32) << 23; |
| 1303 | f32::from_bits(sign | e_f32 | (f_norm << 13)) |
| 1304 | } |
| 1305 | } else if exp == 0x1F { |
| 1306 | f32::from_bits(sign | 0x7F80_0000 | (frac << 13)) |
| 1307 | } else { |
| 1308 | let e_f32 = ((exp as u32) + 112) << 23; |
| 1309 | f32::from_bits(sign | e_f32 | (frac << 13)) |
| 1310 | } |
| 1311 | } |
| 1312 | |
| 1313 | fn readback_rgba16f(eng: &Engine, tex: &AuxChannelTex) -> Vec<[f32; 4]> { |
| 1314 | let [w, h] = tex.size; |
| 1315 | assert_eq!(tex.format, wgpu::TextureFormat::Rgba16Float); |
| 1316 | let unpadded_bpr = w * 8; |
| 1317 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 1318 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 1319 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { |
| 1320 | label: Some("readback-aux-f16"), |
| 1321 | size: u64::from(padded_bpr) * u64::from(h), |
| 1322 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 1323 | mapped_at_creation: false, |
| 1324 | }); |
| 1325 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 1326 | enc.copy_texture_to_buffer( |
| 1327 | tex.texture.as_image_copy(), |
| 1328 | wgpu::TexelCopyBufferInfo { |
| 1329 | buffer: &buf, |
| 1330 | layout: wgpu::TexelCopyBufferLayout { |
| 1331 | offset: 0, |
| 1332 | bytes_per_row: Some(padded_bpr), |
| 1333 | rows_per_image: Some(h), |
| 1334 | }, |
| 1335 | }, |
| 1336 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 1337 | ); |
| 1338 | eng.queue.submit(Some(enc.finish())); |
| 1339 | let slice = buf.slice(..); |
| 1340 | let (tx, rx) = std::sync::mpsc::channel(); |
| 1341 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 1342 | let _ = tx.send(res); |
| 1343 | }); |
| 1344 | eng.device |
| 1345 | .poll(wgpu::PollType::Wait { |
| 1346 | submission_index: None, |
| 1347 | timeout: Some(std::time::Duration::from_secs(10)), |
| 1348 | }) |
| 1349 | .unwrap(); |
| 1350 | rx.recv().unwrap().unwrap(); |
| 1351 | let data = slice.get_mapped_range().unwrap(); |
| 1352 | let mut out = Vec::with_capacity((w * h) as usize); |
| 1353 | for y in 0..h as usize { |
| 1354 | let row = &data[y * padded_bpr as usize..y * padded_bpr as usize + unpadded_bpr as usize]; |
| 1355 | for ch in row.chunks_exact(8) { |
| 1356 | out.push([ |
| 1357 | f16_to_f32(u16::from_le_bytes([ch[0], ch[1]])), |
| 1358 | f16_to_f32(u16::from_le_bytes([ch[2], ch[3]])), |
| 1359 | f16_to_f32(u16::from_le_bytes([ch[4], ch[5]])), |
| 1360 | f16_to_f32(u16::from_le_bytes([ch[6], ch[7]])), |
| 1361 | ]); |
| 1362 | } |
| 1363 | } |
| 1364 | drop(data); |
| 1365 | buf.unmap(); |
| 1366 | out |
| 1367 | } |
| 1368 | |
| 1369 | fn px_center(px: &[u8], w: u32, h: u32) -> [u8; 4] { |
| 1370 | let i = (((h / 2) * w + (w / 2)) * 4) as usize; |
| 1371 | [px[i], px[i + 1], px[i + 2], px[i + 3]] |
| 1372 | } |
| 1373 | |
| 1374 | /// Helper snippet building a 16x16 float32 image with RGBA `(r,g,b,a)` and `aux.z = z_val` |
| 1375 | /// via `CopyAux` Mode 1 + `ChannelBoolean` `ToZBuffer = 18`. |
| 1376 | fn z_layer_nodes(prefix: &str, rgba: [f32; 4], z_val: f32) -> String { |
| 1377 | format!( |
| 1378 | r#" |
| 1379 | {prefix}Col = Background {{ |
| 1380 | Inputs = {{ |
| 1381 | Width = Input {{ Value = 16, }}, |
| 1382 | Height = Input {{ Value = 16, }}, |
| 1383 | Depth = Input {{ Value = 4, }}, |
| 1384 | TopLeftRed = Input {{ Value = {r}, }}, |
| 1385 | TopLeftGreen = Input {{ Value = {g}, }}, |
| 1386 | TopLeftBlue = Input {{ Value = {b}, }}, |
| 1387 | TopLeftAlpha = Input {{ Value = {a}, }}, |
| 1388 | }}, |
| 1389 | }}, |
| 1390 | {prefix}ZSrc = Background {{ |
| 1391 | Inputs = {{ |
| 1392 | Width = Input {{ Value = 16, }}, |
| 1393 | Height = Input {{ Value = 16, }}, |
| 1394 | Depth = Input {{ Value = 4, }}, |
| 1395 | TopLeftRed = Input {{ Value = {z}, }}, |
| 1396 | TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 1397 | }}, |
| 1398 | }}, |
| 1399 | {prefix}ZAux = Dimension.CopyAux {{ |
| 1400 | Inputs = {{ |
| 1401 | Mode = Input {{ Value = 1, }}, |
| 1402 | Channel = Input {{ Value = FuID {{ "Z" }}, }}, |
| 1403 | Input = Input {{ SourceOp = "{prefix}ZSrc", Source = "Output", }}, |
| 1404 | }}, |
| 1405 | }}, |
| 1406 | {prefix} = ChannelBoolean {{ |
| 1407 | Inputs = {{ |
| 1408 | ToRed = Input {{ Value = 5, }}, |
| 1409 | ToGreen = Input {{ Value = 6, }}, |
| 1410 | ToBlue = Input {{ Value = 7, }}, |
| 1411 | ToAlpha = Input {{ Value = 8, }}, |
| 1412 | EnableExtraChannels = Input {{ Value = 1, }}, |
| 1413 | ToZBuffer = Input {{ Value = 18, }}, |
| 1414 | Background = Input {{ SourceOp = "{prefix}Col", Source = "Output", }}, |
| 1415 | Foreground = Input {{ SourceOp = "{prefix}ZAux", Source = "Output", }}, |
| 1416 | }}, |
| 1417 | }},"#, |
| 1418 | r = rgba[0], |
| 1419 | g = rgba[1], |
| 1420 | b = rgba[2], |
| 1421 | a = rgba[3], |
| 1422 | z = z_val, |
| 1423 | ) |
| 1424 | } |
| 1425 | |
| 1426 | #[test] |
| 1427 | fn merge_perform_depth_merge_all_snow_globe_cases() { |
| 1428 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1429 | let src = format!( |
| 1430 | r#"Composition {{ |
| 1431 | CurrentTime = 0, |
| 1432 | RenderRange = {{ 0, 1 }}, |
| 1433 | GlobalRange = {{ 0, 1 }}, |
| 1434 | Tools = ordered() {{ |
| 1435 | {} |
| 1436 | {} |
| 1437 | {} |
| 1438 | {} |
| 1439 | Plain2DRed = Background {{ |
| 1440 | Inputs = {{ |
| 1441 | Width = Input {{ Value = 16, }}, |
| 1442 | Height = Input {{ Value = 16, }}, |
| 1443 | Depth = Input {{ Value = 4, }}, |
| 1444 | TopLeftRed = Input {{ Value = 1.0, }}, |
| 1445 | TopLeftGreen = Input {{ Value = 0.0, }}, |
| 1446 | TopLeftBlue = Input {{ Value = 0.0, }}, |
| 1447 | TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 1448 | }}, |
| 1449 | }}, |
| 1450 | Plain2DGreen = Background {{ |
| 1451 | Inputs = {{ |
| 1452 | Width = Input {{ Value = 16, }}, |
| 1453 | Height = Input {{ Value = 16, }}, |
| 1454 | Depth = Input {{ Value = 4, }}, |
| 1455 | TopLeftRed = Input {{ Value = 0.0, }}, |
| 1456 | TopLeftGreen = Input {{ Value = 1.0, }}, |
| 1457 | TopLeftBlue = Input {{ Value = 0.0, }}, |
| 1458 | TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 1459 | }}, |
| 1460 | }}, |
| 1461 | -- 1. Opaque FG near (-2) over BG far (-5): FG wins, Z = -2 |
| 1462 | M1_FgNear = Merge {{ |
| 1463 | Inputs = {{ |
| 1464 | Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1465 | Foreground = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 1466 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1467 | }}, |
| 1468 | }}, |
| 1469 | -- 2. Opaque FG far (-5) over BG near (-2): BG wins completely, Z = -2 |
| 1470 | M2_FgFar = Merge {{ |
| 1471 | Inputs = {{ |
| 1472 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 1473 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1474 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1475 | }}, |
| 1476 | }}, |
| 1477 | -- 3. Semi-transparent FG near (-2, a=0.5) over opaque BG far (-5): FG blends over BG, Z = -2 |
| 1478 | M3_SemiFgNear = Merge {{ |
| 1479 | Inputs = {{ |
| 1480 | Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1481 | Foreground = Input {{ SourceOp = "SemiNear", Source = "Output", }}, |
| 1482 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1483 | }}, |
| 1484 | }}, |
| 1485 | -- 4. Opaque FG far (-5) over semi-transparent BG near (-2, a=0.5): BG blends OVER FG, Z = -2 |
| 1486 | M4_FgFarOverSemiBgNear = Merge {{ |
| 1487 | Inputs = {{ |
| 1488 | Background = Input {{ SourceOp = "SemiNear", Source = "Output", }}, |
| 1489 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1490 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1491 | }}, |
| 1492 | }}, |
| 1493 | -- 5. 2D FG (no Z, implicit 0.0) over Z BG (-5): FG wins, output Z = 0.0! |
| 1494 | M5_2dFgOverZBg = Merge {{ |
| 1495 | Inputs = {{ |
| 1496 | Background = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1497 | Foreground = Input {{ SourceOp = "Plain2DGreen", Source = "Output", }}, |
| 1498 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1499 | }}, |
| 1500 | }}, |
| 1501 | -- 6. Z FG (-5) over 2D BG (no Z, implicit 0.0): BG wins (0.0 > -5.0), output Z = None! |
| 1502 | M6_ZFgOver2dBg = Merge {{ |
| 1503 | Inputs = {{ |
| 1504 | Background = Input {{ SourceOp = "Plain2DRed", Source = "Output", }}, |
| 1505 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1506 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1507 | }}, |
| 1508 | }}, |
| 1509 | -- 7. PerformDepthMerge = 0: FG far (-5) composited OVER BG near (-2) normally, Z = -5! |
| 1510 | M7_NoDepthMerge = Merge {{ |
| 1511 | Inputs = {{ |
| 1512 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 1513 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1514 | PerformDepthMerge = Input {{ Value = 0, }}, |
| 1515 | }}, |
| 1516 | }}, |
| 1517 | -- 8. ForegroundZOffset shifts FG far (-5) by +4 -> -1 (> BG -2), so FG wins! |
| 1518 | M8_ZOffset = Merge {{ |
| 1519 | Inputs = {{ |
| 1520 | Background = Input {{ SourceOp = "FgNear", Source = "Output", }}, |
| 1521 | Foreground = Input {{ SourceOp = "BgFar", Source = "Output", }}, |
| 1522 | PerformDepthMerge = Input {{ Value = 1, }}, |
| 1523 | ForegroundZOffset = Input {{ Value = 4.0, }}, |
| 1524 | }}, |
| 1525 | }}, |
| 1526 | }}, |
| 1527 | }}"#, |
| 1528 | // BgFar: opaque blue (0, 0, 1, 1) at Z = -5.0 |
| 1529 | z_layer_nodes("BgFar", [0.0, 0.0, 1.0, 1.0], -5.0), |
| 1530 | // FgNear: opaque red (1, 0, 0, 1) at Z = -2.0 |
| 1531 | z_layer_nodes("FgNear", [1.0, 0.0, 0.0, 1.0], -2.0), |
| 1532 | // SemiNear: semi-transparent premultiplied green (0, 0.5, 0, 0.5) at Z = -2.0 |
| 1533 | z_layer_nodes("SemiNear", [0.0, 0.5, 0.0, 0.5], -2.0), |
| 1534 | // Unused helper just for variety |
| 1535 | z_layer_nodes("UnusedExtra", [0.2, 0.3, 0.4, 1.0], -8.0), |
| 1536 | ); |
| 1537 | |
| 1538 | let comp = Comp::from_fusion_str(&src).expect("parse depth merge comp"); |
| 1539 | let mut eval_one = |name: &str| -> ([u8; 4], Option<f32>) { |
| 1540 | let id = comp.find_node(name).unwrap(); |
| 1541 | let (tex, stats) = eng.evaluate(&comp, id, 0.0); |
| 1542 | assert!(stats.unsupported_nodes.is_empty(), "{name}: {:?}", stats.unsupported_nodes); |
| 1543 | let px = eng.readback_rgba(&tex).unwrap(); |
| 1544 | let c = px_center(&px, tex.size[0], tex.size[1]); |
| 1545 | let z = tex.aux.as_ref().and_then(|a| a.z.as_ref()).map(|zt| { |
| 1546 | let zs = readback_r32f(&eng, zt); |
| 1547 | zs[(zt.size[1] / 2 * zt.size[0] + zt.size[0] / 2) as usize] |
| 1548 | }); |
| 1549 | (c, z) |
| 1550 | }; |
| 1551 | |
| 1552 | // 1. Opaque FG near (red, -2) over BG far (blue, -5) -> red, Z = -2 |
| 1553 | let (c1, z1) = eval_one("M1_FgNear"); |
| 1554 | assert_eq!(c1, [255, 0, 0, 255], "M1_FgNear color"); |
| 1555 | assert!((z1.unwrap() - (-2.0)).abs() < 1e-3, "M1_FgNear z={z1:?}"); |
| 1556 | |
| 1557 | // 2. Opaque FG far (blue, -5) over BG near (red, -2) -> red (BG wins!), Z = -2 |
| 1558 | let (c2, z2) = eval_one("M2_FgFar"); |
| 1559 | assert_eq!(c2, [255, 0, 0, 255], "M2_FgFar color (BG must occlude far FG)"); |
| 1560 | assert!((z2.unwrap() - (-2.0)).abs() < 1e-3, "M2_FgFar z={z2:?}"); |
| 1561 | |
| 1562 | // 3. Semi-transparent FG near (0, 0.5, 0, 0.5 @ -2) over opaque BG far (0, 0, 1, 1 @ -5) |
| 1563 | // -> (0, 0.5, 0.5, 1.0) = [0, 128, 128, 255], Z = -2 |
| 1564 | let (c3, z3) = eval_one("M3_SemiFgNear"); |
| 1565 | assert_eq!(c3[0], 0); |
| 1566 | assert!((c3[1] as i32 - 128).abs() <= 2, "M3 G={c3:?}"); |
| 1567 | assert!((c3[2] as i32 - 128).abs() <= 2, "M3 B={c3:?}"); |
| 1568 | assert_eq!(c3[3], 255); |
| 1569 | assert!((z3.unwrap() - (-2.0)).abs() < 1e-3, "M3 z={z3:?}"); |
| 1570 | |
| 1571 | // 4. Opaque FG far (0, 0, 1, 1 @ -5) over semi-transparent BG near (0, 0.5, 0, 0.5 @ -2) |
| 1572 | // -> BG over FG = (0, 0.5, 0.5, 1.0) = [0, 128, 128, 255], Z = -2! |
| 1573 | let (c4, z4) = eval_one("M4_FgFarOverSemiBgNear"); |
| 1574 | assert_eq!(c4[0], 0); |
| 1575 | assert!((c4[1] as i32 - 128).abs() <= 2, "M4 G={c4:?}"); |
| 1576 | assert!((c4[2] as i32 - 128).abs() <= 2, "M4 B={c4:?}"); |
| 1577 | assert_eq!(c4[3], 255); |
| 1578 | assert!((z4.unwrap() - (-2.0)).abs() < 1e-3, "M4 z={z4:?}"); |
| 1579 | |
| 1580 | // 5. 2D FG (green, no Z -> implicit 0.0) over Z BG (blue, -5) -> green, Z = 0.0! |
| 1581 | let (c5, z5) = eval_one("M5_2dFgOverZBg"); |
| 1582 | assert_eq!(c5, [0, 255, 0, 255], "M5 2D FG must beat -5 BG"); |
| 1583 | assert!((z5.unwrap() - 0.0).abs() < 1e-3, "M5 z={z5:?}"); |
| 1584 | |
| 1585 | // 6. Z FG (blue, -5) over 2D BG (red, no Z -> implicit 0.0) -> red (BG wins!), Z = None! |
| 1586 | let (c6, z6) = eval_one("M6_ZFgOver2dBg"); |
| 1587 | assert_eq!(c6, [255, 0, 0, 255], "M6 2D BG at 0.0 must occlude -5 FG"); |
| 1588 | assert!(z6.is_none(), "M6 output Z must be None when BG had no Z, got {z6:?}"); |
| 1589 | |
| 1590 | // 7. PerformDepthMerge = 0: FG far (blue, -5) wins over BG near (red, -2), Z = -5! |
| 1591 | let (c7, z7) = eval_one("M7_NoDepthMerge"); |
| 1592 | assert_eq!(c7, [0, 0, 255, 255], "M7 PerformDepthMerge=0 must composite FG over BG"); |
| 1593 | assert!((z7.unwrap() - (-5.0)).abs() < 1e-3, "M7 z={z7:?}"); |
| 1594 | |
| 1595 | // 8. ForegroundZOffset = +4.0 shifts FG (-5 + 4 = -1 > -2) in front of BG -> blue, Z = -1! |
| 1596 | let (c8, z8) = eval_one("M8_ZOffset"); |
| 1597 | assert_eq!(c8, [0, 0, 255, 255], "M8 ZOffset must bring FG in front of BG"); |
| 1598 | assert!((z8.unwrap() - (-1.0)).abs() < 1e-3, "M8 z={z8:?}"); |
| 1599 | } |
| 1600 | |
| 1601 | #[test] |
| 1602 | fn copy_aux_modes_remap_channels_and_kill_aux() { |
| 1603 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1604 | let src = r#"Composition { |
| 1605 | CurrentTime = 0, |
| 1606 | RenderRange = { 0, 1 }, |
| 1607 | GlobalRange = { 0, 1 }, |
| 1608 | Tools = ordered() { |
| 1609 | ZData = Background { |
| 1610 | Inputs = { |
| 1611 | Width = Input { Value = 16, }, |
| 1612 | Height = Input { Value = 16, }, |
| 1613 | Depth = Input { Value = 4, }, |
| 1614 | TopLeftRed = Input { Value = -5.0, }, |
| 1615 | TopLeftGreen = Input { Value = 0.25, }, |
| 1616 | TopLeftBlue = Input { Value = 0.75, }, |
| 1617 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1618 | }, |
| 1619 | }, |
| 1620 | -- Mode 1: Color -> Z (preserves RGBA + sets aux.z = -5.0) |
| 1621 | WriteZ = Dimension.CopyAux { |
| 1622 | Inputs = { |
| 1623 | Mode = Input { Value = 1, }, |
| 1624 | Channel = Input { Value = FuID { "Z" }, }, |
| 1625 | Input = Input { SourceOp = "ZData", Source = "Output", }, |
| 1626 | }, |
| 1627 | }, |
| 1628 | -- Mode 0: Z -> Color with Remap -10..0 -> 0..1 (-5.0 -> 0.5 -> ~128) |
| 1629 | ReadZRemap = Dimension.CopyAux { |
| 1630 | Inputs = { |
| 1631 | Mode = Input { Value = 0, }, |
| 1632 | Channel = Input { Value = FuID { "Z" }, }, |
| 1633 | ["Z.Remap.Enable"] = Input { Value = 1, }, |
| 1634 | ["Z.Remap.From.Min"] = Input { Value = -10.0, }, |
| 1635 | ["Z.Remap.From.Max"] = Input { Value = 0.0, }, |
| 1636 | ["Z.Remap.To.Min"] = Input { Value = 0.0, }, |
| 1637 | ["Z.Remap.To.Max"] = Input { Value = 1.0, }, |
| 1638 | Input = Input { SourceOp = "WriteZ", Source = "Output", }, |
| 1639 | }, |
| 1640 | }, |
| 1641 | -- Mode 0: Z -> Color with Remap + Invert + KillAuxChannels = 1 |
| 1642 | ReadZInvertKill = Dimension.CopyAux { |
| 1643 | Inputs = { |
| 1644 | Mode = Input { Value = 0, }, |
| 1645 | Channel = Input { Value = FuID { "Z" }, }, |
| 1646 | KillAuxChannels = Input { Value = 1, }, |
| 1647 | ["Z.Remap.Enable"] = Input { Value = 1, }, |
| 1648 | ["Z.Remap.From.Min"] = Input { Value = -10.0, }, |
| 1649 | ["Z.Remap.From.Max"] = Input { Value = 0.0, }, |
| 1650 | ["Z.Remap.To.Min"] = Input { Value = 0.0, }, |
| 1651 | ["Z.Remap.To.Max"] = Input { Value = 1.0, }, |
| 1652 | ["Z.Remap.To.Invert"] = Input { Value = 1, }, |
| 1653 | Input = Input { SourceOp = "WriteZ", Source = "Output", }, |
| 1654 | }, |
| 1655 | }, |
| 1656 | -- Mode 1 -> Mode 0 for Normal |
| 1657 | NormSrc = Background { |
| 1658 | Inputs = { |
| 1659 | Width = Input { Value = 16, }, |
| 1660 | Height = Input { Value = 16, }, |
| 1661 | Depth = Input { Value = 4, }, |
| 1662 | TopLeftRed = Input { Value = 0.2, }, |
| 1663 | TopLeftGreen = Input { Value = 0.6, }, |
| 1664 | TopLeftBlue = Input { Value = 0.8, }, |
| 1665 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1666 | }, |
| 1667 | }, |
| 1668 | WriteNorm = Dimension.CopyAux { |
| 1669 | Inputs = { |
| 1670 | Mode = Input { Value = 1, }, |
| 1671 | Channel = Input { Value = FuID { "Normal" }, }, |
| 1672 | Input = Input { SourceOp = "NormSrc", Source = "Output", }, |
| 1673 | }, |
| 1674 | }, |
| 1675 | ReadNorm = Dimension.CopyAux { |
| 1676 | Inputs = { |
| 1677 | Mode = Input { Value = 0, }, |
| 1678 | Channel = Input { Value = FuID { "Normal" }, }, |
| 1679 | Input = Input { SourceOp = "WriteNorm", Source = "Output", }, |
| 1680 | }, |
| 1681 | }, |
| 1682 | -- Mode 1 -> Mode 0 for Vector with MinX/MaxX/MinY/MaxY remap |
| 1683 | VecSrc = Background { |
| 1684 | Inputs = { |
| 1685 | Width = Input { Value = 16, }, |
| 1686 | Height = Input { Value = 16, }, |
| 1687 | Depth = Input { Value = 4, }, |
| 1688 | TopLeftRed = Input { Value = 4.0, }, |
| 1689 | TopLeftGreen = Input { Value = -2.0, }, |
| 1690 | TopLeftBlue = Input { Value = 0.9, }, |
| 1691 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1692 | }, |
| 1693 | }, |
| 1694 | WriteVec = Dimension.CopyAux { |
| 1695 | Inputs = { |
| 1696 | Mode = Input { Value = 1, }, |
| 1697 | Channel = Input { Value = FuID { "Vector" }, }, |
| 1698 | Input = Input { SourceOp = "VecSrc", Source = "Output", }, |
| 1699 | }, |
| 1700 | }, |
| 1701 | ReadVec = Dimension.CopyAux { |
| 1702 | Inputs = { |
| 1703 | Mode = Input { Value = 0, }, |
| 1704 | Channel = Input { Value = FuID { "Vector" }, }, |
| 1705 | ["Vector.Remap.Enable"] = Input { Value = 1, }, |
| 1706 | ["Vector.Remap.From.MinX"] = Input { Value = 0.0, }, |
| 1707 | ["Vector.Remap.From.MaxX"] = Input { Value = 8.0, }, |
| 1708 | ["Vector.Remap.From.MinY"] = Input { Value = -4.0, }, |
| 1709 | ["Vector.Remap.From.MaxY"] = Input { Value = 4.0, }, |
| 1710 | ["Vector.Remap.To.Min"] = Input { Value = 0.0, }, |
| 1711 | ["Vector.Remap.To.Max"] = Input { Value = 1.0, }, |
| 1712 | Input = Input { SourceOp = "WriteVec", Source = "Output", }, |
| 1713 | }, |
| 1714 | }, |
| 1715 | }, |
| 1716 | }"#; |
| 1717 | let comp = Comp::from_fusion_str(src).expect("parse CopyAux comp"); |
| 1718 | |
| 1719 | // Mode 1: WriteZ preserves RGBA (G=0.25~64, B=0.75~191) AND sets aux.z = -5.0 |
| 1720 | let (wz, _) = eng.evaluate(&comp, comp.find_node("WriteZ").unwrap(), 0.0); |
| 1721 | let wz_px = px_center(&eng.readback_rgba(&wz).unwrap(), wz.size[0], wz.size[1]); |
| 1722 | assert!((wz_px[1] as i32 - 64).abs() <= 2 && (wz_px[2] as i32 - 191).abs() <= 2, "WriteZ RGBA={wz_px:?}"); |
| 1723 | let wz_z = readback_r32f(&eng, wz.aux.as_ref().unwrap().z.as_ref().unwrap()); |
| 1724 | assert!((wz_z[8 * 16 + 8] - (-5.0)).abs() < 1e-3, "WriteZ aux.z={}", wz_z[8 * 16 + 8]); |
| 1725 | |
| 1726 | // Mode 0: ReadZRemap maps -5 in [-10..0] -> 0.5 (~128) and preserves aux.z |
| 1727 | let (rz, _) = eng.evaluate(&comp, comp.find_node("ReadZRemap").unwrap(), 0.0); |
| 1728 | let rz_px = px_center(&eng.readback_rgba(&rz).unwrap(), rz.size[0], rz.size[1]); |
| 1729 | 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:?}"); |
| 1730 | assert!(rz.aux.as_ref().and_then(|a| a.z.as_ref()).is_some(), "Mode 0 preserves aux when KillAuxChannels=0"); |
| 1731 | |
| 1732 | // Mode 0 + KillAuxChannels = 1 clears aux! |
| 1733 | let (rzk, _) = eng.evaluate(&comp, comp.find_node("ReadZInvertKill").unwrap(), 0.0); |
| 1734 | assert!(rzk.aux.is_none(), "KillAuxChannels=1 must clear aux"); |
| 1735 | |
| 1736 | // Normal roundtrip: (0.2, 0.6, 0.8) -> ~(51, 153, 204, 255) |
| 1737 | let (rn, _) = eng.evaluate(&comp, comp.find_node("ReadNorm").unwrap(), 0.0); |
| 1738 | let rn_px = px_center(&eng.readback_rgba(&rn).unwrap(), rn.size[0], rn.size[1]); |
| 1739 | 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:?}"); |
| 1740 | |
| 1741 | // Vector remap: vx=4 in [0..8] -> 0.5 (~128), vy=-2 in [-4..4] -> 0.25 (~64), b=0, a=1 |
| 1742 | let (rv, _) = eng.evaluate(&comp, comp.find_node("ReadVec").unwrap(), 0.0); |
| 1743 | let rv_px = px_center(&eng.readback_rgba(&rv).unwrap(), rv.size[0], rv.size[1]); |
| 1744 | 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:?}"); |
| 1745 | } |
| 1746 | |
| 1747 | #[test] |
| 1748 | fn channel_boolean_to_zbuffer_and_color_op_aux_propagation() { |
| 1749 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1750 | let src = format!( |
| 1751 | r#"Composition {{ |
| 1752 | CurrentTime = 0, |
| 1753 | RenderRange = {{ 0, 1 }}, |
| 1754 | GlobalRange = {{ 0, 1 }}, |
| 1755 | Tools = ordered() {{ |
| 1756 | {} |
| 1757 | PlainBg = Background {{ |
| 1758 | Inputs = {{ |
| 1759 | Width = Input {{ Value = 16, }}, |
| 1760 | Height = Input {{ Value = 16, }}, |
| 1761 | Depth = Input {{ Value = 3, }}, |
| 1762 | TopLeftRed = Input {{ Value = 0.3, }}, |
| 1763 | TopLeftGreen = Input {{ Value = 0.6, }}, |
| 1764 | TopLeftBlue = Input {{ Value = 0.9, }}, |
| 1765 | TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 1766 | }}, |
| 1767 | }}, |
| 1768 | -- Copy FG's aux.z (-3.5) onto PlainBg while keeping PlainBg's RGBA |
| 1769 | CbCopyZ = ChannelBoolean {{ |
| 1770 | Inputs = {{ |
| 1771 | ToRed = Input {{ Value = 5, }}, |
| 1772 | ToGreen = Input {{ Value = 6, }}, |
| 1773 | ToBlue = Input {{ Value = 7, }}, |
| 1774 | ToAlpha = Input {{ Value = 8, }}, |
| 1775 | EnableExtraChannels = Input {{ Value = 1, }}, |
| 1776 | ToZBuffer = Input {{ Value = 18, }}, |
| 1777 | Background = Input {{ SourceOp = "PlainBg", Source = "Output", }}, |
| 1778 | Foreground = Input {{ SourceOp = "ZLayer", Source = "Output", }}, |
| 1779 | }}, |
| 1780 | }}, |
| 1781 | -- Chain every single-input color/depth op to verify aux.z propagation! |
| 1782 | N_CC = ColorCorrector {{ Inputs = {{ MasterRGBGain = Input {{ Value = 1.1, }}, Input = Input {{ SourceOp = "CbCopyZ", Source = "Output", }}, }}, }}, |
| 1783 | N_BC = BrightnessContrast {{ Inputs = {{ Gain = Input {{ Value = 0.95, }}, Input = Input {{ SourceOp = "N_CC", Source = "Output", }}, }}, }}, |
| 1784 | N_CG = ColorGain {{ Inputs = {{ GainRed = Input {{ Value = 1.05, }}, Input = Input {{ SourceOp = "N_BC", Source = "Output", }}, }}, }}, |
| 1785 | N_GC = GamutConvert {{ Inputs = {{ SourceSpace = Input {{ Value = FuID {{ "sRGB" }}, }}, OutputSpace = Input {{ Value = FuID {{ "NoChange" }}, }}, Input = Input {{ SourceOp = "N_CG", Source = "Output", }}, }}, }}, |
| 1786 | N_CD = ChangeDepth {{ Inputs = {{ Depth = Input {{ Value = 4, }}, Input = Input {{ SourceOp = "N_GC", Source = "Output", }}, }}, }}, |
| 1787 | N_INV = InvertColor {{ Inputs = {{ Input = Input {{ SourceOp = "N_CD", Source = "Output", }}, }}, }}, |
| 1788 | N_CRV = ColorCurves {{ Inputs = {{ Input = Input {{ SourceOp = "N_INV", Source = "Output", }}, }}, }}, |
| 1789 | N_HUE = HueCurves {{ Inputs = {{ Input = Input {{ SourceOp = "N_CRV", Source = "Output", }}, }}, }}, |
| 1790 | -- ChannelBoolean ToZBuffer = 0 (FG R -> Z) and 16 (White -> 1.0) |
| 1791 | CbFgRToZ = ChannelBoolean {{ |
| 1792 | Inputs = {{ |
| 1793 | ToRed = Input {{ Value = 5, }}, |
| 1794 | ToGreen = Input {{ Value = 6, }}, |
| 1795 | ToBlue = Input {{ Value = 7, }}, |
| 1796 | ToAlpha = Input {{ Value = 8, }}, |
| 1797 | EnableExtraChannels = Input {{ Value = 1, }}, |
| 1798 | ToZBuffer = Input {{ Value = 0, }}, |
| 1799 | Background = Input {{ SourceOp = "PlainBg", Source = "Output", }}, |
| 1800 | Foreground = Input {{ SourceOp = "PlainBg", Source = "Output", }}, |
| 1801 | }}, |
| 1802 | }}, |
| 1803 | CbWhiteZ = ChannelBoolean {{ |
| 1804 | Inputs = {{ |
| 1805 | ToRed = Input {{ Value = 4, }}, |
| 1806 | ToGreen = Input {{ Value = 4, }}, |
| 1807 | ToBlue = Input {{ Value = 4, }}, |
| 1808 | ToAlpha = Input {{ Value = 4, }}, |
| 1809 | EnableExtraChannels = Input {{ Value = 1, }}, |
| 1810 | ToZBuffer = Input {{ Value = 16, }}, |
| 1811 | Background = Input {{ SourceOp = "PlainBg", Source = "Output", }}, |
| 1812 | }}, |
| 1813 | }}, |
| 1814 | }}, |
| 1815 | }}"#, |
| 1816 | z_layer_nodes("ZLayer", [1.0, 0.0, 0.0, 1.0], -3.5), |
| 1817 | ); |
| 1818 | let comp = Comp::from_fusion_str(&src).expect("parse CB + propagation comp"); |
| 1819 | |
| 1820 | // Verify CbCopyZ kept PlainBg RGBA (0.3, 0.6, 0.9) and got aux.z = -3.5 |
| 1821 | let (cb_tex, _) = eng.evaluate(&comp, comp.find_node("CbCopyZ").unwrap(), 0.0); |
| 1822 | let cb_px = px_center(&eng.readback_rgba(&cb_tex).unwrap(), 16, 16); |
| 1823 | assert!((cb_px[0] as i32 - 77).abs() <= 2 && (cb_px[2] as i32 - 230).abs() <= 2, "CbCopyZ RGBA={cb_px:?}"); |
| 1824 | let cb_z = readback_r32f(&eng, cb_tex.aux.as_ref().unwrap().z.as_ref().unwrap()); |
| 1825 | assert!((cb_z[8 * 16 + 8] - (-3.5)).abs() < 1e-3); |
| 1826 | |
| 1827 | // Verify aux.z survived all 8 color/depth ops! |
| 1828 | let (end_tex, _) = eng.evaluate(&comp, comp.find_node("N_HUE").unwrap(), 0.0); |
| 1829 | let end_z = readback_r32f(&eng, end_tex.aux.as_ref().expect("aux survived 8 color ops").z.as_ref().unwrap()); |
| 1830 | assert!((end_z[8 * 16 + 8] - (-3.5)).abs() < 1e-3, "aux.z after 8 ops = {}", end_z[8 * 16 + 8]); |
| 1831 | |
| 1832 | // Verify ToZBuffer = 0 (FG R = 0.3) and ToZBuffer = 16 (White = 1.0) |
| 1833 | let (r_tex, _) = eng.evaluate(&comp, comp.find_node("CbFgRToZ").unwrap(), 0.0); |
| 1834 | let r_z = readback_r32f(&eng, r_tex.aux.as_ref().unwrap().z.as_ref().unwrap()); |
| 1835 | assert!((r_z[8 * 16 + 8] - 0.3).abs() < 0.01, "ToZBuffer=0 got {}", r_z[8 * 16 + 8]); |
| 1836 | |
| 1837 | let (w_tex, _) = eng.evaluate(&comp, comp.find_node("CbWhiteZ").unwrap(), 0.0); |
| 1838 | let w_z = readback_r32f(&eng, w_tex.aux.as_ref().unwrap().z.as_ref().unwrap()); |
| 1839 | assert!((w_z[8 * 16 + 8] - 1.0).abs() < 1e-3, "ToZBuffer=16 got {}", w_z[8 * 16 + 8]); |
| 1840 | } |
| 1841 | |
| 1842 | #[test] |
| 1843 | fn vector_motion_blur_consumes_aux_vector_and_optical_flow() { |
| 1844 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1845 | // 1. Sharp vertical white bar on black with synthetic aux.vector = (16.0, 0.0) |
| 1846 | // -> VectorMotionBlur smears horizontally into adjacent columns! |
| 1847 | let src = r#"Composition { |
| 1848 | CurrentTime = 0, |
| 1849 | RenderRange = { 0, 5 }, |
| 1850 | GlobalRange = { 0, 5 }, |
| 1851 | Tools = ordered() { |
| 1852 | Black = Background { |
| 1853 | Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftAlpha = Input { Value = 1.0, }, }, |
| 1854 | }, |
| 1855 | BarMask = RectangleMask { |
| 1856 | Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.0625, }, Height = Input { Value = 0.75, }, }, |
| 1857 | }, |
| 1858 | WhiteBar = Background { |
| 1859 | Inputs = { |
| 1860 | Width = Input { Value = 64, }, |
| 1861 | Height = Input { Value = 64, }, |
| 1862 | TopLeftRed = Input { Value = 1.0, }, |
| 1863 | TopLeftGreen = Input { Value = 1.0, }, |
| 1864 | TopLeftBlue = Input { Value = 1.0, }, |
| 1865 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1866 | EffectMask = Input { SourceOp = "BarMask", Source = "Mask", }, |
| 1867 | }, |
| 1868 | }, |
| 1869 | Scene = Merge { |
| 1870 | Inputs = { |
| 1871 | Background = Input { SourceOp = "Black", Source = "Output", }, |
| 1872 | Foreground = Input { SourceOp = "WhiteBar", Source = "Output", }, |
| 1873 | }, |
| 1874 | }, |
| 1875 | -- Put vx=20.0, vy=0.0 into aux.vector via CopyAux Mode 1 |
| 1876 | VecVal = Background { |
| 1877 | Inputs = { |
| 1878 | Width = Input { Value = 64, }, |
| 1879 | Height = Input { Value = 64, }, |
| 1880 | Depth = Input { Value = 4, }, |
| 1881 | TopLeftRed = Input { Value = 20.0, }, |
| 1882 | TopLeftGreen = Input { Value = 0.0, }, |
| 1883 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1884 | }, |
| 1885 | }, |
| 1886 | VecAux = Dimension.CopyAux { |
| 1887 | Inputs = { |
| 1888 | Mode = Input { Value = 1, }, |
| 1889 | Channel = Input { Value = FuID { "Vector" }, }, |
| 1890 | Input = Input { SourceOp = "VecVal", Source = "Output", }, |
| 1891 | }, |
| 1892 | }, |
| 1893 | -- Copy Scene RGBA onto VecAux (ChannelBoolean preserves BG's aux.vector when ToZBuffer=4) |
| 1894 | SceneWithAuxVec = ChannelBoolean { |
| 1895 | Inputs = { |
| 1896 | Background = Input { SourceOp = "VecAux", Source = "Output", }, |
| 1897 | Foreground = Input { SourceOp = "Scene", Source = "Output", }, |
| 1898 | ToRed = Input { Value = 0, }, |
| 1899 | ToGreen = Input { Value = 1, }, |
| 1900 | ToBlue = Input { Value = 2, }, |
| 1901 | ToAlpha = Input { Value = 3, }, |
| 1902 | }, |
| 1903 | }, |
| 1904 | VMB = VectorMotionBlur { |
| 1905 | Inputs = { |
| 1906 | Input = Input { SourceOp = "SceneWithAuxVec", Source = "Output", }, |
| 1907 | Scale = Input { Value = 1.0, }, |
| 1908 | }, |
| 1909 | }, |
| 1910 | -- 2. Animated moving textured rectangle -> Dimension.OpticalFlow -> VectorMotionBlur |
| 1911 | MoveMask = RectangleMask { |
| 1912 | Inputs = { |
| 1913 | MaskWidth = Input { Value = 64, }, |
| 1914 | MaskHeight = Input { Value = 64, }, |
| 1915 | Width = Input { Value = 0.35, }, |
| 1916 | Height = Input { Value = 0.35, }, |
| 1917 | Center = Input { Value = { 0.5, 0.5 }, }, |
| 1918 | }, |
| 1919 | }, |
| 1920 | MoveRect = Background { |
| 1921 | Inputs = { |
| 1922 | Width = Input { Value = 64, }, |
| 1923 | Height = Input { Value = 64, }, |
| 1924 | Type = Input { Value = FuID { "Horizontal" }, }, |
| 1925 | TopLeftRed = Input { Value = 0.1, }, |
| 1926 | TopLeftGreen = Input { Value = 0.9, }, |
| 1927 | TopLeftBlue = Input { Value = 0.2, }, |
| 1928 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1929 | TopRightRed = Input { Value = 1.0, }, |
| 1930 | TopRightGreen = Input { Value = 0.1, }, |
| 1931 | TopRightBlue = Input { Value = 0.8, }, |
| 1932 | TopRightAlpha = Input { Value = 1.0, }, |
| 1933 | EffectMask = Input { SourceOp = "MoveMask", Source = "Mask", }, |
| 1934 | }, |
| 1935 | }, |
| 1936 | MoveXf = Merge { |
| 1937 | Inputs = { |
| 1938 | Background = Input { SourceOp = "Black", Source = "Output", }, |
| 1939 | Foreground = Input { SourceOp = "MoveRect", Source = "Output", }, |
| 1940 | Center = Input { |
| 1941 | Value = { 0.5, 0.5 }, |
| 1942 | Expression = "Point(0.4 + time * 0.1, 0.5)", |
| 1943 | }, |
| 1944 | }, |
| 1945 | }, |
| 1946 | OF = Dimension.OpticalFlow { |
| 1947 | Inputs = { Input = Input { SourceOp = "MoveXf", Source = "Output", }, }, |
| 1948 | }, |
| 1949 | OF_VMB = VectorMotionBlur { |
| 1950 | Inputs = { Input = Input { SourceOp = "OF", Source = "Output", }, }, |
| 1951 | }, |
| 1952 | }, |
| 1953 | }"#; |
| 1954 | let comp = Comp::from_fusion_str(src).expect("parse VMB comp"); |
| 1955 | |
| 1956 | // Before blur: pixel at (x=38, y=32) is black (bar spans [30..34]). |
| 1957 | let (sc_tex, _) = eng.evaluate(&comp, comp.find_node("SceneWithAuxVec").unwrap(), 0.0); |
| 1958 | assert!(sc_tex.aux.as_ref().and_then(|a| a.vector.as_ref()).is_some(), "aux.vector must survive ChannelBoolean"); |
| 1959 | let sc_px = eng.readback_rgba(&sc_tex).unwrap(); |
| 1960 | assert_eq!(sc_px[(32 * 64 + 38) * 4], 0, "unblurred pixel at x=38 must be black"); |
| 1961 | |
| 1962 | // After VectorMotionBlur consuming aux.vector (vx=20px -> +-10px): |
| 1963 | // x=38 (6px right of bar center) smears bright, while y=4 (above bar) stays black! |
| 1964 | let (vmb_tex, stats) = eng.evaluate(&comp, comp.find_node("VMB").unwrap(), 0.0); |
| 1965 | assert!(stats.unsupported_nodes.is_empty(), "{:?}", stats.unsupported_nodes); |
| 1966 | let vmb_px = eng.readback_rgba(&vmb_tex).unwrap(); |
| 1967 | let smeared = vmb_px[(32 * 64 + 38) * 4]; |
| 1968 | assert!(smeared > 20, "VectorMotionBlur should smear white bar horizontally to x=38, got {smeared}"); |
| 1969 | assert_eq!(vmb_px[(4 * 64 + 32) * 4], 0, "horizontal vector should not blur vertically into y=4"); |
| 1970 | |
| 1971 | // OpticalFlow attaches both aux.vector and aux.back_vector when VectorMotionBlur is in comp |
| 1972 | let (of_tex, _) = eng.evaluate(&comp, comp.find_node("OF").unwrap(), 1.0); |
| 1973 | let of_aux = of_tex.aux.as_ref().expect("OpticalFlow must attach aux vectors when VMB exists"); |
| 1974 | let fwd = readback_rgba16f(&eng, of_aux.vector.as_ref().expect("aux.vector")); |
| 1975 | let bwd = readback_rgba16f(&eng, of_aux.back_vector.as_ref().expect("aux.back_vector")); |
| 1976 | let c_fwd = fwd[32 * 64 + 32]; |
| 1977 | let c_bwd = bwd[32 * 64 + 32]; |
| 1978 | // Box moves +0.1 * 64 = +6.4 px/frame right -> fwd.x > 0, bwd.x < 0! |
| 1979 | assert!(c_fwd[0] > 2.0, "expected positive forward flow x, got {c_fwd:?}"); |
| 1980 | assert!(c_bwd[0] < -2.0, "expected negative backward flow x, got {c_bwd:?}"); |
| 1981 | } |
| 1982 | } |