1//! Content-hashed GPU texture cache with hard VRAM budget, LRU eviction,
2//! VRAM-budgeted texture pooling, per-node profiling hooks, and surgical
3//! cache-busting modes for profiling and playback verification.
4
5use crate::profile::{FrameProfile, ProfileRecorder};
6use model::{BitDepth, Comp, NodeId};
7use std::collections::{HashMap, VecDeque};
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::sync::{Arc, Mutex};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum CacheMode {
13 /// Content-hashed cache across all nodes up to `budget_bytes`.
14 Enabled,
15 /// Forces full re-evaluation every frame (zero reads/writes to node cache).
16 Bypass,
17}
18
19/// Fusion's empty-sky Z-buffer sentinel value (eye-space Z is negative in front of the
20/// camera, so closer geometry has a larger/less-negative Z than `-1e30`).
21pub const EMPTY_Z_SENTINEL: f32 = -1.0e30;
22
23/// A single GPU auxiliary image channel texture (`Z`, `Normal`, `Vector`, `BackVector`).
24#[derive(Clone, Debug)]
25pub struct AuxChannelTex {
26 pub texture: Arc<wgpu::Texture>,
27 pub view: Arc<wgpu::TextureView>,
28 pub size: [u32; 2],
29 pub format: wgpu::TextureFormat,
30 pub bytes: u64,
31}
32
33impl AuxChannelTex {
34 pub fn new(device: &wgpu::Device, size: [u32; 2], format: wgpu::TextureFormat, label: &str) -> Self {
35 let max_dim = device.limits().max_texture_dimension_2d.max(1);
36 let (clamped, _) = clamp_dims_to_limit(size[0], size[1], max_dim);
37 let texture = device.create_texture(&wgpu::TextureDescriptor {
38 label: Some(label),
39 size: wgpu::Extent3d {
40 width: clamped[0],
41 height: clamped[1],
42 depth_or_array_layers: 1,
43 },
44 mip_level_count: 1,
45 sample_count: 1,
46 dimension: wgpu::TextureDimension::D2,
47 format,
48 usage: wgpu::TextureUsages::TEXTURE_BINDING
49 | wgpu::TextureUsages::STORAGE_BINDING
50 | wgpu::TextureUsages::COPY_SRC
51 | wgpu::TextureUsages::COPY_DST,
52 view_formats: &[],
53 });
54 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
55 let bytes = texture_bytes(clamped, format);
56 Self {
57 texture: Arc::new(texture),
58 view: Arc::new(view),
59 size: clamped,
60 format,
61 bytes,
62 }
63 }
64
65 pub fn from_texture(texture: wgpu::Texture, size: [u32; 2]) -> Self {
66 let format = texture.format();
67 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
68 let bytes = texture_bytes(size, format);
69 Self {
70 texture: Arc::new(texture),
71 view: Arc::new(view),
72 size,
73 format,
74 bytes,
75 }
76 }
77}
78
79/// Optional Fusion auxiliary channels carried alongside RGBA on a `CachedTexture`.
80/// Remains `None` (zero allocation, zero runtime overhead) when no aux channels exist.
81#[derive(Clone, Debug, Default)]
82pub struct AuxChannels {
83 /// Eye-space Z depth (`R32Float`, negative in front of camera, `EMPTY_Z_SENTINEL` on sky).
84 pub z: Option<AuxChannelTex>,
85 /// Surface normal `(NX, NY, NZ, 0)` (`Rgba16Float`).
86 pub normal: Option<AuxChannelTex>,
87 /// Forward motion vector `(vx, vy, 0, 0)` in pixels (`Rgba16Float`).
88 pub vector: Option<AuxChannelTex>,
89 /// Backward motion vector `(bx, by, 0, 0)` in pixels (`Rgba16Float`).
90 pub back_vector: Option<AuxChannelTex>,
91}
92
93impl AuxChannels {
94 pub fn is_empty(&self) -> bool {
95 self.z.is_none()
96 && self.normal.is_none()
97 && self.vector.is_none()
98 && self.back_vector.is_none()
99 }
100
101 pub fn total_bytes(&self) -> u64 {
102 self.z.as_ref().map_or(0, |t| t.bytes)
103 .saturating_add(self.normal.as_ref().map_or(0, |t| t.bytes))
104 .saturating_add(self.vector.as_ref().map_or(0, |t| t.bytes))
105 .saturating_add(self.back_vector.as_ref().map_or(0, |t| t.bytes))
106 }
107}
108
109#[derive(Clone, Debug)]
110pub struct CachedTexture {
111 pub texture: Arc<wgpu::Texture>,
112 pub view: Arc<wgpu::TextureView>,
113 /// Actual allocated GPU texture dimensions `[w, h]`.
114 pub size: [u32; 2],
115 /// Domain of Definition (DoD) top-left offset in logical canvas pixels (`[0, 0]` for standard frames).
116 pub origin: [i32; 2],
117 /// Logical frame canvas dimensions (e.g. `[1920, 1080]`, matching `size` when DoD == canvas).
118 pub canvas_size: [u32; 2],
119 /// Logical Fusion color bit depth (`Int8`, `Int16`, `Float16`, `Float32`).
120 pub depth: BitDepth,
121 /// Underlying GPU texture format (`Rgba8Unorm`, `Rgba16Float`, or `Rgba32Float`).
122 pub format: wgpu::TextureFormat,
123 /// Scale ratio `physical_px / logical_px` when an oversized generator (>8K) is capped to GPU limits (1.0 normally).
124 pub tex_scale: f32,
125 /// Infinite RoI edge mode propagated from upstream `Merge` (`Some(1)` = Wrap, `Some(3)` = Mirror).
126 pub edge_mode: Option<u8>,
127 /// Optional Fusion auxiliary channels (`Z`, `Normal`, `Vector`, `BackVector`).
128 pub aux: Option<Arc<AuxChannels>>,
129 pub content_hash: u64,
130 pub bytes: u64,
131}
132
133fn depth_for_format(format: wgpu::TextureFormat) -> BitDepth {
134 match format {
135 wgpu::TextureFormat::Rgba16Float => BitDepth::Float16,
136 wgpu::TextureFormat::Rgba32Float => BitDepth::Float32,
137 _ => BitDepth::Int8,
138 }
139}
140
141fn bytes_per_pixel(format: wgpu::TextureFormat) -> u64 {
142 match format {
143 wgpu::TextureFormat::Rgba32Float => 16,
144 wgpu::TextureFormat::Rgba16Float => 8,
145 wgpu::TextureFormat::R32Float => 4,
146 _ => u64::from(format.block_copy_size(None).unwrap_or(4)),
147 }
148}
149
150fn texture_bytes(size: [u32; 2], format: wgpu::TextureFormat) -> u64 {
151 u64::from(size[0].max(1))
152 .saturating_mul(u64::from(size[1].max(1)))
153 .saturating_mul(bytes_per_pixel(format))
154}
155
156fn base_texture_bytes(tex: &CachedTexture) -> u64 {
157 if tex.bytes == 0 || tex.size[0] == 0 || tex.size[1] == 0 {
158 0
159 } else {
160 texture_bytes(tex.size, tex.format)
161 }
162}
163
164/// Clamps `(width, height)` to at least 1 and at most `max_dim` while preserving aspect ratio.
165/// Returns `(clamped_size, tex_scale)` where `tex_scale = physical / logical` (`1.0` if unclamped).
166pub(crate) fn clamp_dims_to_limit(width: u32, height: u32, max_dim: u32) -> ([u32; 2], f32) {
167 let w = width.max(1);
168 let h = height.max(1);
169 let max_d = max_dim.max(1);
170 let peak = w.max(h);
171 if peak <= max_d {
172 return ([w, h], 1.0);
173 }
174 let scale = max_d as f32 / peak as f32;
175 let cw = ((f64::from(w) * f64::from(max_d) / f64::from(peak)).round() as u32).clamp(1, max_d);
176 let ch = ((f64::from(h) * f64::from(max_d) / f64::from(peak)).round() as u32).clamp(1, max_d);
177 ([cw, ch], scale)
178}
179
180impl CachedTexture {
181 pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self {
182 Self::from_texture_dod(texture, size, [0, 0], size, content_hash)
183 }
184
185 pub fn from_texture_dod(
186 texture: wgpu::Texture,
187 size: [u32; 2],
188 origin: [i32; 2],
189 canvas_size: [u32; 2],
190 content_hash: u64,
191 ) -> Self {
192 let format = texture.format();
193 let depth = depth_for_format(format);
194 Self::from_texture_dod_depth(texture, size, origin, canvas_size, depth, content_hash)
195 }
196
197 pub fn from_texture_dod_depth(
198 texture: wgpu::Texture,
199 size: [u32; 2],
200 origin: [i32; 2],
201 canvas_size: [u32; 2],
202 depth: BitDepth,
203 content_hash: u64,
204 ) -> Self {
205 let format = texture.format();
206 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
207 let bytes = texture_bytes(size, format);
208 Self {
209 texture: Arc::new(texture),
210 view: Arc::new(view),
211 size,
212 origin,
213 canvas_size,
214 depth,
215 format,
216 tex_scale: 1.0,
217 edge_mode: None,
218 aux: None,
219 content_hash,
220 bytes,
221 }
222 }
223
224 #[allow(clippy::too_many_arguments)]
225 pub(crate) fn from_parts(
226 texture: Arc<wgpu::Texture>,
227 view: Arc<wgpu::TextureView>,
228 size: [u32; 2],
229 origin: [i32; 2],
230 canvas_size: [u32; 2],
231 depth: BitDepth,
232 format: wgpu::TextureFormat,
233 content_hash: u64,
234 bytes: u64,
235 ) -> Self {
236 Self {
237 texture,
238 view,
239 size,
240 origin,
241 canvas_size,
242 depth,
243 format,
244 tex_scale: 1.0,
245 edge_mode: None,
246 aux: None,
247 content_hash,
248 bytes,
249 }
250 }
251
252 pub fn has_dod(&self) -> bool {
253 self.origin != [0, 0] || self.size != self.canvas_size
254 }
255
256 /// Attaches (or clears) auxiliary channels and updates `self.bytes` for VRAM tracking.
257 pub fn set_aux(&mut self, aux: Option<Arc<AuxChannels>>) {
258 let base = texture_bytes(self.size, self.format);
259 let aux_filtered = aux.filter(|a| !a.is_empty());
260 let aux_bytes = aux_filtered.as_ref().map_or(0, |a| a.total_bytes());
261 self.aux = aux_filtered;
262 self.bytes = base.saturating_add(aux_bytes);
263 }
264
265 /// Returns a cloned copy of existing `AuxChannels` or an empty default.
266 pub fn aux_cloned(&self) -> AuxChannels {
267 self.aux.as_deref().cloned().unwrap_or_default()
268 }
269}
270
271#[derive(Clone, Debug, Default)]
272pub struct EvalStats {
273 pub eval_ms: f64,
274 pub nodes_evaluated: usize,
275 pub cache_hits: usize,
276 pub cache_misses: usize,
277 pub source_loads: usize,
278 pub pruned_branches: usize,
279 pub cached_entries: usize,
280 pub cached_vram_mb: f64,
281 pub media_entries: usize,
282 pub media_mb: f64,
283 pub unsupported_nodes: Vec<String>,
284}
285
286/// Key identifying compatible GPU textures in `TexturePool`.
287#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
288pub struct TexturePoolKey {
289 pub width: u32,
290 pub height: u32,
291 pub format: wgpu::TextureFormat,
292 pub usage: wgpu::TextureUsages,
293}
294
295/// Snapshot of `TexturePool` counters and resident VRAM.
296#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
297pub struct TexturePoolStats {
298 pub pooled_count: usize,
299 pub pooled_bytes: u64,
300 pub hits: u64,
301 pub misses: u64,
302 pub evictions: u64,
303 pub returns: u64,
304}
305
306struct PooledTexture {
307 texture: Arc<wgpu::Texture>,
308 view: Arc<wgpu::TextureView>,
309 bytes: u64,
310 last_returned: u64,
311}
312
313/// LRU pool of recycled `wgpu::Texture` allocations keyed by `(width, height, format, usage)`.
314pub struct TexturePool {
315 buckets: HashMap<TexturePoolKey, VecDeque<PooledTexture>>,
316 total_bytes: u64,
317 pooled_count: usize,
318 tick: u64,
319 hits: u64,
320 misses: u64,
321 evictions: u64,
322 returns: u64,
323}
324
325impl Default for TexturePool {
326 fn default() -> Self {
327 Self::new()
328 }
329}
330
331impl TexturePool {
332 pub fn new() -> Self {
333 Self {
334 buckets: HashMap::new(),
335 total_bytes: 0,
336 pooled_count: 0,
337 tick: 0,
338 hits: 0,
339 misses: 0,
340 evictions: 0,
341 returns: 0,
342 }
343 }
344
345 pub fn stats(&self) -> TexturePoolStats {
346 TexturePoolStats {
347 pooled_count: self.pooled_count,
348 pooled_bytes: self.total_bytes,
349 hits: self.hits,
350 misses: self.misses,
351 evictions: self.evictions,
352 returns: self.returns,
353 }
354 }
355
356 pub fn pooled_bytes(&self) -> u64 {
357 self.total_bytes
358 }
359
360 pub fn pooled_count(&self) -> usize {
361 self.pooled_count
362 }
363
364 pub fn hits(&self) -> u64 {
365 self.hits
366 }
367
368 pub fn misses(&self) -> u64 {
369 self.misses
370 }
371
372 pub fn evictions(&self) -> u64 {
373 self.evictions
374 }
375
376 pub fn clear(&mut self) {
377 self.buckets.clear();
378 self.total_bytes = 0;
379 self.pooled_count = 0;
380 }
381
382 fn push(&mut self, tex: &CachedTexture) {
383 let base_bytes = base_texture_bytes(tex);
384 if base_bytes == 0 {
385 return;
386 }
387 let key = TexturePoolKey {
388 width: tex.size[0],
389 height: tex.size[1],
390 format: tex.format,
391 usage: tex.texture.usage(),
392 };
393 self.tick += 1;
394 self.total_bytes = self.total_bytes.saturating_add(base_bytes);
395 self.pooled_count += 1;
396 self.returns += 1;
397 self.buckets.entry(key).or_default().push_back(PooledTexture {
398 texture: Arc::clone(&tex.texture),
399 view: Arc::clone(&tex.view),
400 bytes: base_bytes,
401 last_returned: self.tick,
402 });
403 }
404
405 /// Pops an exclusively owned (`Arc::strong_count == 1`) texture matching `key`.
406 /// Entries still referenced elsewhere (e.g. by `output_cache`) are dropped from the pool
407 /// rather than aliased.
408 fn pop(&mut self, key: TexturePoolKey) -> Option<(Arc<wgpu::Texture>, Arc<wgpu::TextureView>, u64)> {
409 let mut found = None;
410 let remove_bucket = if let Some(bucket) = self.buckets.get_mut(&key) {
411 while let Some(item) = bucket.pop_back() {
412 self.total_bytes = self.total_bytes.saturating_sub(item.bytes);
413 self.pooled_count = self.pooled_count.saturating_sub(1);
414 if Arc::strong_count(&item.texture) == 1 && Arc::strong_count(&item.view) == 1 {
415 found = Some((item.texture, item.view, item.bytes));
416 break;
417 }
418 }
419 bucket.is_empty()
420 } else {
421 false
422 };
423 if remove_bucket {
424 self.buckets.remove(&key);
425 }
426 found
427 }
428
429 /// Evicts the globally oldest pooled texture (FIFO/LRU by return order).
430 fn evict_oldest(&mut self) -> bool {
431 let oldest_key = self
432 .buckets
433 .iter()
434 .filter_map(|(&k, q)| q.front().map(|front| (k, front.last_returned)))
435 .min_by_key(|(_, tick)| *tick)
436 .map(|(k, _)| k);
437 let Some(key) = oldest_key else {
438 return false;
439 };
440 let mut remove_bucket = false;
441 if let Some(bucket) = self.buckets.get_mut(&key) {
442 if let Some(item) = bucket.pop_front() {
443 self.total_bytes = self.total_bytes.saturating_sub(item.bytes);
444 self.pooled_count = self.pooled_count.saturating_sub(1);
445 self.evictions += 1;
446 }
447 remove_bucket = bucket.is_empty();
448 }
449 if remove_bucket {
450 self.buckets.remove(&key);
451 }
452 true
453 }
454}
455
456struct Entry {
457 tex: CachedTexture,
458 last_used: u64,
459 sticky: bool,
460 first_producer: NodeId,
461 extra_producers: Vec<NodeId>,
462 first_frame: i64,
463 extra_frames: Vec<i64>,
464}
465
466impl Entry {
467 fn has_producer(&self, node: NodeId) -> bool {
468 self.first_producer == node || self.extra_producers.contains(&node)
469 }
470
471 fn record_producer(&mut self, node: NodeId) {
472 if !self.has_producer(node) {
473 self.extra_producers.push(node);
474 }
475 }
476
477 fn has_frame(&self, frame: i64) -> bool {
478 self.first_frame == frame || self.extra_frames.contains(&frame)
479 }
480
481 fn record_frame(&mut self, frame: i64) {
482 if !self.has_frame(frame) {
483 self.extra_frames.push(frame);
484 }
485 }
486
487 fn is_multi_frame(&self) -> bool {
488 !self.extra_frames.is_empty()
489 }
490
491 /// Eviction priority `(tier, last_used)` where smaller values are evicted first:
492 /// - Tier 0: single-frame transient intermediates (`!sticky && !multi_frame`)
493 /// - Tier 1: single-frame sticky generators OR multi-frame non-sticky intermediates
494 /// - Tier 2: live multi-frame sticky generators (e.g. static `Loader`, `TextPlus`)
495 fn eviction_priority(&self) -> (u8, u64) {
496 let tier = match (self.sticky, self.is_multi_frame()) {
497 (false, false) => 0,
498 (true, false) | (false, true) => 1,
499 (true, true) => 2,
500 };
501 (tier, self.last_used)
502 }
503}
504
505/// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB).
506pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768;
507
508#[cfg(not(target_arch = "wasm32"))]
509fn system_ram_mb() -> Option<u64> {
510 use std::sync::OnceLock;
511 static RAM_MB: OnceLock<Option<u64>> = OnceLock::new();
512 *RAM_MB.get_or_init(|| {
513 #[cfg(target_os = "macos")]
514 {
515 let out = std::process::Command::new("sysctl")
516 .args(["-n", "hw.memsize"])
517 .output()
518 .ok()?;
519 if !out.status.success() {
520 return None;
521 }
522 let bytes: u64 = std::str::from_utf8(&out.stdout).ok()?.trim().parse().ok()?;
523 Some(bytes / (1024 * 1024))
524 }
525 #[cfg(target_os = "linux")]
526 {
527 let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
528 for line in meminfo.lines() {
529 if let Some(rest) = line.strip_prefix("MemTotal:") {
530 let kb: u64 = rest.split_whitespace().next()?.parse().ok()?;
531 return Some(kb / 1024);
532 }
533 }
534 None
535 }
536 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
537 {
538 None
539 }
540 })
541}
542
543/// Computes `default_vram_budget_mb` from total system RAM (`min(ram_mb / 8, 8192).max(768)`).
544#[cfg(any(not(target_arch = "wasm32"), test))]
545pub(crate) fn vram_budget_mb_for_ram(ram_mb: Option<u64>) -> u64 {
546 match ram_mb {
547 Some(mb) if mb > 0 => (mb / 8).min(8192).max(DEFAULT_VRAM_BUDGET_MB),
548 _ => DEFAULT_VRAM_BUDGET_MB,
549 }
550}
551
552/// System-aware default GPU texture cache VRAM budget in MiB.
553///
554/// Scales up to `8192 MiB` on high-RAM unified-memory machines (`min(ram_mb / 8, 8192).max(768)`)
555/// so static 4K `Loader` textures are not evicted during playback, while keeping `wasm32`
556/// and low-RAM systems at `DEFAULT_VRAM_BUDGET_MB` (768 MiB).
557pub fn default_vram_budget_mb() -> u64 {
558 #[cfg(target_arch = "wasm32")]
559 {
560 DEFAULT_VRAM_BUDGET_MB
561 }
562 #[cfg(not(target_arch = "wasm32"))]
563 {
564 vram_budget_mb_for_ram(system_ram_mb())
565 }
566}
567
568/// Alias for `NodeCache` (GPU texture cache + VRAM-budgeted `TexturePool`).
569pub type GpuCache = NodeCache;
570
571pub struct NodeCache {
572 pub mode: CacheMode,
573 pub budget_bytes: u64,
574 entries: HashMap<u64, Entry>,
575 total_bytes: u64,
576 tick: u64,
577 evictions: u64,
578 /// Monotonic counter incremented whenever a texture is dropped without being pooled
579 /// or evicted from `TexturePool`, used to invalidate `BindGroup` caches before they pin VRAM.
580 vram_drops: AtomicU64,
581 /// Monotonic salt bumped when busting GPU cache globally.
582 pub gpu_salt: u64,
583 /// Per-node salt bumped when surgically busting a subtree.
584 node_salts: HashMap<NodeId, u64>,
585 pool: Mutex<TexturePool>,
586 /// Evicted textures deferred until after `queue.submit` so `queue.write_texture`
587 /// never aliases a texture still referenced by in-flight commands in the current encoder.
588 pending_pool: VecDeque<CachedTexture>,
589 /// Unkeyed scratch textures (`content_hash == 0`) deferred until after `queue.submit`
590 /// and recycled into `TexturePool` if no longer referenced on the CPU.
591 pending_scratch: Mutex<Vec<CachedTexture>>,
592 profiler: Option<ProfileRecorder>,
593}
594
595impl NodeCache {
596 pub fn new(budget_mb: u64) -> Self {
597 Self {
598 mode: CacheMode::Enabled,
599 budget_bytes: budget_mb.saturating_mul(1024 * 1024),
600 entries: HashMap::new(),
601 total_bytes: 0,
602 tick: 0,
603 evictions: 0,
604 vram_drops: AtomicU64::new(0),
605 gpu_salt: 0,
606 node_salts: HashMap::new(),
607 pool: Mutex::new(TexturePool::new()),
608 pending_pool: VecDeque::new(),
609 pending_scratch: Mutex::new(Vec::new()),
610 profiler: None,
611 }
612 }
613
614 /// Standard compositor GPU texture usage flags used by `Evaluator`.
615 pub fn default_texture_usage() -> wgpu::TextureUsages {
616 wgpu::TextureUsages::TEXTURE_BINDING
617 | wgpu::TextureUsages::STORAGE_BINDING
618 | wgpu::TextureUsages::COPY_SRC
619 | wgpu::TextureUsages::COPY_DST
620 | wgpu::TextureUsages::RENDER_ATTACHMENT
621 }
622
623 pub fn set_budget_mb(&mut self, budget_mb: u64) {
624 self.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
625 self.trim_pool_to_budget();
626 self.evict_over_budget();
627 self.trim_pool_to_budget();
628 }
629
630 pub fn budget_mb(&self) -> u64 {
631 self.budget_bytes / (1024 * 1024)
632 }
633
634 pub fn eviction_count(&self) -> u64 {
635 self.evictions
636 }
637
638 pub fn vram_drops(&self) -> u64 {
639 self.vram_drops.load(Ordering::Relaxed)
640 }
641
642 pub fn node_salt(&self, id: NodeId) -> u64 {
643 self.node_salts.get(&id).copied().unwrap_or(0)
644 }
645
646 pub fn pool_stats(&self) -> TexturePoolStats {
647 self.pool.lock().expect("texture pool lock").stats()
648 }
649
650 pub fn pooled_bytes(&self) -> u64 {
651 self.pool.lock().expect("texture pool lock").pooled_bytes()
652 }
653
654 pub fn pooled_mb(&self) -> f64 {
655 self.pooled_bytes() as f64 / (1024.0 * 1024.0)
656 }
657
658 pub fn live_bytes(&self) -> u64 {
659 self.total_bytes
660 }
661
662 pub fn live_mb(&self) -> f64 {
663 self.total_bytes as f64 / (1024.0 * 1024.0)
664 }
665
666 pub fn total_vram_bytes(&self) -> u64 {
667 self.total_bytes.saturating_add(self.pooled_bytes())
668 }
669
670 /// Acquires a GPU texture matching `(width, height, format, usage)` from the pool if an
671 /// exclusively-owned texture is available, otherwise allocates a fresh one on `device`.
672 /// Dimensions exceeding `device.limits().max_texture_dimension_2d` are clamped proportionally
673 /// and the resulting scale factor is recorded in `tex_scale`.
674 pub fn acquire_texture(
675 &self,
676 device: &wgpu::Device,
677 width: u32,
678 height: u32,
679 format: wgpu::TextureFormat,
680 usage: wgpu::TextureUsages,
681 ) -> CachedTexture {
682 let max_dim = device.limits().max_texture_dimension_2d.max(1);
683 let (clamped, tex_scale) = clamp_dims_to_limit(width, height, max_dim);
684 let bytes = texture_bytes(clamped, format);
685 let key = TexturePoolKey {
686 width: clamped[0],
687 height: clamped[1],
688 format,
689 usage,
690 };
691 let depth = depth_for_format(format);
692
693 {
694 let mut pool = self.pool.lock().expect("texture pool lock");
695 if let Some((texture, view, pooled_bytes)) = pool.pop(key) {
696 pool.hits += 1;
697 let mut tex = CachedTexture::from_parts(
698 texture,
699 view,
700 clamped,
701 [0, 0],
702 clamped,
703 depth,
704 format,
705 0,
706 pooled_bytes,
707 );
708 tex.tex_scale = tex_scale;
709 return tex;
710 }
711 pool.misses += 1;
712 // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget.
713 self.trim_pool_locked(&mut pool, bytes);
714 }
715
716 let texture = device.create_texture(&wgpu::TextureDescriptor {
717 label: Some("comp-tex"),
718 size: wgpu::Extent3d {
719 width: clamped[0],
720 height: clamped[1],
721 depth_or_array_layers: 1,
722 },
723 mip_level_count: 1,
724 sample_count: 1,
725 dimension: wgpu::TextureDimension::D2,
726 format,
727 usage,
728 view_formats: &[],
729 });
730 let mut tex = CachedTexture::from_texture_dod_depth(texture, clamped, [0, 0], clamped, depth, 0);
731 tex.tex_scale = tex_scale;
732 tex
733 }
734
735 /// Pool-backed DoD texture allocation matching `create_texture_dod_fmt` semantics.
736 #[allow(clippy::too_many_arguments)]
737 pub fn acquire_texture_dod_fmt(
738 &self,
739 device: &wgpu::Device,
740 size: [u32; 2],
741 origin: [i32; 2],
742 canvas_size: [u32; 2],
743 depth: BitDepth,
744 format: wgpu::TextureFormat,
745 content_hash: u64,
746 ) -> CachedTexture {
747 let mut tex = self.acquire_texture(
748 device,
749 size[0],
750 size[1],
751 format,
752 Self::default_texture_usage(),
753 );
754 tex.origin = if tex.tex_scale < 1.0 {
755 [
756 (origin[0] as f32 * tex.tex_scale).round() as i32,
757 (origin[1] as f32 * tex.tex_scale).round() as i32,
758 ]
759 } else {
760 origin
761 };
762 tex.canvas_size = if size == canvas_size {
763 tex.size
764 } else if tex.tex_scale < 1.0 {
765 [
766 ((canvas_size[0].max(1) as f32 * tex.tex_scale).round() as u32).max(1),
767 ((canvas_size[1].max(1) as f32 * tex.tex_scale).round() as u32).max(1),
768 ]
769 } else {
770 [canvas_size[0].max(1), canvas_size[1].max(1)]
771 };
772 tex.depth = depth;
773 tex.content_hash = content_hash;
774 if content_hash == 0 {
775 if let Ok(mut scratch) = self.pending_scratch.lock() {
776 scratch.push(tex.clone());
777 }
778 }
779 tex
780 }
781
782 /// Marks a cached entry as belonging to a sticky/high-cost generator (e.g. `Loader`, `TextPlus`)
783 /// so tight-VRAM eviction sheds single-frame transient intermediates first.
784 pub fn mark_entry_sticky(&mut self, key: u64) {
785 if let Some(entry) = self.entries.get_mut(&key) {
786 entry.sticky = true;
787 }
788 }
789
790 #[cfg(test)]
791 pub(crate) fn is_entry_sticky(&self, key: u64) -> bool {
792 self.entries.get(&key).is_some_and(|e| e.sticky)
793 }
794
795 /// Starts per-node profiling for the upcoming frame evaluation.
796 pub fn begin_frame_profile(&mut self) {
797 let stats = self.pool_stats();
798 self.profiler = Some(ProfileRecorder::new(stats.hits, stats.misses));
799 }
800
801 /// Starts per-node profiling with node names and kinds pre-populated from `comp`.
802 pub fn begin_frame_profile_with_comp(&mut self, comp: &Comp) {
803 let stats = self.pool_stats();
804 self.profiler = Some(ProfileRecorder::with_comp(comp, stats.hits, stats.misses));
805 }
806
807 /// Stops profiling and returns the collected `FrameProfile`, if active.
808 pub fn take_frame_profile(&mut self) -> Option<FrameProfile> {
809 let rec = self.profiler.take()?;
810 let stats = self.pool_stats();
811 Some(rec.finish(self.total_bytes, stats.pooled_bytes, stats.hits, stats.misses))
812 }
813
814 pub fn get(&mut self, key: u64, node: NodeId, frame: i64) -> Option<CachedTexture> {
815 if self.mode == CacheMode::Bypass {
816 return None;
817 }
818 self.tick += 1;
819 let e = self.entries.get_mut(&key)?;
820 e.last_used = self.tick;
821 e.record_producer(node);
822 e.record_frame(frame);
823 let tex = e.tex.clone();
824 if let Some(prof) = &mut self.profiler {
825 prof.record(node, true, tex.size, tex.bytes);
826 }
827 Some(tex)
828 }
829
830 pub fn insert(&mut self, key: u64, tex: CachedTexture, node: NodeId, frame: i64) {
831 if let Some(prof) = &mut self.profiler {
832 prof.record(node, false, tex.size, tex.bytes);
833 }
834 if self.mode == CacheMode::Bypass {
835 return;
836 }
837 self.tick += 1;
838 let mut was_sticky = false;
839 if let Some(old) = self.entries.remove(&key) {
840 was_sticky = old.sticky;
841 self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes);
842 if !Arc::ptr_eq(&old.tex.texture, &tex.texture) {
843 self.defer_to_pool(old.tex);
844 }
845 }
846 self.total_bytes = self.total_bytes.saturating_add(tex.bytes);
847 self.entries.insert(
848 key,
849 Entry {
850 tex,
851 last_used: self.tick,
852 sticky: was_sticky,
853 first_producer: node,
854 extra_producers: Vec::new(),
855 first_frame: frame,
856 extra_frames: Vec::new(),
857 },
858 );
859 // Trim pooled textures before evicting live cached nodes so live working sets stay hot.
860 self.trim_pool_to_budget();
861 self.evict_over_budget();
862 self.trim_pool_to_budget();
863 }
864
865 fn defer_to_pool(&mut self, mut tex: CachedTexture) {
866 let base_bytes = base_texture_bytes(&tex);
867 if base_bytes == 0 || base_bytes > self.budget_bytes {
868 if base_bytes > 0 {
869 self.vram_drops.fetch_add(1, Ordering::Relaxed);
870 }
871 return;
872 }
873 // Aux channels are not pooled; drop them immediately so deferred pool entries
874 // only account for base RGBA texture bytes.
875 tex.set_aux(None);
876 let mut pending_bytes: u64 = self.pending_pool.iter().map(base_texture_bytes).sum();
877 if self
878 .total_bytes
879 .saturating_add(pending_bytes)
880 .saturating_add(base_bytes)
881 <= self.budget_bytes
882 {
883 self.pending_pool.push_back(tex);
884 } else {
885 // Keep most recently evicted textures within budget; drop older pending ones.
886 while let Some(dropped) = self.pending_pool.front() {
887 if self
888 .total_bytes
889 .saturating_add(pending_bytes)
890 .saturating_add(base_bytes)
891 <= self.budget_bytes
892 {
893 break;
894 }
895 pending_bytes = pending_bytes.saturating_sub(base_texture_bytes(dropped));
896 self.pending_pool.pop_front();
897 self.vram_drops.fetch_add(1, Ordering::Relaxed);
898 }
899 if self
900 .total_bytes
901 .saturating_add(pending_bytes)
902 .saturating_add(base_bytes)
903 <= self.budget_bytes
904 {
905 self.pending_pool.push_back(tex);
906 } else {
907 self.vram_drops.fetch_add(1, Ordering::Relaxed);
908 }
909 }
910 }
911
912 /// Moves textures evicted or allocated as scratch during the current frame into `TexturePool`.
913 /// Must be called right after `queue.submit` so `queue.write_texture` cannot
914 /// overwrite a texture still used by commands in the submitted encoder.
915 pub fn flush_pending_pool(&mut self) {
916 let drained = std::mem::take(&mut self.pending_pool);
917 for tex in drained {
918 self.return_to_pool(&tex);
919 }
920 let scratch = {
921 let mut guard = self.pending_scratch.lock().expect("pending scratch lock");
922 std::mem::take(&mut *guard)
923 };
924 for tex in scratch {
925 if Arc::strong_count(&tex.texture) == 1 && Arc::strong_count(&tex.view) == 1 {
926 self.return_to_pool(&tex);
927 }
928 }
929 }
930
931 fn trim_pool_locked(&self, pool: &mut TexturePool, reserve_bytes: u64) {
932 while self
933 .total_bytes
934 .saturating_add(pool.total_bytes)
935 .saturating_add(reserve_bytes)
936 > self.budget_bytes
937 {
938 if !pool.evict_oldest() {
939 break;
940 }
941 self.vram_drops.fetch_add(1, Ordering::Relaxed);
942 }
943 }
944
945 fn return_to_pool(&self, tex: &CachedTexture) {
946 let base_bytes = base_texture_bytes(tex);
947 if base_bytes == 0 || base_bytes > self.budget_bytes {
948 if base_bytes > 0 {
949 self.vram_drops.fetch_add(1, Ordering::Relaxed);
950 }
951 return;
952 }
953 let mut pool = self.pool.lock().expect("texture pool lock");
954 pool.push(tex);
955 self.trim_pool_locked(&mut pool, 0);
956 }
957
958 fn trim_pool_to_budget(&self) {
959 let mut pool = self.pool.lock().expect("texture pool lock");
960 self.trim_pool_locked(&mut pool, 0);
961 }
962
963 fn evict_over_budget(&mut self) {
964 while self.total_bytes > self.budget_bytes && self.entries.len() > 1 {
965 let Some((&victim_key, _)) = self
966 .entries
967 .iter()
968 .min_by_key(|(_, e)| e.eviction_priority())
969 else {
970 break;
971 };
972 if let Some(removed) = self.entries.remove(&victim_key) {
973 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
974 self.evictions += 1;
975 self.defer_to_pool(removed.tex);
976 }
977 }
978 }
979
980 /// Wipes every cached GPU node texture (returning eligible textures to the pool) and bumps global salt.
981 pub fn bust_all(&mut self) {
982 let _ = self.clear_dynamic();
983 }
984
985 /// Clears all dynamic cached GPU node textures into the pool (within VRAM budget) and bumps global salt.
986 pub fn clear_dynamic(&mut self) -> usize {
987 let count = self.entries.len();
988 let mut drained: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect();
989 let pending = std::mem::take(&mut self.pending_pool);
990 let scratch = {
991 let mut guard = self.pending_scratch.lock().expect("pending scratch lock");
992 std::mem::take(&mut *guard)
993 };
994 self.total_bytes = 0;
995 self.gpu_salt += 1;
996 // Drop or recycle unreferenced scratch textures before pushing drained entries so
997 // `Arc::strong_count` reflects true external ownership.
998 let mut recycle_scratch = Vec::new();
999 for tex in scratch {
1000 if Arc::strong_count(&tex.texture) == 1 && Arc::strong_count(&tex.view) == 1 {
1001 recycle_scratch.push(tex);
1002 }
1003 }
1004 if (!drained.is_empty() || !pending.is_empty() || !recycle_scratch.is_empty())
1005 && self.budget_bytes > 0
1006 {
1007 // Push lower-priority / older entries first so sticky/multi-frame entries
1008 // get higher `last_returned` ticks and survive longest under pool pressure.
1009 drained.sort_by_key(|e| e.eviction_priority());
1010 let mut pool = self.pool.lock().expect("texture pool lock");
1011 for tex in recycle_scratch {
1012 let base_bytes = base_texture_bytes(&tex);
1013 if base_bytes > 0 && base_bytes <= self.budget_bytes {
1014 pool.push(&tex);
1015 } else if base_bytes > 0 {
1016 self.vram_drops.fetch_add(1, Ordering::Relaxed);
1017 }
1018 }
1019 for tex in pending {
1020 let base_bytes = base_texture_bytes(&tex);
1021 if base_bytes > 0 && base_bytes <= self.budget_bytes {
1022 pool.push(&tex);
1023 } else if base_bytes > 0 {
1024 self.vram_drops.fetch_add(1, Ordering::Relaxed);
1025 }
1026 }
1027 for entry in drained {
1028 let base_bytes = base_texture_bytes(&entry.tex);
1029 if base_bytes > 0 && base_bytes <= self.budget_bytes {
1030 pool.push(&entry.tex);
1031 } else if base_bytes > 0 {
1032 self.vram_drops.fetch_add(1, Ordering::Relaxed);
1033 }
1034 }
1035 self.trim_pool_locked(&mut pool, 0);
1036 } else {
1037 let dropped = drained.iter().filter(|e| base_texture_bytes(&e.tex) > 0).count()
1038 + pending.iter().filter(|t| base_texture_bytes(t) > 0).count()
1039 + recycle_scratch.iter().filter(|t| base_texture_bytes(t) > 0).count();
1040 if dropped > 0 {
1041 self.vram_drops.fetch_add(dropped as u64, Ordering::Relaxed);
1042 }
1043 }
1044 count
1045 }
1046
1047 /// Removes cached entries produced for a specific integer frame, returning them to the pool.
1048 pub fn bust_frame(&mut self, frame: i64) -> usize {
1049 let keys: Vec<u64> = self
1050 .entries
1051 .iter()
1052 .filter(|(_, e)| e.has_frame(frame))
1053 .map(|(k, _)| *k)
1054 .collect();
1055 let count = keys.len();
1056 for k in keys {
1057 if let Some(removed) = self.entries.remove(&k) {
1058 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
1059 self.return_to_pool(&removed.tex);
1060 }
1061 }
1062 count
1063 }
1064
1065 /// Bumps the salt on `node` (automatically invalidating `node` AND everything downstream
1066 /// via Merkle hashing!) and evicts its existing entries back into the pool.
1067 pub fn bust_subtree(&mut self, node: NodeId) -> usize {
1068 *self.node_salts.entry(node).or_insert(0) += 1;
1069 let keys: Vec<u64> = self
1070 .entries
1071 .iter()
1072 .filter(|(_, e)| e.has_producer(node))
1073 .map(|(k, _)| *k)
1074 .collect();
1075 let count = keys.len();
1076 for k in keys {
1077 if let Some(removed) = self.entries.remove(&k) {
1078 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
1079 self.return_to_pool(&removed.tex);
1080 }
1081 }
1082 count
1083 }
1084
1085 pub fn entry_count(&self) -> usize {
1086 self.entries.len()
1087 }
1088
1089 pub fn total_mb(&self) -> f64 {
1090 self.total_vram_bytes() as f64 / (1024.0 * 1024.0)
1091 }
1092}
1093
1094#[cfg(test)]
1095mod tests {
1096 use super::*;
1097 use crate::Engine;
1098
1099 #[test]
1100 fn texture_pool_recycles_after_clear_dynamic_and_bust() {
1101 let eng = Engine::new_headless().expect("gpu");
1102 let device = eng.device();
1103 let usage = NodeCache::default_texture_usage();
1104 let mut cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB);
1105
1106 // Initial acquire misses pool and allocates a 512x512 RGBA8 texture (1 MiB).
1107 let t1 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1108 let ptr1 = Arc::as_ptr(&t1.texture);
1109 assert_eq!(t1.bytes, 1024 * 1024);
1110 assert_eq!(cache.pool_stats().misses, 1);
1111 assert_eq!(cache.pool_stats().hits, 0);
1112
1113 cache.insert(101, t1, NodeId(1), 0);
1114 assert_eq!(cache.live_bytes(), 1024 * 1024);
1115 assert_eq!(cache.pooled_bytes(), 0);
1116
1117 // clear_dynamic returns unshared texture to pool without freeing GPU allocation.
1118 let cleared = cache.clear_dynamic();
1119 assert_eq!(cleared, 1);
1120 assert_eq!(cache.live_bytes(), 0);
1121 assert_eq!(cache.pooled_bytes(), 1024 * 1024);
1122 assert_eq!(cache.pool_stats().pooled_count, 1);
1123
1124 // Acquiring same (w, h, format, usage) reuses the exact same wgpu::Texture allocation!
1125 let t2 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1126 assert_eq!(Arc::as_ptr(&t2.texture), ptr1);
1127 assert_eq!(cache.pool_stats().hits, 1);
1128 assert_eq!(cache.pool_stats().misses, 1);
1129 assert_eq!(cache.pooled_bytes(), 0);
1130
1131 // Different format must miss pool and allocate separately.
1132 let t3 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba16Float, usage);
1133 assert_ne!(Arc::as_ptr(&t3.texture), ptr1);
1134 assert_eq!(cache.pool_stats().misses, 2);
1135
1136 // Insert both and bust_frame(5) -> returns only frame 5 texture to pool.
1137 cache.insert(201, t2, NodeId(1), 5);
1138 cache.insert(202, t3, NodeId(2), 6);
1139 assert_eq!(cache.bust_frame(5), 1);
1140 assert_eq!(cache.pooled_bytes(), 1024 * 1024);
1141 assert_eq!(cache.live_bytes(), 2 * 1024 * 1024);
1142
1143 let t4 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1144 assert_eq!(Arc::as_ptr(&t4.texture), ptr1);
1145 assert_eq!(cache.pool_stats().hits, 2);
1146 }
1147
1148 #[test]
1149 fn texture_pool_never_aliases_shared_arc() {
1150 let eng = Engine::new_headless().expect("gpu");
1151 let device = eng.device();
1152 let usage = NodeCache::default_texture_usage();
1153 let mut cache = NodeCache::new(16);
1154
1155 let t1 = cache.acquire_texture(device, 256, 256, wgpu::TextureFormat::Rgba8Unorm, usage);
1156 let pinned = t1.clone(); // External holder keeps strong_count > 1!
1157 let ptr1 = Arc::as_ptr(&t1.texture);
1158 cache.insert(1, t1, NodeId(0), 0);
1159 cache.bust_all();
1160
1161 // While `pinned` is still alive, acquire_texture must NOT alias `t1`.
1162 let t2 = cache.acquire_texture(device, 256, 256, wgpu::TextureFormat::Rgba8Unorm, usage);
1163 assert_ne!(Arc::as_ptr(&t2.texture), ptr1);
1164 assert_eq!(cache.pool_stats().hits, 0);
1165 drop(pinned);
1166 }
1167
1168 #[test]
1169 fn vram_budget_enforces_live_plus_pooled_cap_and_lru_eviction() {
1170 let eng = Engine::new_headless().expect("gpu");
1171 let device = eng.device();
1172 let usage = NodeCache::default_texture_usage();
1173 // 8 MiB budget; each 1024x1024 RGBA8 texture is 4 MiB.
1174 let mut cache = NodeCache::new(8);
1175 let budget = 8 * 1024 * 1024;
1176
1177 let a = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage);
1178 let b = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage);
1179 cache.insert(1, a, NodeId(0), 0);
1180 cache.insert(2, b, NodeId(1), 0);
1181 assert_eq!(cache.total_vram_bytes(), 8 * 1024 * 1024);
1182
1183 // Bust both into pool: live=0, pooled=8 MiB <= 8 MiB.
1184 cache.bust_all();
1185 assert_eq!(cache.live_bytes(), 0);
1186 assert_eq!(cache.pooled_bytes(), 8 * 1024 * 1024);
1187
1188 // Inserting a 1024x1024 RGBA16F (8 MiB) must evict ALL pooled RGBA8 textures so live + pooled <= 8 MiB.
1189 let c = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba16Float, usage);
1190 assert!(cache.total_vram_bytes() <= budget);
1191 cache.insert(3, c, NodeId(2), 1);
1192 assert!(cache.total_vram_bytes() <= budget);
1193 assert_eq!(cache.pooled_bytes(), 0);
1194 assert!(cache.pool_stats().evictions >= 2);
1195
1196 // Verify deterministic LRU eviction order in pool within 8 MiB.
1197 let mut cache3 = NodeCache::new(8);
1198 let first = cache3.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); // 4 MiB
1199 let second = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); // 2 MiB
1200 let third = cache3.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); // 1 MiB
1201 let ptr_second = Arc::as_ptr(&second.texture);
1202 cache3.insert(1, first, NodeId(0), 1);
1203 cache3.insert(2, second, NodeId(1), 2);
1204 cache3.insert(3, third, NodeId(2), 3);
1205 assert!(cache3.total_vram_bytes() <= budget);
1206
1207 // Bust in deterministic order: frame 1 (4 MiB) oldest, then frame 2 (2 MiB), then frame 3 (1 MiB) => 7 MiB pooled.
1208 assert_eq!(cache3.bust_frame(1), 1);
1209 assert_eq!(cache3.bust_frame(2), 1);
1210 assert_eq!(cache3.bust_frame(3), 1);
1211 assert_eq!(cache3.pooled_bytes(), 7 * 1024 * 1024);
1212
1213 // Acquiring a 4 MiB Rgba16Float (512x1024x8 = 4 MiB) misses pool and must evict oldest (frame 1's 4 MiB),
1214 // leaving frame 2 (2 MiB) + frame 3 (1 MiB) intact!
1215 let _new_f16 = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba16Float, usage);
1216 assert_eq!(cache3.pooled_bytes(), 3 * 1024 * 1024);
1217 let reused_second = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba8Unorm, usage);
1218 assert_eq!(Arc::as_ptr(&reused_second.texture), ptr_second);
1219 }
1220
1221 #[test]
1222 fn default_budget_is_768_mb_and_profiler_records_hits_misses() {
1223 let eng = Engine::new_headless().expect("gpu");
1224 let device = eng.device();
1225 let usage = NodeCache::default_texture_usage();
1226 let mut cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB);
1227 assert_eq!(cache.budget_mb(), 768);
1228 assert_eq!(cache.budget_bytes, 768 * 1024 * 1024);
1229
1230 // Cold profile: 1 miss + insert
1231 cache.begin_frame_profile();
1232 assert!(cache.get(42, NodeId(7), 10).is_none());
1233 let t = cache.acquire_texture(device, 640, 360, wgpu::TextureFormat::Rgba8Unorm, usage);
1234 cache.insert(42, t, NodeId(7), 10);
1235 let p_cold = cache.take_frame_profile().expect("profile");
1236 assert_eq!(p_cold.cache_hits, 0);
1237 assert_eq!(p_cold.cache_misses, 1);
1238 assert_eq!(p_cold.pool_misses, 1);
1239 assert_eq!(p_cold.pool_hits, 0);
1240 assert_eq!(p_cold.entries.len(), 1);
1241 assert_eq!(p_cold.entries[0].width, 640);
1242 assert_eq!(p_cold.entries[0].height, 360);
1243
1244 // Warm profile: 1 hit
1245 cache.begin_frame_profile();
1246 assert!(cache.get(42, NodeId(7), 10).is_some());
1247 let p_warm = cache.take_frame_profile().expect("profile");
1248 assert_eq!(p_warm.cache_hits, 1);
1249 assert_eq!(p_warm.cache_misses, 0);
1250 assert_eq!(p_warm.entries.len(), 1);
1251 assert!(p_warm.entries[0].cache_hit);
1252 }
1253
1254 #[test]
1255 fn oversized_texture_clamps_to_device_limit_preserving_aspect_and_tex_scale() {
1256 let eng = Engine::new_headless().expect("gpu");
1257 let device = eng.device();
1258 let max_dim = device.limits().max_texture_dimension_2d;
1259 let usage = NodeCache::default_texture_usage();
1260 let cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB);
1261
1262 let req_w = max_dim + 4096;
1263 let req_h = (max_dim + 4096) / 2;
1264 let expected_scale = max_dim as f32 / req_w as f32;
1265
1266 let t_pool = cache.acquire_texture(device, req_w, req_h, wgpu::TextureFormat::Rgba8Unorm, usage);
1267 assert_eq!(t_pool.size[0], max_dim);
1268 assert!((t_pool.size[1] as i32 - (max_dim as i32 / 2)).abs() <= 1);
1269 assert!((t_pool.tex_scale - expected_scale).abs() < 1e-5);
1270 assert_eq!(t_pool.canvas_size, t_pool.size);
1271
1272 let t_raw = crate::eval::create_texture_dod_fmt(
1273 device,
1274 [req_w, req_h],
1275 [0, 0],
1276 [req_w, req_h],
1277 BitDepth::Int8,
1278 wgpu::TextureFormat::Rgba8Unorm,
1279 77,
1280 );
1281 assert_eq!(t_raw.size, t_pool.size);
1282 assert!((t_raw.tex_scale - expected_scale).abs() < 1e-5);
1283 }
1284
1285 #[test]
1286 fn deferred_evictions_flush_into_pool_after_submit() {
1287 let eng = Engine::new_headless().expect("gpu");
1288 let device = eng.device();
1289 let usage = NodeCache::default_texture_usage();
1290 // 4 MiB budget: each 512x512 RGBA8 is 1 MiB.
1291 let mut cache = NodeCache::new(4);
1292 for i in 0..5u64 {
1293 let t = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1294 cache.insert(i, t, NodeId(i as usize), 0);
1295 }
1296 // Evicted texture is deferred until flush_pending_pool() so mid-frame uploads can't alias.
1297 assert_eq!(cache.eviction_count(), 1);
1298 assert_eq!(cache.pooled_bytes(), 0);
1299 cache.flush_pending_pool();
1300 assert_eq!(cache.pooled_bytes(), 0); // 4 MiB live + 0 pooled <= 4 MiB (budget full)
1301
1302 // With 2 MiB live and 1 evicted texture, flush moves it into pool.
1303 let mut cache2 = NodeCache::new(4);
1304 let a = cache2.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1305 let b = cache2.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1306 cache2.insert(1, a, NodeId(0), 0);
1307 cache2.insert(1, b, NodeId(0), 0); // Overwrites key 1 -> defers `a`
1308 assert_eq!(cache2.pooled_bytes(), 0);
1309 cache2.flush_pending_pool();
1310 assert_eq!(cache2.pooled_bytes(), 1024 * 1024);
1311 }
1312
1313 #[test]
1314 fn default_vram_budget_scales_sensibly_and_respects_floor() {
1315 assert_eq!(vram_budget_mb_for_ram(None), 768);
1316 assert_eq!(vram_budget_mb_for_ram(Some(0)), 768);
1317 assert_eq!(vram_budget_mb_for_ram(Some(4 * 1024)), 768);
1318 assert_eq!(vram_budget_mb_for_ram(Some(16 * 1024)), 2048);
1319 assert_eq!(vram_budget_mb_for_ram(Some(64 * 1024)), 8192);
1320 assert_eq!(vram_budget_mb_for_ram(Some(256 * 1024)), 8192);
1321 assert!(default_vram_budget_mb() >= DEFAULT_VRAM_BUDGET_MB);
1322 }
1323
1324 #[test]
1325 fn eviction_protects_sticky_and_multi_frame_entries_over_single_frame_intermediates() {
1326 let eng = Engine::new_headless().expect("gpu");
1327 let device = eng.device();
1328 let usage = NodeCache::default_texture_usage();
1329 // 3 MiB budget; each 512x512 RGBA8 texture is 1 MiB.
1330 let mut cache = NodeCache::new(3);
1331
1332 // Insert a sticky Loader texture (key 100) and hit it on frame 1 so it becomes Tier 2.
1333 let loader = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1334 cache.insert(100, loader, NodeId(0), 0);
1335 cache.mark_entry_sticky(100);
1336 assert!(cache.get(100, NodeId(0), 1).is_some());
1337
1338 // Insert a non-sticky multi-frame texture (key 200, Tier 1).
1339 let static_op = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1340 cache.insert(200, static_op, NodeId(1), 0);
1341 assert!(cache.get(200, NodeId(1), 1).is_some());
1342
1343 // Flood with newer single-frame transient intermediates (Tier 0, keys 301..=304).
1344 // Even though keys 301..=304 have newer `last_used` ticks than keys 100 and 200,
1345 // Tier 0 transient intermediates must be evicted first so the Loader (key 100) survives!
1346 for k in 301..=304u64 {
1347 let tmp = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1348 cache.insert(k, tmp, NodeId(2), 2);
1349 }
1350
1351 assert!(cache.total_vram_bytes() <= 3 * 1024 * 1024);
1352 assert!(cache.get(100, NodeId(0), 2).is_some(), "sticky multi-frame Loader must survive eviction");
1353 assert!(cache.get(200, NodeId(1), 2).is_some(), "multi-frame entry must survive ahead of Tier 0 intermediates");
1354 assert!(cache.get(301, NodeId(2), 2).is_none(), "single-frame transient intermediate must be evicted first");
1355 }
1356
1357 #[test]
1358 fn scratch_textures_recycle_into_pool_after_flush() {
1359 let eng = Engine::new_headless().expect("gpu");
1360 let device = eng.device();
1361 let mut cache = NodeCache::new(16);
1362
1363 let ptr = {
1364 let scratch = cache.acquire_texture_dod_fmt(
1365 device,
1366 [512, 512],
1367 [0, 0],
1368 [512, 512],
1369 BitDepth::Int8,
1370 wgpu::TextureFormat::Rgba8Unorm,
1371 0,
1372 );
1373 Arc::as_ptr(&scratch.texture)
1374 };
1375 // Still deferred until flush_pending_pool() so mid-frame passes cannot alias.
1376 assert_eq!(cache.pooled_bytes(), 0);
1377
1378 cache.flush_pending_pool();
1379 assert_eq!(cache.pooled_bytes(), 1024 * 1024);
1380
1381 let reused = cache.acquire_texture_dod_fmt(
1382 device,
1383 [512, 512],
1384 [0, 0],
1385 [512, 512],
1386 BitDepth::Int8,
1387 wgpu::TextureFormat::Rgba8Unorm,
1388 0,
1389 );
1390 assert_eq!(Arc::as_ptr(&reused.texture), ptr);
1391 assert_eq!(cache.pool_stats().hits, 1);
1392 }
1393
1394 #[test]
1395 fn vram_drops_increments_on_eviction_overflow_and_pool_trim() {
1396 let eng = Engine::new_headless().expect("gpu");
1397 let device = eng.device();
1398 let usage = NodeCache::default_texture_usage();
1399 // 4 MiB budget: each 512x512 RGBA8 is 1 MiB.
1400 let mut cache = NodeCache::new(4);
1401 assert_eq!(cache.vram_drops(), 0);
1402
1403 // Insert 5 entries -> 1 is evicted to pending_pool; flushing exceeds 4 MiB and drops it.
1404 for i in 0..5u64 {
1405 let t = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1406 cache.insert(i, t, NodeId(i as usize), 0);
1407 }
1408 cache.flush_pending_pool();
1409 let after_overflow = cache.vram_drops();
1410 assert!(after_overflow >= 1, "expected vram_drops >= 1 after overflow, got {after_overflow}");
1411
1412 // Lowering budget below live bytes evicts & drops entries monotonically.
1413 cache.set_budget_mb(1);
1414 assert!(cache.vram_drops() > after_overflow);
1415
1416 // Busting with 0 budget drops all remaining entries.
1417 let before_bust = cache.vram_drops();
1418 cache.set_budget_mb(0);
1419 cache.bust_all();
1420 assert!(cache.vram_drops() > before_bust);
1421 }
1422
1423 #[test]
1424 fn pooled_texture_with_aux_drops_aux_bytes_without_phantom_vram_inflation() {
1425 let eng = Engine::new_headless().expect("gpu");
1426 let device = eng.device();
1427 let usage = NodeCache::default_texture_usage();
1428 let mut cache = NodeCache::new(16);
1429
1430 // 512x512 RGBA8 = 1 MiB base; Z (R32F = 1 MiB) + Normal (RGBA16F = 2 MiB) = 3 MiB aux.
1431 let base_bytes: u64 = 512 * 512 * 4;
1432 let aux_bytes: u64 = 512 * 512 * 4 + 512 * 512 * 8;
1433 let mut t1 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1434 let ptr1 = Arc::as_ptr(&t1.texture);
1435 assert_eq!(t1.bytes, base_bytes);
1436 let make_aux = || {
1437 Arc::new(AuxChannels {
1438 z: Some(AuxChannelTex::new(device, [512, 512], wgpu::TextureFormat::R32Float, "test-z")),
1439 normal: Some(AuxChannelTex::new(device, [512, 512], wgpu::TextureFormat::Rgba16Float, "test-n")),
1440 ..Default::default()
1441 })
1442 };
1443 t1.set_aux(Some(make_aux()));
1444 assert_eq!(t1.bytes, base_bytes + aux_bytes);
1445
1446 // Live cache includes aux_bytes.
1447 cache.insert(1, t1, NodeId(0), 0);
1448 assert_eq!(cache.live_bytes(), base_bytes + aux_bytes);
1449 assert_eq!(cache.pooled_bytes(), 0);
1450 assert_eq!(cache.total_vram_bytes(), base_bytes + aux_bytes);
1451
1452 // clear_dynamic drops aux and pools ONLY base RGBA bytes.
1453 assert_eq!(cache.clear_dynamic(), 1);
1454 assert_eq!(cache.live_bytes(), 0);
1455 assert_eq!(cache.pooled_bytes(), base_bytes);
1456 assert_eq!(cache.total_vram_bytes(), base_bytes);
1457
1458 // Re-acquiring from pool returns exact base RGBA bytes with no aux.
1459 let mut t2 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1460 assert_eq!(Arc::as_ptr(&t2.texture), ptr1);
1461 assert!(t2.aux.is_none());
1462 assert_eq!(t2.bytes, base_bytes);
1463 assert_eq!(cache.pooled_bytes(), 0);
1464 assert_eq!(cache.live_bytes(), 0);
1465 assert_eq!(cache.total_vram_bytes(), 0);
1466
1467 // Re-attach aux, insert, and evict via overwrite (defer_to_pool -> flush_pending_pool).
1468 t2.set_aux(Some(make_aux()));
1469 cache.insert(2, t2, NodeId(1), 0);
1470 let t3 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1471 cache.insert(2, t3, NodeId(1), 0);
1472 assert_eq!(cache.live_bytes(), base_bytes);
1473 cache.flush_pending_pool();
1474 assert_eq!(cache.pooled_bytes(), base_bytes);
1475 assert_eq!(cache.total_vram_bytes(), base_bytes * 2);
1476
1477 // Re-acquire the deferred texture and verify base bytes again.
1478 let t4 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1479 assert_eq!(t4.bytes, base_bytes);
1480 assert_eq!(cache.pooled_bytes(), 0);
1481 assert_eq!(cache.live_bytes(), base_bytes);
1482 assert_eq!(cache.total_vram_bytes(), base_bytes);
1483 }
1484}