Skip to main content

euv_core/runtime/streaming/residency/
impl.rs

1use super::*;
2
3/// Default AAA desktop/mobile streaming budget presets for `AssetStreamBudget`.
4impl Default for AssetStreamBudget {
5    /// Creates an `AssetStreamBudget` initialized with `256 MiB` RAM, `128 MiB` VRAM, and `1.5 ms` / `4 MiB` per-frame caps.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default streaming budget configuration.
10    fn default() -> Self {
11        Self {
12            ram_budget_bytes: ASSET_STREAM_DEFAULT_RAM_BUDGET_BYTES,
13            vram_budget_bytes: ASSET_STREAM_DEFAULT_VRAM_BUDGET_BYTES,
14            max_decode_us_per_frame: ASSET_STREAM_DEFAULT_MAX_DECODE_US,
15            max_gpu_upload_bytes_per_frame: GPU_UPLOAD_BELT_MAX_BYTES_PER_FRAME,
16            max_gpu_upload_us_per_frame: GPU_UPLOAD_BELT_MAX_TIME_US_PER_FRAME,
17        }
18    }
19}
20
21/// Convenience accessors unpacking per-tier VRAM sizes and dimensions from `TextureMipSpec`.
22impl TextureMipSpec {
23    /// Returns the `MipTail` VRAM footprint in bytes.
24    ///
25    /// # Returns
26    ///
27    /// - `usize` - `MipTail` byte size.
28    #[must_use]
29    pub fn mip_tail_bytes(&self) -> usize {
30        self.get_tier_vram_bytes()[0]
31    }
32
33    /// Returns the `MidMip` VRAM footprint in bytes.
34    ///
35    /// # Returns
36    ///
37    /// - `usize` - `MidMip` byte size.
38    #[must_use]
39    pub fn mid_mip_bytes(&self) -> usize {
40        self.get_tier_vram_bytes()[1]
41    }
42
43    /// Returns the `FullRes` VRAM footprint in bytes.
44    ///
45    /// # Returns
46    ///
47    /// - `usize` - `FullRes` byte size.
48    #[must_use]
49    pub fn full_res_bytes(&self) -> usize {
50        self.get_tier_vram_bytes()[2]
51    }
52
53    /// Returns the full-resolution texture width in texels.
54    ///
55    /// # Returns
56    ///
57    /// - `u32` - Width in texels.
58    #[must_use]
59    pub fn width(&self) -> u32 {
60        self.get_dimensions()[0]
61    }
62
63    /// Returns the full-resolution texture height in texels.
64    ///
65    /// # Returns
66    ///
67    /// - `u32` - Height in texels.
68    #[must_use]
69    pub fn height(&self) -> u32 {
70        self.get_dimensions()[1]
71    }
72}
73
74/// Default empty `ProgressiveResidencyPool` using default streaming budgets.
75impl Default for ProgressiveResidencyPool {
76    /// Creates an empty `ProgressiveResidencyPool` with default RAM/VRAM ceilings.
77    ///
78    /// # Returns
79    ///
80    /// - `Self` - Empty residency pool.
81    fn default() -> Self {
82        Self::new(
83            AssetStreamBudget::default(),
84            ResourceOwnerId::new(
85                ResourceOwnerKind::RenderCache,
86                RESIDENCY_DEFAULT_OWNER_ID,
87                1,
88            ),
89        )
90    }
91}
92
93/// O(1) 2-hand Clock-LRU progressive mipmap residency, strict budget enforcement, and `ResourceAccountant` lifecycle management.
94impl ProgressiveResidencyPool {
95    /// Creates an empty `ProgressiveResidencyPool` governed by `budget` and attributed to `owner`.
96    ///
97    /// # Arguments
98    ///
99    /// - `AssetStreamBudget` - Hard RAM and VRAM ceilings.
100    /// - `ResourceOwnerId` - Authoritative resource owner registered in `ResourceAccountant`.
101    ///
102    /// # Returns
103    ///
104    /// - `Self` - Initialized residency pool.
105    #[must_use]
106    pub fn new(budget: AssetStreamBudget, owner: ResourceOwnerId) -> Self {
107        Self {
108            budget,
109            owner,
110            slots: Vec::new(),
111            free_slots: Vec::new(),
112            key_to_slot: HashMap::new(),
113            scan_hand: 0,
114            evict_hand: 0,
115            ram_used_bytes: 0,
116            vram_used_bytes: 0,
117            textures_mip_tail: 0,
118            textures_mid_mip: 0,
119            textures_full_res: 0,
120            offscreen_demotable_textures: 0,
121            evictions_to_mip_tail: 0,
122            full_evictions: 0,
123        }
124    }
125
126    /// Returns the active RAM/VRAM budget configuration.
127    ///
128    /// # Returns
129    ///
130    /// - `AssetStreamBudget` - Active memory ceilings.
131    #[must_use]
132    pub fn budget(&self) -> AssetStreamBudget {
133        let Self { budget, .. } = self;
134        *budget
135    }
136
137    /// Returns the authoritative `ResourceOwnerId` used for `ResourceAccountant` tracking.
138    ///
139    /// # Returns
140    ///
141    /// - `ResourceOwnerId` - Owner identifier.
142    #[must_use]
143    pub fn owner(&self) -> ResourceOwnerId {
144        let Self { owner, .. } = self;
145        *owner
146    }
147
148    /// Replaces the active memory budget and immediately demotes/evicts down to the new ceilings.
149    ///
150    /// # Arguments
151    ///
152    /// - `AssetStreamBudget` - Updated RAM and VRAM ceilings.
153    /// - `&mut ResourceAccountant` - Resource accountant receiving release/update notifications.
154    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after enforcement.
155    pub fn set_budget(
156        &mut self,
157        next_budget: AssetStreamBudget,
158        accountant: &mut ResourceAccountant,
159        telemetry: &StreamingTelemetryCounters,
160    ) {
161        let Self { budget, .. } = self;
162        *budget = next_budget;
163        let _: usize = self.enforce_budgets(
164            next_budget.get_ram_budget_bytes(),
165            next_budget.get_vram_budget_bytes(),
166            accountant,
167            telemetry,
168        );
169        self.sync_telemetry(telemetry);
170    }
171
172    /// Synchronizes exact live RAM, VRAM, and texture tier counters into `telemetry`.
173    ///
174    /// # Arguments
175    ///
176    /// - `&StreamingTelemetryCounters` - Lock-free telemetry counters to update.
177    pub fn sync_telemetry(&self, telemetry: &StreamingTelemetryCounters) {
178        let Self {
179            ram_used_bytes,
180            vram_used_bytes,
181            textures_mip_tail,
182            textures_mid_mip,
183            textures_full_res,
184            ..
185        } = self;
186        telemetry.set_memory_usage(*ram_used_bytes, *vram_used_bytes);
187        telemetry.set_texture_tier_counts(
188            *textures_mip_tail,
189            *textures_mid_mip,
190            *textures_full_res,
191        );
192    }
193
194    /// Returns the current resident RAM bytes.
195    ///
196    /// # Returns
197    ///
198    /// - `usize` - Live RAM bytes.
199    #[must_use]
200    pub fn ram_used_bytes(&self) -> usize {
201        let Self { ram_used_bytes, .. } = self;
202        *ram_used_bytes
203    }
204
205    /// Returns the current resident VRAM bytes.
206    ///
207    /// # Returns
208    ///
209    /// - `usize` - Live VRAM bytes.
210    #[must_use]
211    pub fn vram_used_bytes(&self) -> usize {
212        let Self {
213            vram_used_bytes, ..
214        } = self;
215        *vram_used_bytes
216    }
217
218    /// Returns the total count of live resident slots.
219    ///
220    /// # Returns
221    ///
222    /// - `usize` - Live slot count.
223    #[must_use]
224    pub fn live_count(&self) -> usize {
225        let Self { key_to_slot, .. } = self;
226        key_to_slot.len()
227    }
228
229    /// Returns the cumulative count of cold textures demoted to `MipTail`.
230    ///
231    /// # Returns
232    ///
233    /// - `u64` - Cumulative mip-tail demotion count.
234    #[must_use]
235    pub fn evictions_to_mip_tail(&self) -> u64 {
236        let Self {
237            evictions_to_mip_tail,
238            ..
239        } = self;
240        *evictions_to_mip_tail
241    }
242
243    /// Returns `(textures_mip_tail, textures_mid_mip, textures_full_res)`.
244    ///
245    /// # Returns
246    ///
247    /// - `(u32, u32, u32)` - Live counts of textures across the 3 resident tiers.
248    #[must_use]
249    pub fn texture_tier_counts(&self) -> (u32, u32, u32) {
250        let Self {
251            textures_mip_tail,
252            textures_mid_mip,
253            textures_full_res,
254            ..
255        } = self;
256        (*textures_mip_tail, *textures_mid_mip, *textures_full_res)
257    }
258
259    /// Looks up the current progressive residency tier for `key_hash`.
260    ///
261    /// # Arguments
262    ///
263    /// - `u64` - Deterministic 64-bit asset key hash.
264    ///
265    /// # Returns
266    ///
267    /// - `TextureResidencyTier` - Current tier (`Unloaded` when absent).
268    #[must_use]
269    pub fn texture_tier(&self, key_hash: u64) -> TextureResidencyTier {
270        let Self {
271            slots, key_to_slot, ..
272        } = self;
273        let Some(&slot_idx) = key_to_slot.get(&key_hash) else {
274            return TextureResidencyTier::Unloaded;
275        };
276        slots
277            .get(slot_idx)
278            .and_then(|slot_opt: &Option<ResidencySlot>| slot_opt.as_ref())
279            .map_or(TextureResidencyTier::Unloaded, |slot: &ResidencySlot| {
280                slot.tier
281            })
282    }
283
284    /// Returns `true` when `key_hash` is currently resident in this pool.
285    ///
286    /// # Arguments
287    ///
288    /// - `u64` - Deterministic 64-bit asset key hash.
289    ///
290    /// # Returns
291    ///
292    /// - `bool` - Whether the asset is resident.
293    #[must_use]
294    pub fn contains(&self, key_hash: u64) -> bool {
295        let Self { key_to_slot, .. } = self;
296        key_to_slot.contains_key(&key_hash)
297    }
298
299    /// Returns the resident full-resolution dimensions `(width, height)` for a tracked texture, if present.
300    ///
301    /// # Arguments
302    ///
303    /// - `u64` - Deterministic 64-bit asset key hash.
304    ///
305    /// # Returns
306    ///
307    /// - `Option<(u32, u32)>` - Texture width and height in texels when resident.
308    #[must_use]
309    pub fn texture_dimensions(&self, key_hash: u64) -> Option<(u32, u32)> {
310        let Self {
311            slots, key_to_slot, ..
312        } = self;
313        let &slot_idx = key_to_slot.get(&key_hash)?;
314        let slot: &ResidencySlot = slots.get(slot_idx)?.as_ref()?;
315        if slot.kind == ResidencyAssetKind::Texture {
316            Some((slot.width, slot.height))
317        } else {
318            None
319        }
320    }
321
322    /// Returns the resident CPU RAM payload slice for `key_hash`, if present.
323    ///
324    /// # Arguments
325    ///
326    /// - `u64` - Deterministic 64-bit asset key hash.
327    ///
328    /// # Returns
329    ///
330    /// - `Option<&[u8]>` - Borrowed RAM payload bytes when resident.
331    #[must_use]
332    pub fn ram_payload(&self, key_hash: u64) -> Option<&[u8]> {
333        let Self {
334            slots, key_to_slot, ..
335        } = self;
336        let &slot_idx = key_to_slot.get(&key_hash)?;
337        let slot: &ResidencySlot = slots.get(slot_idx)?.as_ref()?;
338        Some(slot.ram_payload.as_slice())
339    }
340
341    /// Adjusts live texture tier counters when a texture transitions from `prev` to `next`.
342    ///
343    /// # Arguments
344    ///
345    /// - `TextureResidencyTier` - Previous tier (`Unloaded` for newly inserted textures).
346    /// - `TextureResidencyTier` - New tier (`Unloaded` for evicted textures).
347    fn adjust_tier_counters(&mut self, prev: TextureResidencyTier, next: TextureResidencyTier) {
348        let Self {
349            textures_mip_tail,
350            textures_mid_mip,
351            textures_full_res,
352            ..
353        } = self;
354        match prev {
355            TextureResidencyTier::MipTail => {
356                *textures_mip_tail = textures_mip_tail.saturating_sub(1);
357            }
358            TextureResidencyTier::MidMip => {
359                *textures_mid_mip = textures_mid_mip.saturating_sub(1);
360            }
361            TextureResidencyTier::FullRes => {
362                *textures_full_res = textures_full_res.saturating_sub(1);
363            }
364            TextureResidencyTier::Unloaded => {}
365        }
366        match next {
367            TextureResidencyTier::MipTail => {
368                *textures_mip_tail = textures_mip_tail.saturating_add(1);
369            }
370            TextureResidencyTier::MidMip => {
371                *textures_mid_mip = textures_mid_mip.saturating_add(1);
372            }
373            TextureResidencyTier::FullRes => {
374                *textures_full_res = textures_full_res.saturating_add(1);
375            }
376            TextureResidencyTier::Unloaded => {}
377        }
378    }
379
380    /// Allocates a free slot index or appends a new slot, keeping the 2-hand Clock-LRU pointers aligned.
381    ///
382    /// # Returns
383    ///
384    /// - `usize` - Allocated slot index.
385    fn alloc_slot(&mut self) -> usize {
386        let Self {
387            slots,
388            free_slots,
389            scan_hand,
390            evict_hand,
391            ..
392        } = self;
393        if let Some(reused) = free_slots.pop() {
394            return reused;
395        }
396        let idx: usize = slots.len();
397        slots.push(None);
398        let total: usize = slots.len();
399        if total == 1 {
400            *evict_hand = 0;
401            *scan_hand = 0;
402        } else {
403            let lead: usize = clock_lead_distance(total);
404            *scan_hand = (*evict_hand + lead) % total;
405        }
406        idx
407    }
408
409    /// Releases `ResourceAccountant` RAM and VRAM handles associated with `slot`.
410    ///
411    /// # Arguments
412    ///
413    /// - `&ResidencySlot` - Slot being evicted or updated.
414    /// - `&mut ResourceAccountant` - Authoritative resource accountant.
415    fn release_slot_accounting(slot: &ResidencySlot, accountant: &mut ResourceAccountant) {
416        if slot.ram_account_handle != 0 {
417            let _: bool = accountant.release_resource(
418                TrackedResourceKind::CacheAllocation,
419                slot.ram_account_handle,
420            );
421        }
422        if slot.vram_account_handle != 0 {
423            let vram_kind: TrackedResourceKind = if slot.kind == ResidencyAssetKind::Texture {
424                TrackedResourceKind::GpuTexture
425            } else {
426                TrackedResourceKind::GpuBuffer
427            };
428            let _: bool = accountant.release_resource(vram_kind, slot.vram_account_handle);
429        }
430    }
431
432    /// Selects a cold demotable texture slot (`FullRes` or `MidMip`) in O(1) amortized time using 2-hand Clock-LRU.
433    ///
434    /// # Arguments
435    ///
436    /// - `bool` - When `true`, skips visible textures on the first scan pass so off-screen textures demote first.
437    ///
438    /// # Returns
439    ///
440    /// - `Option<usize>` - Selected victim slot index or `None` if no demotable texture exists.
441    fn clock_select_demotable_texture(&mut self, prefer_offscreen: bool) -> Option<usize> {
442        let Self {
443            slots,
444            scan_hand,
445            evict_hand,
446            ..
447        } = self;
448        let len: usize = slots.len();
449        if len == 0 {
450            return None;
451        }
452        if *evict_hand >= len {
453            *evict_hand = 0;
454        }
455        let lead: usize = clock_lead_distance(len);
456        if *scan_hand >= len {
457            *scan_hand = (*evict_hand + lead) % len;
458        }
459        let max_steps: usize = len.saturating_mul(2);
460        for _ in 0..max_steps {
461            let scan_idx: usize = *scan_hand;
462            *scan_hand = (scan_idx + 1) % len;
463            if let Some(scan_slot) = slots[scan_idx].as_mut()
464                && !scan_slot.pinned
465            {
466                scan_slot.referenced = false;
467            }
468            let cand_idx: usize = *evict_hand;
469            *evict_hand = (cand_idx + 1) % len;
470            let Some(slot) = slots[cand_idx].as_mut() else {
471                continue;
472            };
473            if slot.pinned || slot.kind != ResidencyAssetKind::Texture {
474                continue;
475            }
476            let is_demotable: bool = matches!(
477                slot.tier,
478                TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
479            );
480            if !is_demotable {
481                continue;
482            }
483            if prefer_offscreen && slot.visible {
484                continue;
485            }
486            if !slot.referenced {
487                return Some(cand_idx);
488            }
489            slot.referenced = false;
490        }
491        None
492    }
493
494    /// Selects a cold evictable slot freeing RAM or VRAM in O(1) amortized time using 2-hand Clock-LRU.
495    ///
496    /// # Arguments
497    ///
498    /// - `bool` - Whether the victim must release RAM bytes.
499    /// - `bool` - Whether the victim must release VRAM bytes.
500    /// - `bool` - When `false`, protects visible textures from full eviction (never blanking visible surfaces).
501    ///
502    /// # Returns
503    ///
504    /// - `Option<usize>` - Selected victim slot index or `None` if all matching slots are pinned or protected.
505    fn clock_select_evictable_slot(
506        &mut self,
507        need_ram: bool,
508        need_vram: bool,
509        allow_visible_textures: bool,
510    ) -> Option<usize> {
511        let Self {
512            slots,
513            scan_hand,
514            evict_hand,
515            ..
516        } = self;
517        let len: usize = slots.len();
518        if len == 0 {
519            return None;
520        }
521        if *evict_hand >= len {
522            *evict_hand = 0;
523        }
524        let lead: usize = clock_lead_distance(len);
525        if *scan_hand >= len {
526            *scan_hand = (*evict_hand + lead) % len;
527        }
528        let max_steps: usize = len.saturating_mul(2);
529        for _ in 0..max_steps {
530            let scan_idx: usize = *scan_hand;
531            *scan_hand = (scan_idx + 1) % len;
532            if let Some(scan_slot) = slots[scan_idx].as_mut()
533                && !scan_slot.pinned
534            {
535                scan_slot.referenced = false;
536            }
537            let cand_idx: usize = *evict_hand;
538            *evict_hand = (cand_idx + 1) % len;
539            let Some(slot) = slots[cand_idx].as_mut() else {
540                continue;
541            };
542            if slot.pinned {
543                continue;
544            }
545            if !allow_visible_textures && slot.kind == ResidencyAssetKind::Texture && slot.visible {
546                continue;
547            }
548            let frees_ram: bool = need_ram && slot.ram_bytes > 0;
549            let frees_vram: bool = need_vram && slot.vram_bytes > 0;
550            if !frees_ram && !frees_vram {
551                continue;
552            }
553            if !slot.referenced {
554                return Some(cand_idx);
555            }
556            slot.referenced = false;
557        }
558        None
559    }
560
561    /// Demotes texture slot `slot_idx` one residency step (`FullRes -> MidMip -> MipTail`) and updates `ResourceAccountant`.
562    ///
563    /// # Arguments
564    ///
565    /// - `usize` - Resident texture slot index.
566    /// - `&mut ResourceAccountant` - Resource accountant updating live VRAM bytes.
567    /// - `&StreamingTelemetryCounters` - Telemetry counters recording mip-tail demotions.
568    ///
569    /// # Returns
570    ///
571    /// - `bool` - `true` when the texture was demoted and released VRAM bytes.
572    fn demote_texture_slot(
573        &mut self,
574        slot_idx: usize,
575        accountant: &mut ResourceAccountant,
576        telemetry: &StreamingTelemetryCounters,
577    ) -> bool {
578        let owner: ResourceOwnerId = self.owner();
579        let (prev_tier, next_tier, old_vram, new_vram, old_handle, retention): (
580            TextureResidencyTier,
581            TextureResidencyTier,
582            usize,
583            usize,
584            u64,
585            ResourceRetentionClass,
586        ) = {
587            let Self { slots, .. } = self;
588            let Some(Some(slot)) = slots.get(slot_idx) else {
589                return false;
590            };
591            let Some(next_tier) = demote_tier_one_step(slot.tier) else {
592                return false;
593            };
594            let next_vram: usize = tier_vram_bytes(
595                next_tier,
596                slot.mip_tail_vram_bytes,
597                slot.mid_mip_vram_bytes,
598                slot.full_res_vram_bytes,
599            );
600            let retention: ResourceRetentionClass = if slot.pinned {
601                ResourceRetentionClass::Active
602            } else {
603                ResourceRetentionClass::ExpectedRetained
604            };
605            (
606                slot.tier,
607                next_tier,
608                slot.vram_bytes,
609                next_vram,
610                slot.vram_account_handle,
611                retention,
612            )
613        };
614        if old_handle != 0 {
615            let _: bool = accountant.release_resource(TrackedResourceKind::GpuTexture, old_handle);
616        }
617        let new_handle: u64 = if new_vram > 0 {
618            accountant.register_auto_handle(
619                owner,
620                TrackedResourceKind::GpuTexture,
621                new_vram,
622                retention,
623            )
624        } else {
625            0
626        };
627        {
628            let Self {
629                slots,
630                vram_used_bytes,
631                offscreen_demotable_textures,
632                evictions_to_mip_tail,
633                ..
634            } = self;
635            if let Some(Some(slot)) = slots.get_mut(slot_idx) {
636                let was_offscreen_demotable: bool = !slot.visible
637                    && matches!(
638                        slot.tier,
639                        TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
640                    );
641                slot.tier = next_tier;
642                slot.vram_bytes = new_vram;
643                slot.vram_account_handle = new_handle;
644                let now_offscreen_demotable: bool = !slot.visible
645                    && matches!(
646                        next_tier,
647                        TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
648                    );
649                if was_offscreen_demotable && !now_offscreen_demotable {
650                    *offscreen_demotable_textures = offscreen_demotable_textures.saturating_sub(1);
651                }
652            }
653            *vram_used_bytes = vram_used_bytes
654                .saturating_sub(old_vram)
655                .saturating_add(new_vram);
656            if next_tier == TextureResidencyTier::MipTail {
657                *evictions_to_mip_tail = evictions_to_mip_tail.saturating_add(1);
658                telemetry.add_eviction_to_mip_tail();
659            }
660        }
661        self.adjust_tier_counters(prev_tier, next_tier);
662        true
663    }
664
665    /// Fully evicts slot `slot_idx`, releasing all RAM and VRAM handles from `accountant`.
666    ///
667    /// # Arguments
668    ///
669    /// - `usize` - Resident slot index to remove.
670    /// - `&mut ResourceAccountant` - Resource accountant receiving release notifications.
671    ///
672    /// # Returns
673    ///
674    /// - `bool` - `true` when an occupied slot was removed.
675    fn evict_slot(&mut self, slot_idx: usize, accountant: &mut ResourceAccountant) -> bool {
676        let removed: Option<ResidencySlot> = {
677            let Self {
678                slots,
679                free_slots,
680                key_to_slot,
681                ram_used_bytes,
682                vram_used_bytes,
683                offscreen_demotable_textures,
684                full_evictions,
685                ..
686            } = self;
687            let Some(slot) = slots.get_mut(slot_idx).and_then(Option::take) else {
688                return false;
689            };
690            let _: Option<usize> = key_to_slot.remove(&slot.key_hash);
691            free_slots.push(slot_idx);
692            *ram_used_bytes = ram_used_bytes.saturating_sub(slot.ram_bytes);
693            *vram_used_bytes = vram_used_bytes.saturating_sub(slot.vram_bytes);
694            *full_evictions = full_evictions.saturating_add(1);
695            if slot.kind == ResidencyAssetKind::Texture
696                && !slot.visible
697                && matches!(
698                    slot.tier,
699                    TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
700                )
701            {
702                *offscreen_demotable_textures = offscreen_demotable_textures.saturating_sub(1);
703            }
704            Some(slot)
705        };
706        if let Some(slot) = removed {
707            if slot.kind == ResidencyAssetKind::Texture {
708                self.adjust_tier_counters(slot.tier, TextureResidencyTier::Unloaded);
709            }
710            Self::release_slot_accounting(&slot, accountant);
711            true
712        } else {
713            false
714        }
715    }
716
717    /// Enforces `target_ram` and `target_vram` ceilings using 2-hand Clock-LRU, demoting cold textures to `MipTail` before evicting off-screen entries.
718    ///
719    /// # Arguments
720    ///
721    /// - `usize` - Target maximum RAM bytes.
722    /// - `usize` - Target maximum VRAM bytes.
723    /// - `&mut ResourceAccountant` - Resource accountant receiving release updates.
724    /// - `&StreamingTelemetryCounters` - Telemetry counters receiving demotion increments.
725    ///
726    /// # Returns
727    ///
728    /// - `usize` - Total demotions and evictions performed.
729    pub fn enforce_budgets(
730        &mut self,
731        target_ram: usize,
732        target_vram: usize,
733        accountant: &mut ResourceAccountant,
734        telemetry: &StreamingTelemetryCounters,
735    ) -> usize {
736        let mut actions: usize = 0;
737        while self.vram_used_bytes() > target_vram {
738            let (has_demotable, has_offscreen_demotable): (bool, bool) = {
739                let Self {
740                    textures_mid_mip,
741                    textures_full_res,
742                    offscreen_demotable_textures,
743                    ..
744                } = self;
745                (
746                    *textures_mid_mip > 0 || *textures_full_res > 0,
747                    *offscreen_demotable_textures > 0,
748                )
749            };
750            if has_offscreen_demotable
751                && let Some(victim) = self.clock_select_demotable_texture(true)
752                && self.demote_texture_slot(victim, accountant, telemetry)
753            {
754                actions = actions.saturating_add(1);
755                continue;
756            }
757            if has_demotable
758                && let Some(victim) = self.clock_select_demotable_texture(false)
759                && self.demote_texture_slot(victim, accountant, telemetry)
760            {
761                actions = actions.saturating_add(1);
762                continue;
763            }
764            if let Some(victim) = self.clock_select_evictable_slot(false, true, false)
765                && self.evict_slot(victim, accountant)
766            {
767                actions = actions.saturating_add(1);
768                continue;
769            }
770            break;
771        }
772        while self.ram_used_bytes() > target_ram {
773            if let Some(victim) = self.clock_select_evictable_slot(true, false, false)
774                && self.evict_slot(victim, accountant)
775            {
776                actions = actions.saturating_add(1);
777                continue;
778            }
779            break;
780        }
781        self.sync_telemetry(telemetry);
782        actions
783    }
784
785    /// Binds a texture instantly at `TextureResidencyTier::MipTail` from the `.euvpak` Mip-Tail Superblock to eliminate blank pop-in.
786    ///
787    /// # Arguments
788    ///
789    /// - `TextureMipSpec` - Progressive texture descriptor.
790    /// - `Vec<u8>` - Compact `16x16`/`32x32` RGBA8 mip-tail texels.
791    /// - `&mut ResourceAccountant` - Authoritative resource accountant.
792    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after admission.
793    ///
794    /// # Returns
795    ///
796    /// - `Result<GpuTextureMipUpload, String>` - Ready Frame-1 mip-tail GPU upload payload or budget error.
797    pub fn bind_texture_mip_tail(
798        &mut self,
799        spec: TextureMipSpec,
800        mip_tail_rgba8: Vec<u8>,
801        accountant: &mut ResourceAccountant,
802        telemetry: &StreamingTelemetryCounters,
803    ) -> Result<GpuTextureMipUpload, String> {
804        let key_hash: u64 = spec.get_key_hash();
805        let mip_tail_bytes: usize = spec
806            .mip_tail_bytes()
807            .max(mip_tail_rgba8.len())
808            .max(RESIDENCY_DEFAULT_MIP_TAIL_BYTES.min(mip_tail_rgba8.len().max(64)));
809        let mid_mip_bytes: usize = spec.mid_mip_bytes().max(mip_tail_bytes);
810        let full_res_bytes: usize = spec.full_res_bytes().max(mid_mip_bytes);
811        let vram_cap: usize = self.budget().get_vram_budget_bytes();
812        if mip_tail_bytes > vram_cap {
813            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
814        }
815        let existing_slot: Option<usize> = {
816            let Self { key_to_slot, .. } = self;
817            key_to_slot.get(&key_hash).copied()
818        };
819        if let Some(slot_idx) = existing_slot {
820            let Self { slots, .. } = self;
821            if let Some(Some(slot)) = slots.get_mut(slot_idx) {
822                slot.referenced = true;
823                slot.mip_tail_rgba8 = mip_tail_rgba8.clone();
824                let clamp: u8 = min_lod_clamp_for_tier(slot.tier, slot.total_mip_levels);
825                let tail_side: u32 = ((mip_tail_rgba8.len() / 4) as f32).sqrt().max(1.0) as u32;
826                return Ok(GpuTextureMipUpload {
827                    texture_slot: slot.texture_slot,
828                    mip_level: slot.total_mip_levels.saturating_sub(1),
829                    total_mip_levels: slot.total_mip_levels,
830                    is_srgb: slot.is_srgb,
831                    min_lod_clamp: clamp,
832                    width: tail_side,
833                    height: tail_side,
834                    rgba8: mip_tail_rgba8,
835                });
836            }
837        }
838        let target_vram: usize = vram_cap.saturating_sub(mip_tail_bytes);
839        let _: usize = self.enforce_budgets(
840            self.budget().get_ram_budget_bytes(),
841            target_vram,
842            accountant,
843            telemetry,
844        );
845        if self.vram_used_bytes().saturating_add(mip_tail_bytes) > vram_cap {
846            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
847        }
848        let owner: ResourceOwnerId = self.owner();
849        let vram_handle: u64 = accountant.register_auto_handle(
850            owner,
851            TrackedResourceKind::GpuTexture,
852            mip_tail_bytes,
853            ResourceRetentionClass::ExpectedRetained,
854        );
855        let slot_idx: usize = self.alloc_slot();
856        let total_mips: u8 = spec.get_total_mip_levels().max(1);
857        let entry: ResidencySlot = ResidencySlot {
858            key_hash,
859            kind: ResidencyAssetKind::Texture,
860            texture_slot: spec.get_texture_slot(),
861            tier: TextureResidencyTier::MipTail,
862            mip_tail_vram_bytes: mip_tail_bytes,
863            mid_mip_vram_bytes: mid_mip_bytes,
864            full_res_vram_bytes: full_res_bytes,
865            ram_bytes: 0,
866            vram_bytes: mip_tail_bytes,
867            ram_account_handle: 0,
868            vram_account_handle: vram_handle,
869            referenced: false,
870            visible: true,
871            pinned: false,
872            width: spec.width().max(1),
873            height: spec.height().max(1),
874            total_mip_levels: total_mips,
875            is_srgb: spec.get_is_srgb(),
876            mip_tail_rgba8: mip_tail_rgba8.clone(),
877            ram_payload: Vec::new(),
878        };
879        {
880            let Self {
881                slots,
882                key_to_slot,
883                vram_used_bytes,
884                ..
885            } = self;
886            slots[slot_idx] = Some(entry);
887            let _: Option<usize> = key_to_slot.insert(key_hash, slot_idx);
888            *vram_used_bytes = vram_used_bytes.saturating_add(mip_tail_bytes);
889        }
890        self.adjust_tier_counters(
891            TextureResidencyTier::Unloaded,
892            TextureResidencyTier::MipTail,
893        );
894        self.sync_telemetry(telemetry);
895        let tail_side: u32 = ((mip_tail_rgba8.len() / 4) as f32).sqrt().max(1.0) as u32;
896        Ok(GpuTextureMipUpload {
897            texture_slot: spec.get_texture_slot(),
898            mip_level: total_mips.saturating_sub(1),
899            total_mip_levels: total_mips,
900            is_srgb: spec.get_is_srgb(),
901            min_lod_clamp: total_mips.saturating_sub(1),
902            width: tail_side,
903            height: tail_side,
904            rgba8: mip_tail_rgba8,
905        })
906    }
907
908    /// Promotes a texture toward `desired_tier` while strictly respecting the VRAM ceiling (gracefully capping at a lower non-blank tier if needed).
909    ///
910    /// # Arguments
911    ///
912    /// - `TextureMipSpec` - Progressive texture descriptor.
913    /// - `TextureResidencyTier` - Desired target residency tier.
914    /// - `Vec<u8>` - Decoded RGBA8 texels for the promoted mip level.
915    /// - `&mut ResourceAccountant` - Authoritative resource accountant.
916    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after promotion.
917    ///
918    /// # Returns
919    ///
920    /// - `Result<(TextureResidencyTier, Option<GpuTextureMipUpload>), String>` - Effective admitted tier and optional GPU mip upload.
921    pub fn promote_texture_tier(
922        &mut self,
923        spec: TextureMipSpec,
924        desired_tier: TextureResidencyTier,
925        rgba8: Vec<u8>,
926        accountant: &mut ResourceAccountant,
927        telemetry: &StreamingTelemetryCounters,
928    ) -> Result<(TextureResidencyTier, Option<GpuTextureMipUpload>), String> {
929        let key_hash: u64 = spec.get_key_hash();
930        if !self.contains(key_hash) {
931            let tail_len: usize = spec.mip_tail_bytes().max(64).min(rgba8.len().max(64));
932            let tail_buf: Vec<u8> = if rgba8.len() >= tail_len {
933                rgba8[..tail_len].to_vec()
934            } else {
935                rgba8.clone()
936            };
937            let first_upload: GpuTextureMipUpload =
938                self.bind_texture_mip_tail(spec, tail_buf, accountant, telemetry)?;
939            if desired_tier == TextureResidencyTier::MipTail {
940                return Ok((TextureResidencyTier::MipTail, Some(first_upload)));
941            }
942        }
943        let Some(&slot_idx) = ({
944            let Self { key_to_slot, .. } = self;
945            key_to_slot.get(&key_hash)
946        }) else {
947            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
948        };
949        let (prev_tier, prev_vram, mip_tail_b, mid_mip_b, full_res_b, old_handle, total_mips): (
950            TextureResidencyTier,
951            usize,
952            usize,
953            usize,
954            usize,
955            u64,
956            u8,
957        ) = {
958            let Self { slots, .. } = self;
959            let Some(Some(slot)) = slots.get_mut(slot_idx) else {
960                return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
961            };
962            slot.referenced = true;
963            slot.visible = true;
964            (
965                slot.tier,
966                slot.vram_bytes,
967                slot.mip_tail_vram_bytes,
968                slot.mid_mip_vram_bytes.max(spec.mid_mip_bytes()),
969                slot.full_res_vram_bytes.max(spec.full_res_bytes()),
970                slot.vram_account_handle,
971                slot.total_mip_levels,
972            )
973        };
974        if (desired_tier as u8) <= (prev_tier as u8) {
975            return Ok((prev_tier, None));
976        }
977        let vram_cap: usize = self.budget().get_vram_budget_bytes();
978        let ram_cap: usize = self.budget().get_ram_budget_bytes();
979        let candidates: [TextureResidencyTier; 3] = match desired_tier {
980            TextureResidencyTier::FullRes => [
981                TextureResidencyTier::FullRes,
982                TextureResidencyTier::MidMip,
983                TextureResidencyTier::MipTail,
984            ],
985            TextureResidencyTier::MidMip => [
986                TextureResidencyTier::MidMip,
987                TextureResidencyTier::MipTail,
988                TextureResidencyTier::MipTail,
989            ],
990            TextureResidencyTier::MipTail | TextureResidencyTier::Unloaded => [
991                TextureResidencyTier::MipTail,
992                TextureResidencyTier::MipTail,
993                TextureResidencyTier::MipTail,
994            ],
995        };
996        let mut chosen_tier: TextureResidencyTier = prev_tier;
997        let mut chosen_vram: usize = prev_vram;
998        for cand_tier in candidates {
999            if (cand_tier as u8) <= (prev_tier as u8) {
1000                break;
1001            }
1002            let cand_vram: usize = tier_vram_bytes(cand_tier, mip_tail_b, mid_mip_b, full_res_b);
1003            if cand_vram > vram_cap {
1004                continue;
1005            }
1006            let delta: usize = cand_vram.saturating_sub(prev_vram);
1007            let target_vram: usize = vram_cap.saturating_sub(delta);
1008            let _: usize = self.enforce_budgets(ram_cap, target_vram, accountant, telemetry);
1009            if self.vram_used_bytes().saturating_add(delta) <= vram_cap {
1010                chosen_tier = cand_tier;
1011                chosen_vram = cand_vram;
1012                break;
1013            }
1014        }
1015        if chosen_tier == prev_tier {
1016            return Ok((prev_tier, None));
1017        }
1018        let owner: ResourceOwnerId = self.owner();
1019        if old_handle != 0 {
1020            let _: bool = accountant.release_resource(TrackedResourceKind::GpuTexture, old_handle);
1021        }
1022        let new_handle: u64 = accountant.register_auto_handle(
1023            owner,
1024            TrackedResourceKind::GpuTexture,
1025            chosen_vram,
1026            ResourceRetentionClass::ExpectedRetained,
1027        );
1028        {
1029            let Self {
1030                slots,
1031                vram_used_bytes,
1032                ..
1033            } = self;
1034            if let Some(Some(slot)) = slots.get_mut(slot_idx) {
1035                slot.tier = chosen_tier;
1036                slot.mid_mip_vram_bytes = mid_mip_b;
1037                slot.full_res_vram_bytes = full_res_b;
1038                slot.vram_bytes = chosen_vram;
1039                slot.vram_account_handle = new_handle;
1040                slot.referenced = true;
1041            }
1042            *vram_used_bytes = vram_used_bytes
1043                .saturating_sub(prev_vram)
1044                .saturating_add(chosen_vram);
1045        }
1046        self.adjust_tier_counters(prev_tier, chosen_tier);
1047        self.sync_telemetry(telemetry);
1048        let mip_level: u8 = min_lod_clamp_for_tier(chosen_tier, total_mips);
1049        let mip_width: u32 = (spec.width() >> mip_level).max(1);
1050        let mip_height: u32 = (spec.height() >> mip_level).max(1);
1051        Ok((
1052            chosen_tier,
1053            Some(GpuTextureMipUpload {
1054                texture_slot: spec.get_texture_slot(),
1055                mip_level,
1056                total_mip_levels: total_mips,
1057                is_srgb: spec.get_is_srgb(),
1058                min_lod_clamp: mip_level,
1059                width: mip_width,
1060                height: mip_height,
1061                rgba8,
1062            }),
1063        ))
1064    }
1065
1066    /// Admits a decoded non-texture asset (mesh, audio, font, shader cache, or raw bytes) under strict RAM/VRAM ceilings.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// - `u64` - Deterministic 64-bit asset key hash.
1071    /// - `ResidencyAssetKind` - Semantic asset category.
1072    /// - `Vec<u8>` - Decoded CPU RAM payload bytes.
1073    /// - `usize` - Optional GPU VRAM byte footprint (e.g. mesh VBO/IBO size).
1074    /// - `&mut ResourceAccountant` - Authoritative resource accountant.
1075    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after admission.
1076    ///
1077    /// # Returns
1078    ///
1079    /// - `Result<(), String>` - `Ok(())` once resident or error when exceeding total capacity.
1080    pub fn admit_asset(
1081        &mut self,
1082        key_hash: u64,
1083        kind: ResidencyAssetKind,
1084        ram_payload: Vec<u8>,
1085        vram_bytes: usize,
1086        accountant: &mut ResourceAccountant,
1087        telemetry: &StreamingTelemetryCounters,
1088    ) -> Result<(), String> {
1089        let ram_bytes: usize = ram_payload.len();
1090        let ram_cap: usize = self.budget().get_ram_budget_bytes();
1091        let vram_cap: usize = self.budget().get_vram_budget_bytes();
1092        if ram_bytes > ram_cap || vram_bytes > vram_cap {
1093            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
1094        }
1095        let existing_slot: Option<usize> = {
1096            let Self { key_to_slot, .. } = self;
1097            key_to_slot.get(&key_hash).copied()
1098        };
1099        if let Some(slot_idx) = existing_slot {
1100            let _: bool = self.evict_slot(slot_idx, accountant);
1101        }
1102        let target_ram: usize = ram_cap.saturating_sub(ram_bytes);
1103        let target_vram: usize = vram_cap.saturating_sub(vram_bytes);
1104        let _: usize = self.enforce_budgets(target_ram, target_vram, accountant, telemetry);
1105        if self.ram_used_bytes().saturating_add(ram_bytes) > ram_cap
1106            || self.vram_used_bytes().saturating_add(vram_bytes) > vram_cap
1107        {
1108            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
1109        }
1110        let owner: ResourceOwnerId = self.owner();
1111        let ram_handle: u64 = if ram_bytes > 0 {
1112            accountant.register_auto_handle(
1113                owner,
1114                TrackedResourceKind::CacheAllocation,
1115                ram_bytes,
1116                ResourceRetentionClass::ExpectedRetained,
1117            )
1118        } else {
1119            0
1120        };
1121        let vram_handle: u64 = if vram_bytes > 0 {
1122            accountant.register_auto_handle(
1123                owner,
1124                TrackedResourceKind::GpuBuffer,
1125                vram_bytes,
1126                ResourceRetentionClass::ExpectedRetained,
1127            )
1128        } else {
1129            0
1130        };
1131        let slot_idx: usize = self.alloc_slot();
1132        let entry: ResidencySlot = ResidencySlot {
1133            key_hash,
1134            kind,
1135            texture_slot: 0,
1136            tier: TextureResidencyTier::Unloaded,
1137            mip_tail_vram_bytes: 0,
1138            mid_mip_vram_bytes: 0,
1139            full_res_vram_bytes: 0,
1140            ram_bytes,
1141            vram_bytes,
1142            ram_account_handle: ram_handle,
1143            vram_account_handle: vram_handle,
1144            referenced: false,
1145            visible: false,
1146            pinned: false,
1147            width: 0,
1148            height: 0,
1149            total_mip_levels: 0,
1150            is_srgb: false,
1151            mip_tail_rgba8: Vec::new(),
1152            ram_payload,
1153        };
1154        {
1155            let Self {
1156                slots,
1157                key_to_slot,
1158                ram_used_bytes,
1159                vram_used_bytes,
1160                ..
1161            } = self;
1162            slots[slot_idx] = Some(entry);
1163            let _: Option<usize> = key_to_slot.insert(key_hash, slot_idx);
1164            *ram_used_bytes = ram_used_bytes.saturating_add(ram_bytes);
1165            *vram_used_bytes = vram_used_bytes.saturating_add(vram_bytes);
1166        }
1167        self.sync_telemetry(telemetry);
1168        Ok(())
1169    }
1170
1171    /// Marks `key_hash` as recently accessed in O(1) so 2-hand Clock-LRU retains it.
1172    ///
1173    /// # Arguments
1174    ///
1175    /// - `u64` - Deterministic 64-bit asset key hash.
1176    ///
1177    /// # Returns
1178    ///
1179    /// - `bool` - `true` when the key was resident and refreshed.
1180    pub fn touch(&mut self, key_hash: u64) -> bool {
1181        let Self {
1182            slots, key_to_slot, ..
1183        } = self;
1184        let Some(&slot_idx) = key_to_slot.get(&key_hash) else {
1185            return false;
1186        };
1187        if let Some(Some(slot)) = slots.get_mut(slot_idx) {
1188            slot.referenced = true;
1189            true
1190        } else {
1191            false
1192        }
1193    }
1194
1195    /// Updates screen-space coverage and visibility for a texture and returns its target `TextureResidencyTier`.
1196    ///
1197    /// # Arguments
1198    ///
1199    /// - `u64` - Deterministic 64-bit texture key hash.
1200    /// - `f32` - Projected screen-space size in pixels.
1201    /// - `f32` - Camera distance in meters.
1202    /// - `bool` - Whether the texture is currently inside the view frustum.
1203    ///
1204    /// # Returns
1205    ///
1206    /// - `TextureResidencyTier` - Desired residency tier computed from screen coverage.
1207    pub fn report_texture_coverage(
1208        &mut self,
1209        key_hash: u64,
1210        screen_coverage_px: f32,
1211        camera_distance: f32,
1212        visible: bool,
1213    ) -> TextureResidencyTier {
1214        let desired: TextureResidencyTier =
1215            target_tier_for_coverage(screen_coverage_px, camera_distance, visible);
1216        let Self {
1217            slots,
1218            key_to_slot,
1219            offscreen_demotable_textures,
1220            ..
1221        } = self;
1222        if let Some(&slot_idx) = key_to_slot.get(&key_hash)
1223            && let Some(Some(slot)) = slots.get_mut(slot_idx)
1224        {
1225            let is_demotable: bool = slot.kind == ResidencyAssetKind::Texture
1226                && matches!(
1227                    slot.tier,
1228                    TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
1229                );
1230            let was_offscreen: bool = is_demotable && !slot.visible;
1231            slot.visible = visible;
1232            let now_offscreen: bool = is_demotable && !visible;
1233            if was_offscreen && !now_offscreen {
1234                *offscreen_demotable_textures = offscreen_demotable_textures.saturating_sub(1);
1235            } else if !was_offscreen && now_offscreen {
1236                *offscreen_demotable_textures = offscreen_demotable_textures.saturating_add(1);
1237            }
1238            if visible {
1239                slot.referenced = true;
1240            }
1241        }
1242        desired
1243    }
1244
1245    /// Pins or unpins a resident slot to protect or expose it during automatic Clock-LRU demotion/eviction.
1246    ///
1247    /// # Arguments
1248    ///
1249    /// - `u64` - Deterministic 64-bit asset key hash.
1250    /// - `bool` - `true` to pin, `false` to unpin.
1251    ///
1252    /// # Returns
1253    ///
1254    /// - `bool` - `true` when the entry existed and was updated.
1255    pub fn set_pinned(&mut self, key_hash: u64, pinned: bool) -> bool {
1256        let Self {
1257            slots, key_to_slot, ..
1258        } = self;
1259        if let Some(&slot_idx) = key_to_slot.get(&key_hash)
1260            && let Some(Some(slot)) = slots.get_mut(slot_idx)
1261        {
1262            slot.pinned = pinned;
1263            return true;
1264        }
1265        false
1266    }
1267
1268    /// Releases a single resident asset and removes its RAM/VRAM entries from `accountant`.
1269    ///
1270    /// # Arguments
1271    ///
1272    /// - `u64` - Deterministic 64-bit asset key hash.
1273    /// - `&mut ResourceAccountant` - Resource accountant receiving release notifications.
1274    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after release.
1275    ///
1276    /// # Returns
1277    ///
1278    /// - `bool` - `true` when the key existed and was released.
1279    pub fn release_key(
1280        &mut self,
1281        key_hash: u64,
1282        accountant: &mut ResourceAccountant,
1283        telemetry: &StreamingTelemetryCounters,
1284    ) -> bool {
1285        let slot_opt: Option<usize> = {
1286            let Self { key_to_slot, .. } = self;
1287            key_to_slot.get(&key_hash).copied()
1288        };
1289        let Some(slot_idx) = slot_opt else {
1290            return false;
1291        };
1292        let released: bool = self.evict_slot(slot_idx, accountant);
1293        self.sync_telemetry(telemetry);
1294        released
1295    }
1296
1297    /// Releases every resident entry and drains all tracked handles from `accountant` with zero leaks.
1298    ///
1299    /// # Arguments
1300    ///
1301    /// - `&mut ResourceAccountant` - Authoritative resource accountant receiving release notifications.
1302    /// - `&StreamingTelemetryCounters` - Telemetry counters reset to zero live usage.
1303    ///
1304    /// # Returns
1305    ///
1306    /// - `usize` - Number of resident entries released.
1307    pub fn release_all(
1308        &mut self,
1309        accountant: &mut ResourceAccountant,
1310        telemetry: &StreamingTelemetryCounters,
1311    ) -> usize {
1312        let slot_count: usize = {
1313            let Self { slots, .. } = self;
1314            slots.len()
1315        };
1316        let mut released: usize = 0;
1317        for slot_idx in 0..slot_count {
1318            if self.evict_slot(slot_idx, accountant) {
1319                released = released.saturating_add(1);
1320            }
1321        }
1322        self.sync_telemetry(telemetry);
1323        released
1324    }
1325}