Skip to main content

euv_core/game/surface/
impl.rs

1use super::*;
2
3/// Validation and footprint helpers for `GpuTextureHandle`.
4impl GpuTextureHandle {
5    /// Constructs a persistent GPU texture handle bound to `(texture_id, device_id)` with exact `(width, height)` dimensions and `format`.
6    ///
7    /// # Arguments
8    ///
9    /// - `u64` - Backend-opaque GPU texture identifier.
10    /// - `u64` - Owning GPU logical device identifier.
11    /// - `u64` - Surface generation counter.
12    /// - `(u32, u32)` - Texture `(width, height)` in physical pixels.
13    /// - `GpuTextureFormat` - GPU texture pixel format.
14    /// - `u64` - Synchronization fence value.
15    /// - `bool` - Whether the texture uses top-left origin orientation.
16    ///
17    /// # Returns
18    ///
19    /// - `Self` - Constructed GPU texture handle.
20    #[must_use]
21    pub const fn new(
22        texture_id: u64,
23        device_id: u64,
24        generation: u64,
25        dimensions: (u32, u32),
26        format: GpuTextureFormat,
27        fence_value: u64,
28        origin_top_left: bool,
29    ) -> Self {
30        Self {
31            texture_id,
32            device_id,
33            generation,
34            width: dimensions.0,
35            height: dimensions.1,
36            format,
37            fence_value,
38            origin_top_left,
39        }
40    }
41
42    /// Returns `true` when this handle refers to a non-zero GPU texture with non-zero dimensions.
43    ///
44    /// # Arguments
45    ///
46    /// - `&Self` - Texture handle reference.
47    ///
48    /// # Returns
49    ///
50    /// - `bool` - Validity flag.
51    #[must_use]
52    pub const fn is_valid(&self) -> bool {
53        let Self {
54            texture_id,
55            device_id,
56            width,
57            height,
58            ..
59        } = *self;
60        texture_id != 0 && device_id != 0 && width > 0 && height > 0
61    }
62
63    /// Returns `true` when this handle belongs to `device_id` and can be composited without cross-device copies.
64    ///
65    /// # Arguments
66    ///
67    /// - `&Self` - Texture handle reference.
68    /// - `u64` - Expected logical GPU device identifier.
69    ///
70    /// # Returns
71    ///
72    /// - `bool` - `true` when valid and matching `device_id`.
73    #[must_use]
74    pub const fn matches_device(&self, expected_device: u64) -> bool {
75        let Self { device_id, .. } = *self;
76        self.is_valid() && device_id == expected_device
77    }
78
79    /// Returns bytes per pixel for this handle's `GpuTextureFormat`.
80    ///
81    /// # Arguments
82    ///
83    /// - `&Self` - Texture handle reference.
84    ///
85    /// # Returns
86    ///
87    /// - `usize` - Byte width per pixel (`4` or `8`).
88    #[must_use]
89    pub const fn bytes_per_pixel(&self) -> usize {
90        let Self { format, .. } = *self;
91        match format {
92            GpuTextureFormat::Rgba16Float => 8,
93            GpuTextureFormat::Rgba8Unorm
94            | GpuTextureFormat::Rgba8UnormSrgb
95            | GpuTextureFormat::Bgra8Unorm
96            | GpuTextureFormat::Rgb10A2Unorm => 4,
97        }
98    }
99
100    /// Returns estimated GPU texture footprint in bytes.
101    ///
102    /// # Arguments
103    ///
104    /// - `&Self` - Texture handle reference.
105    ///
106    /// # Returns
107    ///
108    /// - `usize` - Estimated GPU memory footprint in bytes.
109    #[must_use]
110    pub const fn estimated_bytes(&self) -> usize {
111        let Self { width, height, .. } = *self;
112        (width as usize)
113            .saturating_mul(height as usize)
114            .saturating_mul(self.bytes_per_pixel())
115    }
116}
117
118/// GPU compositing and isolated world/HUD dirty coordination for `GpuCompositeTarget`.
119impl GpuCompositeTarget {
120    /// Attaches a persistent GPU render target handle and logical viewport rectangle.
121    ///
122    /// # Arguments
123    ///
124    /// - `&Self` - Mutable composite target.
125    /// - `GpuTextureHandle` - Same-device GPU render target handle.
126    /// - `Rect` - Viewport destination rectangle in root logical coordinates.
127    pub fn attach_handle(&mut self, handle: GpuTextureHandle, viewport_rect: Rect) {
128        self.set_handle(handle);
129        self.set_viewport_rect(viewport_rect);
130        self.mark_world_dirty();
131    }
132
133    /// Marks the 2D/3D game world render target dirty without forcing unrelated HUD invalidations.
134    ///
135    /// # Arguments
136    ///
137    /// - `&Self` - Mutable composite target.
138    pub fn mark_world_dirty(&mut self) {
139        let next: u64 = self.get_world_revision().wrapping_add(1);
140        self.set_world_revision(next);
141    }
142
143    /// Marks only the overlaid EUV HUD dirty without forcing a full 3D/2D world re-render.
144    ///
145    /// # Arguments
146    ///
147    /// - `&Self` - Mutable composite target.
148    pub fn mark_hud_dirty(&mut self) {
149        let next: u64 = self.get_hud_revision().wrapping_add(1);
150        self.set_hud_revision(next);
151    }
152
153    /// Returns `true` when the game world target needs a fresh render pass before compositing.
154    ///
155    /// # Arguments
156    ///
157    /// - `&Self` - Composite target reference.
158    ///
159    /// # Returns
160    ///
161    /// - `bool` - `true` when `world_revision != presented_world_revision`.
162    #[must_use]
163    pub fn needs_world_render(&self) -> bool {
164        self.get_world_revision() != self.get_presented_world_revision()
165    }
166
167    /// Returns `true` when only the HUD overlay changed since the last present.
168    ///
169    /// # Arguments
170    ///
171    /// - `&Self` - Composite target reference.
172    ///
173    /// # Returns
174    ///
175    /// - `bool` - `true` when HUD is dirty while the world target is already up to date.
176    #[must_use]
177    pub fn is_hud_only_dirty(&self) -> bool {
178        !self.needs_world_render() && self.get_hud_revision() != self.get_presented_hud_revision()
179    }
180
181    /// Selects `ViewportPresentPath::GpuDirectComposite` when a valid same-device handle is attached, else `CpuPooledFallback`.
182    ///
183    /// # Arguments
184    ///
185    /// - `&Self` - Composite target reference.
186    /// - `u64` - Active compositor GPU device identifier.
187    ///
188    /// # Returns
189    ///
190    /// - `ViewportPresentPath` - Active presentation transport.
191    #[must_use]
192    pub fn resolve_present_path(&self, compositor_device_id: u64) -> ViewportPresentPath {
193        if self.get_handle().matches_device(compositor_device_id) {
194            ViewportPresentPath::GpuDirectComposite
195        } else {
196            ViewportPresentPath::CpuPooledFallback
197        }
198    }
199
200    /// Records a single-present GPU composite submission advancing fence and revision telemetry.
201    ///
202    /// # Arguments
203    ///
204    /// - `&Self` - Mutable composite target.
205    /// - `u64` - Submission fence value associated with this present pass.
206    ///
207    /// # Returns
208    ///
209    /// - `Option<GpuCompositeDescriptor>` - Descriptor for the compositor when the GPU handle is valid.
210    pub fn record_composite_present(&mut self, fence_value: u64) -> Option<GpuCompositeDescriptor> {
211        let mut handle: GpuTextureHandle = self.get_handle();
212        if !handle.is_valid() {
213            return None;
214        }
215        let hud_only: bool = self.is_hud_only_dirty();
216        handle.set_fence_value(fence_value);
217        self.set_handle(handle);
218        self.set_submitted_fence(fence_value);
219        let world_rev: u64 = self.get_world_revision();
220        let hud_rev: u64 = self.get_hud_revision();
221        self.set_presented_world_revision(world_rev);
222        self.set_presented_hud_revision(hud_rev);
223        let next_presents: u64 = self.get_zero_readback_presents().saturating_add(1);
224        self.set_zero_readback_presents(next_presents);
225        if hud_only {
226            let next_reuse: u64 = self.get_hud_only_reuses().saturating_add(1);
227            self.set_hud_only_reuses(next_reuse);
228        }
229        Some(GpuCompositeDescriptor::new(
230            self.get_viewport_rect(),
231            handle,
232            0,
233            true,
234        ))
235    }
236
237    /// Retires completed GPU fences up to `fence_value`.
238    ///
239    /// # Arguments
240    ///
241    /// - `&Self` - Mutable composite target.
242    /// - `u64` - Latest completed GPU queue fence value.
243    pub fn retire_fence(&mut self, fence_value: u64) {
244        if fence_value > self.get_completed_fence() {
245            self.set_completed_fence(fence_value);
246        }
247    }
248}
249
250/// Default triple-buffered `RenderBufferPool`.
251impl Default for RenderBufferPool {
252    /// Creates a bounded triple-buffered CPU render output pool (`3` slots).
253    ///
254    /// # Returns
255    ///
256    /// - `Self` - Default render buffer pool.
257    fn default() -> Self {
258        Self::with_capacity(RENDER_POOL_DEFAULT_SLOTS)
259    }
260}
261
262/// Bounded zero-allocation buffer pooling and fence-gated release for `RenderBufferPool`.
263impl RenderBufferPool {
264    /// Creates a bounded `RenderBufferPool` holding `slot_count` reusable slots (clamped to `1..=8`).
265    ///
266    /// # Arguments
267    ///
268    /// - `usize` - Requested bounded slot count.
269    ///
270    /// # Returns
271    ///
272    /// - `Self` - Initialized render buffer pool.
273    #[must_use]
274    pub fn with_capacity(slot_count: usize) -> Self {
275        let clamped: usize = slot_count.clamp(RENDER_POOL_MIN_SLOTS, RENDER_POOL_MAX_SLOTS);
276        let mut slots: Vec<PooledRenderBufferSlot> = Vec::with_capacity(clamped);
277        for _ in 0..clamped {
278            slots.push(PooledRenderBufferSlot::default());
279        }
280        Self {
281            state: Rc::new(RefCell::new(RenderBufferPoolState {
282                slots,
283                completed_fence: 0,
284                reuse_hits: 0,
285                backing_allocations: 0,
286                backpressure_rejections: 0,
287            })),
288        }
289    }
290
291    /// Pre-allocates backing storage for all slots for a `(width, height)` RGBA8 framebuffer so steady-state renders allocate zero bytes.
292    ///
293    /// # Arguments
294    ///
295    /// - `&Self` - Pool reference.
296    /// - `u32` - Framebuffer width in pixels.
297    /// - `u32` - Framebuffer height in pixels.
298    pub fn preallocate(&self, width: u32, height: u32) {
299        let needed: usize = (width as usize)
300            .saturating_mul(height as usize)
301            .saturating_mul(4);
302        if needed == 0 {
303            return;
304        }
305        if let Ok(mut guard) = self.get_state().try_borrow_mut() {
306            let mut grew: u64 = 0;
307            for slot in guard.get_mut_slots().iter_mut() {
308                if !slot.get_in_flight() && slot.get_pixels().capacity() < needed {
309                    slot.get_mut_pixels().reserve_exact(needed);
310                    grew += 1;
311                }
312            }
313            let next_allocs: u64 = guard.get_backing_allocations().saturating_add(grew);
314            guard.set_backing_allocations(next_allocs);
315        }
316    }
317
318    /// Acquires a free buffer slot sized for `(width, height)` RGBA8 output tagged with `fence_id`.
319    ///
320    /// Returns `None` when all bounded slots are still in flight (enforcing strict memory backpressure).
321    ///
322    /// # Arguments
323    ///
324    /// - `&Self` - Pool reference.
325    /// - `u32` - Target framebuffer width in pixels.
326    /// - `u32` - Target framebuffer height in pixels.
327    /// - `u64` - Fence value guarding reclamation of this frame.
328    ///
329    /// # Returns
330    ///
331    /// - `Option<PooledFrameLease>` - Exclusive RAII buffer lease, or `None` under backpressure.
332    #[must_use]
333    pub fn acquire(&self, width: u32, height: u32, fence_id: u64) -> Option<PooledFrameLease> {
334        let needed: usize = (width as usize)
335            .saturating_mul(height as usize)
336            .saturating_mul(4);
337        let mut guard: RefMut<'_, RenderBufferPoolState> =
338            self.get_state().try_borrow_mut().ok()?;
339        let free_idx_opt: Option<usize> = guard
340            .get_slots()
341            .iter()
342            .position(|slot: &PooledRenderBufferSlot| !slot.get_in_flight());
343        let Some(slot_index) = free_idx_opt else {
344            let rej: u64 = guard.get_backpressure_rejections().saturating_add(1);
345            guard.set_backpressure_rejections(rej);
346            return None;
347        };
348        let mut pixels: Vec<u8> = {
349            let slot: &mut PooledRenderBufferSlot = &mut guard.get_mut_slots()[slot_index];
350            slot.set_in_flight(true);
351            slot.set_checked_out(true);
352            slot.set_width(width);
353            slot.set_height(height);
354            slot.set_fence_id(fence_id);
355            let next_gen: u64 = slot.get_generation().wrapping_add(1);
356            slot.set_generation(next_gen);
357            take(slot.get_mut_pixels())
358        };
359        let generation: u64 = guard.get_slots()[slot_index].get_generation();
360        if pixels.capacity() < needed {
361            pixels.reserve_exact(needed - pixels.len());
362            let allocs: u64 = guard.get_backing_allocations().saturating_add(1);
363            guard.set_backing_allocations(allocs);
364        } else {
365            let hits: u64 = guard.get_reuse_hits().saturating_add(1);
366            guard.set_reuse_hits(hits);
367        }
368        pixels.clear();
369        drop(guard);
370        Some(PooledFrameLease {
371            state: Rc::clone(self.get_state()),
372            slot_index,
373            width,
374            height,
375            fence_id,
376            generation,
377            pixels,
378            released: false,
379        })
380    }
381
382    /// Retires all in-flight slots whose `fence_id <= completed_fence`, making them available for zero-allocation reuse.
383    ///
384    /// # Arguments
385    ///
386    /// - `&Self` - Pool reference.
387    /// - `u64` - Highest fence confirmed complete by the compositor or uploader.
388    ///
389    /// # Returns
390    ///
391    /// - `usize` - Number of slots retired back to the free set.
392    pub fn retire_fence(&self, completed_fence: u64) -> usize {
393        let Ok(mut guard) = self.get_state().try_borrow_mut() else {
394            return 0;
395        };
396        if completed_fence > guard.get_completed_fence() {
397            guard.set_completed_fence(completed_fence);
398        }
399        let mut freed: usize = 0;
400        for slot in guard.get_mut_slots().iter_mut() {
401            if slot.get_in_flight()
402                && !slot.get_checked_out()
403                && slot.get_fence_id() <= completed_fence
404            {
405                slot.set_in_flight(false);
406                freed += 1;
407            }
408        }
409        freed
410    }
411
412    /// Returns a snapshot of current pool capacity, in-flight slots, reuse hits, and backpressure rejections.
413    ///
414    /// # Arguments
415    ///
416    /// - `&Self` - Pool reference.
417    ///
418    /// # Returns
419    ///
420    /// - `RenderBufferPoolStats` - Current pool telemetry snapshot.
421    #[must_use]
422    pub fn stats(&self) -> RenderBufferPoolStats {
423        let Ok(guard) = self.get_state().try_borrow() else {
424            return RenderBufferPoolStats::default();
425        };
426        let capacity: usize = guard.get_slots().len();
427        let in_flight: usize = guard
428            .get_slots()
429            .iter()
430            .filter(|s: &&PooledRenderBufferSlot| s.get_in_flight())
431            .count();
432        RenderBufferPoolStats::new(
433            capacity,
434            in_flight,
435            capacity.saturating_sub(in_flight),
436            guard.get_reuse_hits(),
437            guard.get_backing_allocations(),
438            guard.get_backpressure_rejections(),
439        )
440    }
441}
442
443/// Buffer access, fence-gated submission, and explicit release for `PooledFrameLease`.
444impl PooledFrameLease {
445    /// Returns a read-only slice of the rendered RGBA8 pixels.
446    ///
447    /// # Arguments
448    ///
449    /// - `&Self` - Frame lease reference.
450    ///
451    /// # Returns
452    ///
453    /// - `&[u8]` - Rendered RGBA8 byte slice.
454    #[must_use]
455    pub fn as_slice(&self) -> &[u8] {
456        self.get_pixels().as_slice()
457    }
458
459    /// Updates recorded pixel dimensions after a renderer writes into `get_mut_pixels()`.
460    ///
461    /// # Arguments
462    ///
463    /// - `&Self` - Mutable frame lease.
464    /// - `u32` - Actual rendered width in pixels.
465    /// - `u32` - Actual rendered height in pixels.
466    pub fn set_dimensions(&mut self, width: u32, height: u32) {
467        self.set_width(width);
468        self.set_height(height);
469    }
470
471    /// Copies the rendered pixels into a standalone `ImageBuffer` for legacy upload callers.
472    ///
473    /// # Arguments
474    ///
475    /// - `&Self` - Frame lease reference.
476    ///
477    /// # Returns
478    ///
479    /// - `ImageBuffer` - Copied RGBA8 image buffer.
480    #[must_use]
481    pub fn to_image_buffer_copy(&self) -> ImageBuffer {
482        ImageBuffer::new(
483            self.get_width(),
484            self.get_height(),
485            self.get_pixels().clone(),
486        )
487    }
488
489    /// Returns the pixel buffer to its pool slot while keeping the slot marked `in_flight` until `RenderBufferPool::retire_fence(fence_id)` completes.
490    ///
491    /// # Arguments
492    ///
493    /// - `Self` - Consumed frame lease.
494    pub fn submit_in_flight(mut self) {
495        self.return_to_pool(true);
496    }
497
498    /// Returns the pixel buffer to its pool slot and immediately marks the slot free for reuse.
499    ///
500    /// # Arguments
501    ///
502    /// - `Self` - Consumed frame lease.
503    pub fn release_now(mut self) {
504        self.return_to_pool(false);
505    }
506
507    /// Internal helper returning backing memory to the pool slot with either fence-gated or immediate release.
508    ///
509    /// # Arguments
510    ///
511    /// - `&Self` - Mutable frame lease.
512    /// - `bool` - When `true`, keeps the slot in flight until its fence retires.
513    fn return_to_pool(&mut self, keep_in_flight: bool) {
514        if self.get_released() {
515            return;
516        }
517        self.set_released(true);
518        let slot_index: usize = self.get_slot_index();
519        let width: u32 = self.get_width();
520        let height: u32 = self.get_height();
521        let fence_id: u64 = self.get_fence_id();
522        let pixels: Vec<u8> = take(self.get_mut_pixels());
523        let Self { state, .. } = self;
524        if let Ok(mut guard) = state.try_borrow_mut() {
525            let completed: u64 = guard.get_completed_fence();
526            if let Some(slot) = guard.get_mut_slots().get_mut(slot_index) {
527                slot.set_pixels(pixels);
528                slot.set_width(width);
529                slot.set_height(height);
530                slot.set_fence_id(fence_id);
531                slot.set_checked_out(false);
532                let still_pending: bool = keep_in_flight && fence_id > completed;
533                slot.set_in_flight(still_pending);
534            }
535        }
536    }
537}
538
539/// Guaranteed buffer reclamation back into `RenderBufferPool` when a lease drops.
540impl Drop for PooledFrameLease {
541    /// Returns the leased buffer to its owning slot on drop without leaking pool capacity.
542    ///
543    /// # Arguments
544    ///
545    /// - `&Self` - Mutable frame lease being dropped.
546    fn drop(&mut self) {
547        self.return_to_pool(false);
548    }
549}