| 1 | use super::*; |
| 2 | use std::path::PathBuf; |
| 3 | use std::sync::{Mutex, OnceLock}; |
| 4 | |
| 5 | #[path = "nv12.rs"] |
| 6 | mod nv12; |
| 7 | pub(crate) use nv12::Nv12Pipelines; |
| 8 | |
| 9 | static DIMS_CACHE: OnceLock<Mutex<HashMap<PathBuf, Option<[u32; 2]>>>> = OnceLock::new(); |
| 10 | |
| 11 | pub(super) fn clear_dims_cache() { |
| 12 | if let Some(cache) = DIMS_CACHE.get() { |
| 13 | if let Ok(mut guard) = cache.lock() { |
| 14 | guard.clear(); |
| 15 | } |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | impl Engine { |
| 20 | fn probe_clip_dims(clip: &model::ClipSpec) -> Option<[u32; 2]> { |
| 21 | let base = PathBuf::from(&clip.filename); |
| 22 | let cache = DIMS_CACHE.get_or_init(|| Mutex::new(HashMap::new())); |
| 23 | if let Ok(guard) = cache.lock() { |
| 24 | if let Some(&cached) = guard.get(&base) { |
| 25 | return cached; |
| 26 | } |
| 27 | } |
| 28 | let dims = if !base.exists() { |
| 29 | None |
| 30 | } else { |
| 31 | let ext = base |
| 32 | .extension() |
| 33 | .and_then(|e| e.to_str()) |
| 34 | .map(|e| e.to_ascii_lowercase()); |
| 35 | if matches!( |
| 36 | ext.as_deref(), |
| 37 | Some("mov" | "mp4" | "m4v" | "mkv" | "avi" | "webm" | "mxf") |
| 38 | ) { |
| 39 | crate::media::open_video_decoder(&base).and_then(|dec| { |
| 40 | let info = dec.info(); |
| 41 | (info.width > 0 && info.height > 0).then_some([info.width, info.height]) |
| 42 | }) |
| 43 | } else { |
| 44 | image::image_dimensions(&base) |
| 45 | .ok() |
| 46 | .filter(|&(w, h)| w > 0 && h > 0) |
| 47 | .map(|(w, h)| [w, h]) |
| 48 | } |
| 49 | }; |
| 50 | if let Ok(mut guard) = cache.lock() { |
| 51 | guard.insert(base, dims); |
| 52 | } |
| 53 | dims |
| 54 | } |
| 55 | |
| 56 | fn apply_loader_timing_overrides( |
| 57 | comp: &Comp, |
| 58 | node: &Node, |
| 59 | clip: &mut model::ClipSpec, |
| 60 | time: f64, |
| 61 | expr: &ExprEngine, |
| 62 | ) { |
| 63 | if node.inputs.contains_key("GlobalIn") { |
| 64 | clip.global_start = comp |
| 65 | .eval_number(node, "GlobalIn", time, clip.global_start as f64, expr) |
| 66 | .round() as i64; |
| 67 | } |
| 68 | if node.inputs.contains_key("GlobalOut") { |
| 69 | clip.global_end = comp |
| 70 | .eval_number(node, "GlobalOut", time, clip.global_end as f64, expr) |
| 71 | .round() as i64; |
| 72 | } |
| 73 | if node.inputs.contains_key("Loop") { |
| 74 | clip.loop_clip = comp.eval_number( |
| 75 | node, |
| 76 | "Loop", |
| 77 | time, |
| 78 | if clip.loop_clip { 1.0 } else { 0.0 }, |
| 79 | expr, |
| 80 | ) > 0.5; |
| 81 | } |
| 82 | if node.inputs.contains_key("Reverse") { |
| 83 | clip.reverse = comp.eval_number( |
| 84 | node, |
| 85 | "Reverse", |
| 86 | time, |
| 87 | if clip.reverse { 1.0 } else { 0.0 }, |
| 88 | expr, |
| 89 | ) > 0.5; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | fn upload_loader_texture( |
| 94 | &self, |
| 95 | enc: &mut wgpu::CommandEncoder, |
| 96 | tex: &CachedTexture, |
| 97 | data: &[u8], |
| 98 | bytes_per_pixel: u32, |
| 99 | size: [u32; 2], |
| 100 | ) { |
| 101 | self.upload_raw_texture(enc, &tex.texture, data, bytes_per_pixel, size); |
| 102 | } |
| 103 | |
| 104 | fn upload_raw_texture( |
| 105 | &self, |
| 106 | enc: &mut wgpu::CommandEncoder, |
| 107 | texture: &wgpu::Texture, |
| 108 | data: &[u8], |
| 109 | bytes_per_pixel: u32, |
| 110 | size: [u32; 2], |
| 111 | ) { |
| 112 | #[cfg(target_arch = "wasm32")] |
| 113 | { |
| 114 | let _ = enc; |
| 115 | self.queue.write_texture( |
| 116 | texture.as_image_copy(), |
| 117 | data, |
| 118 | wgpu::TexelCopyBufferLayout { |
| 119 | offset: 0, |
| 120 | bytes_per_row: Some(size[0] * bytes_per_pixel), |
| 121 | rows_per_image: Some(size[1]), |
| 122 | }, |
| 123 | wgpu::Extent3d { |
| 124 | width: size[0], |
| 125 | height: size[1], |
| 126 | depth_or_array_layers: 1, |
| 127 | }, |
| 128 | ); |
| 129 | } |
| 130 | #[cfg(not(target_arch = "wasm32"))] |
| 131 | { |
| 132 | let [w, h] = size; |
| 133 | if w == 0 || h == 0 { |
| 134 | return; |
| 135 | } |
| 136 | let unpadded_bpr = w * bytes_per_pixel; |
| 137 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 138 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 139 | let needed = u64::from(padded_bpr) * u64::from(h); |
| 140 | if let Some(buf) = self.media.acquire_upload_staging(&self.device, needed) { |
| 141 | struct StagingGuard<'a> { |
| 142 | media: &'a crate::media::MediaCache, |
| 143 | cap: u64, |
| 144 | armed: bool, |
| 145 | } |
| 146 | impl Drop for StagingGuard<'_> { |
| 147 | fn drop(&mut self) { |
| 148 | if self.armed { |
| 149 | self.media.release_failed_upload_staging(self.cap); |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | let mut staging_guard = StagingGuard { |
| 154 | media: &self.media, |
| 155 | cap: buf.size(), |
| 156 | armed: true, |
| 157 | }; |
| 158 | let mut copied = false; |
| 159 | if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() { |
| 160 | if padded_bpr == unpadded_bpr { |
| 161 | let total = (unpadded_bpr as usize) * (h as usize); |
| 162 | view.slice(..total).copy_from_slice(&data[..total]); |
| 163 | } else { |
| 164 | let src_stride = unpadded_bpr as usize; |
| 165 | let dst_stride = padded_bpr as usize; |
| 166 | let mut wo = view.slice(..needed as usize); |
| 167 | for (row_idx, src_row) in data.chunks_exact(src_stride).enumerate() { |
| 168 | let off = row_idx * dst_stride; |
| 169 | wo.slice(off..off + src_stride).copy_from_slice(src_row); |
| 170 | } |
| 171 | } |
| 172 | drop(view); |
| 173 | copied = true; |
| 174 | } |
| 175 | if copied { |
| 176 | buf.unmap(); |
| 177 | enc.copy_buffer_to_texture( |
| 178 | wgpu::TexelCopyBufferInfo { |
| 179 | buffer: &buf, |
| 180 | layout: wgpu::TexelCopyBufferLayout { |
| 181 | offset: 0, |
| 182 | bytes_per_row: Some(padded_bpr), |
| 183 | rows_per_image: Some(h), |
| 184 | }, |
| 185 | }, |
| 186 | texture.as_image_copy(), |
| 187 | wgpu::Extent3d { |
| 188 | width: w, |
| 189 | height: h, |
| 190 | depth_or_array_layers: 1, |
| 191 | }, |
| 192 | ); |
| 193 | staging_guard.armed = false; |
| 194 | self.media.recycle_upload_staging(buf); |
| 195 | return; |
| 196 | } |
| 197 | } |
| 198 | self.queue.write_texture( |
| 199 | texture.as_image_copy(), |
| 200 | data, |
| 201 | wgpu::TexelCopyBufferLayout { |
| 202 | offset: 0, |
| 203 | bytes_per_row: Some(unpadded_bpr), |
| 204 | rows_per_image: Some(h), |
| 205 | }, |
| 206 | wgpu::Extent3d { |
| 207 | width: w, |
| 208 | height: h, |
| 209 | depth_or_array_layers: 1, |
| 210 | }, |
| 211 | ); |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | pub(super) fn eval_loader( |
| 216 | &mut self, |
| 217 | comp: &Comp, |
| 218 | node: &Node, |
| 219 | time: f64, |
| 220 | frame_i: i64, |
| 221 | enc: &mut wgpu::CommandEncoder, |
| 222 | visiting: &mut HashSet<(NodeId, i64)>, |
| 223 | stats: &mut EvalStats, |
| 224 | ) -> CachedTexture { |
| 225 | let Some(clip) = node.clips.first().cloned() else { |
| 226 | return self.dummy.clone(); |
| 227 | }; |
| 228 | self.eval_loader_with_clip(comp, node, &clip, time, frame_i, enc, visiting, stats) |
| 229 | } |
| 230 | |
| 231 | #[allow(clippy::too_many_arguments)] |
| 232 | pub(super) fn eval_loader_with_clip( |
| 233 | &mut self, |
| 234 | comp: &Comp, |
| 235 | node: &Node, |
| 236 | clip: &model::ClipSpec, |
| 237 | time: f64, |
| 238 | frame_i: i64, |
| 239 | enc: &mut wgpu::CommandEncoder, |
| 240 | visiting: &mut HashSet<(NodeId, i64)>, |
| 241 | stats: &mut EvalStats, |
| 242 | ) -> CachedTexture { |
| 243 | let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5; |
| 244 | let exr_channels = [ |
| 245 | node.static_str("Clip1.OpenEXRFormat.RedName"), |
| 246 | node.static_str("Clip1.OpenEXRFormat.GreenName"), |
| 247 | node.static_str("Clip1.OpenEXRFormat.BlueName"), |
| 248 | node.static_str("Clip1.OpenEXRFormat.AlphaName"), |
| 249 | ]; |
| 250 | // Apply Inspector timing overrides (`GlobalIn`, `GlobalOut`, `Loop`, `Reverse`) on a working copy |
| 251 | // before resolving proxy/sequence paths so live Inspector edits take effect immediately. |
| 252 | let mut effective_clip = clip.clone(); |
| 253 | Self::apply_loader_timing_overrides(comp, node, &mut effective_clip, time, &self.expr); |
| 254 | // When `use_proxy_clips` is enabled, prefer Loader `ProxyFilename` or `Clip.AlternateFilename` |
| 255 | // if the resolved proxy file exists on disk, falling back seamlessly to the primary clip. |
| 256 | if self.use_proxy_clips { |
| 257 | let proxy_candidate = node |
| 258 | .static_str("ProxyFilename") |
| 259 | .filter(|s| !s.trim().is_empty()) |
| 260 | .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty())); |
| 261 | if let Some(proxy_name) = proxy_candidate { |
| 262 | let mut proxy_clip = effective_clip.clone(); |
| 263 | proxy_clip.filename = proxy_name.to_owned(); |
| 264 | if self.media.resolve_clip_path_cached(&proxy_clip, frame_i).is_some() { |
| 265 | effective_clip = proxy_clip; |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | let missing_frames = comp |
| 270 | .eval_number(node, "MissingFrames", time, 0.0, &self.expr) |
| 271 | .round() as i32; |
| 272 | // Outside `[GlobalStart - ExtendFirst, GlobalEnd + ExtendLast]` (with `Loop` allowing |
| 273 | // playback past `GlobalEnd`), Fusion outputs no image regardless of `MissingFrames` or |
| 274 | // whether `Length == 1` (even single-frame stills return empty outside their active range). |
| 275 | let out_of_range = effective_clip.global_end >= effective_clip.global_start |
| 276 | && (frame_i < effective_clip.global_start.saturating_sub(effective_clip.extend_first.max(0)) |
| 277 | || (!effective_clip.loop_clip |
| 278 | && frame_i > effective_clip.global_end.saturating_add(effective_clip.extend_last.max(0)))); |
| 279 | let loaded = if out_of_range { |
| 280 | None |
| 281 | } else { |
| 282 | self.media |
| 283 | .load_clip_media(&effective_clip, frame_i, post_mult, exr_channels) |
| 284 | }; |
| 285 | let Some((resolved, local_idx, media, loaded_from_disk)) = loaded else { |
| 286 | if missing_frames != 1 { |
| 287 | return self.dummy.clone(); |
| 288 | } |
| 289 | // When out-of-range or missing with `MissingFrames = 1` (Output Color), return a |
| 290 | // full-resolution transparent [0,0,0,0] canvas instead of 1x1 dummy so downstream |
| 291 | // Merges preserve full canvas dimensions and keep foreground layers intact. |
| 292 | let dst_depth = self.node_depth(comp, node, time, None); |
| 293 | let mut kh = DefaultHasher::new(); |
| 294 | self.cache.gpu_salt.hash(&mut kh); |
| 295 | self.hiq.hash(&mut kh); |
| 296 | self.cache.node_salt(node.id).hash(&mut kh); |
| 297 | "LoaderMissing".hash(&mut kh); |
| 298 | effective_clip.filename.hash(&mut kh); |
| 299 | effective_clip.global_start.hash(&mut kh); |
| 300 | effective_clip.global_end.hash(&mut kh); |
| 301 | effective_clip.loop_clip.hash(&mut kh); |
| 302 | effective_clip.reverse.hash(&mut kh); |
| 303 | self.proxy_scale.hash(&mut kh); |
| 304 | comp.width.hash(&mut kh); |
| 305 | comp.height.hash(&mut kh); |
| 306 | dst_depth.hash(&mut kh); |
| 307 | let key = kh.finish(); |
| 308 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 309 | stats.cache_hits += 1; |
| 310 | return hit; |
| 311 | } |
| 312 | stats.cache_misses += 1; |
| 313 | stats.nodes_evaluated += 1; |
| 314 | let raw_dims = Self::probe_clip_dims(&effective_clip) |
| 315 | .unwrap_or([comp.width, comp.height]); |
| 316 | let dst_size = self.scaled_dims(raw_dims[0], raw_dims[1]); |
| 317 | let dst = self.alloc_tex(dst_size, dst_depth, key); |
| 318 | let u = UniformParams::default(); |
| 319 | self.dispatch_op(enc, ShaderOp::Bg, &self.dummy.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 320 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 321 | return dst; |
| 322 | }; |
| 323 | if loaded_from_disk { |
| 324 | stats.source_loads += 1; |
| 325 | } |
| 326 | let img_size = media.size(); |
| 327 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(self.scaled_dims(img_size[0], img_size[1])), enc, visiting, stats); |
| 328 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 329 | // OpenEXR clips natively produce float HDR in HiQ unless Loader explicitly forces int8/int16. |
| 330 | let explicit_depth = comp |
| 331 | .eval_number(node, "Depth", time, 0.0, &self.expr) |
| 332 | .round() as i32; |
| 333 | let has_hdr_f32 = matches!(&media, crate::media::CachedMedia::Rgba(img) if img.rgba_f32.is_some()); |
| 334 | let native_depth = if self.hiq && has_hdr_f32 { |
| 335 | BitDepth::from_fusion_depth(explicit_depth).unwrap_or_else(|| { |
| 336 | if comp.depth_full == BitDepth::Float32 { |
| 337 | BitDepth::Float32 |
| 338 | } else { |
| 339 | BitDepth::Float16 |
| 340 | } |
| 341 | }) |
| 342 | } else { |
| 343 | self.node_depth(comp, node, time, None) |
| 344 | }; |
| 345 | let dst_depth = self.effective_depth(native_depth); |
| 346 | let use_float_upload = self.hiq && dst_depth.is_float() && has_hdr_f32; |
| 347 | let target_size = self.scaled_dims(img_size[0], img_size[1]); |
| 348 | let mut h = DefaultHasher::new(); |
| 349 | self.cache.gpu_salt.hash(&mut h); |
| 350 | self.cache.node_salt(node.id).hash(&mut h); |
| 351 | "Loader".hash(&mut h); |
| 352 | resolved.hash(&mut h); |
| 353 | local_idx.hash(&mut h); |
| 354 | effective_clip.global_start.hash(&mut h); |
| 355 | effective_clip.global_end.hash(&mut h); |
| 356 | effective_clip.loop_clip.hash(&mut h); |
| 357 | effective_clip.reverse.hash(&mut h); |
| 358 | post_mult.hash(&mut h); |
| 359 | exr_channels.hash(&mut h); |
| 360 | target_size.hash(&mut h); |
| 361 | mask_hash.hash(&mut h); |
| 362 | mask_inv.hash(&mut h); |
| 363 | dst_depth.hash(&mut h); |
| 364 | use_float_upload.hash(&mut h); |
| 365 | let key = h.finish(); |
| 366 | |
| 367 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 368 | stats.cache_hits += 1; |
| 369 | return hit; |
| 370 | } |
| 371 | stats.cache_misses += 1; |
| 372 | stats.nodes_evaluated += 1; |
| 373 | |
| 374 | let is_nv12 = matches!(&media, crate::media::CachedMedia::Nv12(_)); |
| 375 | let need_depth_conv = !use_float_upload && !is_nv12 && dst_depth != BitDepth::Int8; |
| 376 | let need_post = target_size != img_size || mask.is_some() || need_depth_conv; |
| 377 | let (full_tex, work_depth) = match &media { |
| 378 | crate::media::CachedMedia::Nv12(nv12_frame) => { |
| 379 | // Single-pass GPU YUV->RGBA + rotation writes directly into target bit depth. |
| 380 | let tex = self.alloc_tex(img_size, dst_depth, if need_post { 0 } else { key }); |
| 381 | nv12::upload_and_convert_nv12(self, enc, nv12_frame, &tex); |
| 382 | (tex, dst_depth) |
| 383 | } |
| 384 | crate::media::CachedMedia::Rgba(img) => { |
| 385 | if use_float_upload { |
| 386 | let f32_px = img.rgba_f32.as_ref().expect("checked is_some"); |
| 387 | let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key }); |
| 388 | if tex.format == wgpu::TextureFormat::Rgba32Float { |
| 389 | self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f32_px), 16, img.size); |
| 390 | } else { |
| 391 | let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16"); |
| 392 | self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f16_bits), 8, img.size); |
| 393 | } |
| 394 | (tex, dst_depth) |
| 395 | } else { |
| 396 | let tex = self.alloc_tex(img.size, BitDepth::Int8, if need_post { 0 } else { key }); |
| 397 | self.upload_loader_texture(enc, &tex, &img.rgba, 4, img.size); |
| 398 | (tex, BitDepth::Int8) |
| 399 | } |
| 400 | } |
| 401 | }; |
| 402 | let base_tex = if target_size != img_size { |
| 403 | let scaled = self.alloc_tex(target_size, work_depth, if mask.is_some() || need_depth_conv { 0 } else { key }); |
| 404 | let mut u = UniformParams::default(); |
| 405 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; |
| 406 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &full_tex.view, &self.dummy.view, &self.dummy.view, &scaled, &u); |
| 407 | scaled |
| 408 | } else { |
| 409 | full_tex |
| 410 | }; |
| 411 | let masked_tex = if let Some(m) = mask { |
| 412 | let masked = self.alloc_tex(target_size, work_depth, if need_depth_conv { 0 } else { key }); |
| 413 | let mut u = UniformParams::default(); |
| 414 | u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; |
| 415 | self.dispatch_op(enc, ShaderOp::MaskApply, &base_tex.view, &self.dummy.view, &m.view, &masked, &u); |
| 416 | masked |
| 417 | } else { |
| 418 | base_tex |
| 419 | }; |
| 420 | let mut tex = if need_depth_conv { |
| 421 | let promoted = self.alloc_tex(target_size, dst_depth, key); |
| 422 | let u = UniformParams::default(); |
| 423 | self.dispatch_op(enc, ShaderOp::ChangeDepth, &masked_tex.view, &self.dummy.view, &self.dummy.view, &promoted, &u); |
| 424 | promoted |
| 425 | } else { |
| 426 | masked_tex |
| 427 | }; |
| 428 | if let crate::media::CachedMedia::Rgba(img) = &media { |
| 429 | if let Some(z_vals) = img.z_f32.as_ref() { |
| 430 | let expected_len = (img.size[0] as usize).saturating_mul(img.size[1] as usize); |
| 431 | if z_vals.len() == expected_len && tex.size[0] > 0 && tex.size[1] > 0 { |
| 432 | let z_tex = crate::cache::AuxChannelTex::new( |
| 433 | &self.device, |
| 434 | tex.size, |
| 435 | wgpu::TextureFormat::R32Float, |
| 436 | "loader-aux-z", |
| 437 | ); |
| 438 | if z_tex.size == img.size { |
| 439 | self.upload_raw_texture( |
| 440 | enc, |
| 441 | &z_tex.texture, |
| 442 | bytemuck::cast_slice(z_vals), |
| 443 | 4, |
| 444 | img.size, |
| 445 | ); |
| 446 | } else { |
| 447 | let [sw, sh] = [img.size[0] as usize, img.size[1] as usize]; |
| 448 | let [dw, dh] = [z_tex.size[0] as usize, z_tex.size[1] as usize]; |
| 449 | let mut resampled = Vec::with_capacity(dw * dh); |
| 450 | for dy in 0..dh { |
| 451 | let sy = ((dy * sh) / dh).min(sh.saturating_sub(1)); |
| 452 | for dx in 0..dw { |
| 453 | let sx = ((dx * sw) / dw).min(sw.saturating_sub(1)); |
| 454 | resampled.push(z_vals[sy * sw + sx]); |
| 455 | } |
| 456 | } |
| 457 | self.upload_raw_texture( |
| 458 | enc, |
| 459 | &z_tex.texture, |
| 460 | bytemuck::cast_slice(&resampled), |
| 461 | 4, |
| 462 | z_tex.size, |
| 463 | ); |
| 464 | } |
| 465 | let mut aux = tex.aux_cloned(); |
| 466 | aux.z = Some(z_tex); |
| 467 | tex.set_aux(Some(std::sync::Arc::new(aux))); |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | self.cache.insert(key, tex.clone(), node.id, frame_i); |
| 472 | tex |
| 473 | } |
| 474 | |
| 475 | pub(super) fn resolve_upstream_exr_path(&self, comp: &Comp, start_id: NodeId, time: f64) -> Option<std::path::PathBuf> { |
| 476 | let mut cur_id = start_id; |
| 477 | let mut cur_time = time; |
| 478 | for _ in 0..16 { |
| 479 | let n = comp.node(cur_id); |
| 480 | match n.kind.as_str() { |
| 481 | "Loader" => { |
| 482 | let clip = n.clips.first()?; |
| 483 | let mut effective_clip = clip.clone(); |
| 484 | Self::apply_loader_timing_overrides(comp, n, &mut effective_clip, cur_time, &self.expr); |
| 485 | let resolved = crate::media::resolve_clip_path(&effective_clip, cur_time.round() as i64)?; |
| 486 | if resolved |
| 487 | .extension() |
| 488 | .and_then(|e| e.to_str()) |
| 489 | .is_some_and(|e| e.eq_ignore_ascii_case("exr")) |
| 490 | { |
| 491 | return Some(resolved); |
| 492 | } |
| 493 | return None; |
| 494 | } |
| 495 | "TimeStretcher" | "TimeSpeed" => { |
| 496 | cur_time = self.remap_time_node(comp, n, cur_time).unwrap_or(cur_time); |
| 497 | cur_id = n.connected_node("Input").and_then(|s| comp.find_node(s))?; |
| 498 | } |
| 499 | "PipeRouter" | "Fuse.Wireless" | "Dimension.OpticalFlow" | "OpticalFlow" | "GamutConvert" |
| 500 | | "ChangeDepth" | "BrightnessContrast" | "ColorCorrector" | "ColorGain" => { |
| 501 | cur_id = n.connected_node("Input").and_then(|s| comp.find_node(s))?; |
| 502 | } |
| 503 | _ => return None, |
| 504 | } |
| 505 | } |
| 506 | None |
| 507 | } |
| 508 | |
| 509 | #[allow(clippy::too_many_arguments)] |
| 510 | pub(super) fn eval_cryptomatte( |
| 511 | &mut self, |
| 512 | comp: &Comp, |
| 513 | node: &Node, |
| 514 | time: f64, |
| 515 | frame_i: i64, |
| 516 | enc: &mut wgpu::CommandEncoder, |
| 517 | visiting: &mut HashSet<(NodeId, i64)>, |
| 518 | stats: &mut EvalStats, |
| 519 | ) -> CachedTexture { |
| 520 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 521 | return self.dummy.clone(); |
| 522 | }; |
| 523 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 524 | let matte_list = comp.eval_text(node, "MatteList", time, "", &self.expr); |
| 525 | let layer_name = comp.eval_text(node, "LayerName", time, "", &self.expr); |
| 526 | let matte_only = comp.eval_number(node, "MatteOnly", time, 0.0, &self.expr) > 0.5; |
| 527 | let Some(exr_path) = self.resolve_upstream_exr_path(comp, src_id, time) else { |
| 528 | return src; |
| 529 | }; |
| 530 | |
| 531 | let dst_depth = self.node_depth(comp, node, time, Some(src.depth)); |
| 532 | let mut h = DefaultHasher::new(); |
| 533 | self.cache.gpu_salt.hash(&mut h); |
| 534 | self.cache.node_salt(node.id).hash(&mut h); |
| 535 | "Fuse.Cryptomatte".hash(&mut h); |
| 536 | src.content_hash.hash(&mut h); |
| 537 | exr_path.hash(&mut h); |
| 538 | matte_list.hash(&mut h); |
| 539 | layer_name.hash(&mut h); |
| 540 | matte_only.hash(&mut h); |
| 541 | dst_depth.hash(&mut h); |
| 542 | let key = h.finish(); |
| 543 | |
| 544 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 545 | stats.cache_hits += 1; |
| 546 | return hit; |
| 547 | } |
| 548 | stats.cache_misses += 1; |
| 549 | stats.nodes_evaluated += 1; |
| 550 | |
| 551 | let layer_opt = if layer_name.trim().is_empty() { |
| 552 | None |
| 553 | } else { |
| 554 | Some(layer_name.as_str()) |
| 555 | }; |
| 556 | let Some(cm) = crate::cryptomatte::extract_cryptomatte(&exr_path, layer_opt, &matte_list) else { |
| 557 | return src; |
| 558 | }; |
| 559 | |
| 560 | let mut matte_rgba = vec![0u8; (cm.size[0] as usize) * (cm.size[1] as usize) * 4]; |
| 561 | for (i, &m) in cm.matte.iter().enumerate() { |
| 562 | let b = (m.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; |
| 563 | matte_rgba[i * 4] = b; |
| 564 | matte_rgba[i * 4 + 1] = b; |
| 565 | matte_rgba[i * 4 + 2] = b; |
| 566 | matte_rgba[i * 4 + 3] = b; |
| 567 | } |
| 568 | |
| 569 | let matte_full = create_texture(&self.device, cm.size, 0); |
| 570 | self.queue.write_texture( |
| 571 | matte_full.texture.as_image_copy(), |
| 572 | &matte_rgba, |
| 573 | wgpu::TexelCopyBufferLayout { |
| 574 | offset: 0, |
| 575 | bytes_per_row: Some(cm.size[0] * 4), |
| 576 | rows_per_image: Some(cm.size[1]), |
| 577 | }, |
| 578 | wgpu::Extent3d { |
| 579 | width: cm.size[0], |
| 580 | height: cm.size[1], |
| 581 | depth_or_array_layers: 1, |
| 582 | }, |
| 583 | ); |
| 584 | |
| 585 | let matte_tex = if cm.size != src.size { |
| 586 | let scaled = create_texture(&self.device, src.size, 0); |
| 587 | let mut u = UniformParams::default(); |
| 588 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; |
| 589 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &matte_full.view, &self.dummy.view, &self.dummy.view, &scaled, &u); |
| 590 | scaled |
| 591 | } else { |
| 592 | matte_full |
| 593 | }; |
| 594 | |
| 595 | let out = if matte_only { |
| 596 | let dst = self.alloc_tex_like(&src, dst_depth, key); |
| 597 | let mut u = UniformParams::default(); |
| 598 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; |
| 599 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &matte_tex.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 600 | dst |
| 601 | } else { |
| 602 | let dst = self.alloc_tex_like(&src, dst_depth, key); |
| 603 | let mut u = UniformParams::default(); |
| 604 | u.p[0] = [0.0, 0.0, 0.0, 0.0]; |
| 605 | self.dispatch_op(enc, ShaderOp::MaskApply, &src.view, &self.dummy.view, &matte_tex.view, &dst, &u); |
| 606 | dst |
| 607 | }; |
| 608 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 609 | out |
| 610 | } |
| 611 | |
| 612 | pub(super) fn eval_background( |
| 613 | &mut self, |
| 614 | comp: &Comp, |
| 615 | node: &Node, |
| 616 | time: f64, |
| 617 | frame_i: i64, |
| 618 | comp_dims: [u32; 2], |
| 619 | enc: &mut wgpu::CommandEncoder, |
| 620 | visiting: &mut HashSet<(NodeId, i64)>, |
| 621 | stats: &mut EvalStats, |
| 622 | ) -> CachedTexture { |
| 623 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; |
| 624 | let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32; |
| 625 | let size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; |
| 626 | |
| 627 | let tl = [ |
| 628 | comp.eval_number(node, "TopLeftRed", time, 0.0, &self.expr) as f32, |
| 629 | comp.eval_number(node, "TopLeftGreen", time, 0.0, &self.expr) as f32, |
| 630 | comp.eval_number(node, "TopLeftBlue", time, 0.0, &self.expr) as f32, |
| 631 | comp.eval_number(node, "TopLeftAlpha", time, 1.0, &self.expr) as f32, |
| 632 | ]; |
| 633 | let tr = [ |
| 634 | comp.eval_number(node, "TopRightRed", time, 0.0, &self.expr) as f32, |
| 635 | comp.eval_number(node, "TopRightGreen", time, 0.0, &self.expr) as f32, |
| 636 | comp.eval_number(node, "TopRightBlue", time, 0.0, &self.expr) as f32, |
| 637 | comp.eval_number(node, "TopRightAlpha", time, 1.0, &self.expr) as f32, |
| 638 | ]; |
| 639 | let bl = [ |
| 640 | comp.eval_number(node, "BottomLeftRed", time, 0.0, &self.expr) as f32, |
| 641 | comp.eval_number(node, "BottomLeftGreen", time, 0.0, &self.expr) as f32, |
| 642 | comp.eval_number(node, "BottomLeftBlue", time, 0.0, &self.expr) as f32, |
| 643 | comp.eval_number(node, "BottomLeftAlpha", time, 1.0, &self.expr) as f32, |
| 644 | ]; |
| 645 | let br = [ |
| 646 | comp.eval_number(node, "BottomRightRed", time, 0.0, &self.expr) as f32, |
| 647 | comp.eval_number(node, "BottomRightGreen", time, 0.0, &self.expr) as f32, |
| 648 | comp.eval_number(node, "BottomRightBlue", time, 0.0, &self.expr) as f32, |
| 649 | comp.eval_number(node, "BottomRightAlpha", time, 1.0, &self.expr) as f32, |
| 650 | ]; |
| 651 | |
| 652 | let type_str = node.static_str("Type"); |
| 653 | let empty_fuid = matches!(type_str, Some("")); |
| 654 | let mut kind = if empty_fuid { |
| 655 | 0.0 |
| 656 | } else { |
| 657 | match type_str.unwrap_or("Solid") { |
| 658 | "Horizontal" => 1.0, |
| 659 | "Vertical" => 2.0, |
| 660 | "Corner" => 3.0, |
| 661 | "Gradient" => match node.static_str("GradientType").unwrap_or("Linear") { |
| 662 | "Radial" => 5.0, |
| 663 | "Angle" => 6.0, |
| 664 | "Reflect" => 7.0, |
| 665 | _ => 4.0, |
| 666 | }, |
| 667 | _ => 0.0, |
| 668 | } |
| 669 | }; |
| 670 | let mut c0 = if empty_fuid { [0.0, 0.0, 0.0, 0.0] } else { tl }; |
| 671 | let mut c1 = tr; |
| 672 | let mut grad_lut_f16: Option<[u16; 512 * 4]> = None; |
| 673 | let mut grad_hash = 0u64; |
| 674 | if kind >= 4.0 { |
| 675 | if let Some(grad) = comp.eval_gradient(node, "Gradient", time) { |
| 676 | c0 = grad.sample(0.0); |
| 677 | c1 = grad.sample(1.0); |
| 678 | let mut lut = [0u16; 512 * 4]; |
| 679 | for i in 0..512 { |
| 680 | let t = i as f64 / 511.0; |
| 681 | let c = grad.sample(t); |
| 682 | lut[i * 4] = crate::media::f32_to_f16_bits(c[0]); |
| 683 | lut[i * 4 + 1] = crate::media::f32_to_f16_bits(c[1]); |
| 684 | lut[i * 4 + 2] = crate::media::f32_to_f16_bits(c[2]); |
| 685 | lut[i * 4 + 3] = crate::media::f32_to_f16_bits(c[3]); |
| 686 | } |
| 687 | let mut gh = DefaultHasher::new(); |
| 688 | lut.hash(&mut gh); |
| 689 | grad_hash = gh.finish(); |
| 690 | grad_lut_f16 = Some(lut); |
| 691 | } else { |
| 692 | kind = 0.0; |
| 693 | } |
| 694 | } |
| 695 | let start = comp.eval_point(node, "Start", time, [0.0, 0.5], &self.expr); |
| 696 | let end = comp.eval_point(node, "End", time, [1.0, 0.5], &self.expr); |
| 697 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 698 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 699 | |
| 700 | let mut u = UniformParams::default(); |
| 701 | u.p[0] = c0; |
| 702 | u.p[1] = c1; |
| 703 | u.p[2] = bl; |
| 704 | u.p[3] = br; |
| 705 | u.p[4] = [kind, if grad_lut_f16.is_some() { 1.0 } else { 0.0 }, start[0] as f32, start[1] as f32]; |
| 706 | u.p[5] = [ |
| 707 | end[0] as f32, |
| 708 | end[1] as f32, |
| 709 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 710 | if mask_inv { 1.0 } else { 0.0 }, |
| 711 | ]; |
| 712 | |
| 713 | let dst_depth = self.node_depth(comp, node, time, None); |
| 714 | let key = self.make_key(node, "Background", size, &[mask_hash, dst_depth as u64, grad_hash], bytemuck::cast_slice(&u.p[..6])); |
| 715 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 716 | stats.cache_hits += 1; |
| 717 | return hit; |
| 718 | } |
| 719 | stats.cache_misses += 1; |
| 720 | stats.nodes_evaluated += 1; |
| 721 | |
| 722 | let lut_tex = grad_lut_f16.map(|lut| { |
| 723 | let t = create_texture_dod_fmt( |
| 724 | &self.device, |
| 725 | [512, 1], |
| 726 | [0, 0], |
| 727 | [512, 1], |
| 728 | BitDepth::Float16, |
| 729 | wgpu::TextureFormat::Rgba16Float, |
| 730 | 0, |
| 731 | ); |
| 732 | self.queue.write_texture( |
| 733 | t.texture.as_image_copy(), |
| 734 | bytemuck::cast_slice(&lut), |
| 735 | wgpu::TexelCopyBufferLayout { |
| 736 | offset: 0, |
| 737 | bytes_per_row: Some(512 * 8), |
| 738 | rows_per_image: Some(1), |
| 739 | }, |
| 740 | wgpu::Extent3d { |
| 741 | width: 512, |
| 742 | height: 1, |
| 743 | depth_or_array_layers: 1, |
| 744 | }, |
| 745 | ); |
| 746 | t |
| 747 | }); |
| 748 | |
| 749 | let dst = self.alloc_tex(size, dst_depth, key); |
| 750 | let lut_view = lut_tex.as_ref().map_or(&self.dummy.view, |t| &t.view); |
| 751 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 752 | self.dispatch_op(enc, ShaderOp::Bg, &self.dummy.view, lut_view, mv, &dst, &u); |
| 753 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 754 | dst |
| 755 | } |
| 756 | |
| 757 | pub(super) fn eval_scale( |
| 758 | &mut self, |
| 759 | comp: &Comp, |
| 760 | node: &Node, |
| 761 | time: f64, |
| 762 | frame_i: i64, |
| 763 | comp_dims: [u32; 2], |
| 764 | enc: &mut wgpu::CommandEncoder, |
| 765 | visiting: &mut HashSet<(NodeId, i64)>, |
| 766 | stats: &mut EvalStats, |
| 767 | ) -> CachedTexture { |
| 768 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 769 | return self.dummy.clone(); |
| 770 | }; |
| 771 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 772 | let hiq_only = comp.eval_number(node, "HiQOnly", time, 0.0, &self.expr) > 0.5; |
| 773 | if !self.hiq && hiq_only && node.kind == "Scale" { |
| 774 | return src; |
| 775 | } |
| 776 | let src = self.crop_to_canvas(enc, src); |
| 777 | let max_dim = self.device.limits().max_texture_dimension_2d; |
| 778 | // Non-finite or huge factors clamp to the largest texture the device can hold. |
| 779 | let side = |v: f64| if v.is_nan() { 1 } else { v.clamp(1.0, max_dim as f64) as u32 }; |
| 780 | let dst_size = if node.kind == "BetterResize" { |
| 781 | let w = comp.eval_number(node, "Width", time, comp_dims[0] as f64, &self.expr); |
| 782 | let h = comp.eval_number(node, "Height", time, comp_dims[1] as f64, &self.expr); |
| 783 | self.scaled_dims(side(w), side(h)) |
| 784 | } else { |
| 785 | let sx = comp.eval_number(node, "XSize", time, 1.0, &self.expr); |
| 786 | let sy = if comp.eval_number(node, "LockXY", time, 1.0, &self.expr) > 0.5 { |
| 787 | sx |
| 788 | } else { |
| 789 | comp.eval_number(node, "YSize", time, 1.0, &self.expr) |
| 790 | }; |
| 791 | // Fusion rounds each side up to the next size with the source's parity so the image center stays pixel-aligned. |
| 792 | let scaled = |src: u32, s: f64| { |
| 793 | let n = side((src as f64 * s - 1e-4).ceil()); |
| 794 | if (n + src) % 2 == 1 && n < max_dim { n + 1 } else { n } |
| 795 | }; |
| 796 | [scaled(src.size[0], sx), scaled(src.size[1], sy)] |
| 797 | }; |
| 798 | let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 }; |
| 799 | let mut u = UniformParams::default(); |
| 800 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; |
| 801 | u.p[2] = [nearest, 0.0, 0.0, 0.0]; |
| 802 | let key = self.make_key(node, "Scale", dst_size, &[src.content_hash], &[nearest]); |
| 803 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 804 | stats.cache_hits += 1; |
| 805 | return hit; |
| 806 | } |
| 807 | stats.cache_misses += 1; |
| 808 | stats.nodes_evaluated += 1; |
| 809 | let dst = self.alloc_tex(dst_size, src.depth, key); |
| 810 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 811 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 812 | dst |
| 813 | } |
| 814 | |
| 815 | pub(super) fn eval_crop( |
| 816 | &mut self, |
| 817 | comp: &Comp, |
| 818 | node: &Node, |
| 819 | time: f64, |
| 820 | frame_i: i64, |
| 821 | enc: &mut wgpu::CommandEncoder, |
| 822 | visiting: &mut HashSet<(NodeId, i64)>, |
| 823 | stats: &mut EvalStats, |
| 824 | ) -> CachedTexture { |
| 825 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 826 | return self.dummy.clone(); |
| 827 | }; |
| 828 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 829 | let keep_aspect = comp.eval_number(node, "KeepAspect", time, 0.0, &self.expr) > 0.5; |
| 830 | let keep_centered = comp.eval_number(node, "KeepCentered", time, 0.0, &self.expr) > 0.5; |
| 831 | let ps = self.proxy_scale.max(1) as f64; |
| 832 | let x_size_f = comp |
| 833 | .eval_number(node, "XSize", time, src.canvas_size[0] as f64 * ps, &self.expr) |
| 834 | .round() |
| 835 | .max(1.0); |
| 836 | let y_size_f = if keep_aspect { |
| 837 | (x_size_f * src.canvas_size[1].max(1) as f64 / src.canvas_size[0].max(1) as f64) |
| 838 | .round() |
| 839 | .max(1.0) |
| 840 | } else { |
| 841 | comp.eval_number(node, "YSize", time, src.canvas_size[1] as f64 * ps, &self.expr) |
| 842 | .round() |
| 843 | .max(1.0) |
| 844 | }; |
| 845 | let x_size = x_size_f as u32; |
| 846 | let y_size = y_size_f as u32; |
| 847 | let dst_size = self.scaled_dims(x_size, y_size); |
| 848 | let (x_off, y_off) = if keep_centered { |
| 849 | ( |
| 850 | (src.canvas_size[0] as f32 - dst_size[0] as f32) * 0.5, |
| 851 | (src.canvas_size[1] as f32 - dst_size[1] as f32) * 0.5, |
| 852 | ) |
| 853 | } else { |
| 854 | ( |
| 855 | comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32 / ps as f32, |
| 856 | comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32 / ps as f32, |
| 857 | ) |
| 858 | }; |
| 859 | |
| 860 | let mut u = UniformParams::default(); |
| 861 | u.p[0] = [x_off, y_off, 1.0, 1.0]; |
| 862 | if src.has_dod() { |
| 863 | u.p[1] = [src.origin[0] as f32, src.origin[1] as f32, src.canvas_size[0] as f32, src.canvas_size[1] as f32]; |
| 864 | } |
| 865 | let key = self.make_key(node, "Crop", dst_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..2])); |
| 866 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 867 | stats.cache_hits += 1; |
| 868 | return hit; |
| 869 | } |
| 870 | stats.cache_misses += 1; |
| 871 | stats.nodes_evaluated += 1; |
| 872 | let dst = self.alloc_tex(dst_size, src.depth, key); |
| 873 | self.dispatch_op(enc, ShaderOp::Crop, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 874 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 875 | dst |
| 876 | } |
| 877 | |
| 878 | pub(super) fn eval_fast_noise( |
| 879 | &mut self, |
| 880 | comp: &Comp, |
| 881 | node: &Node, |
| 882 | time: f64, |
| 883 | frame_i: i64, |
| 884 | comp_dims: [u32; 2], |
| 885 | enc: &mut wgpu::CommandEncoder, |
| 886 | stats: &mut EvalStats, |
| 887 | ) -> CachedTexture { |
| 888 | let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr) as u32; |
| 889 | let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr) as u32; |
| 890 | let mut size = if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims }; |
| 891 | // Cap giant procedural sky-dome FastNoise textures (e.g. 11520x4000) to 8192 in HiQ / 4096 in Fast |
| 892 | let cap = if self.hiq { 8192 } else { 4096 }; |
| 893 | let max_dim = size[0].max(size[1]); |
| 894 | let mut tex_scale = 1.0_f32; |
| 895 | if max_dim > cap { |
| 896 | let scale = cap as f32 / max_dim as f32; |
| 897 | tex_scale = scale; |
| 898 | size = [((size[0] as f32 * scale).round() as u32).max(1), ((size[1] as f32 * scale).round() as u32).max(1)]; |
| 899 | } |
| 900 | |
| 901 | let lock_xy = comp.eval_number(node, "LockXY", time, 1.0, &self.expr) > 0.5; |
| 902 | let x_scale = comp.eval_number(node, "XScale", time, 2.0, &self.expr) as f32; |
| 903 | let y_scale = if lock_xy { |
| 904 | x_scale |
| 905 | } else { |
| 906 | comp.eval_number(node, "YScale", time, x_scale as f64, &self.expr) as f32 |
| 907 | }; |
| 908 | let detail = comp.eval_number(node, "Detail", time, 2.0, &self.expr) as f32; |
| 909 | let contrast = comp.eval_number(node, "Contrast", time, 1.0, &self.expr) as f32; |
| 910 | let brightness = comp.eval_number(node, "Brightness", time, 0.0, &self.expr) as f32; |
| 911 | let seethe = (comp.eval_number(node, "Seethe", time, 0.0, &self.expr) |
| 912 | + comp.eval_number(node, "SeetheRate", time, 0.0, &self.expr) * time * 0.1) as f32; |
| 913 | let disc = comp.eval_number(node, "Discontinuous", time, 0.0, &self.expr) as f32; |
| 914 | let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); |
| 915 | let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); |
| 916 | let inverted = comp.eval_number(node, "Inverted", time, 0.0, &self.expr) as f32; |
| 917 | |
| 918 | let c1 = [ |
| 919 | comp.eval_number(node, "Color1Red", time, 0.0, &self.expr) as f32, |
| 920 | comp.eval_number(node, "Color1Green", time, 0.0, &self.expr) as f32, |
| 921 | comp.eval_number(node, "Color1Blue", time, 0.0, &self.expr) as f32, |
| 922 | comp.eval_number(node, "Color1Alpha", time, 0.0, &self.expr) as f32, |
| 923 | ]; |
| 924 | let c2 = [ |
| 925 | comp.eval_number(node, "Color2Red", time, 1.0, &self.expr) as f32, |
| 926 | comp.eval_number(node, "Color2Green", time, 1.0, &self.expr) as f32, |
| 927 | comp.eval_number(node, "Color2Blue", time, 1.0, &self.expr) as f32, |
| 928 | comp.eval_number(node, "Color2Alpha", time, 1.0, &self.expr) as f32, |
| 929 | ]; |
| 930 | let noise_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as i32; |
| 931 | let grad = if noise_type == 1 { comp.eval_gradient(node, "Gradient", time) } else { None }; |
| 932 | |
| 933 | let dst_depth = self.node_depth(comp, node, time, None); |
| 934 | let mut u = UniformParams::default(); |
| 935 | u.p[0] = [x_scale, y_scale, detail, contrast]; |
| 936 | u.p[1] = [brightness, seethe, disc, center[0] as f32]; |
| 937 | u.p[2] = [center[1] as f32, angle, inverted, if noise_type == 1 { 2.0 } else { 1.0 }]; |
| 938 | u.p[3] = c1; |
| 939 | u.p[4] = c2; |
| 940 | |
| 941 | // Gradient mode only: 256x1 RGBA LUT so sharp thresholds (e.g. 0.95..0.96 stars) stay exact. |
| 942 | let lut = (noise_type == 1).then(|| { |
| 943 | let mut bytes = [0u8; 256 * 4]; |
| 944 | for (i, texel) in bytes.chunks_exact_mut(4).enumerate() { |
| 945 | let t = i as f64 / 255.0; |
| 946 | // Without a Gradient input Fusion uses an opaque black-to-white ramp, ignoring Color1/Color2. |
| 947 | let c = grad.as_ref().map_or([t as f32, t as f32, t as f32, 1.0], |g| g.sample(t)); |
| 948 | for (b, v) in texel.iter_mut().zip(c) { |
| 949 | *b = (v.clamp(0.0, 1.0) * 255.0).round() as u8; |
| 950 | } |
| 951 | } |
| 952 | let mut gh = DefaultHasher::new(); |
| 953 | bytes.hash(&mut gh); |
| 954 | (bytes, gh.finish()) |
| 955 | }); |
| 956 | let grad_hash = lut.as_ref().map_or(0, |l| l.1); |
| 957 | |
| 958 | let key = self.make_key(node, "FastNoise", size, &[grad_hash, dst_depth as u64], bytemuck::cast_slice(&u.p[..5])); |
| 959 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 960 | stats.cache_hits += 1; |
| 961 | return hit; |
| 962 | } |
| 963 | stats.cache_misses += 1; |
| 964 | stats.nodes_evaluated += 1; |
| 965 | let lut_tex = lut.map(|(bytes, _)| { |
| 966 | let tex = create_texture(&self.device, [256, 1], 0); |
| 967 | self.queue.write_texture( |
| 968 | tex.texture.as_image_copy(), |
| 969 | &bytes, |
| 970 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256 * 4), rows_per_image: Some(1) }, |
| 971 | wgpu::Extent3d { width: 256, height: 1, depth_or_array_layers: 1 }, |
| 972 | ); |
| 973 | tex |
| 974 | }); |
| 975 | let mut dst = self.alloc_tex(size, dst_depth, key); |
| 976 | dst.tex_scale *= tex_scale; |
| 977 | let lut_view = lut_tex.as_ref().map_or(&self.dummy.view, |t| &t.view); |
| 978 | self.dispatch_op(enc, ShaderOp::FastNoise, &self.dummy.view, lut_view, &self.dummy.view, &dst, &u); |
| 979 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 980 | dst |
| 981 | } |
| 982 | |
| 983 | #[allow(clippy::too_many_arguments)] |
| 984 | pub(super) fn eval_plasma( |
| 985 | &mut self, |
| 986 | comp: &Comp, |
| 987 | node: &Node, |
| 988 | time: f64, |
| 989 | frame_i: i64, |
| 990 | comp_dims: [u32; 2], |
| 991 | enc: &mut wgpu::CommandEncoder, |
| 992 | visiting: &mut HashSet<(NodeId, i64)>, |
| 993 | stats: &mut EvalStats, |
| 994 | ) -> CachedTexture { |
| 995 | let use_frame_format = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5; |
| 996 | let w = if use_frame_format { |
| 997 | comp.width |
| 998 | } else { |
| 999 | comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32 |
| 1000 | }; |
| 1001 | let h = if use_frame_format { |
| 1002 | comp.height |
| 1003 | } else { |
| 1004 | comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32 |
| 1005 | }; |
| 1006 | let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) }; |
| 1007 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 1008 | |
| 1009 | let c1 = comp.eval_point(node, "Circle1Center", time, [0.33, 0.67], &self.expr); |
| 1010 | let c2 = comp.eval_point(node, "Circle2Center", time, [0.67, 0.67], &self.expr); |
| 1011 | let c3 = comp.eval_point(node, "Circle3Center", time, [0.67, 0.33], &self.expr); |
| 1012 | let c4 = comp.eval_point(node, "Circle4Center", time, [0.33, 0.33], &self.expr); |
| 1013 | let s1 = comp.eval_number(node, "Circle1Scale", time, 1.0, &self.expr) as f32; |
| 1014 | let s2 = comp.eval_number(node, "Circle2Scale", time, 1.0, &self.expr) as f32; |
| 1015 | let s3 = comp.eval_number(node, "Circle3Scale", time, 1.0, &self.expr) as f32; |
| 1016 | let s4 = comp.eval_number(node, "Circle4Scale", time, 1.0, &self.expr) as f32; |
| 1017 | let t1 = comp.eval_number(node, "Circle1Type", time, 1.0, &self.expr) as f32; |
| 1018 | let t2 = comp.eval_number(node, "Circle2Type", time, 2.0, &self.expr) as f32; |
| 1019 | let t3 = comp.eval_number(node, "Circle3Type", time, 2.0, &self.expr) as f32; |
| 1020 | let t4 = comp.eval_number(node, "Circle4Type", time, 2.0, &self.expr) as f32; |
| 1021 | let scale = comp.eval_number(node, "Scale", time, 1.0, &self.expr) as f32; |
| 1022 | let phase = comp.eval_number(node, "Phase", time, 0.0, &self.expr) as f32; |
| 1023 | let r_phase = comp.eval_number(node, "RedPhase", time, 0.0625, &self.expr) as f32; |
| 1024 | let g_phase = comp.eval_number(node, "GreenPhase", time, 0.1875, &self.expr) as f32; |
| 1025 | let b_phase = comp.eval_number(node, "BluePhase", time, 0.3125, &self.expr) as f32; |
| 1026 | let a_phase = comp.eval_number(node, "AlphaPhase", time, 0.4375, &self.expr) as f32; |
| 1027 | |
| 1028 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 1029 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 1030 | |
| 1031 | let mut u = UniformParams::default(); |
| 1032 | u.p[0] = [c1[0] as f32, c1[1] as f32, s1, t1]; |
| 1033 | u.p[1] = [c2[0] as f32, c2[1] as f32, s2, t2]; |
| 1034 | u.p[2] = [c3[0] as f32, c3[1] as f32, s3, t3]; |
| 1035 | u.p[3] = [c4[0] as f32, c4[1] as f32, s4, t4]; |
| 1036 | u.p[4] = [scale, phase, r_phase, g_phase]; |
| 1037 | u.p[5] = [b_phase, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; |
| 1038 | u.p[6][0] = a_phase; |
| 1039 | u.p[6][1] = comp.eval_number(node, "Operation", time, 0.0, &self.expr).round() as f32; |
| 1040 | |
| 1041 | let dst_depth = self.node_depth(comp, node, time, None); |
| 1042 | let key = self.make_key(node, "Plasma", size, &[mask_hash, dst_depth as u64], bytemuck::cast_slice(&u.p[..7])); |
| 1043 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1044 | stats.cache_hits += 1; |
| 1045 | return hit; |
| 1046 | } |
| 1047 | stats.cache_misses += 1; |
| 1048 | stats.nodes_evaluated += 1; |
| 1049 | let dst = self.alloc_tex(size, dst_depth, key); |
| 1050 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 1051 | self.dispatch_op(enc, ShaderOp::Plasma, &self.dummy.view, &self.dummy.view, mv, &dst, &u); |
| 1052 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1053 | dst |
| 1054 | } |
| 1055 | |
| 1056 | pub(super) fn eval_set_domain( |
| 1057 | &mut self, |
| 1058 | comp: &Comp, |
| 1059 | node: &Node, |
| 1060 | time: f64, |
| 1061 | frame_i: i64, |
| 1062 | enc: &mut wgpu::CommandEncoder, |
| 1063 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1064 | stats: &mut EvalStats, |
| 1065 | ) -> CachedTexture { |
| 1066 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 1067 | return self.dummy.clone(); |
| 1068 | }; |
| 1069 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 1070 | let mode = node.static_str("Mode").unwrap_or("Adjust"); |
| 1071 | let (left, bottom, right, top) = if mode.eq_ignore_ascii_case("Set") { |
| 1072 | ( |
| 1073 | comp.eval_number(node, "Left", time, 0.0, &self.expr), |
| 1074 | comp.eval_number(node, "Bottom", time, 0.0, &self.expr), |
| 1075 | comp.eval_number(node, "Right", time, 1.0, &self.expr), |
| 1076 | comp.eval_number(node, "Top", time, 1.0, &self.expr), |
| 1077 | ) |
| 1078 | } else { |
| 1079 | let cw = src.canvas_size[0].max(1) as f64; |
| 1080 | let ch = src.canvas_size[1].max(1) as f64; |
| 1081 | let cur_l = src.origin[0] as f64 / cw; |
| 1082 | let cur_r = (src.origin[0] + src.size[0] as i32) as f64 / cw; |
| 1083 | let cur_t = 1.0 - src.origin[1] as f64 / ch; |
| 1084 | let cur_b = 1.0 - (src.origin[1] + src.size[1] as i32) as f64 / ch; |
| 1085 | ( |
| 1086 | cur_l + comp.eval_number(node, "AdjustLeft", time, 0.0, &self.expr), |
| 1087 | cur_b + comp.eval_number(node, "AdjustBottom", time, 0.0, &self.expr), |
| 1088 | cur_r + comp.eval_number(node, "AdjustRight", time, 0.0, &self.expr), |
| 1089 | cur_t + comp.eval_number(node, "AdjustTop", time, 0.0, &self.expr), |
| 1090 | ) |
| 1091 | }; |
| 1092 | let cw = src.canvas_size[0].max(1) as f64; |
| 1093 | let ch = src.canvas_size[1].max(1) as f64; |
| 1094 | let clip_mode = node.static_str("Clip").unwrap_or("None"); |
| 1095 | let clip_to_frame = clip_mode.eq_ignore_ascii_case("Frame"); |
| 1096 | |
| 1097 | let (dl, db, dr, dt) = if clip_to_frame { |
| 1098 | (left.max(0.0), bottom.max(0.0), right.min(1.0), top.min(1.0)) |
| 1099 | } else { |
| 1100 | (left, bottom, right, top) |
| 1101 | }; |
| 1102 | |
| 1103 | // If requested domain covers or exceeds the entire existing source image (and source has no DoD), |
| 1104 | // Fusion SetDomain does not inject opaque/black border pixels that would darken frame-clamped blurs. |
| 1105 | if !src.has_dod() && dl <= 1e-4 && db <= 1e-4 && dr >= 1.0 - 1e-4 && dt >= 1.0 - 1e-4 { |
| 1106 | return src; |
| 1107 | } |
| 1108 | // Determine output DoD texture rectangle: expand beyond [0,1] when source already has DoD, or keep canvas size when shrinking |
| 1109 | let need_expand = src.has_dod() && (dl < -1e-4 || db < -1e-4 || dr > 1.0 + 1e-4 || dt > 1.0 + 1e-4); |
| 1110 | let (out_origin, out_size) = if need_expand { |
| 1111 | let x0 = (dl.min(0.0) * cw).floor() as i32; |
| 1112 | let x1 = (dr.max(1.0) * cw).ceil() as i32; |
| 1113 | let y0 = ((1.0 - dt.max(1.0)) * ch).floor() as i32; |
| 1114 | let y1 = ((1.0 - db.min(0.0)) * ch).ceil() as i32; |
| 1115 | let w = x1.saturating_sub(x0).clamp(1, 8192) as u32; |
| 1116 | let h = y1.saturating_sub(y0).clamp(1, 8192) as u32; |
| 1117 | ([x0, y0], [w, h]) |
| 1118 | } else { |
| 1119 | ([0, 0], src.canvas_size) |
| 1120 | }; |
| 1121 | |
| 1122 | let mut u = UniformParams::default(); |
| 1123 | u.p[0] = [dl as f32, db as f32, dr as f32, dt as f32]; |
| 1124 | u.p[1] = [out_origin[0] as f32, out_origin[1] as f32, cw as f32, ch as f32]; |
| 1125 | u.p[2] = [src.origin[0] as f32, src.origin[1] as f32, src.size[0] as f32, src.size[1] as f32]; |
| 1126 | |
| 1127 | let key = self.make_key(node, "SetDomain", out_size, &[src.content_hash], bytemuck::cast_slice(&u.p[..3])); |
| 1128 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1129 | stats.cache_hits += 1; |
| 1130 | return hit; |
| 1131 | } |
| 1132 | stats.cache_misses += 1; |
| 1133 | stats.nodes_evaluated += 1; |
| 1134 | let mut dst = self.alloc_tex_dod(out_size, out_origin, src.canvas_size, src.depth, key); |
| 1135 | dst.tex_scale *= src.tex_scale; |
| 1136 | self.dispatch_op(enc, ShaderOp::SetDomain, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 1137 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1138 | dst |
| 1139 | } |
| 1140 | |
| 1141 | pub(super) fn eval_change_depth( |
| 1142 | &mut self, |
| 1143 | comp: &Comp, |
| 1144 | node: &Node, |
| 1145 | time: f64, |
| 1146 | frame_i: i64, |
| 1147 | enc: &mut wgpu::CommandEncoder, |
| 1148 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1149 | stats: &mut EvalStats, |
| 1150 | ) -> CachedTexture { |
| 1151 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 1152 | return self.dummy.clone(); |
| 1153 | }; |
| 1154 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 1155 | let depth_code = comp.eval_number(node, "Depth", time, 0.0, &self.expr).round() as i32; |
| 1156 | let req_depth = BitDepth::from_fusion_depth(depth_code).unwrap_or(comp.depth_full); |
| 1157 | let dst_depth = self.effective_depth(req_depth); |
| 1158 | let dither = comp.eval_number(node, "Dither", time, 0.0, &self.expr) as f32; |
| 1159 | if dst_depth == src.depth && dither < 0.5 { |
| 1160 | return src; |
| 1161 | } |
| 1162 | let mut u = UniformParams::default(); |
| 1163 | u.p[0] = [dither, dst_depth as u8 as f32, 0.0, 0.0]; |
| 1164 | let key = self.make_key(node, "ChangeDepth", src.size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1])); |
| 1165 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1166 | stats.cache_hits += 1; |
| 1167 | return hit; |
| 1168 | } |
| 1169 | stats.cache_misses += 1; |
| 1170 | stats.nodes_evaluated += 1; |
| 1171 | let dst = self.alloc_tex_like(&src, dst_depth, key); |
| 1172 | self.dispatch_op(enc, ShaderOp::ChangeDepth, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u); |
| 1173 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1174 | dst |
| 1175 | } |
| 1176 | } |
| 1177 | |
| 1178 | #[cfg(test)] |
| 1179 | mod tests { |
| 1180 | use super::*; |
| 1181 | |
| 1182 | fn write_solid_png(path: &std::path::Path, w: u32, h: u32, rgba: [u8; 4]) { |
| 1183 | let mut buf = Vec::with_capacity((w * h * 4) as usize); |
| 1184 | for _ in 0..(w * h) { |
| 1185 | buf.extend_from_slice(&rgba); |
| 1186 | } |
| 1187 | let file = std::fs::File::create(path).expect("create png"); |
| 1188 | let mut enc = png::Encoder::new(file, w, h); |
| 1189 | enc.set_color(png::ColorType::Rgba); |
| 1190 | enc.set_depth(png::BitDepth::Eight); |
| 1191 | enc.write_header() |
| 1192 | .expect("hdr") |
| 1193 | .write_image_data(&buf) |
| 1194 | .expect("data"); |
| 1195 | } |
| 1196 | |
| 1197 | #[test] |
| 1198 | fn loader_prefers_proxy_or_alternate_filename_and_respects_proxy_scale() { |
| 1199 | let dir = std::env::temp_dir().join("fission_proxy_loader_test"); |
| 1200 | let _ = std::fs::create_dir_all(&dir); |
| 1201 | let main_png = dir.join("main.png"); |
| 1202 | let proxy_png = dir.join("proxy.png"); |
| 1203 | let alt_png = dir.join("alt.png"); |
| 1204 | write_solid_png(&main_png, 32, 16, [255, 0, 0, 255]); // red |
| 1205 | write_solid_png(&proxy_png, 32, 16, [0, 255, 0, 255]); // green |
| 1206 | write_solid_png(&alt_png, 32, 16, [0, 0, 255, 255]); // blue |
| 1207 | |
| 1208 | let comp_src = format!( |
| 1209 | r#" |
| 1210 | Composition {{ |
| 1211 | CurrentTime = 0, |
| 1212 | RenderRange = {{ 0, 10 }}, |
| 1213 | GlobalRange = {{ 0, 10 }}, |
| 1214 | Tools = ordered() {{ |
| 1215 | LD1 = Loader {{ |
| 1216 | Clips = {{ |
| 1217 | Clip {{ |
| 1218 | ID = "Clip1", |
| 1219 | Filename = "{}", |
| 1220 | AlternateFilename = "{}", |
| 1221 | FormatID = "PNGFormat", |
| 1222 | StartFrame = 0, |
| 1223 | Length = 1, |
| 1224 | }} |
| 1225 | }}, |
| 1226 | Inputs = {{ |
| 1227 | ProxyFilename = Input {{ Value = "{}", }}, |
| 1228 | }}, |
| 1229 | }}, |
| 1230 | LD2 = Loader {{ |
| 1231 | Clips = {{ |
| 1232 | Clip {{ |
| 1233 | ID = "Clip1", |
| 1234 | Filename = "{}", |
| 1235 | AlternateFilename = "{}", |
| 1236 | FormatID = "PNGFormat", |
| 1237 | StartFrame = 0, |
| 1238 | Length = 1, |
| 1239 | }} |
| 1240 | }}, |
| 1241 | }}, |
| 1242 | }}, |
| 1243 | }} |
| 1244 | "#, |
| 1245 | main_png.display(), |
| 1246 | alt_png.display(), |
| 1247 | proxy_png.display(), |
| 1248 | main_png.display(), |
| 1249 | alt_png.display(), |
| 1250 | ); |
| 1251 | let comp = Comp::from_fusion_str(&comp_src).expect("parse"); |
| 1252 | let ld1 = comp.find_node("LD1").expect("LD1"); |
| 1253 | let ld2 = comp.find_node("LD2").expect("LD2"); |
| 1254 | |
| 1255 | let mut engine = Engine::new_headless().expect("gpu"); |
| 1256 | // Default: primary red clip at 1:1 |
| 1257 | let (tex, _) = engine.evaluate(&comp, ld1, 0.0); |
| 1258 | assert_eq!(tex.size, [32, 16]); |
| 1259 | let px = engine.readback_rgba(&tex).expect("readback"); |
| 1260 | assert!(px[0] > 240 && px[1] < 15 && px[2] < 15, "expected red primary"); |
| 1261 | |
| 1262 | // Proxy clips enabled + 1:2 resolution scale: LD1 picks ProxyFilename (green), LD2 picks AlternateFilename (blue) |
| 1263 | engine.use_proxy_clips = true; |
| 1264 | engine.proxy_scale = 2; |
| 1265 | let (tex1, _) = engine.evaluate(&comp, ld1, 0.0); |
| 1266 | assert_eq!(tex1.size, [16, 8]); |
| 1267 | let px1 = engine.readback_rgba(&tex1).expect("readback"); |
| 1268 | assert!(px1[1] > 240 && px1[0] < 15 && px1[2] < 15, "expected green proxy"); |
| 1269 | |
| 1270 | let (tex2, _) = engine.evaluate(&comp, ld2, 0.0); |
| 1271 | assert_eq!(tex2.size, [16, 8]); |
| 1272 | let px2 = engine.readback_rgba(&tex2).expect("readback"); |
| 1273 | assert!(px2[2] > 240 && px2[0] < 15 && px2[1] < 15, "expected blue alternate"); |
| 1274 | |
| 1275 | // 1:4 scale |
| 1276 | engine.proxy_scale = 4; |
| 1277 | let (tex4, _) = engine.evaluate(&comp, ld1, 0.0); |
| 1278 | assert_eq!(tex4.size, [8, 4]); |
| 1279 | |
| 1280 | let _ = std::fs::remove_dir_all(&dir); |
| 1281 | } |
| 1282 | |
| 1283 | #[test] |
| 1284 | fn png_loader_post_multiply_defaults_to_straight() { |
| 1285 | let dir = std::env::temp_dir().join("fission_post_multiply_loader_test"); |
| 1286 | let _ = std::fs::create_dir_all(&dir); |
| 1287 | let png = dir.join("half.png"); |
| 1288 | write_solid_png(&png, 4, 4, [200, 100, 50, 128]); |
| 1289 | |
| 1290 | let loader = |name: &str, post_mult: &str| { |
| 1291 | format!( |
| 1292 | r#"{name} = Loader {{ |
| 1293 | Clips = {{ Clip {{ ID = "Clip1", Filename = "{}", FormatID = "PNGFormat", StartFrame = 0, Length = 1, }} }}, |
| 1294 | Inputs = {{ {post_mult} }}, |
| 1295 | }},"#, |
| 1296 | png.display() |
| 1297 | ) |
| 1298 | }; |
| 1299 | let comp_src = format!( |
| 1300 | "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ {} {} {} }}, }}", |
| 1301 | loader("OMIT", ""), |
| 1302 | loader("ZERO", r#"["Clip1.PNGFormat.PostMultiply"] = Input { Value = 0, },"#), |
| 1303 | loader("ONE", r#"["Clip1.PNGFormat.PostMultiply"] = Input { Value = 1, },"#), |
| 1304 | ); |
| 1305 | let comp = Comp::from_fusion_str(&comp_src).expect("parse"); |
| 1306 | let rgb = |name: &str| { |
| 1307 | let mut engine = Engine::new_headless().expect("gpu"); |
| 1308 | let (tex, _) = engine.evaluate(&comp, comp.find_node(name).expect(name), 0.0); |
| 1309 | let px = engine.readback_rgba(&tex).expect("readback"); |
| 1310 | [px[0], px[1], px[2]] |
| 1311 | }; |
| 1312 | let straight = rgb("ZERO"); |
| 1313 | assert_eq!(rgb("OMIT"), straight); |
| 1314 | assert_eq!(straight, [200, 100, 50]); |
| 1315 | let premul = rgb("ONE"); |
| 1316 | assert!((i32::from(premul[0]) - 100).abs() <= 1, "premul r = {}", premul[0]); |
| 1317 | |
| 1318 | let _ = std::fs::remove_dir_all(&dir); |
| 1319 | } |
| 1320 | |
| 1321 | #[test] |
| 1322 | fn vram_budget_strictly_caps_node_cache() { |
| 1323 | let mut engine = Engine::new_headless().expect("gpu"); |
| 1324 | engine.set_vram_budget_mb(8); |
| 1325 | assert_eq!(engine.vram_budget_mb(), 8); |
| 1326 | |
| 1327 | let comp_src = r#" |
| 1328 | Composition { |
| 1329 | CurrentTime = 0, |
| 1330 | RenderRange = { 0, 20 }, |
| 1331 | GlobalRange = { 0, 20 }, |
| 1332 | Tools = ordered() { |
| 1333 | BG = Background { |
| 1334 | Inputs = { |
| 1335 | Width = Input { Value = 1024, }, |
| 1336 | Height = Input { Value = 1024, }, |
| 1337 | TopLeftRed = Input { Value = 0.5, }, |
| 1338 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1339 | }, |
| 1340 | }, |
| 1341 | BC = BrightnessContrast { |
| 1342 | Inputs = { |
| 1343 | Gain = Input { SourceOp = "GainSp", Source = "Value", }, |
| 1344 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 1345 | }, |
| 1346 | }, |
| 1347 | GainSp = BezierSpline { |
| 1348 | KeyFrames = { |
| 1349 | [0] = { 0.5 }, |
| 1350 | [10] = { 2.0 }, |
| 1351 | }, |
| 1352 | }, |
| 1353 | }, |
| 1354 | } |
| 1355 | "#; |
| 1356 | let comp = Comp::from_fusion_str(comp_src).expect("parse"); |
| 1357 | let bc = comp.find_node("BC").expect("BC"); |
| 1358 | // Each 1024x1024 RGBA8 texture is 4 MB; 8 MB budget holds at most 2 textures across 6 animated frames. |
| 1359 | for f in 0..6 { |
| 1360 | let (_, stats) = engine.evaluate(&comp, bc, f as f64); |
| 1361 | assert!( |
| 1362 | stats.cached_vram_mb <= 8.5, |
| 1363 | "VRAM exceeded 8 MB cap at frame {f}: {:.1} MB", |
| 1364 | stats.cached_vram_mb |
| 1365 | ); |
| 1366 | } |
| 1367 | assert!(engine.cache.eviction_count() >= 1); |
| 1368 | } |
| 1369 | |
| 1370 | #[test] |
| 1371 | fn loader_out_of_range_missing_frames_1_outputs_full_transparent_canvas() { |
| 1372 | let dir = std::env::temp_dir().join("fission_loader_missing_frames_test"); |
| 1373 | let _ = std::fs::create_dir_all(&dir); |
| 1374 | let missing_clip = dir.join("does_not_exist.mov"); |
| 1375 | let existing_png = dir.join("frame_0001.png"); |
| 1376 | write_solid_png(&existing_png, 64, 32, [200, 100, 50, 255]); |
| 1377 | |
| 1378 | let comp_src = format!( |
| 1379 | r#" |
| 1380 | Composition {{ |
| 1381 | CurrentTime = 20, |
| 1382 | RenderRange = {{ 0, 30 }}, |
| 1383 | GlobalRange = {{ 0, 30 }}, |
| 1384 | Prefs = {{ |
| 1385 | Comp = {{ |
| 1386 | FrameFormat = {{ Width = 320, Height = 180, }}, |
| 1387 | }}, |
| 1388 | }}, |
| 1389 | Tools = ordered() {{ |
| 1390 | LD_Missing = Loader {{ |
| 1391 | Clips = {{ |
| 1392 | Clip {{ |
| 1393 | ID = "Clip1", |
| 1394 | Filename = "{}", |
| 1395 | FormatID = "QuickTimeMovies", |
| 1396 | Length = 10, |
| 1397 | Loop = 0, |
| 1398 | GlobalStart = 0, |
| 1399 | GlobalEnd = 9, |
| 1400 | }} |
| 1401 | }}, |
| 1402 | Inputs = {{ |
| 1403 | MissingFrames = Input {{ Value = 1, }}, |
| 1404 | }}, |
| 1405 | }}, |
| 1406 | LD_Seq = Loader {{ |
| 1407 | Clips = {{ |
| 1408 | Clip {{ |
| 1409 | ID = "Clip1", |
| 1410 | Filename = "{}", |
| 1411 | FormatID = "PNGFormat", |
| 1412 | StartFrame = 1, |
| 1413 | Length = 10, |
| 1414 | Loop = 1, |
| 1415 | GlobalStart = 0, |
| 1416 | GlobalEnd = 9, |
| 1417 | }} |
| 1418 | }}, |
| 1419 | Inputs = {{ |
| 1420 | MissingFrames = Input {{ Value = 1, }}, |
| 1421 | }}, |
| 1422 | }}, |
| 1423 | }}, |
| 1424 | }} |
| 1425 | "#, |
| 1426 | missing_clip.display(), |
| 1427 | existing_png.display(), |
| 1428 | ); |
| 1429 | let comp = Comp::from_fusion_str(&comp_src).expect("parse"); |
| 1430 | let ld_missing = comp.find_node("LD_Missing").expect("LD_Missing"); |
| 1431 | let ld_seq = comp.find_node("LD_Seq").expect("LD_Seq"); |
| 1432 | |
| 1433 | let mut engine = Engine::new_headless().expect("gpu"); |
| 1434 | // Missing file with MissingFrames=1 falls back to comp dimensions (320x180), transparent [0,0,0,0]. |
| 1435 | let (tex, _) = engine.evaluate(&comp, ld_missing, 20.0); |
| 1436 | assert_eq!(tex.size, [320, 180]); |
| 1437 | let rgba = engine.readback_rgba(&tex).expect("readback"); |
| 1438 | assert!(rgba.iter().all(|&b| b == 0), "expected fully transparent canvas"); |
| 1439 | |
| 1440 | // Out-of-range sequence with MissingFrames=1 uses native clip dims (64x32), transparent [0,0,0,0]. |
| 1441 | let (tex_seq, _) = engine.evaluate(&comp, ld_seq, 20.0); |
| 1442 | assert_eq!(tex_seq.size, [64, 32]); |
| 1443 | let rgba_seq = engine.readback_rgba(&tex_seq).expect("readback"); |
| 1444 | assert!(rgba_seq.iter().all(|&b| b == 0), "expected transparent out-of-range sequence frame"); |
| 1445 | |
| 1446 | // Verify proxy_scale is honored on the fallback canvas. |
| 1447 | engine.proxy_scale = 2; |
| 1448 | let (tex_half, _) = engine.evaluate(&comp, ld_missing, 20.0); |
| 1449 | assert_eq!(tex_half.size, [160, 90]); |
| 1450 | |
| 1451 | let _ = std::fs::remove_dir_all(&dir); |
| 1452 | } |
| 1453 | |
| 1454 | #[test] |
| 1455 | fn crop_keep_aspect_matches_fusion_height_and_centered_offset() { |
| 1456 | let src = r#" |
| 1457 | Composition { |
| 1458 | CurrentTime = 0, |
| 1459 | RenderRange = { 0, 1 }, |
| 1460 | GlobalRange = { 0, 1 }, |
| 1461 | Tools = ordered() { |
| 1462 | BG = Background { |
| 1463 | Inputs = { |
| 1464 | Width = Input { Value = 640, }, |
| 1465 | Height = Input { Value = 360, }, |
| 1466 | TopLeftRed = Input { Value = 0.8, }, |
| 1467 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1468 | }, |
| 1469 | }, |
| 1470 | CropAspect = Crop { |
| 1471 | Inputs = { |
| 1472 | XOffset = Input { Value = 67, }, |
| 1473 | YOffset = Input { Value = 104, }, |
| 1474 | XSize = Input { Value = 2563, }, |
| 1475 | YSize = Input { Value = 2563, }, |
| 1476 | KeepAspect = Input { Value = 1, }, |
| 1477 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 1478 | }, |
| 1479 | }, |
| 1480 | CropCentered = Crop { |
| 1481 | Inputs = { |
| 1482 | XSize = Input { Value = 320, }, |
| 1483 | YSize = Input { Value = 320, }, |
| 1484 | KeepAspect = Input { Value = 1, }, |
| 1485 | KeepCentered = Input { Value = 1, }, |
| 1486 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 1487 | }, |
| 1488 | }, |
| 1489 | }, |
| 1490 | } |
| 1491 | "#; |
| 1492 | let comp = Comp::from_fusion_str(src).expect("parse crop comp"); |
| 1493 | let mut eng = Engine::new_headless().expect("gpu"); |
| 1494 | let (t_aspect, _) = eng.evaluate(&comp, comp.find_node("CropAspect").unwrap(), 0.0); |
| 1495 | assert_eq!(t_aspect.size, [2563, 1442]); |
| 1496 | |
| 1497 | let (t_centered, _) = eng.evaluate(&comp, comp.find_node("CropCentered").unwrap(), 0.0); |
| 1498 | assert_eq!(t_centered.size, [320, 180]); |
| 1499 | } |
| 1500 | |
| 1501 | #[test] |
| 1502 | fn loader_reuses_pooled_textures_across_gpu_cache_bust() { |
| 1503 | let dir = std::env::temp_dir().join("fission_loader_pool_test"); |
| 1504 | let _ = std::fs::create_dir_all(&dir); |
| 1505 | let png_path = dir.join("plate.png"); |
| 1506 | write_solid_png(&png_path, 256, 256, [120, 180, 240, 255]); |
| 1507 | |
| 1508 | let comp_src = format!( |
| 1509 | r#" |
| 1510 | Composition {{ |
| 1511 | CurrentTime = 0, |
| 1512 | RenderRange = {{ 0, 1 }}, |
| 1513 | GlobalRange = {{ 0, 1 }}, |
| 1514 | Tools = ordered() {{ |
| 1515 | LD = Loader {{ |
| 1516 | Clips = {{ |
| 1517 | Clip {{ |
| 1518 | ID = "Clip1", |
| 1519 | Filename = "{}", |
| 1520 | FormatID = "PNGFormat", |
| 1521 | StartFrame = 0, |
| 1522 | Length = 1, |
| 1523 | }} |
| 1524 | }}, |
| 1525 | }}, |
| 1526 | }}, |
| 1527 | }} |
| 1528 | "#, |
| 1529 | png_path.display() |
| 1530 | ); |
| 1531 | let comp = Comp::from_fusion_str(&comp_src).expect("parse"); |
| 1532 | let ld = comp.find_node("LD").expect("LD"); |
| 1533 | let mut eng = Engine::new_headless().expect("gpu"); |
| 1534 | |
| 1535 | let (t1, _) = eng.evaluate(&comp, ld, 0.0); |
| 1536 | assert_eq!(t1.size, [256, 256]); |
| 1537 | drop(t1); |
| 1538 | |
| 1539 | eng.bust_gpu_cache(); |
| 1540 | assert!(eng.cache.pool_stats().pooled_count >= 1); |
| 1541 | |
| 1542 | let before_hits = eng.cache.pool_stats().hits; |
| 1543 | let (t2, _) = eng.evaluate(&comp, ld, 0.0); |
| 1544 | assert_eq!(t2.size, [256, 256]); |
| 1545 | assert!( |
| 1546 | eng.cache.pool_stats().hits > before_hits, |
| 1547 | "expected Loader texture to recycle from TexturePool on bust" |
| 1548 | ); |
| 1549 | |
| 1550 | let _ = std::fs::remove_dir_all(&dir); |
| 1551 | } |
| 1552 | |
| 1553 | #[test] |
| 1554 | fn loader_respects_inspector_timing_overrides_and_invalidates_cache() { |
| 1555 | let dir = std::env::temp_dir().join(format!("fission_loader_timing_{}", std::process::id())); |
| 1556 | let _ = std::fs::remove_dir_all(&dir); |
| 1557 | std::fs::create_dir_all(&dir).expect("create temp dir"); |
| 1558 | |
| 1559 | let f0 = dir.join("seq_0000.png"); |
| 1560 | let f1 = dir.join("seq_0001.png"); |
| 1561 | let f2 = dir.join("seq_0002.png"); |
| 1562 | write_solid_png(&f0, 16, 16, [255, 0, 0, 255]); |
| 1563 | write_solid_png(&f1, 16, 16, [0, 255, 0, 255]); |
| 1564 | write_solid_png(&f2, 16, 16, [0, 0, 255, 255]); |
| 1565 | |
| 1566 | let f0_esc = f0.to_string_lossy().replace('\\', "\\\\"); |
| 1567 | let comp_src = format!( |
| 1568 | r#" |
| 1569 | Composition {{ |
| 1570 | CurrentTime = 0, |
| 1571 | RenderRange = {{ 0, 20 }}, |
| 1572 | GlobalRange = {{ 0, 20 }}, |
| 1573 | Tools = ordered() {{ |
| 1574 | LD = Loader {{ |
| 1575 | Clips = {{ |
| 1576 | Clip {{ |
| 1577 | ID = "Clip1", |
| 1578 | Filename = "{f0_esc}", |
| 1579 | FormatID = "PNGFormat", |
| 1580 | StartFrame = 0, |
| 1581 | Length = 3, |
| 1582 | GlobalStart = 0, |
| 1583 | GlobalEnd = 2, |
| 1584 | }} |
| 1585 | }}, |
| 1586 | Inputs = {{ |
| 1587 | MissingFrames = Input {{ Value = 1, }}, |
| 1588 | }}, |
| 1589 | }}, |
| 1590 | }}, |
| 1591 | }} |
| 1592 | "# |
| 1593 | ); |
| 1594 | let mut comp = Comp::from_fusion_str(&comp_src).expect("parse comp"); |
| 1595 | let ld = comp.find_node("LD").expect("LD"); |
| 1596 | let Ok(mut eng) = Engine::new_headless() else { |
| 1597 | let _ = std::fs::remove_dir_all(&dir); |
| 1598 | return; |
| 1599 | }; |
| 1600 | |
| 1601 | let sample_px = |e: &mut Engine, c: &Comp, t: f64| -> [u8; 4] { |
| 1602 | let (tex, _) = e.evaluate(c, ld, t); |
| 1603 | let px = e.readback_rgba(&tex).expect("readback"); |
| 1604 | [px[0], px[1], px[2], px[3]] |
| 1605 | }; |
| 1606 | |
| 1607 | // Baseline from Clips table: 0=red, 2=blue, 3=missing transparent. |
| 1608 | assert_eq!(sample_px(&mut eng, &comp, 0.0), [255, 0, 0, 255]); |
| 1609 | assert_eq!(sample_px(&mut eng, &comp, 2.0), [0, 0, 255, 255]); |
| 1610 | assert_eq!(sample_px(&mut eng, &comp, 3.0), [0, 0, 0, 0]); |
| 1611 | |
| 1612 | // Override GlobalIn=10, GlobalOut=12 via node.inputs (Inspector write path) without clearing caches. |
| 1613 | let set_num = |c: &mut Comp, key: &str, v: f64| { |
| 1614 | c.nodes[ld.0].inputs.insert( |
| 1615 | key.to_owned(), |
| 1616 | model::InputBinding { |
| 1617 | value: Some(model::ParamValue::Number(v)), |
| 1618 | source_op: None, |
| 1619 | source_output: None, |
| 1620 | expression: None, |
| 1621 | }, |
| 1622 | ); |
| 1623 | c.revision += 1; |
| 1624 | }; |
| 1625 | set_num(&mut comp, "GlobalIn", 10.0); |
| 1626 | set_num(&mut comp, "GlobalOut", 12.0); |
| 1627 | assert_eq!(sample_px(&mut eng, &comp, 0.0), [0, 0, 0, 0]); |
| 1628 | assert_eq!(sample_px(&mut eng, &comp, 10.0), [255, 0, 0, 255]); |
| 1629 | assert_eq!(sample_px(&mut eng, &comp, 12.0), [0, 0, 255, 255]); |
| 1630 | |
| 1631 | // Override Reverse=1: frame 10 becomes blue, frame 12 becomes red. |
| 1632 | set_num(&mut comp, "Reverse", 1.0); |
| 1633 | assert_eq!(sample_px(&mut eng, &comp, 10.0), [0, 0, 255, 255]); |
| 1634 | assert_eq!(sample_px(&mut eng, &comp, 12.0), [255, 0, 0, 255]); |
| 1635 | |
| 1636 | // Override Reverse=0, Loop=1: frame 13 wraps to red and is no longer missing! |
| 1637 | set_num(&mut comp, "Reverse", 0.0); |
| 1638 | set_num(&mut comp, "Loop", 1.0); |
| 1639 | assert_eq!(sample_px(&mut eng, &comp, 13.0), [255, 0, 0, 255]); |
| 1640 | assert_eq!(sample_px(&mut eng, &comp, 14.0), [0, 255, 0, 255]); |
| 1641 | |
| 1642 | let _ = std::fs::remove_dir_all(&dir); |
| 1643 | } |
| 1644 | fn render_generator(kind: &str, w: u32, h: u32, inputs: &str) -> Option<Vec<[f32; 4]>> { |
| 1645 | let src = format!( |
| 1646 | r#"Composition {{ Tools = ordered() {{ N = {kind} {{ Inputs = {{ |
| 1647 | Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, |
| 1648 | Color1Alpha = Input {{ Value = 1, }}, {inputs} }}, }}, }}, }}"# |
| 1649 | ); |
| 1650 | let comp = Comp::from_fusion_str(&src).expect("parse generator comp"); |
| 1651 | let mut eng = Engine::new_headless().ok()?; |
| 1652 | let (tex, _) = eng.evaluate(&comp, comp.find_node("N").unwrap(), 0.0); |
| 1653 | let px = eng.readback_rgba(&tex).unwrap(); |
| 1654 | Some(px.chunks_exact(4).map(|p| [p[0], p[1], p[2], p[3]].map(|c| c as f32 / 255.0)).collect()) |
| 1655 | } |
| 1656 | |
| 1657 | #[test] |
| 1658 | fn plasma_alpha_is_a_fourth_phase_of_the_same_wave() { |
| 1659 | let Some(px) = render_generator("Plasma", 64, 64, "") else { return }; |
| 1660 | // Phases step by 1/8 turn (R, G, B, A), so cos(x + 3d) = 2cos(d)cos(x + 2d) - cos(x + d). |
| 1661 | for p in &px { |
| 1662 | let [_, g, b, a] = p.map(|c| 2.0 * c - 1.0); |
| 1663 | let want = std::f32::consts::SQRT_2 * b - g; |
| 1664 | assert!((a - want).abs() < 0.03, "alpha {a:.3} vs recurrence {want:.3} at {p:?}"); |
| 1665 | } |
| 1666 | let (lo, hi) = px.iter().fold((1.0f32, 0.0f32), |(lo, hi), p| (lo.min(p[3]), hi.max(p[3]))); |
| 1667 | assert!(lo < 0.1 && hi > 0.9, "alpha should swing the full range, got {lo}..{hi}"); |
| 1668 | } |
| 1669 | |
| 1670 | #[test] |
| 1671 | fn plasma_alpha_phase_is_independent_input() { |
| 1672 | // AlphaPhase equal to GreenPhase's default must make alpha track the green channel. |
| 1673 | let Some(px) = render_generator("Plasma", 64, 64, "AlphaPhase = Input { Value = 0.1875, },") else { return }; |
| 1674 | for p in &px { |
| 1675 | assert!((p[3] - p[1]).abs() <= 2.0 / 255.0, "alpha {} vs green {}", p[3], p[1]); |
| 1676 | } |
| 1677 | } |
| 1678 | |
| 1679 | /// Fusion 21.1 Float32 probes (R at x, y) of the simplex lattice, octave offsets, Seethe, Angle, Center and YScale. |
| 1680 | #[test] |
| 1681 | fn fast_noise_matches_fusion_float_probes() { |
| 1682 | let cases: [(u32, u32, &str, [(usize, usize, f32); 6]); 4] = [ |
| 1683 | (512, 512, "Detail = Input { Value = 2, }, XScale = Input { Value = 4, }, Seethe = Input { Value = 1, },", |
| 1684 | [(37, 41, 0.4457), (200, 150, 0.5710), (311, 17, 0.4191), (480, 333, 0.5275), (90, 300, 0.4076), (255, 255, 0.2991)]), |
| 1685 | (640, 360, "Detail = Input { Value = 3, }, XScale = Input { Value = 4, }, Discontinuous = Input { Value = 1, },", |
| 1686 | [(37, 41, 0.2150), (200, 150, 0.4042), (311, 17, 0.1601), (480, 333, 0.1774), (90, 300, 0.1933), (255, 255, 0.1025)]), |
| 1687 | (640, 360, "Detail = Input { Value = 1, }, XScale = Input { Value = 4, }, Angle = Input { Value = 30, }, Center = Input { Value = { 0.3, 0.6 }, },", |
| 1688 | [(37, 41, 0.4068), (200, 150, 0.5251), (311, 17, 0.4916), (480, 333, 0.4710), (90, 300, 0.5406), (255, 255, 0.7552)]), |
| 1689 | (640, 360, "Detail = Input { Value = 1, }, XScale = Input { Value = 4, }, LockXY = Input { Value = 0, }, YScale = Input { Value = 7, },", |
| 1690 | [(37, 41, 0.3507), (200, 150, 0.2588), (311, 17, 0.5995), (480, 333, 0.5001), (90, 300, 0.5444), (255, 255, 0.5119)]), |
| 1691 | ]; |
| 1692 | for (w, h, inputs, probes) in cases { |
| 1693 | let Some(px) = render_generator("FastNoise", w, h, inputs) else { return }; |
| 1694 | for (x, y, want) in probes { |
| 1695 | let got = px[y * w as usize + x][0]; |
| 1696 | assert!((got - want).abs() <= 1.5 / 255.0, "{inputs} at ({x}, {y}): got {got:.4}, want {want:.4}"); |
| 1697 | } |
| 1698 | } |
| 1699 | } |
| 1700 | |
| 1701 | #[test] |
| 1702 | fn fast_noise_detail_weight_is_continuous_above_integers() { |
| 1703 | let render = |detail: &str| { |
| 1704 | render_generator("FastNoise", 64, 64, &format!("Detail = Input {{ Value = {detail}, }}, XScale = Input {{ Value = 8, }},")) |
| 1705 | }; |
| 1706 | let (Some(a), Some(b)) = (render("2"), render("2.00005")) else { return }; |
| 1707 | let worst = a.iter().zip(&b).map(|(x, y)| (x[0] - y[0]).abs()).fold(0.0f32, f32::max); |
| 1708 | assert!(worst <= 1.5 / 255.0, "Detail 2 -> 2.00005 jumped by {worst}"); |
| 1709 | } |
| 1710 | |
| 1711 | #[test] |
| 1712 | fn fast_noise_two_color_extrapolates_unclamped_highlights() { |
| 1713 | // High Contrast + Discontinuous pushes `val > 1.0`, so Two-Color mode must extrapolate |
| 1714 | // `mix(c1, c2, val)` past `c2` rather than clamping `val` to 1.0 (e.g. blue channel |
| 1715 | // exceeds Color2Blue=0.65 toward 1.0 in bright highlights). |
| 1716 | let inputs = "Detail = Input { Value = 6, }, Contrast = Input { Value = 2.2, }, \ |
| 1717 | XScale = Input { Value = 6, }, Seethe = Input { Value = 1.7, }, \ |
| 1718 | Discontinuous = Input { Value = 1, }, \ |
| 1719 | Color1Red = Input { Value = 0.04, }, Color1Green = Input { Value = 0.02, }, \ |
| 1720 | Color1Blue = Input { Value = 0.12, }, \ |
| 1721 | Color2Red = Input { Value = 1.0, }, Color2Green = Input { Value = 0.88, }, \ |
| 1722 | Color2Blue = Input { Value = 0.65, },"; |
| 1723 | let Some(px) = render_generator("FastNoise", 128, 128, inputs) else { return }; |
| 1724 | let max_b = px.iter().map(|p| p[2]).fold(0.0f32, f32::max); |
| 1725 | assert!(max_b > 0.80, "expected unclamped Two-Color blue highlight > 0.80, got {max_b:.4}"); |
| 1726 | } |
| 1727 | |
| 1728 | #[test] |
| 1729 | fn loader_clip_loop_zero_loops_and_one_plays_once() { |
| 1730 | let comp_src = r#"Composition { |
| 1731 | Tools = ordered() { |
| 1732 | L0 = Loader { Clips = { Clip { Filename = "a0001.png", Loop = 0, } }, }, |
| 1733 | L1 = Loader { Clips = { Clip { Filename = "a0001.png", Loop = 1, } }, }, |
| 1734 | LOmit = Loader { Clips = { Clip { Filename = "a0001.png", } }, }, |
| 1735 | }, |
| 1736 | }"#; |
| 1737 | let comp = Comp::from_fusion_str(comp_src).expect("parse clip loop"); |
| 1738 | assert!(comp.node(comp.find_node("L0").unwrap()).clips[0].loop_clip); |
| 1739 | assert!(!comp.node(comp.find_node("L1").unwrap()).clips[0].loop_clip); |
| 1740 | assert!(!comp.node(comp.find_node("LOmit").unwrap()).clips[0].loop_clip); |
| 1741 | } |
| 1742 | |
| 1743 | #[test] |
| 1744 | fn scale_rounds_each_side_up_to_the_source_parity_and_lock_xy_follows_x() { |
| 1745 | let src = r#"Composition { Tools = ordered() { |
| 1746 | Src = Background { Inputs = { Width = Input { Value = 255, }, Height = Input { Value = 253, }, }, }, |
| 1747 | Locked = Scale { Inputs = { XSize = Input { Value = 1.5, }, YSize = Input { Value = 3, }, Input = Input { SourceOp = "Src", Source = "Output", }, }, }, |
| 1748 | Free = Scale { Inputs = { LockXY = Input { Value = 0, }, XSize = Input { Value = 0.5, }, Input = Input { SourceOp = "Src", Source = "Output", }, }, }, |
| 1749 | }, }"#; |
| 1750 | let comp = Comp::from_fusion_str(src).expect("parse scale comp"); |
| 1751 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1752 | let (tex, _) = eng.evaluate(&comp, comp.find_node("Locked").unwrap(), 0.0); |
| 1753 | assert_eq!(tex.size, [383, 381], "382.5 and 379.5 round up to odd sizes"); |
| 1754 | let (tex, _) = eng.evaluate(&comp, comp.find_node("Free").unwrap(), 0.0); |
| 1755 | assert_eq!(tex.size, [129, 253], "unlocked YSize keeps its own default of 1"); |
| 1756 | } |
| 1757 | |
| 1758 | #[test] |
| 1759 | fn plasma_operation_counts_none_circles_as_zero() { |
| 1760 | let Some(px) = render_generator("Plasma", 32, 32, "Operation = Input { Value = 2, }, Circle3Type = Input { Value = 0, },") else { return }; |
| 1761 | assert!(px.iter().all(|p| *p == px[0]), "product with a zero term is a constant image"); |
| 1762 | } |
| 1763 | |
| 1764 | #[test] |
| 1765 | fn plasma_divide_ignores_disabled_circles_and_stays_finite() { |
| 1766 | let Some(px) = render_generator("Plasma", 32, 32, "Operation = Input { Value = 3, }, Circle2Type = Input { Value = 0, }, Circle4Type = Input { Value = 0, },") else { return }; |
| 1767 | assert!(px.iter().all(|p| p.iter().any(|c| *c > 0.0)), "a NaN term would store as transparent black"); |
| 1768 | assert!(px.iter().any(|p| *p != px[0]), "the quotient still varies across the frame"); |
| 1769 | } |
| 1770 | |
| 1771 | #[test] |
| 1772 | fn plasma_multiply_and_divide_match_fusion_probes() { |
| 1773 | // Operation = 2 (Multiply) with Phase = 0.21449 matches Fusion 21.1 probes across high-phase fringes. |
| 1774 | if let Some(px) = render_generator("Plasma", 256, 256, "Operation = Input { Value = 2, }, Phase = Input { Value = 0.21449, },") { |
| 1775 | for (x, y, want) in [ |
| 1776 | (64usize, 64usize, [181u8, 84, 12, 8]), |
| 1777 | (128, 128, [227, 254, 208, 114]), |
| 1778 | (192, 192, [4, 63, 160, 238]), |
| 1779 | ] { |
| 1780 | let p = px[y * 256 + x].map(|c| (c * 255.0).round() as u8); |
| 1781 | for ch in 0..4 { |
| 1782 | assert!(p[ch].abs_diff(want[ch]) <= 2, "op2 ({x},{y}) ch{ch}: got {p:?} want {want:?}"); |
| 1783 | } |
| 1784 | } |
| 1785 | } |
| 1786 | // Operation = 3 (Divide) with scaled Type-1 & Type-2 circles + overflow fallback matches Fusion 21.1. |
| 1787 | let inputs = "Phase = Input { Value = 0.3804, }, Operation = Input { Value = 3, }, \ |
| 1788 | Circle1Scale = Input { Value = 7.48849, }, Circle1Center = Input { Value = { 0.0597, 0.8826 }, }, \ |
| 1789 | Circle4Type = Input { Value = 1, }, Circle4Scale = Input { Value = 9.22157, }, \ |
| 1790 | Scale = Input { Value = 4.53735, }, AlphaPhase = Input { Value = 0.06949, }, \ |
| 1791 | Circle2Center = Input { Value = { 0.7631, 0.8558 }, },"; |
| 1792 | if let Some(px) = render_generator("Plasma", 256, 256, inputs) { |
| 1793 | for (x, y, want) in [ |
| 1794 | (192usize, 128usize, [21u8, 3, 58, 18]), |
| 1795 | (192, 64, [197, 252, 235, 201]), |
| 1796 | (128, 64, [151, 233, 253, 156]), |
| 1797 | (0, 128, [245, 176, 79, 243]), |
| 1798 | ] { |
| 1799 | let p = px[y * 256 + x].map(|c| (c * 255.0).round() as u8); |
| 1800 | for ch in 0..4 { |
| 1801 | assert!(p[ch].abs_diff(want[ch]) <= 2, "op3 ({x},{y}) ch{ch}: got {p:?} want {want:?}"); |
| 1802 | } |
| 1803 | } |
| 1804 | } |
| 1805 | } |
| 1806 | |
| 1807 | #[test] |
| 1808 | fn loader_single_frame_still_returns_empty_outside_range_unless_looping() { |
| 1809 | let dir = std::env::temp_dir().join("fission_loader_single_still_oob_test"); |
| 1810 | let _ = std::fs::create_dir_all(&dir); |
| 1811 | let still = dir.join("still.png"); |
| 1812 | write_solid_png(&still, 32, 32, [200, 80, 40, 255]); |
| 1813 | let comp_src = format!( |
| 1814 | r#" |
| 1815 | Composition {{ |
| 1816 | CurrentTime = 10, |
| 1817 | RenderRange = {{ 0, 30 }}, |
| 1818 | GlobalRange = {{ 0, 30 }}, |
| 1819 | Tools = ordered() {{ |
| 1820 | Once = Loader {{ |
| 1821 | Clips = {{ Clip {{ ID = "Clip1", Filename = "{}", Length = 1, Loop = 1, GlobalStart = 10, GlobalEnd = 10, }} }}, |
| 1822 | Inputs = {{ GlobalIn = Input {{ Value = 10, }}, GlobalOut = Input {{ Value = 10, }}, }}, |
| 1823 | }}, |
| 1824 | Looped = Loader {{ |
| 1825 | Clips = {{ Clip {{ ID = "Clip1", Filename = "{}", Length = 1, Loop = 0, GlobalStart = 10, GlobalEnd = 10, }} }}, |
| 1826 | Inputs = {{ GlobalIn = Input {{ Value = 10, }}, GlobalOut = Input {{ Value = 10, }}, }}, |
| 1827 | }}, |
| 1828 | }}, |
| 1829 | }}"#, |
| 1830 | still.display(), |
| 1831 | still.display(), |
| 1832 | ); |
| 1833 | let comp = Comp::from_fusion_str(&comp_src).expect("parse comp"); |
| 1834 | let Ok(mut eng) = Engine::new_headless() else { |
| 1835 | let _ = std::fs::remove_dir_all(&dir); |
| 1836 | return; |
| 1837 | }; |
| 1838 | let once = comp.find_node("Once").unwrap(); |
| 1839 | let looped = comp.find_node("Looped").unwrap(); |
| 1840 | let (in_range, _) = eng.evaluate(&comp, once, 10.0); |
| 1841 | assert_eq!(in_range.size, [32, 32]); |
| 1842 | let (oob_once, _) = eng.evaluate(&comp, once, 25.0); |
| 1843 | assert_eq!(oob_once.size, [1, 1]); |
| 1844 | assert_eq!(eng.readback_rgba(&oob_once).unwrap(), [0, 0, 0, 0]); |
| 1845 | let (oob_loop, _) = eng.evaluate(&comp, looped, 25.0); |
| 1846 | assert_eq!(oob_loop.size, [32, 32]); |
| 1847 | let _ = std::fs::remove_dir_all(&dir); |
| 1848 | } |
| 1849 | |
| 1850 | #[test] |
| 1851 | fn loader_attaches_exr_z_channel_to_aux_with_row_padding() { |
| 1852 | use ::exr::prelude::*; |
| 1853 | |
| 1854 | let w = 13usize; |
| 1855 | let h = 7usize; |
| 1856 | let z_expected: Vec<f32> = (0..(w * h)) |
| 1857 | .map(|i| if i % 5 == 0 { crate::cache::EMPTY_Z_SENTINEL } else { -1.25 - (i as f32) * 0.125 }) |
| 1858 | .collect(); |
| 1859 | let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new(); |
| 1860 | channels.push(AnyChannel::new("R", FlatSamples::F32(vec![0.8; w * h]))); |
| 1861 | channels.push(AnyChannel::new("G", FlatSamples::F32(vec![0.4; w * h]))); |
| 1862 | channels.push(AnyChannel::new("B", FlatSamples::F32(vec![0.2; w * h]))); |
| 1863 | channels.push(AnyChannel::new("A", FlatSamples::F32(vec![1.0; w * h]))); |
| 1864 | channels.push(AnyChannel::new("Z", FlatSamples::F32(z_expected.clone()))); |
| 1865 | let image = Image::from_layer(Layer::new( |
| 1866 | Vec2(w, h), |
| 1867 | LayerAttributes::default(), |
| 1868 | Encoding::UNCOMPRESSED, |
| 1869 | AnyChannels::sort(channels), |
| 1870 | )); |
| 1871 | let dir = std::env::temp_dir().join(format!("fission_loader_exr_z_{}", std::process::id())); |
| 1872 | let _ = std::fs::create_dir_all(&dir); |
| 1873 | let exr_path = dir.join("z_plate.exr"); |
| 1874 | image.write().to_file(&exr_path).expect("write synthetic Z EXR"); |
| 1875 | |
| 1876 | let comp_src = format!( |
| 1877 | r#"Composition {{ |
| 1878 | CurrentTime = 0, |
| 1879 | RenderRange = {{ 0, 1 }}, |
| 1880 | GlobalRange = {{ 0, 1 }}, |
| 1881 | Tools = ordered() {{ |
| 1882 | L = Loader {{ |
| 1883 | Clips = {{ Clip {{ ID = "Clip1", Filename = "{}", Length = 1, GlobalStart = 0, GlobalEnd = 0, }} }}, |
| 1884 | }}, |
| 1885 | }}, |
| 1886 | }}"#, |
| 1887 | exr_path.display() |
| 1888 | ); |
| 1889 | let comp = Comp::from_fusion_str(&comp_src).expect("parse EXR Loader comp"); |
| 1890 | let Ok(mut eng) = Engine::new_headless() else { |
| 1891 | let _ = std::fs::remove_dir_all(&dir); |
| 1892 | return; |
| 1893 | }; |
| 1894 | let (tex, _) = eng.evaluate(&comp, comp.find_node("L").unwrap(), 0.0); |
| 1895 | let aux = tex.aux.as_ref().expect("Loader must attach aux for EXR with Z channel"); |
| 1896 | let z_tex = aux.z.as_ref().expect("aux.z must be present"); |
| 1897 | assert_eq!(z_tex.size, [w as u32, h as u32]); |
| 1898 | assert_eq!(z_tex.format, wgpu::TextureFormat::R32Float); |
| 1899 | |
| 1900 | let unpadded_bpr = (w as u32) * 4; |
| 1901 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 1902 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 1903 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { |
| 1904 | label: Some("readback-exr-z"), |
| 1905 | size: u64::from(padded_bpr) * u64::from(h as u32), |
| 1906 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 1907 | mapped_at_creation: false, |
| 1908 | }); |
| 1909 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 1910 | enc.copy_texture_to_buffer( |
| 1911 | z_tex.texture.as_image_copy(), |
| 1912 | wgpu::TexelCopyBufferInfo { |
| 1913 | buffer: &buf, |
| 1914 | layout: wgpu::TexelCopyBufferLayout { |
| 1915 | offset: 0, |
| 1916 | bytes_per_row: Some(padded_bpr), |
| 1917 | rows_per_image: Some(h as u32), |
| 1918 | }, |
| 1919 | }, |
| 1920 | wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, |
| 1921 | ); |
| 1922 | eng.queue.submit(Some(enc.finish())); |
| 1923 | let slice = buf.slice(..); |
| 1924 | let (tx, rx) = std::sync::mpsc::channel(); |
| 1925 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 1926 | let _ = tx.send(res); |
| 1927 | }); |
| 1928 | eng.device |
| 1929 | .poll(wgpu::PollType::Wait { |
| 1930 | submission_index: None, |
| 1931 | timeout: Some(std::time::Duration::from_secs(10)), |
| 1932 | }) |
| 1933 | .unwrap(); |
| 1934 | rx.recv().unwrap().unwrap(); |
| 1935 | let data = slice.get_mapped_range().unwrap(); |
| 1936 | let mut got = Vec::with_capacity(w * h); |
| 1937 | for y in 0..h { |
| 1938 | let start = y * padded_bpr as usize; |
| 1939 | let row_bytes = &data[start..start + unpadded_bpr as usize]; |
| 1940 | got.extend_from_slice(bytemuck::cast_slice::<u8, f32>(row_bytes)); |
| 1941 | } |
| 1942 | drop(data); |
| 1943 | buf.unmap(); |
| 1944 | let _ = std::fs::remove_dir_all(&dir); |
| 1945 | |
| 1946 | assert_eq!(got, z_expected, "Loader aux.z must match exact EXR float32 depth values"); |
| 1947 | } |
| 1948 | } |