1use super::*;
2
3impl Default for NativeGpuDriver {
5 fn default() -> Self {
11 Self::probe(GraphicsBackend::Headless)
12 }
13}
14
15impl NativeGpuDriver {
17 #[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 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 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 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 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 #[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
161impl GpuDriver for NativeGpuDriver {
163 fn backend(&self) -> GraphicsBackend {
169 self.get_adapter().get_backend()
170 }
171
172 fn shader_source(&self) -> &'static str {
178 self.get_fallback().shader_source()
179 }
180
181 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
225impl Drop for NativeGpuDriver {
227 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}
269
270impl PixelDirtyRect {
272 #[must_use]
278 pub fn right(&self) -> u32 {
279 self.get_x().saturating_add(self.get_width())
280 }
281
282 #[must_use]
288 pub fn bottom(&self) -> u32 {
289 self.get_y().saturating_add(self.get_height())
290 }
291
292 #[must_use]
298 pub fn is_empty(&self) -> bool {
299 self.get_width() == 0 || self.get_height() == 0
300 }
301
302 #[must_use]
308 pub fn area_pixels(&self) -> usize {
309 (self.get_width() as usize).saturating_mul(self.get_height() as usize)
310 }
311
312 #[must_use]
318 pub fn byte_size_rgba8(&self) -> usize {
319 self.area_pixels().saturating_mul(4)
320 }
321
322 #[must_use]
333 pub fn clamp_to(&self, fb_w: u32, fb_h: u32) -> Option<Self> {
334 let x0: u32 = self.get_x().min(fb_w);
335 let y0: u32 = self.get_y().min(fb_h);
336 let x1: u32 = self.right().min(fb_w);
337 let y1: u32 = self.bottom().min(fb_h);
338 let w: u32 = x1.saturating_sub(x0);
339 let h: u32 = y1.saturating_sub(y0);
340 if w == 0 || h == 0 {
341 None
342 } else {
343 Some(Self::new(x0, y0, w, h))
344 }
345 }
346
347 #[must_use]
357 pub fn union_with(&self, other: Self) -> Self {
358 if self.is_empty() {
359 return other;
360 }
361 if other.is_empty() {
362 return *self;
363 }
364 let x0: u32 = self.get_x().min(other.get_x());
365 let y0: u32 = self.get_y().min(other.get_y());
366 let x1: u32 = self.right().max(other.right());
367 let y1: u32 = self.bottom().max(other.bottom());
368 Self::new(x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
369 }
370
371 #[must_use]
382 pub fn intersects_or_adjacent(&self, other: Self, pad_px: u32) -> bool {
383 if self.is_empty() || other.is_empty() {
384 return false;
385 }
386 let ax0: u32 = self.get_x().saturating_sub(pad_px);
387 let ay0: u32 = self.get_y().saturating_sub(pad_px);
388 let ax1: u32 = self.right().saturating_add(pad_px);
389 let ay1: u32 = self.bottom().saturating_add(pad_px);
390 ax0 <= other.right()
391 && ax1 >= other.get_x()
392 && ay0 <= other.bottom()
393 && ay1 >= other.get_y()
394 }
395}
396
397impl DirectGpuFrameBatch {
399 #[must_use]
405 pub fn glyph_r8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
406 let Self { glyph_r8_atlas, .. } = self;
407 glyph_r8_atlas.as_ref()
408 }
409
410 #[must_use]
416 pub fn image_rgba8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
417 let Self {
418 image_rgba8_atlas, ..
419 } = self;
420 image_rgba8_atlas.as_ref()
421 }
422}
423
424impl MobilePresentTelemetry {
426 #[must_use]
438 pub fn for_host(
439 active_path: MobilePresentPath,
440 display_mode_hz: f32,
441 is_simulator: bool,
442 ) -> Self {
443 let cpu_mirror_active: bool = active_path != MobilePresentPath::GpuDirect;
444 let upload_strategy: MobileUploadStrategy = match active_path {
445 MobilePresentPath::GpuDirect => MobileUploadStrategy::DirectGpu,
446 MobilePresentPath::GpuUpload | MobilePresentPath::Software => {
447 MobileUploadStrategy::FullFrame
448 }
449 };
450 let (timing_source, unobservable_reason): (
451 MobilePresentTimingSource,
452 Option<&'static str>,
453 ) = if is_simulator {
454 (
455 MobilePresentTimingSource::SubmissionProxy,
456 Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR),
457 )
458 } else {
459 (MobilePresentTimingSource::Unobservable, None)
460 };
461 Self {
462 active_path,
463 upload_strategy,
464 cpu_mirror_active,
465 timing_source,
466 unobservable_reason,
467 is_simulator,
468 display_mode_hz: display_mode_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ),
469 frame_callback_count: 0,
470 last_callback_timestamp_ns: 0,
471 last_callback_interval_ms: None,
472 last_target_timestamp_ns: None,
473 last_presented_timestamp_ns: None,
474 actual_presented_frames: 0,
475 upload_bytes_last_frame: 0,
476 upload_bytes_total: 0,
477 primitive_count_last_frame: 0,
478 draw_calls_last_frame: 0,
479 submit_failures: 0,
480 present_failures: 0,
481 context_loss_count: 0,
482 blank_frames_prevented: 0,
483 last_valid_frame_retained: false,
484 }
485 }
486
487 pub fn record_vsync_callback(&mut self, callback_ts_ns: u64, target_ts_ns: Option<u64>) {
494 let prev_ts: u64 = self.get_last_callback_timestamp_ns();
495 self.set_frame_callback_count(self.get_frame_callback_count().saturating_add(1));
496 if callback_ts_ns > 0 {
497 if prev_ts > 0 && callback_ts_ns > prev_ts {
498 let delta_ms: f64 = ((callback_ts_ns - prev_ts) as f64) / 1_000_000.0;
499 self.set_last_callback_interval_ms(Some(delta_ms));
500 }
501 self.set_last_callback_timestamp_ns(callback_ts_ns);
502 }
503 if let Some(target_ns) = target_ts_ns
504 && target_ns > 0
505 {
506 self.set_last_target_timestamp_ns(Some(target_ns));
507 }
508 }
509
510 pub fn record_presented_frame(
521 &mut self,
522 path: MobilePresentPath,
523 strategy: MobileUploadStrategy,
524 upload_bytes: u64,
525 primitive_count: u32,
526 draw_calls: u32,
527 compositor_presented_ns: Option<u64>,
528 ) {
529 self.set_active_path(path);
530 self.set_upload_strategy(strategy);
531 self.set_cpu_mirror_active(path != MobilePresentPath::GpuDirect);
532 self.set_upload_bytes_last_frame(upload_bytes);
533 self.set_upload_bytes_total(self.get_upload_bytes_total().saturating_add(upload_bytes));
534 self.set_primitive_count_last_frame(primitive_count);
535 self.set_draw_calls_last_frame(draw_calls);
536 self.set_actual_presented_frames(self.get_actual_presented_frames().saturating_add(1));
537 self.set_last_valid_frame_retained(true);
538 self.record_compositor_present_timestamp(compositor_presented_ns);
539 }
540
541 pub fn record_compositor_present_timestamp(&mut self, presented_ns: Option<u64>) {
547 let is_sim: bool = self.get_is_simulator();
548 match presented_ns {
549 Some(ts) if ts > 0 && !is_sim => {
550 self.set_last_presented_timestamp_ns(Some(ts));
551 self.set_timing_source(MobilePresentTimingSource::CompositorMeasured);
552 self.set_unobservable_reason(None);
553 }
554 _ if is_sim => {
555 self.set_last_presented_timestamp_ns(None);
556 self.set_timing_source(MobilePresentTimingSource::SubmissionProxy);
557 self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR));
558 }
559 _ => {
560 self.set_last_presented_timestamp_ns(None);
561 self.set_timing_source(MobilePresentTimingSource::Unobservable);
562 self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_UNSUPPORTED));
563 }
564 }
565 }
566
567 pub fn record_fault(&mut self, fault: MobileSurfaceFault, blank_prevented: bool) {
574 match fault {
575 MobileSurfaceFault::ContextLost => {
576 self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
577 self.set_present_failures(self.get_present_failures().saturating_add(1));
578 }
579 MobileSurfaceFault::SurfaceLost | MobileSurfaceFault::SubmitFailed => {
580 self.set_submit_failures(self.get_submit_failures().saturating_add(1));
581 }
582 MobileSurfaceFault::ShaderCompileFailed => {
583 self.set_submit_failures(self.get_submit_failures().saturating_add(1));
584 }
585 }
586 if blank_prevented {
587 self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
588 }
589 }
590}
591
592impl Default for MobileFailoverController {
594 fn default() -> Self {
600 Self::for_preferred(MobilePresentPath::GpuDirect, true, true)
601 }
602}
603
604impl MobileFailoverController {
606 #[must_use]
618 pub fn for_preferred(
619 preferred_path: MobilePresentPath,
620 direct_gpu_available: bool,
621 gpu_upload_available: bool,
622 ) -> Self {
623 let active_path: MobilePresentPath = match preferred_path {
624 MobilePresentPath::GpuDirect if direct_gpu_available => MobilePresentPath::GpuDirect,
625 MobilePresentPath::GpuDirect | MobilePresentPath::GpuUpload if gpu_upload_available => {
626 MobilePresentPath::GpuUpload
627 }
628 _ => MobilePresentPath::Software,
629 };
630 Self {
631 active_path,
632 preferred_path,
633 has_valid_presented_frame: false,
634 window_valid: true,
635 direct_gpu_available,
636 gpu_upload_available,
637 context_loss_count: 0,
638 blank_frames_prevented: 0,
639 fallback_transitions: 0,
640 }
641 }
642
643 #[must_use]
649 pub fn cpu_mirror_active(&self) -> bool {
650 self.get_active_path() != MobilePresentPath::GpuDirect
651 }
652
653 pub fn set_surface_valid(&mut self, valid: bool) {
659 self.set_window_valid(valid);
660 if !valid {
661 self.set_has_valid_presented_frame(false);
662 }
663 }
664
665 pub fn mark_frame_presented(&mut self) {
667 self.set_has_valid_presented_frame(true);
668 }
669
670 pub fn handle_fault(&mut self, fault: MobileSurfaceFault) -> MobileFailoverAction {
680 if !self.get_window_valid() {
681 return MobileFailoverAction::WaitForNewSurface;
682 }
683 let retained: bool = self.get_has_valid_presented_frame();
684 if retained {
685 self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
686 }
687 match fault {
688 MobileSurfaceFault::ContextLost => {
689 self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
690 self.set_direct_gpu_available(false);
691 self.set_gpu_upload_available(false);
692 let prev: MobilePresentPath = self.get_active_path();
693 self.set_active_path(MobilePresentPath::Software);
694 if prev != MobilePresentPath::Software {
695 self.set_fallback_transitions(
696 self.get_fallback_transitions().saturating_add(1),
697 );
698 }
699 MobileFailoverAction::KeepLastFrameAndSwitch(MobilePresentPath::Software)
700 }
701 MobileSurfaceFault::ShaderCompileFailed => {
702 self.set_direct_gpu_available(false);
703 let next: MobilePresentPath = if self.get_gpu_upload_available() {
704 MobilePresentPath::GpuUpload
705 } else {
706 MobilePresentPath::Software
707 };
708 if self.get_active_path() != next {
709 self.set_active_path(next);
710 self.set_fallback_transitions(
711 self.get_fallback_transitions().saturating_add(1),
712 );
713 }
714 MobileFailoverAction::KeepLastFrameAndSwitch(next)
715 }
716 MobileSurfaceFault::SubmitFailed => {
717 let next: MobilePresentPath = match self.get_active_path() {
718 MobilePresentPath::GpuDirect => {
719 if self.get_gpu_upload_available() {
720 MobilePresentPath::GpuUpload
721 } else {
722 MobilePresentPath::Software
723 }
724 }
725 MobilePresentPath::GpuUpload => MobilePresentPath::Software,
726 MobilePresentPath::Software => {
727 return MobileFailoverAction::KeepLastFrameAndRetry;
728 }
729 };
730 self.set_active_path(next);
731 self.set_fallback_transitions(self.get_fallback_transitions().saturating_add(1));
732 MobileFailoverAction::KeepLastFrameAndSwitch(next)
733 }
734 MobileSurfaceFault::SurfaceLost => MobileFailoverAction::KeepLastFrameAndRetry,
735 }
736 }
737}