diff --git a/crates/engine/src/cache.rs b/crates/engine/src/cache.rs index 07a584f1376efcdc30ad19ee3e12ad62ae7b68a2..e3cee7d8029e22e5a5e097bfb96adfa5d9392814 100644 --- a/crates/engine/src/cache.rs +++ b/crates/engine/src/cache.rs @@ -4,7 +4,7 @@ use crate::profile::{FrameProfile, ProfileRecorder}; use model::{BitDepth, Comp, NodeId}; -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -337,13 +337,115 @@ impl TexturePool { struct Entry { tex: CachedTexture, last_used: u64, - producers: HashSet, - frames: HashSet, + sticky: bool, + first_producer: NodeId, + extra_producers: Vec, + first_frame: i64, + extra_frames: Vec, +} + +impl Entry { + fn has_producer(&self, node: NodeId) -> bool { + self.first_producer == node || self.extra_producers.contains(&node) + } + + fn record_producer(&mut self, node: NodeId) { + if !self.has_producer(node) { + self.extra_producers.push(node); + } + } + + fn has_frame(&self, frame: i64) -> bool { + self.first_frame == frame || self.extra_frames.contains(&frame) + } + + fn record_frame(&mut self, frame: i64) { + if !self.has_frame(frame) { + self.extra_frames.push(frame); + } + } + + fn is_multi_frame(&self) -> bool { + !self.extra_frames.is_empty() + } + + /// Eviction priority `(tier, last_used)` where smaller values are evicted first: + /// - Tier 0: single-frame transient intermediates (`!sticky && !multi_frame`) + /// - Tier 1: single-frame sticky generators OR multi-frame non-sticky intermediates + /// - Tier 2: live multi-frame sticky generators (e.g. static `Loader`, `TextPlus`) + fn eviction_priority(&self) -> (u8, u64) { + let tier = match (self.sticky, self.is_multi_frame()) { + (false, false) => 0, + (true, false) | (false, true) => 1, + (true, true) => 2, + }; + (tier, self.last_used) + } } /// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB). pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768; +#[cfg(not(target_arch = "wasm32"))] +fn system_ram_mb() -> Option { + use std::sync::OnceLock; + static RAM_MB: OnceLock> = OnceLock::new(); + *RAM_MB.get_or_init(|| { + #[cfg(target_os = "macos")] + { + let out = std::process::Command::new("sysctl") + .args(["-n", "hw.memsize"]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let bytes: u64 = std::str::from_utf8(&out.stdout).ok()?.trim().parse().ok()?; + Some(bytes / (1024 * 1024)) + } + #[cfg(target_os = "linux")] + { + let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?; + for line in meminfo.lines() { + if let Some(rest) = line.strip_prefix("MemTotal:") { + let kb: u64 = rest.split_whitespace().next()?.parse().ok()?; + return Some(kb / 1024); + } + } + None + } + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + { + None + } + }) +} + +/// Computes `default_vram_budget_mb` from total system RAM (`min(ram_mb / 8, 8192).max(768)`). +#[cfg(any(not(target_arch = "wasm32"), test))] +pub(crate) fn vram_budget_mb_for_ram(ram_mb: Option) -> u64 { + match ram_mb { + Some(mb) if mb > 0 => (mb / 8).min(8192).max(DEFAULT_VRAM_BUDGET_MB), + _ => DEFAULT_VRAM_BUDGET_MB, + } +} + +/// System-aware default GPU texture cache VRAM budget in MiB. +/// +/// Scales up to `8192 MiB` on high-RAM unified-memory machines (`min(ram_mb / 8, 8192).max(768)`) +/// so static 4K `Loader` textures are not evicted during playback, while keeping `wasm32` +/// and low-RAM systems at `DEFAULT_VRAM_BUDGET_MB` (768 MiB). +pub fn default_vram_budget_mb() -> u64 { + #[cfg(target_arch = "wasm32")] + { + DEFAULT_VRAM_BUDGET_MB + } + #[cfg(not(target_arch = "wasm32"))] + { + vram_budget_mb_for_ram(system_ram_mb()) + } +} + /// Alias for `NodeCache` (GPU texture cache + VRAM-budgeted `TexturePool`). pub type GpuCache = NodeCache; @@ -361,7 +463,10 @@ pub struct NodeCache { pool: Mutex, /// Evicted textures deferred until after `queue.submit` so `queue.write_texture` /// never aliases a texture still referenced by in-flight commands in the current encoder. - pending_pool: Vec, + pending_pool: VecDeque, + /// Unkeyed scratch textures (`content_hash == 0`) deferred until after `queue.submit` + /// and recycled into `TexturePool` if no longer referenced on the CPU. + pending_scratch: Mutex>, profiler: Option, } @@ -377,7 +482,8 @@ impl NodeCache { gpu_salt: 0, node_salts: HashMap::new(), pool: Mutex::new(TexturePool::new()), - pending_pool: Vec::new(), + pending_pool: VecDeque::new(), + pending_scratch: Mutex::new(Vec::new()), profiler: None, } } @@ -547,9 +653,22 @@ impl NodeCache { }; tex.depth = depth; tex.content_hash = content_hash; + if content_hash == 0 { + if let Ok(mut scratch) = self.pending_scratch.lock() { + scratch.push(tex.clone()); + } + } tex } + /// Marks a cached entry as belonging to a sticky/high-cost generator (e.g. `Loader`, `TextPlus`) + /// so tight-VRAM eviction sheds single-frame transient intermediates first. + pub fn mark_entry_sticky(&mut self, key: u64) { + if let Some(entry) = self.entries.get_mut(&key) { + entry.sticky = true; + } + } + /// Starts per-node profiling for the upcoming frame evaluation. pub fn begin_frame_profile(&mut self) { let stats = self.pool_stats(); @@ -576,8 +695,8 @@ impl NodeCache { self.tick += 1; let e = self.entries.get_mut(&key)?; e.last_used = self.tick; - e.producers.insert(node); - e.frames.insert(frame); + e.record_producer(node); + e.record_frame(frame); let tex = e.tex.clone(); if let Some(prof) = &mut self.profiler { prof.record(node, true, tex.size, tex.bytes); @@ -593,24 +712,25 @@ impl NodeCache { return; } self.tick += 1; + let mut was_sticky = false; if let Some(old) = self.entries.remove(&key) { + was_sticky = old.sticky; self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes); if !Arc::ptr_eq(&old.tex.texture, &tex.texture) { self.defer_to_pool(old.tex); } } self.total_bytes = self.total_bytes.saturating_add(tex.bytes); - let mut producers = HashSet::new(); - producers.insert(node); - let mut frames = HashSet::new(); - frames.insert(frame); self.entries.insert( key, Entry { tex, last_used: self.tick, - producers, - frames, + sticky: was_sticky, + first_producer: node, + extra_producers: Vec::new(), + first_frame: frame, + extra_frames: Vec::new(), }, ); // Trim pooled textures before evicting live cached nodes so live working sets stay hot. @@ -630,18 +750,20 @@ impl NodeCache { .saturating_add(tex.bytes) <= self.budget_bytes { - self.pending_pool.push(tex); + self.pending_pool.push_back(tex); } else { // Keep most recently evicted textures within budget; drop older pending ones. - while !self.pending_pool.is_empty() - && self + while let Some(dropped) = self.pending_pool.front() { + if self .total_bytes .saturating_add(pending_bytes) .saturating_add(tex.bytes) - > self.budget_bytes - { - let dropped = self.pending_pool.remove(0); + <= self.budget_bytes + { + break; + } pending_bytes = pending_bytes.saturating_sub(dropped.bytes); + self.pending_pool.pop_front(); } if self .total_bytes @@ -649,22 +771,28 @@ impl NodeCache { .saturating_add(tex.bytes) <= self.budget_bytes { - self.pending_pool.push(tex); + self.pending_pool.push_back(tex); } } } - /// Moves textures evicted during the current frame into `TexturePool`. + /// Moves textures evicted or allocated as scratch during the current frame into `TexturePool`. /// Must be called right after `queue.submit` so `queue.write_texture` cannot /// overwrite a texture still used by commands in the submitted encoder. pub fn flush_pending_pool(&mut self) { - if self.pending_pool.is_empty() { - return; - } let drained = std::mem::take(&mut self.pending_pool); for tex in drained { self.return_to_pool(&tex); } + let scratch = { + let mut guard = self.pending_scratch.lock().expect("pending scratch lock"); + std::mem::take(&mut *guard) + }; + for tex in scratch { + if Arc::strong_count(&tex.texture) == 1 && Arc::strong_count(&tex.view) == 1 { + self.return_to_pool(&tex); + } + } } fn return_to_pool(&self, tex: &CachedTexture) { @@ -691,11 +819,14 @@ impl NodeCache { fn evict_over_budget(&mut self) { while self.total_bytes > self.budget_bytes && self.entries.len() > 1 { - let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used) + let Some((&victim_key, _)) = self + .entries + .iter() + .min_by_key(|(_, e)| e.eviction_priority()) else { break; }; - if let Some(removed) = self.entries.remove(&oldest_key) { + if let Some(removed) = self.entries.remove(&victim_key) { self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); self.evictions += 1; self.defer_to_pool(removed.tex); @@ -711,12 +842,34 @@ impl NodeCache { /// Clears all dynamic cached GPU node textures into the pool (within VRAM budget) and bumps global salt. pub fn clear_dynamic(&mut self) -> usize { let count = self.entries.len(); - let drained: Vec = self.entries.drain().map(|(_, e)| e).collect(); + let mut drained: Vec = self.entries.drain().map(|(_, e)| e).collect(); let pending = std::mem::take(&mut self.pending_pool); + let scratch = { + let mut guard = self.pending_scratch.lock().expect("pending scratch lock"); + std::mem::take(&mut *guard) + }; self.total_bytes = 0; self.gpu_salt += 1; - if (!drained.is_empty() || !pending.is_empty()) && self.budget_bytes > 0 { + // Drop or recycle unreferenced scratch textures before pushing drained entries so + // `Arc::strong_count` reflects true external ownership. + let mut recycle_scratch = Vec::new(); + for tex in scratch { + if Arc::strong_count(&tex.texture) == 1 && Arc::strong_count(&tex.view) == 1 { + recycle_scratch.push(tex); + } + } + if (!drained.is_empty() || !pending.is_empty() || !recycle_scratch.is_empty()) + && self.budget_bytes > 0 + { + // Push lower-priority / older entries first so sticky/multi-frame entries + // get higher `last_returned` ticks and survive longest under pool pressure. + drained.sort_by_key(|e| e.eviction_priority()); let mut pool = self.pool.lock().expect("texture pool lock"); + for tex in recycle_scratch { + if tex.bytes > 0 && tex.bytes <= self.budget_bytes { + pool.push(&tex); + } + } for tex in pending { if tex.bytes > 0 && tex.bytes <= self.budget_bytes { pool.push(&tex); @@ -741,7 +894,7 @@ impl NodeCache { let keys: Vec = self .entries .iter() - .filter(|(_, e)| e.frames.contains(&frame)) + .filter(|(_, e)| e.has_frame(frame)) .map(|(k, _)| *k) .collect(); let count = keys.len(); @@ -761,7 +914,7 @@ impl NodeCache { let keys: Vec = self .entries .iter() - .filter(|(_, e)| e.producers.contains(&node)) + .filter(|(_, e)| e.has_producer(node)) .map(|(k, _)| *k) .collect(); let count = keys.len(); @@ -1001,4 +1154,85 @@ mod tests { cache2.flush_pending_pool(); assert_eq!(cache2.pooled_bytes(), 1024 * 1024); } + + #[test] + fn default_vram_budget_scales_sensibly_and_respects_floor() { + assert_eq!(vram_budget_mb_for_ram(None), 768); + assert_eq!(vram_budget_mb_for_ram(Some(0)), 768); + assert_eq!(vram_budget_mb_for_ram(Some(4 * 1024)), 768); + assert_eq!(vram_budget_mb_for_ram(Some(16 * 1024)), 2048); + assert_eq!(vram_budget_mb_for_ram(Some(64 * 1024)), 8192); + assert_eq!(vram_budget_mb_for_ram(Some(256 * 1024)), 8192); + assert!(default_vram_budget_mb() >= DEFAULT_VRAM_BUDGET_MB); + } + + #[test] + fn eviction_protects_sticky_and_multi_frame_entries_over_single_frame_intermediates() { + let eng = Engine::new_headless().expect("gpu"); + let device = eng.device(); + let usage = NodeCache::default_texture_usage(); + // 3 MiB budget; each 512x512 RGBA8 texture is 1 MiB. + let mut cache = NodeCache::new(3); + + // Insert a sticky Loader texture (key 100) and hit it on frame 1 so it becomes Tier 2. + let loader = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + cache.insert(100, loader, NodeId(0), 0); + cache.mark_entry_sticky(100); + assert!(cache.get(100, NodeId(0), 1).is_some()); + + // Insert a non-sticky multi-frame texture (key 200, Tier 1). + let static_op = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + cache.insert(200, static_op, NodeId(1), 0); + assert!(cache.get(200, NodeId(1), 1).is_some()); + + // Flood with newer single-frame transient intermediates (Tier 0, keys 301..=304). + // Even though keys 301..=304 have newer `last_used` ticks than keys 100 and 200, + // Tier 0 transient intermediates must be evicted first so the Loader (key 100) survives! + for k in 301..=304u64 { + let tmp = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + cache.insert(k, tmp, NodeId(2), 2); + } + + assert!(cache.total_vram_bytes() <= 3 * 1024 * 1024); + assert!(cache.get(100, NodeId(0), 2).is_some(), "sticky multi-frame Loader must survive eviction"); + assert!(cache.get(200, NodeId(1), 2).is_some(), "multi-frame entry must survive ahead of Tier 0 intermediates"); + assert!(cache.get(301, NodeId(2), 2).is_none(), "single-frame transient intermediate must be evicted first"); + } + + #[test] + fn scratch_textures_recycle_into_pool_after_flush() { + let eng = Engine::new_headless().expect("gpu"); + let device = eng.device(); + let mut cache = NodeCache::new(16); + + let ptr = { + let scratch = cache.acquire_texture_dod_fmt( + device, + [512, 512], + [0, 0], + [512, 512], + BitDepth::Int8, + wgpu::TextureFormat::Rgba8Unorm, + 0, + ); + Arc::as_ptr(&scratch.texture) + }; + // Still deferred until flush_pending_pool() so mid-frame passes cannot alias. + assert_eq!(cache.pooled_bytes(), 0); + + cache.flush_pending_pool(); + assert_eq!(cache.pooled_bytes(), 1024 * 1024); + + let reused = cache.acquire_texture_dod_fmt( + device, + [512, 512], + [0, 0], + [512, 512], + BitDepth::Int8, + wgpu::TextureFormat::Rgba8Unorm, + 0, + ); + assert_eq!(Arc::as_ptr(&reused.texture), ptr); + assert_eq!(cache.pool_stats().hits, 1); + } } diff --git a/crates/engine/src/eval/composite.rs b/crates/engine/src/eval/composite.rs index f2db5ed8899fc823b9d07bead352b9ec7f67f980..93e3ec2a2ba1d4f2f80add6e56adb99a7dc2d534 100644 --- a/crates/engine/src/eval/composite.rs +++ b/crates/engine/src/eval/composite.rs @@ -1,5 +1,37 @@ use super::*; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum RoiBox { + Empty, + Rect { x0: i32, y0: i32, x1: i32, y1: i32 }, +} + +impl RoiBox { + fn union(self, other: Self) -> Self { + match (self, other) { + (Self::Empty, r) | (r, Self::Empty) => r, + ( + Self::Rect { x0: ax0, y0: ay0, x1: ax1, y1: ay1 }, + Self::Rect { x0: bx0, y0: by0, x1: bx1, y1: by1 }, + ) => Self::Rect { + x0: ax0.min(bx0), + y0: ay0.min(by0), + x1: ax1.max(bx1), + y1: ay1.max(by1), + }, + } + } + + fn canvas(canvas_size: [u32; 2]) -> Self { + Self::Rect { + x0: 0, + y0: 0, + x1: canvas_size[0].max(1) as i32, + y1: canvas_size[1].max(1) as i32, + } + } +} + /// Expands `[bg0, bg1)` to include `[fg0, fg1)` with a 2px AA apron while /// clamping total span to `max_dim` without an artificial symmetric half-cap. fn expand_dod_axis(bg0: i32, bg1: i32, fg0: f32, fg1: f32, max_dim: i32) -> (i32, i32) { @@ -22,7 +54,692 @@ fn expand_dod_axis(bg0: i32, bg1: i32, fg0: f32, fg1: f32, max_dim: i32) -> (i32 (bg0 - take0, bg1 + take1) } +fn infer_node_canvas_size( + comp: &Comp, + start_id: NodeId, + time: f64, + expr: &ExprEngine, + comp_dims: [u32; 2], + depth: usize, +) -> Option<[u32; 2]> { + let mut cur_id = start_id; + for _ in 0..depth { + let n = comp.node(cur_id); + if n.bypassed + || matches!( + n.kind.as_str(), + "PipeRouter" + | "Fuse.Wireless" + | "Tracker" + | "Dimension.OpticalFlow" + | "OpticalFlow" + | "Dimension.CopyAux" + | "ColorCorrector" + | "ColorCurves" + | "BrightnessContrast" + | "ColorGain" + | "InvertColor" + | "GamutConvert" + | "HueCurves" + | "ChangeDepth" + | "LumaKeyer" + | "UltraKeyer" + | "DeltaKeyer" + | "Blur" + | "DirectionalBlur" + | "Glow" + | "SoftGlow" + | "Fuse.XGlow" + | "Filter" + | "Sharpen" + | "ErodeDilate" + | "Transform" + ) + { + let port = default_main_input_port(&n.kind); + cur_id = n.connected_node(port).and_then(|s| comp.find_node(s))?; + continue; + } + match n.kind.as_str() { + "Merge" | "ChannelBoolean" | "Dissolve" => { + cur_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?; + } + "Fuse.Colorize" => { + cur_id = n + .connected_node("Image") + .or_else(|| n.connected_node("Input")) + .and_then(|s| comp.find_node(s))?; + } + "Background" | "FastNoise" | "Plasma" | "DaySky" => { + if Engine::resolve_effect_mask_id(comp, n).is_some() + || comp.eval_number(n, "UseFrameFormatSettings", time, 0.0, expr) > 0.5 + { + return None; + } + let w = comp.eval_number(n, "Width", time, comp_dims[0] as f64, expr).max(1.0) as u32; + let h = comp.eval_number(n, "Height", time, comp_dims[1] as f64, expr).max(1.0) as u32; + // Only unambiguous when explicit dimensions aren't additionally proxy-scaled differently. + if !n.inputs.contains_key("Width") && !n.inputs.contains_key("Height") { + return Some(comp_dims); + } + return Some([w, h]); + } + _ => return None, + } + } + None +} + +fn inverse_transform_box( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, + canvas_size: [u32; 2], + has_mask: bool, + blend: f32, + downstream: RoiBox, +) -> Option { + let RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 } = downstream else { + return Some(RoiBox::Empty); + }; + let (dx0, dy0, dx1, dy1) = if has_mask { + ( + dx0.max(0), + dy0.max(0), + dx1.min(canvas_size[0].max(1) as i32), + dy1.min(canvas_size[1].max(1) as i32), + ) + } else { + (dx0, dy0, dx1, dy1) + }; + if dx0 >= dx1 || dy0 >= dy1 { + return Some(RoiBox::Empty); + } + + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], expr); + let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], expr); + let use_xy = comp.eval_number(node, "UseSizeAndAspect", time, 1.0, expr) < 0.5; + let (sx, sy) = if use_xy { + ( + comp.eval_number(node, "XSize", time, 1.0, expr) as f32, + comp.eval_number(node, "YSize", time, 1.0, expr) as f32, + ) + } else { + let s = comp.eval_number(node, "Size", time, 1.0, expr) as f32; + let asp = comp.eval_number(node, "Aspect", time, 1.0, expr) as f32; + (s, s * asp) + }; + let angle = (comp.eval_number(node, "Angle", time, 0.0, expr) as f32).to_radians(); + let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, expr) > 0.5; + let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, expr) > 0.5; + + if !sx.is_finite() + || !sy.is_finite() + || !angle.is_finite() + || !center[0].is_finite() + || !center[1].is_finite() + || !pivot[0].is_finite() + || !pivot[1].is_finite() + || sx <= 1e-4 + || sy <= 1e-4 + { + return None; + } + + let cw = canvas_size[0].max(1) as f32; + let ch = canvas_size[1].max(1) as f32; + let cx = center[0] as f32; + let cy = center[1] as f32; + let px = pivot[0] as f32; + let py = pivot[1] as f32; + let is_identity = (cx - 0.5).abs() < 1e-5 + && (cy - 0.5).abs() < 1e-5 + && (sx - 1.0).abs() < 1e-5 + && (sy - 1.0).abs() < 1e-5 + && angle.abs() < 1e-5 + && !flip_h + && !flip_v; + if is_identity { + return Some(RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 }); + } + + let shift_x = cx - 0.5; + let shift_y = cy - 0.5; + let (s, c) = angle.sin_cos(); + + let mut min_x = f32::INFINITY; + let mut max_x = f32::NEG_INFINITY; + let mut min_y = f32::INFINITY; + let mut max_y = f32::NEG_INFINITY; + if blend < 1.0 - 1e-5 || has_mask { + min_x = dx0 as f32; + max_x = dx1 as f32; + min_y = dy0 as f32; + max_y = dy1 as f32; + } + for &(x, y) in &[ + (dx0 as f32, dy0 as f32), + (dx1 as f32, dy0 as f32), + (dx0 as f32, dy1 as f32), + (dx1 as f32, dy1 as f32), + ] { + let fu_x = x / cw; + let fu_y = 1.0 - y / ch; + let rel_x = (fu_x - px - shift_x) * cw; + let rel_y = (fu_y - py - shift_y) * ch; + let unrot_x = rel_x * c + rel_y * s; + let unrot_y = -rel_x * s + rel_y * c; + let mut sfu_x = unrot_x / sx / cw + px; + let mut sfu_y = unrot_y / sy / ch + py; + if flip_h { + sfu_x = 1.0 - sfu_x; + } + if flip_v { + sfu_y = 1.0 - sfu_y; + } + let sx_px = sfu_x * cw; + let sy_px = (1.0 - sfu_y) * ch; + min_x = min_x.min(sx_px); + max_x = max_x.max(sx_px); + min_y = min_y.min(sy_px); + max_y = max_y.max(sy_px); + } + if !min_x.is_finite() || !max_x.is_finite() || !min_y.is_finite() || !max_y.is_finite() { + return None; + } + let pad = 6; + Some(RoiBox::Rect { + x0: (min_x.floor() as i32).saturating_sub(pad), + y0: (min_y.floor() as i32).saturating_sub(pad), + x1: (max_x.ceil() as i32).saturating_add(pad), + y1: (max_y.ceil() as i32).saturating_add(pad), + }) +} + +fn inverse_merge_fg_box( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, + bg_canvas: [u32; 2], + fg_canvas: [u32; 2], + downstream: RoiBox, +) -> Option { + let RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 } = downstream else { + return Some(RoiBox::Empty); + }; + if dx0 >= dx1 || dy0 >= dy1 { + return Some(RoiBox::Empty); + } + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], expr); + let size = comp.eval_number(node, "Size", time, 1.0, expr) as f32; + let angle = (comp.eval_number(node, "Angle", time, 0.0, expr) as f32).to_radians(); + let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, expr) > 0.5; + let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, expr) > 0.5; + if !size.is_finite() + || !angle.is_finite() + || !center[0].is_finite() + || !center[1].is_finite() + || size <= 1e-4 + { + return None; + } + + let bg_cw = bg_canvas[0].max(1) as f32; + let bg_ch = bg_canvas[1].max(1) as f32; + let fg_cw = fg_canvas[0].max(1) as f32; + let fg_ch = fg_canvas[1].max(1) as f32; + let cx = center[0] as f32; + let cy = center[1] as f32; + let is_identity = bg_canvas == fg_canvas + && (cx - 0.5).abs() < 1e-5 + && (cy - 0.5).abs() < 1e-5 + && (size - 1.0).abs() < 1e-5 + && angle.abs() < 1e-5 + && !flip_h + && !flip_v; + if is_identity { + return Some(RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 }); + } + + let (s, c) = angle.sin_cos(); + let mut min_x = f32::INFINITY; + let mut max_x = f32::NEG_INFINITY; + let mut min_y = f32::INFINITY; + let mut max_y = f32::NEG_INFINITY; + for &(x, y) in &[ + (dx0 as f32, dy0 as f32), + (dx1 as f32, dy0 as f32), + (dx0 as f32, dy1 as f32), + (dx1 as f32, dy1 as f32), + ] { + let fu_x = x / bg_cw; + let fu_y = 1.0 - y / bg_ch; + let delta_x = (fu_x - cx) * bg_cw; + let delta_y = (fu_y - cy) * bg_ch; + let rot_x = (delta_x * c + delta_y * s) / size; + let rot_y = (-delta_x * s + delta_y * c) / size; + let mut fg_fu_x = rot_x / fg_cw + 0.5; + let mut fg_fu_y = rot_y / fg_ch + 0.5; + if flip_h { + fg_fu_x = 1.0 - fg_fu_x; + } + if flip_v { + fg_fu_y = 1.0 - fg_fu_y; + } + let sx_px = fg_fu_x * fg_cw; + let sy_px = (1.0 - fg_fu_y) * fg_ch; + min_x = min_x.min(sx_px); + max_x = max_x.max(sx_px); + min_y = min_y.min(sy_px); + max_y = max_y.max(sy_px); + } + if !min_x.is_finite() || !max_x.is_finite() || !min_y.is_finite() || !max_y.is_finite() { + return None; + } + let pad = 6; + Some(RoiBox::Rect { + x0: (min_x.floor() as i32).saturating_sub(pad), + y0: (min_y.floor() as i32).saturating_sub(pad), + x1: (max_x.ceil() as i32).saturating_add(pad), + y1: (max_y.ceil() as i32).saturating_add(pad), + }) +} + +#[allow(clippy::too_many_arguments)] +fn roi_for_node( + comp: &Comp, + node_id: NodeId, + canvas_size: [u32; 2], + comp_dims: [u32; 2], + time: f64, + time_key: i64, + hiq: bool, + expr: &ExprEngine, + consumers: &[Vec<(NodeId, String)>], + memo: &mut HashMap<(NodeId, i64), Option>, + visiting: &mut HashSet, + depth: usize, +) -> Option { + if depth == 0 { + return None; + } + if let Some(&cached) = memo.get(&(node_id, time_key)) { + return cached; + } + if !visiting.insert(node_id) { + return None; + } + + let node_consumers = &consumers[node_id.0]; + let res = if node_consumers.is_empty() { + Some(RoiBox::canvas(canvas_size)) + } else { + let mut acc = RoiBox::Empty; + let mut ok = true; + for (cid, port) in node_consumers { + if let Some(r) = roi_from_consumer( + comp, + *cid, + port, + canvas_size, + comp_dims, + time, + time_key, + hiq, + expr, + consumers, + memo, + visiting, + depth - 1, + ) { + acc = acc.union(r); + } else { + ok = false; + break; + } + } + if ok { Some(acc) } else { None } + }; + + visiting.remove(&node_id); + memo.insert((node_id, time_key), res); + res +} + +#[allow(clippy::too_many_arguments)] +fn roi_from_consumer( + comp: &Comp, + cid: NodeId, + port: &str, + canvas_size: [u32; 2], + comp_dims: [u32; 2], + time: f64, + time_key: i64, + hiq: bool, + expr: &ExprEngine, + consumers: &[Vec<(NodeId, String)>], + memo: &mut HashMap<(NodeId, i64), Option>, + visiting: &mut HashSet, + depth: usize, +) -> Option { + if matches!( + port, + "EffectMask" | "GlowMask" | "Garbage.Matte" | "GarbageMatte" | "Solid.Matte" | "SolidMatte" + ) { + return None; + } + let n = comp.node(cid); + if port == "__macro_output" { + return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + } + if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { + return None; + } + if n.bypassed + || matches!( + n.kind.as_str(), + "PipeRouter" | "Fuse.Wireless" | "Tracker" | "Dimension.OpticalFlow" | "OpticalFlow" | "Dimension.CopyAux" + ) + { + if port == default_main_input_port(&n.kind) { + return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + } + return None; + } + + match n.kind.as_str() { + "Saver" | "MediaOut" => Some(RoiBox::canvas(canvas_size)), + "BrightnessContrast" | "ColorCorrector" | "ColorCurves" | "ColorGain" | "InvertColor" + | "GamutConvert" | "HueCurves" | "ChangeDepth" | "LumaKeyer" => { + let main_ok = port == "Input" || (n.kind == "InvertColor" && port == "Image1"); + if !main_ok { + return None; + } + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some(); + let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; + if blend <= 1e-6 && !mbm { + return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + } + if has_mask { + return Some(RoiBox::canvas(canvas_size)); + } + roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } + "Fuse.Colorize" => { + if port != "Image" && port != "Input" { + return None; + } + if Engine::resolve_effect_mask_id(comp, n).is_some() { + return Some(RoiBox::canvas(canvas_size)); + } + roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } + "ChannelBoolean" => { + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + let mbm = Engine::resolve_effect_mask_id(comp, n).is_some() + && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; + if blend <= 1e-6 && !mbm { + return match port { + "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth), + "Foreground" => Some(RoiBox::Empty), + _ => None, + }; + } + if port == "Background" || port == "Foreground" { + roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } else { + None + } + } + "DirectionalBlur" => { + if port != "Input" { + return None; + } + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some(); + let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; + if blend <= 1e-6 && !mbm { + return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + } + if n.static_str("ClippingMode").unwrap_or("Frame") != "None" || has_mask { + Some(RoiBox::canvas(canvas_size)) + } else { + None + } + } + "Dissolve" => { + let mix_v = comp.eval_number(n, "Mix", time, 1.0, expr).clamp(0.0, 1.0); + let blend = comp.eval_number(n, "Blend", time, 1.0, expr); + let has_mask = n.connected_node("EffectMask").is_some(); + let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; + if (blend <= 1e-6 || mix_v <= 1e-6) && !mbm { + return match port { + "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth), + "Foreground" => Some(RoiBox::Empty), + _ => None, + }; + } + if mix_v >= 1.0 - 1e-6 && blend >= 1.0 - 1e-6 && !has_mask { + return match port { + "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth), + "Background" => Some(RoiBox::Empty), + _ => None, + }; + } + if port == "Background" || port == "Foreground" { + Some(RoiBox::canvas(canvas_size)) + } else { + None + } + } + "Scale" | "BetterResize" => { + if port != "Input" { + return None; + } + let hiq_only = comp.eval_number(n, "HiQOnly", time, 0.0, expr) > 0.5; + if n.kind == "Scale" && !hiq && hiq_only { + roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } else { + Some(RoiBox::canvas(canvas_size)) + } + } + "Shadow" | "Glow" | "SoftGlow" | "Fuse.XGlow" | "DeltaKeyer" => { + if port != "Input" { + return None; + } + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + let mbm = n.kind != "Fuse.XGlow" + && n.connected_node("EffectMask").is_some() + && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; + if blend <= 1e-6 && !mbm { + roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } else { + Some(RoiBox::canvas(canvas_size)) + } + } + "Displace" => { + if port != "Input" && port != "Foreground" { + return None; + } + let fg_none = n.connected_node("Foreground").and_then(|s| comp.find_node(s)).is_none(); + let mbm = n.connected_node("EffectMask").is_some() + && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; + if fg_none && !mbm { + roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth) + } else { + Some(RoiBox::canvas(canvas_size)) + } + } + "CameraShake" | "DVE" | "Vortex" | "Drip" | "Dent" | "GridWarp" | "VariBlur" + | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Fuse.XfChroma" + | "Paint" => { + if port != default_main_input_port(&n.kind) && port != "Input" && port != "Image" { + return None; + } + // Conservatively union canvas crop with downstream RoI in case the node short-circuits + // on an idle parameter (e.g. Blend = 0, radius = 0, etc.). + let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; + Some(RoiBox::canvas(canvas_size).union(down)) + } + "Blur" => { + if port != "Input" { + return None; + } + let lock_xy = comp.eval_number(n, "LockXY", time, 1.0, expr) > 0.5; + let filter_name = n.static_str("Filter").unwrap_or("Fast Gaussian"); + let gauss_k = match filter_name { + "Box" => 1.0_f32, + "Gaussian" => 1.07_f32, + _ => 0.96_f32, + }; + let scale_ref = canvas_size[0].max(1) as f32 / 720.0; + let x_raw = comp.eval_number(n, "XBlurSize", time, 1.0, expr) as f32; + let y_raw = if lock_xy { + x_raw + } else { + comp.eval_number(n, "YBlurSize", time, 1.0, expr) as f32 + }; + let rx = x_raw * scale_ref * gauss_k; + let ry = y_raw * scale_ref * gauss_k; + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + if rx.max(ry) < 0.25 || blend <= 1e-6 { + return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + } + if Engine::resolve_effect_mask_id(comp, n).is_some() { + return Some(RoiBox::canvas(canvas_size)); + } + if !rx.is_finite() || !ry.is_finite() || rx.abs() * 1.6 > 2048.0 || ry.abs() * 1.6 > 2048.0 { + return None; + } + let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; + let RoiBox::Rect { x0, y0, x1, y1 } = down else { + return Some(RoiBox::Empty); + }; + let pad_x = (rx.abs() * 1.6).ceil() as i32 + 16; + let pad_y = (ry.abs() * 1.6).ceil() as i32 + 16; + Some(RoiBox::Rect { + x0: x0 - pad_x, + y0: y0 - pad_y, + x1: x1 + pad_x, + y1: y1 + pad_y, + }) + } + "Transform" => { + if port != "Input" { + return None; + } + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + if blend <= 1e-6 { + return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + } + if comp.eval_number(n, "InvertTransform", time, 0.0, expr) > 0.5 { + return None; + } + let edges = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32; + if edges != 0 { + return None; + } + let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some(); + let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; + inverse_transform_box(comp, n, time, expr, canvas_size, has_mask, blend, down) + } + "Merge" => { + let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32; + let mbm = n.connected_node("EffectMask").is_some() + && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5; + if blend <= 1e-6 && !mbm { + return match port { + "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth), + "Foreground" => Some(RoiBox::Empty), + _ => None, + }; + } + if port == "Background" { + return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth); + } + if port == "Foreground" { + let edges = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32; + if edges != 0 { + return None; + } + let bg_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?; + let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, 16)?; + let down = roi_for_node(comp, cid, bg_canvas, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?; + return inverse_merge_fg_box(comp, n, time, expr, bg_canvas, canvas_size, down); + } + None + } + _ => None, + } +} + impl Engine { + fn ensure_frame_consumers(&mut self, comp: &Comp) { + if self.frame_consumers.len() == comp.nodes.len() { + return; + } + self.frame_consumers.clear(); + self.frame_consumers.resize_with(comp.nodes.len(), Vec::new); + for n in &comp.nodes { + if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { + if let Some(out_id) = n.macro_output { + if out_id.0 < self.frame_consumers.len() { + self.frame_consumers[out_id.0].push((n.id, "__macro_output".to_owned())); + } + continue; + } + } + for (port, binding) in &n.inputs { + if let Some(src_id) = binding.source_op.as_deref().and_then(|s| comp.find_node(s)) { + if src_id.0 < self.frame_consumers.len() { + self.frame_consumers[src_id.0].push((n.id, port.clone())); + } + } + } + if n.connected_node("EffectMask").is_none() { + if let Some(mid) = Self::resolve_effect_mask_id(comp, n) { + if mid.0 < self.frame_consumers.len() { + self.frame_consumers[mid.0].push((n.id, "EffectMask".to_owned())); + } + } + } + } + } + + fn merge_downstream_roi_bounds( + &mut self, + comp: &Comp, + merge_id: NodeId, + canvas_size: [u32; 2], + time: f64, + ) -> Option<(i32, i32, i32, i32)> { + self.ensure_frame_consumers(comp); + let comp_dims = self.scaled_dims(comp.width, comp.height); + let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; + let mut visiting = HashSet::new(); + let res = roi_for_node( + comp, + merge_id, + canvas_size, + comp_dims, + time, + time_key, + self.hiq, + &self.expr, + &self.frame_consumers, + &mut self.frame_roi_memo, + &mut visiting, + 32, + )?; + match res { + RoiBox::Rect { x0, y0, x1, y1 } => Some((x0, y0, x1, y1)), + RoiBox::Empty => Some((0, 0, canvas_size[0].max(1) as i32, canvas_size[1].max(1) as i32)), + } + } + fn flattened_fg_edge_mode( comp: &Comp, fg_id: NodeId, @@ -147,6 +864,12 @@ impl Engine { let mut dst_origin = bg.origin; let mut dst_size = bg.size; + let roi_bounds = if bg.tex_scale >= 0.99 && fg.tex_scale >= 0.99 { + self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time) + } else { + None + }; + if edges < 0.5 && mask.is_none() && mode_id == 0.0 @@ -183,14 +906,41 @@ impl Engine { fg_y1 = fg_y1.max(py); } let max_dim = self.device.limits().max_texture_dimension_2d.min(8192) as i32; - let (ux0, ux1) = expand_dod_axis(bg_x0, bg_x1, fg_x0, fg_x1, max_dim); - let (uy0, uy1) = expand_dod_axis(bg_y0, bg_y1, fg_y0, fg_y1, max_dim); + let (mut ux0, mut ux1) = expand_dod_axis(bg_x0, bg_x1, fg_x0, fg_x1, max_dim); + let (mut uy0, mut uy1) = expand_dod_axis(bg_y0, bg_y1, fg_y0, fg_y1, max_dim); + if let Some((rx0, ry0, rx1, ry1)) = roi_bounds { + let cx0 = ux0.max(rx0); + let cx1 = ux1.min(rx1); + let cy0 = uy0.max(ry0); + let cy1 = uy1.min(ry1); + if cx0 < cx1 && cy0 < cy1 { + ux0 = cx0; + ux1 = cx1; + uy0 = cy0; + uy1 = cy1; + } + } let uw = (ux1 - ux0).max(1) as u32; let uh = (uy1 - uy0).max(1) as u32; if uw <= max_dim as u32 && uh <= max_dim as u32 && (ux0 != bg_x0 || uy0 != bg_y0 || uw != bg.size[0] || uh != bg.size[1]) { dst_origin = [ux0, uy0]; dst_size = [uw, uh]; } + } else if let Some((rx0, ry0, rx1, ry1)) = roi_bounds { + let cx0 = bg_x0.max(rx0); + let cx1 = bg_x1.min(rx1); + let cy0 = bg_y0.max(ry0); + let cy1 = bg_y1.min(ry1); + if cx0 < cx1 + && cy0 < cy1 + && (cx0 != bg_x0 + || cy0 != bg_y0 + || (cx1 - cx0) as u32 != bg.size[0] + || (cy1 - cy0) as u32 != bg.size[1]) + { + dst_origin = [cx0, cy0]; + dst_size = [(cx1 - cx0) as u32, (cy1 - cy0) as u32]; + } } let dst_has_dod = dst_origin != [0, 0] || dst_size != bg.canvas_size; @@ -1205,4 +1955,109 @@ mod tests { assert_eq!(super::expand_dod_axis(0, 1920, 4400.0, 6324.0, 8192), (0, 6326)); assert_eq!(super::expand_dod_axis(-1000, 1920, -6000.0, 6000.0, 8192), (-3902, 4290)); } + + #[test] + fn downstream_roi_bounds_clips_pixelwise_merge_and_preserves_spatial_dod() { + let comp_src = r#"{ + Tools = ordered() { + Bg = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + HugeFg = Background { + Inputs = { + Width = Input { Value = 256, }, + Height = Input { Value = 256, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + MergePixel = Merge { + Inputs = { + Background = Input { SourceOp = "Bg", Source = "Output", }, + Foreground = Input { SourceOp = "HugeFg", Source = "Output", }, + Size = Input { Value = 2.0, }, + }, + }, + Cc = ColorCorrector { + Inputs = { + Input = Input { SourceOp = "MergePixel", Source = "Output", }, + }, + }, + DbFrame = DirectionalBlur { + Inputs = { + Input = Input { SourceOp = "Cc", Source = "Output", }, + Length = Input { Value = 0.05, }, + }, + }, + MergeXf = Merge { + Inputs = { + Background = Input { SourceOp = "Bg", Source = "Output", }, + Foreground = Input { SourceOp = "HugeFg", Source = "Output", }, + Size = Input { Value = 1.0, }, + }, + }, + XfOut = Transform { + Inputs = { + Size = Input { Value = 0.25, }, + Input = Input { SourceOp = "MergeXf", Source = "Output", }, + }, + }, + MergeCrop = Merge { + Inputs = { + Background = Input { SourceOp = "Bg", Source = "Output", }, + Foreground = Input { SourceOp = "HugeFg", Source = "Output", }, + Size = Input { Value = 1.0, }, + }, + }, + CropOut = Crop { + Inputs = { + XOffset = Input { Value = -32, }, + YOffset = Input { Value = -32, }, + XSize = Input { Value = 64, }, + YSize = Input { Value = 64, }, + Input = Input { SourceOp = "MergeCrop", Source = "Output", }, + }, + }, + } + }"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse roi comp"); + let mut eng = Engine::new_headless().expect("headless engine"); + let mut enc = eng.device.create_command_encoder(&Default::default()); + let mut visiting = std::collections::HashSet::new(); + let mut stats = super::EvalStats::default(); + + // Pixelwise + Frame-clipped DirectionalBlur downstream -> MergePixel stays tightly at 64x64. + let mp_id = comp.find_node("MergePixel").unwrap(); + let mp_tex = eng.eval_node(&comp, mp_id, 0.0, &mut enc, &mut visiting, &mut stats); + assert_eq!(mp_tex.origin, [0, 0]); + assert_eq!(mp_tex.size, [64, 64]); + + // Transform zooming out (Size=0.25) downstream -> MergeXf expands its DoD cleanly. + let mxf_id = comp.find_node("MergeXf").unwrap(); + let mxf_tex = eng.eval_node(&comp, mxf_id, 0.0, &mut enc, &mut visiting, &mut stats); + assert!(mxf_tex.size[0] > 64 && mxf_tex.size[1] > 64, "expected expanded DoD for zoom-out Transform, got {:?}", mxf_tex.size); + + // Crop reading outside canvas -> MergeCrop bails out and preserves full DoD. + let mc_id = comp.find_node("MergeCrop").unwrap(); + let mc_tex = eng.eval_node(&comp, mc_id, 0.0, &mut enc, &mut visiting, &mut stats); + assert_eq!(mc_tex.size, [260, 260]); + eng.queue.submit(Some(enc.finish())); + eng.frame_memo.clear(); + eng.frame_consumers.clear(); + eng.frame_roi_memo.clear(); + + // Corner of XfOut must show HugeFg's red from outside the 64x64 BG canvas. + let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XfOut").unwrap(), 0.0); + let xf_px = eng.readback_rgba(&xf_tex).unwrap(); + assert!(px_at(&xf_px, xf_tex.size[0], 10, 10)[0] > 200, "zoom-out Transform corner must sample expanded DoD"); + + // CropOut reading [-32..32] must also sample HugeFg's red from outside the 64x64 BG canvas. + let (cr_tex, _) = eng.evaluate(&comp, comp.find_node("CropOut").unwrap(), 0.0); + let cr_px = eng.readback_rgba(&cr_tex).unwrap(); + assert!(px_at(&cr_px, cr_tex.size[0], 8, 8)[0] > 200, "Crop at negative offset must sample expanded DoD"); + } } diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index cfc74d38f9ad314b6db29ea89e31ad73414ecfce..2a9beb7f45b28a3c8510b598826bffacdc7b3786 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -81,6 +81,10 @@ pub struct Engine { pub expr: ExprEngine, /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, + /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current frame. + frame_consumers: Vec>, + /// Per-evaluation memo of conservative downstream RoI bounds `(node_id, time_bits)`. + frame_roi_memo: HashMap<(NodeId, i64), Option>, output_cache: OutputCache, /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default /// to matching the dimensions & aspect ratio of the node they mask!). @@ -110,6 +114,7 @@ impl Engine { }, wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, ); + let default_vram_mb = crate::cache::default_vram_budget_mb(); Self { device, queue, @@ -125,11 +130,13 @@ impl Engine { sprite_cache: HashMap::new(), ram_upload_tex: RefCell::new(None), dummy, - vram_budget_bytes: crate::cache::DEFAULT_VRAM_BUDGET_MB.saturating_mul(1024 * 1024), - cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB), + vram_budget_bytes: default_vram_mb.saturating_mul(1024 * 1024), + cache: NodeCache::new(default_vram_mb), media: MediaCache::new(512), expr: ExprEngine::new(), frame_memo: HashMap::new(), + frame_consumers: Vec::new(), + frame_roi_memo: HashMap::new(), output_cache: OutputCache::new(), mask_target_size: None, proxy_scale: 1, @@ -283,8 +290,10 @@ impl Engine { return (tex, stats); } let mut stats = EvalStats::default(); - let mut visiting = HashSet::new(); + let mut visiting = HashSet::with_capacity(comp.nodes.len().min(64)); self.frame_memo.clear(); + self.frame_consumers.clear(); + self.frame_roi_memo.clear(); let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("comp-eval"), }); @@ -296,6 +305,8 @@ impl Engine { } self.queue.submit(Some(encoder.finish())); self.frame_memo.clear(); + self.frame_consumers.clear(); + self.frame_roi_memo.clear(); self.cache.flush_pending_pool(); self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; @@ -327,8 +338,10 @@ impl Engine { stats.unsupported_nodes = unsupported; (cached, false) } else { - let mut visiting = HashSet::new(); + let mut visiting = HashSet::with_capacity(comp.nodes.len().min(64)); self.frame_memo.clear(); + self.frame_consumers.clear(); + self.frame_roi_memo.clear(); let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); (t, true) }; @@ -365,6 +378,8 @@ impl Engine { self.queue.submit(Some(encoder.finish())); self.frame_memo.clear(); + self.frame_consumers.clear(); + self.frame_roi_memo.clear(); self.cache.flush_pending_pool(); if need_output_insert { self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone()); @@ -406,10 +421,41 @@ impl Engine { } let res = self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats); visiting.remove(&(id, time_key)); + if res.content_hash != 0 + && matches!( + comp.node(id).kind.as_str(), + "Loader" | "TextPlus" | "Renderer3D" | "pRender" | "PolylineMask" | "WandMask" + ) + { + self.cache.mark_entry_sticky(res.content_hash); + } self.frame_memo.insert((id, time_key, memo_sz), res.clone()); res } + fn switch_input_port(idx: usize) -> Option<&'static str> { + match idx { + 0 => Some("Input0"), + 1 => Some("Input1"), + 2 => Some("Input2"), + 3 => Some("Input3"), + 4 => Some("Input4"), + 5 => Some("Input5"), + 6 => Some("Input6"), + 7 => Some("Input7"), + 8 => Some("Input8"), + 9 => Some("Input9"), + 10 => Some("Input10"), + 11 => Some("Input11"), + 12 => Some("Input12"), + 13 => Some("Input13"), + 14 => Some("Input14"), + 15 => Some("Input15"), + 16 => Some("Input16"), + _ => None, + } + } + fn eval_node_inner( &mut self, comp: &Comp, @@ -474,17 +520,25 @@ impl Engine { .eval_number(node, "Source", time, 0.0, &self.expr) .round() .max(0.0) as usize; - let port = format!("Input{source}"); - node.connected_node(&port) - .or_else(|| node.connected_node("Input0")) + if let Some(port) = Self::switch_input_port(source) { + node.connected_node(port) + } else { + let port = format!("Input{source}"); + node.connected_node(&port) + } + .or_else(|| node.connected_node("Input0")) } else { let which = comp .eval_number(node, "Which", time, 1.0, &self.expr) .round() .max(1.0) as usize; - let port = format!("Input{which}"); - node.connected_node(&port) - .or_else(|| node.connected_node("Input1")) + if let Some(port) = Self::switch_input_port(which) { + node.connected_node(port) + } else { + let port = format!("Input{which}"); + node.connected_node(&port) + } + .or_else(|| node.connected_node("Input1")) }; if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) { return self.eval_node(comp, src_id, time, enc, visiting, stats); diff --git a/crates/engine/src/eval/output_cache.rs b/crates/engine/src/eval/output_cache.rs index 433cf5730da4f5e043c2ac955bd320d9acc4a0bc..d6e2bd39d928177edf125f0c6654355816603d3d 100644 --- a/crates/engine/src/eval/output_cache.rs +++ b/crates/engine/src/eval/output_cache.rs @@ -59,7 +59,11 @@ impl OutputCache { /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`), /// counting a texture once however many entries point at it. pub(super) fn total_bytes(&self) -> u64 { - self.textures().values().map(|&(bytes, _, _)| bytes).sum() + match self.entries.len() { + 0 => 0, + 1 => self.entries[0].1.bytes, + _ => self.textures().values().map(|&(bytes, _, _)| bytes).sum(), + } } /// GPU bytes held *exclusively* by `output_cache`: every strong reference to the texture is an entry here. @@ -67,11 +71,23 @@ impl OutputCache { /// Textures still resident in `NodeCache` or cloned out to a caller have `strong_count` above the entry /// count and are already accounted for elsewhere, so skipping them avoids double-counting the VRAM budget. pub(super) fn unshared_bytes(&self) -> u64 { - self.textures() - .values() - .filter(|&&(_, entries, strong)| entries == strong) - .map(|&(bytes, _, _)| bytes) - .sum() + match self.entries.len() { + 0 => 0, + 1 => { + let tex = &self.entries[0].1; + if Arc::strong_count(&tex.texture) == 1 { + tex.bytes + } else { + 0 + } + } + _ => self + .textures() + .values() + .filter(|&&(_, entries, strong)| entries == strong) + .map(|&(bytes, _, _)| bytes) + .sum(), + } } pub(super) fn get(&mut self, key: u64, mode: CacheMode) -> Option<(CachedTexture, Vec)> {