euv-core 0.56.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
use super::*;

/// Clean worker pool shutdown guaranteeing zero leaked OS threads when `AssetStreamCoordinator` drops.
impl Drop for AssetStreamCoordinator {
    /// Signals background worker shutdown and joins all native streaming threads cleanly.
    fn drop(&mut self) {
        let Self { queue, .. } = self;
        queue.request_shutdown();
        #[cfg(not(target_arch = "wasm32"))]
        {
            let Self { workers, .. } = self;
            for handle in workers.drain(..) {
                let _: Result<(), Box<dyn Any + Send>> = handle.join();
            }
        }
    }
}

/// Request scheduling, coalescing, cancellation, hybrid async/cooperative decoding, Clock-LRU residency, spatial prefetch, and GPU upload draining for `AssetStreamCoordinator`.
impl AssetStreamCoordinator {
    /// Creates a new `AssetStreamCoordinator` bound to `budget` and an optional mounted `EuvPakArchive`.
    ///
    /// # Arguments
    ///
    /// - `AssetStreamBudget` - RAM, VRAM, decode time, and GPU upload ceilings.
    /// - `Option<Arc<EuvPakArchive>>` - Optional mounted `.euvpak` virtual filesystem archive.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized `AssetStreamCoordinator`.
    #[must_use]
    pub fn new(budget: AssetStreamBudget, vfs: Option<Arc<EuvPakArchive>>) -> Self {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let default_workers: usize = (available_parallelism()
                .map(usize::from)
                .unwrap_or(STREAM_DECODER_MIN_WORKERS * 2)
                / 2)
            .clamp(STREAM_DECODER_MIN_WORKERS, STREAM_DECODER_MAX_WORKERS);
            Self::build_internal(
                budget,
                vfs,
                StreamExecutionMode::AsyncWorkers,
                default_workers,
            )
        }
        #[cfg(target_arch = "wasm32")]
        {
            Self::build_internal(budget, vfs, StreamExecutionMode::CooperativeTimeSliced, 0)
        }
    }

    /// Creates an `AssetStreamCoordinator` explicitly running in cooperative `<= 1.5 ms/frame` time-sliced decode mode on any platform.
    ///
    /// # Arguments
    ///
    /// - `AssetStreamBudget` - RAM, VRAM, decode time, and GPU upload ceilings.
    /// - `Option<Arc<EuvPakArchive>>` - Optional mounted `.euvpak` virtual filesystem archive.
    ///
    /// # Returns
    ///
    /// - `Self` - Cooperative time-sliced streaming coordinator.
    #[must_use]
    pub fn new_cooperative(budget: AssetStreamBudget, vfs: Option<Arc<EuvPakArchive>>) -> Self {
        Self::build_internal(budget, vfs, StreamExecutionMode::CooperativeTimeSliced, 0)
    }

    /// Creates an `AssetStreamCoordinator` with an explicit native background worker thread count.
    ///
    /// # Arguments
    ///
    /// - `AssetStreamBudget` - RAM, VRAM, decode time, and GPU upload ceilings.
    /// - `Option<Arc<EuvPakArchive>>` - Optional mounted `.euvpak` virtual filesystem archive.
    /// - `usize` - Background worker thread count (`0` selects cooperative time-sliced mode).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured streaming coordinator.
    #[must_use]
    pub fn with_worker_count(
        budget: AssetStreamBudget,
        vfs: Option<Arc<EuvPakArchive>>,
        worker_count: usize,
    ) -> Self {
        let mode: StreamExecutionMode = if worker_count == 0 {
            StreamExecutionMode::CooperativeTimeSliced
        } else {
            StreamExecutionMode::AsyncWorkers
        };
        Self::build_internal(budget, vfs, mode, worker_count)
    }

    /// Internal shared constructor initializing queue, worker context, Clock-LRU residency pool, `ResourceAccountant`, and spatial prefetcher.
    ///
    /// # Arguments
    ///
    /// - `AssetStreamBudget` - Memory and per-frame ceilings.
    /// - `Option<Arc<EuvPakArchive>>` - Optional mounted `.euvpak` archive.
    /// - `StreamExecutionMode` - Async worker threads or cooperative time-sliced mode.
    /// - `usize` - Target native worker thread count.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed `AssetStreamCoordinator`.
    fn build_internal(
        budget: AssetStreamBudget,
        vfs: Option<Arc<EuvPakArchive>>,
        execution_mode: StreamExecutionMode,
        worker_count: usize,
    ) -> Self {
        let telemetry: Arc<StreamingTelemetryCounters> =
            Arc::new(StreamingTelemetryCounters::default());
        let queue: Arc<PriorityStreamQueue> = Arc::new(PriorityStreamQueue::new());
        #[cfg(not(target_arch = "wasm32"))]
        let worker_ctx: Arc<StreamWorkerContext> = Arc::new(StreamWorkerContext {
            queue: Arc::clone(&queue),
            vfs: Mutex::new(vfs.clone()),
            completed: Mutex::new(VecDeque::new()),
            completed_count: AtomicUsize::new(0),
            in_progress_workers: AtomicUsize::new(0),
            telemetry: Arc::clone(&telemetry),
        });
        let owner: ResourceOwnerId = ResourceOwnerId::new(
            ResourceOwnerKind::RenderCache,
            RESIDENCY_DEFAULT_OWNER_ID,
            1,
        );
        let residency: ProgressiveResidencyPool = ProgressiveResidencyPool::new(budget, owner);
        #[cfg(target_arch = "wasm32")]
        let _: usize = worker_count;
        Self {
            budget,
            vfs,
            telemetry,
            queue,
            #[cfg(not(target_arch = "wasm32"))]
            worker_ctx,
            #[cfg(not(target_arch = "wasm32"))]
            workers: Vec::new(),
            #[cfg(not(target_arch = "wasm32"))]
            target_worker_count: worker_count.clamp(1, STREAM_DECODER_MAX_WORKERS),
            execution_mode,
            cooperative_job: None,
            residency,
            accountant: ResourceAccountant::default(),
            spatial_grid: SpatialPrefetchGrid::default(),
            pending_gpu_uploads: VecDeque::new(),
            last_prefetch_volume: SpatialPrefetchVolume::default(),
            next_auto_texture_slot: 1,
            texture_slots: HashMap::new(),
            prefetch_scratch: Vec::new(),
            cancel_scratch: Vec::new(),
        }
    }

    /// Lazily spawns dedicated native background I/O & decode threads when `StreamExecutionMode::AsyncWorkers` is active.
    fn ensure_workers_started(&mut self) {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let Self {
                execution_mode,
                workers,
                target_worker_count,
                worker_ctx,
                ..
            } = self;
            if *execution_mode != StreamExecutionMode::AsyncWorkers || !workers.is_empty() {
                return;
            }
            for idx in 0..*target_worker_count {
                let ctx_clone: Arc<StreamWorkerContext> = Arc::clone(worker_ctx);
                let name: String = format!("{STREAM_DECODER_THREAD_PREFIX}-{idx}");
                if let Ok(handle) = Builder::new().name(name).spawn(move || {
                    stream_io_worker_loop(ctx_clone, idx);
                }) {
                    workers.push(handle);
                } else {
                    break;
                }
            }
        }
    }

    /// Allocates or retrieves a deterministic GPU bindless texture slot index for `key_hash`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Asset key hash.
    ///
    /// # Returns
    ///
    /// - `u32` - Stable bindless texture slot identifier.
    fn resolve_texture_slot(&mut self, key_hash: u64) -> u32 {
        let Self {
            texture_slots,
            next_auto_texture_slot,
            ..
        } = self;
        if let Some(&existing) = texture_slots.get(&key_hash) {
            return existing;
        }
        let assigned: u32 = *next_auto_texture_slot;
        *next_auto_texture_slot = next_auto_texture_slot.saturating_add(1);
        let _: Option<u32> = texture_slots.insert(key_hash, assigned);
        assigned
    }

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

    /// Returns the active execution mode (`AsyncWorkers` or `CooperativeTimeSliced`).
    ///
    /// # Returns
    ///
    /// - `StreamExecutionMode` - Active streaming execution mode.
    #[must_use]
    pub fn execution_mode(&self) -> StreamExecutionMode {
        let Self { execution_mode, .. } = self;
        *execution_mode
    }

    /// Replaces the active streaming budget configuration at runtime and immediately enforces new ceilings.
    ///
    /// # Arguments
    ///
    /// - `AssetStreamBudget` - Updated RAM, VRAM, and per-frame ceilings.
    pub fn set_budget(&mut self, next_budget: AssetStreamBudget) {
        let Self {
            budget,
            residency,
            accountant,
            telemetry,
            ..
        } = self;
        *budget = next_budget;
        residency.set_budget(next_budget, accountant, telemetry.as_ref());
    }

    /// Binds every `TextureMipTail` entry from the mounted `.euvpak` Mip-Tail Superblock into `TextureResidencyTier::MipTail` for instant Frame-1 visibility with zero blank pop-in.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of texture mip-tails bound immediately into VRAM residency.
    pub fn warm_bind_mip_tail_superblock(&mut self) -> usize {
        let Some(archive) = ({
            let Self { vfs, .. } = self;
            vfs.clone()
        }) else {
            return 0;
        };
        archive.advise_mip_tails_willneed();
        let mip_metas: Vec<EuvPakEntryMeta> = archive.mip_tail_entries();
        let mut bound_count: usize = 0;
        for meta in mip_metas {
            let key_hash: u64 = meta.get_path_hash();
            let slot_id: u32 = self.resolve_texture_slot(key_hash);
            let Ok(raw_bytes) = archive.read_entry_decoded(key_hash) else {
                continue;
            };
            let Ok(DecodedAssetPayload::Texture {
                width,
                height,
                total_mip_levels,
                is_srgb,
                mip_tail_bytes,
                mid_mip_bytes,
                full_res_bytes,
                rgba8,
                ..
            }) = decode_texture_payload(
                raw_bytes.as_slice(),
                StreamJobKind::TextureMipTail,
                TextureResidencyTier::MipTail,
                true,
            )
            else {
                continue;
            };
            let spec: TextureMipSpec = TextureMipSpec::new(
                key_hash,
                slot_id,
                [mip_tail_bytes, mid_mip_bytes, full_res_bytes],
                [width, height],
                total_mip_levels,
                is_srgb,
            );
            let Self {
                residency,
                accountant,
                telemetry,
                pending_gpu_uploads,
                ..
            } = self;
            telemetry.add_vfs_syscalls_saved(STREAM_SYSCALLS_SAVED_PER_LOOKUP);
            if let Ok(upload) =
                residency.bind_texture_mip_tail(spec, rgba8, accountant, telemetry.as_ref())
            {
                pending_gpu_uploads.push_back(upload);
                bound_count = bound_count.saturating_add(1);
            }
        }
        bound_count
    }

    /// Requests an asynchronous asset load by 64-bit key hash, coalescing duplicate in-flight requests and escalating priority when needed.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit FNV-1a asset key hash.
    /// - `StreamPriority` - Requested scheduling priority lane.
    ///
    /// # Returns
    ///
    /// - `StreamRequestHandle` - Handle referencing the active or coalesced request.
    pub fn request_asset(
        &mut self,
        key_hash: u64,
        priority: StreamPriority,
    ) -> StreamRequestHandle {
        let inferred_kind: StreamJobKind = {
            let Self { vfs, .. } = self;
            vfs.as_ref()
                .and_then(|archive: &Arc<EuvPakArchive>| archive.lookup_hash(key_hash))
                .map_or(StreamJobKind::RawBytes, |slice: EuvPakSlice<'_>| {
                    euvpak_kind_to_stream_job_kind(slice.get_kind())
                })
        };
        let target_tier: TextureResidencyTier = match inferred_kind {
            StreamJobKind::TextureMipTail => TextureResidencyTier::MipTail,
            StreamJobKind::TextureMip => TextureResidencyTier::FullRes,
            _ => TextureResidencyTier::Unloaded,
        };
        let texture_slot: u32 = if matches!(
            inferred_kind,
            StreamJobKind::TextureMip | StreamJobKind::TextureMipTail
        ) {
            self.resolve_texture_slot(key_hash)
        } else {
            0
        };
        self.enqueue_typed_request(
            key_hash,
            priority,
            inferred_kind,
            target_tier,
            texture_slot,
            true,
        )
    }

    /// Requests an asynchronous asset load by virtual archive path string.
    ///
    /// # Arguments
    ///
    /// - `&str` - Virtual asset path inside the mounted `.euvpak`.
    /// - `StreamPriority` - Requested scheduling priority lane.
    ///
    /// # Returns
    ///
    /// - `StreamRequestHandle` - Handle referencing the active or coalesced request.
    pub fn request_path(&mut self, path: &str, priority: StreamPriority) -> StreamRequestHandle {
        self.request_asset(hash_euvpak_path(path), priority)
    }

    /// Requests a progressive texture mipmap promotion to `target_tier` on `texture_slot`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit texture asset key hash.
    /// - `u32` - Target GPU bindless texture slot index.
    /// - `TextureResidencyTier` - Desired residency tier (`MipTail`, `MidMip`, or `FullRes`).
    /// - `StreamPriority` - Scheduling priority lane.
    /// - `bool` - True when texels use sRGB encoding.
    ///
    /// # Returns
    ///
    /// - `StreamRequestHandle` - Handle referencing the active or coalesced texture streaming job.
    pub fn request_texture(
        &mut self,
        key_hash: u64,
        texture_slot: u32,
        target_tier: TextureResidencyTier,
        priority: StreamPriority,
        is_srgb: bool,
    ) -> StreamRequestHandle {
        {
            let Self { texture_slots, .. } = self;
            let _: Option<u32> = texture_slots.insert(key_hash, texture_slot);
        }
        let kind: StreamJobKind = if target_tier == TextureResidencyTier::MipTail {
            StreamJobKind::TextureMipTail
        } else {
            StreamJobKind::TextureMip
        };
        self.enqueue_typed_request(key_hash, priority, kind, target_tier, texture_slot, is_srgb)
    }

    /// Internal typed request entry point handling resident cache hits, VFS syscall accounting, and 4-lane coalescing.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    /// - `StreamPriority` - Priority lane.
    /// - `StreamJobKind` - Decode job category.
    /// - `TextureResidencyTier` - Target texture tier.
    /// - `u32` - GPU texture slot index.
    /// - `bool` - sRGB color space flag.
    ///
    /// # Returns
    ///
    /// - `StreamRequestHandle` - Active or coalesced request handle.
    fn enqueue_typed_request(
        &mut self,
        key_hash: u64,
        priority: StreamPriority,
        kind: StreamJobKind,
        target_tier: TextureResidencyTier,
        texture_slot: u32,
        is_srgb: bool,
    ) -> StreamRequestHandle {
        let already_satisfied: bool = {
            let Self { residency, .. } = self;
            if matches!(
                kind,
                StreamJobKind::TextureMip | StreamJobKind::TextureMipTail
            ) {
                let current_tier: TextureResidencyTier = residency.texture_tier(key_hash);
                current_tier != TextureResidencyTier::Unloaded
                    && (current_tier as u8) >= (target_tier as u8)
            } else {
                residency.contains(key_hash)
            }
        };
        if already_satisfied {
            let Self {
                residency,
                telemetry,
                ..
            } = self;
            let _: bool = residency.touch(key_hash);
            telemetry.add_coalesced_hit();
            return StreamRequestHandle::new(key_hash, priority, CancelToken::new());
        }
        self.ensure_workers_started();
        let Self {
            vfs,
            queue,
            telemetry,
            ..
        } = self;
        let work: StreamWorkItem = StreamWorkItem {
            key_hash,
            priority,
            kind,
            target_tier,
            texture_slot,
            generation: 0,
            cancel_token: CancelToken::new(),
            is_srgb,
        };
        let (handle, is_new): (StreamRequestHandle, bool) =
            queue.enqueue_or_coalesce(work, telemetry.as_ref());
        if is_new
            && let Some(archive) = vfs.as_ref()
            && archive.lookup_hash(key_hash).is_some()
        {
            telemetry.add_vfs_syscalls_saved(STREAM_SYSCALLS_SAVED_PER_LOOKUP);
        }
        handle
    }

    /// Dynamically reprioritizes an in-flight streaming request onto `new_priority`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash.
    /// - `StreamPriority` - Updated priority lane.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when an active in-flight job was reprioritized.
    pub fn reprioritize(&mut self, key_hash: u64, new_priority: StreamPriority) -> bool {
        let Self { queue, .. } = self;
        queue.reprioritize(key_hash, new_priority)
    }

    /// Cancels an in-flight asset request by 64-bit key hash.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit asset key hash to cancel.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when an active request was found and marked cancelled.
    pub fn cancel(&mut self, key_hash: u64) -> bool {
        let Self {
            queue,
            telemetry,
            cooperative_job,
            spatial_grid,
            ..
        } = self;
        spatial_grid.unmark_prefetched(key_hash);
        if let Some(in_prog) = cooperative_job.as_ref()
            && in_prog.work.get_key_hash() == key_hash
        {
            in_prog.work.get_cancel_token().cancel();
            *cooperative_job = None;
        }
        queue.cancel(key_hash, telemetry.as_ref())
    }

    /// Registers a spatial asset anchor for velocity-predicted lookahead prefetching.
    ///
    /// # Arguments
    ///
    /// - `SpatialAssetAnchor` - World-space bounding sphere and asset key hash.
    pub fn register_spatial_asset(&mut self, anchor: SpatialAssetAnchor) {
        let Self { spatial_grid, .. } = self;
        spatial_grid.register_anchor(anchor);
    }

    /// Updates screen-space coverage for a texture and automatically schedules promotion when visible coverage demands a higher mip tier.
    ///
    /// # Arguments
    ///
    /// - `u64` - Deterministic 64-bit texture asset key hash.
    /// - `f32` - Projected screen-space size in pixels.
    /// - `f32` - Camera distance in meters.
    /// - `bool` - Whether the textured surface is currently visible in the frustum.
    ///
    /// # Returns
    ///
    /// - `TextureResidencyTier` - Target residency tier computed from screen-space coverage.
    pub fn report_texture_coverage(
        &mut self,
        key_hash: u64,
        screen_coverage_px: f32,
        camera_distance: f32,
        visible: bool,
    ) -> TextureResidencyTier {
        let (desired_tier, current_tier): (TextureResidencyTier, TextureResidencyTier) = {
            let Self { residency, .. } = self;
            let desired: TextureResidencyTier = residency.report_texture_coverage(
                key_hash,
                screen_coverage_px,
                camera_distance,
                visible,
            );
            let current: TextureResidencyTier = residency.texture_tier(key_hash);
            (desired, current)
        };
        if visible && (desired_tier as u8) > (current_tier as u8) {
            let slot_id: u32 = self.resolve_texture_slot(key_hash);
            let _: StreamRequestHandle = self.request_texture(
                key_hash,
                slot_id,
                desired_tier,
                StreamPriority::VisibleHigh,
                true,
            );
        }
        desired_tier
    }

    /// Updates the camera velocity-predicted spatial prefetch focus volume, schedules `PrefetchMedium` jobs ahead of arrival, and cancels trailing behind-camera prefetches.
    ///
    /// # Arguments
    ///
    /// - `[f32; 3]` - Current camera world position.
    /// - `[f32; 3]` - Current camera world velocity in meters per second.
    /// - `f32` - Spherical prefetch radius in meters.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of speculative prefetch requests enqueued for this update.
    pub fn update_camera_prefetch(
        &mut self,
        camera_pos: [f32; 3],
        camera_vel: [f32; 3],
        lookahead_radius: f32,
    ) -> usize {
        let volume: SpatialPrefetchVolume = SpatialPrefetchVolume::new(
            camera_pos,
            camera_vel,
            PREFETCH_DEFAULT_LOOKAHEAD_SECS,
            lookahead_radius.max(0.0),
        );
        {
            let Self {
                last_prefetch_volume,
                spatial_grid,
                prefetch_scratch,
                cancel_scratch,
                ..
            } = self;
            *last_prefetch_volume = volume;
            spatial_grid.query_lookahead(&volume, prefetch_scratch, cancel_scratch);
        }
        let cancel_count: usize = {
            let Self { cancel_scratch, .. } = self;
            cancel_scratch.len()
        };
        for idx in 0..cancel_count {
            let key_hash: u64 = {
                let Self { cancel_scratch, .. } = self;
                cancel_scratch[idx]
            };
            let _: bool = self.cancel(key_hash);
        }
        let prefetch_count: usize = {
            let Self {
                prefetch_scratch, ..
            } = self;
            prefetch_scratch.len()
        };
        let mut scheduled: usize = 0;
        for idx in 0..prefetch_count {
            let anchor: SpatialAssetAnchor = {
                let Self {
                    prefetch_scratch, ..
                } = self;
                prefetch_scratch[idx]
            };
            let key_hash: u64 = anchor.get_key_hash();
            let already_resident: bool = {
                let Self { residency, .. } = self;
                residency.contains(key_hash)
            };
            if already_resident {
                continue;
            }
            let target_tier: TextureResidencyTier = match anchor.get_kind() {
                StreamJobKind::TextureMipTail => TextureResidencyTier::MipTail,
                StreamJobKind::TextureMip => TextureResidencyTier::MidMip,
                _ => TextureResidencyTier::Unloaded,
            };
            let slot_id: u32 = if anchor.get_texture_slot() != 0 {
                anchor.get_texture_slot()
            } else if matches!(
                anchor.get_kind(),
                StreamJobKind::TextureMip | StreamJobKind::TextureMipTail
            ) {
                self.resolve_texture_slot(key_hash)
            } else {
                0
            };
            let _: StreamRequestHandle = self.enqueue_typed_request(
                key_hash,
                StreamPriority::PrefetchMedium,
                anchor.get_kind(),
                target_tier,
                slot_id,
                anchor.get_is_srgb(),
            );
            {
                let Self { spatial_grid, .. } = self;
                spatial_grid.mark_prefetched(key_hash);
            }
            scheduled = scheduled.saturating_add(1);
        }
        scheduled
    }

    /// Admits one decoded `CompletedStreamJob` into `ProgressiveResidencyPool` and queues any resulting GPU mip upload.
    ///
    /// # Arguments
    ///
    /// - `CompletedStreamJob` - Finished background or cooperative decode result.
    fn ingest_completed_job(&mut self, job: CompletedStreamJob) {
        let Self {
            residency,
            accountant,
            telemetry,
            pending_gpu_uploads,
            spatial_grid,
            ..
        } = self;
        spatial_grid.unmark_prefetched(job.key_hash);
        let Ok(payload) = job.payload else {
            return;
        };
        match payload {
            DecodedAssetPayload::Texture {
                width,
                height,
                total_mip_levels,
                is_srgb,
                tier,
                mip_tail_bytes,
                mid_mip_bytes,
                full_res_bytes,
                rgba8,
                ..
            } => {
                let spec: TextureMipSpec = TextureMipSpec::new(
                    job.key_hash,
                    job.texture_slot,
                    [mip_tail_bytes, mid_mip_bytes, full_res_bytes],
                    [width, height],
                    total_mip_levels,
                    is_srgb,
                );
                if let Ok((_, Some(upload))) = residency.promote_texture_tier(
                    spec,
                    tier,
                    rgba8,
                    accountant,
                    telemetry.as_ref(),
                ) {
                    pending_gpu_uploads.push_back(upload);
                }
            }
            DecodedAssetPayload::Mesh {
                vram_bytes,
                raw_bytes,
            } => {
                let _: Result<(), String> = residency.admit_asset(
                    job.key_hash,
                    ResidencyAssetKind::Mesh,
                    raw_bytes,
                    vram_bytes,
                    accountant,
                    telemetry.as_ref(),
                );
            }
            DecodedAssetPayload::Raw { kind, bytes } => {
                let _: Result<(), String> = residency.admit_asset(
                    job.key_hash,
                    kind,
                    bytes,
                    0,
                    accountant,
                    telemetry.as_ref(),
                );
            }
        }
    }

    /// Advances cooperative chunked time-sliced decoding strictly within `budget_us` microseconds on the calling thread.
    ///
    /// # Arguments
    ///
    /// - `u64` - Hard CPU decode time ceiling in microseconds (e.g. `1_500` for `1.5 ms/frame`).
    ///
    /// # Returns
    ///
    /// - `usize` - Number of asset jobs completed during this cooperative slice.
    pub fn pump_frame_cooperative(&mut self, budget_us: u64) -> usize {
        let effective_budget_us: u64 = if budget_us == 0 {
            self.budget().get_max_decode_us_per_frame()
        } else {
            budget_us
        };
        let frame_start_us: u64 = stream_now_us();
        let mut completed_count: usize = 0;
        loop {
            if stream_now_us().saturating_sub(frame_start_us) >= effective_budget_us {
                break;
            }
            let need_next_job: bool = {
                let Self {
                    cooperative_job, ..
                } = self;
                cooperative_job.is_none()
            };
            if need_next_job {
                let next_work: Option<StreamWorkItem> = {
                    let Self { queue, .. } = self;
                    queue.pop_highest_priority()
                };
                let Some(work) = next_work else {
                    break;
                };
                if work.get_cancel_token().is_cancelled() {
                    continue;
                }
                let work_key: u64 = work.get_key_hash();
                let work_gen: u64 = work.get_generation();
                let prepared: Option<CooperativeInProgressJob> = {
                    let Self { vfs, .. } = self;
                    if let Some(archive) = vfs.as_ref() {
                        if let Some((meta, payload_crc32, uncompressed_crc32)) =
                            archive.probe_toc(work_key)
                        {
                            let start: usize = meta.get_offset() as usize;
                            let end: usize =
                                start.saturating_add(meta.get_compressed_size() as usize);
                            if let Some(stored) = archive.mapping.as_bytes().get(start..end) {
                                if euvpak_crc32(stored) != payload_crc32 {
                                    None
                                } else if meta.get_is_compressed() {
                                    Some(CooperativeInProgressJob {
                                        work,
                                        accumulated_us: 0,
                                        uncompressed_crc32,
                                        running_uncompressed_crc: 0xFFFF_FFFF,
                                        lz4_decoder: Some(Lz4StreamDecoder::new(
                                            meta.get_uncompressed_size() as usize,
                                        )),
                                        compressed_bytes: stored.to_vec(),
                                        uncompressed_bytes: None,
                                    })
                                } else {
                                    Some(CooperativeInProgressJob {
                                        work,
                                        accumulated_us: 0,
                                        uncompressed_crc32,
                                        running_uncompressed_crc: 0xFFFF_FFFF,
                                        lz4_decoder: None,
                                        compressed_bytes: Vec::new(),
                                        uncompressed_bytes: Some(stored.to_vec()),
                                    })
                                }
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                };
                if let Some(job) = prepared {
                    let Self {
                        cooperative_job, ..
                    } = self;
                    *cooperative_job = Some(job);
                } else {
                    let Self {
                        queue, telemetry, ..
                    } = self;
                    let _: bool = queue.mark_completed(work_key, work_gen, telemetry.as_ref());
                    completed_count = completed_count.saturating_add(1);
                    continue;
                }
            }
            let step_start_us: u64 = stream_now_us();
            let finished_job: Option<CompletedStreamJob> = {
                let Self {
                    cooperative_job,
                    queue,
                    telemetry,
                    ..
                } = self;
                if let Some(in_prog) = cooperative_job.as_mut() {
                    if in_prog.work.get_cancel_token().is_cancelled() {
                        *cooperative_job = None;
                        None
                    } else if let Some(lz4_dec) = in_prog.lz4_decoder.as_mut() {
                        let prev_decoded: usize = lz4_dec.decoded_bytes();
                        let decode_step: Result<bool, String> = lz4_dec.decode_up_to_bytes(
                            in_prog.compressed_bytes.as_slice(),
                            STREAM_COOPERATIVE_CHUNK_BYTES,
                        );
                        if decode_step.is_ok() {
                            let newly_decoded: &[u8] = &lz4_dec.decoded_slice()[prev_decoded..];
                            in_prog.running_uncompressed_crc = euvpak_crc32_update(
                                in_prog.running_uncompressed_crc,
                                newly_decoded,
                            );
                        }
                        in_prog.accumulated_us = in_prog
                            .accumulated_us
                            .saturating_add(stream_now_us().saturating_sub(step_start_us));
                        match decode_step {
                            Ok(true) => {
                                let finished_dec: Option<Lz4StreamDecoder> =
                                    in_prog.lz4_decoder.take();
                                let final_crc: u32 = !in_prog.running_uncompressed_crc;
                                match finished_dec.map(Lz4StreamDecoder::into_output) {
                                    Some(Ok(bytes)) if final_crc == in_prog.uncompressed_crc32 => {
                                        in_prog.uncompressed_bytes = Some(bytes);
                                        in_prog.compressed_bytes.clear();
                                        None
                                    }
                                    _ => {
                                        let work: StreamWorkItem = in_prog.work.clone();
                                        *cooperative_job = None;
                                        let live: bool = queue.mark_completed(
                                            work.get_key_hash(),
                                            work.get_generation(),
                                            telemetry.as_ref(),
                                        );
                                        if live {
                                            Some(CompletedStreamJob {
                                                key_hash: work.get_key_hash(),
                                                texture_slot: work.get_texture_slot(),
                                                payload: Err(ERR_STREAM_MISSING_ENTRY.to_string()),
                                            })
                                        } else {
                                            None
                                        }
                                    }
                                }
                            }
                            Ok(false) => None,
                            Err(err) => {
                                let work: StreamWorkItem = in_prog.work.clone();
                                *cooperative_job = None;
                                let live: bool = queue.mark_completed(
                                    work.get_key_hash(),
                                    work.get_generation(),
                                    telemetry.as_ref(),
                                );
                                if live {
                                    Some(CompletedStreamJob {
                                        key_hash: work.get_key_hash(),
                                        texture_slot: work.get_texture_slot(),
                                        payload: Err(err),
                                    })
                                } else {
                                    None
                                }
                            }
                        }
                    } else if let Some(raw_bytes) = in_prog.uncompressed_bytes.take() {
                        let work: StreamWorkItem = in_prog.work.clone();
                        let payload_res: Result<DecodedAssetPayload, String> =
                            decode_uncompressed_asset(
                                raw_bytes,
                                work.get_kind(),
                                work.get_target_tier(),
                                work.get_is_srgb(),
                            );
                        let total_us: u64 = in_prog
                            .accumulated_us
                            .saturating_add(stream_now_us().saturating_sub(step_start_us));
                        *cooperative_job = None;
                        let live: bool = queue.mark_completed(
                            work.get_key_hash(),
                            work.get_generation(),
                            telemetry.as_ref(),
                        );
                        if live {
                            if payload_res.is_ok() {
                                telemetry.record_decode_us(total_us);
                            }
                            Some(CompletedStreamJob {
                                key_hash: work.get_key_hash(),
                                texture_slot: work.get_texture_slot(),
                                payload: payload_res,
                            })
                        } else {
                            None
                        }
                    } else {
                        *cooperative_job = None;
                        None
                    }
                } else {
                    None
                }
            };
            if let Some(done_job) = finished_job {
                self.ingest_completed_job(done_job);
                completed_count = completed_count.saturating_add(1);
            }
        }
        completed_count
    }

    /// Pumps completed background decodes (or executes cooperative time-sliced decode work on `wasm32`) strictly within `max_decode_us`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Maximum main-thread cooperative or ingestion budget in microseconds.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of asset jobs completed during this pump tick.
    pub fn pump_frame(&mut self, max_decode_us: u64) -> usize {
        #[cfg(target_arch = "wasm32")]
        {
            self.pump_frame_cooperative(max_decode_us)
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            if self.execution_mode() == StreamExecutionMode::CooperativeTimeSliced {
                return self.pump_frame_cooperative(max_decode_us);
            }
            let effective_budget_us: u64 = if max_decode_us == 0 {
                self.budget().get_max_decode_us_per_frame()
            } else {
                max_decode_us
            };
            let has_ready: bool = {
                let Self { worker_ctx, .. } = self;
                worker_ctx.completed_count.load(Ordering::Acquire) > 0
            };
            if !has_ready {
                return 0;
            }
            let start_us: u64 = stream_now_us();
            let mut ingested: usize = 0;
            loop {
                let next_job: Option<CompletedStreamJob> = {
                    let Self { worker_ctx, .. } = self;
                    if let Ok(mut ready) = worker_ctx.completed.lock() {
                        let popped: Option<CompletedStreamJob> = ready.pop_front();
                        if popped.is_some() {
                            let _: usize =
                                worker_ctx.completed_count.fetch_sub(1, Ordering::AcqRel);
                        }
                        popped
                    } else {
                        None
                    }
                };
                let Some(job) = next_job else {
                    break;
                };
                self.ingest_completed_job(job);
                ingested = ingested.saturating_add(1);
                if stream_now_us().saturating_sub(start_us) >= effective_budget_us {
                    break;
                }
            }
            ingested
        }
    }

    /// Returns `true` when all queued, in-flight, cooperative, and completed streaming work has drained.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the coordinator is completely idle.
    #[must_use]
    pub fn is_idle(&self) -> bool {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let Self {
                queue,
                worker_ctx,
                cooperative_job,
                ..
            } = self;
            queue.is_empty()
                && queue.active_count() == 0
                && worker_ctx.in_progress_workers.load(Ordering::Acquire) == 0
                && worker_ctx.completed_count.load(Ordering::Acquire) == 0
                && cooperative_job.is_none()
        }
        #[cfg(target_arch = "wasm32")]
        {
            let Self {
                queue,
                cooperative_job,
                ..
            } = self;
            queue.is_empty() && queue.active_count() == 0 && cooperative_job.is_none()
        }
    }

    /// Pumps until all queued async or cooperative jobs complete or `max_wait_ms` elapses.
    ///
    /// # Arguments
    ///
    /// - `u64` - Maximum wall-clock wait duration in milliseconds.
    ///
    /// # Returns
    ///
    /// - `usize` - Total jobs completed while draining.
    pub fn pump_until_idle(&mut self, max_wait_ms: u64) -> usize {
        let deadline_us: u64 = stream_now_us().saturating_add(max_wait_ms.saturating_mul(1_000));
        let mut total_completed: usize = 0;
        loop {
            let step: usize = self.pump_frame(self.budget().get_max_decode_us_per_frame());
            total_completed = total_completed.saturating_add(step);
            if self.is_idle() || stream_now_us() >= deadline_us {
                break;
            }
            #[cfg(not(target_arch = "wasm32"))]
            if step == 0 {
                sleep(Duration::from_micros(250));
            }
        }
        total_completed
    }

    /// Drains ready incremental GPU texture mipmap uploads into `out` without exceeding `max_bytes` or `max_us`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Hard byte budget cap for this frame.
    /// - `u64` - Hard CPU time budget cap in microseconds for this frame.
    /// - `&mut Vec<GpuTextureMipUpload>` - Destination vector receiving drained mip upload payloads.
    ///
    /// # Returns
    ///
    /// - `usize` - Total bytes drained into `out`.
    pub fn drain_gpu_uploads(
        &mut self,
        max_bytes: usize,
        max_us: u64,
        out: &mut Vec<GpuTextureMipUpload>,
    ) -> usize {
        let Self {
            pending_gpu_uploads,
            ..
        } = self;
        let start_us: u64 = stream_now_us();
        let mut consumed: usize = 0;
        while let Some(front) = pending_gpu_uploads.front() {
            if max_us > 0 && consumed > 0 && stream_now_us().saturating_sub(start_us) >= max_us {
                break;
            }
            let payload_len: usize = front.get_rgba8().len();
            if consumed > 0 && consumed.saturating_add(payload_len) > max_bytes {
                break;
            }
            if let Some(upload) = pending_gpu_uploads.pop_front() {
                consumed = consumed.saturating_add(payload_len);
                out.push(upload);
            }
        }
        consumed
    }

    /// Returns the number of queued incremental GPU texture mipmap uploads waiting to drain.
    ///
    /// # Returns
    ///
    /// - `usize` - Pending GPU upload count.
    #[must_use]
    pub fn pending_gpu_upload_count(&self) -> usize {
        let Self {
            pending_gpu_uploads,
            ..
        } = self;
        pending_gpu_uploads.len()
    }

    /// Returns a shared reference to the O(1) Clock-LRU `ProgressiveResidencyPool`.
    ///
    /// # Returns
    ///
    /// - `&ProgressiveResidencyPool` - Active residency pool reference.
    #[must_use]
    pub fn residency_pool(&self) -> &ProgressiveResidencyPool {
        let Self { residency, .. } = self;
        residency
    }

    /// Returns a mutable reference to the O(1) Clock-LRU `ProgressiveResidencyPool`.
    ///
    /// # Returns
    ///
    /// - `&mut ProgressiveResidencyPool` - Mutable residency pool reference.
    pub fn residency_pool_mut(&mut self) -> &mut ProgressiveResidencyPool {
        let Self { residency, .. } = self;
        residency
    }

    /// Returns a shared reference to the authoritative streaming `ResourceAccountant`.
    ///
    /// # Returns
    ///
    /// - `&ResourceAccountant` - Resource accountant reference.
    #[must_use]
    pub fn accountant(&self) -> &ResourceAccountant {
        let Self { accountant, .. } = self;
        accountant
    }

    /// Returns a mutable reference to the authoritative streaming `ResourceAccountant`.
    ///
    /// # Returns
    ///
    /// - `&mut ResourceAccountant` - Mutable resource accountant reference.
    pub fn accountant_mut(&mut self) -> &mut ResourceAccountant {
        let Self { accountant, .. } = self;
        accountant
    }

    /// Releases every resident asset from the Clock-LRU residency pool and removes all tracked handles from `ResourceAccountant` with zero leaks.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of resident assets released.
    pub fn release_all_resident(&mut self) -> usize {
        let Self {
            residency,
            accountant,
            telemetry,
            pending_gpu_uploads,
            ..
        } = self;
        pending_gpu_uploads.clear();
        residency.release_all(accountant, telemetry.as_ref())
    }

    /// Returns a lock-free snapshot of active streaming telemetry counters.
    ///
    /// # Returns
    ///
    /// - `StreamingTelemetrySnapshot` - Current streaming telemetry counters and memory budgets.
    #[must_use]
    pub fn telemetry_snapshot(&self) -> StreamingTelemetrySnapshot {
        let Self {
            budget, telemetry, ..
        } = self;
        telemetry.snapshot(
            budget.get_ram_budget_bytes(),
            budget.get_vram_budget_bytes(),
        )
    }
}