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            blur_up_pipeline_handle: probed.blur_up_pipeline_handle,
39            engine3d_pipeline_handle: probed.engine3d_pipeline_handle,
40            ocean_pipeline_handle: probed.ocean_pipeline_handle,
41            scene_ocean_pipeline_handle: probed.scene_ocean_pipeline_handle,
42            scene_boat_pipeline_handle: probed.scene_boat_pipeline_handle,
43            scene_3d_sky_pipeline_handle: probed.scene_3d_sky_pipeline_handle,
44            scene_3d_mesh_pipeline_handle: probed.scene_3d_mesh_pipeline_handle,
45            scene_depth_stencil_handle: probed.scene_depth_stencil_handle,
46            scene_color_texture_handle: 0,
47            scene_depth_texture_handle: 0,
48            scene_wake_texture_handle: 0,
49            scene_wake_texture_handles: [0; GPU_DRIVER_RING_SLOTS],
50            scene_texture_dims: (0, 0),
51            scene_3d_vertex_buffer_handle: 0,
52            scene_3d_vertex_revision: 0,
53            scene_3d_vertex_capacity: 0,
54            scene_3d_instance_buffer_handle: 0,
55            scene_3d_instance_capacity: 0,
56            scene_3d_instance_buffer_handles: [0; GPU_DRIVER_RING_SLOTS],
57            scene_3d_instance_capacities: [0; GPU_DRIVER_RING_SLOTS],
58            scene_boat_buffer_handle: 0,
59            scene_boat_capacity: 0,
60            scene_boat_buffer_handles: [0; GPU_DRIVER_RING_SLOTS],
61            scene_boat_capacities: [0; GPU_DRIVER_RING_SLOTS],
62            pending_gpu_scene_pass: None,
63            surface_layer_handle: 0,
64            glyph_r8_texture_handle: probed.dummy_r8_tex,
65            glyph_rgba8_texture_handle: probed.dummy_rgba8_tex,
66            image_texture_handle: retain_native_gpu_object(probed.dummy_rgba8_tex),
67            external_texture_handle: 0,
68            blur_scene_texture_handle: 0,
69            blur_half_texture_handle: 0,
70            blur_full_texture_handle: 0,
71            blur_texture_dims: (0, 0),
72            ring_slots: [NativeGpuRingSlot::default(); GPU_DRIVER_RING_SLOTS],
73            ring_cursor: 0,
74            staging_buffer_handle: 0,
75            staging_contents_ptr: 0,
76            staging_buffer_capacity: 0,
77            submitted_frames: 0,
78            uploaded_instances: 0,
79            uploaded_bytes: 0,
80            last_upload_bytes: 0,
81            last_submitted_batches: 0,
82            staging_reallocations: 0,
83            last_presented_time_ns: 0,
84            last_gpu_exec_ns: 0,
85            #[cfg(any(target_os = "macos", target_os = "ios"))]
86            scratch_primitives: Vec::new(),
87            fallback,
88        }
89    }
90
91    /// Re-initializes the GPU driver for `backend`, releasing any previously retained OS handles.
92    ///
93    /// # Arguments
94    ///
95    /// - `GraphicsBackend` - Target graphics backend.
96    pub fn switch_backend(&mut self, backend: GraphicsBackend) {
97        if self.get_adapter().get_backend() == backend {
98            return;
99        }
100        *self = Self::probe(backend);
101    }
102
103    /// Attaches a native `CAMetalLayer*` (or equivalent surface layer) for zero-readback hardware presentation.
104    ///
105    /// # Arguments
106    ///
107    /// - `usize` - Native `CAMetalLayer*` pointer (`0` detaches).
108    pub fn attach_metal_layer(&mut self, layer_handle: usize) {
109        let dev: usize = self.get_device_handle();
110        let Self {
111            surface_layer_handle,
112            ..
113        } = self;
114        *surface_layer_handle = layer_handle;
115        if dev != 0 && layer_handle != 0 {
116            configure_native_metal_layer(dev, layer_handle);
117        }
118    }
119
120    /// Configures `CAMetalLayer.displaySyncEnabled` on macOS to switch between tear-free native VRR sync (`true`) and uncapped non-blocking hardware presentation (`false`).
121    ///
122    /// # Arguments
123    ///
124    /// - `bool` - `true` for hardware display sync; `false` for uncapped non-blocking presentation.
125    pub fn set_display_sync_enabled(&mut self, enabled: bool) {
126        let layer_handle: usize = self.get_surface_layer_handle();
127        if layer_handle != 0 {
128            configure_native_metal_display_sync(layer_handle, enabled);
129        }
130    }
131
132    /// Binds an external shared-device GPU texture handle (3D game render target or hardware video surface).
133    ///
134    /// # Arguments
135    ///
136    /// - `usize` - Native external texture handle (`0` restores fallback dummy texture).
137    pub fn set_external_texture(&mut self, texture_handle: usize) {
138        let Self {
139            external_texture_handle,
140            ..
141        } = self;
142        *external_texture_handle = texture_handle;
143    }
144
145    /// Stages an optional hardware GPU Ocean or 3D PBR offscreen scene pass for execution in the next frame's command buffer.
146    ///
147    /// # Arguments
148    ///
149    /// - `Option<DirectGpuScenePass>` - Hardware scene pass rendered before UI compositing, or `None`.
150    pub fn set_pending_gpu_scene_pass(&mut self, pass: Option<DirectGpuScenePass>) {
151        let Self {
152            pending_gpu_scene_pass,
153            ..
154        } = self;
155        *pending_gpu_scene_pass = pass;
156    }
157
158    /// Uploads a dirty R8 or RGBA8 sub-rectangle to the resident glyph atlas or image texture on GPU.
159    ///
160    /// # Arguments
161    ///
162    /// - `GpuAtlasPixelFormat` - Target texture pixel format (`R8Unorm` or `Rgba8Unorm`).
163    /// - `u8` - Texture slot (`0` = R8 glyph atlas, `1` = RGBA8 color glyph atlas, `2` = UI image texture).
164    /// - `(u32, u32)` - Full backing texture dimensions `(width, height)`.
165    /// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
166    /// - `&[u8]` - Source pixel bytes.
167    /// - `usize` - Row stride in bytes.
168    ///
169    /// # Returns
170    ///
171    /// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly to hardware GPU memory.
172    pub fn upload_texture_dirty_rect(
173        &mut self,
174        format: GpuAtlasPixelFormat,
175        texture_slot: u8,
176        tex_dims: (u32, u32),
177        dirty_rect: (u32, u32, u32, u32),
178        bytes: &[u8],
179        bytes_per_row: usize,
180    ) -> bool {
181        let dev: usize = self.get_device_handle();
182        let Self {
183            glyph_r8_texture_handle,
184            glyph_rgba8_texture_handle,
185            image_texture_handle,
186            ..
187        } = self;
188        let target: &mut usize = match texture_slot {
189            0 => glyph_r8_texture_handle,
190            1 => glyph_rgba8_texture_handle,
191            _ => image_texture_handle,
192        };
193        upload_native_texture_dirty_rect(
194            dev,
195            target,
196            format,
197            tex_dims,
198            dirty_rect,
199            bytes,
200            bytes_per_row,
201        )
202    }
203
204    /// Returns `true` when the driver has both Dual-Kawase `blur_down` and `blur_up` hardware pipelines compiled.
205    ///
206    /// # Returns
207    ///
208    /// - `bool` - `true` when `BackdropBlur` can execute natively on GPU without CPU fallback.
209    #[must_use]
210    pub fn supports_backdrop_blur_pass(&self) -> bool {
211        self.get_blur_pipeline_handle() != 0 && self.get_blur_up_pipeline_handle() != 0
212    }
213
214    /// Executes Pass 3 Dual-Kawase `blur_down` + `blur_up` ping-pong passes on hardware GPU for `blur_passes`.
215    ///
216    /// # Arguments
217    ///
218    /// - `u32` - Physical surface width in pixels.
219    /// - `u32` - Physical surface height in pixels.
220    /// - `&[GpuBackdropBlurPass]` - Active Dual-Kawase backdrop blur regions.
221    ///
222    /// # Returns
223    ///
224    /// - `usize` - Number of Dual-Kawase blur regions executed on hardware GPU (`0` when unsupported).
225    pub fn execute_dual_kawase_blur_passes(
226        &mut self,
227        width: u32,
228        height: u32,
229        blur_passes: &[GpuBackdropBlurPass],
230    ) -> usize {
231        execute_native_dual_kawase_blur_passes(self, width, height, blur_passes)
232    }
233
234    /// Returns the count of resident hardware GPU render pipeline state objects (`UI`, `Blur`, `3D PBR`, `Fluid Ocean`) currently cached on this driver.
235    ///
236    /// # Returns
237    ///
238    /// - `usize` - Number of non-zero resident hardware pipeline handles (`0..=4`).
239    #[must_use]
240    pub fn precompiled_pipeline_count(&self) -> usize {
241        usize::from(self.get_pipeline_handle() != 0)
242            + usize::from(
243                self.get_blur_pipeline_handle() != 0 && self.get_blur_up_pipeline_handle() != 0,
244            )
245            + usize::from(self.get_engine3d_pipeline_handle() != 0)
246            + usize::from(self.get_ocean_pipeline_handle() != 0)
247    }
248}
249
250/// `GpuDriver` implementation uploading packed 64-byte `GpuPrimitiveInstance` streams to the active physical OS GPU.
251impl GpuDriver for NativeGpuDriver {
252    /// Returns the resolved `GraphicsBackend`.
253    ///
254    /// # Returns
255    ///
256    /// - `GraphicsBackend` - Active backend tag.
257    fn backend(&self) -> GraphicsBackend {
258        self.get_adapter().get_backend()
259    }
260
261    /// Returns the native shader source compiled by this GPU backend.
262    ///
263    /// # Returns
264    ///
265    /// - `&'static str` - Native shader program source.
266    fn shader_source(&self) -> &'static str {
267        self.get_fallback().shader_source()
268    }
269
270    /// Uploads instanced 64-byte primitive batches through the 3-slot fenced ring and records draw telemetry.
271    ///
272    /// # Arguments
273    ///
274    /// - `u32` - Surface width.
275    /// - `u32` - Surface height.
276    /// - `Color` - Surface clear color.
277    /// - `&[GpuBatch]` - Ordered draw batches.
278    ///
279    /// # Returns
280    ///
281    /// - `Result<usize, PlatformError>` - Number of submitted GPU draw calls.
282    fn submit_batches(
283        &mut self,
284        width: u32,
285        height: u32,
286        clear_color: Color,
287        batches: &[GpuBatch],
288    ) -> Result<usize, PlatformError> {
289        let uploaded: usize =
290            submit_native_gpu_ring_frame(self, width, height, clear_color, batches);
291        let frame_bytes: usize = uploaded.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
292        let Self {
293            submitted_frames,
294            uploaded_instances,
295            uploaded_bytes,
296            last_upload_bytes,
297            last_submitted_batches,
298            last_presented_time_ns,
299            last_gpu_exec_ns,
300            fallback,
301            ..
302        } = self;
303        *submitted_frames = submitted_frames.wrapping_add(1);
304        *uploaded_instances = uploaded_instances.wrapping_add(uploaded as u64);
305        *uploaded_bytes = uploaded_bytes.wrapping_add(frame_bytes as u64);
306        *last_upload_bytes = frame_bytes;
307        *last_submitted_batches = batches.len();
308        *last_presented_time_ns = native_gpu_last_presented_ns();
309        *last_gpu_exec_ns = native_gpu_last_exec_ns();
310        fallback.submit_batches(width, height, clear_color, batches)
311    }
312}
313
314/// Automatic native GPU handle cleanup when `NativeGpuDriver` is dropped.
315impl Drop for NativeGpuDriver {
316    /// Releases retained OS GPU ring buffers, in-flight command buffers, textures, pipelines, and device handles.
317    fn drop(&mut self) {
318        let Self {
319            device_handle,
320            queue_handle,
321            library_handle,
322            pipeline_handle,
323            blur_pipeline_handle,
324            blur_up_pipeline_handle,
325            engine3d_pipeline_handle,
326            ocean_pipeline_handle,
327            scene_ocean_pipeline_handle,
328            scene_boat_pipeline_handle,
329            scene_3d_sky_pipeline_handle,
330            scene_3d_mesh_pipeline_handle,
331            scene_depth_stencil_handle,
332            scene_color_texture_handle,
333            scene_depth_texture_handle,
334            scene_wake_texture_handle,
335            scene_wake_texture_handles,
336            scene_3d_vertex_buffer_handle,
337            scene_3d_instance_buffer_handle,
338            scene_3d_instance_buffer_handles,
339            scene_3d_instance_capacities,
340            scene_boat_buffer_handle,
341            scene_boat_buffer_handles,
342            scene_boat_capacities,
343            glyph_r8_texture_handle,
344            glyph_rgba8_texture_handle,
345            image_texture_handle,
346            blur_scene_texture_handle,
347            blur_half_texture_handle,
348            blur_full_texture_handle,
349            ring_slots,
350            staging_buffer_handle,
351            staging_contents_ptr,
352            staging_buffer_capacity,
353            ..
354        } = self;
355        for slot in ring_slots.iter_mut() {
356            let cmd: usize = slot.get_in_flight_cmd_buffer();
357            if cmd != 0 {
358                release_native_gpu_object(cmd);
359                slot.set_in_flight_cmd_buffer(0);
360            }
361            let buf: usize = slot.get_buffer_handle();
362            if buf != 0 {
363                release_native_gpu_object(buf);
364                slot.set_buffer_handle(0);
365                slot.set_contents_ptr(0);
366                slot.set_capacity_bytes(0);
367            }
368        }
369        *staging_buffer_handle = 0;
370        *staging_contents_ptr = 0;
371        *staging_buffer_capacity = 0;
372        for slot_idx in 0..GPU_DRIVER_RING_SLOTS {
373            release_native_gpu_object(scene_3d_instance_buffer_handles[slot_idx]);
374            scene_3d_instance_buffer_handles[slot_idx] = 0;
375            scene_3d_instance_capacities[slot_idx] = 0;
376            release_native_gpu_object(scene_boat_buffer_handles[slot_idx]);
377            scene_boat_buffer_handles[slot_idx] = 0;
378            scene_boat_capacities[slot_idx] = 0;
379            release_native_gpu_object(scene_wake_texture_handles[slot_idx]);
380            scene_wake_texture_handles[slot_idx] = 0;
381        }
382        *scene_3d_instance_buffer_handle = 0;
383        *scene_boat_buffer_handle = 0;
384        *scene_wake_texture_handle = 0;
385        release_native_gpu_object(*blur_scene_texture_handle);
386        release_native_gpu_object(*blur_half_texture_handle);
387        release_native_gpu_object(*blur_full_texture_handle);
388        release_native_gpu_object(*scene_color_texture_handle);
389        release_native_gpu_object(*scene_depth_texture_handle);
390        release_native_gpu_object(*scene_3d_vertex_buffer_handle);
391        release_native_gpu_object(*scene_depth_stencil_handle);
392        release_native_gpu_object(*scene_3d_mesh_pipeline_handle);
393        release_native_gpu_object(*scene_3d_sky_pipeline_handle);
394        release_native_gpu_object(*scene_boat_pipeline_handle);
395        release_native_gpu_object(*scene_ocean_pipeline_handle);
396        release_native_gpu_object(*glyph_r8_texture_handle);
397        release_native_gpu_object(*glyph_rgba8_texture_handle);
398        release_native_gpu_object(*image_texture_handle);
399        release_native_gpu_object(*ocean_pipeline_handle);
400        release_native_gpu_object(*engine3d_pipeline_handle);
401        release_native_gpu_object(*blur_up_pipeline_handle);
402        release_native_gpu_object(*blur_pipeline_handle);
403        release_native_gpu_object(*pipeline_handle);
404        release_native_gpu_handles(*device_handle, *queue_handle, *library_handle);
405    }
406}
407
408/// Geometry and byte-size helpers for `PixelDirtyRect`.
409impl PixelDirtyRect {
410    /// Returns the exclusive right pixel edge (`x + width`).
411    ///
412    /// # Returns
413    ///
414    /// - `u32` - Exclusive right coordinate in pixels.
415    #[must_use]
416    pub fn right(&self) -> u32 {
417        self.get_x().saturating_add(self.get_width())
418    }
419
420    /// Returns the exclusive bottom pixel edge (`y + height`).
421    ///
422    /// # Returns
423    ///
424    /// - `u32` - Exclusive bottom coordinate in pixels.
425    #[must_use]
426    pub fn bottom(&self) -> u32 {
427        self.get_y().saturating_add(self.get_height())
428    }
429
430    /// Returns `true` when either width or height is zero.
431    ///
432    /// # Returns
433    ///
434    /// - `bool` - `true` when the rectangle covers zero pixels.
435    #[must_use]
436    pub fn is_empty(&self) -> bool {
437        self.get_width() == 0 || self.get_height() == 0
438    }
439
440    /// Returns the covered pixel count (`width * height`).
441    ///
442    /// # Returns
443    ///
444    /// - `usize` - Total covered pixels.
445    #[must_use]
446    pub fn area_pixels(&self) -> usize {
447        (self.get_width() as usize).saturating_mul(self.get_height() as usize)
448    }
449
450    /// Returns the RGBA8 byte payload size (`width * height * 4`).
451    ///
452    /// # Returns
453    ///
454    /// - `usize` - Payload size in bytes.
455    #[must_use]
456    pub fn byte_size_rgba8(&self) -> usize {
457        self.area_pixels().saturating_mul(4)
458    }
459
460    /// Clamps this rectangle strictly inside `(fb_w, fb_h)` surface bounds.
461    ///
462    /// # Arguments
463    ///
464    /// - `u32` - Surface width in pixels.
465    /// - `u32` - Surface height in pixels.
466    ///
467    /// # Returns
468    ///
469    /// - `Option<Self>` - Clamped non-empty rectangle, or `None` when outside bounds.
470    #[must_use]
471    pub fn clamp_to(&self, fb_w: u32, fb_h: u32) -> Option<Self> {
472        let x0: u32 = self.get_x().min(fb_w);
473        let y0: u32 = self.get_y().min(fb_h);
474        let x1: u32 = self.right().min(fb_w);
475        let y1: u32 = self.bottom().min(fb_h);
476        let width_val: u32 = x1.saturating_sub(x0);
477        let height_val: u32 = y1.saturating_sub(y0);
478        if width_val == 0 || height_val == 0 {
479            None
480        } else {
481            Some(Self::new(x0, y0, width_val, height_val))
482        }
483    }
484
485    /// Returns the smallest enclosing bounding rectangle containing both `self` and `other`.
486    ///
487    /// # Arguments
488    ///
489    /// - `Self` - Other pixel rectangle.
490    ///
491    /// # Returns
492    ///
493    /// - `Self` - Enclosing union rectangle.
494    #[must_use]
495    pub fn union_with(&self, other: Self) -> Self {
496        if self.is_empty() {
497            return other;
498        }
499        if other.is_empty() {
500            return *self;
501        }
502        let x0: u32 = self.get_x().min(other.get_x());
503        let y0: u32 = self.get_y().min(other.get_y());
504        let x1: u32 = self.right().max(other.right());
505        let y1: u32 = self.bottom().max(other.bottom());
506        Self::new(x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
507    }
508
509    /// Returns `true` when `self` and `other` overlap or lie within `pad_px` pixels of each other.
510    ///
511    /// # Arguments
512    ///
513    /// - `Self` - Other pixel rectangle.
514    /// - `u32` - Adjacency tolerance in pixels.
515    ///
516    /// # Returns
517    ///
518    /// - `bool` - `true` when the two rectangles overlap or are adjacent within `pad_px`.
519    #[must_use]
520    pub fn intersects_or_adjacent(&self, other: Self, pad_px: u32) -> bool {
521        if self.is_empty() || other.is_empty() {
522            return false;
523        }
524        let ax0: u32 = self.get_x().saturating_sub(pad_px);
525        let ay0: u32 = self.get_y().saturating_sub(pad_px);
526        let ax1: u32 = self.right().saturating_add(pad_px);
527        let ay1: u32 = self.bottom().saturating_add(pad_px);
528        ax0 <= other.right()
529            && ax1 >= other.get_x()
530            && ay0 <= other.bottom()
531            && ay1 >= other.get_y()
532    }
533}
534
535/// Zero-copy borrowed atlas accessors for `DirectGpuFrameBatch`.
536impl DirectGpuFrameBatch {
537    /// Returns a borrowed reference to the optional R8 monochrome glyph atlas upload without cloning.
538    ///
539    /// # Returns
540    ///
541    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed R8 glyph atlas upload when present.
542    #[must_use]
543    pub fn glyph_r8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
544        let Self { glyph_r8_atlas, .. } = self;
545        glyph_r8_atlas.as_ref()
546    }
547
548    /// Returns a borrowed reference to the optional RGBA8 image atlas upload without cloning.
549    ///
550    /// # Returns
551    ///
552    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed RGBA8 image atlas upload when present.
553    #[must_use]
554    pub fn image_rgba8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
555        let Self {
556            image_rgba8_atlas, ..
557        } = self;
558        image_rgba8_atlas.as_ref()
559    }
560}
561
562/// Telemetry recording and simulator-honesty methods for `MobilePresentTelemetry`.
563impl MobilePresentTelemetry {
564    /// Creates an initialized telemetry snapshot configured for `active_path`, `display_mode_hz`, and simulator status.
565    ///
566    /// # Arguments
567    ///
568    /// - `MobilePresentPath` - Active presentation channel.
569    /// - `f32` - Display refresh rate in Hertz.
570    /// - `bool` - `true` when executing inside a simulator where compositor timestamps are unobservable.
571    ///
572    /// # Returns
573    ///
574    /// - `Self` - Configured mobile presentation telemetry state.
575    #[must_use]
576    pub fn for_host(
577        active_path: MobilePresentPath,
578        display_mode_hz: f32,
579        is_simulator: bool,
580    ) -> Self {
581        let cpu_mirror_active: bool = active_path != MobilePresentPath::GpuDirect;
582        let upload_strategy: MobileUploadStrategy = match active_path {
583            MobilePresentPath::GpuDirect => MobileUploadStrategy::DirectGpu,
584            MobilePresentPath::GpuUpload | MobilePresentPath::Software => {
585                MobileUploadStrategy::FullFrame
586            }
587        };
588        let (timing_source, unobservable_reason): (
589            MobilePresentTimingSource,
590            Option<&'static str>,
591        ) = if is_simulator {
592            (
593                MobilePresentTimingSource::SubmissionProxy,
594                Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR),
595            )
596        } else {
597            (MobilePresentTimingSource::Unobservable, None)
598        };
599        Self {
600            active_path,
601            upload_strategy,
602            cpu_mirror_active,
603            timing_source,
604            unobservable_reason,
605            is_simulator,
606            display_mode_hz: display_mode_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ),
607            frame_callback_count: 0,
608            last_callback_timestamp_ns: 0,
609            last_callback_interval_ms: None,
610            last_target_timestamp_ns: None,
611            last_presented_timestamp_ns: None,
612            actual_presented_frames: 0,
613            upload_bytes_last_frame: 0,
614            upload_bytes_total: 0,
615            primitive_count_last_frame: 0,
616            draw_calls_last_frame: 0,
617            submit_failures: 0,
618            present_failures: 0,
619            context_loss_count: 0,
620            blank_frames_prevented: 0,
621            last_valid_frame_retained: false,
622        }
623    }
624
625    /// Records a VSync callback (`Choreographer.doFrame` or `CADisplayLink`) timestamp and optional target timestamp.
626    ///
627    /// # Arguments
628    ///
629    /// - `u64` - Monotonic VSync callback timestamp in nanoseconds.
630    /// - `Option<u64>` - Optional target presentation deadline timestamp in nanoseconds.
631    pub fn record_vsync_callback(&mut self, callback_ts_ns: u64, target_ts_ns: Option<u64>) {
632        let prev_ts: u64 = self.get_last_callback_timestamp_ns();
633        self.set_frame_callback_count(self.get_frame_callback_count().saturating_add(1));
634        if callback_ts_ns > 0 {
635            if prev_ts > 0 && callback_ts_ns > prev_ts {
636                let delta_ms: f64 = ((callback_ts_ns - prev_ts) as f64) / 1_000_000.0;
637                self.set_last_callback_interval_ms(Some(delta_ms));
638            }
639            self.set_last_callback_timestamp_ns(callback_ts_ns);
640        }
641        if let Some(target_ns) = target_ts_ns
642            && target_ns > 0
643        {
644            self.set_last_target_timestamp_ns(Some(target_ns));
645        }
646    }
647
648    /// Records a successful frame presentation with exact path, upload strategy, byte count, and draw telemetry.
649    ///
650    /// # Arguments
651    ///
652    /// - `MobilePresentPath` - Active presentation channel executed for this frame.
653    /// - `MobileUploadStrategy` - Upload strategy executed for this frame.
654    /// - `u64` - Payload bytes uploaded to GPU or native surface memory.
655    /// - `u32` - Number of 64-byte `GpuPrimitiveInstance` records emitted (`0` on upload/software).
656    /// - `u32` - Number of GPU draw calls emitted.
657    /// - `Option<u64>` - Optional hardware compositor presentation timestamp in nanoseconds (`None` when unobservable).
658    pub fn record_presented_frame(
659        &mut self,
660        path: MobilePresentPath,
661        strategy: MobileUploadStrategy,
662        upload_bytes: u64,
663        primitive_count: u32,
664        draw_calls: u32,
665        compositor_presented_ns: Option<u64>,
666    ) {
667        self.set_active_path(path);
668        self.set_upload_strategy(strategy);
669        self.set_cpu_mirror_active(path != MobilePresentPath::GpuDirect);
670        self.set_upload_bytes_last_frame(upload_bytes);
671        self.set_upload_bytes_total(self.get_upload_bytes_total().saturating_add(upload_bytes));
672        self.set_primitive_count_last_frame(primitive_count);
673        self.set_draw_calls_last_frame(draw_calls);
674        self.set_actual_presented_frames(self.get_actual_presented_frames().saturating_add(1));
675        self.set_last_valid_frame_retained(true);
676        self.record_compositor_present_timestamp(compositor_presented_ns);
677    }
678
679    /// Records an observed compositor presentation timestamp while honestly marking simulator or missing timestamps unobservable.
680    ///
681    /// # Arguments
682    ///
683    /// - `Option<u64>` - Compositor presentation timestamp in nanoseconds (`None` or `Some(0)` when unobservable).
684    pub fn record_compositor_present_timestamp(&mut self, presented_ns: Option<u64>) {
685        let is_sim: bool = self.get_is_simulator();
686        match presented_ns {
687            Some(timestamp_val) if timestamp_val > 0 && !is_sim => {
688                self.set_last_presented_timestamp_ns(Some(timestamp_val));
689                self.set_timing_source(MobilePresentTimingSource::CompositorMeasured);
690                self.set_unobservable_reason(None);
691            }
692            _ if is_sim => {
693                self.set_last_presented_timestamp_ns(None);
694                self.set_timing_source(MobilePresentTimingSource::SubmissionProxy);
695                self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR));
696            }
697            _ => {
698                self.set_last_presented_timestamp_ns(None);
699                self.set_timing_source(MobilePresentTimingSource::Unobservable);
700                self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_UNSUPPORTED));
701            }
702        }
703    }
704
705    /// Records a frame submission or presentation fault without fabricating a presented frame.
706    ///
707    /// # Arguments
708    ///
709    /// - `MobileSurfaceFault` - Fault category observed during submit or present.
710    /// - `bool` - `true` when the last valid frame was retained to prevent submitting a blank frame.
711    pub fn record_fault(&mut self, fault: MobileSurfaceFault, blank_prevented: bool) {
712        match fault {
713            MobileSurfaceFault::ContextLost => {
714                self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
715                self.set_present_failures(self.get_present_failures().saturating_add(1));
716            }
717            MobileSurfaceFault::SurfaceLost | MobileSurfaceFault::SubmitFailed => {
718                self.set_submit_failures(self.get_submit_failures().saturating_add(1));
719            }
720            MobileSurfaceFault::ShaderCompileFailed => {
721                self.set_submit_failures(self.get_submit_failures().saturating_add(1));
722            }
723        }
724        if blank_prevented {
725            self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
726        }
727    }
728}
729
730/// Immediate zero-blank-frame failover logic for `MobileFailoverController`.
731impl Default for MobileFailoverController {
732    /// Creates a failover controller preferring `GpuDirect` with both `GpuUpload` and `Software` fallbacks enabled.
733    ///
734    /// # Returns
735    ///
736    /// - `Self` - Default GPU-first failover controller.
737    fn default() -> Self {
738        Self::for_preferred(MobilePresentPath::GpuDirect, true, true)
739    }
740}
741
742/// Fault-handling and path-selection methods for `MobileFailoverController`.
743impl MobileFailoverController {
744    /// Creates a failover controller honoring `preferred_path` and detected hardware capabilities.
745    ///
746    /// # Arguments
747    ///
748    /// - `MobilePresentPath` - Preferred initial presentation path.
749    /// - `bool` - `true` when direct GPU uber-shader rendering is available.
750    /// - `bool` - `true` when GPU texture upload rendering is available.
751    ///
752    /// # Returns
753    ///
754    /// - `Self` - Configured failover controller with an immediately runnable active path.
755    #[must_use]
756    pub fn for_preferred(
757        preferred_path: MobilePresentPath,
758        direct_gpu_available: bool,
759        gpu_upload_available: bool,
760    ) -> Self {
761        let active_path: MobilePresentPath = match preferred_path {
762            MobilePresentPath::GpuDirect if direct_gpu_available => MobilePresentPath::GpuDirect,
763            MobilePresentPath::GpuDirect | MobilePresentPath::GpuUpload if gpu_upload_available => {
764                MobilePresentPath::GpuUpload
765            }
766            _ => MobilePresentPath::Software,
767        };
768        Self {
769            active_path,
770            preferred_path,
771            has_valid_presented_frame: false,
772            window_valid: true,
773            direct_gpu_available,
774            gpu_upload_available,
775            context_loss_count: 0,
776            blank_frames_prevented: 0,
777            fallback_transitions: 0,
778        }
779    }
780
781    /// Returns `true` when the active presentation path requires a CPU framebuffer mirror (`false` on `GpuDirect`).
782    ///
783    /// # Returns
784    ///
785    /// - `bool` - `false` for `GpuDirect`; `true` for `GpuUpload` and `Software`.
786    #[must_use]
787    pub fn cpu_mirror_active(&self) -> bool {
788        self.get_active_path() != MobilePresentPath::GpuDirect
789    }
790
791    /// Marks the active window surface valid or detached (`false` clears retained-frame status on new surface).
792    ///
793    /// # Arguments
794    ///
795    /// - `bool` - `true` when a live native window / Metal layer is attached.
796    pub fn set_surface_valid(&mut self, valid: bool) {
797        self.set_window_valid(valid);
798        if !valid {
799            self.set_has_valid_presented_frame(false);
800        }
801    }
802
803    /// Records that a valid non-blank frame has been presented onto the current surface.
804    pub fn mark_frame_presented(&mut self) {
805        self.set_has_valid_presented_frame(true);
806    }
807
808    /// Handles a graphics context or submission fault immediately without waiting for perf comparisons while preventing blank frames.
809    ///
810    /// # Arguments
811    ///
812    /// - `MobileSurfaceFault` - Observed context, shader, surface, or submission fault.
813    ///
814    /// # Returns
815    ///
816    /// - `MobileFailoverAction` - Deterministic immediate failover instruction.
817    pub fn handle_fault(&mut self, fault: MobileSurfaceFault) -> MobileFailoverAction {
818        if !self.get_window_valid() {
819            return MobileFailoverAction::WaitForNewSurface;
820        }
821        let retained: bool = self.get_has_valid_presented_frame();
822        if retained {
823            self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
824        }
825        match fault {
826            MobileSurfaceFault::ContextLost => {
827                self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
828                self.set_direct_gpu_available(false);
829                self.set_gpu_upload_available(false);
830                let prev: MobilePresentPath = self.get_active_path();
831                self.set_active_path(MobilePresentPath::Software);
832                if prev != MobilePresentPath::Software {
833                    self.set_fallback_transitions(
834                        self.get_fallback_transitions().saturating_add(1),
835                    );
836                }
837                MobileFailoverAction::KeepLastFrameAndSwitch(MobilePresentPath::Software)
838            }
839            MobileSurfaceFault::ShaderCompileFailed => {
840                self.set_direct_gpu_available(false);
841                let next: MobilePresentPath = if self.get_gpu_upload_available() {
842                    MobilePresentPath::GpuUpload
843                } else {
844                    MobilePresentPath::Software
845                };
846                if self.get_active_path() != next {
847                    self.set_active_path(next);
848                    self.set_fallback_transitions(
849                        self.get_fallback_transitions().saturating_add(1),
850                    );
851                }
852                MobileFailoverAction::KeepLastFrameAndSwitch(next)
853            }
854            MobileSurfaceFault::SubmitFailed => {
855                let next: MobilePresentPath = match self.get_active_path() {
856                    MobilePresentPath::GpuDirect => {
857                        if self.get_gpu_upload_available() {
858                            MobilePresentPath::GpuUpload
859                        } else {
860                            MobilePresentPath::Software
861                        }
862                    }
863                    MobilePresentPath::GpuUpload => MobilePresentPath::Software,
864                    MobilePresentPath::Software => {
865                        return MobileFailoverAction::KeepLastFrameAndRetry;
866                    }
867                };
868                self.set_active_path(next);
869                self.set_fallback_transitions(self.get_fallback_transitions().saturating_add(1));
870                MobileFailoverAction::KeepLastFrameAndSwitch(next)
871            }
872            MobileSurfaceFault::SurfaceLost => MobileFailoverAction::KeepLastFrameAndRetry,
873        }
874    }
875}
876
877/// Canonical shader program listing, metadata, and per-backend source lookup for `ShaderProgramId`.
878impl ShaderProgramId {
879    /// Returns all built-in GPU shader programs ordered for ahead-of-time precompilation.
880    ///
881    /// # Returns
882    ///
883    /// - `[Self; 4]` - Complete ordered list of built-in shader programs.
884    #[must_use]
885    pub const fn all() -> [Self; 4] {
886        [
887            Self::UiUber,
888            Self::BackdropBlur,
889            Self::Engine3dPbr,
890            Self::FluidOceanOptical,
891        ]
892    }
893
894    /// Returns the human-readable diagnostic title for this shader program.
895    ///
896    /// # Returns
897    ///
898    /// - `&'static str` - Descriptive shader pipeline name.
899    #[must_use]
900    pub const fn label(self) -> &'static str {
901        match self {
902            Self::UiUber => "UI Uber-Shader (64B SDF)",
903            Self::BackdropBlur => "Dual-Kawase BackdropBlur",
904            Self::Engine3dPbr => "3D Engine PBR (GGX + ACES)",
905            Self::FluidOceanOptical => "Fluid Ocean Optical (Gerstner + GGX)",
906        }
907    }
908
909    /// Resolves the shading language name paired with `backend`.
910    ///
911    /// # Arguments
912    ///
913    /// - `GraphicsBackend` - Active graphics API backend.
914    ///
915    /// # Returns
916    ///
917    /// - `&'static str` - Target shading language label (`MSL`, `WGSL`, `GLSL ES 3.0`, or `HLSL SM 6.0`).
918    #[must_use]
919    pub const fn language_for_backend(backend: GraphicsBackend) -> &'static str {
920        match backend {
921            GraphicsBackend::Metal => "MSL",
922            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => "GLSL ES 3.0",
923            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => "HLSL SM 6.0",
924            GraphicsBackend::WebGpu
925            | GraphicsBackend::Vulkan
926            | GraphicsBackend::SoftwareCpu
927            | GraphicsBackend::Canvas2d
928            | GraphicsBackend::Headless => "WGSL",
929        }
930    }
931
932    /// Returns the primary and optional secondary shader source slices for this program on `backend`.
933    ///
934    /// # Arguments
935    ///
936    /// - `GraphicsBackend` - Active graphics API backend.
937    ///
938    /// # Returns
939    ///
940    /// - `(&'static str, &'static str)` - Primary shader source and optional paired fragment shader source (empty when unified).
941    #[must_use]
942    pub const fn source_pair(self, backend: GraphicsBackend) -> (&'static str, &'static str) {
943        match (self, backend) {
944            (Self::UiUber, GraphicsBackend::Metal) => (MSL_UI_SHADER, ""),
945            (Self::UiUber, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => {
946                (GLSL_ES3_UI_VERTEX_SHADER, GLSL_ES3_UI_FRAGMENT_SHADER)
947            }
948            (Self::UiUber, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
949                (HLSL_UI_SHADER, "")
950            }
951            (Self::UiUber, _) => (WGSL_UI_SHADER, ""),
952            (Self::BackdropBlur, GraphicsBackend::Metal) => (MSL_BACKDROP_BLUR_SHADER, ""),
953            (Self::BackdropBlur, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
954                GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER,
955                GLSL_ES3_BACKDROP_BLUR_FRAGMENT_SHADER,
956            ),
957            (Self::BackdropBlur, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
958                (HLSL_BACKDROP_BLUR_SHADER, "")
959            }
960            (Self::BackdropBlur, _) => (WGSL_BACKDROP_BLUR_SHADER, ""),
961            (Self::Engine3dPbr, GraphicsBackend::Metal) => (MSL_ENGINE3D_PBR_SHADER, ""),
962            (Self::Engine3dPbr, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
963                GLSL_ES3_ENGINE3D_VERTEX_SHADER,
964                GLSL_ES3_ENGINE3D_FRAGMENT_SHADER,
965            ),
966            (Self::Engine3dPbr, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
967                (HLSL_ENGINE3D_PBR_SHADER, "")
968            }
969            (Self::Engine3dPbr, _) => (WGSL_ENGINE3D_PBR_SHADER, ""),
970            (Self::FluidOceanOptical, GraphicsBackend::Metal) => (MSL_FLUID_OCEAN_SHADER, ""),
971            (Self::FluidOceanOptical, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
972                GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER,
973                GLSL_ES3_FLUID_OCEAN_FRAGMENT_SHADER,
974            ),
975            (
976                Self::FluidOceanOptical,
977                GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11,
978            ) => (HLSL_FLUID_OCEAN_SHADER, ""),
979            (Self::FluidOceanOptical, _) => (WGSL_FLUID_OCEAN_SHADER, ""),
980        }
981    }
982}
983
984/// Diagnostic label and readiness query helpers for `ShaderCompileState`.
985impl ShaderCompileState {
986    /// Returns a concise human-readable label for UI telemetry displays.
987    ///
988    /// # Returns
989    ///
990    /// - `&'static str` - Status label string.
991    #[must_use]
992    pub const fn label(self) -> &'static str {
993        match self {
994            Self::Pending => "Pending",
995            Self::Compiling => "Compiling",
996            Self::CompiledHardware => "GPU PSO Ready",
997            Self::LoadedFromBinaryArchive => "Binary Archive Hit",
998            Self::ValidatedFallback => SHADER_STATE_LABEL_VALIDATED_FALLBACK,
999            Self::Failed => "Fallback",
1000        }
1001    }
1002
1003    /// Returns `true` when this state represents a ready precompiled or validated shader entry.
1004    ///
1005    /// # Returns
1006    ///
1007    /// - `bool` - `true` for hardware compiled, archive hit, or validated fallback states.
1008    #[must_use]
1009    pub const fn is_ready(self) -> bool {
1010        matches!(
1011            self,
1012            Self::CompiledHardware | Self::LoadedFromBinaryArchive | Self::ValidatedFallback
1013        )
1014    }
1015}
1016
1017/// Summary and lookup helpers for `ShaderPrecompileReport`.
1018impl ShaderPrecompileReport {
1019    /// Returns `true` when all registered shader programs are ready for zero-hitch rendering.
1020    ///
1021    /// # Returns
1022    ///
1023    /// - `bool` - `true` when `total_programs > 0 && ready_programs == total_programs`.
1024    #[must_use]
1025    pub fn is_all_ready(&self) -> bool {
1026        self.get_total_programs() > 0 && self.get_ready_programs() == self.get_total_programs()
1027    }
1028
1029    /// Looks up the cache entry for a specific `ShaderProgramId`.
1030    ///
1031    /// # Arguments
1032    ///
1033    /// - `ShaderProgramId` - Target built-in shader program identifier.
1034    ///
1035    /// # Returns
1036    ///
1037    /// - `Option<&ShaderProgramCacheEntry>` - Matching shader cache entry if present.
1038    #[must_use]
1039    pub fn entry_for(&self, program: ShaderProgramId) -> Option<&ShaderProgramCacheEntry> {
1040        self.get_entries()
1041            .iter()
1042            .find(|entry: &&ShaderProgramCacheEntry| entry.get_program() == program)
1043    }
1044
1045    /// Formats a single-line telemetry summary suitable for HUD badges and developer inspector cards.
1046    ///
1047    /// # Returns
1048    ///
1049    /// - `String` - Formatted shader precompile status line.
1050    #[must_use]
1051    pub fn summary_line(&self) -> String {
1052        let mode_label: &str = if self.get_binary_archive_hit() {
1053            "Disk Archive Hit"
1054        } else if self.get_cache_hit() {
1055            "Warm PSO Hit"
1056        } else if self.get_hardware_gpu() {
1057            "GPU Compiled"
1058        } else {
1059            SHADER_STATE_LABEL_VALIDATED_FALLBACK
1060        };
1061        let cold_ms: f64 = (self.get_cold_compile_us() as f64) / 1000.0;
1062        let call_ms: f64 = (self.get_last_call_us() as f64) / 1000.0;
1063        format!(
1064            "PSO {}/{} ({mode_label}) | {} | Cold {cold_ms:.2}ms -> Call {call_ms:.3}ms",
1065            self.get_ready_programs(),
1066            self.get_total_programs(),
1067            self.get_device_name(),
1068        )
1069    }
1070}