euv-core 0.55.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
use super::*;

/// Default AAA desktop/mobile streaming budget presets for `AssetStreamBudget`.
impl Default for AssetStreamBudget {
    /// Creates an `AssetStreamBudget` initialized with `256 MiB` RAM, `128 MiB` VRAM, and `1.5 ms` / `4 MiB` per-frame caps.
    ///
    /// # Returns
    ///
    /// - `Self` - Default streaming budget configuration.
    fn default() -> Self {
        Self {
            ram_budget_bytes: ASSET_STREAM_DEFAULT_RAM_BUDGET_BYTES,
            vram_budget_bytes: ASSET_STREAM_DEFAULT_VRAM_BUDGET_BYTES,
            max_decode_us_per_frame: ASSET_STREAM_DEFAULT_MAX_DECODE_US,
            max_gpu_upload_bytes_per_frame: GPU_UPLOAD_BELT_MAX_BYTES_PER_FRAME,
            max_gpu_upload_us_per_frame: GPU_UPLOAD_BELT_MAX_TIME_US_PER_FRAME,
        }
    }
}

/// Convenience accessors unpacking per-tier VRAM sizes and dimensions from `TextureMipSpec`.
impl TextureMipSpec {
    /// Returns the `MipTail` VRAM footprint in bytes.
    ///
    /// # Returns
    ///
    /// - `usize` - `MipTail` byte size.
    #[must_use]
    pub fn mip_tail_bytes(&self) -> usize {
        self.get_tier_vram_bytes()[0]
    }

    /// Returns the `MidMip` VRAM footprint in bytes.
    ///
    /// # Returns
    ///
    /// - `usize` - `MidMip` byte size.
    #[must_use]
    pub fn mid_mip_bytes(&self) -> usize {
        self.get_tier_vram_bytes()[1]
    }

    /// Returns the `FullRes` VRAM footprint in bytes.
    ///
    /// # Returns
    ///
    /// - `usize` - `FullRes` byte size.
    #[must_use]
    pub fn full_res_bytes(&self) -> usize {
        self.get_tier_vram_bytes()[2]
    }

    /// Returns the full-resolution texture width in texels.
    ///
    /// # Returns
    ///
    /// - `u32` - Width in texels.
    #[must_use]
    pub fn width(&self) -> u32 {
        self.get_dimensions()[0]
    }

    /// Returns the full-resolution texture height in texels.
    ///
    /// # Returns
    ///
    /// - `u32` - Height in texels.
    #[must_use]
    pub fn height(&self) -> u32 {
        self.get_dimensions()[1]
    }
}

/// Default empty `ProgressiveResidencyPool` using default streaming budgets.
impl Default for ProgressiveResidencyPool {
    /// Creates an empty `ProgressiveResidencyPool` with default RAM/VRAM ceilings.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty residency pool.
    fn default() -> Self {
        Self::new(
            AssetStreamBudget::default(),
            ResourceOwnerId::new(
                ResourceOwnerKind::RenderCache,
                RESIDENCY_DEFAULT_OWNER_ID,
                1,
            ),
        )
    }
}

/// O(1) 2-hand Clock-LRU progressive mipmap residency, strict budget enforcement, and `ResourceAccountant` lifecycle management.
impl ProgressiveResidencyPool {
    /// Creates an empty `ProgressiveResidencyPool` governed by `budget` and attributed to `owner`.
    ///
    /// # Arguments
    ///
    /// - `AssetStreamBudget` - Hard RAM and VRAM ceilings.
    /// - `ResourceOwnerId` - Authoritative resource owner registered in `ResourceAccountant`.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized residency pool.
    #[must_use]
    pub fn new(budget: AssetStreamBudget, owner: ResourceOwnerId) -> Self {
        Self {
            budget,
            owner,
            slots: Vec::new(),
            free_slots: Vec::new(),
            key_to_slot: HashMap::new(),
            scan_hand: 0,
            evict_hand: 0,
            ram_used_bytes: 0,
            vram_used_bytes: 0,
            textures_mip_tail: 0,
            textures_mid_mip: 0,
            textures_full_res: 0,
            offscreen_demotable_textures: 0,
            evictions_to_mip_tail: 0,
            full_evictions: 0,
        }
    }

    /// Returns the active RAM/VRAM budget configuration.
    ///
    /// # Returns
    ///
    /// - `AssetStreamBudget` - Active memory ceilings.
    #[must_use]
    pub fn budget(&self) -> AssetStreamBudget {
        let Self { budget, .. } = self;
        *budget
    }

    /// Returns the authoritative `ResourceOwnerId` used for `ResourceAccountant` tracking.
    ///
    /// # Returns
    ///
    /// - `ResourceOwnerId` - Owner identifier.
    #[must_use]
    pub fn owner(&self) -> ResourceOwnerId {
        let Self { owner, .. } = self;
        *owner
    }

    /// Replaces the active memory budget and immediately demotes/evicts down to the new ceilings.
    ///
    /// # Arguments
    ///
    /// - `AssetStreamBudget` - Updated RAM and VRAM ceilings.
    /// - `&mut ResourceAccountant` - Resource accountant receiving release/update notifications.
    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after enforcement.
    pub fn set_budget(
        &mut self,
        next_budget: AssetStreamBudget,
        accountant: &mut ResourceAccountant,
        telemetry: &StreamingTelemetryCounters,
    ) {
        let Self { budget, .. } = self;
        *budget = next_budget;
        let _: usize = self.enforce_budgets(
            next_budget.get_ram_budget_bytes(),
            next_budget.get_vram_budget_bytes(),
            accountant,
            telemetry,
        );
        self.sync_telemetry(telemetry);
    }

    /// Synchronizes exact live RAM, VRAM, and texture tier counters into `telemetry`.
    ///
    /// # Arguments
    ///
    /// - `&StreamingTelemetryCounters` - Lock-free telemetry counters to update.
    pub fn sync_telemetry(&self, telemetry: &StreamingTelemetryCounters) {
        let Self {
            ram_used_bytes,
            vram_used_bytes,
            textures_mip_tail,
            textures_mid_mip,
            textures_full_res,
            ..
        } = self;
        telemetry.set_memory_usage(*ram_used_bytes, *vram_used_bytes);
        telemetry.set_texture_tier_counts(
            *textures_mip_tail,
            *textures_mid_mip,
            *textures_full_res,
        );
    }

    /// Returns the current resident RAM bytes.
    ///
    /// # Returns
    ///
    /// - `usize` - Live RAM bytes.
    #[must_use]
    pub fn ram_used_bytes(&self) -> usize {
        let Self { ram_used_bytes, .. } = self;
        *ram_used_bytes
    }

    /// Returns the current resident VRAM bytes.
    ///
    /// # Returns
    ///
    /// - `usize` - Live VRAM bytes.
    #[must_use]
    pub fn vram_used_bytes(&self) -> usize {
        let Self {
            vram_used_bytes, ..
        } = self;
        *vram_used_bytes
    }

    /// Returns the total count of live resident slots.
    ///
    /// # Returns
    ///
    /// - `usize` - Live slot count.
    #[must_use]
    pub fn live_count(&self) -> usize {
        let Self { key_to_slot, .. } = self;
        key_to_slot.len()
    }

    /// Returns the cumulative count of cold textures demoted to `MipTail`.
    ///
    /// # Returns
    ///
    /// - `u64` - Cumulative mip-tail demotion count.
    #[must_use]
    pub fn evictions_to_mip_tail(&self) -> u64 {
        let Self {
            evictions_to_mip_tail,
            ..
        } = self;
        *evictions_to_mip_tail
    }

    /// Returns `(textures_mip_tail, textures_mid_mip, textures_full_res)`.
    ///
    /// # Returns
    ///
    /// - `(u32, u32, u32)` - Live counts of textures across the 3 resident tiers.
    #[must_use]
    pub fn texture_tier_counts(&self) -> (u32, u32, u32) {
        let Self {
            textures_mip_tail,
            textures_mid_mip,
            textures_full_res,
            ..
        } = self;
        (*textures_mip_tail, *textures_mid_mip, *textures_full_res)
    }

    /// Looks up the current progressive residency tier for `key_hash`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    ///
    /// # Returns
    ///
    /// - `TextureResidencyTier` - Current tier (`Unloaded` when absent).
    #[must_use]
    pub fn texture_tier(&self, key_hash: u64) -> TextureResidencyTier {
        let Self {
            slots, key_to_slot, ..
        } = self;
        let Some(&slot_idx) = key_to_slot.get(&key_hash) else {
            return TextureResidencyTier::Unloaded;
        };
        slots
            .get(slot_idx)
            .and_then(|slot_opt: &Option<ResidencySlot>| slot_opt.as_ref())
            .map_or(TextureResidencyTier::Unloaded, |slot: &ResidencySlot| {
                slot.tier
            })
    }

    /// Returns `true` when `key_hash` is currently resident in this pool.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the asset is resident.
    #[must_use]
    pub fn contains(&self, key_hash: u64) -> bool {
        let Self { key_to_slot, .. } = self;
        key_to_slot.contains_key(&key_hash)
    }

    /// Returns the resident full-resolution dimensions `(width, height)` for a tracked texture, if present.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    ///
    /// # Returns
    ///
    /// - `Option<(u32, u32)>` - Texture width and height in texels when resident.
    #[must_use]
    pub fn texture_dimensions(&self, key_hash: u64) -> Option<(u32, u32)> {
        let Self {
            slots, key_to_slot, ..
        } = self;
        let &slot_idx = key_to_slot.get(&key_hash)?;
        let slot: &ResidencySlot = slots.get(slot_idx)?.as_ref()?;
        if slot.kind == ResidencyAssetKind::Texture {
            Some((slot.width, slot.height))
        } else {
            None
        }
    }

    /// Returns the resident CPU RAM payload slice for `key_hash`, if present.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    ///
    /// # Returns
    ///
    /// - `Option<&[u8]>` - Borrowed RAM payload bytes when resident.
    #[must_use]
    pub fn ram_payload(&self, key_hash: u64) -> Option<&[u8]> {
        let Self {
            slots, key_to_slot, ..
        } = self;
        let &slot_idx = key_to_slot.get(&key_hash)?;
        let slot: &ResidencySlot = slots.get(slot_idx)?.as_ref()?;
        Some(slot.ram_payload.as_slice())
    }

    /// Adjusts live texture tier counters when a texture transitions from `prev` to `next`.
    ///
    /// # Arguments
    ///
    /// - `TextureResidencyTier` - Previous tier (`Unloaded` for newly inserted textures).
    /// - `TextureResidencyTier` - New tier (`Unloaded` for evicted textures).
    fn adjust_tier_counters(&mut self, prev: TextureResidencyTier, next: TextureResidencyTier) {
        let Self {
            textures_mip_tail,
            textures_mid_mip,
            textures_full_res,
            ..
        } = self;
        match prev {
            TextureResidencyTier::MipTail => {
                *textures_mip_tail = textures_mip_tail.saturating_sub(1);
            }
            TextureResidencyTier::MidMip => {
                *textures_mid_mip = textures_mid_mip.saturating_sub(1);
            }
            TextureResidencyTier::FullRes => {
                *textures_full_res = textures_full_res.saturating_sub(1);
            }
            TextureResidencyTier::Unloaded => {}
        }
        match next {
            TextureResidencyTier::MipTail => {
                *textures_mip_tail = textures_mip_tail.saturating_add(1);
            }
            TextureResidencyTier::MidMip => {
                *textures_mid_mip = textures_mid_mip.saturating_add(1);
            }
            TextureResidencyTier::FullRes => {
                *textures_full_res = textures_full_res.saturating_add(1);
            }
            TextureResidencyTier::Unloaded => {}
        }
    }

    /// Allocates a free slot index or appends a new slot, keeping the 2-hand Clock-LRU pointers aligned.
    ///
    /// # Returns
    ///
    /// - `usize` - Allocated slot index.
    fn alloc_slot(&mut self) -> usize {
        let Self {
            slots,
            free_slots,
            scan_hand,
            evict_hand,
            ..
        } = self;
        if let Some(reused) = free_slots.pop() {
            return reused;
        }
        let idx: usize = slots.len();
        slots.push(None);
        let total: usize = slots.len();
        if total == 1 {
            *evict_hand = 0;
            *scan_hand = 0;
        } else {
            let lead: usize = clock_lead_distance(total);
            *scan_hand = (*evict_hand + lead) % total;
        }
        idx
    }

    /// Releases `ResourceAccountant` RAM and VRAM handles associated with `slot`.
    ///
    /// # Arguments
    ///
    /// - `&ResidencySlot` - Slot being evicted or updated.
    /// - `&mut ResourceAccountant` - Authoritative resource accountant.
    fn release_slot_accounting(slot: &ResidencySlot, accountant: &mut ResourceAccountant) {
        if slot.ram_account_handle != 0 {
            let _: bool = accountant.release_resource(
                TrackedResourceKind::CacheAllocation,
                slot.ram_account_handle,
            );
        }
        if slot.vram_account_handle != 0 {
            let vram_kind: TrackedResourceKind = if slot.kind == ResidencyAssetKind::Texture {
                TrackedResourceKind::GpuTexture
            } else {
                TrackedResourceKind::GpuBuffer
            };
            let _: bool = accountant.release_resource(vram_kind, slot.vram_account_handle);
        }
    }

    /// Selects a cold demotable texture slot (`FullRes` or `MidMip`) in O(1) amortized time using 2-hand Clock-LRU.
    ///
    /// # Arguments
    ///
    /// - `bool` - When `true`, skips visible textures on the first scan pass so off-screen textures demote first.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Selected victim slot index or `None` if no demotable texture exists.
    fn clock_select_demotable_texture(&mut self, prefer_offscreen: bool) -> Option<usize> {
        let Self {
            slots,
            scan_hand,
            evict_hand,
            ..
        } = self;
        let len: usize = slots.len();
        if len == 0 {
            return None;
        }
        if *evict_hand >= len {
            *evict_hand = 0;
        }
        let lead: usize = clock_lead_distance(len);
        if *scan_hand >= len {
            *scan_hand = (*evict_hand + lead) % len;
        }
        let max_steps: usize = len.saturating_mul(2);
        for _ in 0..max_steps {
            let scan_idx: usize = *scan_hand;
            *scan_hand = (scan_idx + 1) % len;
            if let Some(scan_slot) = slots[scan_idx].as_mut()
                && !scan_slot.pinned
            {
                scan_slot.referenced = false;
            }
            let cand_idx: usize = *evict_hand;
            *evict_hand = (cand_idx + 1) % len;
            let Some(slot) = slots[cand_idx].as_mut() else {
                continue;
            };
            if slot.pinned || slot.kind != ResidencyAssetKind::Texture {
                continue;
            }
            let is_demotable: bool = matches!(
                slot.tier,
                TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
            );
            if !is_demotable {
                continue;
            }
            if prefer_offscreen && slot.visible {
                continue;
            }
            if !slot.referenced {
                return Some(cand_idx);
            }
            slot.referenced = false;
        }
        None
    }

    /// Selects a cold evictable slot freeing RAM or VRAM in O(1) amortized time using 2-hand Clock-LRU.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether the victim must release RAM bytes.
    /// - `bool` - Whether the victim must release VRAM bytes.
    /// - `bool` - When `false`, protects visible textures from full eviction (never blanking visible surfaces).
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Selected victim slot index or `None` if all matching slots are pinned or protected.
    fn clock_select_evictable_slot(
        &mut self,
        need_ram: bool,
        need_vram: bool,
        allow_visible_textures: bool,
    ) -> Option<usize> {
        let Self {
            slots,
            scan_hand,
            evict_hand,
            ..
        } = self;
        let len: usize = slots.len();
        if len == 0 {
            return None;
        }
        if *evict_hand >= len {
            *evict_hand = 0;
        }
        let lead: usize = clock_lead_distance(len);
        if *scan_hand >= len {
            *scan_hand = (*evict_hand + lead) % len;
        }
        let max_steps: usize = len.saturating_mul(2);
        for _ in 0..max_steps {
            let scan_idx: usize = *scan_hand;
            *scan_hand = (scan_idx + 1) % len;
            if let Some(scan_slot) = slots[scan_idx].as_mut()
                && !scan_slot.pinned
            {
                scan_slot.referenced = false;
            }
            let cand_idx: usize = *evict_hand;
            *evict_hand = (cand_idx + 1) % len;
            let Some(slot) = slots[cand_idx].as_mut() else {
                continue;
            };
            if slot.pinned {
                continue;
            }
            if !allow_visible_textures && slot.kind == ResidencyAssetKind::Texture && slot.visible {
                continue;
            }
            let frees_ram: bool = need_ram && slot.ram_bytes > 0;
            let frees_vram: bool = need_vram && slot.vram_bytes > 0;
            if !frees_ram && !frees_vram {
                continue;
            }
            if !slot.referenced {
                return Some(cand_idx);
            }
            slot.referenced = false;
        }
        None
    }

    /// Demotes texture slot `slot_idx` one residency step (`FullRes -> MidMip -> MipTail`) and updates `ResourceAccountant`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Resident texture slot index.
    /// - `&mut ResourceAccountant` - Resource accountant updating live VRAM bytes.
    /// - `&StreamingTelemetryCounters` - Telemetry counters recording mip-tail demotions.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the texture was demoted and released VRAM bytes.
    fn demote_texture_slot(
        &mut self,
        slot_idx: usize,
        accountant: &mut ResourceAccountant,
        telemetry: &StreamingTelemetryCounters,
    ) -> bool {
        let owner: ResourceOwnerId = self.owner();
        let (prev_tier, next_tier, old_vram, new_vram, old_handle, retention): (
            TextureResidencyTier,
            TextureResidencyTier,
            usize,
            usize,
            u64,
            ResourceRetentionClass,
        ) = {
            let Self { slots, .. } = self;
            let Some(Some(slot)) = slots.get(slot_idx) else {
                return false;
            };
            let Some(next_tier) = demote_tier_one_step(slot.tier) else {
                return false;
            };
            let next_vram: usize = tier_vram_bytes(
                next_tier,
                slot.mip_tail_vram_bytes,
                slot.mid_mip_vram_bytes,
                slot.full_res_vram_bytes,
            );
            let retention: ResourceRetentionClass = if slot.pinned {
                ResourceRetentionClass::Active
            } else {
                ResourceRetentionClass::ExpectedRetained
            };
            (
                slot.tier,
                next_tier,
                slot.vram_bytes,
                next_vram,
                slot.vram_account_handle,
                retention,
            )
        };
        if old_handle != 0 {
            let _: bool = accountant.release_resource(TrackedResourceKind::GpuTexture, old_handle);
        }
        let new_handle: u64 = if new_vram > 0 {
            accountant.register_auto_handle(
                owner,
                TrackedResourceKind::GpuTexture,
                new_vram,
                retention,
            )
        } else {
            0
        };
        {
            let Self {
                slots,
                vram_used_bytes,
                offscreen_demotable_textures,
                evictions_to_mip_tail,
                ..
            } = self;
            if let Some(Some(slot)) = slots.get_mut(slot_idx) {
                let was_offscreen_demotable: bool = !slot.visible
                    && matches!(
                        slot.tier,
                        TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
                    );
                slot.tier = next_tier;
                slot.vram_bytes = new_vram;
                slot.vram_account_handle = new_handle;
                let now_offscreen_demotable: bool = !slot.visible
                    && matches!(
                        next_tier,
                        TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
                    );
                if was_offscreen_demotable && !now_offscreen_demotable {
                    *offscreen_demotable_textures = offscreen_demotable_textures.saturating_sub(1);
                }
            }
            *vram_used_bytes = vram_used_bytes
                .saturating_sub(old_vram)
                .saturating_add(new_vram);
            if next_tier == TextureResidencyTier::MipTail {
                *evictions_to_mip_tail = evictions_to_mip_tail.saturating_add(1);
                telemetry.add_eviction_to_mip_tail();
            }
        }
        self.adjust_tier_counters(prev_tier, next_tier);
        true
    }

    /// Fully evicts slot `slot_idx`, releasing all RAM and VRAM handles from `accountant`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Resident slot index to remove.
    /// - `&mut ResourceAccountant` - Resource accountant receiving release notifications.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when an occupied slot was removed.
    fn evict_slot(&mut self, slot_idx: usize, accountant: &mut ResourceAccountant) -> bool {
        let removed: Option<ResidencySlot> = {
            let Self {
                slots,
                free_slots,
                key_to_slot,
                ram_used_bytes,
                vram_used_bytes,
                offscreen_demotable_textures,
                full_evictions,
                ..
            } = self;
            let Some(slot) = slots.get_mut(slot_idx).and_then(Option::take) else {
                return false;
            };
            let _: Option<usize> = key_to_slot.remove(&slot.key_hash);
            free_slots.push(slot_idx);
            *ram_used_bytes = ram_used_bytes.saturating_sub(slot.ram_bytes);
            *vram_used_bytes = vram_used_bytes.saturating_sub(slot.vram_bytes);
            *full_evictions = full_evictions.saturating_add(1);
            if slot.kind == ResidencyAssetKind::Texture
                && !slot.visible
                && matches!(
                    slot.tier,
                    TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
                )
            {
                *offscreen_demotable_textures = offscreen_demotable_textures.saturating_sub(1);
            }
            Some(slot)
        };
        if let Some(slot) = removed {
            if slot.kind == ResidencyAssetKind::Texture {
                self.adjust_tier_counters(slot.tier, TextureResidencyTier::Unloaded);
            }
            Self::release_slot_accounting(&slot, accountant);
            true
        } else {
            false
        }
    }

    /// Enforces `target_ram` and `target_vram` ceilings using 2-hand Clock-LRU, demoting cold textures to `MipTail` before evicting off-screen entries.
    ///
    /// # Arguments
    ///
    /// - `usize` - Target maximum RAM bytes.
    /// - `usize` - Target maximum VRAM bytes.
    /// - `&mut ResourceAccountant` - Resource accountant receiving release updates.
    /// - `&StreamingTelemetryCounters` - Telemetry counters receiving demotion increments.
    ///
    /// # Returns
    ///
    /// - `usize` - Total demotions and evictions performed.
    pub fn enforce_budgets(
        &mut self,
        target_ram: usize,
        target_vram: usize,
        accountant: &mut ResourceAccountant,
        telemetry: &StreamingTelemetryCounters,
    ) -> usize {
        let mut actions: usize = 0;
        while self.vram_used_bytes() > target_vram {
            let (has_demotable, has_offscreen_demotable): (bool, bool) = {
                let Self {
                    textures_mid_mip,
                    textures_full_res,
                    offscreen_demotable_textures,
                    ..
                } = self;
                (
                    *textures_mid_mip > 0 || *textures_full_res > 0,
                    *offscreen_demotable_textures > 0,
                )
            };
            if has_offscreen_demotable
                && let Some(victim) = self.clock_select_demotable_texture(true)
                && self.demote_texture_slot(victim, accountant, telemetry)
            {
                actions = actions.saturating_add(1);
                continue;
            }
            if has_demotable
                && let Some(victim) = self.clock_select_demotable_texture(false)
                && self.demote_texture_slot(victim, accountant, telemetry)
            {
                actions = actions.saturating_add(1);
                continue;
            }
            if let Some(victim) = self.clock_select_evictable_slot(false, true, false)
                && self.evict_slot(victim, accountant)
            {
                actions = actions.saturating_add(1);
                continue;
            }
            break;
        }
        while self.ram_used_bytes() > target_ram {
            if let Some(victim) = self.clock_select_evictable_slot(true, false, false)
                && self.evict_slot(victim, accountant)
            {
                actions = actions.saturating_add(1);
                continue;
            }
            break;
        }
        self.sync_telemetry(telemetry);
        actions
    }

    /// Binds a texture instantly at `TextureResidencyTier::MipTail` from the `.euvpak` Mip-Tail Superblock to eliminate blank pop-in.
    ///
    /// # Arguments
    ///
    /// - `TextureMipSpec` - Progressive texture descriptor.
    /// - `Vec<u8>` - Compact `16x16`/`32x32` RGBA8 mip-tail texels.
    /// - `&mut ResourceAccountant` - Authoritative resource accountant.
    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after admission.
    ///
    /// # Returns
    ///
    /// - `Result<GpuTextureMipUpload, String>` - Ready Frame-1 mip-tail GPU upload payload or budget error.
    pub fn bind_texture_mip_tail(
        &mut self,
        spec: TextureMipSpec,
        mip_tail_rgba8: Vec<u8>,
        accountant: &mut ResourceAccountant,
        telemetry: &StreamingTelemetryCounters,
    ) -> Result<GpuTextureMipUpload, String> {
        let key_hash: u64 = spec.get_key_hash();
        let mip_tail_bytes: usize = spec
            .mip_tail_bytes()
            .max(mip_tail_rgba8.len())
            .max(RESIDENCY_DEFAULT_MIP_TAIL_BYTES.min(mip_tail_rgba8.len().max(64)));
        let mid_mip_bytes: usize = spec.mid_mip_bytes().max(mip_tail_bytes);
        let full_res_bytes: usize = spec.full_res_bytes().max(mid_mip_bytes);
        let vram_cap: usize = self.budget().get_vram_budget_bytes();
        if mip_tail_bytes > vram_cap {
            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
        }
        let existing_slot: Option<usize> = {
            let Self { key_to_slot, .. } = self;
            key_to_slot.get(&key_hash).copied()
        };
        if let Some(slot_idx) = existing_slot {
            let Self { slots, .. } = self;
            if let Some(Some(slot)) = slots.get_mut(slot_idx) {
                slot.referenced = true;
                slot.mip_tail_rgba8 = mip_tail_rgba8.clone();
                let clamp: u8 = min_lod_clamp_for_tier(slot.tier, slot.total_mip_levels);
                let tail_side: u32 = ((mip_tail_rgba8.len() / 4) as f32).sqrt().max(1.0) as u32;
                return Ok(GpuTextureMipUpload {
                    texture_slot: slot.texture_slot,
                    mip_level: slot.total_mip_levels.saturating_sub(1),
                    total_mip_levels: slot.total_mip_levels,
                    is_srgb: slot.is_srgb,
                    min_lod_clamp: clamp,
                    width: tail_side,
                    height: tail_side,
                    rgba8: mip_tail_rgba8,
                });
            }
        }
        let target_vram: usize = vram_cap.saturating_sub(mip_tail_bytes);
        let _: usize = self.enforce_budgets(
            self.budget().get_ram_budget_bytes(),
            target_vram,
            accountant,
            telemetry,
        );
        if self.vram_used_bytes().saturating_add(mip_tail_bytes) > vram_cap {
            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
        }
        let owner: ResourceOwnerId = self.owner();
        let vram_handle: u64 = accountant.register_auto_handle(
            owner,
            TrackedResourceKind::GpuTexture,
            mip_tail_bytes,
            ResourceRetentionClass::ExpectedRetained,
        );
        let slot_idx: usize = self.alloc_slot();
        let total_mips: u8 = spec.get_total_mip_levels().max(1);
        let entry: ResidencySlot = ResidencySlot {
            key_hash,
            kind: ResidencyAssetKind::Texture,
            texture_slot: spec.get_texture_slot(),
            tier: TextureResidencyTier::MipTail,
            mip_tail_vram_bytes: mip_tail_bytes,
            mid_mip_vram_bytes: mid_mip_bytes,
            full_res_vram_bytes: full_res_bytes,
            ram_bytes: 0,
            vram_bytes: mip_tail_bytes,
            ram_account_handle: 0,
            vram_account_handle: vram_handle,
            referenced: false,
            visible: true,
            pinned: false,
            width: spec.width().max(1),
            height: spec.height().max(1),
            total_mip_levels: total_mips,
            is_srgb: spec.get_is_srgb(),
            mip_tail_rgba8: mip_tail_rgba8.clone(),
            ram_payload: Vec::new(),
        };
        {
            let Self {
                slots,
                key_to_slot,
                vram_used_bytes,
                ..
            } = self;
            slots[slot_idx] = Some(entry);
            let _: Option<usize> = key_to_slot.insert(key_hash, slot_idx);
            *vram_used_bytes = vram_used_bytes.saturating_add(mip_tail_bytes);
        }
        self.adjust_tier_counters(
            TextureResidencyTier::Unloaded,
            TextureResidencyTier::MipTail,
        );
        self.sync_telemetry(telemetry);
        let tail_side: u32 = ((mip_tail_rgba8.len() / 4) as f32).sqrt().max(1.0) as u32;
        Ok(GpuTextureMipUpload {
            texture_slot: spec.get_texture_slot(),
            mip_level: total_mips.saturating_sub(1),
            total_mip_levels: total_mips,
            is_srgb: spec.get_is_srgb(),
            min_lod_clamp: total_mips.saturating_sub(1),
            width: tail_side,
            height: tail_side,
            rgba8: mip_tail_rgba8,
        })
    }

    /// Promotes a texture toward `desired_tier` while strictly respecting the VRAM ceiling (gracefully capping at a lower non-blank tier if needed).
    ///
    /// # Arguments
    ///
    /// - `TextureMipSpec` - Progressive texture descriptor.
    /// - `TextureResidencyTier` - Desired target residency tier.
    /// - `Vec<u8>` - Decoded RGBA8 texels for the promoted mip level.
    /// - `&mut ResourceAccountant` - Authoritative resource accountant.
    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after promotion.
    ///
    /// # Returns
    ///
    /// - `Result<(TextureResidencyTier, Option<GpuTextureMipUpload>), String>` - Effective admitted tier and optional GPU mip upload.
    pub fn promote_texture_tier(
        &mut self,
        spec: TextureMipSpec,
        desired_tier: TextureResidencyTier,
        rgba8: Vec<u8>,
        accountant: &mut ResourceAccountant,
        telemetry: &StreamingTelemetryCounters,
    ) -> Result<(TextureResidencyTier, Option<GpuTextureMipUpload>), String> {
        let key_hash: u64 = spec.get_key_hash();
        if !self.contains(key_hash) {
            let tail_len: usize = spec.mip_tail_bytes().max(64).min(rgba8.len().max(64));
            let tail_buf: Vec<u8> = if rgba8.len() >= tail_len {
                rgba8[..tail_len].to_vec()
            } else {
                rgba8.clone()
            };
            let first_upload: GpuTextureMipUpload =
                self.bind_texture_mip_tail(spec, tail_buf, accountant, telemetry)?;
            if desired_tier == TextureResidencyTier::MipTail {
                return Ok((TextureResidencyTier::MipTail, Some(first_upload)));
            }
        }
        let Some(&slot_idx) = ({
            let Self { key_to_slot, .. } = self;
            key_to_slot.get(&key_hash)
        }) else {
            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
        };
        let (prev_tier, prev_vram, mip_tail_b, mid_mip_b, full_res_b, old_handle, total_mips): (
            TextureResidencyTier,
            usize,
            usize,
            usize,
            usize,
            u64,
            u8,
        ) = {
            let Self { slots, .. } = self;
            let Some(Some(slot)) = slots.get_mut(slot_idx) else {
                return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
            };
            slot.referenced = true;
            slot.visible = true;
            (
                slot.tier,
                slot.vram_bytes,
                slot.mip_tail_vram_bytes,
                slot.mid_mip_vram_bytes.max(spec.mid_mip_bytes()),
                slot.full_res_vram_bytes.max(spec.full_res_bytes()),
                slot.vram_account_handle,
                slot.total_mip_levels,
            )
        };
        if (desired_tier as u8) <= (prev_tier as u8) {
            return Ok((prev_tier, None));
        }
        let vram_cap: usize = self.budget().get_vram_budget_bytes();
        let ram_cap: usize = self.budget().get_ram_budget_bytes();
        let candidates: [TextureResidencyTier; 3] = match desired_tier {
            TextureResidencyTier::FullRes => [
                TextureResidencyTier::FullRes,
                TextureResidencyTier::MidMip,
                TextureResidencyTier::MipTail,
            ],
            TextureResidencyTier::MidMip => [
                TextureResidencyTier::MidMip,
                TextureResidencyTier::MipTail,
                TextureResidencyTier::MipTail,
            ],
            TextureResidencyTier::MipTail | TextureResidencyTier::Unloaded => [
                TextureResidencyTier::MipTail,
                TextureResidencyTier::MipTail,
                TextureResidencyTier::MipTail,
            ],
        };
        let mut chosen_tier: TextureResidencyTier = prev_tier;
        let mut chosen_vram: usize = prev_vram;
        for cand_tier in candidates {
            if (cand_tier as u8) <= (prev_tier as u8) {
                break;
            }
            let cand_vram: usize = tier_vram_bytes(cand_tier, mip_tail_b, mid_mip_b, full_res_b);
            if cand_vram > vram_cap {
                continue;
            }
            let delta: usize = cand_vram.saturating_sub(prev_vram);
            let target_vram: usize = vram_cap.saturating_sub(delta);
            let _: usize = self.enforce_budgets(ram_cap, target_vram, accountant, telemetry);
            if self.vram_used_bytes().saturating_add(delta) <= vram_cap {
                chosen_tier = cand_tier;
                chosen_vram = cand_vram;
                break;
            }
        }
        if chosen_tier == prev_tier {
            return Ok((prev_tier, None));
        }
        let owner: ResourceOwnerId = self.owner();
        if old_handle != 0 {
            let _: bool = accountant.release_resource(TrackedResourceKind::GpuTexture, old_handle);
        }
        let new_handle: u64 = accountant.register_auto_handle(
            owner,
            TrackedResourceKind::GpuTexture,
            chosen_vram,
            ResourceRetentionClass::ExpectedRetained,
        );
        {
            let Self {
                slots,
                vram_used_bytes,
                ..
            } = self;
            if let Some(Some(slot)) = slots.get_mut(slot_idx) {
                slot.tier = chosen_tier;
                slot.mid_mip_vram_bytes = mid_mip_b;
                slot.full_res_vram_bytes = full_res_b;
                slot.vram_bytes = chosen_vram;
                slot.vram_account_handle = new_handle;
                slot.referenced = true;
            }
            *vram_used_bytes = vram_used_bytes
                .saturating_sub(prev_vram)
                .saturating_add(chosen_vram);
        }
        self.adjust_tier_counters(prev_tier, chosen_tier);
        self.sync_telemetry(telemetry);
        let mip_level: u8 = min_lod_clamp_for_tier(chosen_tier, total_mips);
        let mip_width: u32 = (spec.width() >> mip_level).max(1);
        let mip_height: u32 = (spec.height() >> mip_level).max(1);
        Ok((
            chosen_tier,
            Some(GpuTextureMipUpload {
                texture_slot: spec.get_texture_slot(),
                mip_level,
                total_mip_levels: total_mips,
                is_srgb: spec.get_is_srgb(),
                min_lod_clamp: mip_level,
                width: mip_width,
                height: mip_height,
                rgba8,
            }),
        ))
    }

    /// Admits a decoded non-texture asset (mesh, audio, font, shader cache, or raw bytes) under strict RAM/VRAM ceilings.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    /// - `ResidencyAssetKind` - Semantic asset category.
    /// - `Vec<u8>` - Decoded CPU RAM payload bytes.
    /// - `usize` - Optional GPU VRAM byte footprint (e.g. mesh VBO/IBO size).
    /// - `&mut ResourceAccountant` - Authoritative resource accountant.
    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after admission.
    ///
    /// # Returns
    ///
    /// - `Result<(), String>` - `Ok(())` once resident or error when exceeding total capacity.
    pub fn admit_asset(
        &mut self,
        key_hash: u64,
        kind: ResidencyAssetKind,
        ram_payload: Vec<u8>,
        vram_bytes: usize,
        accountant: &mut ResourceAccountant,
        telemetry: &StreamingTelemetryCounters,
    ) -> Result<(), String> {
        let ram_bytes: usize = ram_payload.len();
        let ram_cap: usize = self.budget().get_ram_budget_bytes();
        let vram_cap: usize = self.budget().get_vram_budget_bytes();
        if ram_bytes > ram_cap || vram_bytes > vram_cap {
            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
        }
        let existing_slot: Option<usize> = {
            let Self { key_to_slot, .. } = self;
            key_to_slot.get(&key_hash).copied()
        };
        if let Some(slot_idx) = existing_slot {
            let _: bool = self.evict_slot(slot_idx, accountant);
        }
        let target_ram: usize = ram_cap.saturating_sub(ram_bytes);
        let target_vram: usize = vram_cap.saturating_sub(vram_bytes);
        let _: usize = self.enforce_budgets(target_ram, target_vram, accountant, telemetry);
        if self.ram_used_bytes().saturating_add(ram_bytes) > ram_cap
            || self.vram_used_bytes().saturating_add(vram_bytes) > vram_cap
        {
            return Err(ERR_RESIDENCY_BUDGET_EXCEEDED.to_string());
        }
        let owner: ResourceOwnerId = self.owner();
        let ram_handle: u64 = if ram_bytes > 0 {
            accountant.register_auto_handle(
                owner,
                TrackedResourceKind::CacheAllocation,
                ram_bytes,
                ResourceRetentionClass::ExpectedRetained,
            )
        } else {
            0
        };
        let vram_handle: u64 = if vram_bytes > 0 {
            accountant.register_auto_handle(
                owner,
                TrackedResourceKind::GpuBuffer,
                vram_bytes,
                ResourceRetentionClass::ExpectedRetained,
            )
        } else {
            0
        };
        let slot_idx: usize = self.alloc_slot();
        let entry: ResidencySlot = ResidencySlot {
            key_hash,
            kind,
            texture_slot: 0,
            tier: TextureResidencyTier::Unloaded,
            mip_tail_vram_bytes: 0,
            mid_mip_vram_bytes: 0,
            full_res_vram_bytes: 0,
            ram_bytes,
            vram_bytes,
            ram_account_handle: ram_handle,
            vram_account_handle: vram_handle,
            referenced: false,
            visible: false,
            pinned: false,
            width: 0,
            height: 0,
            total_mip_levels: 0,
            is_srgb: false,
            mip_tail_rgba8: Vec::new(),
            ram_payload,
        };
        {
            let Self {
                slots,
                key_to_slot,
                ram_used_bytes,
                vram_used_bytes,
                ..
            } = self;
            slots[slot_idx] = Some(entry);
            let _: Option<usize> = key_to_slot.insert(key_hash, slot_idx);
            *ram_used_bytes = ram_used_bytes.saturating_add(ram_bytes);
            *vram_used_bytes = vram_used_bytes.saturating_add(vram_bytes);
        }
        self.sync_telemetry(telemetry);
        Ok(())
    }

    /// Marks `key_hash` as recently accessed in O(1) so 2-hand Clock-LRU retains it.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the key was resident and refreshed.
    pub fn touch(&mut self, key_hash: u64) -> bool {
        let Self {
            slots, key_to_slot, ..
        } = self;
        let Some(&slot_idx) = key_to_slot.get(&key_hash) else {
            return false;
        };
        if let Some(Some(slot)) = slots.get_mut(slot_idx) {
            slot.referenced = true;
            true
        } else {
            false
        }
    }

    /// Updates screen-space coverage and visibility for a texture and returns its target `TextureResidencyTier`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit texture key hash.
    /// - `f32` - Projected screen-space size in pixels.
    /// - `f32` - Camera distance in meters.
    /// - `bool` - Whether the texture is currently inside the view frustum.
    ///
    /// # Returns
    ///
    /// - `TextureResidencyTier` - Desired residency tier computed from screen coverage.
    pub fn report_texture_coverage(
        &mut self,
        key_hash: u64,
        screen_coverage_px: f32,
        camera_distance: f32,
        visible: bool,
    ) -> TextureResidencyTier {
        let desired: TextureResidencyTier =
            target_tier_for_coverage(screen_coverage_px, camera_distance, visible);
        let Self {
            slots,
            key_to_slot,
            offscreen_demotable_textures,
            ..
        } = self;
        if let Some(&slot_idx) = key_to_slot.get(&key_hash)
            && let Some(Some(slot)) = slots.get_mut(slot_idx)
        {
            let is_demotable: bool = slot.kind == ResidencyAssetKind::Texture
                && matches!(
                    slot.tier,
                    TextureResidencyTier::FullRes | TextureResidencyTier::MidMip
                );
            let was_offscreen: bool = is_demotable && !slot.visible;
            slot.visible = visible;
            let now_offscreen: bool = is_demotable && !visible;
            if was_offscreen && !now_offscreen {
                *offscreen_demotable_textures = offscreen_demotable_textures.saturating_sub(1);
            } else if !was_offscreen && now_offscreen {
                *offscreen_demotable_textures = offscreen_demotable_textures.saturating_add(1);
            }
            if visible {
                slot.referenced = true;
            }
        }
        desired
    }

    /// Pins or unpins a resident slot to protect or expose it during automatic Clock-LRU demotion/eviction.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    /// - `bool` - `true` to pin, `false` to unpin.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the entry existed and was updated.
    pub fn set_pinned(&mut self, key_hash: u64, pinned: bool) -> bool {
        let Self {
            slots, key_to_slot, ..
        } = self;
        if let Some(&slot_idx) = key_to_slot.get(&key_hash)
            && let Some(Some(slot)) = slots.get_mut(slot_idx)
        {
            slot.pinned = pinned;
            return true;
        }
        false
    }

    /// Releases a single resident asset and removes its RAM/VRAM entries from `accountant`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    /// - `&mut ResourceAccountant` - Resource accountant receiving release notifications.
    /// - `&StreamingTelemetryCounters` - Telemetry counters synchronized after release.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the key existed and was released.
    pub fn release_key(
        &mut self,
        key_hash: u64,
        accountant: &mut ResourceAccountant,
        telemetry: &StreamingTelemetryCounters,
    ) -> bool {
        let slot_opt: Option<usize> = {
            let Self { key_to_slot, .. } = self;
            key_to_slot.get(&key_hash).copied()
        };
        let Some(slot_idx) = slot_opt else {
            return false;
        };
        let released: bool = self.evict_slot(slot_idx, accountant);
        self.sync_telemetry(telemetry);
        released
    }

    /// Releases every resident entry and drains all tracked handles from `accountant` with zero leaks.
    ///
    /// # Arguments
    ///
    /// - `&mut ResourceAccountant` - Authoritative resource accountant receiving release notifications.
    /// - `&StreamingTelemetryCounters` - Telemetry counters reset to zero live usage.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of resident entries released.
    pub fn release_all(
        &mut self,
        accountant: &mut ResourceAccountant,
        telemetry: &StreamingTelemetryCounters,
    ) -> usize {
        let slot_count: usize = {
            let Self { slots, .. } = self;
            slots.len()
        };
        let mut released: usize = 0;
        for slot_idx in 0..slot_count {
            if self.evict_slot(slot_idx, accountant) {
                released = released.saturating_add(1);
            }
        }
        self.sync_telemetry(telemetry);
        released
    }
}