authoravatarclover caruso<git@paperclover.net>2026-12-01 13:19:15-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 13:31:51-08:00
loge5f36c175bc0257886e466e69dca1e6be2849baa
tree3fb91ceadc172588f2059535b9e55ae78684c26e
parentb72d3326c594153d96b2fa4add70819663b71002
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

engine: downstream RoI DoD bounding and smart VRAM tiering


4 files changed, 1207 insertions(+), 48 deletions(-)

crates/engine/src/cache.rs+264-30
...@@ -4,7 +4,7 @@...@@ -4,7 +4,7 @@
44
5use crate::profile::{FrameProfile, ProfileRecorder};5use crate::profile::{FrameProfile, ProfileRecorder};
6use model::{BitDepth, Comp, NodeId};6use model::{BitDepth, Comp, NodeId};
7use std::collections::{HashMap, HashSet, VecDeque};7use std::collections::{HashMap, VecDeque};
8use std::sync::{Arc, Mutex};8use std::sync::{Arc, Mutex};
99
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
...@@ -337,13 +337,115 @@ impl TexturePool {...@@ -337,13 +337,115 @@ impl TexturePool {
337struct Entry {337struct Entry {
338 tex: CachedTexture,338 tex: CachedTexture,
339 last_used: u64,339 last_used: u64,
340 producers: HashSet<NodeId>,340 sticky: bool,
341 frames: HashSet<i64>,341 first_producer: NodeId,
342 extra_producers: Vec<NodeId>,
343 first_frame: i64,
344 extra_frames: Vec<i64>,
345}
346
347impl Entry {
348 fn has_producer(&self, node: NodeId) -> bool {
349 self.first_producer == node || self.extra_producers.contains(&node)
350 }
351
352 fn record_producer(&mut self, node: NodeId) {
353 if !self.has_producer(node) {
354 self.extra_producers.push(node);
355 }
356 }
357
358 fn has_frame(&self, frame: i64) -> bool {
359 self.first_frame == frame || self.extra_frames.contains(&frame)
360 }
361
362 fn record_frame(&mut self, frame: i64) {
363 if !self.has_frame(frame) {
364 self.extra_frames.push(frame);
365 }
366 }
367
368 fn is_multi_frame(&self) -> bool {
369 !self.extra_frames.is_empty()
370 }
371
372 /// Eviction priority `(tier, last_used)` where smaller values are evicted first:
373 /// - Tier 0: single-frame transient intermediates (`!sticky && !multi_frame`)
374 /// - Tier 1: single-frame sticky generators OR multi-frame non-sticky intermediates
375 /// - Tier 2: live multi-frame sticky generators (e.g. static `Loader`, `TextPlus`)
376 fn eviction_priority(&self) -> (u8, u64) {
377 let tier = match (self.sticky, self.is_multi_frame()) {
378 (false, false) => 0,
379 (true, false) | (false, true) => 1,
380 (true, true) => 2,
381 };
382 (tier, self.last_used)
383 }
342}384}
343385
344/// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB).386/// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB).
345pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768;387pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768;
346388
389#[cfg(not(target_arch = "wasm32"))]
390fn system_ram_mb() -> Option<u64> {
391 use std::sync::OnceLock;
392 static RAM_MB: OnceLock<Option<u64>> = OnceLock::new();
393 *RAM_MB.get_or_init(|| {
394 #[cfg(target_os = "macos")]
395 {
396 let out = std::process::Command::new("sysctl")
397 .args(["-n", "hw.memsize"])
398 .output()
399 .ok()?;
400 if !out.status.success() {
401 return None;
402 }
403 let bytes: u64 = std::str::from_utf8(&out.stdout).ok()?.trim().parse().ok()?;
404 Some(bytes / (1024 * 1024))
405 }
406 #[cfg(target_os = "linux")]
407 {
408 let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
409 for line in meminfo.lines() {
410 if let Some(rest) = line.strip_prefix("MemTotal:") {
411 let kb: u64 = rest.split_whitespace().next()?.parse().ok()?;
412 return Some(kb / 1024);
413 }
414 }
415 None
416 }
417 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
418 {
419 None
420 }
421 })
422}
423
424/// Computes `default_vram_budget_mb` from total system RAM (`min(ram_mb / 8, 8192).max(768)`).
425#[cfg(any(not(target_arch = "wasm32"), test))]
426pub(crate) fn vram_budget_mb_for_ram(ram_mb: Option<u64>) -> u64 {
427 match ram_mb {
428 Some(mb) if mb > 0 => (mb / 8).min(8192).max(DEFAULT_VRAM_BUDGET_MB),
429 _ => DEFAULT_VRAM_BUDGET_MB,
430 }
431}
432
433/// System-aware default GPU texture cache VRAM budget in MiB.
434///
435/// Scales up to `8192 MiB` on high-RAM unified-memory machines (`min(ram_mb / 8, 8192).max(768)`)
436/// so static 4K `Loader` textures are not evicted during playback, while keeping `wasm32`
437/// and low-RAM systems at `DEFAULT_VRAM_BUDGET_MB` (768 MiB).
438pub fn default_vram_budget_mb() -> u64 {
439 #[cfg(target_arch = "wasm32")]
440 {
441 DEFAULT_VRAM_BUDGET_MB
442 }
443 #[cfg(not(target_arch = "wasm32"))]
444 {
445 vram_budget_mb_for_ram(system_ram_mb())
446 }
447}
448
347/// Alias for `NodeCache` (GPU texture cache + VRAM-budgeted `TexturePool`).449/// Alias for `NodeCache` (GPU texture cache + VRAM-budgeted `TexturePool`).
348pub type GpuCache = NodeCache;450pub type GpuCache = NodeCache;
349451
...@@ -361,7 +463,10 @@ pub struct NodeCache {...@@ -361,7 +463,10 @@ pub struct NodeCache {
361 pool: Mutex<TexturePool>,463 pool: Mutex<TexturePool>,
362 /// Evicted textures deferred until after `queue.submit` so `queue.write_texture`464 /// Evicted textures deferred until after `queue.submit` so `queue.write_texture`
363 /// never aliases a texture still referenced by in-flight commands in the current encoder.465 /// never aliases a texture still referenced by in-flight commands in the current encoder.
364 pending_pool: Vec<CachedTexture>,466 pending_pool: VecDeque<CachedTexture>,
467 /// Unkeyed scratch textures (`content_hash == 0`) deferred until after `queue.submit`
468 /// and recycled into `TexturePool` if no longer referenced on the CPU.
469 pending_scratch: Mutex<Vec<CachedTexture>>,
365 profiler: Option<ProfileRecorder>,470 profiler: Option<ProfileRecorder>,
366}471}
367472
...@@ -377,7 +482,8 @@ impl NodeCache {...@@ -377,7 +482,8 @@ impl NodeCache {
377 gpu_salt: 0,482 gpu_salt: 0,
378 node_salts: HashMap::new(),483 node_salts: HashMap::new(),
379 pool: Mutex::new(TexturePool::new()),484 pool: Mutex::new(TexturePool::new()),
380 pending_pool: Vec::new(),485 pending_pool: VecDeque::new(),
486 pending_scratch: Mutex::new(Vec::new()),
381 profiler: None,487 profiler: None,
382 }488 }
383 }489 }
...@@ -547,9 +653,22 @@ impl NodeCache {...@@ -547,9 +653,22 @@ impl NodeCache {
547 };653 };
548 tex.depth = depth;654 tex.depth = depth;
549 tex.content_hash = content_hash;655 tex.content_hash = content_hash;
656 if content_hash == 0 {
657 if let Ok(mut scratch) = self.pending_scratch.lock() {
658 scratch.push(tex.clone());
659 }
660 }
550 tex661 tex
551 }662 }
552663
664 /// Marks a cached entry as belonging to a sticky/high-cost generator (e.g. `Loader`, `TextPlus`)
665 /// so tight-VRAM eviction sheds single-frame transient intermediates first.
666 pub fn mark_entry_sticky(&mut self, key: u64) {
667 if let Some(entry) = self.entries.get_mut(&key) {
668 entry.sticky = true;
669 }
670 }
671
553 /// Starts per-node profiling for the upcoming frame evaluation.672 /// Starts per-node profiling for the upcoming frame evaluation.
554 pub fn begin_frame_profile(&mut self) {673 pub fn begin_frame_profile(&mut self) {
555 let stats = self.pool_stats();674 let stats = self.pool_stats();
...@@ -576,8 +695,8 @@ impl NodeCache {...@@ -576,8 +695,8 @@ impl NodeCache {
576 self.tick += 1;695 self.tick += 1;
577 let e = self.entries.get_mut(&key)?;696 let e = self.entries.get_mut(&key)?;
578 e.last_used = self.tick;697 e.last_used = self.tick;
579 e.producers.insert(node);698 e.record_producer(node);
580 e.frames.insert(frame);699 e.record_frame(frame);
581 let tex = e.tex.clone();700 let tex = e.tex.clone();
582 if let Some(prof) = &mut self.profiler {701 if let Some(prof) = &mut self.profiler {
583 prof.record(node, true, tex.size, tex.bytes);702 prof.record(node, true, tex.size, tex.bytes);
...@@ -593,24 +712,25 @@ impl NodeCache {...@@ -593,24 +712,25 @@ impl NodeCache {
593 return;712 return;
594 }713 }
595 self.tick += 1;714 self.tick += 1;
715 let mut was_sticky = false;
596 if let Some(old) = self.entries.remove(&key) {716 if let Some(old) = self.entries.remove(&key) {
717 was_sticky = old.sticky;
597 self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes);718 self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes);
598 if !Arc::ptr_eq(&old.tex.texture, &tex.texture) {719 if !Arc::ptr_eq(&old.tex.texture, &tex.texture) {
599 self.defer_to_pool(old.tex);720 self.defer_to_pool(old.tex);
600 }721 }
601 }722 }
602 self.total_bytes = self.total_bytes.saturating_add(tex.bytes);723 self.total_bytes = self.total_bytes.saturating_add(tex.bytes);
603 let mut producers = HashSet::new();
604 producers.insert(node);
605 let mut frames = HashSet::new();
606 frames.insert(frame);
607 self.entries.insert(724 self.entries.insert(
608 key,725 key,
609 Entry {726 Entry {
610 tex,727 tex,
611 last_used: self.tick,728 last_used: self.tick,
612 producers,729 sticky: was_sticky,
613 frames,730 first_producer: node,
731 extra_producers: Vec::new(),
732 first_frame: frame,
733 extra_frames: Vec::new(),
614 },734 },
615 );735 );
616 // Trim pooled textures before evicting live cached nodes so live working sets stay hot.736 // Trim pooled textures before evicting live cached nodes so live working sets stay hot.
...@@ -630,18 +750,20 @@ impl NodeCache {...@@ -630,18 +750,20 @@ impl NodeCache {
630 .saturating_add(tex.bytes)750 .saturating_add(tex.bytes)
631 <= self.budget_bytes751 <= self.budget_bytes
632 {752 {
633 self.pending_pool.push(tex);753 self.pending_pool.push_back(tex);
634 } else {754 } else {
635 // Keep most recently evicted textures within budget; drop older pending ones.755 // Keep most recently evicted textures within budget; drop older pending ones.
636 while !self.pending_pool.is_empty()756 while let Some(dropped) = self.pending_pool.front() {
637 && self757 if self
638 .total_bytes758 .total_bytes
639 .saturating_add(pending_bytes)759 .saturating_add(pending_bytes)
640 .saturating_add(tex.bytes)760 .saturating_add(tex.bytes)
641 > self.budget_bytes761 <= self.budget_bytes
642 {762 {
643 let dropped = self.pending_pool.remove(0);763 break;
764 }
644 pending_bytes = pending_bytes.saturating_sub(dropped.bytes);765 pending_bytes = pending_bytes.saturating_sub(dropped.bytes);
766 self.pending_pool.pop_front();
645 }767 }
646 if self768 if self
647 .total_bytes769 .total_bytes
...@@ -649,22 +771,28 @@ impl NodeCache {...@@ -649,22 +771,28 @@ impl NodeCache {
649 .saturating_add(tex.bytes)771 .saturating_add(tex.bytes)
650 <= self.budget_bytes772 <= self.budget_bytes
651 {773 {
652 self.pending_pool.push(tex);774 self.pending_pool.push_back(tex);
653 }775 }
654 }776 }
655 }777 }
656778
657 /// Moves textures evicted during the current frame into `TexturePool`.779 /// Moves textures evicted or allocated as scratch during the current frame into `TexturePool`.
658 /// Must be called right after `queue.submit` so `queue.write_texture` cannot780 /// Must be called right after `queue.submit` so `queue.write_texture` cannot
659 /// overwrite a texture still used by commands in the submitted encoder.781 /// overwrite a texture still used by commands in the submitted encoder.
660 pub fn flush_pending_pool(&mut self) {782 pub fn flush_pending_pool(&mut self) {
661 if self.pending_pool.is_empty() {
662 return;
663 }
664 let drained = std::mem::take(&mut self.pending_pool);783 let drained = std::mem::take(&mut self.pending_pool);
665 for tex in drained {784 for tex in drained {
666 self.return_to_pool(&tex);785 self.return_to_pool(&tex);
667 }786 }
787 let scratch = {
788 let mut guard = self.pending_scratch.lock().expect("pending scratch lock");
789 std::mem::take(&mut *guard)
790 };
791 for tex in scratch {
792 if Arc::strong_count(&tex.texture) == 1 && Arc::strong_count(&tex.view) == 1 {
793 self.return_to_pool(&tex);
794 }
795 }
668 }796 }
669797
670 fn return_to_pool(&self, tex: &CachedTexture) {798 fn return_to_pool(&self, tex: &CachedTexture) {
...@@ -691,11 +819,14 @@ impl NodeCache {...@@ -691,11 +819,14 @@ impl NodeCache {
691819
692 fn evict_over_budget(&mut self) {820 fn evict_over_budget(&mut self) {
693 while self.total_bytes > self.budget_bytes && self.entries.len() > 1 {821 while self.total_bytes > self.budget_bytes && self.entries.len() > 1 {
694 let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used)822 let Some((&victim_key, _)) = self
823 .entries
824 .iter()
825 .min_by_key(|(_, e)| e.eviction_priority())
695 else {826 else {
696 break;827 break;
697 };828 };
698 if let Some(removed) = self.entries.remove(&oldest_key) {829 if let Some(removed) = self.entries.remove(&victim_key) {
699 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);830 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
700 self.evictions += 1;831 self.evictions += 1;
701 self.defer_to_pool(removed.tex);832 self.defer_to_pool(removed.tex);
...@@ -711,12 +842,34 @@ impl NodeCache {...@@ -711,12 +842,34 @@ impl NodeCache {
711 /// Clears all dynamic cached GPU node textures into the pool (within VRAM budget) and bumps global salt.842 /// Clears all dynamic cached GPU node textures into the pool (within VRAM budget) and bumps global salt.
712 pub fn clear_dynamic(&mut self) -> usize {843 pub fn clear_dynamic(&mut self) -> usize {
713 let count = self.entries.len();844 let count = self.entries.len();
714 let drained: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect();845 let mut drained: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect();
715 let pending = std::mem::take(&mut self.pending_pool);846 let pending = std::mem::take(&mut self.pending_pool);
847 let scratch = {
848 let mut guard = self.pending_scratch.lock().expect("pending scratch lock");
849 std::mem::take(&mut *guard)
850 };
716 self.total_bytes = 0;851 self.total_bytes = 0;
717 self.gpu_salt += 1;852 self.gpu_salt += 1;
718 if (!drained.is_empty() || !pending.is_empty()) && self.budget_bytes > 0 {853 // Drop or recycle unreferenced scratch textures before pushing drained entries so
854 // `Arc::strong_count` reflects true external ownership.
855 let mut recycle_scratch = Vec::new();
856 for tex in scratch {
857 if Arc::strong_count(&tex.texture) == 1 && Arc::strong_count(&tex.view) == 1 {
858 recycle_scratch.push(tex);
859 }
860 }
861 if (!drained.is_empty() || !pending.is_empty() || !recycle_scratch.is_empty())
862 && self.budget_bytes > 0
863 {
864 // Push lower-priority / older entries first so sticky/multi-frame entries
865 // get higher `last_returned` ticks and survive longest under pool pressure.
866 drained.sort_by_key(|e| e.eviction_priority());
719 let mut pool = self.pool.lock().expect("texture pool lock");867 let mut pool = self.pool.lock().expect("texture pool lock");
868 for tex in recycle_scratch {
869 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {
870 pool.push(&tex);
871 }
872 }
720 for tex in pending {873 for tex in pending {
721 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {874 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {
722 pool.push(&tex);875 pool.push(&tex);
...@@ -741,7 +894,7 @@ impl NodeCache {...@@ -741,7 +894,7 @@ impl NodeCache {
741 let keys: Vec<u64> = self894 let keys: Vec<u64> = self
742 .entries895 .entries
743 .iter()896 .iter()
744 .filter(|(_, e)| e.frames.contains(&frame))897 .filter(|(_, e)| e.has_frame(frame))
745 .map(|(k, _)| *k)898 .map(|(k, _)| *k)
746 .collect();899 .collect();
747 let count = keys.len();900 let count = keys.len();
...@@ -761,7 +914,7 @@ impl NodeCache {...@@ -761,7 +914,7 @@ impl NodeCache {
761 let keys: Vec<u64> = self914 let keys: Vec<u64> = self
762 .entries915 .entries
763 .iter()916 .iter()
764 .filter(|(_, e)| e.producers.contains(&node))917 .filter(|(_, e)| e.has_producer(node))
765 .map(|(k, _)| *k)918 .map(|(k, _)| *k)
766 .collect();919 .collect();
767 let count = keys.len();920 let count = keys.len();
...@@ -1001,4 +1154,85 @@ mod tests {...@@ -1001,4 +1154,85 @@ mod tests {
1001 cache2.flush_pending_pool();1154 cache2.flush_pending_pool();
1002 assert_eq!(cache2.pooled_bytes(), 1024 * 1024);1155 assert_eq!(cache2.pooled_bytes(), 1024 * 1024);
1003 }1156 }
1157
1158 #[test]
1159 fn default_vram_budget_scales_sensibly_and_respects_floor() {
1160 assert_eq!(vram_budget_mb_for_ram(None), 768);
1161 assert_eq!(vram_budget_mb_for_ram(Some(0)), 768);
1162 assert_eq!(vram_budget_mb_for_ram(Some(4 * 1024)), 768);
1163 assert_eq!(vram_budget_mb_for_ram(Some(16 * 1024)), 2048);
1164 assert_eq!(vram_budget_mb_for_ram(Some(64 * 1024)), 8192);
1165 assert_eq!(vram_budget_mb_for_ram(Some(256 * 1024)), 8192);
1166 assert!(default_vram_budget_mb() >= DEFAULT_VRAM_BUDGET_MB);
1167 }
1168
1169 #[test]
1170 fn eviction_protects_sticky_and_multi_frame_entries_over_single_frame_intermediates() {
1171 let eng = Engine::new_headless().expect("gpu");
1172 let device = eng.device();
1173 let usage = NodeCache::default_texture_usage();
1174 // 3 MiB budget; each 512x512 RGBA8 texture is 1 MiB.
1175 let mut cache = NodeCache::new(3);
1176
1177 // Insert a sticky Loader texture (key 100) and hit it on frame 1 so it becomes Tier 2.
1178 let loader = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1179 cache.insert(100, loader, NodeId(0), 0);
1180 cache.mark_entry_sticky(100);
1181 assert!(cache.get(100, NodeId(0), 1).is_some());
1182
1183 // Insert a non-sticky multi-frame texture (key 200, Tier 1).
1184 let static_op = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1185 cache.insert(200, static_op, NodeId(1), 0);
1186 assert!(cache.get(200, NodeId(1), 1).is_some());
1187
1188 // Flood with newer single-frame transient intermediates (Tier 0, keys 301..=304).
1189 // Even though keys 301..=304 have newer `last_used` ticks than keys 100 and 200,
1190 // Tier 0 transient intermediates must be evicted first so the Loader (key 100) survives!
1191 for k in 301..=304u64 {
1192 let tmp = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1193 cache.insert(k, tmp, NodeId(2), 2);
1194 }
1195
1196 assert!(cache.total_vram_bytes() <= 3 * 1024 * 1024);
1197 assert!(cache.get(100, NodeId(0), 2).is_some(), "sticky multi-frame Loader must survive eviction");
1198 assert!(cache.get(200, NodeId(1), 2).is_some(), "multi-frame entry must survive ahead of Tier 0 intermediates");
1199 assert!(cache.get(301, NodeId(2), 2).is_none(), "single-frame transient intermediate must be evicted first");
1200 }
1201
1202 #[test]
1203 fn scratch_textures_recycle_into_pool_after_flush() {
1204 let eng = Engine::new_headless().expect("gpu");
1205 let device = eng.device();
1206 let mut cache = NodeCache::new(16);
1207
1208 let ptr = {
1209 let scratch = cache.acquire_texture_dod_fmt(
1210 device,
1211 [512, 512],
1212 [0, 0],
1213 [512, 512],
1214 BitDepth::Int8,
1215 wgpu::TextureFormat::Rgba8Unorm,
1216 0,
1217 );
1218 Arc::as_ptr(&scratch.texture)
1219 };
1220 // Still deferred until flush_pending_pool() so mid-frame passes cannot alias.
1221 assert_eq!(cache.pooled_bytes(), 0);
1222
1223 cache.flush_pending_pool();
1224 assert_eq!(cache.pooled_bytes(), 1024 * 1024);
1225
1226 let reused = cache.acquire_texture_dod_fmt(
1227 device,
1228 [512, 512],
1229 [0, 0],
1230 [512, 512],
1231 BitDepth::Int8,
1232 wgpu::TextureFormat::Rgba8Unorm,
1233 0,
1234 );
1235 assert_eq!(Arc::as_ptr(&reused.texture), ptr);
1236 assert_eq!(cache.pool_stats().hits, 1);
1237 }
1004}1238}
crates/engine/src/eval/composite.rs+857-2
...@@ -1,5 +1,37 @@...@@ -1,5 +1,37 @@
1use super::*;1use super::*;
22
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub(super) enum RoiBox {
5 Empty,
6 Rect { x0: i32, y0: i32, x1: i32, y1: i32 },
7}
8
9impl RoiBox {
10 fn union(self, other: Self) -> Self {
11 match (self, other) {
12 (Self::Empty, r) | (r, Self::Empty) => r,
13 (
14 Self::Rect { x0: ax0, y0: ay0, x1: ax1, y1: ay1 },
15 Self::Rect { x0: bx0, y0: by0, x1: bx1, y1: by1 },
16 ) => Self::Rect {
17 x0: ax0.min(bx0),
18 y0: ay0.min(by0),
19 x1: ax1.max(bx1),
20 y1: ay1.max(by1),
21 },
22 }
23 }
24
25 fn canvas(canvas_size: [u32; 2]) -> Self {
26 Self::Rect {
27 x0: 0,
28 y0: 0,
29 x1: canvas_size[0].max(1) as i32,
30 y1: canvas_size[1].max(1) as i32,
31 }
32 }
33}
34
3/// Expands `[bg0, bg1)` to include `[fg0, fg1)` with a 2px AA apron while35/// Expands `[bg0, bg1)` to include `[fg0, fg1)` with a 2px AA apron while
4/// clamping total span to `max_dim` without an artificial symmetric half-cap.36/// clamping total span to `max_dim` without an artificial symmetric half-cap.
5fn expand_dod_axis(bg0: i32, bg1: i32, fg0: f32, fg1: f32, max_dim: i32) -> (i32, i32) {37fn 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...@@ -22,7 +54,692 @@ fn expand_dod_axis(bg0: i32, bg1: i32, fg0: f32, fg1: f32, max_dim: i32) -> (i32
22 (bg0 - take0, bg1 + take1)54 (bg0 - take0, bg1 + take1)
23}55}
2456
57fn infer_node_canvas_size(
58 comp: &Comp,
59 start_id: NodeId,
60 time: f64,
61 expr: &ExprEngine,
62 comp_dims: [u32; 2],
63 depth: usize,
64) -> Option<[u32; 2]> {
65 let mut cur_id = start_id;
66 for _ in 0..depth {
67 let n = comp.node(cur_id);
68 if n.bypassed
69 || matches!(
70 n.kind.as_str(),
71 "PipeRouter"
72 | "Fuse.Wireless"
73 | "Tracker"
74 | "Dimension.OpticalFlow"
75 | "OpticalFlow"
76 | "Dimension.CopyAux"
77 | "ColorCorrector"
78 | "ColorCurves"
79 | "BrightnessContrast"
80 | "ColorGain"
81 | "InvertColor"
82 | "GamutConvert"
83 | "HueCurves"
84 | "ChangeDepth"
85 | "LumaKeyer"
86 | "UltraKeyer"
87 | "DeltaKeyer"
88 | "Blur"
89 | "DirectionalBlur"
90 | "Glow"
91 | "SoftGlow"
92 | "Fuse.XGlow"
93 | "Filter"
94 | "Sharpen"
95 | "ErodeDilate"
96 | "Transform"
97 )
98 {
99 let port = default_main_input_port(&n.kind);
100 cur_id = n.connected_node(port).and_then(|s| comp.find_node(s))?;
101 continue;
102 }
103 match n.kind.as_str() {
104 "Merge" | "ChannelBoolean" | "Dissolve" => {
105 cur_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?;
106 }
107 "Fuse.Colorize" => {
108 cur_id = n
109 .connected_node("Image")
110 .or_else(|| n.connected_node("Input"))
111 .and_then(|s| comp.find_node(s))?;
112 }
113 "Background" | "FastNoise" | "Plasma" | "DaySky" => {
114 if Engine::resolve_effect_mask_id(comp, n).is_some()
115 || comp.eval_number(n, "UseFrameFormatSettings", time, 0.0, expr) > 0.5
116 {
117 return None;
118 }
119 let w = comp.eval_number(n, "Width", time, comp_dims[0] as f64, expr).max(1.0) as u32;
120 let h = comp.eval_number(n, "Height", time, comp_dims[1] as f64, expr).max(1.0) as u32;
121 // Only unambiguous when explicit dimensions aren't additionally proxy-scaled differently.
122 if !n.inputs.contains_key("Width") && !n.inputs.contains_key("Height") {
123 return Some(comp_dims);
124 }
125 return Some([w, h]);
126 }
127 _ => return None,
128 }
129 }
130 None
131}
132
133fn inverse_transform_box(
134 comp: &Comp,
135 node: &Node,
136 time: f64,
137 expr: &ExprEngine,
138 canvas_size: [u32; 2],
139 has_mask: bool,
140 blend: f32,
141 downstream: RoiBox,
142) -> Option<RoiBox> {
143 let RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 } = downstream else {
144 return Some(RoiBox::Empty);
145 };
146 let (dx0, dy0, dx1, dy1) = if has_mask {
147 (
148 dx0.max(0),
149 dy0.max(0),
150 dx1.min(canvas_size[0].max(1) as i32),
151 dy1.min(canvas_size[1].max(1) as i32),
152 )
153 } else {
154 (dx0, dy0, dx1, dy1)
155 };
156 if dx0 >= dx1 || dy0 >= dy1 {
157 return Some(RoiBox::Empty);
158 }
159
160 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], expr);
161 let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], expr);
162 let use_xy = comp.eval_number(node, "UseSizeAndAspect", time, 1.0, expr) < 0.5;
163 let (sx, sy) = if use_xy {
164 (
165 comp.eval_number(node, "XSize", time, 1.0, expr) as f32,
166 comp.eval_number(node, "YSize", time, 1.0, expr) as f32,
167 )
168 } else {
169 let s = comp.eval_number(node, "Size", time, 1.0, expr) as f32;
170 let asp = comp.eval_number(node, "Aspect", time, 1.0, expr) as f32;
171 (s, s * asp)
172 };
173 let angle = (comp.eval_number(node, "Angle", time, 0.0, expr) as f32).to_radians();
174 let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, expr) > 0.5;
175 let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, expr) > 0.5;
176
177 if !sx.is_finite()
178 || !sy.is_finite()
179 || !angle.is_finite()
180 || !center[0].is_finite()
181 || !center[1].is_finite()
182 || !pivot[0].is_finite()
183 || !pivot[1].is_finite()
184 || sx <= 1e-4
185 || sy <= 1e-4
186 {
187 return None;
188 }
189
190 let cw = canvas_size[0].max(1) as f32;
191 let ch = canvas_size[1].max(1) as f32;
192 let cx = center[0] as f32;
193 let cy = center[1] as f32;
194 let px = pivot[0] as f32;
195 let py = pivot[1] as f32;
196 let is_identity = (cx - 0.5).abs() < 1e-5
197 && (cy - 0.5).abs() < 1e-5
198 && (sx - 1.0).abs() < 1e-5
199 && (sy - 1.0).abs() < 1e-5
200 && angle.abs() < 1e-5
201 && !flip_h
202 && !flip_v;
203 if is_identity {
204 return Some(RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 });
205 }
206
207 let shift_x = cx - 0.5;
208 let shift_y = cy - 0.5;
209 let (s, c) = angle.sin_cos();
210
211 let mut min_x = f32::INFINITY;
212 let mut max_x = f32::NEG_INFINITY;
213 let mut min_y = f32::INFINITY;
214 let mut max_y = f32::NEG_INFINITY;
215 if blend < 1.0 - 1e-5 || has_mask {
216 min_x = dx0 as f32;
217 max_x = dx1 as f32;
218 min_y = dy0 as f32;
219 max_y = dy1 as f32;
220 }
221 for &(x, y) in &[
222 (dx0 as f32, dy0 as f32),
223 (dx1 as f32, dy0 as f32),
224 (dx0 as f32, dy1 as f32),
225 (dx1 as f32, dy1 as f32),
226 ] {
227 let fu_x = x / cw;
228 let fu_y = 1.0 - y / ch;
229 let rel_x = (fu_x - px - shift_x) * cw;
230 let rel_y = (fu_y - py - shift_y) * ch;
231 let unrot_x = rel_x * c + rel_y * s;
232 let unrot_y = -rel_x * s + rel_y * c;
233 let mut sfu_x = unrot_x / sx / cw + px;
234 let mut sfu_y = unrot_y / sy / ch + py;
235 if flip_h {
236 sfu_x = 1.0 - sfu_x;
237 }
238 if flip_v {
239 sfu_y = 1.0 - sfu_y;
240 }
241 let sx_px = sfu_x * cw;
242 let sy_px = (1.0 - sfu_y) * ch;
243 min_x = min_x.min(sx_px);
244 max_x = max_x.max(sx_px);
245 min_y = min_y.min(sy_px);
246 max_y = max_y.max(sy_px);
247 }
248 if !min_x.is_finite() || !max_x.is_finite() || !min_y.is_finite() || !max_y.is_finite() {
249 return None;
250 }
251 let pad = 6;
252 Some(RoiBox::Rect {
253 x0: (min_x.floor() as i32).saturating_sub(pad),
254 y0: (min_y.floor() as i32).saturating_sub(pad),
255 x1: (max_x.ceil() as i32).saturating_add(pad),
256 y1: (max_y.ceil() as i32).saturating_add(pad),
257 })
258}
259
260fn inverse_merge_fg_box(
261 comp: &Comp,
262 node: &Node,
263 time: f64,
264 expr: &ExprEngine,
265 bg_canvas: [u32; 2],
266 fg_canvas: [u32; 2],
267 downstream: RoiBox,
268) -> Option<RoiBox> {
269 let RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 } = downstream else {
270 return Some(RoiBox::Empty);
271 };
272 if dx0 >= dx1 || dy0 >= dy1 {
273 return Some(RoiBox::Empty);
274 }
275 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], expr);
276 let size = comp.eval_number(node, "Size", time, 1.0, expr) as f32;
277 let angle = (comp.eval_number(node, "Angle", time, 0.0, expr) as f32).to_radians();
278 let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, expr) > 0.5;
279 let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, expr) > 0.5;
280 if !size.is_finite()
281 || !angle.is_finite()
282 || !center[0].is_finite()
283 || !center[1].is_finite()
284 || size <= 1e-4
285 {
286 return None;
287 }
288
289 let bg_cw = bg_canvas[0].max(1) as f32;
290 let bg_ch = bg_canvas[1].max(1) as f32;
291 let fg_cw = fg_canvas[0].max(1) as f32;
292 let fg_ch = fg_canvas[1].max(1) as f32;
293 let cx = center[0] as f32;
294 let cy = center[1] as f32;
295 let is_identity = bg_canvas == fg_canvas
296 && (cx - 0.5).abs() < 1e-5
297 && (cy - 0.5).abs() < 1e-5
298 && (size - 1.0).abs() < 1e-5
299 && angle.abs() < 1e-5
300 && !flip_h
301 && !flip_v;
302 if is_identity {
303 return Some(RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 });
304 }
305
306 let (s, c) = angle.sin_cos();
307 let mut min_x = f32::INFINITY;
308 let mut max_x = f32::NEG_INFINITY;
309 let mut min_y = f32::INFINITY;
310 let mut max_y = f32::NEG_INFINITY;
311 for &(x, y) in &[
312 (dx0 as f32, dy0 as f32),
313 (dx1 as f32, dy0 as f32),
314 (dx0 as f32, dy1 as f32),
315 (dx1 as f32, dy1 as f32),
316 ] {
317 let fu_x = x / bg_cw;
318 let fu_y = 1.0 - y / bg_ch;
319 let delta_x = (fu_x - cx) * bg_cw;
320 let delta_y = (fu_y - cy) * bg_ch;
321 let rot_x = (delta_x * c + delta_y * s) / size;
322 let rot_y = (-delta_x * s + delta_y * c) / size;
323 let mut fg_fu_x = rot_x / fg_cw + 0.5;
324 let mut fg_fu_y = rot_y / fg_ch + 0.5;
325 if flip_h {
326 fg_fu_x = 1.0 - fg_fu_x;
327 }
328 if flip_v {
329 fg_fu_y = 1.0 - fg_fu_y;
330 }
331 let sx_px = fg_fu_x * fg_cw;
332 let sy_px = (1.0 - fg_fu_y) * fg_ch;
333 min_x = min_x.min(sx_px);
334 max_x = max_x.max(sx_px);
335 min_y = min_y.min(sy_px);
336 max_y = max_y.max(sy_px);
337 }
338 if !min_x.is_finite() || !max_x.is_finite() || !min_y.is_finite() || !max_y.is_finite() {
339 return None;
340 }
341 let pad = 6;
342 Some(RoiBox::Rect {
343 x0: (min_x.floor() as i32).saturating_sub(pad),
344 y0: (min_y.floor() as i32).saturating_sub(pad),
345 x1: (max_x.ceil() as i32).saturating_add(pad),
346 y1: (max_y.ceil() as i32).saturating_add(pad),
347 })
348}
349
350#[allow(clippy::too_many_arguments)]
351fn roi_for_node(
352 comp: &Comp,
353 node_id: NodeId,
354 canvas_size: [u32; 2],
355 comp_dims: [u32; 2],
356 time: f64,
357 time_key: i64,
358 hiq: bool,
359 expr: &ExprEngine,
360 consumers: &[Vec<(NodeId, String)>],
361 memo: &mut HashMap<(NodeId, i64), Option<RoiBox>>,
362 visiting: &mut HashSet<NodeId>,
363 depth: usize,
364) -> Option<RoiBox> {
365 if depth == 0 {
366 return None;
367 }
368 if let Some(&cached) = memo.get(&(node_id, time_key)) {
369 return cached;
370 }
371 if !visiting.insert(node_id) {
372 return None;
373 }
374
375 let node_consumers = &consumers[node_id.0];
376 let res = if node_consumers.is_empty() {
377 Some(RoiBox::canvas(canvas_size))
378 } else {
379 let mut acc = RoiBox::Empty;
380 let mut ok = true;
381 for (cid, port) in node_consumers {
382 if let Some(r) = roi_from_consumer(
383 comp,
384 *cid,
385 port,
386 canvas_size,
387 comp_dims,
388 time,
389 time_key,
390 hiq,
391 expr,
392 consumers,
393 memo,
394 visiting,
395 depth - 1,
396 ) {
397 acc = acc.union(r);
398 } else {
399 ok = false;
400 break;
401 }
402 }
403 if ok { Some(acc) } else { None }
404 };
405
406 visiting.remove(&node_id);
407 memo.insert((node_id, time_key), res);
408 res
409}
410
411#[allow(clippy::too_many_arguments)]
412fn roi_from_consumer(
413 comp: &Comp,
414 cid: NodeId,
415 port: &str,
416 canvas_size: [u32; 2],
417 comp_dims: [u32; 2],
418 time: f64,
419 time_key: i64,
420 hiq: bool,
421 expr: &ExprEngine,
422 consumers: &[Vec<(NodeId, String)>],
423 memo: &mut HashMap<(NodeId, i64), Option<RoiBox>>,
424 visiting: &mut HashSet<NodeId>,
425 depth: usize,
426) -> Option<RoiBox> {
427 if matches!(
428 port,
429 "EffectMask" | "GlowMask" | "Garbage.Matte" | "GarbageMatte" | "Solid.Matte" | "SolidMatte"
430 ) {
431 return None;
432 }
433 let n = comp.node(cid);
434 if port == "__macro_output" {
435 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
436 }
437 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
438 return None;
439 }
440 if n.bypassed
441 || matches!(
442 n.kind.as_str(),
443 "PipeRouter" | "Fuse.Wireless" | "Tracker" | "Dimension.OpticalFlow" | "OpticalFlow" | "Dimension.CopyAux"
444 )
445 {
446 if port == default_main_input_port(&n.kind) {
447 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
448 }
449 return None;
450 }
451
452 match n.kind.as_str() {
453 "Saver" | "MediaOut" => Some(RoiBox::canvas(canvas_size)),
454 "BrightnessContrast" | "ColorCorrector" | "ColorCurves" | "ColorGain" | "InvertColor"
455 | "GamutConvert" | "HueCurves" | "ChangeDepth" | "LumaKeyer" => {
456 let main_ok = port == "Input" || (n.kind == "InvertColor" && port == "Image1");
457 if !main_ok {
458 return None;
459 }
460 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
461 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
462 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
463 if blend <= 1e-6 && !mbm {
464 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
465 }
466 if has_mask {
467 return Some(RoiBox::canvas(canvas_size));
468 }
469 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
470 }
471 "Fuse.Colorize" => {
472 if port != "Image" && port != "Input" {
473 return None;
474 }
475 if Engine::resolve_effect_mask_id(comp, n).is_some() {
476 return Some(RoiBox::canvas(canvas_size));
477 }
478 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
479 }
480 "ChannelBoolean" => {
481 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
482 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
483 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
484 if blend <= 1e-6 && !mbm {
485 return match port {
486 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),
487 "Foreground" => Some(RoiBox::Empty),
488 _ => None,
489 };
490 }
491 if port == "Background" || port == "Foreground" {
492 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
493 } else {
494 None
495 }
496 }
497 "DirectionalBlur" => {
498 if port != "Input" {
499 return None;
500 }
501 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
502 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
503 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
504 if blend <= 1e-6 && !mbm {
505 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
506 }
507 if n.static_str("ClippingMode").unwrap_or("Frame") != "None" || has_mask {
508 Some(RoiBox::canvas(canvas_size))
509 } else {
510 None
511 }
512 }
513 "Dissolve" => {
514 let mix_v = comp.eval_number(n, "Mix", time, 1.0, expr).clamp(0.0, 1.0);
515 let blend = comp.eval_number(n, "Blend", time, 1.0, expr);
516 let has_mask = n.connected_node("EffectMask").is_some();
517 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
518 if (blend <= 1e-6 || mix_v <= 1e-6) && !mbm {
519 return match port {
520 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),
521 "Foreground" => Some(RoiBox::Empty),
522 _ => None,
523 };
524 }
525 if mix_v >= 1.0 - 1e-6 && blend >= 1.0 - 1e-6 && !has_mask {
526 return match port {
527 "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),
528 "Background" => Some(RoiBox::Empty),
529 _ => None,
530 };
531 }
532 if port == "Background" || port == "Foreground" {
533 Some(RoiBox::canvas(canvas_size))
534 } else {
535 None
536 }
537 }
538 "Scale" | "BetterResize" => {
539 if port != "Input" {
540 return None;
541 }
542 let hiq_only = comp.eval_number(n, "HiQOnly", time, 0.0, expr) > 0.5;
543 if n.kind == "Scale" && !hiq && hiq_only {
544 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
545 } else {
546 Some(RoiBox::canvas(canvas_size))
547 }
548 }
549 "Shadow" | "Glow" | "SoftGlow" | "Fuse.XGlow" | "DeltaKeyer" => {
550 if port != "Input" {
551 return None;
552 }
553 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
554 let mbm = n.kind != "Fuse.XGlow"
555 && n.connected_node("EffectMask").is_some()
556 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
557 if blend <= 1e-6 && !mbm {
558 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
559 } else {
560 Some(RoiBox::canvas(canvas_size))
561 }
562 }
563 "Displace" => {
564 if port != "Input" && port != "Foreground" {
565 return None;
566 }
567 let fg_none = n.connected_node("Foreground").and_then(|s| comp.find_node(s)).is_none();
568 let mbm = n.connected_node("EffectMask").is_some()
569 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
570 if fg_none && !mbm {
571 roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)
572 } else {
573 Some(RoiBox::canvas(canvas_size))
574 }
575 }
576 "CameraShake" | "DVE" | "Vortex" | "Drip" | "Dent" | "GridWarp" | "VariBlur"
577 | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Fuse.XfChroma"
578 | "Paint" => {
579 if port != default_main_input_port(&n.kind) && port != "Input" && port != "Image" {
580 return None;
581 }
582 // Conservatively union canvas crop with downstream RoI in case the node short-circuits
583 // on an idle parameter (e.g. Blend = 0, radius = 0, etc.).
584 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
585 Some(RoiBox::canvas(canvas_size).union(down))
586 }
587 "Blur" => {
588 if port != "Input" {
589 return None;
590 }
591 let lock_xy = comp.eval_number(n, "LockXY", time, 1.0, expr) > 0.5;
592 let filter_name = n.static_str("Filter").unwrap_or("Fast Gaussian");
593 let gauss_k = match filter_name {
594 "Box" => 1.0_f32,
595 "Gaussian" => 1.07_f32,
596 _ => 0.96_f32,
597 };
598 let scale_ref = canvas_size[0].max(1) as f32 / 720.0;
599 let x_raw = comp.eval_number(n, "XBlurSize", time, 1.0, expr) as f32;
600 let y_raw = if lock_xy {
601 x_raw
602 } else {
603 comp.eval_number(n, "YBlurSize", time, 1.0, expr) as f32
604 };
605 let rx = x_raw * scale_ref * gauss_k;
606 let ry = y_raw * scale_ref * gauss_k;
607 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
608 if rx.max(ry) < 0.25 || blend <= 1e-6 {
609 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
610 }
611 if Engine::resolve_effect_mask_id(comp, n).is_some() {
612 return Some(RoiBox::canvas(canvas_size));
613 }
614 if !rx.is_finite() || !ry.is_finite() || rx.abs() * 1.6 > 2048.0 || ry.abs() * 1.6 > 2048.0 {
615 return None;
616 }
617 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
618 let RoiBox::Rect { x0, y0, x1, y1 } = down else {
619 return Some(RoiBox::Empty);
620 };
621 let pad_x = (rx.abs() * 1.6).ceil() as i32 + 16;
622 let pad_y = (ry.abs() * 1.6).ceil() as i32 + 16;
623 Some(RoiBox::Rect {
624 x0: x0 - pad_x,
625 y0: y0 - pad_y,
626 x1: x1 + pad_x,
627 y1: y1 + pad_y,
628 })
629 }
630 "Transform" => {
631 if port != "Input" {
632 return None;
633 }
634 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
635 if blend <= 1e-6 {
636 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
637 }
638 if comp.eval_number(n, "InvertTransform", time, 0.0, expr) > 0.5 {
639 return None;
640 }
641 let edges = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32;
642 if edges != 0 {
643 return None;
644 }
645 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
646 let down = roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
647 inverse_transform_box(comp, n, time, expr, canvas_size, has_mask, blend, down)
648 }
649 "Merge" => {
650 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
651 let mbm = n.connected_node("EffectMask").is_some()
652 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
653 if blend <= 1e-6 && !mbm {
654 return match port {
655 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth),
656 "Foreground" => Some(RoiBox::Empty),
657 _ => None,
658 };
659 }
660 if port == "Background" {
661 return roi_for_node(comp, cid, canvas_size, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth);
662 }
663 if port == "Foreground" {
664 let edges = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32;
665 if edges != 0 {
666 return None;
667 }
668 let bg_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?;
669 let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, 16)?;
670 let down = roi_for_node(comp, cid, bg_canvas, comp_dims, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
671 return inverse_merge_fg_box(comp, n, time, expr, bg_canvas, canvas_size, down);
672 }
673 None
674 }
675 _ => None,
676 }
677}
678
25impl Engine {679impl Engine {
680 fn ensure_frame_consumers(&mut self, comp: &Comp) {
681 if self.frame_consumers.len() == comp.nodes.len() {
682 return;
683 }
684 self.frame_consumers.clear();
685 self.frame_consumers.resize_with(comp.nodes.len(), Vec::new);
686 for n in &comp.nodes {
687 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
688 if let Some(out_id) = n.macro_output {
689 if out_id.0 < self.frame_consumers.len() {
690 self.frame_consumers[out_id.0].push((n.id, "__macro_output".to_owned()));
691 }
692 continue;
693 }
694 }
695 for (port, binding) in &n.inputs {
696 if let Some(src_id) = binding.source_op.as_deref().and_then(|s| comp.find_node(s)) {
697 if src_id.0 < self.frame_consumers.len() {
698 self.frame_consumers[src_id.0].push((n.id, port.clone()));
699 }
700 }
701 }
702 if n.connected_node("EffectMask").is_none() {
703 if let Some(mid) = Self::resolve_effect_mask_id(comp, n) {
704 if mid.0 < self.frame_consumers.len() {
705 self.frame_consumers[mid.0].push((n.id, "EffectMask".to_owned()));
706 }
707 }
708 }
709 }
710 }
711
712 fn merge_downstream_roi_bounds(
713 &mut self,
714 comp: &Comp,
715 merge_id: NodeId,
716 canvas_size: [u32; 2],
717 time: f64,
718 ) -> Option<(i32, i32, i32, i32)> {
719 self.ensure_frame_consumers(comp);
720 let comp_dims = self.scaled_dims(comp.width, comp.height);
721 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
722 let mut visiting = HashSet::new();
723 let res = roi_for_node(
724 comp,
725 merge_id,
726 canvas_size,
727 comp_dims,
728 time,
729 time_key,
730 self.hiq,
731 &self.expr,
732 &self.frame_consumers,
733 &mut self.frame_roi_memo,
734 &mut visiting,
735 32,
736 )?;
737 match res {
738 RoiBox::Rect { x0, y0, x1, y1 } => Some((x0, y0, x1, y1)),
739 RoiBox::Empty => Some((0, 0, canvas_size[0].max(1) as i32, canvas_size[1].max(1) as i32)),
740 }
741 }
742
26 fn flattened_fg_edge_mode(743 fn flattened_fg_edge_mode(
27 comp: &Comp,744 comp: &Comp,
28 fg_id: NodeId,745 fg_id: NodeId,
...@@ -147,6 +864,12 @@ impl Engine {...@@ -147,6 +864,12 @@ impl Engine {
147 let mut dst_origin = bg.origin;864 let mut dst_origin = bg.origin;
148 let mut dst_size = bg.size;865 let mut dst_size = bg.size;
149866
867 let roi_bounds = if bg.tex_scale >= 0.99 && fg.tex_scale >= 0.99 {
868 self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time)
869 } else {
870 None
871 };
872
150 if edges < 0.5873 if edges < 0.5
151 && mask.is_none()874 && mask.is_none()
152 && mode_id == 0.0875 && mode_id == 0.0
...@@ -183,14 +906,41 @@ impl Engine {...@@ -183,14 +906,41 @@ impl Engine {
183 fg_y1 = fg_y1.max(py);906 fg_y1 = fg_y1.max(py);
184 }907 }
185 let max_dim = self.device.limits().max_texture_dimension_2d.min(8192) as i32;908 let max_dim = self.device.limits().max_texture_dimension_2d.min(8192) as i32;
186 let (ux0, ux1) = expand_dod_axis(bg_x0, bg_x1, fg_x0, fg_x1, max_dim);909 let (mut ux0, mut ux1) = expand_dod_axis(bg_x0, bg_x1, fg_x0, fg_x1, max_dim);
187 let (uy0, uy1) = expand_dod_axis(bg_y0, bg_y1, fg_y0, fg_y1, max_dim);910 let (mut uy0, mut uy1) = expand_dod_axis(bg_y0, bg_y1, fg_y0, fg_y1, max_dim);
911 if let Some((rx0, ry0, rx1, ry1)) = roi_bounds {
912 let cx0 = ux0.max(rx0);
913 let cx1 = ux1.min(rx1);
914 let cy0 = uy0.max(ry0);
915 let cy1 = uy1.min(ry1);
916 if cx0 < cx1 && cy0 < cy1 {
917 ux0 = cx0;
918 ux1 = cx1;
919 uy0 = cy0;
920 uy1 = cy1;
921 }
922 }
188 let uw = (ux1 - ux0).max(1) as u32;923 let uw = (ux1 - ux0).max(1) as u32;
189 let uh = (uy1 - uy0).max(1) as u32;924 let uh = (uy1 - uy0).max(1) as u32;
190 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]) {925 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]) {
191 dst_origin = [ux0, uy0];926 dst_origin = [ux0, uy0];
192 dst_size = [uw, uh];927 dst_size = [uw, uh];
193 }928 }
929 } else if let Some((rx0, ry0, rx1, ry1)) = roi_bounds {
930 let cx0 = bg_x0.max(rx0);
931 let cx1 = bg_x1.min(rx1);
932 let cy0 = bg_y0.max(ry0);
933 let cy1 = bg_y1.min(ry1);
934 if cx0 < cx1
935 && cy0 < cy1
936 && (cx0 != bg_x0
937 || cy0 != bg_y0
938 || (cx1 - cx0) as u32 != bg.size[0]
939 || (cy1 - cy0) as u32 != bg.size[1])
940 {
941 dst_origin = [cx0, cy0];
942 dst_size = [(cx1 - cx0) as u32, (cy1 - cy0) as u32];
943 }
194 }944 }
195 let dst_has_dod = dst_origin != [0, 0] || dst_size != bg.canvas_size;945 let dst_has_dod = dst_origin != [0, 0] || dst_size != bg.canvas_size;
196946
...@@ -1205,4 +1955,109 @@ mod tests {...@@ -1205,4 +1955,109 @@ mod tests {
1205 assert_eq!(super::expand_dod_axis(0, 1920, 4400.0, 6324.0, 8192), (0, 6326));1955 assert_eq!(super::expand_dod_axis(0, 1920, 4400.0, 6324.0, 8192), (0, 6326));
1206 assert_eq!(super::expand_dod_axis(-1000, 1920, -6000.0, 6000.0, 8192), (-3902, 4290));1956 assert_eq!(super::expand_dod_axis(-1000, 1920, -6000.0, 6000.0, 8192), (-3902, 4290));
1207 }1957 }
1958
1959 #[test]
1960 fn downstream_roi_bounds_clips_pixelwise_merge_and_preserves_spatial_dod() {
1961 let comp_src = r#"{
1962 Tools = ordered() {
1963 Bg = Background {
1964 Inputs = {
1965 Width = Input { Value = 64, },
1966 Height = Input { Value = 64, },
1967 TopLeftAlpha = Input { Value = 1.0, },
1968 },
1969 },
1970 HugeFg = Background {
1971 Inputs = {
1972 Width = Input { Value = 256, },
1973 Height = Input { Value = 256, },
1974 TopLeftRed = Input { Value = 1.0, },
1975 TopLeftAlpha = Input { Value = 1.0, },
1976 },
1977 },
1978 MergePixel = Merge {
1979 Inputs = {
1980 Background = Input { SourceOp = "Bg", Source = "Output", },
1981 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
1982 Size = Input { Value = 2.0, },
1983 },
1984 },
1985 Cc = ColorCorrector {
1986 Inputs = {
1987 Input = Input { SourceOp = "MergePixel", Source = "Output", },
1988 },
1989 },
1990 DbFrame = DirectionalBlur {
1991 Inputs = {
1992 Input = Input { SourceOp = "Cc", Source = "Output", },
1993 Length = Input { Value = 0.05, },
1994 },
1995 },
1996 MergeXf = Merge {
1997 Inputs = {
1998 Background = Input { SourceOp = "Bg", Source = "Output", },
1999 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2000 Size = Input { Value = 1.0, },
2001 },
2002 },
2003 XfOut = Transform {
2004 Inputs = {
2005 Size = Input { Value = 0.25, },
2006 Input = Input { SourceOp = "MergeXf", Source = "Output", },
2007 },
2008 },
2009 MergeCrop = Merge {
2010 Inputs = {
2011 Background = Input { SourceOp = "Bg", Source = "Output", },
2012 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2013 Size = Input { Value = 1.0, },
2014 },
2015 },
2016 CropOut = Crop {
2017 Inputs = {
2018 XOffset = Input { Value = -32, },
2019 YOffset = Input { Value = -32, },
2020 XSize = Input { Value = 64, },
2021 YSize = Input { Value = 64, },
2022 Input = Input { SourceOp = "MergeCrop", Source = "Output", },
2023 },
2024 },
2025 }
2026 }"#;
2027 let comp = Comp::from_fusion_str(comp_src).expect("parse roi comp");
2028 let mut eng = Engine::new_headless().expect("headless engine");
2029 let mut enc = eng.device.create_command_encoder(&Default::default());
2030 let mut visiting = std::collections::HashSet::new();
2031 let mut stats = super::EvalStats::default();
2032
2033 // Pixelwise + Frame-clipped DirectionalBlur downstream -> MergePixel stays tightly at 64x64.
2034 let mp_id = comp.find_node("MergePixel").unwrap();
2035 let mp_tex = eng.eval_node(&comp, mp_id, 0.0, &mut enc, &mut visiting, &mut stats);
2036 assert_eq!(mp_tex.origin, [0, 0]);
2037 assert_eq!(mp_tex.size, [64, 64]);
2038
2039 // Transform zooming out (Size=0.25) downstream -> MergeXf expands its DoD cleanly.
2040 let mxf_id = comp.find_node("MergeXf").unwrap();
2041 let mxf_tex = eng.eval_node(&comp, mxf_id, 0.0, &mut enc, &mut visiting, &mut stats);
2042 assert!(mxf_tex.size[0] > 64 && mxf_tex.size[1] > 64, "expected expanded DoD for zoom-out Transform, got {:?}", mxf_tex.size);
2043
2044 // Crop reading outside canvas -> MergeCrop bails out and preserves full DoD.
2045 let mc_id = comp.find_node("MergeCrop").unwrap();
2046 let mc_tex = eng.eval_node(&comp, mc_id, 0.0, &mut enc, &mut visiting, &mut stats);
2047 assert_eq!(mc_tex.size, [260, 260]);
2048 eng.queue.submit(Some(enc.finish()));
2049 eng.frame_memo.clear();
2050 eng.frame_consumers.clear();
2051 eng.frame_roi_memo.clear();
2052
2053 // Corner of XfOut must show HugeFg's red from outside the 64x64 BG canvas.
2054 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XfOut").unwrap(), 0.0);
2055 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
2056 assert!(px_at(&xf_px, xf_tex.size[0], 10, 10)[0] > 200, "zoom-out Transform corner must sample expanded DoD");
2057
2058 // CropOut reading [-32..32] must also sample HugeFg's red from outside the 64x64 BG canvas.
2059 let (cr_tex, _) = eng.evaluate(&comp, comp.find_node("CropOut").unwrap(), 0.0);
2060 let cr_px = eng.readback_rgba(&cr_tex).unwrap();
2061 assert!(px_at(&cr_px, cr_tex.size[0], 8, 8)[0] > 200, "Crop at negative offset must sample expanded DoD");
2062 }
1208}2063}
crates/engine/src/eval/mod.rs+64-10
...@@ -81,6 +81,10 @@ pub struct Engine {...@@ -81,6 +81,10 @@ pub struct Engine {
81 pub expr: ExprEngine,81 pub expr: ExprEngine,
82 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.82 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.
83 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,83 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,
84 /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current frame.
85 frame_consumers: Vec<Vec<(NodeId, String)>>,
86 /// Per-evaluation memo of conservative downstream RoI bounds `(node_id, time_bits)`.
87 frame_roi_memo: HashMap<(NodeId, i64), Option<composite::RoiBox>>,
84 output_cache: OutputCache,88 output_cache: OutputCache,
85 /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default89 /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default
86 /// to matching the dimensions & aspect ratio of the node they mask!).90 /// to matching the dimensions & aspect ratio of the node they mask!).
...@@ -110,6 +114,7 @@ impl Engine {...@@ -110,6 +114,7 @@ impl Engine {
110 },114 },
111 wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },115 wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
112 );116 );
117 let default_vram_mb = crate::cache::default_vram_budget_mb();
113 Self {118 Self {
114 device,119 device,
115 queue,120 queue,
...@@ -125,11 +130,13 @@ impl Engine {...@@ -125,11 +130,13 @@ impl Engine {
125 sprite_cache: HashMap::new(),130 sprite_cache: HashMap::new(),
126 ram_upload_tex: RefCell::new(None),131 ram_upload_tex: RefCell::new(None),
127 dummy,132 dummy,
128 vram_budget_bytes: crate::cache::DEFAULT_VRAM_BUDGET_MB.saturating_mul(1024 * 1024),133 vram_budget_bytes: default_vram_mb.saturating_mul(1024 * 1024),
129 cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB),134 cache: NodeCache::new(default_vram_mb),
130 media: MediaCache::new(512),135 media: MediaCache::new(512),
131 expr: ExprEngine::new(),136 expr: ExprEngine::new(),
132 frame_memo: HashMap::new(),137 frame_memo: HashMap::new(),
138 frame_consumers: Vec::new(),
139 frame_roi_memo: HashMap::new(),
133 output_cache: OutputCache::new(),140 output_cache: OutputCache::new(),
134 mask_target_size: None,141 mask_target_size: None,
135 proxy_scale: 1,142 proxy_scale: 1,
...@@ -283,8 +290,10 @@ impl Engine {...@@ -283,8 +290,10 @@ impl Engine {
283 return (tex, stats);290 return (tex, stats);
284 }291 }
285 let mut stats = EvalStats::default();292 let mut stats = EvalStats::default();
286 let mut visiting = HashSet::new();293 let mut visiting = HashSet::with_capacity(comp.nodes.len().min(64));
287 self.frame_memo.clear();294 self.frame_memo.clear();
295 self.frame_consumers.clear();
296 self.frame_roi_memo.clear();
288 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {297 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
289 label: Some("comp-eval"),298 label: Some("comp-eval"),
290 });299 });
...@@ -296,6 +305,8 @@ impl Engine {...@@ -296,6 +305,8 @@ impl Engine {
296 }305 }
297 self.queue.submit(Some(encoder.finish()));306 self.queue.submit(Some(encoder.finish()));
298 self.frame_memo.clear();307 self.frame_memo.clear();
308 self.frame_consumers.clear();
309 self.frame_roi_memo.clear();
299 self.cache.flush_pending_pool();310 self.cache.flush_pending_pool();
300 self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone());311 self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone());
301 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;312 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;
...@@ -327,8 +338,10 @@ impl Engine {...@@ -327,8 +338,10 @@ impl Engine {
327 stats.unsupported_nodes = unsupported;338 stats.unsupported_nodes = unsupported;
328 (cached, false)339 (cached, false)
329 } else {340 } else {
330 let mut visiting = HashSet::new();341 let mut visiting = HashSet::with_capacity(comp.nodes.len().min(64));
331 self.frame_memo.clear();342 self.frame_memo.clear();
343 self.frame_consumers.clear();
344 self.frame_roi_memo.clear();
332 let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);345 let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);
333 (t, true)346 (t, true)
334 };347 };
...@@ -365,6 +378,8 @@ impl Engine {...@@ -365,6 +378,8 @@ impl Engine {
365378
366 self.queue.submit(Some(encoder.finish()));379 self.queue.submit(Some(encoder.finish()));
367 self.frame_memo.clear();380 self.frame_memo.clear();
381 self.frame_consumers.clear();
382 self.frame_roi_memo.clear();
368 self.cache.flush_pending_pool();383 self.cache.flush_pending_pool();
369 if need_output_insert {384 if need_output_insert {
370 self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone());385 self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone());
...@@ -406,10 +421,41 @@ impl Engine {...@@ -406,10 +421,41 @@ impl Engine {
406 }421 }
407 let res = self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats);422 let res = self.eval_node_inner(comp, id, time, frame_i, enc, visiting, stats);
408 visiting.remove(&(id, time_key));423 visiting.remove(&(id, time_key));
424 if res.content_hash != 0
425 && matches!(
426 comp.node(id).kind.as_str(),
427 "Loader" | "TextPlus" | "Renderer3D" | "pRender" | "PolylineMask" | "WandMask"
428 )
429 {
430 self.cache.mark_entry_sticky(res.content_hash);
431 }
409 self.frame_memo.insert((id, time_key, memo_sz), res.clone());432 self.frame_memo.insert((id, time_key, memo_sz), res.clone());
410 res433 res
411 }434 }
412435
436 fn switch_input_port(idx: usize) -> Option<&'static str> {
437 match idx {
438 0 => Some("Input0"),
439 1 => Some("Input1"),
440 2 => Some("Input2"),
441 3 => Some("Input3"),
442 4 => Some("Input4"),
443 5 => Some("Input5"),
444 6 => Some("Input6"),
445 7 => Some("Input7"),
446 8 => Some("Input8"),
447 9 => Some("Input9"),
448 10 => Some("Input10"),
449 11 => Some("Input11"),
450 12 => Some("Input12"),
451 13 => Some("Input13"),
452 14 => Some("Input14"),
453 15 => Some("Input15"),
454 16 => Some("Input16"),
455 _ => None,
456 }
457 }
458
413 fn eval_node_inner(459 fn eval_node_inner(
414 &mut self,460 &mut self,
415 comp: &Comp,461 comp: &Comp,
...@@ -474,17 +520,25 @@ impl Engine {...@@ -474,17 +520,25 @@ impl Engine {
474 .eval_number(node, "Source", time, 0.0, &self.expr)520 .eval_number(node, "Source", time, 0.0, &self.expr)
475 .round()521 .round()
476 .max(0.0) as usize;522 .max(0.0) as usize;
477 let port = format!("Input{source}");523 if let Some(port) = Self::switch_input_port(source) {
478 node.connected_node(&port)524 node.connected_node(port)
479 .or_else(|| node.connected_node("Input0"))525 } else {
526 let port = format!("Input{source}");
527 node.connected_node(&port)
528 }
529 .or_else(|| node.connected_node("Input0"))
480 } else {530 } else {
481 let which = comp531 let which = comp
482 .eval_number(node, "Which", time, 1.0, &self.expr)532 .eval_number(node, "Which", time, 1.0, &self.expr)
483 .round()533 .round()
484 .max(1.0) as usize;534 .max(1.0) as usize;
485 let port = format!("Input{which}");535 if let Some(port) = Self::switch_input_port(which) {
486 node.connected_node(&port)536 node.connected_node(port)
487 .or_else(|| node.connected_node("Input1"))537 } else {
538 let port = format!("Input{which}");
539 node.connected_node(&port)
540 }
541 .or_else(|| node.connected_node("Input1"))
488 };542 };
489 if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) {543 if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) {
490 return self.eval_node(comp, src_id, time, enc, visiting, stats);544 return self.eval_node(comp, src_id, time, enc, visiting, stats);
crates/engine/src/eval/output_cache.rs+22-6
...@@ -59,7 +59,11 @@ impl OutputCache {...@@ -59,7 +59,11 @@ impl OutputCache {
59 /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`),59 /// Total GPU bytes referenced by `output_cache` entries (including textures shared with `NodeCache`),
60 /// counting a texture once however many entries point at it.60 /// counting a texture once however many entries point at it.
61 pub(super) fn total_bytes(&self) -> u64 {61 pub(super) fn total_bytes(&self) -> u64 {
62 self.textures().values().map(|&(bytes, _, _)| bytes).sum()62 match self.entries.len() {
63 0 => 0,
64 1 => self.entries[0].1.bytes,
65 _ => self.textures().values().map(|&(bytes, _, _)| bytes).sum(),
66 }
63 }67 }
6468
65 /// GPU bytes held *exclusively* by `output_cache`: every strong reference to the texture is an entry here.69 /// GPU bytes held *exclusively* by `output_cache`: every strong reference to the texture is an entry here.
...@@ -67,11 +71,23 @@ impl OutputCache {...@@ -67,11 +71,23 @@ impl OutputCache {
67 /// Textures still resident in `NodeCache` or cloned out to a caller have `strong_count` above the entry71 /// Textures still resident in `NodeCache` or cloned out to a caller have `strong_count` above the entry
68 /// count and are already accounted for elsewhere, so skipping them avoids double-counting the VRAM budget.72 /// count and are already accounted for elsewhere, so skipping them avoids double-counting the VRAM budget.
69 pub(super) fn unshared_bytes(&self) -> u64 {73 pub(super) fn unshared_bytes(&self) -> u64 {
70 self.textures()74 match self.entries.len() {
71 .values()75 0 => 0,
72 .filter(|&&(_, entries, strong)| entries == strong)76 1 => {
73 .map(|&(bytes, _, _)| bytes)77 let tex = &self.entries[0].1;
74 .sum()78 if Arc::strong_count(&tex.texture) == 1 {
79 tex.bytes
80 } else {
81 0
82 }
83 }
84 _ => self
85 .textures()
86 .values()
87 .filter(|&&(_, entries, strong)| entries == strong)
88 .map(|&(bytes, _, _)| bytes)
89 .sum(),
90 }
75 }91 }
7692
77 pub(super) fn get(&mut self, key: u64, mode: CacheMode) -> Option<(CachedTexture, Vec<String>)> {93 pub(super) fn get(&mut self, key: u64, mode: CacheMode) -> Option<(CachedTexture, Vec<String>)> {