Skip to main content

euv_core/render/gpu/
impl.rs

1use super::*;
2
3/// Default `NativeGpuDriver` targets headless recording fallback.
4impl Default for NativeGpuDriver {
5    /// Creates a headless `NativeGpuDriver`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Headless GPU driver.
10    fn default() -> Self {
11        Self::probe(GraphicsBackend::Headless)
12    }
13}
14
15/// Construction, surface attachment, texture dirty-rect upload, and pipeline query helpers for `NativeGpuDriver`.
16impl NativeGpuDriver {
17    /// Probes the active OS GPU hardware, loads or compiles cached native pipelines, and returns a live `NativeGpuDriver`.
18    ///
19    /// # Arguments
20    ///
21    /// - `GraphicsBackend` - Requested graphics backend.
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Initialized native GPU driver with automatic headless fallback.
26    #[must_use]
27    pub fn probe(backend: GraphicsBackend) -> Self {
28        let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
29        let mut fallback: RecordingGpuDriver = RecordingGpuDriver::default();
30        fallback.set_backend_kind(backend);
31        Self {
32            adapter: probed.adapter,
33            device_handle: probed.device_handle,
34            queue_handle: probed.queue_handle,
35            library_handle: probed.library_handle,
36            pipeline_handle: probed.pipeline_handle,
37            blur_pipeline_handle: probed.blur_pipeline_handle,
38            surface_layer_handle: 0,
39            glyph_r8_texture_handle: probed.dummy_r8_tex,
40            glyph_rgba8_texture_handle: probed.dummy_rgba8_tex,
41            image_texture_handle: retain_native_gpu_object(probed.dummy_rgba8_tex),
42            external_texture_handle: 0,
43            ring_slots: [NativeGpuRingSlot::default(); GPU_DRIVER_RING_SLOTS],
44            ring_cursor: 0,
45            staging_buffer_handle: 0,
46            staging_contents_ptr: 0,
47            staging_buffer_capacity: 0,
48            submitted_frames: 0,
49            uploaded_instances: 0,
50            uploaded_bytes: 0,
51            last_upload_bytes: 0,
52            last_submitted_batches: 0,
53            staging_reallocations: 0,
54            last_presented_time_ns: 0,
55            last_gpu_exec_ns: 0,
56            #[cfg(any(target_os = "macos", target_os = "ios"))]
57            scratch_primitives: Vec::new(),
58            fallback,
59        }
60    }
61
62    /// Re-initializes the GPU driver for `backend`, releasing any previously retained OS handles.
63    ///
64    /// # Arguments
65    ///
66    /// - `GraphicsBackend` - Target graphics backend.
67    pub fn switch_backend(&mut self, backend: GraphicsBackend) {
68        if self.get_adapter().get_backend() == backend {
69            return;
70        }
71        *self = Self::probe(backend);
72    }
73
74    /// Attaches a native `CAMetalLayer*` (or equivalent surface layer) for zero-readback hardware presentation.
75    ///
76    /// # Arguments
77    ///
78    /// - `usize` - Native `CAMetalLayer*` pointer (`0` detaches).
79    pub fn attach_metal_layer(&mut self, layer_handle: usize) {
80        let dev: usize = self.get_device_handle();
81        let Self {
82            surface_layer_handle,
83            ..
84        } = self;
85        *surface_layer_handle = layer_handle;
86        if dev != 0 && layer_handle != 0 {
87            configure_native_metal_layer(dev, layer_handle);
88        }
89    }
90
91    /// Binds an external shared-device GPU texture handle (3D game render target or hardware video surface).
92    ///
93    /// # Arguments
94    ///
95    /// - `usize` - Native external texture handle (`0` restores fallback dummy texture).
96    pub fn set_external_texture(&mut self, texture_handle: usize) {
97        let Self {
98            external_texture_handle,
99            ..
100        } = self;
101        *external_texture_handle = texture_handle;
102    }
103
104    /// Uploads a dirty R8 or RGBA8 sub-rectangle to the resident glyph atlas or image texture on GPU.
105    ///
106    /// # Arguments
107    ///
108    /// - `GpuAtlasPixelFormat` - Target texture pixel format (`R8Unorm` or `Rgba8Unorm`).
109    /// - `u8` - Texture slot (`0` = R8 glyph atlas, `1` = RGBA8 color glyph atlas, `2` = UI image texture).
110    /// - `(u32, u32)` - Full backing texture dimensions `(width, height)`.
111    /// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
112    /// - `&[u8]` - Source pixel bytes.
113    /// - `usize` - Row stride in bytes.
114    ///
115    /// # Returns
116    ///
117    /// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly to hardware GPU memory.
118    pub fn upload_texture_dirty_rect(
119        &mut self,
120        format: GpuAtlasPixelFormat,
121        texture_slot: u8,
122        tex_dims: (u32, u32),
123        dirty_rect: (u32, u32, u32, u32),
124        bytes: &[u8],
125        bytes_per_row: usize,
126    ) -> bool {
127        let dev: usize = self.get_device_handle();
128        let Self {
129            glyph_r8_texture_handle,
130            glyph_rgba8_texture_handle,
131            image_texture_handle,
132            ..
133        } = self;
134        let target: &mut usize = match texture_slot {
135            0 => glyph_r8_texture_handle,
136            1 => glyph_rgba8_texture_handle,
137            _ => image_texture_handle,
138        };
139        upload_native_texture_dirty_rect(
140            dev,
141            target,
142            format,
143            tex_dims,
144            dirty_rect,
145            bytes,
146            bytes_per_row,
147        )
148    }
149
150    /// Returns `true` when the driver has both a live compiled GPU blur pipeline and an attached presentation surface.
151    ///
152    /// # Returns
153    ///
154    /// - `bool` - `true` when `BackdropBlur` can execute natively on GPU without CPU fallback.
155    #[must_use]
156    pub fn supports_backdrop_blur_pass(&self) -> bool {
157        self.get_blur_pipeline_handle() != 0 && self.get_surface_layer_handle() != 0
158    }
159}
160
161/// `GpuDriver` implementation uploading packed 64-byte `GpuPrimitiveInstance` streams to the active physical OS GPU.
162impl GpuDriver for NativeGpuDriver {
163    /// Returns the resolved `GraphicsBackend`.
164    ///
165    /// # Returns
166    ///
167    /// - `GraphicsBackend` - Active backend tag.
168    fn backend(&self) -> GraphicsBackend {
169        self.get_adapter().get_backend()
170    }
171
172    /// Returns the native shader source compiled by this GPU backend.
173    ///
174    /// # Returns
175    ///
176    /// - `&'static str` - Native shader program source.
177    fn shader_source(&self) -> &'static str {
178        self.get_fallback().shader_source()
179    }
180
181    /// Uploads instanced 64-byte primitive batches through the 3-slot fenced ring and records draw telemetry.
182    ///
183    /// # Arguments
184    ///
185    /// - `u32` - Surface width.
186    /// - `u32` - Surface height.
187    /// - `Color` - Surface clear color.
188    /// - `&[GpuBatch]` - Ordered draw batches.
189    ///
190    /// # Returns
191    ///
192    /// - `Result<usize, PlatformError>` - Number of submitted GPU draw calls.
193    fn submit_batches(
194        &mut self,
195        width: u32,
196        height: u32,
197        clear_color: Color,
198        batches: &[GpuBatch],
199    ) -> Result<usize, PlatformError> {
200        let uploaded: usize =
201            submit_native_gpu_ring_frame(self, width, height, clear_color, batches);
202        let frame_bytes: usize = uploaded.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
203        let Self {
204            submitted_frames,
205            uploaded_instances,
206            uploaded_bytes,
207            last_upload_bytes,
208            last_submitted_batches,
209            last_presented_time_ns,
210            last_gpu_exec_ns,
211            fallback,
212            ..
213        } = self;
214        *submitted_frames = submitted_frames.wrapping_add(1);
215        *uploaded_instances = uploaded_instances.wrapping_add(uploaded as u64);
216        *uploaded_bytes = uploaded_bytes.wrapping_add(frame_bytes as u64);
217        *last_upload_bytes = frame_bytes;
218        *last_submitted_batches = batches.len();
219        *last_presented_time_ns = native_gpu_last_presented_ns();
220        *last_gpu_exec_ns = native_gpu_last_exec_ns();
221        fallback.submit_batches(width, height, clear_color, batches)
222    }
223}
224
225/// Automatic native GPU handle cleanup when `NativeGpuDriver` is dropped.
226impl Drop for NativeGpuDriver {
227    /// Releases retained OS GPU ring buffers, in-flight command buffers, textures, pipelines, and device handles.
228    fn drop(&mut self) {
229        let Self {
230            device_handle,
231            queue_handle,
232            library_handle,
233            pipeline_handle,
234            blur_pipeline_handle,
235            glyph_r8_texture_handle,
236            glyph_rgba8_texture_handle,
237            image_texture_handle,
238            ring_slots,
239            staging_buffer_handle,
240            staging_contents_ptr,
241            staging_buffer_capacity,
242            ..
243        } = self;
244        for slot in ring_slots.iter_mut() {
245            let cmd: usize = slot.get_in_flight_cmd_buffer();
246            if cmd != 0 {
247                release_native_gpu_object(cmd);
248                slot.set_in_flight_cmd_buffer(0);
249            }
250            let buf: usize = slot.get_buffer_handle();
251            if buf != 0 {
252                release_native_gpu_object(buf);
253                slot.set_buffer_handle(0);
254                slot.set_contents_ptr(0);
255                slot.set_capacity_bytes(0);
256            }
257        }
258        *staging_buffer_handle = 0;
259        *staging_contents_ptr = 0;
260        *staging_buffer_capacity = 0;
261        release_native_gpu_object(*glyph_r8_texture_handle);
262        release_native_gpu_object(*glyph_rgba8_texture_handle);
263        release_native_gpu_object(*image_texture_handle);
264        release_native_gpu_object(*blur_pipeline_handle);
265        release_native_gpu_object(*pipeline_handle);
266        release_native_gpu_handles(*device_handle, *queue_handle, *library_handle);
267    }
268}