| 1 | //! Headless `wgpu` 2D compositor evaluator with Merkle content-hash caching, |
| 2 | //! branch pruning, and surgical cache-busting. |
| 3 | |
| 4 | use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; |
| 5 | use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; |
| 6 | use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port}; |
| 7 | use std::cell::{Cell, OnceCell, RefCell}; |
| 8 | use std::collections::{HashMap, HashSet}; |
| 9 | use std::collections::hash_map::DefaultHasher; |
| 10 | use std::hash::{Hash, Hasher}; |
| 11 | #[cfg(not(target_arch = "wasm32"))] |
| 12 | use std::time::Instant; |
| 13 | #[cfg(target_arch = "wasm32")] |
| 14 | use web_time::Instant; |
| 15 | |
| 16 | mod io; |
| 17 | mod alpha_keyers; |
| 18 | mod aux_ops; |
| 19 | mod color_science; |
| 20 | mod color_lut; |
| 21 | mod depth_optical; |
| 22 | mod composite; |
| 23 | mod transform; |
| 24 | mod color; |
| 25 | mod blur_glow; |
| 26 | mod fuses; |
| 27 | mod keyers; |
| 28 | mod masks; |
| 29 | mod paint; |
| 30 | mod shapes; |
| 31 | mod warps; |
| 32 | mod warps_masks; |
| 33 | mod fx_fuses; |
| 34 | mod archive_fx2; |
| 35 | mod surface_fx; |
| 36 | mod layer_ocio; |
| 37 | mod deep_flow; |
| 38 | mod text_3d; |
| 39 | mod registry; |
| 40 | mod dispatch; |
| 41 | mod output_cache; |
| 42 | |
| 43 | use dispatch::UniformParams; |
| 44 | pub use dispatch::{PendingReadback, create_texture, create_texture_dod, create_texture_dod_fmt}; |
| 45 | pub use color_lut::lut_io::export_cube_from_rgba; |
| 46 | pub(crate) use io::Nv12Pipelines; |
| 47 | use output_cache::OutputCache; |
| 48 | use registry::{ShaderOp, ShaderRegistry}; |
| 49 | |
| 50 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 51 | pub struct DisplaySettings { |
| 52 | pub exposure: f32, // stops (0.0 = 1x) |
| 53 | pub gamma: f32, // default 1.0 |
| 54 | pub channel: u32, // 0=RGBA, 1=R, 2=G, 3=B, 4=A |
| 55 | pub checker_bg: bool, |
| 56 | /// False (default) = exact nearest-neighbor pixels ("raw truth" when zooming in); |
| 57 | /// True = bilinear "Smooth Resize". |
| 58 | pub smooth_resize: bool, |
| 59 | /// Visible normalized UV rectangle `[u0, v0, u1, v1]` sampled into the viewer output texture. |
| 60 | pub uv_rect: [f32; 4], |
| 61 | } |
| 62 | |
| 63 | impl Default for DisplaySettings { |
| 64 | fn default() -> Self { |
| 65 | Self { |
| 66 | exposure: 0.0, |
| 67 | gamma: 1.0, |
| 68 | channel: 0, |
| 69 | checker_bg: true, |
| 70 | smooth_resize: false, |
| 71 | uv_rect: [0.0, 0.0, 1.0, 1.0], |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | pub struct Engine { |
| 77 | pub(crate) device: wgpu::Device, |
| 78 | pub(crate) queue: wgpu::Queue, |
| 79 | pipelines: RefCell<ShaderRegistry>, |
| 80 | pipelines_int16: OnceCell<RefCell<ShaderRegistry>>, |
| 81 | pipelines_f16: OnceCell<RefCell<ShaderRegistry>>, |
| 82 | pipelines_f32: OnceCell<RefCell<ShaderRegistry>>, |
| 83 | aux_pipelines: OnceCell<RefCell<aux_ops::AuxPipelines>>, |
| 84 | alpha_keyer_pipelines: OnceCell<RefCell<alpha_keyers::AlphaKeyerPipelines>>, |
| 85 | color_science_pipelines: OnceCell<RefCell<color_science::ColorSciencePipelines>>, |
| 86 | color_lut_pipelines: OnceCell<RefCell<color_lut::ColorLutPipelines>>, |
| 87 | depth_optical_pipelines: OnceCell<RefCell<depth_optical::DepthOpticalPipelines>>, |
| 88 | warps_masks_pipelines: OnceCell<RefCell<warps_masks::WarpsMasksPipelines>>, |
| 89 | fx_fuses_pipelines: OnceCell<RefCell<fx_fuses::FxFusesPipelines>>, |
| 90 | archive_fx2_pipelines: OnceCell<RefCell<archive_fx2::ArchiveFx2Pipelines>>, |
| 91 | pub(crate) surface_fx: OnceCell<RefCell<surface_fx::SurfaceFxPipelines>>, |
| 92 | pub(crate) layer_ocio: OnceCell<RefCell<layer_ocio::LayerOcioPipelines>>, |
| 93 | pub(crate) deep_flow: OnceCell<RefCell<deep_flow::DeepFlowPipelines>>, |
| 94 | auto_matte_pipelines: OnceCell<RefCell<crate::auto_matte::AutoMattePipelines>>, |
| 95 | pub auto_matte_cache: crate::auto_matte::AutoMatteCache, |
| 96 | motion_blur: crate::motion_blur::MotionBlurPipelines, |
| 97 | pub(crate) supports_f32_filter: bool, |
| 98 | scene3d: crate::scene3d::Scene3DRenderer, |
| 99 | optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>, |
| 100 | tracker: std::sync::OnceLock<crate::tracker::TrackerPipelines>, |
| 101 | particles: crate::particles::ParticleCache, |
| 102 | custom_shaders: crate::custom_shader::CustomShaderCache, |
| 103 | pub fuse_registry: crate::fuse_runtime::FuseRegistry, |
| 104 | sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, |
| 105 | ram_upload_tex: RefCell<Option<CachedTexture>>, |
| 106 | pub(crate) dummy: CachedTexture, |
| 107 | vram_budget_bytes: u64, |
| 108 | last_bg_vram_drops: Cell<u64>, |
| 109 | pub cache: NodeCache, |
| 110 | pub media: MediaCache, |
| 111 | pub expr: ExprEngine, |
| 112 | /// Active evaluation target node (set during `evaluate` / `render_into_viewer`). |
| 113 | pub(super) frame_eval_target: Option<NodeId>, |
| 114 | /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. |
| 115 | frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, |
| 116 | /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current comp revision. |
| 117 | frame_consumers: Vec<Vec<(NodeId, String)>>, |
| 118 | /// Comp revision for which `frame_consumers` was built, so steady-state frames skip rebuilding it. |
| 119 | frame_consumers_rev: Option<u64>, |
| 120 | /// Per-evaluation memo of conservative downstream RoI bounds `(node_id, time_bits)`. |
| 121 | frame_roi_memo: HashMap<(NodeId, i64), Option<composite::RoiBox>>, |
| 122 | /// Reusable cycle-detection set for `eval_node` across frames. |
| 123 | frame_visiting: HashSet<(NodeId, i64)>, |
| 124 | /// Active per-`NodeId` cycle-detection set forbidding temporal-lookback re-entrancy across shifted times. |
| 125 | frame_visiting_nodes: HashSet<NodeId>, |
| 126 | output_cache: OutputCache, |
| 127 | /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default |
| 128 | /// to matching the dimensions & aspect ratio of the node they mask!). |
| 129 | mask_target_size: Option<[u32; 2]>, |
| 130 | /// Proxy downscale divisor: 1 = full res, 2 = half res, 4 = quarter res. |
| 131 | pub proxy_scale: u32, |
| 132 | /// When `true`, `Loader` nodes prefer `ProxyFilename` or `Clip.AlternateFilename` if present on disk. |
| 133 | pub use_proxy_clips: bool, |
| 134 | /// High-Quality mode (`true` = exact Fusion bar-for-bar passes & project/ChangeDepth bit depth; |
| 135 | /// `false` = perfmaxxed pyramid blur/glow & fast Rgba8Unorm working textures). |
| 136 | pub hiq: bool, |
| 137 | } |
| 138 | |
| 139 | fn is_video_filename(filename: &str) -> bool { |
| 140 | let Some(ext) = std::path::Path::new(filename) |
| 141 | .extension() |
| 142 | .and_then(|e| e.to_str()) |
| 143 | else { |
| 144 | return false; |
| 145 | }; |
| 146 | matches!( |
| 147 | ext.to_ascii_lowercase().as_str(), |
| 148 | "mov" | "mp4" | "m4v" | "mkv" | "avi" | "webm" | "mxf" |
| 149 | ) |
| 150 | } |
| 151 | |
| 152 | fn is_static_loader_node(node: &Node) -> bool { |
| 153 | let Some(clip) = node.clips.first() else { |
| 154 | return false; |
| 155 | }; |
| 156 | if clip.length.unwrap_or(1) > 1 { |
| 157 | return false; |
| 158 | } |
| 159 | if is_video_filename(&clip.filename) { |
| 160 | return false; |
| 161 | } |
| 162 | if clip |
| 163 | .alternate_filename |
| 164 | .as_deref() |
| 165 | .is_some_and(is_video_filename) |
| 166 | { |
| 167 | return false; |
| 168 | } |
| 169 | if node |
| 170 | .static_str("ProxyFilename") |
| 171 | .is_some_and(is_video_filename) |
| 172 | { |
| 173 | return false; |
| 174 | } |
| 175 | true |
| 176 | } |
| 177 | |
| 178 | impl Engine { |
| 179 | pub fn new(device: wgpu::Device, queue: wgpu::Queue) -> Self { |
| 180 | let supports_f32_filter = device.features().contains(wgpu::Features::FLOAT32_FILTERABLE); |
| 181 | let pipelines = RefCell::new(ShaderRegistry::new(&device, wgpu::TextureFormat::Rgba8Unorm, false)); |
| 182 | let scene3d = crate::scene3d::Scene3DRenderer::new(&device); |
| 183 | let dummy = create_texture(&device, [1, 1], 0); |
| 184 | queue.write_texture( |
| 185 | dummy.texture.as_image_copy(), |
| 186 | &[0, 0, 0, 0], |
| 187 | wgpu::TexelCopyBufferLayout { |
| 188 | offset: 0, |
| 189 | bytes_per_row: Some(4), |
| 190 | rows_per_image: Some(1), |
| 191 | }, |
| 192 | wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, |
| 193 | ); |
| 194 | let default_vram_mb = crate::cache::default_vram_budget_mb(); |
| 195 | Self { |
| 196 | device, |
| 197 | queue, |
| 198 | pipelines, |
| 199 | pipelines_int16: OnceCell::new(), |
| 200 | pipelines_f16: OnceCell::new(), |
| 201 | pipelines_f32: OnceCell::new(), |
| 202 | aux_pipelines: OnceCell::new(), |
| 203 | alpha_keyer_pipelines: OnceCell::new(), |
| 204 | color_science_pipelines: OnceCell::new(), |
| 205 | color_lut_pipelines: OnceCell::new(), |
| 206 | depth_optical_pipelines: OnceCell::new(), |
| 207 | warps_masks_pipelines: OnceCell::new(), |
| 208 | fx_fuses_pipelines: OnceCell::new(), |
| 209 | archive_fx2_pipelines: OnceCell::new(), |
| 210 | surface_fx: OnceCell::new(), |
| 211 | layer_ocio: OnceCell::new(), |
| 212 | deep_flow: OnceCell::new(), |
| 213 | auto_matte_pipelines: OnceCell::new(), |
| 214 | auto_matte_cache: crate::auto_matte::AutoMatteCache::new(), |
| 215 | motion_blur: crate::motion_blur::MotionBlurPipelines::default(), |
| 216 | supports_f32_filter, |
| 217 | scene3d, |
| 218 | optflow: std::sync::OnceLock::new(), |
| 219 | tracker: std::sync::OnceLock::new(), |
| 220 | particles: crate::particles::ParticleCache::default(), |
| 221 | custom_shaders: crate::custom_shader::CustomShaderCache::new(), |
| 222 | fuse_registry: crate::fuse_runtime::FuseRegistry::new(), |
| 223 | sprite_cache: HashMap::new(), |
| 224 | ram_upload_tex: RefCell::new(None), |
| 225 | dummy, |
| 226 | vram_budget_bytes: default_vram_mb.saturating_mul(1024 * 1024), |
| 227 | last_bg_vram_drops: Cell::new(0), |
| 228 | cache: NodeCache::new(default_vram_mb), |
| 229 | media: MediaCache::default(), |
| 230 | expr: ExprEngine::new(), |
| 231 | frame_eval_target: None, |
| 232 | frame_memo: HashMap::new(), |
| 233 | frame_consumers: Vec::new(), |
| 234 | frame_consumers_rev: None, |
| 235 | frame_roi_memo: HashMap::new(), |
| 236 | frame_visiting: HashSet::new(), |
| 237 | frame_visiting_nodes: HashSet::new(), |
| 238 | output_cache: OutputCache::new(), |
| 239 | mask_target_size: None, |
| 240 | proxy_scale: 1, |
| 241 | use_proxy_clips: false, |
| 242 | hiq: true, |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | pub fn new_with_device( |
| 247 | device: std::sync::Arc<wgpu::Device>, |
| 248 | queue: std::sync::Arc<wgpu::Queue>, |
| 249 | vram_budget_bytes: u64, |
| 250 | media_budget_bytes: u64, |
| 251 | ) -> Self { |
| 252 | let mut eng = Self::new((*device).clone(), (*queue).clone()); |
| 253 | eng.vram_budget_bytes = vram_budget_bytes; |
| 254 | eng.cache.budget_bytes = vram_budget_bytes; |
| 255 | let media_mb = if media_budget_bytes == 0 { |
| 256 | 0 |
| 257 | } else { |
| 258 | media_budget_bytes.div_ceil(1024 * 1024) |
| 259 | }; |
| 260 | eng.media.set_budget_mb(media_mb); |
| 261 | eng |
| 262 | } |
| 263 | |
| 264 | pub fn new_headless() -> Result<Self, Box<dyn std::error::Error>> { |
| 265 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 266 | let adapter = pollster::block_on(instance.request_adapter(&Default::default()))?; |
| 267 | let mut req_features = wgpu::Features::empty(); |
| 268 | if adapter.features().contains(wgpu::Features::FLOAT32_FILTERABLE) { |
| 269 | req_features |= wgpu::Features::FLOAT32_FILTERABLE; |
| 270 | } |
| 271 | let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { |
| 272 | required_features: req_features, |
| 273 | ..Default::default() |
| 274 | }))?; |
| 275 | Ok(Self::new(device, queue)) |
| 276 | } |
| 277 | |
| 278 | fn effective_depth(&self, requested: BitDepth) -> BitDepth { |
| 279 | if !self.hiq { |
| 280 | BitDepth::Int8 |
| 281 | } else { |
| 282 | requested |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | pub(crate) fn node_depth(&self, comp: &Comp, node: &Node, time: f64, upstream: Option<BitDepth>) -> BitDepth { |
| 287 | if !self.hiq { |
| 288 | return BitDepth::Int8; |
| 289 | } |
| 290 | let explicit = comp.eval_number(node, "Depth", time, 0.0, &self.expr).round() as i32; |
| 291 | if let Some(d) = BitDepth::from_fusion_depth(explicit) { |
| 292 | return d; |
| 293 | } |
| 294 | upstream.unwrap_or(comp.depth_full) |
| 295 | } |
| 296 | |
| 297 | fn texture_format_for(&self, depth: BitDepth) -> wgpu::TextureFormat { |
| 298 | match depth { |
| 299 | BitDepth::Int8 => wgpu::TextureFormat::Rgba8Unorm, |
| 300 | BitDepth::Int16 | BitDepth::Float16 => wgpu::TextureFormat::Rgba16Float, |
| 301 | BitDepth::Float32 => { |
| 302 | if self.supports_f32_filter { |
| 303 | wgpu::TextureFormat::Rgba32Float |
| 304 | } else { |
| 305 | wgpu::TextureFormat::Rgba16Float |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | pub fn device(&self) -> &wgpu::Device { |
| 312 | &self.device |
| 313 | } |
| 314 | |
| 315 | pub fn queue(&self) -> &wgpu::Queue { |
| 316 | &self.queue |
| 317 | } |
| 318 | |
| 319 | pub fn device_arc(&self) -> std::sync::Arc<wgpu::Device> { |
| 320 | std::sync::Arc::new(self.device.clone()) |
| 321 | } |
| 322 | |
| 323 | pub fn queue_arc(&self) -> std::sync::Arc<wgpu::Queue> { |
| 324 | std::sync::Arc::new(self.queue.clone()) |
| 325 | } |
| 326 | |
| 327 | pub fn set_cache_mode(&mut self, mode: CacheMode) { |
| 328 | self.cache.mode = mode; |
| 329 | } |
| 330 | |
| 331 | pub fn set_media_budget_mb(&mut self, budget_mb: u64) { |
| 332 | self.media.set_budget_mb(budget_mb); |
| 333 | } |
| 334 | |
| 335 | fn for_each_registry(&self, mut f: impl FnMut(&mut ShaderRegistry)) { |
| 336 | f(&mut self.pipelines.borrow_mut()); |
| 337 | if let Some(r) = self.pipelines_int16.get() { |
| 338 | f(&mut r.borrow_mut()); |
| 339 | } |
| 340 | if let Some(r) = self.pipelines_f16.get() { |
| 341 | f(&mut r.borrow_mut()); |
| 342 | } |
| 343 | if let Some(r) = self.pipelines_f32.get() { |
| 344 | f(&mut r.borrow_mut()); |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | fn clear_bind_group_caches(&self) { |
| 349 | self.for_each_registry(|r| r.clear_bind_group_cache()); |
| 350 | self.last_bg_vram_drops.set(self.cache.vram_drops()); |
| 351 | } |
| 352 | |
| 353 | pub(super) fn reset_uniform_cursors(&self) { |
| 354 | self.for_each_registry(|r| r.reset_uniform_cursor()); |
| 355 | if let Some(ap) = self.aux_pipelines.get() { |
| 356 | ap.borrow_mut().reset_uniform_cursor(); |
| 357 | } |
| 358 | if let Some(ak) = self.alpha_keyer_pipelines.get() { |
| 359 | ak.borrow_mut().reset_uniform_cursor(); |
| 360 | } |
| 361 | if let Some(cs) = self.color_science_pipelines.get() { |
| 362 | cs.borrow_mut().reset_uniform_cursor(); |
| 363 | } |
| 364 | if let Some(cl) = self.color_lut_pipelines.get() { |
| 365 | cl.borrow_mut().reset_uniform_cursor(); |
| 366 | } |
| 367 | if let Some(dp) = self.depth_optical_pipelines.get() { |
| 368 | dp.borrow_mut().reset_uniform_cursor(); |
| 369 | } |
| 370 | if let Some(wm) = self.warps_masks_pipelines.get() { |
| 371 | wm.borrow_mut().reset_uniform_cursor(); |
| 372 | } |
| 373 | if let Some(ff) = self.fx_fuses_pipelines.get() { |
| 374 | ff.borrow_mut().reset_uniform_cursor(); |
| 375 | } |
| 376 | if let Some(fx2) = self.archive_fx2_pipelines.get() { |
| 377 | fx2.borrow_mut().reset_uniform_cursor(); |
| 378 | } |
| 379 | if let Some(sfx) = self.surface_fx.get() { |
| 380 | sfx.borrow_mut().reset_uniform_cursor(); |
| 381 | } |
| 382 | if let Some(lo) = self.layer_ocio.get() { |
| 383 | lo.borrow_mut().reset_uniform_cursor(); |
| 384 | } |
| 385 | if let Some(df) = self.deep_flow.get() { |
| 386 | df.borrow_mut().reset_uniform_cursor(); |
| 387 | } |
| 388 | if let Some(am) = self.auto_matte_pipelines.get() { |
| 389 | am.borrow_mut().reset_uniform_cursor(); |
| 390 | } |
| 391 | if let Some(of) = self.optflow.get() { |
| 392 | of.reset_uniform_cursor(); |
| 393 | } |
| 394 | self.media.reset_nv12_uniform_cursor(); |
| 395 | } |
| 396 | |
| 397 | fn trim_uniform_chunks(&self) { |
| 398 | self.for_each_registry(|r| r.trim_uniform_chunks(2)); |
| 399 | if let Some(ap) = self.aux_pipelines.get() { |
| 400 | ap.borrow_mut().trim_uniform_chunks(2); |
| 401 | } |
| 402 | if let Some(ak) = self.alpha_keyer_pipelines.get() { |
| 403 | ak.borrow_mut().trim_uniform_chunks(2); |
| 404 | } |
| 405 | if let Some(cs) = self.color_science_pipelines.get() { |
| 406 | cs.borrow_mut().trim_uniform_chunks(2); |
| 407 | } |
| 408 | if let Some(cl) = self.color_lut_pipelines.get() { |
| 409 | cl.borrow_mut().trim_uniform_chunks(2); |
| 410 | } |
| 411 | if let Some(dp) = self.depth_optical_pipelines.get() { |
| 412 | dp.borrow_mut().trim_uniform_chunks(2); |
| 413 | } |
| 414 | if let Some(wm) = self.warps_masks_pipelines.get() { |
| 415 | wm.borrow_mut().trim_uniform_chunks(2); |
| 416 | } |
| 417 | if let Some(ff) = self.fx_fuses_pipelines.get() { |
| 418 | ff.borrow_mut().trim_uniform_chunks(2); |
| 419 | } |
| 420 | if let Some(fx2) = self.archive_fx2_pipelines.get() { |
| 421 | fx2.borrow_mut().trim_uniform_chunks(2); |
| 422 | } |
| 423 | if let Some(sfx) = self.surface_fx.get() { |
| 424 | sfx.borrow_mut().trim_uniform_chunks(2); |
| 425 | } |
| 426 | if let Some(lo) = self.layer_ocio.get() { |
| 427 | lo.borrow_mut().trim_uniform_chunks(2); |
| 428 | } |
| 429 | if let Some(df) = self.deep_flow.get() { |
| 430 | df.borrow_mut().trim_uniform_chunks(2); |
| 431 | } |
| 432 | if let Some(am) = self.auto_matte_pipelines.get() { |
| 433 | am.borrow_mut().trim_uniform_chunks(2); |
| 434 | } |
| 435 | self.media.trim_nv12_uniform_chunks(2); |
| 436 | } |
| 437 | |
| 438 | pub(super) fn sync_bg_cache_with_vram_drops(&mut self) { |
| 439 | let drops = self.cache.vram_drops(); |
| 440 | if drops != self.last_bg_vram_drops.get() { |
| 441 | self.custom_shaders.clear_bind_group_cache(); |
| 442 | self.clear_bind_group_caches(); |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | pub fn bust_all_caches(&mut self) { |
| 447 | self.output_cache.clear(); |
| 448 | self.sync_node_cache_budget(); |
| 449 | self.cache.bust_all(); |
| 450 | self.custom_shaders.clear_bind_group_cache(); |
| 451 | self.custom_shaders.trim_uniform_chunks(2); |
| 452 | self.clear_bind_group_caches(); |
| 453 | self.trim_uniform_chunks(); |
| 454 | if let Some(of) = self.optflow.get() { |
| 455 | of.clear_scratch(); |
| 456 | } |
| 457 | if let Some(cl) = self.color_lut_pipelines.get() { |
| 458 | cl.borrow_mut().clear_lut_cache(); |
| 459 | } |
| 460 | #[cfg(not(target_arch = "wasm32"))] |
| 461 | self.pipelines.borrow_mut().readback_pool.clear(); |
| 462 | self.media.clear(); |
| 463 | self.particles.clear(); |
| 464 | self.sprite_cache.clear(); |
| 465 | self.scene3d.clear_shadow_targets(); |
| 466 | self.frame_consumers.clear(); |
| 467 | self.frame_consumers_rev = None; |
| 468 | *self.ram_upload_tex.borrow_mut() = None; |
| 469 | io::clear_dims_cache(); |
| 470 | } |
| 471 | |
| 472 | pub fn bust_gpu_cache(&mut self) { |
| 473 | self.output_cache.clear(); |
| 474 | self.sync_node_cache_budget(); |
| 475 | self.cache.bust_all(); |
| 476 | self.custom_shaders.clear_bind_group_cache(); |
| 477 | self.custom_shaders.trim_uniform_chunks(2); |
| 478 | self.clear_bind_group_caches(); |
| 479 | self.trim_uniform_chunks(); |
| 480 | if let Some(of) = self.optflow.get() { |
| 481 | of.clear_scratch(); |
| 482 | } |
| 483 | if let Some(cl) = self.color_lut_pipelines.get() { |
| 484 | cl.borrow_mut().clear_lut_cache(); |
| 485 | } |
| 486 | self.media.clear_nv12_gpu_state(); |
| 487 | #[cfg(not(target_arch = "wasm32"))] |
| 488 | self.pipelines.borrow_mut().readback_pool.clear(); |
| 489 | self.sprite_cache.clear(); |
| 490 | self.scene3d.clear_shadow_targets(); |
| 491 | *self.ram_upload_tex.borrow_mut() = None; |
| 492 | } |
| 493 | |
| 494 | pub fn bust_frame(&mut self, frame: i64) -> usize { |
| 495 | self.output_cache.clear(); |
| 496 | self.sync_node_cache_budget(); |
| 497 | let busted = self.cache.bust_frame(frame); |
| 498 | self.custom_shaders.clear_bind_group_cache(); |
| 499 | self.clear_bind_group_caches(); |
| 500 | busted |
| 501 | } |
| 502 | |
| 503 | pub fn bust_subtree(&mut self, node: NodeId) -> usize { |
| 504 | self.output_cache.clear(); |
| 505 | self.sync_node_cache_budget(); |
| 506 | let busted = self.cache.bust_subtree(node); |
| 507 | self.custom_shaders.clear_bind_group_cache(); |
| 508 | self.clear_bind_group_caches(); |
| 509 | busted |
| 510 | } |
| 511 | |
| 512 | fn prepare_frame_scratch(&mut self, comp: &Comp) -> HashSet<(NodeId, i64)> { |
| 513 | self.frame_eval_target = None; |
| 514 | self.frame_memo.clear(); |
| 515 | self.frame_roi_memo.clear(); |
| 516 | if self.frame_consumers_rev != Some(comp.revision) |
| 517 | || self.frame_consumers.len() != comp.nodes.len() |
| 518 | { |
| 519 | self.frame_consumers.clear(); |
| 520 | self.frame_consumers_rev = Some(comp.revision); |
| 521 | } |
| 522 | let mut visiting = std::mem::take(&mut self.frame_visiting); |
| 523 | visiting.clear(); |
| 524 | self.frame_visiting_nodes.clear(); |
| 525 | visiting |
| 526 | } |
| 527 | |
| 528 | fn finish_frame_scratch(&mut self, mut visiting: HashSet<(NodeId, i64)>) { |
| 529 | self.frame_eval_target = None; |
| 530 | self.frame_memo.clear(); |
| 531 | self.frame_roi_memo.clear(); |
| 532 | visiting.clear(); |
| 533 | self.frame_visiting = visiting; |
| 534 | self.frame_visiting_nodes.clear(); |
| 535 | } |
| 536 | |
| 537 | /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. |
| 538 | pub fn evaluate( |
| 539 | &mut self, |
| 540 | comp: &Comp, |
| 541 | target: NodeId, |
| 542 | time: f64, |
| 543 | ) -> (CachedTexture, EvalStats) { |
| 544 | let t0 = Instant::now(); |
| 545 | self.sync_bg_cache_with_vram_drops(); |
| 546 | let out_key = self.output_cache_key(comp, target, time) |
| 547 | ^ self.auto_matte_cache.generation().wrapping_mul(0x9e37_79b9_7f4a_7c15); |
| 548 | if let Some((tex, unsupported)) = self.output_cache_get(out_key) { |
| 549 | let stats = EvalStats { |
| 550 | eval_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| 551 | cache_hits: 1, |
| 552 | cached_entries: self.cache.entry_count(), |
| 553 | cached_vram_mb: self.vram_mb(), |
| 554 | media_entries: self.media.entry_count(), |
| 555 | media_mb: self.media.total_mb(), |
| 556 | unsupported_nodes: unsupported, |
| 557 | ..EvalStats::default() |
| 558 | }; |
| 559 | return (tex, stats); |
| 560 | } |
| 561 | let mut stats = EvalStats::default(); |
| 562 | self.media |
| 563 | .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); |
| 564 | let mut visiting = self.prepare_frame_scratch(comp); |
| 565 | self.frame_eval_target = Some(target); |
| 566 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 567 | label: Some("comp-eval"), |
| 568 | }); |
| 569 | |
| 570 | let mut tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); |
| 571 | if tex.has_dod() { |
| 572 | // Crop expanded DoD cleanly back to logical canvas_size for final readback/export |
| 573 | tex = self.crop_to_canvas(&mut encoder, tex); |
| 574 | } |
| 575 | self.queue.submit(Some(encoder.finish())); |
| 576 | self.reset_uniform_cursors(); |
| 577 | self.custom_shaders.reset_uniform_cursor(); |
| 578 | #[cfg(not(target_arch = "wasm32"))] |
| 579 | self.media.flush_upload_staging_after_submit(&self.device); |
| 580 | self.finish_frame_scratch(visiting); |
| 581 | self.cache.flush_pending_pool(); |
| 582 | self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); |
| 583 | self.sync_bg_cache_with_vram_drops(); |
| 584 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 585 | stats.cached_entries = self.cache.entry_count(); |
| 586 | stats.cached_vram_mb = self.vram_mb(); |
| 587 | stats.media_entries = self.media.entry_count(); |
| 588 | stats.media_mb = self.media.total_mb(); |
| 589 | (tex, stats) |
| 590 | } |
| 591 | |
| 592 | /// Zero-copy render straight into a persistent viewer `wgpu::Texture` (premultiplied Rgba8Unorm). |
| 593 | pub fn render_into_viewer( |
| 594 | &mut self, |
| 595 | comp: &Comp, |
| 596 | target: NodeId, |
| 597 | time: f64, |
| 598 | dst_texture: &wgpu::Texture, |
| 599 | display: DisplaySettings, |
| 600 | ) -> EvalStats { |
| 601 | let t0 = Instant::now(); |
| 602 | self.sync_bg_cache_with_vram_drops(); |
| 603 | let out_key = self.output_cache_key(comp, target, time) |
| 604 | ^ self.auto_matte_cache.generation().wrapping_mul(0x9e37_79b9_7f4a_7c15); |
| 605 | let mut stats = EvalStats::default(); |
| 606 | let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 607 | label: Some("comp-viewer-eval"), |
| 608 | }); |
| 609 | |
| 610 | let (tex, visiting_opt) = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { |
| 611 | stats.cache_hits = 1; |
| 612 | stats.unsupported_nodes = unsupported; |
| 613 | (cached, None) |
| 614 | } else { |
| 615 | self.media |
| 616 | .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); |
| 617 | let mut visiting = self.prepare_frame_scratch(comp); |
| 618 | self.frame_eval_target = Some(target); |
| 619 | let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); |
| 620 | (t, Some(visiting)) |
| 621 | }; |
| 622 | |
| 623 | let dst_size = [dst_texture.width(), dst_texture.height()]; |
| 624 | let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default()); |
| 625 | let mut params = UniformParams::default(); |
| 626 | params.p[0] = [ |
| 627 | 2.0_f32.powf(display.exposure), |
| 628 | display.gamma, |
| 629 | display.channel as f32, |
| 630 | if display.checker_bg { 1.0 } else { 0.0 }, |
| 631 | ]; |
| 632 | params.p[1] = display.uv_rect; |
| 633 | params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0]; |
| 634 | if tex.has_dod() { |
| 635 | params.p[4] = [ |
| 636 | tex.origin[0] as f32, |
| 637 | tex.origin[1] as f32, |
| 638 | tex.canvas_size[0] as f32, |
| 639 | tex.canvas_size[1] as f32, |
| 640 | ]; |
| 641 | } |
| 642 | self.dispatch_to_view_uncached( |
| 643 | &mut encoder, |
| 644 | ShaderOp::DisplayBlit, |
| 645 | &tex.view, |
| 646 | &self.dummy.view, |
| 647 | &self.dummy.view, |
| 648 | &dst_view, |
| 649 | dst_size, |
| 650 | &params, |
| 651 | ); |
| 652 | |
| 653 | self.queue.submit(Some(encoder.finish())); |
| 654 | self.reset_uniform_cursors(); |
| 655 | self.custom_shaders.reset_uniform_cursor(); |
| 656 | #[cfg(not(target_arch = "wasm32"))] |
| 657 | self.media.flush_upload_staging_after_submit(&self.device); |
| 658 | if let Some(visiting) = visiting_opt { |
| 659 | self.finish_frame_scratch(visiting); |
| 660 | self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone()); |
| 661 | } |
| 662 | self.cache.flush_pending_pool(); |
| 663 | self.sync_bg_cache_with_vram_drops(); |
| 664 | |
| 665 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 666 | stats.cached_entries = self.cache.entry_count(); |
| 667 | stats.cached_vram_mb = self.vram_mb(); |
| 668 | stats.media_entries = self.media.entry_count(); |
| 669 | stats.media_mb = self.media.total_mb(); |
| 670 | stats |
| 671 | } |
| 672 | |
| 673 | fn scaled_dims(&self, w: u32, h: u32) -> [u32; 2] { |
| 674 | let s = self.proxy_scale.max(1); |
| 675 | [(w / s).max(1), (h / s).max(1)] |
| 676 | } |
| 677 | |
| 678 | pub(crate) fn eval_node( |
| 679 | &mut self, |
| 680 | comp: &Comp, |
| 681 | id: NodeId, |
| 682 | time: f64, |
| 683 | enc: &mut wgpu::CommandEncoder, |
| 684 | visiting: &mut HashSet<(NodeId, i64)>, |
| 685 | stats: &mut EvalStats, |
| 686 | ) -> CachedTexture { |
| 687 | const MAX_EVAL_DEPTH: usize = 256; |
| 688 | if id.0 >= comp.nodes.len() || visiting.len() >= MAX_EVAL_DEPTH { |
| 689 | return self.dummy.clone(); |
| 690 | } |
| 691 | let frame_i = time.round() as i64; |
| 692 | let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; |
| 693 | let memo_sz = self.mask_target_size; |
| 694 | // Always memoize within a single frame's DAG pass so diamond graphs never explode |
| 695 | // exponentially (even in CacheMode::Bypass, which bypasses the cross-frame cache). |
| 696 | if let Some(hit) = self.frame_memo.get(&(id, time_key, memo_sz)).cloned() { |
| 697 | stats.cache_hits += 1; |
| 698 | return hit; |
| 699 | } |
| 700 | if !self.frame_visiting_nodes.insert(id) { |
| 701 | return self.dummy.clone(); |
| 702 | } |
| 703 | if !visiting.insert((id, time_key)) { |
| 704 | self.frame_visiting_nodes.remove(&id); |
| 705 | return self.dummy.clone(); |
| 706 | } |
| 707 | let mb_cfg = if self.hiq && !comp.node(id).bypassed { |
| 708 | crate::motion_blur::read_motion_blur_config(comp, comp.node(id), time, &self.expr) |
| 709 | } else { |
| 710 | None |
| 711 | }; |
| 712 | let res = if let Some(cfg) = mb_cfg { |
| 713 | self.eval_node_motion_blur(comp, id, time, frame_i, cfg, enc, visiting, stats) |
| 714 | } else { |
| 715 | self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats) |
| 716 | }; |
| 717 | visiting.remove(&(id, time_key)); |
| 718 | self.frame_visiting_nodes.remove(&id); |
| 719 | if res.content_hash != 0 { |
| 720 | let node = comp.node(id); |
| 721 | let sticky = match node.kind.as_str() { |
| 722 | "Loader" | "MediaIn" => is_static_loader_node(node), |
| 723 | "TextPlus" | "Renderer3D" | "pRender" | "PolylineMask" | "BSplineMask" | "MultiPoly" | "TeapotMask" | "WandMask" => true, |
| 724 | _ => false, |
| 725 | }; |
| 726 | if sticky { |
| 727 | self.cache.mark_entry_sticky(res.content_hash); |
| 728 | } |
| 729 | } |
| 730 | self.frame_memo.insert((id, time_key, memo_sz), res.clone()); |
| 731 | res |
| 732 | } |
| 733 | |
| 734 | #[allow(clippy::too_many_arguments)] |
| 735 | fn eval_node_motion_blur( |
| 736 | &mut self, |
| 737 | comp: &Comp, |
| 738 | id: NodeId, |
| 739 | time: f64, |
| 740 | frame_i: i64, |
| 741 | cfg: crate::motion_blur::MotionBlurConfig, |
| 742 | enc: &mut wgpu::CommandEncoder, |
| 743 | visiting: &mut HashSet<(NodeId, i64)>, |
| 744 | stats: &mut EvalStats, |
| 745 | ) -> CachedTexture { |
| 746 | let times = cfg.shutter_times(time); |
| 747 | if times.len() < 2 { |
| 748 | return self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats); |
| 749 | } |
| 750 | let mut samples = Vec::with_capacity(times.len()); |
| 751 | for t_k in times { |
| 752 | let s = self.eval_node_inner(comp, id, t_k, t_k.round() as i64, enc, visiting, stats); |
| 753 | samples.push(s); |
| 754 | } |
| 755 | let center_idx = samples.len() / 2; |
| 756 | let first = &samples[0]; |
| 757 | if first.content_hash != 0 |
| 758 | && samples.iter().all(|s| { |
| 759 | s.content_hash == first.content_hash |
| 760 | && s.origin == first.origin |
| 761 | && s.size == first.size |
| 762 | }) |
| 763 | { |
| 764 | return samples.swap_remove(center_idx); |
| 765 | } |
| 766 | let center = &samples[center_idx]; |
| 767 | let mut hasher = std::collections::hash_map::DefaultHasher::new(); |
| 768 | "motion_blur".hash(&mut hasher); |
| 769 | id.0.hash(&mut hasher); |
| 770 | self.cache.gpu_salt.hash(&mut hasher); |
| 771 | self.cache.node_salt(id).hash(&mut hasher); |
| 772 | cfg.cache_key_bits().hash(&mut hasher); |
| 773 | center.format.hash(&mut hasher); |
| 774 | center.depth.hash(&mut hasher); |
| 775 | for s in &samples { |
| 776 | s.content_hash.hash(&mut hasher); |
| 777 | s.origin.hash(&mut hasher); |
| 778 | s.size.hash(&mut hasher); |
| 779 | } |
| 780 | let mb_key = hasher.finish(); |
| 781 | if let Some(hit) = self.cache.get(mb_key, id, frame_i) { |
| 782 | stats.cache_hits += 1; |
| 783 | return hit; |
| 784 | } |
| 785 | let mut out = self.motion_blur.accumulate_samples( |
| 786 | &self.device, |
| 787 | &self.queue, |
| 788 | enc, |
| 789 | &samples, |
| 790 | center.depth, |
| 791 | center.format, |
| 792 | mb_key, |
| 793 | ); |
| 794 | if center.aux.is_some() && (center.origin != out.origin || center.size != out.size) { |
| 795 | self.reorigin_aux(enc, center, &mut out); |
| 796 | } |
| 797 | self.cache.insert(mb_key, out.clone(), id, frame_i); |
| 798 | out |
| 799 | } |
| 800 | |
| 801 | fn switch_input_port(idx: usize) -> Option<&'static str> { |
| 802 | match idx { |
| 803 | 0 => Some("Input0"), |
| 804 | 1 => Some("Input1"), |
| 805 | 2 => Some("Input2"), |
| 806 | 3 => Some("Input3"), |
| 807 | 4 => Some("Input4"), |
| 808 | 5 => Some("Input5"), |
| 809 | 6 => Some("Input6"), |
| 810 | 7 => Some("Input7"), |
| 811 | 8 => Some("Input8"), |
| 812 | 9 => Some("Input9"), |
| 813 | 10 => Some("Input10"), |
| 814 | 11 => Some("Input11"), |
| 815 | 12 => Some("Input12"), |
| 816 | 13 => Some("Input13"), |
| 817 | 14 => Some("Input14"), |
| 818 | 15 => Some("Input15"), |
| 819 | 16 => Some("Input16"), |
| 820 | _ => None, |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | fn eval_node_inner( |
| 825 | &mut self, |
| 826 | comp: &Comp, |
| 827 | id: NodeId, |
| 828 | time: f64, |
| 829 | frame_i: i64, |
| 830 | enc: &mut wgpu::CommandEncoder, |
| 831 | visiting: &mut HashSet<(NodeId, i64)>, |
| 832 | stats: &mut EvalStats, |
| 833 | ) -> CachedTexture { |
| 834 | let node = comp.node(id); |
| 835 | let comp_dims = self.scaled_dims(comp.width, comp.height); |
| 836 | |
| 837 | // Bypass (`PassThrough`) or passthrough utility nodes |
| 838 | if node.bypassed |
| 839 | || matches!( |
| 840 | node.kind.as_str(), |
| 841 | "Saver" |
| 842 | | "PipeRouter" |
| 843 | | "Fuse.Wireless" |
| 844 | | "Tracker" |
| 845 | ) |
| 846 | { |
| 847 | let port = default_main_input_port(&node.kind); |
| 848 | if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { |
| 849 | return self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 850 | } |
| 851 | return self.dummy.clone(); |
| 852 | } |
| 853 | |
| 854 | // MacroOperator / GroupOperator: seamlessly evaluate the unpacked internal output tool! |
| 855 | if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") { |
| 856 | if let Some(out_id) = node.macro_output { |
| 857 | return self.eval_node(comp, out_id, time, enc, visiting, stats); |
| 858 | } |
| 859 | if let Some(src_id) = node |
| 860 | .connected_node("Input") |
| 861 | .or_else(|| node.connected_node("MainInput1")) |
| 862 | .and_then(|s| comp.find_node(s)) |
| 863 | { |
| 864 | return self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 865 | } |
| 866 | return self.dummy.clone(); |
| 867 | } |
| 868 | |
| 869 | // TimeStretcher / TimeSpeed: remap time BEFORE evaluating upstream! |
| 870 | if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") { |
| 871 | if let Some(remapped) = self.remap_time_node(comp, node, time) { |
| 872 | return self.eval_time_remapped(comp, node, time, frame_i, remapped, enc, visiting, stats); |
| 873 | } |
| 874 | } |
| 875 | if node.kind == "Switch" || node.kind == "Fuse.Switch" { |
| 876 | let is_native_zero_indexed = node.kind == "Switch" |
| 877 | && (node.inputs.contains_key("Source") |
| 878 | || node.inputs.contains_key("Input0") |
| 879 | || !node.inputs.contains_key("Which")); |
| 880 | let src_name = if is_native_zero_indexed { |
| 881 | let source = comp |
| 882 | .eval_number(node, "Source", time, 0.0, &self.expr) |
| 883 | .round() |
| 884 | .max(0.0) as usize; |
| 885 | if let Some(port) = Self::switch_input_port(source) { |
| 886 | node.connected_node(port) |
| 887 | } else { |
| 888 | let port = format!("Input{source}"); |
| 889 | node.connected_node(&port) |
| 890 | } |
| 891 | .or_else(|| node.connected_node("Input0")) |
| 892 | } else { |
| 893 | let which = comp |
| 894 | .eval_number(node, "Which", time, 1.0, &self.expr) |
| 895 | .round() |
| 896 | .max(1.0) as usize; |
| 897 | if let Some(port) = Self::switch_input_port(which) { |
| 898 | node.connected_node(port) |
| 899 | } else { |
| 900 | let port = format!("Input{which}"); |
| 901 | node.connected_node(&port) |
| 902 | } |
| 903 | .or_else(|| node.connected_node("Input1")) |
| 904 | }; |
| 905 | if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) { |
| 906 | return self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 907 | } |
| 908 | return self.dummy.clone(); |
| 909 | } |
| 910 | |
| 911 | match node.kind.as_str() { |
| 912 | "Loader" => self.eval_loader(comp, node, time, frame_i, enc, visiting, stats), |
| 913 | "MediaIn" => self.eval_media_in(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 914 | "MediaOut" => self.eval_media_out(comp, node, time, enc, visiting, stats), |
| 915 | "Background" => self.eval_background(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 916 | "Merge" => self.eval_merge(comp, node, time, frame_i, enc, visiting, stats), |
| 917 | "MultiMerge" | "Fuse.MultiMerge" => self.eval_multi_merge(comp, node, time, frame_i, enc, visiting, stats), |
| 918 | "Dissolve" => self.eval_dissolve(comp, node, time, frame_i, enc, visiting, stats), |
| 919 | "Transform" => self.eval_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 920 | "CameraShake" => self.eval_camera_shake(comp, node, time, frame_i, enc, visiting, stats), |
| 921 | "CornerPositioner" => self.eval_corner_positioner(comp, node, time, frame_i, enc, visiting, stats), |
| 922 | "PerspectivePositioner" => self.eval_perspective_positioner(comp, node, time, frame_i, enc, visiting, stats), |
| 923 | "DVE" => self.eval_dve(comp, node, time, frame_i, enc, visiting, stats), |
| 924 | "Shadow" => self.eval_shadow(comp, node, time, frame_i, enc, visiting, stats), |
| 925 | "Scale" | "BetterResize" => self.eval_scale(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 926 | "Letterbox" => self.eval_letterbox(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 927 | "Crop" => self.eval_crop(comp, node, time, frame_i, enc, visiting, stats), |
| 928 | "SetDomain" => self.eval_set_domain(comp, node, time, frame_i, enc, visiting, stats), |
| 929 | "ChangeDepth" => { |
| 930 | let mut out = self.eval_change_depth(comp, node, time, frame_i, enc, visiting, stats); |
| 931 | if out.aux.is_none() |
| 932 | && let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) |
| 933 | { |
| 934 | let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; |
| 935 | if let Some(src) = self.frame_memo.get(&(src_id, time_key, self.mask_target_size)) |
| 936 | && src.aux.is_some() |
| 937 | && src.size == out.size |
| 938 | { |
| 939 | out.set_aux(src.aux.clone()); |
| 940 | } |
| 941 | } |
| 942 | out |
| 943 | } |
| 944 | "Dimension.CopyAux" => self.eval_copy_aux(comp, node, time, frame_i, enc, visiting, stats), |
| 945 | "Dimension.OpticalFlow" | "OpticalFlow" => self.eval_optical_flow(comp, node, time, frame_i, enc, visiting, stats), |
| 946 | "VectorMotionBlur" => self.eval_vector_motion_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 947 | "VectorDenoise" => self.eval_vector_denoise(comp, node, time, frame_i, enc, visiting, stats), |
| 948 | "BrightnessContrast" => self.eval_bc(comp, node, time, frame_i, enc, visiting, stats), |
| 949 | "ColorCorrector" => self.eval_cc(comp, node, time, frame_i, enc, visiting, stats), |
| 950 | "ColorGain" => self.eval_color_gain(comp, node, time, frame_i, enc, visiting, stats), |
| 951 | "ColorCurves" => self.eval_color_curves(comp, node, time, frame_i, enc, visiting, stats), |
| 952 | "HueCurves" => self.eval_hue_curves(comp, node, time, frame_i, enc, visiting, stats), |
| 953 | "GamutConvert" => self.eval_gamut_convert(comp, node, time, frame_i, enc, visiting, stats), |
| 954 | "AcesTransform" => self.eval_aces_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 955 | "ColorSpace" => self.eval_color_space(comp, node, time, frame_i, enc, visiting, stats), |
| 956 | "ColorMatrix" => self.eval_color_matrix(comp, node, time, frame_i, enc, visiting, stats), |
| 957 | "CustomColorMatrix" => self.eval_custom_color_matrix(comp, node, time, frame_i, enc, visiting, stats), |
| 958 | "SetCanvasColor" => self.eval_set_canvas_color(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 959 | "ChromaticAdaptation" => self.eval_chromatic_adaptation(comp, node, time, frame_i, enc, visiting, stats), |
| 960 | "ColorSpaceTransform" => self.eval_color_space_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 961 | "GamutLimiter" => self.eval_gamut_limiter(comp, node, time, frame_i, enc, visiting, stats), |
| 962 | "GamutMapping" => self.eval_gamut_mapping(comp, node, time, frame_i, enc, visiting, stats), |
| 963 | "FilmLookCreator" => self.eval_film_look_creator(comp, node, time, frame_i, enc, visiting, stats), |
| 964 | "OCIOCDLTransform" => self.eval_ocio_cdl_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 965 | "FileLUT" => self.eval_file_lut(comp, node, time, frame_i, enc, visiting, stats), |
| 966 | "Fuse.LUTCubeCreator" | "LUTCubeCreator" => self.eval_lut_cube_creator(comp, node, time, frame_i, enc, stats), |
| 967 | "Fuse.LUTCubeApply" | "LUTCubeApply" => self.eval_lut_cube_apply(comp, node, time, frame_i, enc, visiting, stats), |
| 968 | "Fuse.LUTCubeAnalyzer" | "LUTCubeAnalyzer" => self.eval_lut_cube_analyzer(comp, node, time, frame_i, enc, visiting, stats), |
| 969 | "WhiteBalance" => self.eval_white_balance(comp, node, time, frame_i, enc, visiting, stats), |
| 970 | "MatteControl" => self.eval_matte_control(comp, node, time, frame_i, enc, visiting, stats), |
| 971 | "InvertColor" => self.eval_invert(comp, node, time, frame_i, enc, visiting, stats), |
| 972 | "AlphaMultiply" => self.eval_alpha_multiply(comp, node, time, frame_i, enc, visiting, stats), |
| 973 | "AlphaDivide" => self.eval_alpha_divide(comp, node, time, frame_i, enc, visiting, stats), |
| 974 | "PseudoColor" => self.eval_pseudo_color(comp, node, time, frame_i, enc, visiting, stats), |
| 975 | "ChannelBoolean" => self.eval_channel_boolean(comp, node, time, frame_i, enc, visiting, stats), |
| 976 | "LumaKeyer" => self.eval_luma_key(comp, node, time, frame_i, enc, visiting, stats), |
| 977 | "UltraKeyer" => self.eval_ultra_keyer(comp, node, time, frame_i, enc, visiting, stats), |
| 978 | "DeltaKeyer" => self.eval_delta_keyer(comp, node, time, frame_i, enc, visiting, stats), |
| 979 | "DifferenceKeyer" => self.eval_difference_keyer(comp, node, time, frame_i, enc, visiting, stats), |
| 980 | "ChromaKeyer" => self.eval_chroma_keyer(comp, node, time, frame_i, enc, visiting, stats), |
| 981 | "CleanPLate" | "CleanPlate" => self.eval_clean_plate(comp, node, time, frame_i, enc, visiting, stats), |
| 982 | "Blur" => self.eval_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 983 | "Sharpen" => self.eval_sharpen(comp, node, time, frame_i, enc, visiting, stats), |
| 984 | "UnsharpMask" => self.eval_unsharp_mask(comp, node, time, frame_i, enc, visiting, stats), |
| 985 | "Filter" => self.eval_filter(comp, node, time, frame_i, enc, visiting, stats), |
| 986 | "RemoveNoise" => self.eval_remove_noise(comp, node, time, frame_i, enc, visiting, stats), |
| 987 | "VariBlur" => self.eval_vari_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 988 | "DirectionalBlur" => self.eval_dir_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 989 | "Glow" | "SoftGlow" => self.eval_glow(comp, node, time, frame_i, enc, visiting, stats), |
| 990 | "Fuse.XGlow" => self.eval_xglow(comp, node, time, frame_i, enc, visiting, stats), |
| 991 | "DepthBlur" => self.eval_depth_blur(comp, node, time, frame_i, enc, visiting, stats), |
| 992 | "Fog" => self.eval_fog(comp, node, time, frame_i, enc, visiting, stats), |
| 993 | "Highlight" => self.eval_highlight(comp, node, time, frame_i, enc, visiting, stats), |
| 994 | "HotSpot" => self.eval_hot_spot(comp, node, time, frame_i, enc, visiting, stats), |
| 995 | "RankFilter" => self.eval_rank_filter(comp, node, time, frame_i, enc, visiting, stats), |
| 996 | "ErodeDilate" => { |
| 997 | let mut out = self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats); |
| 998 | if self.multiplies_by_mask(comp, node, time) { |
| 999 | let (mask, mask_inv) = self.eval_mask_input_sized( |
| 1000 | comp, |
| 1001 | node, |
| 1002 | time, |
| 1003 | Some(out.canvas_size), |
| 1004 | enc, |
| 1005 | visiting, |
| 1006 | stats, |
| 1007 | ); |
| 1008 | if let Some(m) = mask { |
| 1009 | let out_c = self.crop_to_canvas(enc, out); |
| 1010 | let key = self.make_key( |
| 1011 | node, |
| 1012 | "ErodeDilateMBM", |
| 1013 | out_c.size, |
| 1014 | &[out_c.content_hash, m.content_hash], |
| 1015 | &[if mask_inv { 1.0 } else { 0.0 }], |
| 1016 | ); |
| 1017 | out = if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1018 | hit |
| 1019 | } else { |
| 1020 | let dst = self.alloc_tex(out_c.size, out_c.depth, key); |
| 1021 | let mut u = UniformParams::default(); |
| 1022 | u.p[0][0] = if mask_inv { 1.0 } else { 0.0 }; |
| 1023 | self.dispatch_op( |
| 1024 | enc, |
| 1025 | ShaderOp::MaskApply, |
| 1026 | &out_c.view, |
| 1027 | &self.dummy.view, |
| 1028 | &m.view, |
| 1029 | &dst, |
| 1030 | &u, |
| 1031 | ); |
| 1032 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1033 | dst |
| 1034 | }; |
| 1035 | } |
| 1036 | } |
| 1037 | out |
| 1038 | } |
| 1039 | "FastNoise" => self.eval_fast_noise(comp, node, time, frame_i, comp_dims, enc, stats), |
| 1040 | "Plasma" => self.eval_plasma(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1041 | "DaySky" => self.eval_day_sky(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1042 | "Mandel" => self.eval_mandel(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1043 | "FilmGrain" => self.eval_film_grain(comp, node, time, frame_i, enc, visiting, stats), |
| 1044 | "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats), |
| 1045 | "Vortex" => self.eval_vortex(comp, node, time, frame_i, enc, visiting, stats), |
| 1046 | "Drip" => self.eval_drip(comp, node, time, frame_i, enc, visiting, stats), |
| 1047 | "Dent" => self.eval_dent(comp, node, time, frame_i, enc, visiting, stats), |
| 1048 | "GridWarp" => self.eval_grid_warp(comp, node, time, frame_i, enc, visiting, stats), |
| 1049 | "CoordSpace" => self.eval_coord_space(comp, node, time, frame_i, enc, visiting, stats), |
| 1050 | "LensDistort" => self.eval_lens_distort(comp, node, time, frame_i, enc, visiting, stats), |
| 1051 | "Trails" => self.eval_trails(comp, node, time, frame_i, enc, visiting, stats), |
| 1052 | "Fuse.Duplicate" => self.eval_duplicate(comp, node, time, frame_i, enc, visiting, stats), |
| 1053 | "Fuse.KScope" => self.eval_kscope(comp, node, time, frame_i, enc, visiting, stats), |
| 1054 | "Fuse.SwitchElse" => self.eval_switch_else(comp, node, time, enc, visiting, stats), |
| 1055 | "Fuse.CheckerPieceGenerator" => self.eval_checker_piece(comp, node, time, frame_i, enc, stats), |
| 1056 | "Fuse.AlphaWeightedNoise" => self.eval_alpha_weighted_noise(comp, node, time, frame_i, enc, visiting, stats), |
| 1057 | "Fuse.Crystallize" => self.eval_crystallize(comp, node, time, frame_i, enc, visiting, stats), |
| 1058 | "Fuse.HexagonTiles" => self.eval_hexagon_tiles(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1059 | "Fuse.Wipe" => self.eval_fuse_wipe(comp, node, time, frame_i, enc, visiting, stats), |
| 1060 | "Fuse.Null" => self.eval_fuse_null(comp, node, time, enc, visiting, stats), |
| 1061 | "Fuse.SetMetaData" => self.eval_fuse_set_metadata(comp, node, time, enc, visiting, stats), |
| 1062 | "Fuse.Linger" => self.eval_fuse_linger(comp, node, time, frame_i, enc, visiting, stats), |
| 1063 | "Fuse.OCLRays" => self.eval_fuse_ocl_rays(comp, node, time, frame_i, enc, visiting, stats), |
| 1064 | "Fuse.Hexagon" => self.eval_fuse_hexagon(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1065 | "Fuse.Lightning" => self.eval_fuse_lightning(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1066 | "Fuse.VORONOI_DIAGRAM" => self.eval_fuse_voronoi_diagram(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1067 | "Defocus" => self.eval_defocus(comp, node, time, frame_i, enc, visiting, stats), |
| 1068 | "AutoGain" => self.eval_auto_gain(comp, node, time, frame_i, enc, visiting, stats), |
| 1069 | "ColorBalance" => self.eval_color_balance(comp, node, time, frame_i, enc, visiting, stats), |
| 1070 | "SoftClip" => self.eval_soft_clip(comp, node, time, frame_i, enc, visiting, stats), |
| 1071 | "Grain" => self.eval_grain(comp, node, time, frame_i, enc, visiting, stats), |
| 1072 | "Distort" => self.eval_distort(comp, node, time, frame_i, enc, visiting, stats), |
| 1073 | "CreateBumpMap" => self.eval_create_bump_map(comp, node, time, frame_i, enc, visiting, stats), |
| 1074 | "CreateReliefMap" => self.eval_create_relief_map(comp, node, time, frame_i, enc, visiting, stats), |
| 1075 | "CustomFilter" => self.eval_custom_filter(comp, node, time, frame_i, enc, visiting, stats), |
| 1076 | "CineonLog" => self.eval_cineon_log(comp, node, time, frame_i, enc, visiting, stats), |
| 1077 | "LightTrim" => self.eval_light_trim(comp, node, time, frame_i, enc, visiting, stats), |
| 1078 | "MultiPoly" => self.eval_multi_poly(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1079 | "RangesMask" => self.eval_ranges_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1080 | "TeapotMask" => self.eval_teapot_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1081 | "TV" => self.eval_tv(comp, node, time, frame_i, enc, visiting, stats), |
| 1082 | "AutoDomain" => self.eval_auto_domain(comp, node, time, frame_i, enc, visiting, stats), |
| 1083 | "Fuse.FrameAverage" => self.eval_fuse_frame_average(comp, node, time, frame_i, enc, visiting, stats), |
| 1084 | "OCIOColorSpace" => self.eval_ocio_color_space(comp, node, time, frame_i, enc, visiting, stats), |
| 1085 | "OCIODisplay" => self.eval_ocio_display(comp, node, time, frame_i, enc, visiting, stats), |
| 1086 | "OCIOFileTransform" => self.eval_ocio_file_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 1087 | "LayerMuxer" => self.eval_layer_muxer(comp, node, time, enc, visiting, stats), |
| 1088 | "LayerRegex" => self.eval_layer_filter(comp, node, time, false, enc, visiting, stats), |
| 1089 | "LayerRemover" => self.eval_layer_filter(comp, node, time, true, enc, visiting, stats), |
| 1090 | "Swizzler" => self.eval_swizzler(comp, node, time, frame_i, enc, visiting, stats), |
| 1091 | "Dummy" | "Fuse.FLS_CopyMetadata" | "Fuse.SetMetaDataTC" => self.eval_passthrough(comp, node, time, enc, visiting, stats), |
| 1092 | "MultiText" => self.eval_multi_text(comp, node, time, frame_i, comp_dims, enc, stats), |
| 1093 | "Fields" => self.eval_fields(comp, node, time, frame_i, enc, visiting, stats), |
| 1094 | "KeyStretcher" => self.eval_key_stretcher(comp, node, time, frame_i, enc, visiting, stats), |
| 1095 | "ChromaticAberrationRemoval" => self.eval_chromatic_aberration_removal(comp, node, time, frame_i, enc, visiting, stats), |
| 1096 | "VolumeFog" => self.eval_volume_fog(comp, node, time, frame_i, enc, visiting, stats), |
| 1097 | "VolumeMask" => self.eval_volume_mask(comp, node, time, frame_i, enc, visiting, stats), |
| 1098 | "ZtoWorldPos" => self.eval_z_to_world_pos(comp, node, time, frame_i, enc, visiting, stats), |
| 1099 | "SSAO" => self.eval_ssao(comp, node, time, frame_i, enc, visiting, stats), |
| 1100 | "Shader" => self.eval_deep_shader(comp, node, time, frame_i, enc, visiting, stats), |
| 1101 | "Texture" => self.eval_texture_tool(comp, node, time, frame_i, enc, visiting, stats), |
| 1102 | "Dimension.RepairFrame" | "RepairFrame" => self.eval_repair_frame(comp, node, time, frame_i, enc, visiting, stats), |
| 1103 | "Dimension.SmoothMotion" | "SmoothMotion" => self.eval_smooth_motion(comp, node, time, frame_i, enc, visiting, stats), |
| 1104 | "Dimension.Tween" | "Tween" => self.eval_tween(comp, node, time, frame_i, enc, visiting, stats), |
| 1105 | "PropagateDepth" | "Dimension.PropagateDepth" => self.eval_propagate_depth(comp, node, time, frame_i, enc, visiting, stats), |
| 1106 | "VectorTransform" => self.eval_vector_transform(comp, node, time, frame_i, enc, visiting, stats), |
| 1107 | "VectorWarp" => self.eval_vector_warp(comp, node, time, frame_i, enc, visiting, stats), |
| 1108 | "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1109 | "sNGon" |
| 1110 | | "sRectangle" |
| 1111 | | "sEllipse" |
| 1112 | | "sStar" |
| 1113 | | "sPolygon" |
| 1114 | | "sBSpline" |
| 1115 | | "sChangeStyle" |
| 1116 | | "sText" |
| 1117 | | "sGrid" |
| 1118 | | "sMerge" |
| 1119 | | "sTransform" |
| 1120 | | "sDuplicate" |
| 1121 | | "sJitter" |
| 1122 | | "sExpand" |
| 1123 | | "sOffset" |
| 1124 | | "sBoolean" |
| 1125 | | "sOutline" => self.dummy.clone(), |
| 1126 | "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), |
| 1127 | "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats), |
| 1128 | "TriangleMask" => self.eval_triangle_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1129 | "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1130 | "BSplineMask" => self.eval_bspline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1131 | "Paint" => self.eval_paint(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1132 | "PaintMask" => self.eval_paint_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1133 | "PolylineStroke" | "Multistroke" => self.dummy.clone(), |
| 1134 | "BitmapMask" => self.eval_bitmap_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1135 | "WandMask" => self.eval_wand_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1136 | "TextPlus" => self.eval_text_plus(comp, node, time, frame_i, comp_dims, enc, stats), |
| 1137 | "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats), |
| 1138 | "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), |
| 1139 | "Fuse.XfChroma" => self.eval_xf_chroma(comp, node, time, frame_i, enc, visiting, stats), |
| 1140 | "Fuse.Cryptomatte" | "Cryptomatte" => self.eval_cryptomatte(comp, node, time, frame_i, enc, visiting, stats), |
| 1141 | "AutoMatte" => self.eval_auto_matte(comp, node, time, frame_i, false, enc, visiting, stats), |
| 1142 | "MagicMask" => self.eval_auto_matte(comp, node, time, frame_i, true, enc, visiting, stats), |
| 1143 | "pRender" => self.eval_p_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1144 | "pEmitter" |
| 1145 | | "pPointForce" |
| 1146 | | "pDirectionalForce" |
| 1147 | | "pTurbulence" |
| 1148 | | "pDrag" |
| 1149 | | "pFriction" |
| 1150 | | "pKill" |
| 1151 | | "pMerge" |
| 1152 | | "pBounce" |
| 1153 | | "pVortex" |
| 1154 | | "pFlock" |
| 1155 | | "pAvoid" |
| 1156 | | "pFollow" |
| 1157 | | "pTangentForce" |
| 1158 | | "pCustom" |
| 1159 | | "pCustomForce" |
| 1160 | | "pImageEmitter" |
| 1161 | | "pSpawn" |
| 1162 | | "pChangeStyle" |
| 1163 | | "pGradientForce" => self.dummy.clone(), |
| 1164 | "Custom" if node.connected_node("Image1").and_then(|s| comp.find_node(s)).is_none() => self.dummy.clone(), |
| 1165 | "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1166 | "SurfaceTracker" => self.eval_surface_tracker(comp, node, time, frame_i, enc, visiting, stats), |
| 1167 | "Dimension.PlanarTransform" | "PlanarTransform" => { |
| 1168 | self.eval_planar_transform(comp, node, time, frame_i, enc, visiting, stats) |
| 1169 | } |
| 1170 | "Dimension.PlanarTracker" | "PlanarTracker" => { |
| 1171 | self.eval_planar_tracker(comp, node, time, frame_i, enc, visiting, stats) |
| 1172 | } |
| 1173 | "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), |
| 1174 | other => { |
| 1175 | // Dynamically evaluate any registered Fusion Lua / GPU-DCTL `.fuse` tool before |
| 1176 | // falling back to passthrough + unsupported_nodes. |
| 1177 | if other.starts_with("Fuse.") |
| 1178 | && let Some(tex) = self.eval_fuse_runtime( |
| 1179 | comp, node, time, frame_i, comp_dims, enc, visiting, stats, |
| 1180 | ) |
| 1181 | { |
| 1182 | return tex; |
| 1183 | } |
| 1184 | // Graceful passthrough for preserved/unknown image nodes (e.g. SurfaceTracker, MagicMask, |
| 1185 | // Fuse.Cryptomatte, Dimension.OpticalFlow) via standard primary image ports so downstream |
| 1186 | // graphs stay live without mistaking auxiliary sprite/material ports (like pEmitter's |
| 1187 | // ParticleStyleBitmap.DropToolsHere) for a full-frame passthrough. |
| 1188 | if !stats.unsupported_nodes.iter().any(|s| s == other) { |
| 1189 | stats.unsupported_nodes.push(other.to_owned()); |
| 1190 | } |
| 1191 | let port = default_main_input_port(other); |
| 1192 | let primary_src = node |
| 1193 | .connected_node(port) |
| 1194 | .or_else(|| node.connected_node("Input")) |
| 1195 | .or_else(|| node.connected_node("Source")) |
| 1196 | .or_else(|| node.connected_node("MainInput1")) |
| 1197 | .or_else(|| node.connected_node("Image")) |
| 1198 | .or_else(|| node.connected_node("Image1")) |
| 1199 | .or_else(|| node.connected_node("Background")) |
| 1200 | .and_then(|s| comp.find_node(s)); |
| 1201 | if let Some(src_id) = primary_src { |
| 1202 | self.eval_node(comp, src_id, time, enc, visiting, stats) |
| 1203 | } else { |
| 1204 | self.dummy.clone() |
| 1205 | } |
| 1206 | } |
| 1207 | } |
| 1208 | } |
| 1209 | |
| 1210 | /// The node's `EffectMask` after its `MaskChannel` selection and `MaskLow`/`MaskHigh` remap, |
| 1211 | /// pooled and cached; identity settings skip the remap pass. |
| 1212 | #[allow(clippy::too_many_arguments)] |
| 1213 | fn eval_mask_input_sized( |
| 1214 | &mut self, |
| 1215 | comp: &Comp, |
| 1216 | node: &Node, |
| 1217 | time: f64, |
| 1218 | target_size: Option<[u32; 2]>, |
| 1219 | enc: &mut wgpu::CommandEncoder, |
| 1220 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1221 | stats: &mut EvalStats, |
| 1222 | ) -> (Option<CachedTexture>, bool) { |
| 1223 | let invert = comp.eval_number(node, "ApplyMaskInverted", time, 0.0, &self.expr) > 0.5; |
| 1224 | let prev_sz = self.mask_target_size; |
| 1225 | if target_size.is_some() { |
| 1226 | self.mask_target_size = target_size; |
| 1227 | } |
| 1228 | let tex = Self::resolve_effect_mask_id(comp, node).map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)); |
| 1229 | self.mask_target_size = prev_sz; |
| 1230 | let Some(m) = &tex else { |
| 1231 | return (None, invert); |
| 1232 | }; |
| 1233 | |
| 1234 | let channel = comp.eval_number(node, "MaskChannel", time, 3.0, &self.expr).round().clamp(0.0, 7.0) as usize; |
| 1235 | let low = comp.eval_number(node, "MaskLow", time, 0.0, &self.expr) as f32; |
| 1236 | let high = comp.eval_number(node, "MaskHigh", time, 1.0, &self.expr) as f32; |
| 1237 | if channel == 3 && low == 0.0 && high == 1.0 { |
| 1238 | return (tex, invert); |
| 1239 | } |
| 1240 | // Red, Green, Blue, Alpha, Hue, Luminance, Saturation, Coverage as `BitmapMask` channel ids. |
| 1241 | let bitmap_channel: f32 = [2.0, 3.0, 4.0, 0.0, 7.0, 1.0, 5.0, 8.0][channel]; |
| 1242 | let frame_i = time.round() as i64; |
| 1243 | let key = self.make_key(node, "MaskLevels", m.size, &[m.content_hash], bytemuck::cast_slice(&[bitmap_channel, low, high])); |
| 1244 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1245 | return (Some(hit), invert); |
| 1246 | } |
| 1247 | let out = self.alloc_tex(m.size, m.depth, key); |
| 1248 | let mut u = UniformParams::default(); |
| 1249 | u.p[0] = [bitmap_channel, low, high, 1.0]; |
| 1250 | self.dispatch_op(enc, ShaderOp::BitmapMask, &m.view, &self.dummy.view, &self.dummy.view, &out, &u); |
| 1251 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 1252 | (Some(out), invert) |
| 1253 | } |
| 1254 | |
| 1255 | /// Computes the remapped source time for `TimeStretcher` or `TimeSpeed`. |
| 1256 | pub(super) fn remap_time_node(&self, comp: &Comp, node: &Node, time: f64) -> Option<f64> { |
| 1257 | match node.kind.as_str() { |
| 1258 | "TimeStretcher" => Some(comp.eval_number(node, "SourceTime", time, 0.0, &self.expr)), |
| 1259 | "TimeSpeed" => { |
| 1260 | let speed = comp.eval_number(node, "Speed", time, 1.0, &self.expr); |
| 1261 | let delay = comp.eval_number(node, "Delay", time, 0.0, &self.expr); |
| 1262 | let g_start = comp.global_range[0] as f64; |
| 1263 | let g_end = comp.global_range[1] as f64; |
| 1264 | let raw = if speed < 0.0 { |
| 1265 | // Fusion plays negative-speed clips backward from (GlobalEnd + 1) anchored at GlobalStart. |
| 1266 | ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end) |
| 1267 | } else { |
| 1268 | g_start + (time - delay - g_start) * speed |
| 1269 | }; |
| 1270 | Some(raw) |
| 1271 | } |
| 1272 | _ => None, |
| 1273 | } |
| 1274 | } |
| 1275 | |
| 1276 | #[allow(clippy::too_many_arguments)] |
| 1277 | fn eval_time_remapped( |
| 1278 | &mut self, |
| 1279 | comp: &Comp, |
| 1280 | node: &Node, |
| 1281 | time: f64, |
| 1282 | frame_i: i64, |
| 1283 | remapped: f64, |
| 1284 | enc: &mut wgpu::CommandEncoder, |
| 1285 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1286 | stats: &mut EvalStats, |
| 1287 | ) -> CachedTexture { |
| 1288 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 1289 | return self.dummy.clone(); |
| 1290 | }; |
| 1291 | let interp = comp |
| 1292 | .eval_number(node, "InterpolateBetweenFrames", time, 1.0, &self.expr) |
| 1293 | .round() as i32; |
| 1294 | if interp <= 0 { |
| 1295 | let snapped = (remapped + 0.5).floor(); |
| 1296 | return self.eval_node(comp, src_id, snapped, enc, visiting, stats); |
| 1297 | } |
| 1298 | let f0 = remapped.floor(); |
| 1299 | let frac = (remapped - f0) as f32; |
| 1300 | if frac > 1e-3 && frac < 1.0 - 1e-3 { |
| 1301 | let src_node = comp.node(src_id); |
| 1302 | let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow"); |
| 1303 | let eval_src_id = if has_optflow { |
| 1304 | src_node |
| 1305 | .connected_node("Input") |
| 1306 | .and_then(|s| comp.find_node(s)) |
| 1307 | .unwrap_or(src_id) |
| 1308 | } else { |
| 1309 | src_id |
| 1310 | }; |
| 1311 | let tex_a = self.eval_node(comp, eval_src_id, f0, enc, visiting, stats); |
| 1312 | let tex_b = self.eval_node(comp, eval_src_id, f0 + 1.0, enc, visiting, stats); |
| 1313 | let use_flow = interp == 2 && (has_optflow || self.hiq); |
| 1314 | let dst_depth = self.node_depth(comp, node, time, Some(tex_a.depth.max(tex_b.depth))); |
| 1315 | let mut h = DefaultHasher::new(); |
| 1316 | self.cache.gpu_salt.hash(&mut h); |
| 1317 | self.cache.node_salt(node.id).hash(&mut h); |
| 1318 | "TimeRemapInterp".hash(&mut h); |
| 1319 | use_flow.hash(&mut h); |
| 1320 | tex_a.content_hash.hash(&mut h); |
| 1321 | tex_b.content_hash.hash(&mut h); |
| 1322 | ((frac * 1000.0).round() as i32).hash(&mut h); |
| 1323 | dst_depth.hash(&mut h); |
| 1324 | let key = h.finish(); |
| 1325 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1326 | stats.cache_hits += 1; |
| 1327 | return hit; |
| 1328 | } |
| 1329 | stats.cache_misses += 1; |
| 1330 | stats.nodes_evaluated += 1; |
| 1331 | let fmt = self.texture_format_for(self.effective_depth(dst_depth)); |
| 1332 | let optflow = self.optflow.get_or_init(|| crate::optflow::OpticalFlowPipelines::new(&self.device)); |
| 1333 | let mut out = if use_flow { |
| 1334 | optflow.interpolate_flow(&self.device, &self.queue, enc, &tex_a, &tex_b, frac, fmt) |
| 1335 | } else { |
| 1336 | optflow.blend_frames(&self.device, &self.queue, enc, &tex_a, &tex_b, frac, fmt) |
| 1337 | }; |
| 1338 | out.depth = self.effective_depth(dst_depth); |
| 1339 | out.content_hash = key; |
| 1340 | self.cache.insert(key, out.clone(), node.id, frame_i); |
| 1341 | return out; |
| 1342 | } |
| 1343 | self.eval_node(comp, src_id, remapped, enc, visiting, stats) |
| 1344 | } |
| 1345 | |
| 1346 | fn parse_surface_apply_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 { |
| 1347 | let mode_str = node |
| 1348 | .static_str("OverlayCompositeMode") |
| 1349 | .or_else(|| node.static_str("CompositeMode")) |
| 1350 | .or_else(|| node.static_str("ApplyMode")); |
| 1351 | if let Some(s) = mode_str { |
| 1352 | return match s { |
| 1353 | "Screen" => 1.0, |
| 1354 | "Multiply" => 2.0, |
| 1355 | "Overlay" => 3.0, |
| 1356 | "SoftLight" | "Soft Light" => 4.0, |
| 1357 | "HardLight" | "Hard Light" => 5.0, |
| 1358 | "ColorDodge" | "Color Dodge" => 6.0, |
| 1359 | "Darken" => 7.0, |
| 1360 | "Lighten" => 8.0, |
| 1361 | "Difference" => 9.0, |
| 1362 | "Exclusion" => 10.0, |
| 1363 | "Add" | "LinearDodge" | "Linear Dodge" => 11.0, |
| 1364 | _ => 0.0, |
| 1365 | }; |
| 1366 | } |
| 1367 | let n = comp |
| 1368 | .eval_number(node, "OverlayCompositeMode", time, 0.0, expr) |
| 1369 | .round() as i32; |
| 1370 | match n { |
| 1371 | 1 => 1.0, |
| 1372 | 2 => 2.0, |
| 1373 | 3 => 3.0, |
| 1374 | 4 => 4.0, |
| 1375 | 5 => 5.0, |
| 1376 | _ => 0.0, |
| 1377 | } |
| 1378 | } |
| 1379 | |
| 1380 | #[allow(clippy::too_many_arguments)] |
| 1381 | fn eval_surface_tracker( |
| 1382 | &mut self, |
| 1383 | comp: &Comp, |
| 1384 | node: &Node, |
| 1385 | time: f64, |
| 1386 | frame_i: i64, |
| 1387 | enc: &mut wgpu::CommandEncoder, |
| 1388 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1389 | stats: &mut EvalStats, |
| 1390 | ) -> CachedTexture { |
| 1391 | let Some(bg_id) = node |
| 1392 | .connected_node("Input") |
| 1393 | .or_else(|| node.connected_node("Background")) |
| 1394 | .and_then(|s| comp.find_node(s)) |
| 1395 | else { |
| 1396 | return self.dummy.clone(); |
| 1397 | }; |
| 1398 | let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); |
| 1399 | |
| 1400 | let stage = comp |
| 1401 | .eval_number(node, "ProcessStage", time, 2.0, &self.expr) |
| 1402 | .round() as i32; |
| 1403 | if stage < 2 { |
| 1404 | return bg; |
| 1405 | } |
| 1406 | |
| 1407 | let Some(overlay_id) = node |
| 1408 | .connected_node("Overlay") |
| 1409 | .or_else(|| node.connected_node("Foreground")) |
| 1410 | .and_then(|s| comp.find_node(s)) |
| 1411 | else { |
| 1412 | return bg; |
| 1413 | }; |
| 1414 | |
| 1415 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 1416 | let opacity = comp.eval_number(node, "OverlayOpacity", time, 1.0, &self.expr) as f32; |
| 1417 | let eff_blend = (blend * opacity).clamp(0.0, 1.0); |
| 1418 | if eff_blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { |
| 1419 | return bg; |
| 1420 | } |
| 1421 | |
| 1422 | let explicit_ref = node |
| 1423 | .inputs |
| 1424 | .contains_key("ReferenceFrame") |
| 1425 | .then(|| comp.eval_number(node, "ReferenceFrame", time, 0.0, &self.expr)); |
| 1426 | let Some((ref_mesh, cur_mesh, ref_frame)) = |
| 1427 | crate::tracker::eval_surface_mesh(comp, node, time, explicit_ref) |
| 1428 | else { |
| 1429 | return bg; |
| 1430 | }; |
| 1431 | |
| 1432 | let overlay_time = match node.static_str("OverlaySource") { |
| 1433 | Some("OverlayFrameRef" | "OverlayFrameReference") => ref_frame, |
| 1434 | Some("OverlayFrameCurrent" | "OverlayFrameFirst") => time, |
| 1435 | _ => time, |
| 1436 | }; |
| 1437 | let overlay = self.eval_node(comp, overlay_id, overlay_time, enc, visiting, stats); |
| 1438 | let bg = self.crop_to_canvas(enc, bg); |
| 1439 | let overlay = self.crop_to_canvas(enc, overlay); |
| 1440 | |
| 1441 | let placement = comp |
| 1442 | .eval_number(node, "OverlayPlacement", time, 1.0, &self.expr) |
| 1443 | .round() as i32; |
| 1444 | let corners = if placement == 0 { |
| 1445 | crate::tracker::extract_warpable_canvas_corners(node) |
| 1446 | .unwrap_or([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) |
| 1447 | } else { |
| 1448 | crate::tracker::extract_warpable_canvas_corners(node) |
| 1449 | .unwrap_or([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) |
| 1450 | }; |
| 1451 | let h_inv = crate::tracker::quad_to_unit_homography( |
| 1452 | corners[0], |
| 1453 | corners[1], |
| 1454 | corners[2], |
| 1455 | corners[3], |
| 1456 | ); |
| 1457 | |
| 1458 | let photo_strength = if node.inputs.contains_key("LightingWeight") { |
| 1459 | comp.eval_number(node, "LightingWeight", time, 0.0, &self.expr) as f32 |
| 1460 | } else if node.inputs.contains_key("MatchLighting") { |
| 1461 | comp.eval_number(node, "MatchLighting", time, 0.0, &self.expr) as f32 |
| 1462 | } else { |
| 1463 | 0.0 |
| 1464 | } |
| 1465 | .clamp(0.0, 1.0); |
| 1466 | |
| 1467 | let apply_mode = Self::parse_surface_apply_mode(comp, node, time, &self.expr); |
| 1468 | let (mask, mask_inv) = |
| 1469 | self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); |
| 1470 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 1471 | let mbm = mask.is_some() |
| 1472 | && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; |
| 1473 | let dst_depth = self.node_depth(comp, node, time, Some(bg.depth.max(overlay.depth))); |
| 1474 | |
| 1475 | let ref_hash = ref_mesh.content_hash(); |
| 1476 | let cur_hash = cur_mesh.content_hash(); |
| 1477 | let params_f32: [f32; 14] = [ |
| 1478 | h_inv[0] as f32, |
| 1479 | h_inv[1] as f32, |
| 1480 | h_inv[2] as f32, |
| 1481 | h_inv[3] as f32, |
| 1482 | h_inv[4] as f32, |
| 1483 | h_inv[5] as f32, |
| 1484 | h_inv[6] as f32, |
| 1485 | h_inv[7] as f32, |
| 1486 | h_inv[8] as f32, |
| 1487 | eff_blend, |
| 1488 | apply_mode, |
| 1489 | photo_strength, |
| 1490 | if mask_inv { 1.0 } else { 0.0 }, |
| 1491 | if mbm { 1.0 } else { 0.0 }, |
| 1492 | ]; |
| 1493 | let key = self.make_key( |
| 1494 | node, |
| 1495 | "SurfaceTracker", |
| 1496 | bg.size, |
| 1497 | &[bg.content_hash, overlay.content_hash, mask_hash, ref_hash, cur_hash], |
| 1498 | &params_f32, |
| 1499 | ); |
| 1500 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1501 | stats.cache_hits += 1; |
| 1502 | return hit; |
| 1503 | } |
| 1504 | stats.cache_misses += 1; |
| 1505 | stats.nodes_evaluated += 1; |
| 1506 | |
| 1507 | // WebGPU safety: render mesh exclusively into Rgba8Unorm or Rgba16Float (never Rgba32Float). |
| 1508 | let render_depth = match self.effective_depth(dst_depth) { |
| 1509 | BitDepth::Int8 => BitDepth::Int8, |
| 1510 | _ => BitDepth::Float16, |
| 1511 | }; |
| 1512 | let warped = self.alloc_tex(bg.size, render_depth, key ^ 0x57A1_7EAC); |
| 1513 | let tracker = self |
| 1514 | .tracker |
| 1515 | .get_or_init(|| crate::tracker::TrackerPipelines::new(&self.device)); |
| 1516 | tracker.render_surface_mesh( |
| 1517 | &self.device, |
| 1518 | enc, |
| 1519 | &overlay.view, |
| 1520 | &warped.view, |
| 1521 | warped.format, |
| 1522 | &ref_mesh, |
| 1523 | &cur_mesh, |
| 1524 | h_inv, |
| 1525 | photo_strength, |
| 1526 | ); |
| 1527 | |
| 1528 | let dst = self.alloc_tex(bg.size, dst_depth, key); |
| 1529 | let mut u = UniformParams::default(); |
| 1530 | u.p[0] = [0.5, 0.5, 1.0, 0.0]; |
| 1531 | u.p[1] = [eff_blend, 1.0, apply_mode, 0.0]; |
| 1532 | u.p[2] = [0.0, 0.0, 0.0, 0.0]; |
| 1533 | u.p[3] = [ |
| 1534 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 1535 | if mask_inv { 1.0 } else { 0.0 }, |
| 1536 | bg.size[0] as f32, |
| 1537 | bg.size[1] as f32, |
| 1538 | ]; |
| 1539 | u.p[6] = [0.0, 1.0, 0.0, 0.0]; |
| 1540 | u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; |
| 1541 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 1542 | self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &warped.view, mv, &dst, &u); |
| 1543 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1544 | dst |
| 1545 | } |
| 1546 | |
| 1547 | #[allow(clippy::too_many_arguments)] |
| 1548 | fn dispatch_planar_homography( |
| 1549 | &mut self, |
| 1550 | comp: &Comp, |
| 1551 | node: &Node, |
| 1552 | tag: &str, |
| 1553 | src: &CachedTexture, |
| 1554 | dst_size: [u32; 2], |
| 1555 | dst_depth: BitDepth, |
| 1556 | h_inv: [f64; 9], |
| 1557 | blend: f32, |
| 1558 | mask: Option<&CachedTexture>, |
| 1559 | mask_inv: bool, |
| 1560 | mbm: bool, |
| 1561 | time: f64, |
| 1562 | frame_i: i64, |
| 1563 | enc: &mut wgpu::CommandEncoder, |
| 1564 | stats: &mut EvalStats, |
| 1565 | ) -> CachedTexture { |
| 1566 | let mask_hash = mask.map_or(0, |m| m.content_hash); |
| 1567 | let mut u = UniformParams::default(); |
| 1568 | u.p[0] = [h_inv[0] as f32, h_inv[1] as f32, h_inv[2] as f32, h_inv[3] as f32]; |
| 1569 | u.p[1] = [h_inv[4] as f32, h_inv[5] as f32, h_inv[6] as f32, h_inv[7] as f32]; |
| 1570 | u.p[2] = [ |
| 1571 | h_inv[8] as f32, |
| 1572 | blend, |
| 1573 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 1574 | if mask_inv { 1.0 } else { 0.0 }, |
| 1575 | ]; |
| 1576 | u.p[3][1] = if mbm { 1.0 } else { 0.0 }; |
| 1577 | if src.size != dst_size { |
| 1578 | u.p[4] = [0.0, 0.0, dst_size[0] as f32, dst_size[1] as f32]; |
| 1579 | } |
| 1580 | u.p[5] = self.process_skip(comp, node, time); |
| 1581 | let key = self.make_key( |
| 1582 | node, |
| 1583 | tag, |
| 1584 | dst_size, |
| 1585 | &[src.content_hash, mask_hash], |
| 1586 | bytemuck::cast_slice(&u.p[..6]), |
| 1587 | ); |
| 1588 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1589 | stats.cache_hits += 1; |
| 1590 | return hit; |
| 1591 | } |
| 1592 | stats.cache_misses += 1; |
| 1593 | stats.nodes_evaluated += 1; |
| 1594 | let dst = self.alloc_tex(dst_size, dst_depth, key); |
| 1595 | let mv = mask.map_or(&self.dummy.view, |m| &m.view); |
| 1596 | self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u); |
| 1597 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1598 | dst |
| 1599 | } |
| 1600 | |
| 1601 | #[allow(clippy::too_many_arguments)] |
| 1602 | fn eval_planar_transform( |
| 1603 | &mut self, |
| 1604 | comp: &Comp, |
| 1605 | node: &Node, |
| 1606 | time: f64, |
| 1607 | frame_i: i64, |
| 1608 | enc: &mut wgpu::CommandEncoder, |
| 1609 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1610 | stats: &mut EvalStats, |
| 1611 | ) -> CachedTexture { |
| 1612 | let Some(src_id) = node |
| 1613 | .connected_node("Input") |
| 1614 | .or_else(|| node.connected_node("Background")) |
| 1615 | .and_then(|s| comp.find_node(s)) |
| 1616 | else { |
| 1617 | return self.dummy.clone(); |
| 1618 | }; |
| 1619 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 1620 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 1621 | if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { |
| 1622 | return src; |
| 1623 | } |
| 1624 | let Some(track) = crate::tracker::eval_planar_track(comp, node, "Track", time) else { |
| 1625 | return src; |
| 1626 | }; |
| 1627 | let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) >= 0.5; |
| 1628 | let h_inv = if invert { |
| 1629 | crate::tracker::mat3_invert(&track.to_ref_3x3).unwrap_or(track.to_ref_3x3) |
| 1630 | } else { |
| 1631 | track.to_ref_3x3 |
| 1632 | }; |
| 1633 | let src = self.crop_to_canvas(enc, src); |
| 1634 | let (mask, mask_inv) = |
| 1635 | self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 1636 | let mbm = mask.is_some() |
| 1637 | && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; |
| 1638 | let dst_depth = self.node_depth(comp, node, time, Some(src.depth)); |
| 1639 | self.dispatch_planar_homography( |
| 1640 | comp, |
| 1641 | node, |
| 1642 | "PlanarTransform", |
| 1643 | &src, |
| 1644 | src.size, |
| 1645 | dst_depth, |
| 1646 | h_inv, |
| 1647 | blend, |
| 1648 | mask.as_ref(), |
| 1649 | mask_inv, |
| 1650 | mbm, |
| 1651 | time, |
| 1652 | frame_i, |
| 1653 | enc, |
| 1654 | stats, |
| 1655 | ) |
| 1656 | } |
| 1657 | |
| 1658 | #[allow(clippy::too_many_arguments)] |
| 1659 | fn eval_planar_tracker( |
| 1660 | &mut self, |
| 1661 | comp: &Comp, |
| 1662 | node: &Node, |
| 1663 | time: f64, |
| 1664 | frame_i: i64, |
| 1665 | enc: &mut wgpu::CommandEncoder, |
| 1666 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1667 | stats: &mut EvalStats, |
| 1668 | ) -> CachedTexture { |
| 1669 | let Some(bg_id) = node |
| 1670 | .connected_node("Background") |
| 1671 | .or_else(|| node.connected_node("Input")) |
| 1672 | .and_then(|s| comp.find_node(s)) |
| 1673 | else { |
| 1674 | return self.dummy.clone(); |
| 1675 | }; |
| 1676 | let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats); |
| 1677 | |
| 1678 | // OperationMode: "Track"/0 = passthrough, "CornerPin"/1, "Steady"/2, "Stabilize"/3. |
| 1679 | let op_mode = match node.static_str("OperationMode") { |
| 1680 | Some("CornerPin") => 1, |
| 1681 | Some("Steady") => 2, |
| 1682 | Some("Stabilize") => 3, |
| 1683 | Some(_) => 0, |
| 1684 | None => comp |
| 1685 | .eval_number(node, "OperationMode", time, 0.0, &self.expr) |
| 1686 | .round() as i32, |
| 1687 | }; |
| 1688 | if op_mode == 0 { |
| 1689 | return bg; |
| 1690 | } |
| 1691 | |
| 1692 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 1693 | if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) { |
| 1694 | return bg; |
| 1695 | } |
| 1696 | |
| 1697 | if op_mode == 2 || op_mode == 3 { |
| 1698 | // Steady (2) warps Background by inv(ToRef) to lock the plane to RefTime. |
| 1699 | // Stabilize (3) uses StableTrack if valid, falling back to inv(Track.ToRef). |
| 1700 | let mat = if op_mode == 3 { |
| 1701 | crate::tracker::eval_planar_track(comp, node, "StableTrack", time) |
| 1702 | .or_else(|| crate::tracker::eval_planar_track(comp, node, "Track", time)) |
| 1703 | } else { |
| 1704 | crate::tracker::eval_planar_track(comp, node, "Track", time) |
| 1705 | }; |
| 1706 | let Some(track) = mat else { |
| 1707 | return bg; |
| 1708 | }; |
| 1709 | let Some(h_inv) = crate::tracker::mat3_invert(&track.to_ref_3x3) else { |
| 1710 | return bg; |
| 1711 | }; |
| 1712 | let bg = self.crop_to_canvas(enc, bg); |
| 1713 | let (mask, mask_inv) = |
| 1714 | self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); |
| 1715 | let mbm = mask.is_some() |
| 1716 | && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; |
| 1717 | let dst_depth = self.node_depth(comp, node, time, Some(bg.depth)); |
| 1718 | let tag = if op_mode == 3 { "PlanarStabilize" } else { "PlanarSteady" }; |
| 1719 | return self.dispatch_planar_homography( |
| 1720 | comp, |
| 1721 | node, |
| 1722 | tag, |
| 1723 | &bg, |
| 1724 | bg.size, |
| 1725 | dst_depth, |
| 1726 | h_inv, |
| 1727 | blend, |
| 1728 | mask.as_ref(), |
| 1729 | mask_inv, |
| 1730 | mbm, |
| 1731 | time, |
| 1732 | frame_i, |
| 1733 | enc, |
| 1734 | stats, |
| 1735 | ); |
| 1736 | } |
| 1737 | |
| 1738 | // CornerPin (1): warp CornerPin1 / Foreground via CornerPin quad + ToRef over Background. |
| 1739 | let Some(fg_id) = node |
| 1740 | .connected_node("CornerPin1") |
| 1741 | .or_else(|| node.connected_node("Foreground")) |
| 1742 | .or_else(|| node.connected_node("CornerPin")) |
| 1743 | .and_then(|s| comp.find_node(s)) |
| 1744 | else { |
| 1745 | return bg; |
| 1746 | }; |
| 1747 | let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats); |
| 1748 | let bg = self.crop_to_canvas(enc, bg); |
| 1749 | let fg = self.crop_to_canvas(enc, fg); |
| 1750 | |
| 1751 | let read_corner = |primary: &str, alt: &str, default: [f64; 2]| -> [f64; 2] { |
| 1752 | if node.inputs.contains_key(primary) { |
| 1753 | comp.eval_point(node, primary, time, default, &self.expr) |
| 1754 | } else { |
| 1755 | comp.eval_point(node, alt, time, default, &self.expr) |
| 1756 | } |
| 1757 | }; |
| 1758 | let bl = read_corner("CornerPinBottomLeft", "BottomLeft", [0.0, 0.0]); |
| 1759 | let br = read_corner("CornerPinBottomRight", "BottomRight", [1.0, 0.0]); |
| 1760 | let tr = read_corner("CornerPinTopRight", "TopRight", [1.0, 1.0]); |
| 1761 | let tl = read_corner("CornerPinTopLeft", "TopLeft", [0.0, 1.0]); |
| 1762 | let h_pin_inv = crate::tracker::quad_to_unit_homography(tl, tr, br, bl); |
| 1763 | let h_to_ref = crate::tracker::eval_planar_track(comp, node, "Track", time) |
| 1764 | .map_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |m| m.to_ref_3x3); |
| 1765 | let h_combined = crate::tracker::mat3_mul(&h_pin_inv, &h_to_ref); |
| 1766 | |
| 1767 | let dst_depth = self.node_depth(comp, node, time, Some(bg.depth.max(fg.depth))); |
| 1768 | let warped_fg = self.dispatch_planar_homography( |
| 1769 | comp, |
| 1770 | node, |
| 1771 | "PlanarCornerPinWarp", |
| 1772 | &fg, |
| 1773 | bg.size, |
| 1774 | dst_depth, |
| 1775 | h_combined, |
| 1776 | 1.0, |
| 1777 | None, |
| 1778 | false, |
| 1779 | false, |
| 1780 | time, |
| 1781 | frame_i, |
| 1782 | enc, |
| 1783 | stats, |
| 1784 | ); |
| 1785 | |
| 1786 | let (mask, mask_inv) = |
| 1787 | self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats); |
| 1788 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 1789 | let mbm = mask.is_some() |
| 1790 | && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5; |
| 1791 | let key = self.make_key( |
| 1792 | node, |
| 1793 | "PlanarCornerPinComp", |
| 1794 | bg.size, |
| 1795 | &[bg.content_hash, warped_fg.content_hash, mask_hash], |
| 1796 | &[blend, if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }], |
| 1797 | ); |
| 1798 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1799 | stats.cache_hits += 1; |
| 1800 | return hit; |
| 1801 | } |
| 1802 | stats.cache_misses += 1; |
| 1803 | let dst = self.alloc_tex(bg.size, dst_depth, key); |
| 1804 | let mut u = UniformParams::default(); |
| 1805 | u.p[0] = [0.5, 0.5, 1.0, 0.0]; |
| 1806 | u.p[1] = [blend, 1.0, 0.0, 0.0]; |
| 1807 | u.p[2] = [0.0, 0.0, 0.0, 0.0]; |
| 1808 | u.p[3] = [ |
| 1809 | if mask.is_some() { 1.0 } else { 0.0 }, |
| 1810 | if mask_inv { 1.0 } else { 0.0 }, |
| 1811 | bg.size[0] as f32, |
| 1812 | bg.size[1] as f32, |
| 1813 | ]; |
| 1814 | u.p[6] = [0.0, 1.0, 0.0, 0.0]; |
| 1815 | u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; |
| 1816 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 1817 | self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &warped_fg.view, mv, &dst, &u); |
| 1818 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1819 | dst |
| 1820 | } |
| 1821 | |
| 1822 | #[allow(clippy::too_many_arguments)] |
| 1823 | fn eval_auto_matte( |
| 1824 | &mut self, |
| 1825 | comp: &Comp, |
| 1826 | node: &Node, |
| 1827 | time: f64, |
| 1828 | frame_i: i64, |
| 1829 | is_magic_mask: bool, |
| 1830 | enc: &mut wgpu::CommandEncoder, |
| 1831 | visiting: &mut HashSet<(NodeId, i64)>, |
| 1832 | stats: &mut EvalStats, |
| 1833 | ) -> CachedTexture { |
| 1834 | let primary_src = node |
| 1835 | .connected_node("Input") |
| 1836 | .or_else(|| node.connected_node("Image")) |
| 1837 | .or_else(|| node.connected_node("Source")) |
| 1838 | .or_else(|| node.connected_node("Background")) |
| 1839 | .and_then(|s| comp.find_node(s)); |
| 1840 | let Some(src_id) = primary_src else { |
| 1841 | return self.dummy.clone(); |
| 1842 | }; |
| 1843 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 1844 | let params = if is_magic_mask { |
| 1845 | crate::auto_matte::extract_magic_mask_params(comp, node, time, &self.expr) |
| 1846 | } else { |
| 1847 | crate::auto_matte::extract_auto_matte_params(comp, node, time, &self.expr) |
| 1848 | }; |
| 1849 | let mbm = self.multiplies_by_mask(comp, node, time); |
| 1850 | if params.blend <= 1e-6 && !mbm { |
| 1851 | return src; |
| 1852 | } |
| 1853 | let cached_matte = self.auto_matte_cache.get_or_load_frame( |
| 1854 | &node.name, |
| 1855 | frame_i, |
| 1856 | params.cache_dir.as_deref(), |
| 1857 | ); |
| 1858 | // Empty MagicMask / AutoMatte (no strokes/points & no cached neural matte) passes through |
| 1859 | // foreground cleanly with 0.00% MAE regression. |
| 1860 | if cached_matte.is_none() && params.effective_gpu_seeds().is_empty() { |
| 1861 | return src; |
| 1862 | } |
| 1863 | |
| 1864 | let src = self.crop_to_canvas(enc, src); |
| 1865 | let (mask, mask_inv) = |
| 1866 | self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 1867 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 1868 | let matte_hash = cached_matte.as_ref().map_or(0, |m| m.content_hash); |
| 1869 | let skip = self.process_skip(comp, node, time); |
| 1870 | |
| 1871 | let mut ph = DefaultHasher::new(); |
| 1872 | params.hash_into(&mut ph); |
| 1873 | self.proxy_scale.hash(&mut ph); |
| 1874 | mask_inv.hash(&mut ph); |
| 1875 | mbm.hash(&mut ph); |
| 1876 | for s in skip { |
| 1877 | s.to_bits().hash(&mut ph); |
| 1878 | } |
| 1879 | let param_hash = ph.finish(); |
| 1880 | let key = self.make_key( |
| 1881 | node, |
| 1882 | if is_magic_mask { "MagicMask" } else { "AutoMatte" }, |
| 1883 | src.size, |
| 1884 | &[src.content_hash, mask_hash, matte_hash, param_hash], |
| 1885 | &[], |
| 1886 | ); |
| 1887 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 1888 | stats.cache_hits += 1; |
| 1889 | return hit; |
| 1890 | } |
| 1891 | stats.cache_misses += 1; |
| 1892 | stats.nodes_evaluated += 1; |
| 1893 | |
| 1894 | let dst = self.alloc_tex(src.size, src.depth, key); |
| 1895 | let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 1896 | let pipelines = self |
| 1897 | .auto_matte_pipelines |
| 1898 | .get_or_init(|| RefCell::new(crate::auto_matte::AutoMattePipelines::new(&self.device))); |
| 1899 | pipelines.borrow_mut().execute( |
| 1900 | &self.device, |
| 1901 | &self.queue, |
| 1902 | enc, |
| 1903 | &self.cache, |
| 1904 | &self.dummy.view, |
| 1905 | &src, |
| 1906 | mv, |
| 1907 | mask.is_some(), |
| 1908 | mask_inv, |
| 1909 | mbm, |
| 1910 | skip, |
| 1911 | &dst, |
| 1912 | &params, |
| 1913 | cached_matte.as_deref(), |
| 1914 | self.proxy_scale, |
| 1915 | ); |
| 1916 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 1917 | dst |
| 1918 | } |
| 1919 | |
| 1920 | fn make_key(&self, node: &Node, tag: &str, size: [u32; 2], upstream: &[u64], params: &[f32]) -> u64 { |
| 1921 | let mut h = DefaultHasher::new(); |
| 1922 | self.cache.gpu_salt.hash(&mut h); |
| 1923 | self.hiq.hash(&mut h); |
| 1924 | self.cache.node_salt(node.id).hash(&mut h); |
| 1925 | tag.hash(&mut h); |
| 1926 | size.hash(&mut h); |
| 1927 | upstream.hash(&mut h); |
| 1928 | for &v in params { |
| 1929 | v.to_bits().hash(&mut h); |
| 1930 | } |
| 1931 | h.finish() |
| 1932 | } |
| 1933 | } |
| 1934 | |
| 1935 | #[cfg(test)] |
| 1936 | mod lazy_shader_verify { |
| 1937 | use super::*; |
| 1938 | |
| 1939 | #[test] |
| 1940 | fn verify_all_43_shader_ops_compile() { |
| 1941 | let eng = Engine::new_headless().expect("gpu"); |
| 1942 | let all_ops = [ |
| 1943 | ShaderOp::Bg, ShaderOp::Merge, ShaderOp::Transform, ShaderOp::Bc, ShaderOp::Cc, |
| 1944 | ShaderOp::ColorGain, ShaderOp::LumaKey, ShaderOp::Blur, ShaderOp::DirBlur, |
| 1945 | ShaderOp::FastNoise, ShaderOp::Displace, ShaderOp::MaskShape, ShaderOp::MaskCombine, |
| 1946 | ShaderOp::MaskApply, ShaderOp::BitmapMask, ShaderOp::Colorize, ShaderOp::ColorCurves, |
| 1947 | ShaderOp::XfChroma, ShaderOp::GamutConvert, ShaderOp::VariBlur, ShaderOp::OutlineTint, |
| 1948 | ShaderOp::OutlineComposite, ShaderOp::CustomWave, ShaderOp::Crop, |
| 1949 | ShaderOp::GlowAdd, ShaderOp::XGlowPrep, ShaderOp::XGlowAccum, ShaderOp::DisplayBlit, |
| 1950 | ShaderOp::Invert, ShaderOp::ChannelBoolean, ShaderOp::Filter, ShaderOp::HueCurves, |
| 1951 | ShaderOp::UltraKeyer, ShaderOp::Dissolve, ShaderOp::Homography, ShaderOp::ShadowComp, |
| 1952 | ShaderOp::Plasma, ShaderOp::FilmGrain, ShaderOp::SetDomain, ShaderOp::ChangeDepth, |
| 1953 | ShaderOp::Vortex, ShaderOp::KScope, ShaderOp::Drip, ShaderOp::Dent, |
| 1954 | ShaderOp::PerspectivePos, ShaderOp::DaySky, ShaderOp::GridWarp, ShaderOp::CheckerPiece, |
| 1955 | ShaderOp::AlphaWeightedNoise, ShaderOp::Crystallize, ShaderOp::HexagonTiles, ShaderOp::RemoveNoise, ShaderOp::DeltaKeyer, |
| 1956 | ]; |
| 1957 | // Verify starts completely empty (lazy!) |
| 1958 | assert_eq!(eng.pipelines.borrow().modules.len(), 0); |
| 1959 | assert_eq!(eng.pipelines.borrow().pipelines.len(), 0); |
| 1960 | for op in all_ops { |
| 1961 | eng.pipelines.borrow_mut().ensure_pipeline(&eng.device, op); |
| 1962 | eng.pipelines_for(BitDepth::Float16).borrow_mut().ensure_pipeline(&eng.device, op); |
| 1963 | } |
| 1964 | assert_eq!(eng.pipelines.borrow().modules.len(), 7); |
| 1965 | assert_eq!(eng.pipelines.borrow().pipelines.len(), 53); |
| 1966 | assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().modules.len(), 7); |
| 1967 | assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 53); |
| 1968 | } |
| 1969 | |
| 1970 | #[test] |
| 1971 | fn switch_supports_native_zero_indexed_source_and_legacy_one_indexed_which() { |
| 1972 | let src = r#" |
| 1973 | Composition { |
| 1974 | CurrentTime = 0, |
| 1975 | RenderRange = { 0, 5 }, |
| 1976 | GlobalRange = { 0, 5 }, |
| 1977 | Tools = ordered() { |
| 1978 | Red = Background { |
| 1979 | Inputs = { |
| 1980 | Width = Input { Value = 16, }, |
| 1981 | Height = Input { Value = 16, }, |
| 1982 | TopLeftRed = Input { Value = 1.0, }, |
| 1983 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1984 | }, |
| 1985 | }, |
| 1986 | Green = Background { |
| 1987 | Inputs = { |
| 1988 | Width = Input { Value = 16, }, |
| 1989 | Height = Input { Value = 16, }, |
| 1990 | TopLeftGreen = Input { Value = 1.0, }, |
| 1991 | TopLeftAlpha = Input { Value = 1.0, }, |
| 1992 | }, |
| 1993 | }, |
| 1994 | Blue = Background { |
| 1995 | Inputs = { |
| 1996 | Width = Input { Value = 16, }, |
| 1997 | Height = Input { Value = 16, }, |
| 1998 | TopLeftBlue = Input { Value = 1.0, }, |
| 1999 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2000 | }, |
| 2001 | }, |
| 2002 | SwNative0 = Switch { |
| 2003 | Inputs = { |
| 2004 | Source = Input { Value = 0, }, |
| 2005 | Input0 = Input { SourceOp = "Red", Source = "Output", }, |
| 2006 | Input1 = Input { SourceOp = "Green", Source = "Output", }, |
| 2007 | }, |
| 2008 | }, |
| 2009 | SwNative1 = Switch { |
| 2010 | Inputs = { |
| 2011 | Source = Input { Value = 1, }, |
| 2012 | Input0 = Input { SourceOp = "Red", Source = "Output", }, |
| 2013 | Input1 = Input { SourceOp = "Green", Source = "Output", }, |
| 2014 | }, |
| 2015 | }, |
| 2016 | SwNativeOmittedSource = Switch { |
| 2017 | Inputs = { |
| 2018 | Input0 = Input { SourceOp = "Red", Source = "Output", }, |
| 2019 | Input1 = Input { SourceOp = "Green", Source = "Output", }, |
| 2020 | }, |
| 2021 | }, |
| 2022 | SwFuse2 = Fuse.Switch { |
| 2023 | Inputs = { |
| 2024 | Which = Input { Value = 2, }, |
| 2025 | Input1 = Input { SourceOp = "Red", Source = "Output", }, |
| 2026 | Input2 = Input { SourceOp = "Blue", Source = "Output", }, |
| 2027 | }, |
| 2028 | }, |
| 2029 | SwLegacy2 = Switch { |
| 2030 | Inputs = { |
| 2031 | Which = Input { Value = 2, }, |
| 2032 | Input1 = Input { SourceOp = "Red", Source = "Output", }, |
| 2033 | Input2 = Input { SourceOp = "Blue", Source = "Output", }, |
| 2034 | }, |
| 2035 | }, |
| 2036 | }, |
| 2037 | } |
| 2038 | "#; |
| 2039 | let comp = Comp::from_fusion_str(src).expect("parse switch comp"); |
| 2040 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2041 | |
| 2042 | let (t0, _) = eng.evaluate(&comp, comp.find_node("SwNative0").unwrap(), 0.0); |
| 2043 | let p0 = eng.readback_rgba(&t0).unwrap(); |
| 2044 | assert!(p0[0] > 240 && p0[1] < 15 && p0[2] < 15, "SwNative0 expected red, got {:?}", &p0[..4]); |
| 2045 | |
| 2046 | let (t1, _) = eng.evaluate(&comp, comp.find_node("SwNative1").unwrap(), 0.0); |
| 2047 | let p1 = eng.readback_rgba(&t1).unwrap(); |
| 2048 | assert!(p1[1] > 240 && p1[0] < 15 && p1[2] < 15, "SwNative1 expected green, got {:?}", &p1[..4]); |
| 2049 | |
| 2050 | let (to, _) = eng.evaluate(&comp, comp.find_node("SwNativeOmittedSource").unwrap(), 0.0); |
| 2051 | let po = eng.readback_rgba(&to).unwrap(); |
| 2052 | assert!(po[0] > 240 && po[1] < 15 && po[2] < 15, "SwNativeOmittedSource expected red, got {:?}", &po[..4]); |
| 2053 | |
| 2054 | let (tf, _) = eng.evaluate(&comp, comp.find_node("SwFuse2").unwrap(), 0.0); |
| 2055 | let pf = eng.readback_rgba(&tf).unwrap(); |
| 2056 | assert!(pf[2] > 240 && pf[0] < 15 && pf[1] < 15, "SwFuse2 expected blue, got {:?}", &pf[..4]); |
| 2057 | |
| 2058 | let (tl, _) = eng.evaluate(&comp, comp.find_node("SwLegacy2").unwrap(), 0.0); |
| 2059 | let pl = eng.readback_rgba(&tl).unwrap(); |
| 2060 | assert!(pl[2] > 240 && pl[0] < 15 && pl[1] < 15, "SwLegacy2 expected blue, got {:?}", &pl[..4]); |
| 2061 | } |
| 2062 | |
| 2063 | #[test] |
| 2064 | fn custom_without_image1_renders_nothing() { |
| 2065 | let src = r#" |
| 2066 | Composition { |
| 2067 | CurrentTime = 0, |
| 2068 | RenderRange = { 0, 0 }, |
| 2069 | GlobalRange = { 0, 0 }, |
| 2070 | Tools = ordered() { |
| 2071 | Unwired = Custom { |
| 2072 | Inputs = { |
| 2073 | RedExpression = Input { Value = "0.7", }, |
| 2074 | AlphaExpression = Input { Value = "1", }, |
| 2075 | }, |
| 2076 | }, |
| 2077 | Dangling = Custom { |
| 2078 | Inputs = { |
| 2079 | Image1 = Input { SourceOp = "NoSuchTool", Source = "Output", }, |
| 2080 | RedExpression = Input { Value = "0.7", }, |
| 2081 | AlphaExpression = Input { Value = "1", }, |
| 2082 | }, |
| 2083 | }, |
| 2084 | }, |
| 2085 | } |
| 2086 | "#; |
| 2087 | let comp = Comp::from_fusion_str(src).expect("parse custom comp"); |
| 2088 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2089 | for name in ["Unwired", "Dangling"] { |
| 2090 | let (t, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0); |
| 2091 | let px = eng.readback_rgba(&t).unwrap(); |
| 2092 | assert_eq!(&px[..4], &[0, 0, 0, 0], "{name} must be transparent without Image1"); |
| 2093 | } |
| 2094 | } |
| 2095 | |
| 2096 | #[test] |
| 2097 | fn frame_memo_distinguishes_subframe_times_within_same_rounded_frame() { |
| 2098 | // BG1 animates TopLeftRed from 0.0 at t=9.0 to 1.0 at t=10.0. |
| 2099 | // At t=10.0: BG1 is evaluated directly (red=1.0). |
| 2100 | // At t=9.6 (via TimeSpeed Speed=0.96, Delay=0.0): time.round() is ALSO 10, |
| 2101 | // so frame_memo keyed by rounded frame would wrongly return t=10.0's red=1.0! |
| 2102 | let src = r#" |
| 2103 | Composition { |
| 2104 | CurrentTime = 10, |
| 2105 | RenderRange = { 0, 20 }, |
| 2106 | GlobalRange = { 0, 20 }, |
| 2107 | Tools = ordered() { |
| 2108 | AnimRed = BezierSpline { |
| 2109 | KeyFrames = { |
| 2110 | [9] = { 0.0, Flags = { Linear = true } }, |
| 2111 | [10] = { 1.0, Flags = { Linear = true } }, |
| 2112 | }, |
| 2113 | }, |
| 2114 | BG1 = Background { |
| 2115 | Inputs = { |
| 2116 | Width = Input { Value = 32, }, |
| 2117 | Height = Input { Value = 32, }, |
| 2118 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, |
| 2119 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2120 | }, |
| 2121 | }, |
| 2122 | TS = TimeSpeed { |
| 2123 | Inputs = { |
| 2124 | Speed = Input { Value = 0.96, }, |
| 2125 | Input = Input { SourceOp = "BG1", Source = "Output", }, |
| 2126 | }, |
| 2127 | }, |
| 2128 | Out = Merge { |
| 2129 | Inputs = { |
| 2130 | Background = Input { SourceOp = "BG1", Source = "Output", }, |
| 2131 | Foreground = Input { SourceOp = "TS", Source = "Output", }, |
| 2132 | Size = Input { Value = 0.5, }, |
| 2133 | }, |
| 2134 | }, |
| 2135 | }, |
| 2136 | } |
| 2137 | "#; |
| 2138 | let comp = Comp::from_fusion_str(src).expect("parse subframe comp"); |
| 2139 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2140 | let out_id = comp.find_node("Out").unwrap(); |
| 2141 | let (tex, _) = eng.evaluate(&comp, out_id, 10.0); |
| 2142 | assert_eq!(tex.size, [32, 32]); |
| 2143 | let rgba = eng.readback_rgba(&tex).unwrap(); |
| 2144 | // Corner pixel (0, 0) is BG1 at t=10.0 -> red ~255. |
| 2145 | assert!(rgba[0] > 240, "corner pixel (BG1 @10.0) expected ~255, got {}", rgba[0]); |
| 2146 | // Center pixel (16, 16) is TS (BG1 @9.6) -> red ~0.6 * 255 = 153! |
| 2147 | let mid_idx = (16 * 32 + 16) * 4; |
| 2148 | assert!( |
| 2149 | (rgba[mid_idx] as i32 - 153).abs() <= 6, |
| 2150 | "center pixel (BG1 @9.6) expected ~153, got {}", |
| 2151 | rgba[mid_idx] |
| 2152 | ); |
| 2153 | // Also verify frame_memo was cleared after evaluate. |
| 2154 | assert!(eng.frame_memo.is_empty()); |
| 2155 | } |
| 2156 | |
| 2157 | #[test] |
| 2158 | fn frame_memo_includes_mask_target_size_and_new_with_device_sets_budgets() { |
| 2159 | let eng0 = Engine::new_headless().expect("gpu"); |
| 2160 | let mut eng = Engine::new_with_device( |
| 2161 | std::sync::Arc::new(eng0.device().clone()), |
| 2162 | std::sync::Arc::new(eng0.queue().clone()), |
| 2163 | 64 * 1024 * 1024, |
| 2164 | 32 * 1024 * 1024, |
| 2165 | ); |
| 2166 | assert_eq!(eng.vram_budget_mb(), 64); |
| 2167 | |
| 2168 | let src = r#" |
| 2169 | Composition { |
| 2170 | CurrentTime = 0, |
| 2171 | RenderRange = { 0, 1 }, |
| 2172 | GlobalRange = { 0, 1 }, |
| 2173 | Tools = ordered() { |
| 2174 | MaskImg = Background { |
| 2175 | Inputs = { |
| 2176 | Width = Input { Value = 64, }, |
| 2177 | Height = Input { Value = 64, }, |
| 2178 | TopLeftRed = Input { Value = 1.0, }, |
| 2179 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2180 | }, |
| 2181 | }, |
| 2182 | BM = BitmapMask { |
| 2183 | Inputs = { |
| 2184 | Image = Input { SourceOp = "MaskImg", Source = "Output", }, |
| 2185 | }, |
| 2186 | }, |
| 2187 | SmallBG = Background { |
| 2188 | Inputs = { |
| 2189 | Width = Input { Value = 32, }, |
| 2190 | Height = Input { Value = 32, }, |
| 2191 | TopLeftGreen = Input { Value = 1.0, }, |
| 2192 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2193 | EffectMask = Input { SourceOp = "BM", Source = "Mask", }, |
| 2194 | }, |
| 2195 | }, |
| 2196 | LargeBG = Background { |
| 2197 | Inputs = { |
| 2198 | Width = Input { Value = 64, }, |
| 2199 | Height = Input { Value = 64, }, |
| 2200 | TopLeftBlue = Input { Value = 1.0, }, |
| 2201 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2202 | EffectMask = Input { SourceOp = "BM", Source = "Mask", }, |
| 2203 | }, |
| 2204 | }, |
| 2205 | Out = Merge { |
| 2206 | Inputs = { |
| 2207 | Background = Input { SourceOp = "LargeBG", Source = "Output", }, |
| 2208 | Foreground = Input { SourceOp = "SmallBG", Source = "Output", }, |
| 2209 | }, |
| 2210 | }, |
| 2211 | }, |
| 2212 | } |
| 2213 | "#; |
| 2214 | let comp = Comp::from_fusion_str(src).expect("parse mask target size comp"); |
| 2215 | let out_id = comp.find_node("Out").unwrap(); |
| 2216 | let (tex, _) = eng.evaluate(&comp, out_id, 0.0); |
| 2217 | assert_eq!(tex.size, [64, 64]); |
| 2218 | assert!(eng.frame_memo.is_empty()); |
| 2219 | } |
| 2220 | |
| 2221 | #[test] |
| 2222 | fn display_blit_preserves_hdr_highlights_and_negatives_across_scale_and_crop() { |
| 2223 | let src = r#" |
| 2224 | Composition { |
| 2225 | CurrentTime = 0, |
| 2226 | RenderRange = { 0, 1 }, |
| 2227 | GlobalRange = { 0, 1 }, |
| 2228 | Prefs = { Comp = { FrameFormat = { Width = 8, Height = 8, DepthFull = 4 } } }, |
| 2229 | Tools = ordered() { |
| 2230 | BG1 = Background { |
| 2231 | Inputs = { |
| 2232 | Width = Input { Value = 8, }, |
| 2233 | Height = Input { Value = 8, }, |
| 2234 | Depth = Input { Value = 4, }, |
| 2235 | TopLeftRed = Input { Value = 3.5, }, |
| 2236 | TopLeftGreen = Input { Value = -0.25, }, |
| 2237 | TopLeftBlue = Input { Value = 0.5, }, |
| 2238 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2239 | }, |
| 2240 | }, |
| 2241 | SC = Scale { |
| 2242 | Inputs = { |
| 2243 | Input = Input { SourceOp = "BG1", Source = "Output", }, |
| 2244 | XSize = Input { Value = 0.5, }, |
| 2245 | YSize = Input { Value = 0.5, }, |
| 2246 | }, |
| 2247 | }, |
| 2248 | }, |
| 2249 | } |
| 2250 | "#; |
| 2251 | let comp = Comp::from_fusion_str(src).expect("parse hdr scale comp"); |
| 2252 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2253 | let sc_id = comp.find_node("SC").unwrap(); |
| 2254 | let (tex, _) = eng.evaluate(&comp, sc_id, 0.0); |
| 2255 | assert!(tex.depth.is_float()); |
| 2256 | |
| 2257 | // Read raw float pixels from tex (Float32 or Float16) to verify > 1.0 and < 0.0 survived Scale's DisplayBlit! |
| 2258 | let [w, h] = tex.size; |
| 2259 | let bpp = if tex.format == wgpu::TextureFormat::Rgba32Float { 16u32 } else { 8u32 }; |
| 2260 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 2261 | let padded_bpr = (w * bpp).div_ceil(align) * align; |
| 2262 | let buf = eng.device.create_buffer(&wgpu::BufferDescriptor { |
| 2263 | label: Some("hdr-readback"), |
| 2264 | size: u64::from(padded_bpr) * u64::from(h), |
| 2265 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 2266 | mapped_at_creation: false, |
| 2267 | }); |
| 2268 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 2269 | enc.copy_texture_to_buffer( |
| 2270 | tex.texture.as_image_copy(), |
| 2271 | wgpu::TexelCopyBufferInfo { |
| 2272 | buffer: &buf, |
| 2273 | layout: wgpu::TexelCopyBufferLayout { |
| 2274 | offset: 0, |
| 2275 | bytes_per_row: Some(padded_bpr), |
| 2276 | rows_per_image: Some(h), |
| 2277 | }, |
| 2278 | }, |
| 2279 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2280 | ); |
| 2281 | eng.queue.submit(Some(enc.finish())); |
| 2282 | let slice = buf.slice(..); |
| 2283 | let (tx, rx) = std::sync::mpsc::channel(); |
| 2284 | slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); }); |
| 2285 | eng.device.poll(wgpu::PollType::Wait { |
| 2286 | submission_index: None, |
| 2287 | timeout: Some(std::time::Duration::from_secs(5)), |
| 2288 | }).unwrap(); |
| 2289 | rx.recv().unwrap().unwrap(); |
| 2290 | let data = slice.get_mapped_range().unwrap(); |
| 2291 | let f16_to_f32 = |h: u16| -> f32 { |
| 2292 | let sign = u32::from(h >> 15) << 31; |
| 2293 | let exp = u32::from((h >> 10) & 0x1F); |
| 2294 | let mant = u32::from(h & 0x3FF); |
| 2295 | if exp == 0 { |
| 2296 | if mant == 0 { |
| 2297 | f32::from_bits(sign) |
| 2298 | } else { |
| 2299 | let mut m = mant; |
| 2300 | let mut e = 127 - 14; |
| 2301 | while (m & 0x400) == 0 { |
| 2302 | m <<= 1; |
| 2303 | e -= 1; |
| 2304 | } |
| 2305 | f32::from_bits(sign | (e << 23) | ((m & 0x3FF) << 13)) |
| 2306 | } |
| 2307 | } else if exp == 31 { |
| 2308 | f32::from_bits(sign | 0x7F80_0000 | (mant << 13)) |
| 2309 | } else { |
| 2310 | f32::from_bits(sign | ((exp + 112) << 23) | (mant << 13)) |
| 2311 | } |
| 2312 | }; |
| 2313 | let (r, g, b) = if tex.format == wgpu::TextureFormat::Rgba32Float { |
| 2314 | let px: &[f32] = bytemuck::cast_slice(&data[..16]); |
| 2315 | (px[0], px[1], px[2]) |
| 2316 | } else { |
| 2317 | let px: &[u16] = bytemuck::cast_slice(&data[..8]); |
| 2318 | (f16_to_f32(px[0]), f16_to_f32(px[1]), f16_to_f32(px[2])) |
| 2319 | }; |
| 2320 | assert!((r - 3.5).abs() < 0.05, "expected HDR red ~3.5, got {r}"); |
| 2321 | assert!((g - (-0.25)).abs() < 0.05, "expected negative HDR green ~-0.25, got {g}"); |
| 2322 | assert!((b - 0.5).abs() < 0.05, "expected blue ~0.5, got {b}"); |
| 2323 | } |
| 2324 | |
| 2325 | #[test] |
| 2326 | fn output_cache_enforces_byte_budget_and_reports_in_vram_bytes() { |
| 2327 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2328 | // 64 MiB total VRAM budget -> output_cache cap is 64 / 4 = 16 MiB. |
| 2329 | eng.set_vram_budget_mb(64); |
| 2330 | assert_eq!(eng.output_cache_budget_bytes(), 16 * 1024 * 1024); |
| 2331 | |
| 2332 | // 2048x1024 RGBA8 = 8 MiB per frame (so 16 MiB cap fits 2 frames, evicting the 3rd). |
| 2333 | let src = r#" |
| 2334 | Composition { |
| 2335 | CurrentTime = 0, |
| 2336 | RenderRange = { 0, 5 }, |
| 2337 | GlobalRange = { 0, 5 }, |
| 2338 | Tools = ordered() { |
| 2339 | AnimRed = BezierSpline { |
| 2340 | KeyFrames = { |
| 2341 | [0] = { 0.1 }, |
| 2342 | [5] = { 0.9 }, |
| 2343 | }, |
| 2344 | }, |
| 2345 | BG = Background { |
| 2346 | Inputs = { |
| 2347 | Width = Input { Value = 2048, }, |
| 2348 | Height = Input { Value = 1024, }, |
| 2349 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, |
| 2350 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2351 | }, |
| 2352 | }, |
| 2353 | }, |
| 2354 | } |
| 2355 | "#; |
| 2356 | let comp = Comp::from_fusion_str(src).expect("parse output_cache test comp"); |
| 2357 | let bg = comp.find_node("BG").unwrap(); |
| 2358 | |
| 2359 | let (_, s0) = eng.evaluate(&comp, bg, 0.0); |
| 2360 | assert_eq!(eng.output_cache.len(), 1); |
| 2361 | assert_eq!(eng.output_cache_bytes(), 8 * 1024 * 1024); |
| 2362 | assert!(eng.vram_bytes() >= eng.output_cache_bytes()); |
| 2363 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); |
| 2364 | assert!((s0.cached_vram_mb - eng.vram_mb()).abs() < 0.01); |
| 2365 | |
| 2366 | let (_, _) = eng.evaluate(&comp, bg, 1.0); |
| 2367 | assert_eq!(eng.output_cache.len(), 2); |
| 2368 | assert_eq!(eng.output_cache_bytes(), 16 * 1024 * 1024); |
| 2369 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); |
| 2370 | |
| 2371 | // Touch frame 0 so frame 1 becomes LRU, then evaluate frame 2 -> frame 1 evicted. |
| 2372 | let (_, warm0) = eng.evaluate(&comp, bg, 0.0); |
| 2373 | assert_eq!(warm0.cache_hits, 1); |
| 2374 | |
| 2375 | let (_, _) = eng.evaluate(&comp, bg, 2.0); |
| 2376 | assert_eq!(eng.output_cache.len(), 2); |
| 2377 | assert_eq!(eng.output_cache_bytes(), 16 * 1024 * 1024); |
| 2378 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); |
| 2379 | |
| 2380 | // Frame 1 was evicted, so evaluating frame 1 misses output_cache; frame 2 hits. |
| 2381 | let k1 = eng.output_cache_key(&comp, bg, 1.0); |
| 2382 | let k2 = eng.output_cache_key(&comp, bg, 2.0); |
| 2383 | assert!(eng.output_cache_get(k1).is_none(), "LRU frame 1 should have been evicted"); |
| 2384 | assert!(eng.output_cache_get(k2).is_some(), "recent frame 2 should still be cached"); |
| 2385 | |
| 2386 | // Even a single frame exceeding the byte cap (e.g., 4096x2048 RGBA8 = 32 MiB > 16 MiB) |
| 2387 | // must always keep at least the most recent frame in output_cache. |
| 2388 | let big_tex = create_texture(&eng.device, [4096, 2048], 0); |
| 2389 | assert_eq!(big_tex.bytes, 32 * 1024 * 1024); |
| 2390 | eng.output_cache_insert(999_999, big_tex, Vec::new()); |
| 2391 | assert_eq!(eng.output_cache.len(), 1); |
| 2392 | assert_eq!(eng.output_cache_bytes(), 32 * 1024 * 1024); |
| 2393 | } |
| 2394 | |
| 2395 | #[test] |
| 2396 | fn output_cache_does_not_double_count_shared_node_cache_textures() { |
| 2397 | let mut eng = Engine::new_headless().expect("gpu"); |
| 2398 | eng.set_vram_budget_mb(64); |
| 2399 | |
| 2400 | let src = r#" |
| 2401 | Composition { |
| 2402 | CurrentTime = 0, |
| 2403 | RenderRange = { 0, 1 }, |
| 2404 | GlobalRange = { 0, 1 }, |
| 2405 | Tools = ordered() { |
| 2406 | BG = Background { |
| 2407 | Inputs = { |
| 2408 | Width = Input { Value = 2048, }, |
| 2409 | Height = Input { Value = 1024, }, |
| 2410 | TopLeftRed = Input { Value = 0.5, }, |
| 2411 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2412 | }, |
| 2413 | }, |
| 2414 | }, |
| 2415 | } |
| 2416 | "#; |
| 2417 | let comp = Comp::from_fusion_str(src).expect("parse shared vram comp"); |
| 2418 | let bg = comp.find_node("BG").unwrap(); |
| 2419 | |
| 2420 | let (tex, _) = eng.evaluate(&comp, bg, 0.0); |
| 2421 | assert_eq!(tex.bytes, 8 * 1024 * 1024); |
| 2422 | drop(tex); |
| 2423 | |
| 2424 | // Texture is held in both NodeCache and output_cache (Arc::strong_count >= 2). |
| 2425 | // vram_bytes() must count the 8 MiB allocation once, not 16 MiB, and NodeCache's |
| 2426 | // budget must remain at the full 64 MiB. |
| 2427 | assert_eq!(eng.output_cache.unshared_bytes(), 0); |
| 2428 | assert_eq!(eng.vram_bytes(), eng.cache.total_vram_bytes()); |
| 2429 | assert_eq!(eng.vram_bytes(), 8 * 1024 * 1024); |
| 2430 | assert_eq!(eng.cache.budget_bytes, 64 * 1024 * 1024); |
| 2431 | |
| 2432 | // If an unshared texture (strong_count == 1) is in output_cache, it IS counted |
| 2433 | // in vram_bytes() and subtracted from NodeCache's budget. |
| 2434 | let unshared = create_texture(&eng.device, [2048, 1024], 42); |
| 2435 | assert_eq!(std::sync::Arc::strong_count(&unshared.texture), 1); |
| 2436 | eng.output_cache_insert(123_456, unshared, Vec::new()); |
| 2437 | assert_eq!(eng.output_cache.unshared_bytes(), 8 * 1024 * 1024); |
| 2438 | assert_eq!(eng.vram_bytes(), 16 * 1024 * 1024); |
| 2439 | assert_eq!(eng.cache.budget_bytes, 56 * 1024 * 1024); |
| 2440 | } |
| 2441 | |
| 2442 | #[test] |
| 2443 | fn time_speed_and_time_stretcher_match_fusion_global_range_and_defaults() { |
| 2444 | let src = r#" |
| 2445 | Composition { |
| 2446 | CurrentTime = 0, |
| 2447 | RenderRange = { 0, 10 }, |
| 2448 | GlobalRange = { -10, 40 }, |
| 2449 | Tools = ordered() { |
| 2450 | TimeR = BezierSpline { |
| 2451 | KeyFrames = { |
| 2452 | [-10] = { 0.0, Flags = { Linear = true } }, |
| 2453 | [40] = { 1.0, Flags = { Linear = true } }, |
| 2454 | }, |
| 2455 | }, |
| 2456 | BG = Background { |
| 2457 | Inputs = { |
| 2458 | Width = Input { Value = 16, }, |
| 2459 | Height = Input { Value = 16, }, |
| 2460 | TopLeftRed = Input { SourceOp = "TimeR", Source = "Value", }, |
| 2461 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2462 | }, |
| 2463 | }, |
| 2464 | TSNeg = TimeSpeed { |
| 2465 | Inputs = { |
| 2466 | Speed = Input { Value = -0.5, }, |
| 2467 | Delay = Input { Value = 2.0, }, |
| 2468 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2469 | }, |
| 2470 | }, |
| 2471 | TSPos = TimeSpeed { |
| 2472 | Inputs = { |
| 2473 | Speed = Input { Value = 0.5, }, |
| 2474 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2475 | }, |
| 2476 | }, |
| 2477 | StrDef = TimeStretcher { |
| 2478 | Inputs = { |
| 2479 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2480 | }, |
| 2481 | }, |
| 2482 | StrSnap = TimeStretcher { |
| 2483 | Inputs = { |
| 2484 | SourceTime = Input { Value = 13.5, }, |
| 2485 | InterpolateBetweenFrames = Input { Value = 0, }, |
| 2486 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2487 | }, |
| 2488 | }, |
| 2489 | }, |
| 2490 | } |
| 2491 | "#; |
| 2492 | let comp = Comp::from_fusion_str(src).expect("parse time remap comp"); |
| 2493 | let Ok(mut eng) = Engine::new_headless() else { |
| 2494 | return; |
| 2495 | }; |
| 2496 | let red_at = |e: &mut Engine, name: &str, t: f64| -> u8 { |
| 2497 | let (tex, _) = e.evaluate(&comp, comp.find_node(name).unwrap(), t); |
| 2498 | e.readback_rgba(&tex).unwrap()[0] |
| 2499 | }; |
| 2500 | // Negative speed at t=4, delay=2, GlobalRange=[-10, 40]: |
| 2501 | // (40 + 1) + (4 - 2 - (-10)) * (-0.5) = 41 - 6 = 35 -> (35 - (-10))/50 = 0.90 -> 230 |
| 2502 | assert!((red_at(&mut eng, "TSNeg", 4.0) as i32 - 230).abs() <= 2); |
| 2503 | // Positive speed at t=4, delay=0, GlobalRange=[-10, 40]: |
| 2504 | // -10 + (4 - (-10)) * 0.5 = -3 -> (-3 - (-10))/50 = 0.14 -> 36 |
| 2505 | assert!((red_at(&mut eng, "TSPos", 4.0) as i32 - 36).abs() <= 2); |
| 2506 | // Omitted SourceTime defaults to 0.0 even at t=6 -> (0 - (-10))/50 = 0.20 -> 51 |
| 2507 | assert!((red_at(&mut eng, "StrDef", 6.0) as i32 - 51).abs() <= 2); |
| 2508 | // InterpolateBetweenFrames=0 rounds half-up via floor(x + 0.5): 13.5 -> 14 -> (14 - (-10))/50 = 0.48 -> 122 |
| 2509 | assert!((red_at(&mut eng, "StrSnap", 0.0) as i32 - 122).abs() <= 2); |
| 2510 | } |
| 2511 | |
| 2512 | #[test] |
| 2513 | fn frame_consumers_persist_within_revision_and_rebuild_on_edit() { |
| 2514 | let src = r#" |
| 2515 | Composition { |
| 2516 | CurrentTime = 0, |
| 2517 | RenderRange = { 0, 2 }, |
| 2518 | GlobalRange = { 0, 2 }, |
| 2519 | Tools = ordered() { |
| 2520 | BG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, |
| 2521 | FG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftRed = Input { Value = 1.0, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, |
| 2522 | FG2 = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftGreen = Input { Value = 1.0, }, TopLeftAlpha = Input { Value = 1.0, }, }, }, |
| 2523 | M = Merge { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Foreground = Input { SourceOp = "FG", Source = "Output", }, }, }, |
| 2524 | }, |
| 2525 | } |
| 2526 | "#; |
| 2527 | let mut comp = Comp::from_fusion_str(src).expect("parse merge comp"); |
| 2528 | let Ok(mut eng) = Engine::new_headless() else { |
| 2529 | return; |
| 2530 | }; |
| 2531 | let m_id = comp.find_node("M").unwrap(); |
| 2532 | let fg_id = comp.find_node("FG").unwrap(); |
| 2533 | let fg2_id = comp.find_node("FG2").unwrap(); |
| 2534 | |
| 2535 | let _ = eng.evaluate(&comp, m_id, 0.0); |
| 2536 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); |
| 2537 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); |
| 2538 | assert!(eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 2539 | |
| 2540 | // Second frame at same revision keeps the cached adjacency table instead of clearing it. |
| 2541 | let _ = eng.evaluate(&comp, m_id, 1.0); |
| 2542 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); |
| 2543 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); |
| 2544 | assert!(eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 2545 | |
| 2546 | // Mutating the comp increments comp.revision and refreshes frame_consumers on next eval. |
| 2547 | comp.connect_output(fg2_id, "Output", m_id, "Foreground").unwrap(); |
| 2548 | let _ = eng.evaluate(&comp, m_id, 1.0); |
| 2549 | assert_eq!(eng.frame_consumers_rev, Some(comp.revision)); |
| 2550 | assert_eq!(eng.frame_consumers.len(), comp.nodes.len()); |
| 2551 | assert!(!eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 2552 | assert!(eng.frame_consumers[fg2_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); |
| 2553 | } |
| 2554 | |
| 2555 | #[test] |
| 2556 | fn vram_drops_clear_bind_groups_and_viewer_blit_bypasses_bg_cache() { |
| 2557 | let Ok(mut eng) = Engine::new_headless() else { |
| 2558 | return; |
| 2559 | }; |
| 2560 | // Default Engine::new wires RAM-scaled MediaCache::default(). |
| 2561 | assert!(crate::media::default_media_cache_budget_mb() >= 512); |
| 2562 | |
| 2563 | // Tight 8 MiB VRAM budget: 1024x1024 RGBA8 = 4 MiB per texture. |
| 2564 | eng.set_vram_budget_mb(8); |
| 2565 | |
| 2566 | let src = r#" |
| 2567 | Composition { |
| 2568 | CurrentTime = 0, |
| 2569 | RenderRange = { 0, 10 }, |
| 2570 | GlobalRange = { 0, 10 }, |
| 2571 | Tools = ordered() { |
| 2572 | AnimRed = BezierSpline { |
| 2573 | KeyFrames = { |
| 2574 | [0] = { 0.1 }, |
| 2575 | [10] = { 0.9 }, |
| 2576 | }, |
| 2577 | }, |
| 2578 | BG = Background { |
| 2579 | Inputs = { |
| 2580 | Width = Input { Value = 1024, }, |
| 2581 | Height = Input { Value = 1024, }, |
| 2582 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, |
| 2583 | TopLeftAlpha = Input { Value = 1.0, }, |
| 2584 | }, |
| 2585 | }, |
| 2586 | BC = BrightnessContrast { |
| 2587 | Inputs = { |
| 2588 | Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2589 | Gain = Input { Value = 1.2, }, |
| 2590 | }, |
| 2591 | }, |
| 2592 | }, |
| 2593 | } |
| 2594 | "#; |
| 2595 | let comp = Comp::from_fusion_str(src).expect("parse vram bg test comp"); |
| 2596 | let bc = comp.find_node("BC").unwrap(); |
| 2597 | |
| 2598 | // Evaluate frame 0 -> uniform_cursor resets to 0 after submit, bg_cache populated. |
| 2599 | let _ = eng.evaluate(&comp, bc, 0.0); |
| 2600 | assert!(eng.frame_eval_target.is_none()); |
| 2601 | assert_eq!(eng.pipelines.borrow().uniform_chunks.len(), 1); |
| 2602 | // Next uniform slot allocated must start at chunk 0, offset 0 (cursor was reset post-submit). |
| 2603 | { |
| 2604 | let mut reg = eng.pipelines.borrow_mut(); |
| 2605 | let slot = reg.alloc_uniform_slot(&eng.device, &eng.queue, &UniformParams::default()); |
| 2606 | assert_eq!(slot, (0, 0)); |
| 2607 | reg.reset_uniform_cursor(); |
| 2608 | } |
| 2609 | assert!(eng.pipelines.borrow().bg_entry_count() > 0); |
| 2610 | |
| 2611 | // Render into ephemeral viewer textures on frame 0 (output_cache hit): must not grow bg_cache! |
| 2612 | let bg_before_viewer = eng.pipelines.borrow().bg_entry_count(); |
| 2613 | let misses_before_viewer = eng.pipelines.borrow().bg_misses; |
| 2614 | let viewer_tex_a = create_texture(&eng.device, [512, 512], 0); |
| 2615 | let viewer_tex_b = create_texture(&eng.device, [640, 360], 0); |
| 2616 | let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_a.texture, DisplaySettings::default()); |
| 2617 | let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_b.texture, DisplaySettings::default()); |
| 2618 | assert_eq!(eng.pipelines.borrow().bg_entry_count(), bg_before_viewer); |
| 2619 | assert_eq!(eng.pipelines.borrow().bg_misses, misses_before_viewer); |
| 2620 | |
| 2621 | // Evaluate frames 1..=3 under 8 MiB budget -> organic eviction increments vram_drops |
| 2622 | // and sync_bg_cache_with_vram_drops clears bg_cache so evicted textures aren't pinned. |
| 2623 | for f in 1..=3 { |
| 2624 | let _ = eng.evaluate(&comp, bc, f as f64); |
| 2625 | } |
| 2626 | assert!(eng.cache.vram_drops() > 0); |
| 2627 | assert_eq!(eng.last_bg_vram_drops.get(), eng.cache.vram_drops()); |
| 2628 | } |
| 2629 | |
| 2630 | #[test] |
| 2631 | fn static_still_loader_is_sticky_while_video_and_sequence_loaders_are_not() { |
| 2632 | let dir = std::env::temp_dir().join("fission_sticky_loader_tiering_test"); |
| 2633 | let _ = std::fs::remove_dir_all(&dir); |
| 2634 | std::fs::create_dir_all(&dir).unwrap(); |
| 2635 | |
| 2636 | let still_path = dir.join("still.png"); |
| 2637 | image::RgbaImage::from_pixel(32, 32, image::Rgba([200, 100, 50, 255])) |
| 2638 | .save(&still_path) |
| 2639 | .unwrap(); |
| 2640 | |
| 2641 | for i in 0..3 { |
| 2642 | let seq_path = dir.join(format!("seq_{i:04}.png")); |
| 2643 | image::RgbaImage::from_pixel(32, 32, image::Rgba([40 * i as u8, 120, 200, 255])) |
| 2644 | .save(&seq_path) |
| 2645 | .unwrap(); |
| 2646 | } |
| 2647 | let seq_first = dir.join("seq_0000.png"); |
| 2648 | |
| 2649 | let video_path = dir.join("anim.mp4"); |
| 2650 | let has_video = std::process::Command::new("ffmpeg") |
| 2651 | .args([ |
| 2652 | "-y", |
| 2653 | "-v", |
| 2654 | "error", |
| 2655 | "-f", |
| 2656 | "lavfi", |
| 2657 | "-i", |
| 2658 | "testsrc2=size=64x64:rate=24:duration=0.5", |
| 2659 | "-c:v", |
| 2660 | "libx264", |
| 2661 | "-pix_fmt", |
| 2662 | "yuv420p", |
| 2663 | ]) |
| 2664 | .arg(&video_path) |
| 2665 | .status() |
| 2666 | .is_ok_and(|s| s.success()); |
| 2667 | |
| 2668 | let video_tool = if has_video { |
| 2669 | format!( |
| 2670 | r#" |
| 2671 | VidLoader = Loader {{ |
| 2672 | Clips = {{ |
| 2673 | Clip {{ |
| 2674 | ID = "Clip1", |
| 2675 | Filename = "{}", |
| 2676 | FormatID = "QuickTimeMovies", |
| 2677 | Length = 12, |
| 2678 | TrimIn = 0, |
| 2679 | TrimOut = 11, |
| 2680 | GlobalStart = 0, |
| 2681 | GlobalEnd = 11, |
| 2682 | }}, |
| 2683 | }}, |
| 2684 | }},"#, |
| 2685 | video_path.to_string_lossy().replace('\\', "/") |
| 2686 | ) |
| 2687 | } else { |
| 2688 | String::new() |
| 2689 | }; |
| 2690 | |
| 2691 | let src = format!( |
| 2692 | r#" |
| 2693 | Composition {{ |
| 2694 | CurrentTime = 0, |
| 2695 | RenderRange = {{ 0, 5 }}, |
| 2696 | GlobalRange = {{ 0, 5 }}, |
| 2697 | Tools = ordered() {{ |
| 2698 | StillLoader = Loader {{ |
| 2699 | Clips = {{ |
| 2700 | Clip {{ |
| 2701 | ID = "Clip1", |
| 2702 | Filename = "{}", |
| 2703 | FormatID = "PNGFormat", |
| 2704 | StartFrame = -1, |
| 2705 | GlobalStart = 0, |
| 2706 | GlobalEnd = 10, |
| 2707 | }}, |
| 2708 | }}, |
| 2709 | }}, |
| 2710 | SeqLoader = Loader {{ |
| 2711 | Clips = {{ |
| 2712 | Clip {{ |
| 2713 | ID = "Clip1", |
| 2714 | Filename = "{}", |
| 2715 | FormatID = "PNGFormat", |
| 2716 | StartFrame = 0, |
| 2717 | Length = 3, |
| 2718 | TrimIn = 0, |
| 2719 | TrimOut = 2, |
| 2720 | GlobalStart = 0, |
| 2721 | GlobalEnd = 2, |
| 2722 | }}, |
| 2723 | }}, |
| 2724 | }},{video_tool} |
| 2725 | }}, |
| 2726 | }} |
| 2727 | "#, |
| 2728 | still_path.to_string_lossy().replace('\\', "/"), |
| 2729 | seq_first.to_string_lossy().replace('\\', "/"), |
| 2730 | ); |
| 2731 | |
| 2732 | let comp = Comp::from_fusion_str(&src).expect("parse loader tiering comp"); |
| 2733 | let still_id = comp.find_node("StillLoader").unwrap(); |
| 2734 | let seq_id = comp.find_node("SeqLoader").unwrap(); |
| 2735 | assert!(is_static_loader_node(comp.node(still_id))); |
| 2736 | assert!(!is_static_loader_node(comp.node(seq_id))); |
| 2737 | if has_video { |
| 2738 | let vid_id = comp.find_node("VidLoader").unwrap(); |
| 2739 | assert!(!is_static_loader_node(comp.node(vid_id))); |
| 2740 | } |
| 2741 | |
| 2742 | let Ok(mut eng) = Engine::new_headless() else { |
| 2743 | let _ = std::fs::remove_dir_all(&dir); |
| 2744 | return; |
| 2745 | }; |
| 2746 | |
| 2747 | let (still_tex, _) = eng.evaluate(&comp, still_id, 0.0); |
| 2748 | assert_ne!(still_tex.content_hash, 0); |
| 2749 | assert!( |
| 2750 | eng.cache.is_entry_sticky(still_tex.content_hash), |
| 2751 | "static still Loader must be marked sticky" |
| 2752 | ); |
| 2753 | |
| 2754 | let (seq_tex, _) = eng.evaluate(&comp, seq_id, 0.0); |
| 2755 | assert_ne!(seq_tex.content_hash, 0); |
| 2756 | assert!( |
| 2757 | !eng.cache.is_entry_sticky(seq_tex.content_hash), |
| 2758 | "multi-frame image-sequence Loader must NOT be sticky" |
| 2759 | ); |
| 2760 | |
| 2761 | if has_video { |
| 2762 | let vid_id = comp.find_node("VidLoader").unwrap(); |
| 2763 | let (vid_tex, _) = eng.evaluate(&comp, vid_id, 0.0); |
| 2764 | assert_ne!(vid_tex.content_hash, 0); |
| 2765 | assert!( |
| 2766 | !eng.cache.is_entry_sticky(vid_tex.content_hash), |
| 2767 | "video Loader must NOT be sticky" |
| 2768 | ); |
| 2769 | |
| 2770 | // Also verify lazy EOF frame-hold in video decoder works cleanly past EOF. |
| 2771 | let mut dec = crate::media::open_video_decoder(&video_path).expect("open video decoder"); |
| 2772 | let nb = dec.info().nb_frames; |
| 2773 | assert!(nb >= 6); |
| 2774 | let near_eof = dec.decode_frame(nb - 2).expect("decode near EOF"); |
| 2775 | let past_eof = dec.decode_frame(nb + 1).expect("hold frame past EOF"); |
| 2776 | assert_eq!(near_eof.len(), past_eof.len()); |
| 2777 | } |
| 2778 | |
| 2779 | let _ = std::fs::remove_dir_all(&dir); |
| 2780 | } |
| 2781 | } |