| 1 | //! Wave 36 GPU pipelines & evaluators: |
| 2 | //! - `VectorDenoise` (motion-compensated bilateral temporal denoiser) |
| 3 | //! - `Mandel` (escape-time Mandelbrot generator with continuous-potential coloring) |
| 4 | //! - `UnsharpMask` (separable Gaussian blur + thresholded high-frequency boost) |
| 5 | //! - `Letterbox` (aspect-preserving Letterbox & Pan-and-Scan framing) |
| 6 | //! - Archive Fuses in `fx_fuses/fuses.rs`: `Fuse.Wipe`, `Fuse.Null`, |
| 7 | //! `Fuse.SetMetaData`, `Fuse.Linger`, and `Fuse.OCLRays`. |
| 8 | |
| 9 | mod fuses; |
| 10 | #[cfg(test)] |
| 11 | mod tests; |
| 12 | |
| 13 | use super::*; |
| 14 | use crate::cache::AuxChannelTex; |
| 15 | use std::num::NonZeroU64; |
| 16 | use std::sync::Arc; |
| 17 | |
| 18 | const FX_FUSES_WGSL: &str = include_str!("../shaders/fx_fuses.wgsl"); |
| 19 | const FX_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; |
| 20 | |
| 21 | fn build_fx_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { |
| 22 | let storage_fmt = match format { |
| 23 | wgpu::TextureFormat::Rgba16Float => "rgba16float", |
| 24 | wgpu::TextureFormat::Rgba32Float => "rgba32float", |
| 25 | _ => "rgba8unorm", |
| 26 | }; |
| 27 | let mut src = FX_FUSES_WGSL.to_owned(); |
| 28 | if storage_fmt != "rgba8unorm" { |
| 29 | src = src.replace( |
| 30 | "texture_storage_2d<rgba8unorm, write>", |
| 31 | &format!("texture_storage_2d<{storage_fmt}, write>"), |
| 32 | ); |
| 33 | } |
| 34 | if hdr_float { |
| 35 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); |
| 36 | } |
| 37 | src |
| 38 | } |
| 39 | |
| 40 | fn tex_entry(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry { |
| 41 | wgpu::BindGroupLayoutEntry { |
| 42 | binding, |
| 43 | visibility: wgpu::ShaderStages::COMPUTE, |
| 44 | ty: wgpu::BindingType::Texture { |
| 45 | sample_type: wgpu::TextureSampleType::Float { filterable }, |
| 46 | view_dimension: wgpu::TextureViewDimension::D2, |
| 47 | multisampled: false, |
| 48 | }, |
| 49 | count: None, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[derive(Clone, Copy)] |
| 54 | pub(self) enum FxOp { |
| 55 | VdWarp, |
| 56 | VdAccumColor, |
| 57 | VdAccumWeight, |
| 58 | VdFinalize, |
| 59 | Mandel, |
| 60 | UnsharpMask, |
| 61 | Letterbox, |
| 62 | Wipe, |
| 63 | LingerStep, |
| 64 | OclRays, |
| 65 | } |
| 66 | |
| 67 | struct FxFormatPipelines { |
| 68 | bgl: wgpu::BindGroupLayout, |
| 69 | vd_warp: wgpu::ComputePipeline, |
| 70 | vd_accum_color: wgpu::ComputePipeline, |
| 71 | vd_accum_weight: wgpu::ComputePipeline, |
| 72 | vd_finalize: wgpu::ComputePipeline, |
| 73 | mandel: wgpu::ComputePipeline, |
| 74 | unsharp_mask: wgpu::ComputePipeline, |
| 75 | letterbox: wgpu::ComputePipeline, |
| 76 | wipe: wgpu::ComputePipeline, |
| 77 | linger_step: wgpu::ComputePipeline, |
| 78 | ocl_rays: wgpu::ComputePipeline, |
| 79 | } |
| 80 | |
| 81 | impl FxFormatPipelines { |
| 82 | fn pipeline(&self, op: FxOp) -> &wgpu::ComputePipeline { |
| 83 | match op { |
| 84 | FxOp::VdWarp => &self.vd_warp, |
| 85 | FxOp::VdAccumColor => &self.vd_accum_color, |
| 86 | FxOp::VdAccumWeight => &self.vd_accum_weight, |
| 87 | FxOp::VdFinalize => &self.vd_finalize, |
| 88 | FxOp::Mandel => &self.mandel, |
| 89 | FxOp::UnsharpMask => &self.unsharp_mask, |
| 90 | FxOp::Letterbox => &self.letterbox, |
| 91 | FxOp::Wipe => &self.wipe, |
| 92 | FxOp::LingerStep => &self.linger_step, |
| 93 | FxOp::OclRays => &self.ocl_rays, |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | pub(super) struct FxFusesPipelines { |
| 99 | sampler: wgpu::Sampler, |
| 100 | uniform_stride: u32, |
| 101 | uniform_chunks: Vec<wgpu::Buffer>, |
| 102 | uniform_cursor: u32, |
| 103 | dummy_aux: AuxChannelTex, |
| 104 | by_format: HashMap<(wgpu::TextureFormat, bool), FxFormatPipelines>, |
| 105 | } |
| 106 | |
| 107 | impl FxFusesPipelines { |
| 108 | pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self { |
| 109 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; |
| 110 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 111 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; |
| 112 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { |
| 113 | label: Some("fx-fuses-linear"), |
| 114 | address_mode_u: wgpu::AddressMode::ClampToEdge, |
| 115 | address_mode_v: wgpu::AddressMode::ClampToEdge, |
| 116 | mag_filter: wgpu::FilterMode::Linear, |
| 117 | min_filter: wgpu::FilterMode::Linear, |
| 118 | mipmap_filter: wgpu::MipmapFilterMode::Nearest, |
| 119 | ..Default::default() |
| 120 | }); |
| 121 | let dummy_aux = AuxChannelTex::new(device, [1, 1], wgpu::TextureFormat::Rgba16Float, "fx-dummy-aux"); |
| 122 | queue.write_texture( |
| 123 | dummy_aux.texture.as_image_copy(), |
| 124 | &[0u8; 8], |
| 125 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(8), rows_per_image: Some(1) }, |
| 126 | wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, |
| 127 | ); |
| 128 | Self { |
| 129 | sampler, |
| 130 | uniform_stride, |
| 131 | uniform_chunks: Vec::new(), |
| 132 | uniform_cursor: 0, |
| 133 | dummy_aux, |
| 134 | by_format: HashMap::new(), |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | pub(super) fn reset_uniform_cursor(&mut self) { |
| 139 | self.uniform_cursor = 0; |
| 140 | } |
| 141 | |
| 142 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { |
| 143 | self.uniform_cursor = 0; |
| 144 | if self.uniform_chunks.len() > max_chunks { |
| 145 | self.uniform_chunks.truncate(max_chunks); |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | fn alloc_uniform_slot(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, params: &UniformParams) -> (usize, u32) { |
| 150 | let slot_global = self.uniform_cursor; |
| 151 | let chunk_idx = (slot_global / FX_UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 152 | let slot_in_chunk = slot_global % FX_UNIFORM_SLOTS_PER_CHUNK; |
| 153 | while chunk_idx >= self.uniform_chunks.len() { |
| 154 | let size = u64::from(FX_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); |
| 155 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 156 | label: Some("fx-fuses-params-ring"), |
| 157 | size, |
| 158 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 159 | mapped_at_creation: false, |
| 160 | }); |
| 161 | self.uniform_chunks.push(buf); |
| 162 | } |
| 163 | let offset = slot_in_chunk * self.uniform_stride; |
| 164 | queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params)); |
| 165 | self.uniform_cursor = slot_global + 1; |
| 166 | (chunk_idx, offset) |
| 167 | } |
| 168 | |
| 169 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { |
| 170 | if self.by_format.contains_key(&(format, hdr_float)) { |
| 171 | return; |
| 172 | } |
| 173 | let u_size = std::mem::size_of::<UniformParams>() as u64; |
| 174 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 175 | label: Some("fx-fuses-bgl"), |
| 176 | entries: &[ |
| 177 | tex_entry(0, true), |
| 178 | tex_entry(1, true), |
| 179 | tex_entry(2, true), |
| 180 | tex_entry(3, false), // aux_tex: unfilterable float safe for WebGPU/wasm32 |
| 181 | wgpu::BindGroupLayoutEntry { |
| 182 | binding: 4, |
| 183 | visibility: wgpu::ShaderStages::COMPUTE, |
| 184 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 185 | count: None, |
| 186 | }, |
| 187 | wgpu::BindGroupLayoutEntry { |
| 188 | binding: 5, |
| 189 | visibility: wgpu::ShaderStages::COMPUTE, |
| 190 | ty: wgpu::BindingType::StorageTexture { |
| 191 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 192 | format, |
| 193 | view_dimension: wgpu::TextureViewDimension::D2, |
| 194 | }, |
| 195 | count: None, |
| 196 | }, |
| 197 | wgpu::BindGroupLayoutEntry { |
| 198 | binding: 6, |
| 199 | visibility: wgpu::ShaderStages::COMPUTE, |
| 200 | ty: wgpu::BindingType::Buffer { |
| 201 | ty: wgpu::BufferBindingType::Uniform, |
| 202 | has_dynamic_offset: true, |
| 203 | min_binding_size: NonZeroU64::new(u_size), |
| 204 | }, |
| 205 | count: None, |
| 206 | }, |
| 207 | ], |
| 208 | }); |
| 209 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 210 | label: Some("fx-fuses-pl"), |
| 211 | bind_group_layouts: &[Some(&bgl)], |
| 212 | immediate_size: 0, |
| 213 | }); |
| 214 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 215 | label: Some("fx-fuses-wgsl"), |
| 216 | source: wgpu::ShaderSource::Wgsl(build_fx_wgsl(format, hdr_float).into()), |
| 217 | }); |
| 218 | let mk = |entry: &str| { |
| 219 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 220 | label: Some(entry), |
| 221 | layout: Some(&pl), |
| 222 | module: &module, |
| 223 | entry_point: Some(entry), |
| 224 | compilation_options: Default::default(), |
| 225 | cache: None, |
| 226 | }) |
| 227 | }; |
| 228 | let fp = FxFormatPipelines { |
| 229 | bgl, |
| 230 | vd_warp: mk("vd_warp_op"), |
| 231 | vd_accum_color: mk("vd_accum_color_op"), |
| 232 | vd_accum_weight: mk("vd_accum_weight_op"), |
| 233 | vd_finalize: mk("vd_finalize_op"), |
| 234 | mandel: mk("mandel_op"), |
| 235 | unsharp_mask: mk("unsharp_mask_op"), |
| 236 | letterbox: mk("letterbox_op"), |
| 237 | wipe: mk("wipe_op"), |
| 238 | linger_step: mk("linger_step_op"), |
| 239 | ocl_rays: mk("ocl_rays_op"), |
| 240 | }; |
| 241 | self.by_format.insert((format, hdr_float), fp); |
| 242 | } |
| 243 | |
| 244 | #[allow(clippy::too_many_arguments)] |
| 245 | fn dispatch( |
| 246 | &mut self, |
| 247 | device: &wgpu::Device, |
| 248 | queue: &wgpu::Queue, |
| 249 | enc: &mut wgpu::CommandEncoder, |
| 250 | op: FxOp, |
| 251 | src_a: &wgpu::TextureView, |
| 252 | src_b: &wgpu::TextureView, |
| 253 | mask: &wgpu::TextureView, |
| 254 | aux: Option<&wgpu::TextureView>, |
| 255 | dst: &CachedTexture, |
| 256 | params: &UniformParams, |
| 257 | ) { |
| 258 | let hdr_float = dst.depth.is_float(); |
| 259 | self.ensure_format(device, dst.format, hdr_float); |
| 260 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 261 | let fp = &self.by_format[&(dst.format, hdr_float)]; |
| 262 | let aux_view = aux.unwrap_or(&self.dummy_aux.view); |
| 263 | let u_size = NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64); |
| 264 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 265 | label: Some("fx-fuses-bg"), |
| 266 | layout: &fp.bgl, |
| 267 | entries: &[ |
| 268 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, |
| 269 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, |
| 270 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, |
| 271 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(aux_view) }, |
| 272 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| 273 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&dst.view) }, |
| 274 | wgpu::BindGroupEntry { |
| 275 | binding: 6, |
| 276 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 277 | buffer: &self.uniform_chunks[chunk_idx], |
| 278 | offset: 0, |
| 279 | size: u_size, |
| 280 | }), |
| 281 | }, |
| 282 | ], |
| 283 | }); |
| 284 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 285 | label: Some("fx-fuses-pass"), |
| 286 | timestamp_writes: None, |
| 287 | }); |
| 288 | pass.set_pipeline(fp.pipeline(op)); |
| 289 | pass.set_bind_group(0, &bg, &[offset]); |
| 290 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | /// `c` for pixel `(x, row)`: offsets run from the frame center in pixel-corner units, imaginary growing downward. |
| 295 | fn mandel_c(size: [u32; 2], pos: [f64; 2], unit: f64, rot: f64, x: f64, row: f64) -> [f64; 2] { |
| 296 | let local = [x - 0.5 * size[0] as f64, row + 1.0 - 0.5 * size[1] as f64]; |
| 297 | let (sa, ca) = rot.sin_cos(); |
| 298 | [pos[0] + (local[0] * ca - local[1] * sa) * unit, pos[1] + (local[0] * sa + local[1] * ca) * unit] |
| 299 | } |
| 300 | |
| 301 | /// log2 of the largest continuous potential `ln|z| / 2^n` in the frame, which Fusion normalizes by. |
| 302 | /// The potential is harmonic outside the set, so its maximum lies on the frame border. |
| 303 | fn mandel_border_log2_potential(size: [u32; 2], pos: [f64; 2], unit: f64, rot: f64, iterations: u32, escape: f64) -> f64 { |
| 304 | let [w, h] = size.map(|v| v.max(1) as f64 - 1.0); |
| 305 | let steps = size[0].max(size[1]).max(2) as usize; |
| 306 | let border = (0..=steps).flat_map(|i| { |
| 307 | let t = i as f64 / steps as f64; |
| 308 | [[t * w, 0.0], [t * w, h], [0.0, t * h], [w, t * h]] |
| 309 | }); |
| 310 | border |
| 311 | .filter_map(|[x, row]| { |
| 312 | let c = mandel_c(size, pos, unit, rot, x, row); |
| 313 | let mut z = [0.0_f64; 2]; |
| 314 | (1..=iterations).find_map(|n| { |
| 315 | z = [z[0] * z[0] - z[1] * z[1] + c[0], 2.0 * z[0] * z[1] + c[1]]; |
| 316 | let z2 = z[0] * z[0] + z[1] * z[1]; |
| 317 | (z2 > escape * escape).then(|| (0.5 * z2.ln()).log2() - n as f64) |
| 318 | }) |
| 319 | }) |
| 320 | .fold(f64::NEG_INFINITY, f64::max) |
| 321 | } |
| 322 | |
| 323 | pub(self) fn first_num(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f64 { |
| 324 | for &k in keys { |
| 325 | if node.inputs.contains_key(k) { |
| 326 | return comp.eval_number(node, k, time, default, expr); |
| 327 | } |
| 328 | } |
| 329 | default |
| 330 | } |
| 331 | |
| 332 | pub(self) fn first_point(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: [f64; 2], expr: &ExprEngine) -> [f64; 2] { |
| 333 | for &k in keys { |
| 334 | if node.inputs.contains_key(k) { |
| 335 | return comp.eval_point(node, k, time, default, expr); |
| 336 | } |
| 337 | } |
| 338 | default |
| 339 | } |
| 340 | |
| 341 | pub(self) fn first_connected(comp: &Comp, node: &Node, ports: &[&str]) -> Option<NodeId> { |
| 342 | ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s))) |
| 343 | } |
| 344 | |
| 345 | pub(self) fn first_str<'a>(node: &'a Node, keys: &[&str]) -> Option<&'a str> { |
| 346 | keys.iter().find_map(|k| node.static_str(k)) |
| 347 | } |
| 348 | |
| 349 | impl Engine { |
| 350 | fn fx_fuses_pipelines(&self) -> &RefCell<FxFusesPipelines> { |
| 351 | self.fx_fuses_pipelines |
| 352 | .get_or_init(|| RefCell::new(FxFusesPipelines::new(&self.device, &self.queue))) |
| 353 | } |
| 354 | |
| 355 | #[allow(clippy::too_many_arguments)] |
| 356 | pub(self) fn dispatch_fx( |
| 357 | &self, |
| 358 | enc: &mut wgpu::CommandEncoder, |
| 359 | op: FxOp, |
| 360 | src_a: &wgpu::TextureView, |
| 361 | src_b: &wgpu::TextureView, |
| 362 | mask: &wgpu::TextureView, |
| 363 | aux: Option<&wgpu::TextureView>, |
| 364 | dst: &CachedTexture, |
| 365 | params: &UniformParams, |
| 366 | ) { |
| 367 | self.fx_fuses_pipelines() |
| 368 | .borrow_mut() |
| 369 | .dispatch(&self.device, &self.queue, enc, op, src_a, src_b, mask, aux, dst, params); |
| 370 | } |
| 371 | |
| 372 | // ------------------------------------------------------------------------ |
| 373 | // 1. VectorDenoise |
| 374 | // ------------------------------------------------------------------------ |
| 375 | #[allow(clippy::too_many_arguments)] |
| 376 | pub(super) fn eval_vector_denoise( |
| 377 | &mut self, |
| 378 | comp: &Comp, |
| 379 | node: &Node, |
| 380 | time: f64, |
| 381 | frame_i: i64, |
| 382 | enc: &mut wgpu::CommandEncoder, |
| 383 | visiting: &mut HashSet<(NodeId, i64)>, |
| 384 | stats: &mut EvalStats, |
| 385 | ) -> CachedTexture { |
| 386 | let Some(src_id) = first_connected(comp, node, &["Input", "Background", "Image"]) else { |
| 387 | return self.dummy.clone(); |
| 388 | }; |
| 389 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 390 | let mbm_flag = self.multiplies_by_mask(comp, node, time); |
| 391 | let skip = self.process_skip(comp, node, time); |
| 392 | let curr = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 393 | if blend <= 1e-6 && !mbm_flag { |
| 394 | return curr; |
| 395 | } |
| 396 | |
| 397 | let radius = first_num(comp, node, &["TemporalRadius", "Radius", "Frames", "Average"], time, 1.0, &self.expr) |
| 398 | .round() |
| 399 | .clamp(0.0, 3.0) as i64; |
| 400 | if radius == 0 && !mbm_flag && skip == [0.0; 4] { |
| 401 | return curr; |
| 402 | } |
| 403 | let sigma = first_num(comp, node, &["Sigma", "Threshold", "ColorThreshold", "Tolerance"], time, 0.15, &self.expr) |
| 404 | .max(1e-3) as f32; |
| 405 | let vec_scale = first_num(comp, node, &["VectorScale", "Scale"], time, 1.0, &self.expr) as f32; |
| 406 | |
| 407 | let mut neighbors: Vec<(i64, CachedTexture)> = Vec::with_capacity((radius * 2) as usize); |
| 408 | let mut all_same = true; |
| 409 | for dt in -radius..=radius { |
| 410 | if dt == 0 { |
| 411 | continue; |
| 412 | } |
| 413 | let nbr = self.eval_node(comp, src_id, time + dt as f64, enc, visiting, stats); |
| 414 | if nbr.content_hash != curr.content_hash || curr.content_hash == 0 { |
| 415 | all_same = false; |
| 416 | } |
| 417 | neighbors.push((dt, nbr)); |
| 418 | } |
| 419 | if all_same && !mbm_flag && skip == [0.0; 4] { |
| 420 | return curr; |
| 421 | } |
| 422 | |
| 423 | let ext_vec = first_connected(comp, node, &["VectorInput", "Vectors"]).map(|vid| { |
| 424 | let t = self.eval_node(comp, vid, time, enc, visiting, stats); |
| 425 | self.crop_to_canvas(enc, t) |
| 426 | }); |
| 427 | let curr_c = self.crop_to_canvas(enc, curr.clone()); |
| 428 | let size = curr_c.size; |
| 429 | let dst_depth = self.node_depth(comp, node, time, Some(curr_c.depth)); |
| 430 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 431 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 432 | let mbm = mask.is_some() && mbm_flag; |
| 433 | |
| 434 | let fwd_vec: Option<(Arc<wgpu::TextureView>, u64)> = if let Some(ext) = ext_vec.as_ref() { |
| 435 | if let Some(av) = ext.aux.as_ref().and_then(|a| a.vector.as_ref()) { |
| 436 | Some((av.view.clone(), ext.content_hash ^ 0xF001)) |
| 437 | } else { |
| 438 | Some((ext.view.clone(), ext.content_hash ^ 0xF002)) |
| 439 | } |
| 440 | } else { |
| 441 | curr_c.aux.as_ref().and_then(|a| a.vector.as_ref()).map(|av| (av.view.clone(), curr_c.content_hash ^ 0xF003)) |
| 442 | }; |
| 443 | let bwd_vec: Option<(Arc<wgpu::TextureView>, u64)> = curr_c |
| 444 | .aux |
| 445 | .as_ref() |
| 446 | .and_then(|a| a.back_vector.as_ref()) |
| 447 | .map(|av| (av.view.clone(), curr_c.content_hash ^ 0xB003)); |
| 448 | |
| 449 | let mut hashes = Vec::with_capacity(neighbors.len() + 5); |
| 450 | hashes.push(curr_c.content_hash); |
| 451 | for (_, n) in &neighbors { |
| 452 | hashes.push(n.content_hash); |
| 453 | } |
| 454 | hashes.push(fwd_vec.as_ref().map_or(0, |v| v.1)); |
| 455 | hashes.push(bwd_vec.as_ref().map_or(0, |v| v.1)); |
| 456 | hashes.push(mask_hash); |
| 457 | hashes.push(dst_depth as u64); |
| 458 | let params_f32 = [ |
| 459 | radius as f32, |
| 460 | sigma, |
| 461 | vec_scale, |
| 462 | blend, |
| 463 | if mask_inv { 1.0 } else { 0.0 }, |
| 464 | if mbm { 1.0 } else { 0.0 }, |
| 465 | skip[0], |
| 466 | skip[1], |
| 467 | skip[2], |
| 468 | skip[3], |
| 469 | ]; |
| 470 | let key = self.make_key(node, "VectorDenoise", size, &hashes, &params_f32); |
| 471 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 472 | stats.cache_hits += 1; |
| 473 | return hit; |
| 474 | } |
| 475 | stats.cache_misses += 1; |
| 476 | stats.nodes_evaluated += 1; |
| 477 | |
| 478 | let work_depth = BitDepth::Float16; |
| 479 | let search_rad = if self.hiq { 4.0_f32 } else { 2.0_f32 }; |
| 480 | let mut w_tex = self.alloc_tex(size, work_depth, 0); |
| 481 | let mut u_init = UniformParams::default(); |
| 482 | u_init.p[0] = [sigma, 1.0, 1.0, 0.0]; |
| 483 | self.dispatch_fx(enc, FxOp::VdAccumWeight, &curr_c.view, &curr_c.view, &self.dummy.view, None, &w_tex, &u_init); |
| 484 | |
| 485 | let mut accum = curr_c.clone(); |
| 486 | for (dt, nbr) in &neighbors { |
| 487 | let nbr_c = self.crop_to_canvas(enc, nbr.clone()); |
| 488 | let warped = if nbr_c.content_hash != 0 && nbr_c.content_hash == curr_c.content_hash { |
| 489 | curr_c.clone() |
| 490 | } else { |
| 491 | let (vec_view, has_vec, scale_dt) = if *dt > 0 { |
| 492 | if let Some((v, _)) = &fwd_vec { |
| 493 | (Some(v.as_ref()), 1.0_f32, vec_scale * (*dt as f32)) |
| 494 | } else { |
| 495 | (None, 0.0_f32, 0.0) |
| 496 | } |
| 497 | } else if let Some((v, _)) = &bwd_vec { |
| 498 | (Some(v.as_ref()), 1.0_f32, vec_scale * ((-*dt) as f32)) |
| 499 | } else if let Some((v, _)) = &fwd_vec { |
| 500 | (Some(v.as_ref()), 1.0_f32, vec_scale * (*dt as f32)) |
| 501 | } else { |
| 502 | (None, 0.0_f32, 0.0) |
| 503 | }; |
| 504 | let dst_w = self.alloc_tex(size, work_depth, 0); |
| 505 | let mut uw = UniformParams::default(); |
| 506 | uw.p[0] = [has_vec, scale_dt, scale_dt, search_rad]; |
| 507 | self.dispatch_fx(enc, FxOp::VdWarp, &curr_c.view, &nbr_c.view, &self.dummy.view, vec_view, &dst_w, &uw); |
| 508 | dst_w |
| 509 | }; |
| 510 | |
| 511 | let temporal_w = (-0.25 * (*dt * *dt) as f32).exp(); |
| 512 | let mut ua = UniformParams::default(); |
| 513 | ua.p[0] = [sigma, temporal_w, 0.0, 0.0]; |
| 514 | let next_acc = self.alloc_tex(size, work_depth, 0); |
| 515 | self.dispatch_fx(enc, FxOp::VdAccumColor, &accum.view, &warped.view, &curr_c.view, Some(&w_tex.view), &next_acc, &ua); |
| 516 | let next_w = self.alloc_tex(size, work_depth, 0); |
| 517 | self.dispatch_fx(enc, FxOp::VdAccumWeight, &curr_c.view, &warped.view, &self.dummy.view, Some(&w_tex.view), &next_w, &ua); |
| 518 | accum = next_acc; |
| 519 | w_tex = next_w; |
| 520 | } |
| 521 | |
| 522 | let mut dst = self.alloc_tex(size, dst_depth, key); |
| 523 | let mut uf = UniformParams::default(); |
| 524 | uf.p[0] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }]; |
| 525 | uf.p[1] = skip; |
| 526 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 527 | self.dispatch_fx(enc, FxOp::VdFinalize, &curr_c.view, &accum.view, mv, None, &dst, &uf); |
| 528 | if curr_c.aux.is_some() && dst.size == curr_c.size && dst.origin == curr_c.origin { |
| 529 | dst.set_aux(curr_c.aux.clone()); |
| 530 | } |
| 531 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 532 | dst |
| 533 | } |
| 534 | |
| 535 | // ------------------------------------------------------------------------ |
| 536 | // 2. Mandel |
| 537 | // ------------------------------------------------------------------------ |
| 538 | #[allow(clippy::too_many_arguments)] |
| 539 | pub(super) fn eval_mandel( |
| 540 | &mut self, |
| 541 | comp: &Comp, |
| 542 | node: &Node, |
| 543 | time: f64, |
| 544 | frame_i: i64, |
| 545 | comp_dims: [u32; 2], |
| 546 | enc: &mut wgpu::CommandEncoder, |
| 547 | visiting: &mut HashSet<(NodeId, i64)>, |
| 548 | stats: &mut EvalStats, |
| 549 | ) -> CachedTexture { |
| 550 | let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; |
| 551 | let w = if use_ff { comp.width } else { comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32 }; |
| 552 | let h = if use_ff { comp.height } else { comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32 }; |
| 553 | let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) }; |
| 554 | let depth = self.node_depth(comp, node, time, None); |
| 555 | |
| 556 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 557 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 558 | let num = |id: &str, default: f64| comp.eval_number(node, id, time, default, &self.expr); |
| 559 | |
| 560 | // Zoom compounds 1.25x per unit above 1; Zoom 1 spans 5 units across the frame width. |
| 561 | let unit = 5.0 / (size[0] as f64 * 1.25_f64.powf(num("Zoom", 1.0).max(1.0) - 1.0)); |
| 562 | let pos = [num("XPosition", -0.5), num("YPosition", 0.0)]; |
| 563 | let rot = num("Rotation", 0.0).to_radians(); |
| 564 | let iterations = num("Iterations", 256.0).round().clamp(1.0, 4096.0); |
| 565 | let escape = num("EscapeLimit", 16.0); |
| 566 | let mut u = UniformParams::default(); |
| 567 | u.p[0] = [pos[0] as f32, pos[1] as f32, unit as f32, rot as f32]; |
| 568 | u.p[1] = [iterations as f32, escape as f32, num("GradientCurve", 0.125) as f32, num("GradMethod", 0.0).round() as f32]; |
| 569 | u.p[2] = ["RedRepetitions", "GreenRepetitions", "BlueRepetitions", "AlphaRepetitions"].map(|id| num(id, 1.0) as f32); |
| 570 | u.p[3] = ["RedPhase", "GreenPhase", "BluePhase", "AlphaPhase"].map(|id| num(id, 0.0) as f32); |
| 571 | u.p[4] = [ |
| 572 | num("Blend", 1.0) as f32, |
| 573 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 574 | if mask_inv { 1.0 } else { 0.0 }, |
| 575 | mandel_border_log2_potential(size, pos, unit, rot, iterations as u32, escape) as f32, |
| 576 | ]; |
| 577 | |
| 578 | let key = self.make_key(node, "Mandel", size, &[mask_hash, depth as u64], bytemuck::cast_slice(&u.p[..5])); |
| 579 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 580 | stats.cache_hits += 1; |
| 581 | return hit; |
| 582 | } |
| 583 | stats.cache_misses += 1; |
| 584 | stats.nodes_evaluated += 1; |
| 585 | |
| 586 | let dst = self.alloc_tex(size, depth, key); |
| 587 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 588 | self.dispatch_fx(enc, FxOp::Mandel, &self.dummy.view, &self.dummy.view, mv, None, &dst, &u); |
| 589 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 590 | dst |
| 591 | } |
| 592 | |
| 593 | // ------------------------------------------------------------------------ |
| 594 | // 3. UnsharpMask |
| 595 | // ------------------------------------------------------------------------ |
| 596 | #[allow(clippy::too_many_arguments)] |
| 597 | pub(super) fn eval_unsharp_mask( |
| 598 | &mut self, |
| 599 | comp: &Comp, |
| 600 | node: &Node, |
| 601 | time: f64, |
| 602 | frame_i: i64, |
| 603 | enc: &mut wgpu::CommandEncoder, |
| 604 | visiting: &mut HashSet<(NodeId, i64)>, |
| 605 | stats: &mut EvalStats, |
| 606 | ) -> CachedTexture { |
| 607 | let Some(src_id) = first_connected(comp, node, &["Input", "Background"]) else { |
| 608 | return self.dummy.clone(); |
| 609 | }; |
| 610 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 611 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 612 | let lock_xy = first_num(comp, node, &["LockXY", "LockSizeXY"], time, 1.0, &self.expr) > 0.5; |
| 613 | let x_size = first_num(comp, node, &["XSize", "Size"], time, 2.0, &self.expr).max(0.0) as f32; |
| 614 | let y_size = if lock_xy { x_size } else { first_num(comp, node, &["YSize", "Size"], time, x_size as f64, &self.expr).max(0.0) as f32 }; |
| 615 | let gain = first_num(comp, node, &["Gain", "Amount"], time, 1.0, &self.expr) as f32; |
| 616 | let threshold = first_num(comp, node, &["Threshold"], time, 0.0, &self.expr).max(0.0) as f32; |
| 617 | let mbm_flag = self.multiplies_by_mask(comp, node, time); |
| 618 | let skip = self.process_skip(comp, node, time); |
| 619 | |
| 620 | if (blend <= 1e-6 || gain.abs() <= 1e-6 || x_size.max(y_size) <= 1e-5) && !mbm_flag && skip == [0.0; 4] { |
| 621 | return src; |
| 622 | } |
| 623 | let has_mask = Self::resolve_effect_mask_id(comp, node).is_some(); |
| 624 | let src = if has_mask { self.crop_to_canvas(enc, src) } else { src }; |
| 625 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 626 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 627 | let mbm = mask.is_some() && mbm_flag; |
| 628 | |
| 629 | let scale_ref = (src.canvas_size[0] as f32 / 720.0).max(1e-4); |
| 630 | let rx = x_size * scale_ref; |
| 631 | let ry = y_size * scale_ref; |
| 632 | |
| 633 | let mut u = UniformParams::default(); |
| 634 | u.p[0] = [gain, threshold, blend, if mask.is_some() { 1.0 } else { 0.0 }]; |
| 635 | u.p[1] = [if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }, rx, ry]; |
| 636 | u.p[2] = skip; |
| 637 | |
| 638 | let key = self.make_key(node, "UnsharpMask", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); |
| 639 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 640 | stats.cache_hits += 1; |
| 641 | return hit; |
| 642 | } |
| 643 | stats.cache_misses += 1; |
| 644 | stats.nodes_evaluated += 1; |
| 645 | |
| 646 | let blurred = self.blur_separable(enc, &src, rx, ry, 0.0, 1.0); |
| 647 | let mut dst = self.alloc_tex_like(&src, src.depth, key); |
| 648 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 649 | self.dispatch_fx(enc, FxOp::UnsharpMask, &src.view, &blurred.view, mv, None, &dst, &u); |
| 650 | if src.aux.is_some() && dst.size == src.size && dst.origin == src.origin { |
| 651 | dst.set_aux(src.aux.clone()); |
| 652 | } |
| 653 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 654 | dst |
| 655 | } |
| 656 | |
| 657 | // ------------------------------------------------------------------------ |
| 658 | // 4. Letterbox |
| 659 | // ------------------------------------------------------------------------ |
| 660 | #[allow(clippy::too_many_arguments)] |
| 661 | pub(super) fn eval_letterbox( |
| 662 | &mut self, |
| 663 | comp: &Comp, |
| 664 | node: &Node, |
| 665 | time: f64, |
| 666 | frame_i: i64, |
| 667 | comp_dims: [u32; 2], |
| 668 | enc: &mut wgpu::CommandEncoder, |
| 669 | visiting: &mut HashSet<(NodeId, i64)>, |
| 670 | stats: &mut EvalStats, |
| 671 | ) -> CachedTexture { |
| 672 | let Some(src_id) = first_connected(comp, node, &["Input", "Background"]) else { |
| 673 | return self.dummy.clone(); |
| 674 | }; |
| 675 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 676 | let hiq_only = comp.eval_number(node, "HiQOnly", time, 0.0, &self.expr) > 0.5; |
| 677 | if !self.hiq && hiq_only { |
| 678 | return src; |
| 679 | } |
| 680 | let src = self.crop_to_canvas(enc, src); |
| 681 | let max_dim = self.device.limits().max_texture_dimension_2d as f64; |
| 682 | let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; |
| 683 | let dst_size = if use_ff { |
| 684 | comp_dims |
| 685 | } else { |
| 686 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).clamp(1.0, max_dim).round() as u32; |
| 687 | let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).clamp(1.0, max_dim).round() as u32; |
| 688 | if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) } |
| 689 | }; |
| 690 | |
| 691 | let mode = match node.static_str("Mode") { |
| 692 | Some(s) if s.to_ascii_lowercase().contains("pan") => 1.0_f32, |
| 693 | Some(_) => 0.0_f32, |
| 694 | None => if comp.eval_number(node, "Mode", time, 0.0, &self.expr) >= 0.5 { 1.0 } else { 0.0 }, |
| 695 | }; |
| 696 | let position = first_num(comp, node, &["Position", "CenterOffset"], time, 0.0, &self.expr).clamp(-1.0, 1.0) as f32; |
| 697 | let filter = match node.static_str("FilterMethod") { |
| 698 | Some("Nearest" | "Nearest Neighbor") => 0.0_f32, |
| 699 | Some("Box" | "Linear" | "Bilinear") => 1.0_f32, |
| 700 | Some("Cubic" | "Catmull-Rom" | "CatmullRom" | "Lanczos" | "Mitchell" | "Quadratic") => 3.0_f32, |
| 701 | Some(_) => 2.0_f32, |
| 702 | None => comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) as f32, |
| 703 | }; |
| 704 | let pa_pt = comp.eval_point(node, "PixelAspect", time, [1.0, 1.0], &self.expr); |
| 705 | let pa = (pa_pt[0] / pa_pt[1].max(1e-4)).clamp(0.1, 10.0) as f32; |
| 706 | |
| 707 | let mut u = UniformParams::default(); |
| 708 | u.p[0] = [mode, position, filter, pa]; |
| 709 | let key = self.make_key(node, "Letterbox", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1])); |
| 710 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 711 | stats.cache_hits += 1; |
| 712 | return hit; |
| 713 | } |
| 714 | stats.cache_misses += 1; |
| 715 | stats.nodes_evaluated += 1; |
| 716 | let dst = self.alloc_tex(dst_size, src.depth, key); |
| 717 | self.dispatch_fx(enc, FxOp::Letterbox, &src.view, &self.dummy.view, &self.dummy.view, None, &dst, &u); |
| 718 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 719 | dst |
| 720 | } |
| 721 | } |