Skip to main content

euv_core/render/ring/
impl.rs

1use super::*;
2
3/// Default bounded GPU resource ring configured for 3 in-flight frames and 16 MiB scroll tile cache.
4impl Default for GpuResourceRing {
5    /// Creates a bounded GPU resource ring with default staging and tile budgets.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Initialized GPU resource ring.
10    fn default() -> Self {
11        Self::with_limits(
12            GPU_RING_DEFAULT_SLOTS,
13            GPU_RING_DEFAULT_MAX_TOTAL_BYTES,
14            GPU_TILE_CACHE_DEFAULT_BUDGET_BYTES,
15        )
16    }
17}
18
19/// Bounded staging ring acquisition, fence completion, persistent scroll tile caching, and deferred reclamation for `GpuResourceRing`.
20impl GpuResourceRing {
21    /// Creates a bounded GPU resource ring with explicit staging slot count, staging byte ceiling, and tile budget.
22    ///
23    /// # Arguments
24    ///
25    /// - `usize` - Maximum number of staging ring slots (`>= 1`).
26    /// - `usize` - Maximum aggregate staging bytes across all slots.
27    /// - `usize` - Maximum resident bytes for persistent scroll tile textures.
28    ///
29    /// # Returns
30    ///
31    /// - `Self` - Configured GPU resource ring.
32    #[must_use]
33    pub fn with_limits(max_slots: usize, max_total_bytes: usize, tile_budget_bytes: usize) -> Self {
34        let clamped_slots: usize = max_slots.max(1);
35        let clamped_staging: usize = max_total_bytes.max(4096);
36        let clamped_tiles: usize = tile_budget_bytes.max(GPU_TILE_CACHE_MIN_BUDGET_BYTES);
37        let mut slots: Vec<GpuStagingSlot> = Vec::with_capacity(clamped_slots);
38        for idx in 0..clamped_slots {
39            slots.push(GpuStagingSlot {
40                slot_index: idx,
41                handle: RenderResourceHandle::new(
42                    (idx as u64) + 1,
43                    1,
44                    RenderResourceKind::StagingSlot,
45                    0,
46                    0,
47                ),
48                capacity_bytes: 0,
49                used_bytes: 0,
50                fence_id: 0,
51                in_flight: false,
52                reuse_count: 0,
53            });
54        }
55        Self {
56            max_slots: clamped_slots,
57            max_total_bytes: clamped_staging,
58            slots,
59            next_fence_id: 1,
60            completed_fence_id: 0,
61            next_handle_id: (clamped_slots as u64) + 1,
62            cursor: 0,
63            total_allocations: 0,
64            total_reuses: 0,
65            dropped_prefetch_uploads: 0,
66            deferred_frame_uploads: 0,
67            tile_budget_bytes: clamped_tiles,
68            tile_resident_bytes: 0,
69            tile_clock: 0,
70            tile_hits: 0,
71            tile_misses: 0,
72            tile_evictions: 0,
73            tiles: Vec::new(),
74            pending_reclaim: Vec::new(),
75            pending_reclaim_bytes: 0,
76            reclaimed_count: 0,
77        }
78    }
79
80    /// Allocates the next monotonic `RenderResourceHandle` of `kind` and `byte_size`.
81    ///
82    /// # Arguments
83    ///
84    /// - `&Self` - Mutable GPU resource ring.
85    /// - `RenderResourceKind` - Resource category.
86    /// - `usize` - Resident byte size.
87    /// - `u64` - Associated GPU fence ID.
88    ///
89    /// # Returns
90    ///
91    /// - `RenderResourceHandle` - Fresh generation-1 handle.
92    fn alloc_handle(
93        &mut self,
94        kind: RenderResourceKind,
95        byte_size: usize,
96        fence_id: u64,
97    ) -> RenderResourceHandle {
98        let id: u64 = self.get_next_handle_id();
99        self.set_next_handle_id(id.wrapping_add(1).max(1));
100        RenderResourceHandle::new(id, 1, kind, byte_size, fence_id)
101    }
102
103    /// Acquires an idle or fence-completed staging slot for `required_bytes` without unbounded queue growth.
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Mutable GPU resource ring.
108    /// - `usize` - Upload payload size in bytes.
109    /// - `GpuUploadPriority` - Priority deciding whether a full ring drops prefetch or defers the frame.
110    ///
111    /// # Returns
112    ///
113    /// - `GpuRingAcquireResult` - Acquired slot and fence ID, or bounded backpressure status.
114    pub fn acquire_staging(
115        &mut self,
116        required_bytes: usize,
117        priority: GpuUploadPriority,
118    ) -> GpuRingAcquireResult {
119        let completed: u64 = self.get_completed_fence_id();
120        let slot_count: usize = self.get_slots().len();
121        let start: usize = self.get_cursor() % slot_count.max(1);
122        let mut chosen: Option<usize> = None;
123        for step in 0..slot_count {
124            let idx: usize = (start + step) % slot_count;
125            let slot: GpuStagingSlot = self.get_slots()[idx];
126            if !slot.get_in_flight() || slot.get_fence_id() <= completed {
127                chosen = Some(idx);
128                break;
129            }
130        }
131        let Some(slot_idx) = chosen else {
132            return match priority {
133                GpuUploadPriority::OptionalPrefetch => {
134                    self.set_dropped_prefetch_uploads(
135                        self.get_dropped_prefetch_uploads().saturating_add(1),
136                    );
137                    GpuRingAcquireResult::DroppedPrefetchRingFull
138                }
139                GpuUploadPriority::RequiredFrame => {
140                    self.set_deferred_frame_uploads(
141                        self.get_deferred_frame_uploads().saturating_add(1),
142                    );
143                    GpuRingAcquireResult::DeferredFrameRingFull
144                }
145            };
146        };
147        let fence_id: u64 = self.get_next_fence_id();
148        self.set_next_fence_id(fence_id.wrapping_add(1).max(1));
149        let prev_slot: GpuStagingSlot = self.get_slots()[slot_idx];
150        let old_cap: usize = prev_slot.get_capacity_bytes();
151        let mut total_other_bytes: usize = 0;
152        for (idx, s) in self.get_slots().iter().enumerate() {
153            if idx != slot_idx {
154                total_other_bytes = total_other_bytes.saturating_add(s.get_capacity_bytes());
155            }
156        }
157        let needed_cap: usize = if required_bytes == 0 {
158            old_cap.max(4096)
159        } else {
160            required_bytes
161                .max(GPU_RING_DEFAULT_SLOT_BYTES.min(required_bytes.next_power_of_two()))
162                .next_power_of_two()
163        };
164        let mut reused: bool = old_cap >= required_bytes && old_cap > 0;
165        let new_cap: usize = if reused {
166            old_cap
167        } else {
168            let max_allowed: usize = self.get_max_total_bytes().saturating_sub(total_other_bytes);
169            if required_bytes > max_allowed && priority == GpuUploadPriority::OptionalPrefetch {
170                self.set_dropped_prefetch_uploads(
171                    self.get_dropped_prefetch_uploads().saturating_add(1),
172                );
173                return GpuRingAcquireResult::DroppedPrefetchRingFull;
174            }
175            if old_cap > 0 && prev_slot.get_fence_id() > completed {
176                self.queue_deferred_reclaim(prev_slot.get_handle(), prev_slot.get_fence_id());
177            }
178            reused = false;
179            needed_cap.min(max_allowed.max(required_bytes))
180        };
181        let slot_ref: &mut GpuStagingSlot = &mut self.get_mut_slots()[slot_idx];
182        if !reused {
183            let next_gen: u32 = slot_ref
184                .get_handle()
185                .get_generation()
186                .wrapping_add(1)
187                .max(1);
188            let mut next_handle: RenderResourceHandle = slot_ref.get_handle();
189            next_handle.set_generation(next_gen);
190            next_handle.set_byte_size(new_cap);
191            next_handle.set_fence_id(fence_id);
192            slot_ref.set_handle(next_handle);
193            slot_ref.set_capacity_bytes(new_cap);
194        } else {
195            let mut next_handle: RenderResourceHandle = slot_ref.get_handle();
196            next_handle.set_fence_id(fence_id);
197            slot_ref.set_handle(next_handle);
198            slot_ref.set_reuse_count(slot_ref.get_reuse_count().saturating_add(1));
199        }
200        slot_ref.set_used_bytes(required_bytes);
201        slot_ref.set_fence_id(fence_id);
202        slot_ref.set_in_flight(true);
203        if reused {
204            self.set_total_reuses(self.get_total_reuses().saturating_add(1));
205        } else {
206            self.set_total_allocations(self.get_total_allocations().saturating_add(1));
207        }
208        self.set_cursor((slot_idx + 1) % slot_count.max(1));
209        GpuRingAcquireResult::Acquired {
210            slot_index: slot_idx,
211            fence_id,
212            reused,
213        }
214    }
215
216    /// Marks GPU fence `fence_id` complete, releasing finished staging slots and reclaiming deferred GPU resources.
217    ///
218    /// # Arguments
219    ///
220    /// - `&Self` - Mutable GPU resource ring.
221    /// - `u64` - Completed monotonic GPU fence identifier.
222    ///
223    /// # Returns
224    ///
225    /// - `usize` - Number of deferred GPU resources reclaimed by this fence completion.
226    pub fn complete_fence(&mut self, fence_id: u64) -> usize {
227        if fence_id > self.get_completed_fence_id() {
228            self.set_completed_fence_id(fence_id);
229        }
230        let completed: u64 = self.get_completed_fence_id();
231        for slot in self.get_mut_slots().iter_mut() {
232            if slot.get_in_flight() && slot.get_fence_id() <= completed {
233                slot.set_in_flight(false);
234            }
235        }
236        let Self {
237            pending_reclaim,
238            pending_reclaim_bytes,
239            reclaimed_count,
240            ..
241        } = self;
242        let before: usize = pending_reclaim.len();
243        let mut reclaimed_bytes: usize = 0;
244        pending_reclaim.retain(|item: &DeferredGpuReclaim| {
245            if item.get_retire_fence_id() <= completed {
246                reclaimed_bytes = reclaimed_bytes.saturating_add(item.get_byte_size());
247                false
248            } else {
249                true
250            }
251        });
252        let reclaimed_now: usize = before.saturating_sub(pending_reclaim.len());
253        *pending_reclaim_bytes = pending_reclaim_bytes.saturating_sub(reclaimed_bytes);
254        *reclaimed_count = reclaimed_count.saturating_add(reclaimed_now as u64);
255        reclaimed_now
256    }
257
258    /// Returns the number of staging slots currently in flight on the GPU.
259    ///
260    /// # Arguments
261    ///
262    /// - `&Self` - GPU resource ring reference.
263    ///
264    /// # Returns
265    ///
266    /// - `usize` - Count of in-flight staging slots.
267    #[must_use]
268    pub fn in_flight_slot_count(&self) -> usize {
269        let completed: u64 = self.get_completed_fence_id();
270        self.get_slots()
271            .iter()
272            .filter(|s: &&GpuStagingSlot| s.get_in_flight() && s.get_fence_id() > completed)
273            .count()
274    }
275
276    /// Returns total allocated bytes across all staging buffer slots.
277    ///
278    /// # Arguments
279    ///
280    /// - `&Self` - GPU resource ring reference.
281    ///
282    /// # Returns
283    ///
284    /// - `usize` - Aggregate staging buffer bytes.
285    #[must_use]
286    pub fn staging_allocated_bytes(&self) -> usize {
287        self.get_slots()
288            .iter()
289            .fold(0_usize, |acc: usize, s: &GpuStagingSlot| {
290                acc.saturating_add(s.get_capacity_bytes())
291            })
292    }
293
294    /// Queues an evicted GPU resource handle for fence-deferred reclamation.
295    ///
296    /// # Arguments
297    ///
298    /// - `&Self` - Mutable GPU resource ring.
299    /// - `RenderResourceHandle` - Evicted resource handle.
300    /// - `u64` - Fence ID that must complete before release.
301    fn queue_deferred_reclaim(&mut self, handle: RenderResourceHandle, retire_fence_id: u64) {
302        let bytes: usize = handle.get_byte_size();
303        if retire_fence_id <= self.get_completed_fence_id() {
304            self.set_reclaimed_count(self.get_reclaimed_count().saturating_add(1));
305            return;
306        }
307        self.get_mut_pending_reclaim().push(DeferredGpuReclaim::new(
308            handle,
309            retire_fence_id,
310            bytes,
311        ));
312        self.set_pending_reclaim_bytes(self.get_pending_reclaim_bytes().saturating_add(bytes));
313    }
314
315    /// Marks all cached scroll tiles as non-visible before starting a new frame's visibility pass.
316    ///
317    /// # Arguments
318    ///
319    /// - `&Self` - Mutable GPU resource ring.
320    pub fn begin_tile_frame(&mut self) {
321        for tile in self.get_mut_tiles().iter_mut() {
322            tile.set_visible_this_frame(false);
323        }
324    }
325
326    /// Looks up or allocates a persistent scroll tile texture, touching LRU age and tagging `fence_id`.
327    ///
328    /// # Arguments
329    ///
330    /// - `&Self` - Mutable GPU resource ring.
331    /// - `GpuScrollTileKey` - Content/DPI/layer key for the tile.
332    /// - `u32` - Tile physical width in pixels.
333    /// - `u32` - Tile physical height in pixels.
334    /// - `u64` - Active frame GPU fence identifier.
335    /// - `bool` - Whether this tile is visible in the current viewport.
336    ///
337    /// # Returns
338    ///
339    /// - `(RenderResourceHandle, bool)` - Tile handle and `true` on cache hit (`false` on fresh miss).
340    pub fn acquire_scroll_tile(
341        &mut self,
342        key: GpuScrollTileKey,
343        width: u32,
344        height: u32,
345        fence_id: u64,
346        visible: bool,
347    ) -> (RenderResourceHandle, bool) {
348        let next_tick: u64 = self.get_tile_clock().wrapping_add(1);
349        self.set_tile_clock(next_tick);
350        let hit_idx: Option<usize> = self
351            .get_tiles()
352            .iter()
353            .position(|entry: &GpuScrollTileEntry| entry.get_key() == key);
354        if let Some(idx) = hit_idx {
355            let tile_ref: &mut GpuScrollTileEntry = &mut self.get_mut_tiles()[idx];
356            tile_ref.set_last_used_tick(next_tick);
357            tile_ref.set_last_fence_id(fence_id.max(tile_ref.get_last_fence_id()));
358            if visible {
359                tile_ref.set_visible_this_frame(true);
360            }
361            let handle: RenderResourceHandle = tile_ref.get_handle();
362            self.set_tile_hits(self.get_tile_hits().saturating_add(1));
363            return (handle, true);
364        }
365        let byte_size: usize = (width.max(1) as usize)
366            .saturating_mul(height.max(1) as usize)
367            .saturating_mul(4);
368        let handle: RenderResourceHandle =
369            self.alloc_handle(RenderResourceKind::TileLayer, byte_size, fence_id);
370        self.get_mut_tiles().push(GpuScrollTileEntry {
371            key,
372            handle,
373            width: width.max(1),
374            height: height.max(1),
375            byte_size,
376            last_used_tick: next_tick,
377            last_fence_id: fence_id,
378            visible_this_frame: visible,
379        });
380        self.set_tile_resident_bytes(self.get_tile_resident_bytes().saturating_add(byte_size));
381        self.set_tile_misses(self.get_tile_misses().saturating_add(1));
382        self.evict_cold_tiles_to_budget(self.get_tile_budget_bytes());
383        (handle, false)
384    }
385
386    /// Invalidates all cached scroll tiles belonging to a destroyed or invalidated layer node or old DPI scale.
387    ///
388    /// # Arguments
389    ///
390    /// - `&Self` - Mutable GPU resource ring.
391    /// - `Option<NodeId>` - Optional specific layer node to invalidate (`None` invalidates all non-matching DPI tiles).
392    /// - `Option<f32>` - Optional active DPI scale; tiles with a different scale are evicted cleanly.
393    ///
394    /// # Returns
395    ///
396    /// - `usize` - Number of invalidated tiles moved to fence-deferred reclamation.
397    pub fn invalidate_scroll_tiles(
398        &mut self,
399        layer_node: Option<NodeId>,
400        active_dpr: Option<f32>,
401    ) -> usize {
402        let target_dpr_bits: Option<u32> = active_dpr.map(|d: f32| d.max(0.5).to_bits());
403        let mut evicted: Vec<GpuScrollTileEntry> = Vec::new();
404        self.get_mut_tiles().retain(|entry: &GpuScrollTileEntry| {
405            let match_node: bool = layer_node.is_some_and(|nid: NodeId| {
406                entry.get_key().get_layer_node_index() == nid.get_index()
407                    && entry.get_key().get_layer_node_gen() == nid.get_generation()
408            });
409            let mismatch_dpr: bool =
410                target_dpr_bits.is_some_and(|bits: u32| entry.get_key().get_dpr_bits() != bits);
411            if match_node || mismatch_dpr {
412                evicted.push(*entry);
413                false
414            } else {
415                true
416            }
417        });
418        let count: usize = evicted.len();
419        for item in evicted.into_iter() {
420            self.set_tile_resident_bytes(
421                self.get_tile_resident_bytes()
422                    .saturating_sub(item.get_byte_size()),
423            );
424            self.set_tile_evictions(self.get_tile_evictions().saturating_add(1));
425            self.queue_deferred_reclaim(item.get_handle(), item.get_last_fence_id());
426        }
427        count
428    }
429
430    /// Trims invisible cold scroll tiles down to `target_bytes`, never evicting currently visible tiles.
431    ///
432    /// # Arguments
433    ///
434    /// - `&Self` - Mutable GPU resource ring.
435    /// - `usize` - Target resident VRAM ceiling in bytes.
436    ///
437    /// # Returns
438    ///
439    /// - `usize` - Number of cold tiles evicted.
440    pub fn evict_cold_tiles_to_budget(&mut self, target_bytes: usize) -> usize {
441        if self.get_tile_resident_bytes() <= target_bytes || self.get_tiles().is_empty() {
442            return 0;
443        }
444        let mut cold_indices: Vec<(u64, usize)> = Vec::new();
445        for (idx, tile) in self.get_tiles().iter().enumerate() {
446            if !tile.get_visible_this_frame() {
447                cold_indices.push((tile.get_last_used_tick(), idx));
448            }
449        }
450        cold_indices.sort_unstable_by_key(|pair: &(u64, usize)| pair.0);
451        let mut drop_flags: Vec<bool> = vec![false; self.get_tiles().len()];
452        let mut rem_bytes: usize = self.get_tile_resident_bytes();
453        let mut dropped_count: usize = 0;
454        for (_, idx) in cold_indices.into_iter() {
455            if rem_bytes <= target_bytes {
456                break;
457            }
458            drop_flags[idx] = true;
459            rem_bytes = rem_bytes.saturating_sub(self.get_tiles()[idx].get_byte_size());
460            dropped_count += 1;
461        }
462        if dropped_count == 0 {
463            return 0;
464        }
465        let mut evicted: Vec<GpuScrollTileEntry> = Vec::with_capacity(dropped_count);
466        let mut write_idx: usize = 0;
467        for (read_idx, &dropped) in drop_flags.iter().enumerate() {
468            if dropped {
469                evicted.push(self.get_tiles()[read_idx]);
470            } else {
471                if write_idx != read_idx {
472                    self.get_mut_tiles().swap(write_idx, read_idx);
473                }
474                write_idx += 1;
475            }
476        }
477        self.get_mut_tiles().truncate(write_idx);
478        for item in evicted.into_iter() {
479            self.set_tile_resident_bytes(
480                self.get_tile_resident_bytes()
481                    .saturating_sub(item.get_byte_size()),
482            );
483            self.set_tile_evictions(self.get_tile_evictions().saturating_add(1));
484            self.queue_deferred_reclaim(item.get_handle(), item.get_last_fence_id());
485        }
486        dropped_count
487    }
488
489    /// Shrinks the persistent tile cache budget under memory pressure and evicts invisible cold tiles immediately.
490    ///
491    /// # Arguments
492    ///
493    /// - `&Self` - Mutable GPU resource ring.
494    /// - `f32` - Retained budget fraction in `(0.0..=1.0]`.
495    ///
496    /// # Returns
497    ///
498    /// - `usize` - Number of cold tiles evicted.
499    pub fn apply_retention_ratio(&mut self, retain_ratio: f32) -> usize {
500        let clamped: f32 = retain_ratio.clamp(0.1, 1.0);
501        let target: usize = ((GPU_TILE_CACHE_DEFAULT_BUDGET_BYTES as f32) * clamped)
502            .round()
503            .max(GPU_TILE_CACHE_MIN_BUDGET_BYTES as f32) as usize;
504        self.set_tile_budget_bytes(target);
505        self.evict_cold_tiles_to_budget(target)
506    }
507
508    /// Returns total live GPU bytes combining staging slots, resident scroll tiles, and pending fence-deferred bytes.
509    ///
510    /// # Arguments
511    ///
512    /// - `&Self` - GPU resource ring reference.
513    ///
514    /// # Returns
515    ///
516    /// - `usize` - Total live GPU allocation bytes.
517    #[must_use]
518    pub fn total_live_gpu_bytes(&self) -> usize {
519        self.staging_allocated_bytes()
520            .saturating_add(self.get_tile_resident_bytes())
521            .saturating_add(self.get_pending_reclaim_bytes())
522    }
523}