Skip to main content

euv_core/render/gpu/
fn.rs

1use super::*;
2
3/// Probes the host OS for a physical GPU adapter, compiles or loads cached native UI pipelines, and returns handles.
4///
5/// # Arguments
6///
7/// - `GraphicsBackend` - Requested graphics backend.
8///
9/// # Returns
10///
11/// - `(GpuAdapterInfo, usize, usize, usize)` - Adapter info plus `(device, queue, library)` raw handles.
12#[must_use]
13pub fn probe_native_gpu(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
14    let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
15    (
16        probed.adapter,
17        probed.device_handle,
18        probed.queue_handle,
19        probed.library_handle,
20    )
21}
22
23/// Probes the host OS for a physical GPU adapter, cached uber-shader & blur pipelines, and fallback textures.
24///
25/// # Arguments
26///
27/// - `GraphicsBackend` - Requested graphics backend.
28///
29/// # Returns
30///
31/// - `NativeGpuProbeOutput` - Adapter info plus retained device, queue, library, pipeline, and dummy texture handles.
32#[must_use]
33pub(crate) fn probe_native_gpu_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
34    if backend == GraphicsBackend::Headless || backend == GraphicsBackend::SoftwareCpu {
35        return NativeGpuProbeOutput {
36            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
37            device_handle: 0,
38            queue_handle: 0,
39            library_handle: 0,
40            pipeline_handle: 0,
41            blur_pipeline_handle: 0,
42            blur_up_pipeline_handle: 0,
43            engine3d_pipeline_handle: 0,
44            ocean_pipeline_handle: 0,
45            scene_ocean_pipeline_handle: 0,
46            scene_boat_pipeline_handle: 0,
47            scene_3d_sky_pipeline_handle: 0,
48            scene_3d_mesh_pipeline_handle: 0,
49            scene_depth_stencil_handle: 0,
50            dummy_r8_tex: 0,
51            dummy_rgba8_tex: 0,
52            scene_pbr_pipelines: [0; 5],
53        };
54    }
55    #[cfg(any(target_os = "macos", target_os = "ios"))]
56    {
57        if backend == GraphicsBackend::Metal {
58            probe_apple_metal_full(backend)
59        } else {
60            NativeGpuProbeOutput {
61                adapter: GpuAdapterInfo::new(
62                    backend,
63                    GPU_DEVICE_FALLBACK.to_string(),
64                    false,
65                    false,
66                ),
67                device_handle: 0,
68                queue_handle: 0,
69                library_handle: 0,
70                pipeline_handle: 0,
71                blur_pipeline_handle: 0,
72                blur_up_pipeline_handle: 0,
73                engine3d_pipeline_handle: 0,
74                ocean_pipeline_handle: 0,
75                scene_ocean_pipeline_handle: 0,
76                scene_boat_pipeline_handle: 0,
77                scene_3d_sky_pipeline_handle: 0,
78                scene_3d_mesh_pipeline_handle: 0,
79                scene_depth_stencil_handle: 0,
80                dummy_r8_tex: 0,
81                dummy_rgba8_tex: 0,
82                scene_pbr_pipelines: [0; 5],
83            }
84        }
85    }
86    #[cfg(target_os = "windows")]
87    {
88        let (adapter, device_handle, queue_handle, library_handle): (
89            GpuAdapterInfo,
90            usize,
91            usize,
92            usize,
93        ) = probe_windows_d3d12(backend);
94        NativeGpuProbeOutput {
95            adapter,
96            device_handle,
97            queue_handle,
98            library_handle,
99            pipeline_handle: 0,
100            blur_pipeline_handle: 0,
101            blur_up_pipeline_handle: 0,
102            engine3d_pipeline_handle: 0,
103            ocean_pipeline_handle: 0,
104            scene_ocean_pipeline_handle: 0,
105            scene_boat_pipeline_handle: 0,
106            scene_3d_sky_pipeline_handle: 0,
107            scene_3d_mesh_pipeline_handle: 0,
108            scene_depth_stencil_handle: 0,
109            dummy_r8_tex: 0,
110            dummy_rgba8_tex: 0,
111            scene_pbr_pipelines: [0; 5],
112        }
113    }
114    #[cfg(any(target_os = "linux", target_os = "android"))]
115    {
116        let (adapter, device_handle, queue_handle, library_handle): (
117            GpuAdapterInfo,
118            usize,
119            usize,
120            usize,
121        ) = probe_vulkan_runtime(backend);
122        NativeGpuProbeOutput {
123            adapter,
124            device_handle,
125            queue_handle,
126            library_handle,
127            pipeline_handle: 0,
128            blur_pipeline_handle: 0,
129            blur_up_pipeline_handle: 0,
130            engine3d_pipeline_handle: 0,
131            ocean_pipeline_handle: 0,
132            scene_ocean_pipeline_handle: 0,
133            scene_boat_pipeline_handle: 0,
134            scene_3d_sky_pipeline_handle: 0,
135            scene_3d_mesh_pipeline_handle: 0,
136            scene_depth_stencil_handle: 0,
137            dummy_r8_tex: 0,
138            dummy_rgba8_tex: 0,
139            scene_pbr_pipelines: [0; 5],
140        }
141    }
142    #[cfg(target_arch = "wasm32")]
143    {
144        NativeGpuProbeOutput {
145            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
146            device_handle: 0,
147            queue_handle: 0,
148            library_handle: 0,
149            pipeline_handle: 0,
150            blur_pipeline_handle: 0,
151            blur_up_pipeline_handle: 0,
152            engine3d_pipeline_handle: 0,
153            ocean_pipeline_handle: 0,
154            scene_ocean_pipeline_handle: 0,
155            scene_boat_pipeline_handle: 0,
156            scene_3d_sky_pipeline_handle: 0,
157            scene_3d_mesh_pipeline_handle: 0,
158            scene_depth_stencil_handle: 0,
159            dummy_r8_tex: 0,
160            dummy_rgba8_tex: 0,
161            scene_pbr_pipelines: [0; 5],
162        }
163    }
164    #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
165    #[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
166    {
167        NativeGpuProbeOutput {
168            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
169            device_handle: 0,
170            queue_handle: 0,
171            library_handle: 0,
172            pipeline_handle: 0,
173            blur_pipeline_handle: 0,
174            blur_up_pipeline_handle: 0,
175            engine3d_pipeline_handle: 0,
176            ocean_pipeline_handle: 0,
177            scene_ocean_pipeline_handle: 0,
178            scene_boat_pipeline_handle: 0,
179            scene_3d_sky_pipeline_handle: 0,
180            scene_3d_mesh_pipeline_handle: 0,
181            scene_depth_stencil_handle: 0,
182            dummy_r8_tex: 0,
183            dummy_rgba8_tex: 0,
184            scene_pbr_pipelines: [0; 5],
185        }
186    }
187}
188
189/// Uploads instanced quad buffers and submits a command buffer to the active physical GPU.
190///
191/// # Arguments
192///
193/// - `usize` - Raw OS device handle.
194/// - `usize` - Raw OS command queue handle.
195/// - `&[GpuBatch]` - Compiled instanced draw batches.
196///
197/// # Returns
198///
199/// - `usize` - Total GPU instances uploaded and submitted.
200pub fn submit_native_gpu_batches(
201    device_handle: usize,
202    queue_handle: usize,
203    batches: &[GpuBatch],
204) -> usize {
205    #[cfg(any(target_os = "macos", target_os = "ios"))]
206    {
207        metal_submit_batches(device_handle, queue_handle, batches)
208    }
209    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
210    {
211        let _: (usize, usize) = (device_handle, queue_handle);
212        batches
213            .iter()
214            .map(|blue_val: &GpuBatch| {
215                blue_val
216                    .get_primitives()
217                    .len()
218                    .max(blue_val.get_instances().len())
219            })
220            .sum()
221    }
222}
223
224/// Uploads packed 64-byte `GpuPrimitiveInstance` streams into a fenced 3-slot ring, encodes real instanced draw calls when a `CAMetalLayer` is bound, and commits.
225///
226/// # Arguments
227///
228/// - `&mut NativeGpuDriver` - Mutable GPU driver holding ring slots, pipelines, textures, and surface handle.
229/// - `u32` - Physical surface width in pixels.
230/// - `u32` - Physical surface height in pixels.
231/// - `Color` - Surface clear color.
232/// - `&[GpuBatch]` - Ordered instanced draw batches.
233///
234/// # Returns
235///
236/// - `usize` - Total 64-byte `GpuPrimitiveInstance` records uploaded and submitted.
237pub(crate) fn submit_native_gpu_ring_frame(
238    driver: &mut NativeGpuDriver,
239    width: u32,
240    height: u32,
241    clear_color: Color,
242    batches: &[GpuBatch],
243) -> usize {
244    #[cfg(any(target_os = "macos", target_os = "ios"))]
245    {
246        metal_submit_ring_frame(driver, width, height, clear_color, batches)
247    }
248    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
249    {
250        let _: (&mut NativeGpuDriver, u32, u32, Color) = (driver, width, height, clear_color);
251        batches
252            .iter()
253            .map(|blue_val: &GpuBatch| {
254                blue_val
255                    .get_primitives()
256                    .len()
257                    .max(blue_val.get_instances().len())
258            })
259            .sum()
260    }
261}
262
263/// Executes Pass 3 Dual-Kawase `blur_down` + `blur_up` ping-pong passes on the active hardware GPU.
264///
265/// # Arguments
266///
267/// - `&mut NativeGpuDriver` - Mutable hardware GPU driver owning both blur pipelines and ping-pong textures.
268/// - `u32` - Physical surface width in pixels.
269/// - `u32` - Physical surface height in pixels.
270/// - `&[GpuBackdropBlurPass]` - Active Dual-Kawase backdrop blur regions.
271///
272/// # Returns
273///
274/// - `usize` - Number of blur regions executed on hardware GPU (`0` when unsupported).
275pub(crate) fn execute_native_dual_kawase_blur_passes(
276    driver: &mut NativeGpuDriver,
277    width: u32,
278    height: u32,
279    blur_passes: &[GpuBackdropBlurPass],
280) -> usize {
281    if blur_passes.is_empty() || !driver.supports_backdrop_blur_pass() {
282        return 0;
283    }
284    #[cfg(any(target_os = "macos", target_os = "ios"))]
285    {
286        metal_execute_dual_kawase_blur_passes(driver, width, height, blur_passes)
287    }
288    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
289    {
290        let _: (&mut NativeGpuDriver, u32, u32) = (driver, width, height);
291        0
292    }
293}
294
295/// Configures a native `CAMetalLayer` for triple-buffered direct-draw presentation (`framebufferOnly = YES`, `maximumDrawableCount = 3`).
296///
297/// # Arguments
298///
299/// - `usize` - Raw OS device handle (`id<MTLDevice>`).
300/// - `usize` - Raw `CAMetalLayer*` pointer.
301pub(crate) fn configure_native_metal_layer(device_handle: usize, layer_handle: usize) {
302    #[cfg(any(target_os = "macos", target_os = "ios"))]
303    {
304        metal_configure_layer(device_handle, layer_handle);
305    }
306    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
307    {
308        let _: (usize, usize) = (device_handle, layer_handle);
309    }
310}
311
312/// Configures `CAMetalLayer.displaySyncEnabled` on Apple platforms (`false` unlocks uncapped non-blocking hardware presentation on macOS).
313///
314/// # Arguments
315///
316/// - `usize` - Raw `CAMetalLayer*` pointer.
317/// - `bool` - `true` to enable hardware VRR display sync; `false` for uncapped non-blocking presentation.
318pub(crate) fn configure_native_metal_display_sync(layer_handle: usize, enabled: bool) {
319    #[cfg(any(target_os = "macos", target_os = "ios"))]
320    {
321        metal_set_layer_display_sync(layer_handle, enabled);
322    }
323    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
324    {
325        let _: (usize, bool) = (layer_handle, enabled);
326    }
327}
328
329/// Uploads a dirty sub-rectangle of R8 or RGBA8 texels into a resident native GPU texture without full-texture reallocation.
330///
331/// # Arguments
332///
333/// - `usize` - Raw OS GPU device handle.
334/// - `&mut usize` - Resident native texture handle (`0` triggers lazy creation).
335/// - `GpuAtlasPixelFormat` - Target texture format (`R8Unorm` or `Rgba8Unorm`).
336/// - `(u32, u32)` - Full backing texture dimensions `(tex_w, tex_h)`.
337/// - `(u32, u32, u32, u32)` - Dirty rectangle `(x, y, width, height)`.
338/// - `&[u8]` - Tightly or stride-packed source texel bytes.
339/// - `usize` - Row stride in bytes of `bytes`.
340///
341/// # Returns
342///
343/// - `bool` - `true` when the dirty sub-rectangle was uploaded cleanly.
344pub(crate) fn upload_native_texture_dirty_rect(
345    device_handle: usize,
346    texture_handle: &mut usize,
347    format: GpuAtlasPixelFormat,
348    tex_dims: (u32, u32),
349    dirty_rect: (u32, u32, u32, u32),
350    bytes: &[u8],
351    bytes_per_row: usize,
352) -> bool {
353    #[cfg(any(target_os = "macos", target_os = "ios"))]
354    {
355        metal_upload_texture_dirty_rect(
356            device_handle,
357            texture_handle,
358            format,
359            tex_dims,
360            dirty_rect,
361            bytes,
362            bytes_per_row,
363        )
364    }
365    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
366    {
367        let _: usize = device_handle;
368        let _: &mut usize = texture_handle;
369        let _: GpuAtlasPixelFormat = format;
370        let _: (u32, u32) = tex_dims;
371        let _: (u32, u32, u32, u32) = dirty_rect;
372        let _: &[u8] = bytes;
373        let _: usize = bytes_per_row;
374        false
375    }
376}
377
378/// Retains a single native GPU object handle cleanly so each owning slot holds an independent reference.
379///
380/// # Arguments
381///
382/// - `usize` - Raw OS GPU object handle (`0` returns `0`).
383///
384/// # Returns
385///
386/// - `usize` - Independently retained GPU object handle.
387pub(crate) fn retain_native_gpu_object(handle: usize) -> usize {
388    #[cfg(any(target_os = "macos", target_os = "ios"))]
389    {
390        mtl_retain_handle(handle)
391    }
392    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
393    {
394        handle
395    }
396}
397
398/// Releases a single retained native GPU object handle cleanly on teardown.
399///
400/// # Arguments
401///
402/// - `usize` - Retained OS GPU handle (`0` is a no-op).
403pub(crate) fn release_native_gpu_object(handle: usize) {
404    #[cfg(any(target_os = "macos", target_os = "ios"))]
405    {
406        if handle != 0 {
407            let sel: &MetalSelectors = cached_metal_selectors();
408            mtl_send_void0(handle as *mut c_void, sel.release as *mut c_void);
409        }
410    }
411    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
412    {
413        let _: usize = handle;
414    }
415}
416
417/// Releases native GPU handles on driver teardown.
418///
419/// # Arguments
420///
421/// - `usize` - Raw device handle.
422/// - `usize` - Raw command queue handle.
423/// - `usize` - Raw shader library handle.
424pub fn release_native_gpu_handles(
425    device_handle: usize,
426    queue_handle: usize,
427    library_handle: usize,
428) {
429    #[cfg(any(target_os = "macos", target_os = "ios"))]
430    {
431        metal_release_handles(device_handle, queue_handle, library_handle);
432    }
433    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
434    {
435        let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
436    }
437}
438
439/// Returns the latest hardware presentation timestamp in nanoseconds recorded by the GPU driver.
440///
441/// # Returns
442///
443/// - `u64` - Presentation timestamp in nanoseconds (`0` before first hardware present).
444#[must_use]
445pub fn native_gpu_last_presented_ns() -> u64 {
446    #[cfg(any(target_os = "macos", target_os = "ios"))]
447    {
448        METAL_LAST_PRESENTED_NS.load(Ordering::Relaxed)
449    }
450    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
451    {
452        0
453    }
454}
455
456/// Returns the latest hardware GPU command execution duration in nanoseconds.
457///
458/// # Returns
459///
460/// - `u64` - GPU execution duration in nanoseconds (`0` before first completed GPU command buffer).
461#[must_use]
462pub fn native_gpu_last_exec_ns() -> u64 {
463    #[cfg(any(target_os = "macos", target_os = "ios"))]
464    {
465        METAL_LAST_GPU_EXEC_NS.load(Ordering::Relaxed)
466    }
467    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
468    {
469        0
470    }
471}
472
473#[cfg(any(target_os = "macos", target_os = "ios"))]
474#[link(name = "Metal", kind = "framework")]
475unsafe extern "C" {
476    /// Creates the default Apple Metal GPU device handle.
477    ///
478    /// # Returns
479    ///
480    /// - `*mut c_void` - Retained `id<MTLDevice>` pointer or null.
481    fn MTLCreateSystemDefaultDevice() -> *mut c_void;
482}
483
484#[cfg(any(target_os = "macos", target_os = "ios"))]
485#[link(name = "objc")]
486unsafe extern "C" {
487    /// Looks up an Objective-C class pointer by null-terminated C name.
488    ///
489    /// # Arguments
490    ///
491    /// - `*const c_char` - Null-terminated class name.
492    ///
493    /// # Returns
494    ///
495    /// - `*mut c_void` - Objective-C class pointer or null.
496    fn objc_getClass(name: *const c_char) -> *mut c_void;
497    /// Registers an Objective-C selector by null-terminated C name.
498    ///
499    /// # Arguments
500    ///
501    /// - `*const c_char` - Null-terminated selector name.
502    ///
503    /// # Returns
504    ///
505    /// - `*mut c_void` - Registered selector pointer.
506    fn sel_registerName(name: *const c_char) -> *mut c_void;
507    /// Pushes a scoped Objective-C autorelease pool frame.
508    ///
509    /// # Returns
510    ///
511    /// - `*mut c_void` - Autorelease pool token to pop via `objc_autoreleasePoolPop`.
512    pub(crate) fn objc_autoreleasePoolPush() -> *mut c_void;
513    /// Pops and drains a scoped Objective-C autorelease pool frame.
514    ///
515    /// # Arguments
516    ///
517    /// - `*mut c_void` - Pool token returned by `objc_autoreleasePoolPush`.
518    pub(crate) fn objc_autoreleasePoolPop(pool: *mut c_void);
519    /// Objective-C dynamic message dispatch entry point.
520    pub(crate) fn objc_msgSend();
521}
522
523#[cfg(any(target_os = "macos", target_os = "ios"))]
524unsafe extern "C" {
525    /// Standard Apple `libSystem` class symbol identifying static global Objective-C blocks.
526    pub(crate) static _NSConcreteGlobalBlock: c_void;
527}
528
529/// Registers an Objective-C selector from a static null-terminated string literal.
530///
531/// # Arguments
532///
533/// - `&'static str` - Null-terminated selector name.
534///
535/// # Returns
536///
537/// - `*mut c_void` - Registered Objective-C selector pointer.
538#[cfg(any(target_os = "macos", target_os = "ios"))]
539pub(crate) fn mtl_sel_cstr(name: &'static str) -> *mut c_void {
540    unsafe { sel_registerName(name.as_ptr().cast::<c_char>()) }
541}
542
543/// Looks up an Objective-C class from a static null-terminated string literal.
544///
545/// # Arguments
546///
547/// - `&'static str` - Null-terminated class name.
548///
549/// # Returns
550///
551/// - `*mut c_void` - Objective-C class pointer or null.
552#[cfg(any(target_os = "macos", target_os = "ios"))]
553pub(crate) fn mtl_cls_cstr(name: &'static str) -> *mut c_void {
554    unsafe { objc_getClass(name.as_ptr().cast::<c_char>()) }
555}
556
557/// Allocates an autoreleased `NSString` from a UTF-8 Rust slice.
558///
559/// # Arguments
560///
561/// - `&str` - Source UTF-8 string.
562///
563/// # Returns
564///
565/// - `*mut c_void` - Objective-C `NSString` pointer.
566#[cfg(any(target_os = "macos", target_os = "ios"))]
567pub(crate) fn mtl_ns_string(text: &str) -> *mut c_void {
568    let Ok(c_text) = CString::new(text) else {
569        return null_mut();
570    };
571    unsafe {
572        let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_STRING);
573        if cls.is_null() {
574            return null_mut();
575        }
576        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
577            transmute(objc_msgSend as *const c_void);
578        send(cls, mtl_sel_cstr(MTL_SEL_STRING_UTF8), c_text.as_ptr())
579    }
580}
581
582/// Sends a zero-argument Objective-C message returning a pointer.
583///
584/// # Arguments
585///
586/// - `*mut c_void` - Target Objective-C object.
587/// - `*mut c_void` - Selector pointer.
588///
589/// # Returns
590///
591/// - `*mut c_void` - Returned Objective-C object pointer.
592#[cfg(any(target_os = "macos", target_os = "ios"))]
593pub(crate) fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
594    if obj.is_null() || sel.is_null() {
595        return null_mut();
596    }
597    unsafe {
598        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
599            transmute(objc_msgSend as *const c_void);
600        send(obj, sel)
601    }
602}
603
604/// Sends a one-pointer-argument Objective-C message returning a pointer.
605///
606/// # Arguments
607///
608/// - `*mut c_void` - Target Objective-C object.
609/// - `*mut c_void` - Selector pointer.
610/// - `*mut c_void` - Pointer argument.
611///
612/// # Returns
613///
614/// - `*mut c_void` - Returned Objective-C object pointer.
615#[cfg(any(target_os = "macos", target_os = "ios"))]
616pub(crate) fn mtl_send_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) -> *mut c_void {
617    if obj.is_null() || sel.is_null() {
618        return null_mut();
619    }
620    unsafe {
621        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
622            transmute(objc_msgSend as *const c_void);
623        send(obj, sel, arg0)
624    }
625}
626
627/// Sends a zero-argument Objective-C message returning void.
628///
629/// # Arguments
630///
631/// - `*mut c_void` - Target Objective-C object.
632/// - `*mut c_void` - Selector pointer.
633#[cfg(any(target_os = "macos", target_os = "ios"))]
634pub(crate) fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
635    if obj.is_null() || sel.is_null() {
636        return;
637    }
638    unsafe {
639        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
640            transmute(objc_msgSend as *const c_void);
641        send(obj, sel);
642    }
643}
644
645/// Sends a one-pointer-argument Objective-C message returning void.
646///
647/// # Arguments
648///
649/// - `*mut c_void` - Target Objective-C object.
650/// - `*mut c_void` - Selector pointer.
651/// - `*mut c_void` - Pointer argument.
652#[cfg(any(target_os = "macos", target_os = "ios"))]
653pub(crate) fn mtl_send_void_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) {
654    if obj.is_null() || sel.is_null() {
655        return;
656    }
657    unsafe {
658        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
659            transmute(objc_msgSend as *const c_void);
660        send(obj, sel, arg0);
661    }
662}
663
664/// Sends a one-`usize`-argument Objective-C message returning void.
665///
666/// # Arguments
667///
668/// - `*mut c_void` - Target Objective-C object.
669/// - `*mut c_void` - Selector pointer.
670/// - `usize` - Unsigned integer argument (`NSUInteger`).
671#[cfg(any(target_os = "macos", target_os = "ios"))]
672pub(crate) fn mtl_send_void_usize(obj: *mut c_void, sel: *mut c_void, val: usize) {
673    if obj.is_null() || sel.is_null() {
674        return;
675    }
676    unsafe {
677        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
678            transmute(objc_msgSend as *const c_void);
679        send(obj, sel, val);
680    }
681}
682
683/// Sends a one-boolean Objective-C message returning void.
684///
685/// # Arguments
686///
687/// - `*mut c_void` - Target Objective-C object.
688/// - `*mut c_void` - Selector pointer.
689/// - `bool` - Boolean flag converted to Objective-C `BOOL`.
690#[cfg(any(target_os = "macos", target_os = "ios"))]
691pub(crate) fn mtl_send_void_bool(obj: *mut c_void, sel: *mut c_void, val: bool) {
692    if obj.is_null() || sel.is_null() {
693        return;
694    }
695    unsafe {
696        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
697            transmute(objc_msgSend as *const c_void);
698        send(obj, sel, if val { 1 } else { 0 });
699    }
700}
701
702/// Sends a zero-argument Objective-C message returning `usize` (`NSUInteger`).
703///
704/// # Arguments
705///
706/// - `*mut c_void` - Target Objective-C object.
707/// - `*mut c_void` - Selector pointer.
708///
709/// # Returns
710///
711/// - `usize` - Returned `NSUInteger`.
712#[cfg(any(target_os = "macos", target_os = "ios"))]
713pub(crate) fn mtl_send_usize0(obj: *mut c_void, sel: *mut c_void) -> usize {
714    if obj.is_null() || sel.is_null() {
715        return 0;
716    }
717    unsafe {
718        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
719            transmute(objc_msgSend as *const c_void);
720        send(obj, sel)
721    }
722}
723
724/// Sends a zero-argument Objective-C message returning `f64` (`CFTimeInterval`).
725///
726/// # Arguments
727///
728/// - `*mut c_void` - Target Objective-C object.
729/// - `*mut c_void` - Selector pointer.
730///
731/// # Returns
732///
733/// - `f64` - Returned floating-point timestamp or duration in seconds.
734#[cfg(any(target_os = "macos", target_os = "ios"))]
735pub(crate) fn mtl_send_f64_0(obj: *mut c_void, sel: *mut c_void) -> f64 {
736    if obj.is_null() || sel.is_null() {
737        return 0.0;
738    }
739    unsafe {
740        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
741            transmute(objc_msgSend as *const c_void);
742        send(obj, sel)
743    }
744}
745
746/// Checks whether an Objective-C object responds to `sel`.
747///
748/// # Arguments
749///
750/// - `*mut c_void` - Target Objective-C object.
751/// - `*mut c_void` - Selector to query.
752///
753/// # Returns
754///
755/// - `bool` - `true` when the object implements `sel`.
756#[cfg(any(target_os = "macos", target_os = "ios"))]
757pub(crate) fn mtl_responds_to_sel(obj: *mut c_void, sel: *mut c_void) -> bool {
758    if obj.is_null() || sel.is_null() {
759        return false;
760    }
761    let responds_sel: *mut c_void = cached_metal_selectors().responds_to_sel as *mut c_void;
762    unsafe {
763        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
764            transmute(objc_msgSend as *const c_void);
765        send(obj, responds_sel, sel) != 0
766    }
767}
768
769/// Retains a non-zero Objective-C handle and returns it as `usize`.
770///
771/// # Arguments
772///
773/// - `usize` - Raw Objective-C object handle (`0` returns `0`).
774///
775/// # Returns
776///
777/// - `usize` - Retained handle.
778#[cfg(any(target_os = "macos", target_os = "ios"))]
779pub(crate) fn mtl_retain_handle(handle: usize) -> usize {
780    if handle == 0 {
781        return 0;
782    }
783    let sel_retain: *mut c_void = cached_metal_selectors().retain as *mut c_void;
784    mtl_send_ptr0(handle as *mut c_void, sel_retain) as usize
785}
786
787/// Objective-C global block callback invoked by `-[MTLDrawable addPresentedHandler:]` upon display scan-out.
788///
789/// # Arguments
790///
791/// - `*mut c_void` - Global block pointer (unused).
792/// - `*mut c_void` - Presented `id<MTLDrawable>` pointer.
793#[cfg(all(any(target_os = "macos", target_os = "ios"), not(target_abi = "sim")))]
794unsafe extern "C" fn metal_presented_handler_invoke(_block: *mut c_void, drawable: *mut c_void) {
795    if drawable.is_null() {
796        return;
797    }
798    let sel: &MetalSelectors = cached_metal_selectors();
799    let presented_secs: f64 = mtl_send_f64_0(drawable, sel.presented_time as *mut c_void);
800    if presented_secs.is_finite() && presented_secs > 0.0 {
801        let ns: u64 = (presented_secs * 1_000_000_000.0).round() as u64;
802        METAL_LAST_PRESENTED_NS.store(ns, Ordering::Relaxed);
803    }
804}
805
806/// Objective-C global block callback invoked by `-[MTLCommandBuffer addCompletedHandler:]` on GPU completion.
807///
808/// # Arguments
809///
810/// - `*mut c_void` - Global block pointer (unused).
811/// - `*mut c_void` - Completed `id<MTLCommandBuffer>` pointer.
812#[cfg(any(target_os = "macos", target_os = "ios"))]
813unsafe extern "C" fn metal_completed_handler_invoke(_block: *mut c_void, cmd_buf: *mut c_void) {
814    if cmd_buf.is_null() {
815        return;
816    }
817    let sel: &MetalSelectors = cached_metal_selectors();
818    let start_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_start_time as *mut c_void);
819    let end_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_end_time as *mut c_void);
820    if start_s.is_finite() && end_s.is_finite() && end_s >= start_s {
821        let exec_ns: u64 = ((end_s - start_s) * 1_000_000_000.0).round() as u64;
822        METAL_LAST_GPU_EXEC_NS.store(exec_ns, Ordering::Relaxed);
823        LAST_GPU_RENDER_NS.store(exec_ns, Ordering::Relaxed);
824    }
825    let _: u64 = COMPLETED_GPU_FENCE.fetch_add(1, Ordering::Release);
826}
827
828/// Returns the process-lifetime pinned global Objective-C block pointer for `addPresentedHandler:`.
829///
830/// # Returns
831///
832/// - `*mut c_void` - Pointer to static `ObjcGlobalBlock`.
833#[cfg(all(any(target_os = "macos", target_os = "ios"), not(target_abi = "sim")))]
834fn metal_presented_block_ptr() -> *mut c_void {
835    let addr: usize = *METAL_PRESENTED_BLOCK_ADDR.get_or_init(|| {
836        let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
837            isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
838            flags: OBJC_BLOCK_IS_GLOBAL,
839            reserved: 0,
840            invoke: metal_presented_handler_invoke,
841            descriptor: &METAL_BLOCK_DESCRIPTOR,
842        });
843        Box::into_raw(block) as usize
844    });
845    addr as *mut c_void
846}
847
848/// Returns the process-lifetime pinned global Objective-C block pointer for `addCompletedHandler:`.
849///
850/// # Returns
851///
852/// - `*mut c_void` - Pointer to static `ObjcGlobalBlock`.
853#[cfg(any(target_os = "macos", target_os = "ios"))]
854fn metal_completed_block_ptr() -> *mut c_void {
855    let addr: usize = *METAL_COMPLETED_BLOCK_ADDR.get_or_init(|| {
856        let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
857            isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
858            flags: OBJC_BLOCK_IS_GLOBAL,
859            reserved: 0,
860            invoke: metal_completed_handler_invoke,
861            descriptor: &METAL_BLOCK_DESCRIPTOR,
862        });
863        Box::into_raw(block) as usize
864    });
865    addr as *mut c_void
866}
867
868/// Computes a deterministic 64-bit FNV-1a cache key over shader sources and GPU device name for `MTLBinaryArchive`.
869///
870/// # Arguments
871///
872/// - `&str` - Probed GPU device name.
873///
874/// # Returns
875///
876/// - `u64` - Deterministic cache key hash.
877#[cfg(any(target_os = "macos", target_os = "ios"))]
878fn metal_pipeline_cache_hash(device_name: &str) -> u64 {
879    let mut hash: u64 = FNV1A_OFFSET_BASIS;
880    for chunk in [
881        device_name.as_bytes(),
882        MSL_UI_SHADER.as_bytes(),
883        MSL_BACKDROP_BLUR_SHADER.as_bytes(),
884        MSL_ENGINE3D_PBR_SHADER.as_bytes(),
885        MSL_FLUID_OCEAN_SHADER.as_bytes(),
886        MSL_GPU_SCENE_SHADER.as_bytes(),
887        MSL_PBR_SCENE_SHADER.as_bytes(),
888    ]
889    .iter()
890    {
891        for &byte in chunk.iter() {
892            hash ^= byte as u64;
893            hash = hash.wrapping_mul(FNV1A_PRIME);
894        }
895    }
896    hash
897}
898
899/// Creates a Metal `MTLTexture` (`R8Unorm` or `RGBA8Unorm`) with explicit dimensions for atlases or fallback slots.
900///
901/// # Arguments
902///
903/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
904/// - `GpuAtlasPixelFormat` - Pixel format to allocate.
905/// - `u32` - Texture width in pixels.
906/// - `u32` - Texture height in pixels.
907///
908/// # Returns
909///
910/// - `usize` - Retained `id<MTLTexture>` pointer or `0` on failure.
911#[cfg(any(target_os = "macos", target_os = "ios"))]
912fn metal_create_texture(
913    device: *mut c_void,
914    format: GpuAtlasPixelFormat,
915    width: u32,
916    height: u32,
917) -> usize {
918    if device.is_null() {
919        return 0;
920    }
921    let px_fmt: usize = match format {
922        GpuAtlasPixelFormat::R8Unorm => MTL_PIXEL_FORMAT_R8_UNORM,
923        GpuAtlasPixelFormat::Rgba8Unorm => MTL_PIXEL_FORMAT_RGBA8_UNORM,
924    };
925    let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
926    if cls_desc.is_null() {
927        return 0;
928    }
929    unsafe {
930        let send_desc: unsafe extern "C" fn(
931            *mut c_void,
932            *mut c_void,
933            usize,
934            usize,
935            usize,
936            i8,
937        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
938        let desc: *mut c_void = send_desc(
939            cls_desc,
940            mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
941            px_fmt,
942            width.max(1) as usize,
943            height.max(1) as usize,
944            0,
945        );
946        if desc.is_null() {
947            return 0;
948        }
949        mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
950        let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
951        tex as usize
952    }
953}
954
955/// Builds a real `MTLRenderPipelineState` with optional `MTLBinaryArchive` disk caching and straight-alpha blending.
956///
957/// # Arguments
958///
959/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
960/// - `*mut c_void` - Compiled `id<MTLLibrary>` handle.
961/// - `&str` - Vertex shader entry function name.
962/// - `&str` - Fragment shader entry function name.
963/// - `*mut c_void` - Optional `id<MTLBinaryArchive>` handle (null if unsupported).
964/// - `bool` - Whether alpha blending should be enabled on color attachment 0.
965///
966/// # Returns
967///
968/// - `(usize, bool)` - Tuple `(pipeline_state_handle, functions_found)`.
969#[cfg(any(target_os = "macos", target_os = "ios"))]
970fn metal_build_render_pipeline(
971    device: *mut c_void,
972    library: *mut c_void,
973    vs_name: &str,
974    fs_name: &str,
975    archive: *mut c_void,
976    enable_blend: bool,
977) -> (usize, bool) {
978    metal_build_render_pipeline_with_depth(
979        device,
980        library,
981        vs_name,
982        fs_name,
983        archive,
984        enable_blend,
985        0,
986    )
987}
988
989/// Builds a Metal `MTLRenderPipelineState` with optional alpha blending and optional depth attachment format (`0` = no depth attachment).
990///
991/// # Arguments
992///
993/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
994/// - `*mut c_void` - Compiled `id<MTLLibrary>` handle.
995/// - `&str` - Vertex shader entry function name.
996/// - `&str` - Fragment shader entry function name.
997/// - `*mut c_void` - Optional `id<MTLBinaryArchive>` handle.
998/// - `bool` - Whether alpha blending should be enabled on color attachment `0`.
999/// - `usize` - Metal depth attachment pixel format (`0` for none, `MTL_PIXEL_FORMAT_DEPTH32_FLOAT` for 3D Z-buffer).
1000///
1001/// # Returns
1002///
1003/// - `(usize, bool)` - Tuple `(pipeline_state_handle, functions_found)`.
1004#[cfg(any(target_os = "macos", target_os = "ios"))]
1005fn metal_build_render_pipeline_with_depth(
1006    device: *mut c_void,
1007    library: *mut c_void,
1008    vs_name: &str,
1009    fs_name: &str,
1010    archive: *mut c_void,
1011    enable_blend: bool,
1012    depth_pixel_format: usize,
1013) -> (usize, bool) {
1014    if device.is_null() || library.is_null() {
1015        return (0, false);
1016    }
1017    let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
1018    let vs_fn: *mut c_void = mtl_send_ptr1(
1019        library,
1020        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1021        mtl_ns_string(vs_name),
1022    );
1023    let fs_fn: *mut c_void = mtl_send_ptr1(
1024        library,
1025        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1026        mtl_ns_string(fs_name),
1027    );
1028    let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
1029    if !functions_ok {
1030        if !vs_fn.is_null() {
1031            mtl_send_void0(vs_fn, sel_rel);
1032        }
1033        if !fs_fn.is_null() {
1034            mtl_send_void0(fs_fn, sel_rel);
1035        }
1036        return (0, false);
1037    }
1038    let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
1039    let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1040    let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1041    if desc.is_null() {
1042        mtl_send_void0(vs_fn, sel_rel);
1043        mtl_send_void0(fs_fn, sel_rel);
1044        return (0, functions_ok);
1045    }
1046    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
1047    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
1048    let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
1049    let att0: *mut c_void = unsafe {
1050        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1051            transmute(objc_msgSend as *const c_void);
1052        send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
1053    };
1054    if !att0.is_null() {
1055        mtl_send_void_usize(
1056            att0,
1057            mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1058            MTL_PIXEL_FORMAT_BGRA8_UNORM,
1059        );
1060        if enable_blend {
1061            mtl_send_void_bool(att0, mtl_sel_cstr(MTL_SEL_SET_BLENDING_ENABLED), true);
1062            mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_RGB_BLEND_OP), 0);
1063            mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_ALPHA_BLEND_OP), 0);
1064            mtl_send_void_usize(
1065                att0,
1066                mtl_sel_cstr(MTL_SEL_SET_SRC_RGB_BLEND),
1067                MTL_BLEND_FACTOR_SRC_ALPHA,
1068            );
1069            mtl_send_void_usize(
1070                att0,
1071                mtl_sel_cstr(MTL_SEL_SET_DST_RGB_BLEND),
1072                MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
1073            );
1074            mtl_send_void_usize(
1075                att0,
1076                mtl_sel_cstr(MTL_SEL_SET_SRC_ALPHA_BLEND),
1077                MTL_BLEND_FACTOR_ONE,
1078            );
1079            mtl_send_void_usize(
1080                att0,
1081                mtl_sel_cstr(MTL_SEL_SET_DST_ALPHA_BLEND),
1082                MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
1083            );
1084        }
1085    }
1086    if depth_pixel_format != 0 {
1087        mtl_send_void_usize(
1088            desc,
1089            mtl_sel_cstr(MTL_SEL_SET_DEPTH_ATTACHMENT_PIXEL_FORMAT),
1090            depth_pixel_format,
1091        );
1092    }
1093    if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
1094        let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
1095        let arr: *mut c_void =
1096            mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
1097        if !arr.is_null() {
1098            mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
1099        }
1100    }
1101    let mut err_ptr: *mut c_void = null_mut();
1102    let pipeline: *mut c_void = unsafe {
1103        let send_pso: unsafe extern "C" fn(
1104            *mut c_void,
1105            *mut c_void,
1106            *mut c_void,
1107            *mut *mut c_void,
1108        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1109        send_pso(
1110            device,
1111            mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
1112            desc,
1113            &mut err_ptr,
1114        )
1115    };
1116    if !archive.is_null() && !pipeline.is_null() {
1117        let mut add_err: *mut c_void = null_mut();
1118        unsafe {
1119            let send_add: unsafe extern "C" fn(
1120                *mut c_void,
1121                *mut c_void,
1122                *mut c_void,
1123                *mut *mut c_void,
1124            ) -> i8 = transmute(objc_msgSend as *const c_void);
1125            let _: i8 = send_add(
1126                archive,
1127                mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
1128                desc,
1129                &mut add_err,
1130            );
1131        }
1132    }
1133    mtl_send_void0(desc, sel_rel);
1134    mtl_send_void0(vs_fn, sel_rel);
1135    mtl_send_void0(fs_fn, sel_rel);
1136    (pipeline as usize, functions_ok)
1137}
1138
1139/// Builds a real `MTLRenderPipelineState` with `MTLVertexDescriptor` (`float3 position`, `float3 normal`, stride 24 at buffer 2) for `MSL_ENGINE3D_PBR_SHADER`.
1140///
1141/// # Arguments
1142///
1143/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1144/// - `*mut c_void` - Compiled 3D PBR `id<MTLLibrary>` handle.
1145/// - `*mut c_void` - Optional `id<MTLBinaryArchive>` handle (null if unsupported).
1146///
1147/// # Returns
1148///
1149/// - `(usize, bool)` - Tuple `(pipeline_state_handle, functions_found)`.
1150#[cfg(any(target_os = "macos", target_os = "ios"))]
1151fn metal_build_render_pipeline_3d(
1152    device: *mut c_void,
1153    library: *mut c_void,
1154    archive: *mut c_void,
1155) -> (usize, bool) {
1156    if device.is_null() || library.is_null() {
1157        return (0, false);
1158    }
1159    let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
1160    let vs_fn: *mut c_void = mtl_send_ptr1(
1161        library,
1162        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1163        mtl_ns_string(MTL_FN_3D_VERTEX),
1164    );
1165    let fs_fn: *mut c_void = mtl_send_ptr1(
1166        library,
1167        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1168        mtl_ns_string(MTL_FN_3D_FRAGMENT),
1169    );
1170    let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
1171    if !functions_ok {
1172        if !vs_fn.is_null() {
1173            mtl_send_void0(vs_fn, sel_rel);
1174        }
1175        if !fs_fn.is_null() {
1176            mtl_send_void0(fs_fn, sel_rel);
1177        }
1178        return (0, false);
1179    }
1180    let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
1181    let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1182    let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1183    if desc.is_null() {
1184        mtl_send_void0(vs_fn, sel_rel);
1185        mtl_send_void0(fs_fn, sel_rel);
1186        return (0, functions_ok);
1187    }
1188    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
1189    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
1190    let vdesc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_VERTEX_DESC);
1191    let vdesc_alloc: *mut c_void = mtl_send_ptr0(vdesc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1192    let vdesc: *mut c_void = mtl_send_ptr0(vdesc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1193    if !vdesc.is_null() {
1194        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1195            unsafe { transmute(objc_msgSend as *const c_void) };
1196        let sel_idx: *mut c_void = mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX);
1197        let attrs: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_ATTRIBUTES));
1198        let attr0: *mut c_void = unsafe { send_idx(attrs, sel_idx, 0) };
1199        let attr1: *mut c_void = unsafe { send_idx(attrs, sel_idx, 1) };
1200        if !attr0.is_null() {
1201            mtl_send_void_usize(
1202                attr0,
1203                mtl_sel_cstr(MTL_SEL_SET_FORMAT),
1204                MTL_VERTEX_FORMAT_FLOAT3,
1205            );
1206            mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 0);
1207            mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
1208        }
1209        if !attr1.is_null() {
1210            mtl_send_void_usize(
1211                attr1,
1212                mtl_sel_cstr(MTL_SEL_SET_FORMAT),
1213                MTL_VERTEX_FORMAT_FLOAT3,
1214            );
1215            mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 12);
1216            mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
1217        }
1218        let layouts: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_LAYOUTS));
1219        let layout2: *mut c_void = unsafe { send_idx(layouts, sel_idx, 2) };
1220        if !layout2.is_null() {
1221            mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STRIDE), 24);
1222            mtl_send_void_usize(
1223                layout2,
1224                mtl_sel_cstr(MTL_SEL_SET_STEP_FUNCTION),
1225                MTL_VERTEX_STEP_PER_VERTEX,
1226            );
1227            mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STEP_RATE), 1);
1228        }
1229        mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_DESC), vdesc);
1230        mtl_send_void0(vdesc, sel_rel);
1231    }
1232    let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
1233    let att0: *mut c_void = unsafe {
1234        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1235            transmute(objc_msgSend as *const c_void);
1236        send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
1237    };
1238    if !att0.is_null() {
1239        mtl_send_void_usize(
1240            att0,
1241            mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1242            MTL_PIXEL_FORMAT_BGRA8_UNORM,
1243        );
1244    }
1245    if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
1246        let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
1247        let arr: *mut c_void =
1248            mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
1249        if !arr.is_null() {
1250            mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
1251        }
1252    }
1253    let mut err_ptr: *mut c_void = null_mut();
1254    let pipeline: *mut c_void = unsafe {
1255        let send_pso: unsafe extern "C" fn(
1256            *mut c_void,
1257            *mut c_void,
1258            *mut c_void,
1259            *mut *mut c_void,
1260        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1261        send_pso(
1262            device,
1263            mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
1264            desc,
1265            &mut err_ptr,
1266        )
1267    };
1268    if !archive.is_null() && !pipeline.is_null() {
1269        let mut add_err: *mut c_void = null_mut();
1270        unsafe {
1271            let send_add: unsafe extern "C" fn(
1272                *mut c_void,
1273                *mut c_void,
1274                *mut c_void,
1275                *mut *mut c_void,
1276            ) -> i8 = transmute(objc_msgSend as *const c_void);
1277            let _: i8 = send_add(
1278                archive,
1279                mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
1280                desc,
1281                &mut add_err,
1282            );
1283        }
1284    }
1285    mtl_send_void0(desc, sel_rel);
1286    mtl_send_void0(vs_fn, sel_rel);
1287    mtl_send_void0(fs_fn, sel_rel);
1288    (pipeline as usize, functions_ok)
1289}
1290
1291/// Creates a Metal `MTLDepthStencilState` configured with `MTLCompareFunctionLess` and `depthWriteEnabled = YES`.
1292///
1293/// # Arguments
1294///
1295/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1296///
1297/// # Returns
1298///
1299/// - `usize` - Retained `id<MTLDepthStencilState>` pointer, or `0` on failure.
1300#[cfg(any(target_os = "macos", target_os = "ios"))]
1301fn metal_create_depth_stencil_state(device: *mut c_void) -> usize {
1302    if device.is_null() {
1303        return 0;
1304    }
1305    let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_DEPTH_STENCIL_DESC);
1306    if cls.is_null() {
1307        return 0;
1308    }
1309    let alloc: *mut c_void = mtl_send_ptr0(cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1310    let desc: *mut c_void = mtl_send_ptr0(alloc, mtl_sel_cstr(MTL_SEL_INIT));
1311    if desc.is_null() {
1312        return 0;
1313    }
1314    mtl_send_void_usize(
1315        desc,
1316        mtl_sel_cstr(MTL_SEL_SET_DEPTH_COMPARE_FN),
1317        MTL_COMPARE_FUNC_LESS,
1318    );
1319    mtl_send_void_bool(desc, mtl_sel_cstr(MTL_SEL_SET_DEPTH_WRITE_ENABLED), true);
1320    let state: *mut c_void =
1321        mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_DEPTH_STENCIL_STATE), desc);
1322    mtl_send_void0(desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1323    state as usize
1324}
1325
1326/// Builds a `MTLDepthStencilState` (`Less`, depth writes disabled) for back-to-front alpha-blended PBR geometry.
1327///
1328/// # Arguments
1329///
1330/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1331///
1332/// # Returns
1333///
1334/// - `usize` - Retained `id<MTLDepthStencilState>` pointer, or `0` on failure.
1335#[cfg(any(target_os = "macos", target_os = "ios"))]
1336fn metal_create_read_only_depth_stencil_state(device: *mut c_void) -> usize {
1337    if device.is_null() {
1338        return 0;
1339    }
1340    let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_DEPTH_STENCIL_DESC);
1341    if cls.is_null() {
1342        return 0;
1343    }
1344    let alloc: *mut c_void = mtl_send_ptr0(cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1345    let desc: *mut c_void = mtl_send_ptr0(alloc, mtl_sel_cstr(MTL_SEL_INIT));
1346    if desc.is_null() {
1347        return 0;
1348    }
1349    mtl_send_void_usize(
1350        desc,
1351        mtl_sel_cstr(MTL_SEL_SET_DEPTH_COMPARE_FN),
1352        MTL_COMPARE_FUNC_LESS,
1353    );
1354    mtl_send_void_bool(desc, mtl_sel_cstr(MTL_SEL_SET_DEPTH_WRITE_ENABLED), false);
1355    let state: *mut c_void =
1356        mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_DEPTH_STENCIL_STATE), desc);
1357    mtl_send_void0(desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1358    state as usize
1359}
1360
1361/// Allocates a mipmapped `RGBA8Unorm` shader-read `MTLTexture` sized `(base_width, base_height)` for progressive mipmap streaming.
1362///
1363/// # Arguments
1364///
1365/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1366/// - `u32` - Base `LOD0` width in texels.
1367/// - `u32` - Base `LOD0` height in texels.
1368///
1369/// # Returns
1370///
1371/// - `(usize, u8)` - Tuple `(retained_mtl_texture_handle, allocated_mip_level_count)`.
1372#[cfg(any(target_os = "macos", target_os = "ios"))]
1373fn metal_create_mipmapped_rgba8_texture(
1374    device: *mut c_void,
1375    base_width: u32,
1376    base_height: u32,
1377) -> (usize, u8) {
1378    if device.is_null() {
1379        return (0, 0);
1380    }
1381    let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
1382    if cls_desc.is_null() {
1383        return (0, 0);
1384    }
1385    let w: u32 = base_width.clamp(1, 8192);
1386    let h: u32 = base_height.clamp(1, 8192);
1387    let max_dim: u32 = w.max(h);
1388    let mip_count: u8 = (32u32.saturating_sub(max_dim.leading_zeros())).min(14) as u8;
1389    unsafe {
1390        let send_desc: unsafe extern "C" fn(
1391            *mut c_void,
1392            *mut c_void,
1393            usize,
1394            usize,
1395            usize,
1396            i8,
1397        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1398        let desc: *mut c_void = send_desc(
1399            cls_desc,
1400            mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
1401            MTL_PIXEL_FORMAT_RGBA8_UNORM,
1402            w as usize,
1403            h as usize,
1404            1,
1405        );
1406        if desc.is_null() {
1407            return (0, 0);
1408        }
1409        mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
1410        let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
1411        (tex as usize, mip_count.max(1))
1412    }
1413}
1414
1415/// Applies incremental `GpuTextureMipUpload` records onto resident mipmapped Metal textures via `replaceRegion` and updates zero-copy `minLodClamp` texture views.
1416///
1417/// # Arguments
1418///
1419/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1420/// - `&mut MetalPbrSceneResources` - Resident PBR texture pool receiving mip uploads.
1421/// - `&[GpuTextureMipUpload]` - Frame-budgeted incremental mipmap upload records.
1422#[cfg(any(target_os = "macos", target_os = "ios"))]
1423fn metal_apply_pbr_mip_uploads(
1424    device: *mut c_void,
1425    pbr_res: &mut MetalPbrSceneResources,
1426    uploads: &[GpuTextureMipUpload],
1427) {
1428    if device.is_null() || uploads.is_empty() {
1429        return;
1430    }
1431    let sel: &MetalSelectors = cached_metal_selectors();
1432    for up in uploads.iter() {
1433        let mip: u8 = up.get_mip_level();
1434        let shift: u32 = u32::from(mip.min(13));
1435        let base_w: u32 = up
1436            .get_width()
1437            .max(1)
1438            .checked_shl(shift)
1439            .unwrap_or(8192)
1440            .clamp(1, 8192);
1441        let base_h: u32 = up
1442            .get_height()
1443            .max(1)
1444            .checked_shl(shift)
1445            .unwrap_or(8192)
1446            .clamp(1, 8192);
1447        let slot: u32 = up.get_texture_slot();
1448        let needs_alloc: bool = match pbr_res.textures.get(&slot) {
1449            Some(existing) => {
1450                existing.tex_handle == 0
1451                    || existing.base_width != base_w
1452                    || existing.base_height != base_h
1453            }
1454            None => true,
1455        };
1456        if needs_alloc {
1457            if let Some(old) = pbr_res.textures.remove(&slot) {
1458                release_native_gpu_object(old.view_handle);
1459                release_native_gpu_object(old.tex_handle);
1460            }
1461            let (tex_h, total_mips): (usize, u8) =
1462                metal_create_mipmapped_rgba8_texture(device, base_w, base_h);
1463            if tex_h == 0 {
1464                continue;
1465            }
1466            let _: Option<MetalResidentMipTexture> = pbr_res.textures.insert(
1467                slot,
1468                MetalResidentMipTexture {
1469                    tex_handle: tex_h,
1470                    view_handle: 0,
1471                    base_width: base_w,
1472                    base_height: base_h,
1473                    total_mips,
1474                    min_lod_clamp: total_mips.saturating_sub(1),
1475                },
1476            );
1477        }
1478        let Some(entry) = pbr_res.textures.get_mut(&slot) else {
1479            continue;
1480        };
1481        if mip >= entry.total_mips {
1482            continue;
1483        }
1484        let mip_w: u32 = (entry.base_width >> shift).max(1);
1485        let mip_h: u32 = (entry.base_height >> shift).max(1);
1486        let expected_bytes: usize = (mip_w as usize)
1487            .saturating_mul(mip_h as usize)
1488            .saturating_mul(4);
1489        let rgba8: &[u8] = up.get_rgba8().as_slice();
1490        if rgba8.len() < expected_bytes {
1491            continue;
1492        }
1493        let region: MtlRegion = MtlRegion {
1494            origin: MtlOrigin { x: 0, y: 0, z: 0 },
1495            size: MtlSize {
1496                width: mip_w as usize,
1497                height: mip_h as usize,
1498                depth: 1,
1499            },
1500        };
1501        unsafe {
1502            let send_rep: unsafe extern "C" fn(
1503                *mut c_void,
1504                *mut c_void,
1505                MtlRegion,
1506                usize,
1507                *const c_void,
1508                usize,
1509            ) = transmute(objc_msgSend as *const c_void);
1510            send_rep(
1511                entry.tex_handle as *mut c_void,
1512                sel.replace_region as *mut c_void,
1513                region,
1514                mip as usize,
1515                rgba8.as_ptr().cast::<c_void>(),
1516                (mip_w as usize).saturating_mul(4),
1517            );
1518        }
1519        let next_clamp: u8 = up
1520            .get_min_lod_clamp()
1521            .min(mip)
1522            .min(entry.total_mips.saturating_sub(1));
1523        if entry.min_lod_clamp != next_clamp || (next_clamp > 0 && entry.view_handle == 0) {
1524            release_native_gpu_object(entry.view_handle);
1525            entry.view_handle = 0;
1526            entry.min_lod_clamp = next_clamp;
1527            if next_clamp > 0 {
1528                let len_levels: usize =
1529                    usize::from(entry.total_mips.saturating_sub(next_clamp)).max(1);
1530                let level_range: MtlNsRange = MtlNsRange {
1531                    location: next_clamp as usize,
1532                    length: len_levels,
1533                };
1534                let slice_range: MtlNsRange = MtlNsRange {
1535                    location: 0,
1536                    length: 1,
1537                };
1538                let view_ptr: *mut c_void = unsafe {
1539                    let send_view: unsafe extern "C" fn(
1540                        *mut c_void,
1541                        *mut c_void,
1542                        usize,
1543                        usize,
1544                        MtlNsRange,
1545                        MtlNsRange,
1546                    ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1547                    send_view(
1548                        entry.tex_handle as *mut c_void,
1549                        sel.new_texture_view as *mut c_void,
1550                        MTL_PIXEL_FORMAT_RGBA8_UNORM,
1551                        MTL_TEXTURE_TYPE_2D,
1552                        level_range,
1553                        slice_range,
1554                    )
1555                };
1556                entry.view_handle = view_ptr as usize;
1557            }
1558        }
1559    }
1560}
1561
1562/// Allocates a private `Depth32Float` render-target `MTLTexture` sized `(width, height)`.
1563///
1564/// # Arguments
1565///
1566/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1567/// - `u32` - Width in physical pixels.
1568/// - `u32` - Height in physical pixels.
1569///
1570/// # Returns
1571///
1572/// - `usize` - Retained `id<MTLTexture>` pointer, or `0` on failure.
1573#[cfg(any(target_os = "macos", target_os = "ios"))]
1574fn metal_create_depth_texture(device: *mut c_void, width: u32, height: u32) -> usize {
1575    if device.is_null() {
1576        return 0;
1577    }
1578    let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
1579    if cls_desc.is_null() {
1580        return 0;
1581    }
1582    unsafe {
1583        let send_desc: unsafe extern "C" fn(
1584            *mut c_void,
1585            *mut c_void,
1586            usize,
1587            usize,
1588            usize,
1589            bool,
1590        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1591        let desc: *mut c_void = send_desc(
1592            cls_desc,
1593            mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
1594            MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1595            width.max(1) as usize,
1596            height.max(1) as usize,
1597            false,
1598        );
1599        if desc.is_null() {
1600            return 0;
1601        }
1602        mtl_send_void_usize(
1603            desc,
1604            mtl_sel_cstr(MTL_SEL_SET_USAGE),
1605            MTL_TEX_USAGE_RENDER_TARGET_GPU,
1606        );
1607        mtl_send_void_usize(
1608            desc,
1609            mtl_sel_cstr(MTL_SEL_SET_STORAGE_MODE_GPU),
1610            MTL_STORAGE_MODE_PRIVATE_GPU,
1611        );
1612        mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc) as usize
1613    }
1614}
1615
1616/// Ensures a grow-only shared-memory Metal buffer can store `bytes.len()` bytes and copies `bytes` into it.
1617///
1618/// # Arguments
1619///
1620/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1621/// - `&mut usize` - Resident `id<MTLBuffer>` handle.
1622/// - `&mut usize` - Resident buffer byte capacity.
1623/// - `&[u8]` - Source byte payload to upload.
1624///
1625/// # Returns
1626///
1627/// - `*mut c_void` - Valid `id<MTLBuffer>` pointer, or null on allocation failure.
1628#[cfg(any(target_os = "macos", target_os = "ios"))]
1629fn metal_ensure_and_upload_shared_buffer(
1630    device: *mut c_void,
1631    buf_handle: &mut usize,
1632    buf_capacity: &mut usize,
1633    bytes: &[u8],
1634) -> *mut c_void {
1635    if device.is_null() || bytes.is_empty() {
1636        return *buf_handle as *mut c_void;
1637    }
1638    let sel: &MetalSelectors = cached_metal_selectors();
1639    if *buf_handle == 0 || *buf_capacity < bytes.len() {
1640        if *buf_handle != 0 {
1641            mtl_send_void0(*buf_handle as *mut c_void, sel.release as *mut c_void);
1642            *buf_handle = 0;
1643            *buf_capacity = 0;
1644        }
1645        let alloc_bytes: usize = bytes.len().max(1024).next_power_of_two();
1646        unsafe {
1647            let send_new_len: unsafe extern "C" fn(
1648                *mut c_void,
1649                *mut c_void,
1650                usize,
1651                usize,
1652            ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1653            let new_buf: *mut c_void = send_new_len(
1654                device,
1655                sel.new_buffer_with_length as *mut c_void,
1656                alloc_bytes,
1657                0,
1658            );
1659            if !new_buf.is_null() {
1660                *buf_handle = new_buf as usize;
1661                *buf_capacity = alloc_bytes;
1662            }
1663        }
1664    }
1665    if *buf_handle == 0 {
1666        return null_mut();
1667    }
1668    let ptr: *mut c_void = mtl_send_ptr0(*buf_handle as *mut c_void, sel.contents as *mut c_void);
1669    if !ptr.is_null() {
1670        unsafe {
1671            ptr.cast::<u8>()
1672                .copy_from_nonoverlapping(bytes.as_ptr(), bytes.len());
1673        }
1674    }
1675    *buf_handle as *mut c_void
1676}
1677
1678/// Returns whether disk-backed `MTLBinaryArchive` caching is safe for the active Metal device.
1679///
1680/// # Arguments
1681///
1682/// - `&str` - Probed Metal GPU device name.
1683/// - `bool` - `true` when compiled for an Apple Simulator target (`target_abi = "sim"`).
1684///
1685/// # Returns
1686///
1687/// - `bool` - `true` on real physical Apple GPUs; `false` on simulator or virtualized drivers where `serializeToURL:error:` aborts inside `MTLSimDriver`.
1688#[must_use]
1689pub fn metal_binary_archive_allowed(device_name: &str, is_simulator: bool) -> bool {
1690    if is_simulator {
1691        return false;
1692    }
1693    let lower: String = device_name.to_ascii_lowercase();
1694    !lower.contains(MTL_SIMULATOR_TOKEN) && !lower.contains(MTL_VIRTUAL_TOKEN)
1695}
1696
1697/// Opens or initializes a disk-backed `MTLBinaryArchive` keyed by shader source hash and GPU device name.
1698///
1699/// # Arguments
1700///
1701/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1702/// - `&str` - Detected physical GPU device name.
1703///
1704/// # Returns
1705///
1706/// - `(*mut c_void, *mut c_void, bool)` - Tuple `(archive_handle, ns_url_handle, existed_on_disk)`.
1707#[cfg(any(target_os = "macos", target_os = "ios"))]
1708fn metal_open_binary_archive(
1709    device: *mut c_void,
1710    device_name: &str,
1711) -> (*mut c_void, *mut c_void, bool) {
1712    if !metal_binary_archive_allowed(device_name, cfg!(target_abi = "sim"))
1713        || !mtl_responds_to_sel(device, mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE))
1714    {
1715        return (null_mut(), null_mut(), false);
1716    }
1717    let arch_desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_BINARY_ARCHIVE_DESC);
1718    if arch_desc_cls.is_null() {
1719        return (null_mut(), null_mut(), false);
1720    }
1721    let cache_hash: u64 = metal_pipeline_cache_hash(device_name);
1722    let archive_path: String = env::temp_dir()
1723        .join(format!(
1724            "{MTL_ARCHIVE_FILE_PREFIX}{cache_hash:016x}{MTL_ARCHIVE_FILE_SUFFIX}"
1725        ))
1726        .to_string_lossy()
1727        .into_owned();
1728    let existed: bool = fs::metadata(&archive_path).is_ok();
1729    let ns_path: *mut c_void = mtl_ns_string(&archive_path);
1730    let url_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_URL);
1731    let ns_url: *mut c_void =
1732        mtl_send_ptr1(url_cls, mtl_sel_cstr(MTL_SEL_FILE_URL_WITH_PATH), ns_path);
1733    let arch_desc_alloc: *mut c_void = mtl_send_ptr0(arch_desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1734    let arch_desc: *mut c_void = mtl_send_ptr0(arch_desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1735    if arch_desc.is_null() {
1736        return (null_mut(), ns_url, existed);
1737    }
1738    if existed && !ns_url.is_null() {
1739        mtl_send_void_ptr1(arch_desc, mtl_sel_cstr(MTL_SEL_SET_URL), ns_url);
1740    }
1741    let mut err_ptr: *mut c_void = null_mut();
1742    let archive: *mut c_void = unsafe {
1743        let send_new: unsafe extern "C" fn(
1744            *mut c_void,
1745            *mut c_void,
1746            *mut c_void,
1747            *mut *mut c_void,
1748        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1749        send_new(
1750            device,
1751            mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE),
1752            arch_desc,
1753            &mut err_ptr,
1754        )
1755    };
1756    mtl_send_void0(arch_desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1757    (archive, ns_url, existed)
1758}
1759
1760/// Initializes or returns the process-wide cached Apple Metal device, command queue, binary-archived shader pipelines (`UI`, `Blur`, `3D PBR`, `Fluid Ocean`), and fallback textures.
1761///
1762/// # Arguments
1763///
1764/// - `GraphicsBackend` - Requested graphics backend.
1765///
1766/// # Returns
1767///
1768/// - `&'static MetalSharedPipelineCache` - Reference to the process-wide shared Metal PSO cache.
1769#[cfg(any(target_os = "macos", target_os = "ios"))]
1770pub(crate) fn init_apple_metal_shared_cache(
1771    backend: GraphicsBackend,
1772) -> &'static MetalSharedPipelineCache {
1773    METAL_SHARED_PIPELINE.get_or_init(|| {
1774        let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1775        let total_start: Instant = Instant::now();
1776        let result: MetalSharedPipelineCache = unsafe {
1777            let device: *mut c_void = MTLCreateSystemDefaultDevice();
1778            if device.is_null() {
1779                MetalSharedPipelineCache {
1780                    adapter: GpuAdapterInfo::new(
1781                        backend,
1782                        GPU_DEVICE_FALLBACK.to_string(),
1783                        false,
1784                        false,
1785                    ),
1786                    device: 0,
1787                    queue: 0,
1788                    library: 0,
1789                    pipeline: 0,
1790                    blur_pipeline: 0,
1791                    blur_up_pipeline: 0,
1792                    engine3d_pipeline: 0,
1793                    ocean_pipeline: 0,
1794                    scene_ocean_pipeline: 0,
1795                    scene_boat_pipeline: 0,
1796                    scene_3d_sky_pipeline: 0,
1797                    scene_3d_mesh_pipeline: 0,
1798                    scene_depth_stencil: 0,
1799                    scene_pbr_pipelines: [0; 5],
1800                    binary_archive_enabled: false,
1801                    binary_archive_hit: false,
1802                    ui_compile_us: 0,
1803                    blur_compile_us: 0,
1804                    engine3d_compile_us: 0,
1805                    ocean_compile_us: 0,
1806                    total_compile_us: 0,
1807                    dummy_r8_tex: 0,
1808                    dummy_rgba8_tex: 0,
1809                }
1810            } else {
1811                let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NAME));
1812                let utf8_ptr: *const c_char =
1813                    mtl_send_ptr0(ns_name, mtl_sel_cstr(MTL_SEL_UTF8_STRING)).cast::<c_char>();
1814                let device_name: String = if utf8_ptr.is_null() {
1815                    GPU_DEVICE_APPLE_METAL.to_string()
1816                } else {
1817                    CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
1818                };
1819                let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NEW_CMD_QUEUE));
1820                let (archive, archive_url, archive_existed): (*mut c_void, *mut c_void, bool) =
1821                    metal_open_binary_archive(device, &device_name);
1822                let archive_enabled: bool = !archive.is_null();
1823                let send_lib: unsafe extern "C" fn(
1824                    *mut c_void,
1825                    *mut c_void,
1826                    *mut c_void,
1827                    *mut c_void,
1828                    *mut *mut c_void,
1829                ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1830                let ui_start: Instant = Instant::now();
1831                let mut err_ptr: *mut c_void = null_mut();
1832                let library: *mut c_void = send_lib(
1833                    device,
1834                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1835                    mtl_ns_string(MSL_UI_SHADER),
1836                    null_mut(),
1837                    &mut err_ptr,
1838                );
1839                let (pipeline, ui_fns_ok): (usize, bool) = metal_build_render_pipeline(
1840                    device,
1841                    library,
1842                    MTL_FN_VERTEX,
1843                    MTL_FN_FRAGMENT,
1844                    archive,
1845                    true,
1846                );
1847                let ui_compile_us: u64 = ui_start.elapsed().as_micros() as u64;
1848                let blur_start: Instant = Instant::now();
1849                let mut blur_err: *mut c_void = null_mut();
1850                let blur_lib: *mut c_void = send_lib(
1851                    device,
1852                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1853                    mtl_ns_string(MSL_BACKDROP_BLUR_SHADER),
1854                    null_mut(),
1855                    &mut blur_err,
1856                );
1857                let (blur_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1858                    device,
1859                    blur_lib,
1860                    MTL_FN_BLUR_VERTEX,
1861                    MTL_FN_BLUR_DOWN,
1862                    archive,
1863                    false,
1864                );
1865                let (blur_up_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1866                    device,
1867                    blur_lib,
1868                    MTL_FN_BLUR_VERTEX,
1869                    MTL_FN_BLUR_UP,
1870                    archive,
1871                    false,
1872                );
1873                if !blur_lib.is_null() {
1874                    mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1875                }
1876                let blur_compile_us: u64 = blur_start.elapsed().as_micros() as u64;
1877                let pbr_start: Instant = Instant::now();
1878                let mut pbr_err: *mut c_void = null_mut();
1879                let pbr_lib: *mut c_void = send_lib(
1880                    device,
1881                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1882                    mtl_ns_string(MSL_ENGINE3D_PBR_SHADER),
1883                    null_mut(),
1884                    &mut pbr_err,
1885                );
1886                let (engine3d_pipeline, _): (usize, bool) =
1887                    metal_build_render_pipeline_3d(device, pbr_lib, archive);
1888                if !pbr_lib.is_null() {
1889                    mtl_send_void0(pbr_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1890                }
1891                let engine3d_compile_us: u64 = pbr_start.elapsed().as_micros() as u64;
1892                let ocean_start: Instant = Instant::now();
1893                let mut ocean_err: *mut c_void = null_mut();
1894                let ocean_lib: *mut c_void = send_lib(
1895                    device,
1896                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1897                    mtl_ns_string(MSL_FLUID_OCEAN_SHADER),
1898                    null_mut(),
1899                    &mut ocean_err,
1900                );
1901                let (ocean_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1902                    device,
1903                    ocean_lib,
1904                    MTL_FN_OCEAN_VERTEX,
1905                    MTL_FN_OCEAN_FRAGMENT,
1906                    archive,
1907                    false,
1908                );
1909                if !ocean_lib.is_null() {
1910                    mtl_send_void0(ocean_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1911                }
1912                let ocean_compile_us: u64 = ocean_start.elapsed().as_micros() as u64;
1913                let mut scene_err: *mut c_void = null_mut();
1914                let scene_lib: *mut c_void = send_lib(
1915                    device,
1916                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1917                    mtl_ns_string(MSL_GPU_SCENE_SHADER),
1918                    null_mut(),
1919                    &mut scene_err,
1920                );
1921                let (scene_ocean_pipeline, _): (usize, bool) =
1922                    metal_build_render_pipeline_with_depth(
1923                        device,
1924                        scene_lib,
1925                        MTL_FN_SCENE_OCEAN_VERT,
1926                        MTL_FN_SCENE_OCEAN_FRAG,
1927                        archive,
1928                        false,
1929                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1930                    );
1931                let (scene_boat_pipeline, _): (usize, bool) =
1932                    metal_build_render_pipeline_with_depth(
1933                        device,
1934                        scene_lib,
1935                        MTL_FN_SCENE_BOAT_VERT,
1936                        MTL_FN_SCENE_BOAT_FRAG,
1937                        archive,
1938                        false,
1939                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1940                    );
1941                let (scene_3d_sky_pipeline, _): (usize, bool) =
1942                    metal_build_render_pipeline_with_depth(
1943                        device,
1944                        scene_lib,
1945                        MTL_FN_SCENE_3D_SKY_VERT,
1946                        MTL_FN_SCENE_3D_SKY_FRAG,
1947                        archive,
1948                        false,
1949                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1950                    );
1951                let (scene_3d_mesh_pipeline, _): (usize, bool) =
1952                    metal_build_render_pipeline_with_depth(
1953                        device,
1954                        scene_lib,
1955                        MTL_FN_SCENE_3D_MESH_VERT,
1956                        MTL_FN_SCENE_3D_MESH_FRAG,
1957                        archive,
1958                        false,
1959                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1960                    );
1961                if !scene_lib.is_null() {
1962                    mtl_send_void0(scene_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1963                }
1964                let mut pbr_scene_err: *mut c_void = null_mut();
1965                let pbr_scene_lib: *mut c_void = send_lib(
1966                    device,
1967                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1968                    mtl_ns_string(MSL_PBR_SCENE_SHADER),
1969                    null_mut(),
1970                    &mut pbr_scene_err,
1971                );
1972                let (scene_pbr_sky_pso, _): (usize, bool) = metal_build_render_pipeline_with_depth(
1973                    device,
1974                    pbr_scene_lib,
1975                    MTL_FN_SCENE_PBR_SKY_VERT,
1976                    MTL_FN_SCENE_PBR_SKY_FRAG,
1977                    archive,
1978                    false,
1979                    MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1980                );
1981                let (scene_pbr_opaque_pso, _): (usize, bool) =
1982                    metal_build_render_pipeline_with_depth(
1983                        device,
1984                        pbr_scene_lib,
1985                        MTL_FN_SCENE_PBR_VERT,
1986                        MTL_FN_SCENE_PBR_FRAG,
1987                        archive,
1988                        false,
1989                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1990                    );
1991                let (scene_pbr_skinned_pso, _): (usize, bool) =
1992                    metal_build_render_pipeline_with_depth(
1993                        device,
1994                        pbr_scene_lib,
1995                        MTL_FN_SCENE_PBR_SKINNED_VERT,
1996                        MTL_FN_SCENE_PBR_FRAG,
1997                        archive,
1998                        false,
1999                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
2000                    );
2001                let (scene_pbr_alpha_pso, _): (usize, bool) =
2002                    metal_build_render_pipeline_with_depth(
2003                        device,
2004                        pbr_scene_lib,
2005                        MTL_FN_SCENE_PBR_VERT,
2006                        MTL_FN_SCENE_PBR_FRAG,
2007                        archive,
2008                        true,
2009                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
2010                    );
2011                if !pbr_scene_lib.is_null() {
2012                    mtl_send_void0(pbr_scene_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
2013                }
2014                let scene_depth_stencil: usize = metal_create_depth_stencil_state(device);
2015                let scene_depth_ro_stencil: usize =
2016                    metal_create_read_only_depth_stencil_state(device);
2017                let scene_pbr_pipelines: [usize; 5] = [
2018                    scene_pbr_sky_pso,
2019                    scene_pbr_opaque_pso,
2020                    scene_pbr_skinned_pso,
2021                    scene_pbr_alpha_pso,
2022                    scene_depth_ro_stencil,
2023                ];
2024                if !archive.is_null() {
2025                    if !archive_existed
2026                        && !archive_url.is_null()
2027                        && pipeline != 0
2028                        && metal_binary_archive_allowed(&device_name, cfg!(target_abi = "sim"))
2029                        && mtl_responds_to_sel(archive, mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL))
2030                    {
2031                        let mut ser_err: *mut c_void = null_mut();
2032                        let send_ser: unsafe extern "C" fn(
2033                            *mut c_void,
2034                            *mut c_void,
2035                            *mut c_void,
2036                            *mut *mut c_void,
2037                        ) -> i8 = transmute(objc_msgSend as *const c_void);
2038                        let _: i8 = send_ser(
2039                            archive,
2040                            mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL),
2041                            archive_url,
2042                            &mut ser_err,
2043                        );
2044                    }
2045                    mtl_send_void0(archive, mtl_sel_cstr(MTL_SEL_RELEASE));
2046                }
2047                let dummy_r8_tex: usize =
2048                    metal_create_texture(device, GpuAtlasPixelFormat::R8Unorm, 1, 1);
2049                let dummy_rgba8_tex: usize =
2050                    metal_create_texture(device, GpuAtlasPixelFormat::Rgba8Unorm, 1, 1);
2051                let shader_compiled: bool = ui_fns_ok && pipeline != 0;
2052                let total_compile_us: u64 = total_start.elapsed().as_micros() as u64;
2053                MetalSharedPipelineCache {
2054                    adapter: GpuAdapterInfo::new(
2055                        GraphicsBackend::Metal,
2056                        device_name,
2057                        !queue.is_null(),
2058                        shader_compiled,
2059                    ),
2060                    device: device as usize,
2061                    queue: queue as usize,
2062                    library: library as usize,
2063                    pipeline,
2064                    blur_pipeline,
2065                    blur_up_pipeline,
2066                    engine3d_pipeline,
2067                    ocean_pipeline,
2068                    scene_ocean_pipeline,
2069                    scene_boat_pipeline,
2070                    scene_3d_sky_pipeline,
2071                    scene_3d_mesh_pipeline,
2072                    scene_depth_stencil,
2073                    scene_pbr_pipelines,
2074                    binary_archive_enabled: archive_enabled,
2075                    binary_archive_hit: archive_enabled && archive_existed,
2076                    ui_compile_us,
2077                    blur_compile_us,
2078                    engine3d_compile_us,
2079                    ocean_compile_us,
2080                    total_compile_us,
2081                    dummy_r8_tex,
2082                    dummy_rgba8_tex,
2083                }
2084            }
2085        };
2086        unsafe { objc_autoreleasePoolPop(pool) };
2087        result
2088    })
2089}
2090
2091/// Retains and returns handles from the process-wide Apple Metal shared pipeline cache for a new `NativeGpuDriver`.
2092///
2093/// # Arguments
2094///
2095/// - `GraphicsBackend` - Requested graphics backend.
2096///
2097/// # Returns
2098///
2099/// - `NativeGpuProbeOutput` - Retained device, queue, library, pipelines, and dummy texture handles.
2100#[cfg(any(target_os = "macos", target_os = "ios"))]
2101fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
2102    let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
2103    NativeGpuProbeOutput {
2104        adapter: cached.adapter.clone(),
2105        device_handle: mtl_retain_handle(cached.device),
2106        queue_handle: mtl_retain_handle(cached.queue),
2107        library_handle: mtl_retain_handle(cached.library),
2108        pipeline_handle: mtl_retain_handle(cached.pipeline),
2109        blur_pipeline_handle: mtl_retain_handle(cached.blur_pipeline),
2110        blur_up_pipeline_handle: mtl_retain_handle(cached.blur_up_pipeline),
2111        engine3d_pipeline_handle: mtl_retain_handle(cached.engine3d_pipeline),
2112        ocean_pipeline_handle: mtl_retain_handle(cached.ocean_pipeline),
2113        scene_ocean_pipeline_handle: mtl_retain_handle(cached.scene_ocean_pipeline),
2114        scene_boat_pipeline_handle: mtl_retain_handle(cached.scene_boat_pipeline),
2115        scene_3d_sky_pipeline_handle: mtl_retain_handle(cached.scene_3d_sky_pipeline),
2116        scene_3d_mesh_pipeline_handle: mtl_retain_handle(cached.scene_3d_mesh_pipeline),
2117        scene_depth_stencil_handle: mtl_retain_handle(cached.scene_depth_stencil),
2118        dummy_r8_tex: mtl_retain_handle(cached.dummy_r8_tex),
2119        dummy_rgba8_tex: mtl_retain_handle(cached.dummy_rgba8_tex),
2120        scene_pbr_pipelines: [
2121            mtl_retain_handle(cached.scene_pbr_pipelines[0]),
2122            mtl_retain_handle(cached.scene_pbr_pipelines[1]),
2123            mtl_retain_handle(cached.scene_pbr_pipelines[2]),
2124            mtl_retain_handle(cached.scene_pbr_pipelines[3]),
2125            mtl_retain_handle(cached.scene_pbr_pipelines[4]),
2126        ],
2127    }
2128}
2129
2130/// Returns the process-wide `OnceLock`-cached Objective-C selector pointers for Metal hot-path submission and encoding.
2131///
2132/// # Returns
2133///
2134/// - `&'static MetalSelectors` - Cached Metal selector addresses.
2135#[cfg(any(target_os = "macos", target_os = "ios"))]
2136pub(crate) fn cached_metal_selectors() -> &'static MetalSelectors {
2137    METAL_SELECTORS.get_or_init(|| MetalSelectors {
2138        retain: mtl_sel_cstr(MTL_SEL_RETAIN) as usize,
2139        new_buffer_with_bytes: mtl_sel_cstr(MTL_SEL_NEW_BUFFER) as usize,
2140        new_buffer_with_length: mtl_sel_cstr(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
2141        contents: mtl_sel_cstr(MTL_SEL_CONTENTS) as usize,
2142        command_buffer: mtl_sel_cstr(MTL_SEL_CMD_BUFFER) as usize,
2143        render_encoder: mtl_sel_cstr(MTL_SEL_RENDER_ENCODER) as usize,
2144        set_pipeline_state: mtl_sel_cstr(MTL_SEL_SET_PIPELINE_STATE) as usize,
2145        set_vertex_buffer: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BUFFER) as usize,
2146        set_vertex_bytes: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BYTES) as usize,
2147        set_fragment_texture: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_TEXTURE) as usize,
2148        set_fragment_bytes: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_BYTES) as usize,
2149        set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
2150        set_viewport: mtl_sel_cstr(MTL_SEL_SET_VIEWPORT) as usize,
2151        draw_primitives_instanced: mtl_sel_cstr(MTL_SEL_DRAW_PRIMITIVES_INSTANCED) as usize,
2152        end_encoding: mtl_sel_cstr(MTL_SEL_END_ENCODING) as usize,
2153        present_drawable: mtl_sel_cstr(MTL_SEL_PRESENT_DRAWABLE) as usize,
2154        #[cfg(not(target_abi = "sim"))]
2155        add_presented_handler: mtl_sel_cstr(MTL_SEL_ADD_PRESENTED_HANDLER) as usize,
2156        add_completed_handler: mtl_sel_cstr(MTL_SEL_ADD_COMPLETED_HANDLER) as usize,
2157        #[cfg(not(target_abi = "sim"))]
2158        presented_time: mtl_sel_cstr(MTL_SEL_PRESENTED_TIME) as usize,
2159        responds_to_sel: mtl_sel_cstr(MTL_SEL_RESPONDS_TO_SEL) as usize,
2160        status: mtl_sel_cstr(MTL_SEL_STATUS) as usize,
2161        wait_until_completed: mtl_sel_cstr(MTL_SEL_WAIT_UNTIL_COMPLETED) as usize,
2162        gpu_start_time: mtl_sel_cstr(MTL_SEL_GPU_START_TIME) as usize,
2163        gpu_end_time: mtl_sel_cstr(MTL_SEL_GPU_END_TIME) as usize,
2164        next_drawable: mtl_sel_cstr(MTL_SEL_NEXT_DRAWABLE) as usize,
2165        drawable_size: mtl_sel_cstr(MTL_SEL_DRAWABLE_SIZE) as usize,
2166        set_drawable_size: mtl_sel_cstr(MTL_SEL_SET_DRAWABLE_SIZE) as usize,
2167        texture: mtl_sel_cstr(MTL_SEL_TEXTURE) as usize,
2168        width: mtl_sel_cstr(MTL_SEL_WIDTH) as usize,
2169        height: mtl_sel_cstr(MTL_SEL_HEIGHT) as usize,
2170        render_pass_desc: mtl_sel_cstr(MTL_SEL_RENDER_PASS_DESC) as usize,
2171        color_attachments: mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS) as usize,
2172        object_at_index: mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX) as usize,
2173        set_texture: mtl_sel_cstr(MTL_SEL_SET_TEXTURE) as usize,
2174        set_load_action: mtl_sel_cstr(MTL_SEL_SET_LOAD_ACTION) as usize,
2175        set_store_action: mtl_sel_cstr(MTL_SEL_SET_STORE_ACTION) as usize,
2176        set_clear_color: mtl_sel_cstr(MTL_SEL_SET_CLEAR_COLOR) as usize,
2177        depth_attachment: mtl_sel_cstr(MTL_SEL_DEPTH_ATTACHMENT) as usize,
2178        set_clear_depth: mtl_sel_cstr(MTL_SEL_SET_CLEAR_DEPTH) as usize,
2179        set_depth_stencil_state: mtl_sel_cstr(MTL_SEL_SET_DEPTH_STENCIL_STATE) as usize,
2180        replace_region: mtl_sel_cstr(MTL_SEL_REPLACE_REGION) as usize,
2181        set_fragment_buffer: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_BUFFER) as usize,
2182        draw_indexed_instanced: mtl_sel_cstr(MTL_SEL_DRAW_INDEXED_INSTANCED) as usize,
2183        new_texture_view: mtl_sel_cstr(MTL_SEL_NEW_TEXTURE_VIEW) as usize,
2184        commit: mtl_sel_cstr(MTL_SEL_COMMIT) as usize,
2185        release: mtl_sel_cstr(MTL_SEL_RELEASE) as usize,
2186    })
2187}
2188
2189/// Resolves whether macOS `CAMetalLayer.displaySyncEnabled` should be active by default (`false` when uncapped throughput env flags are set).
2190///
2191/// # Returns
2192///
2193/// - `bool` - `true` for tear-free native VRR sync; `false` when uncapped non-blocking presentation is requested.
2194#[cfg(any(target_os = "macos", target_os = "ios"))]
2195#[must_use]
2196pub(crate) fn metal_preferred_display_sync_enabled() -> bool {
2197    let uncapped_env: bool = env::var(ENV_UNCAPPED_PRESENT)
2198        .map(|val: String| {
2199            let trimmed: &str = val.trim();
2200            trimmed == MTL_ENV_VALUE_ON || trimmed.eq_ignore_ascii_case(MTL_ENV_VALUE_TRUE)
2201        })
2202        .unwrap_or(false);
2203    if uncapped_env {
2204        return false;
2205    }
2206    let sync_disabled: bool = env::var(ENV_METAL_DISPLAY_SYNC)
2207        .map(|val: String| {
2208            let trimmed: &str = val.trim();
2209            trimmed == MTL_ENV_VALUE_OFF || trimmed.eq_ignore_ascii_case(MTL_ENV_VALUE_FALSE)
2210        })
2211        .unwrap_or(false);
2212    !sync_disabled
2213}
2214
2215/// Applies `CAMetalLayer.displaySyncEnabled` when supported by the host Apple OS layer (macOS).
2216///
2217/// # Arguments
2218///
2219/// - `usize` - Target `CAMetalLayer*` pointer.
2220/// - `bool` - `true` for hardware display sync; `false` for uncapped non-blocking throughput.
2221#[cfg(any(target_os = "macos", target_os = "ios"))]
2222fn metal_set_layer_display_sync(layer_handle: usize, enabled: bool) {
2223    if layer_handle == 0 {
2224        return;
2225    }
2226    let layer: *mut c_void = layer_handle as *mut c_void;
2227    let sel_sync: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_DISPLAY_SYNC);
2228    if mtl_responds_to_sel(layer, sel_sync) {
2229        mtl_send_void_bool(layer, sel_sync, enabled);
2230    }
2231}
2232
2233/// Configures a `CAMetalLayer*` for direct triple-buffered GPU draw (`BGRA8Unorm`, `framebufferOnly = YES`, `maximumDrawableCount = 3`).
2234///
2235/// # Arguments
2236///
2237/// - `usize` - Retained `id<MTLDevice>` handle.
2238/// - `usize` - Target `CAMetalLayer*` pointer.
2239#[cfg(any(target_os = "macos", target_os = "ios"))]
2240fn metal_configure_layer(device_handle: usize, layer_handle: usize) {
2241    if device_handle == 0 || layer_handle == 0 {
2242        return;
2243    }
2244    let layer: *mut c_void = layer_handle as *mut c_void;
2245    mtl_send_void_ptr1(
2246        layer,
2247        mtl_sel_cstr(MTL_SEL_SET_DEVICE),
2248        device_handle as *mut c_void,
2249    );
2250    mtl_send_void_usize(
2251        layer,
2252        mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
2253        MTL_PIXEL_FORMAT_BGRA8_UNORM,
2254    );
2255    mtl_send_void_bool(layer, mtl_sel_cstr(MTL_SEL_SET_FRAMEBUFFER_ONLY), true);
2256    let sel_max: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_MAX_DRAWABLE_COUNT);
2257    if mtl_responds_to_sel(layer, sel_max) {
2258        mtl_send_void_usize(layer, sel_max, GPU_DRIVER_RING_SLOTS);
2259    }
2260    metal_set_layer_display_sync(layer_handle, metal_preferred_display_sync_enabled());
2261}
2262
2263/// Uploads a dirty R8 or RGBA8 sub-rectangle into a Metal `MTLTexture` via `replaceRegion:mipmapLevel:withBytes:bytesPerRow:`.
2264///
2265/// # Arguments
2266///
2267/// - `usize` - Retained `id<MTLDevice>` handle.
2268/// - `&mut usize` - Resident `id<MTLTexture>` handle (`0` lazily allocates a new texture).
2269/// - `GpuAtlasPixelFormat` - Target Metal pixel format.
2270/// - `(u32, u32)` - Backing texture dimensions `(width, height)`.
2271/// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
2272/// - `&[u8]` - Source pixel slice.
2273/// - `usize` - Row stride in bytes.
2274///
2275/// # Returns
2276///
2277/// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly.
2278#[cfg(any(target_os = "macos", target_os = "ios"))]
2279fn metal_upload_texture_dirty_rect(
2280    device_handle: usize,
2281    texture_handle: &mut usize,
2282    format: GpuAtlasPixelFormat,
2283    tex_dims: (u32, u32),
2284    dirty_rect: (u32, u32, u32, u32),
2285    bytes: &[u8],
2286    bytes_per_row: usize,
2287) -> bool {
2288    if device_handle == 0 || dirty_rect.2 == 0 || dirty_rect.3 == 0 || bytes.is_empty() {
2289        return false;
2290    }
2291    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2292    let (tex_w, tex_h): (u32, u32) = (tex_dims.0.max(1), tex_dims.1.max(1));
2293    let sel: &MetalSelectors = cached_metal_selectors();
2294    let cur_w: usize = if *texture_handle != 0 {
2295        mtl_send_usize0(*texture_handle as *mut c_void, sel.width as *mut c_void)
2296    } else {
2297        0
2298    };
2299    let cur_h: usize = if *texture_handle != 0 {
2300        mtl_send_usize0(*texture_handle as *mut c_void, sel.height as *mut c_void)
2301    } else {
2302        0
2303    };
2304    if *texture_handle == 0 || cur_w != tex_w as usize || cur_h != tex_h as usize {
2305        if *texture_handle != 0 {
2306            mtl_send_void0(*texture_handle as *mut c_void, sel.release as *mut c_void);
2307        }
2308        *texture_handle = metal_create_texture(device_handle as *mut c_void, format, tex_w, tex_h);
2309    }
2310    if *texture_handle == 0 {
2311        unsafe { objc_autoreleasePoolPop(pool) };
2312        return false;
2313    }
2314    let region: MtlRegion = MtlRegion {
2315        origin: MtlOrigin {
2316            x: dirty_rect.0 as usize,
2317            y: dirty_rect.1 as usize,
2318            z: 0,
2319        },
2320        size: MtlSize {
2321            width: dirty_rect.2 as usize,
2322            height: dirty_rect.3 as usize,
2323            depth: 1,
2324        },
2325    };
2326    unsafe {
2327        let send_replace: unsafe extern "C" fn(
2328            *mut c_void,
2329            *mut c_void,
2330            MtlRegion,
2331            usize,
2332            *const c_void,
2333            usize,
2334        ) = transmute(objc_msgSend as *const c_void);
2335        send_replace(
2336            *texture_handle as *mut c_void,
2337            sel.replace_region as *mut c_void,
2338            region,
2339            0,
2340            bytes.as_ptr().cast::<c_void>(),
2341            bytes_per_row,
2342        );
2343        objc_autoreleasePoolPop(pool);
2344    }
2345    true
2346}
2347
2348/// Uploads packed 64-byte `GpuPrimitiveInstance` buffers into a 3-slot fenced Metal ring, encodes real instanced `MTLRenderCommandEncoder` draws when a `CAMetalLayer` is bound, and commits with presentation timing handlers.
2349///
2350/// # Arguments
2351///
2352/// - `&mut NativeGpuDriver` - Mutable GPU driver holding ring slots, pipelines, textures, and layer handle.
2353/// - `u32` - Physical surface width in pixels.
2354/// - `u32` - Physical surface height in pixels.
2355/// - `Color` - Surface clear color.
2356/// - `&[GpuBatch]` - Ordered GPU batches to encode and submit.
2357///
2358/// # Returns
2359///
2360/// - `usize` - Total 64-byte `GpuPrimitiveInstance` records uploaded and submitted.
2361#[cfg(any(target_os = "macos", target_os = "ios"))]
2362fn metal_submit_ring_frame(
2363    driver: &mut NativeGpuDriver,
2364    width: u32,
2365    height: u32,
2366    clear_color: Color,
2367    batches: &[GpuBatch],
2368) -> usize {
2369    let total_instances: usize = batches
2370        .iter()
2371        .map(|blue_val: &GpuBatch| {
2372            blue_val
2373                .get_primitives()
2374                .len()
2375                .max(blue_val.get_instances().len())
2376        })
2377        .sum();
2378    let device_handle: usize = driver.get_device_handle();
2379    let queue_handle: usize = driver.get_queue_handle();
2380    let layer_handle: usize = driver.get_surface_layer_handle();
2381    if device_handle == 0 || queue_handle == 0 || layer_handle == 0 {
2382        return total_instances;
2383    }
2384    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2385    let sel: &MetalSelectors = cached_metal_selectors();
2386    let sel_rel: *mut c_void = sel.release as *mut c_void;
2387    let slot_idx: usize = driver.get_ring_cursor() % GPU_DRIVER_RING_SLOTS;
2388    let device: *mut c_void = device_handle as *mut c_void;
2389    let queue: *mut c_void = queue_handle as *mut c_void;
2390    let pipeline: *mut c_void = driver.get_pipeline_handle() as *mut c_void;
2391    let blur_down_pso: *mut c_void = driver.get_blur_pipeline_handle() as *mut c_void;
2392    let blur_up_pso: *mut c_void = driver.get_blur_up_pipeline_handle() as *mut c_void;
2393    let scene_pipelines: [*mut c_void; 5] = [
2394        driver.get_scene_ocean_pipeline_handle() as *mut c_void,
2395        driver.get_scene_boat_pipeline_handle() as *mut c_void,
2396        driver.get_scene_3d_sky_pipeline_handle() as *mut c_void,
2397        driver.get_scene_3d_mesh_pipeline_handle() as *mut c_void,
2398        driver.get_scene_depth_stencil_handle() as *mut c_void,
2399    ];
2400    let layer_ptr: *mut c_void = layer_handle as *mut c_void;
2401    let tex_r8: *mut c_void = driver.get_glyph_r8_texture_handle() as *mut c_void;
2402    let tex_rgba8: *mut c_void = driver.get_glyph_rgba8_texture_handle() as *mut c_void;
2403    let tex_img: *mut c_void = driver.get_image_texture_handle() as *mut c_void;
2404    let raw_ext: usize = driver.get_external_texture_handle();
2405    let mut tex_ext: *mut c_void = if raw_ext != 0 {
2406        raw_ext as *mut c_void
2407    } else {
2408        tex_rgba8
2409    };
2410    let has_blur_batches: bool = !blur_down_pso.is_null()
2411        && !blur_up_pso.is_null()
2412        && batches.iter().any(|batch_item: &GpuBatch| {
2413            batch_item
2414                .get_primitives()
2415                .iter()
2416                .any(|prim_item: &GpuPrimitiveInstance| {
2417                    prim_item.prim_kind() == PrimKind::BackdropBlur
2418                })
2419        });
2420    let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuPrimitiveInstance>());
2421    let NativeGpuDriver {
2422        ring_slots,
2423        ring_cursor,
2424        staging_buffer_handle,
2425        staging_contents_ptr,
2426        staging_buffer_capacity,
2427        staging_reallocations,
2428        scratch_primitives,
2429        blur_scene_texture_handle,
2430        blur_half_texture_handle,
2431        blur_full_texture_handle,
2432        blur_texture_dims,
2433        scene_color_texture_handle,
2434        scene_depth_texture_handle,
2435        scene_wake_texture_handle,
2436        scene_wake_texture_handles,
2437        scene_texture_dims,
2438        scene_3d_vertex_buffer_handle,
2439        scene_3d_vertex_revision,
2440        scene_3d_vertex_capacity,
2441        scene_3d_instance_buffer_handle,
2442        scene_3d_instance_capacity,
2443        scene_3d_instance_buffer_handles,
2444        scene_3d_instance_capacities,
2445        scene_boat_buffer_handle,
2446        scene_boat_capacity,
2447        scene_boat_buffer_handles,
2448        scene_boat_capacities,
2449        pending_gpu_scene_pass,
2450        pbr_scene_resources,
2451        ..
2452    } = driver;
2453    let frame_scene_pass: Option<DirectGpuScenePass> = pending_gpu_scene_pass.take();
2454    let slot: &mut NativeGpuRingSlot = &mut ring_slots[slot_idx];
2455    let prev_cmd: usize = slot.get_in_flight_cmd_buffer();
2456    if prev_cmd != 0 {
2457        let status: usize = mtl_send_usize0(prev_cmd as *mut c_void, sel.status as *mut c_void);
2458        if status < MTL_CMD_BUFFER_STATUS_COMPLETED {
2459            mtl_send_void0(
2460                prev_cmd as *mut c_void,
2461                sel.wait_until_completed as *mut c_void,
2462            );
2463        }
2464        mtl_send_void0(prev_cmd as *mut c_void, sel_rel);
2465        slot.set_in_flight_cmd_buffer(0);
2466    }
2467    if total_bytes > 0
2468        && (slot.get_buffer_handle() == 0
2469            || slot.get_contents_ptr() == 0
2470            || total_bytes > slot.get_capacity_bytes())
2471    {
2472        if slot.get_buffer_handle() != 0 {
2473            mtl_send_void0(slot.get_buffer_handle() as *mut c_void, sel_rel);
2474            slot.set_buffer_handle(0);
2475            slot.set_contents_ptr(0);
2476            slot.set_capacity_bytes(0);
2477        }
2478        let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
2479        unsafe {
2480            let send_new_len: unsafe extern "C" fn(
2481                *mut c_void,
2482                *mut c_void,
2483                usize,
2484                usize,
2485            ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
2486            let new_buf: *mut c_void = send_new_len(
2487                device,
2488                sel.new_buffer_with_length as *mut c_void,
2489                alloc_bytes,
2490                0,
2491            );
2492            if !new_buf.is_null() {
2493                let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
2494                if !ptr.is_null() {
2495                    slot.set_buffer_handle(new_buf as usize);
2496                    slot.set_contents_ptr(ptr as usize);
2497                    slot.set_capacity_bytes(alloc_bytes);
2498                    *staging_reallocations = staging_reallocations.wrapping_add(1);
2499                } else {
2500                    mtl_send_void0(new_buf, sel_rel);
2501                }
2502            }
2503        }
2504    }
2505    let buf_handle: usize = slot.get_buffer_handle();
2506    let contents_ptr: usize = slot.get_contents_ptr();
2507    let capacity_bytes: usize = slot.get_capacity_bytes();
2508    *staging_buffer_handle = buf_handle;
2509    *staging_contents_ptr = contents_ptr;
2510    *staging_buffer_capacity = capacity_bytes;
2511    if contents_ptr != 0 && total_bytes > 0 && total_bytes <= capacity_bytes {
2512        unsafe {
2513            let mut dst: *mut u8 = (contents_ptr as *mut c_void).cast::<u8>();
2514            for batch in batches.iter() {
2515                let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
2516                if !prims.is_empty() {
2517                    let byte_len: usize = size_of_val(prims);
2518                    dst.copy_from_nonoverlapping(prims.as_ptr().cast::<u8>(), byte_len);
2519                    dst = dst.add(byte_len);
2520                } else if !batch.get_instances().is_empty() {
2521                    scratch_primitives.clear();
2522                    for quad in batch.get_instances().iter() {
2523                        scratch_primitives.push(GpuPrimitiveInstance::from_quad_instance(
2524                            quad,
2525                            batch.get_texture_slot(),
2526                            batch.get_layer_id(),
2527                        ));
2528                    }
2529                    let byte_len: usize = size_of_val(scratch_primitives.as_slice());
2530                    dst.copy_from_nonoverlapping(
2531                        scratch_primitives.as_ptr().cast::<u8>(),
2532                        byte_len,
2533                    );
2534                    dst = dst.add(byte_len);
2535                }
2536            }
2537        }
2538    }
2539    let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
2540    if !cmd_buf.is_null() {
2541        let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
2542        if mtl_responds_to_sel(cmd_buf, sel_completed) {
2543            mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
2544        }
2545        if !layer_ptr.is_null() && !pipeline.is_null() {
2546            if width > 0
2547                && height > 0
2548                && mtl_responds_to_sel(layer_ptr, sel.set_drawable_size as *mut c_void)
2549            {
2550                let target_w: f64 = f64::from(width);
2551                let target_h: f64 = f64::from(height);
2552                let needs_resize: bool =
2553                    if mtl_responds_to_sel(layer_ptr, sel.drawable_size as *mut c_void) {
2554                        // SAFETY: `-[CAMetalLayer drawableSize]` returns a 16-byte `CGSize` in FP registers on 64-bit Apple targets.
2555                        let cur: MtlCgSize = unsafe {
2556                            let get_size: unsafe extern "C" fn(
2557                                *mut c_void,
2558                                *mut c_void,
2559                            )
2560                                -> MtlCgSize = transmute(objc_msgSend as *const c_void);
2561                            get_size(layer_ptr, sel.drawable_size as *mut c_void)
2562                        };
2563                        (cur.width - target_w).abs() > 0.5 || (cur.height - target_h).abs() > 0.5
2564                    } else {
2565                        true
2566                    };
2567                if needs_resize {
2568                    // SAFETY: `-[CAMetalLayer setDrawableSize:]` takes a single `CGSize` (`{ f64, f64 }`) value.
2569                    unsafe {
2570                        let set_size: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlCgSize) =
2571                            transmute(objc_msgSend as *const c_void);
2572                        set_size(
2573                            layer_ptr,
2574                            sel.set_drawable_size as *mut c_void,
2575                            MtlCgSize {
2576                                width: target_w,
2577                                height: target_h,
2578                            },
2579                        );
2580                    }
2581                }
2582            }
2583            let drawable: *mut c_void = mtl_send_ptr0(layer_ptr, sel.next_drawable as *mut c_void);
2584            if !drawable.is_null() {
2585                let drawable_tex: *mut c_void = mtl_send_ptr0(drawable, sel.texture as *mut c_void);
2586                let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
2587                if !drawable_tex.is_null() && !pass_cls.is_null() {
2588                    let tex_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void);
2589                    let tex_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void);
2590                    let draw_w: usize = if tex_w > 0 {
2591                        tex_w
2592                    } else {
2593                        width.max(1) as usize
2594                    };
2595                    let draw_h: usize = if tex_h > 0 {
2596                        tex_h
2597                    } else {
2598                        height.max(1) as usize
2599                    };
2600                    let clear_rgba: [f32; 4] = clear_color.to_f32_array();
2601                    let mtl_clear: MtlClearColor = MtlClearColor {
2602                        red: clear_rgba[0] as f64,
2603                        green: clear_rgba[1] as f64,
2604                        blue: clear_rgba[2] as f64,
2605                        alpha: clear_rgba[3] as f64,
2606                    };
2607                    let mut use_blur_offscreen: bool = false;
2608                    let mut scene_tex_ptr: *mut c_void = null_mut();
2609                    let mut half_tex_ptr: *mut c_void = null_mut();
2610                    let mut full_tex_ptr: *mut c_void = null_mut();
2611                    let half_w_u32: u32 = ((draw_w as u32) / 2).max(1);
2612                    let half_h_u32: u32 = ((draw_h as u32) / 2).max(1);
2613                    if has_blur_batches {
2614                        let target_dims: (u32, u32) = (draw_w as u32, draw_h as u32);
2615                        if *blur_scene_texture_handle == 0
2616                            || *blur_half_texture_handle == 0
2617                            || *blur_full_texture_handle == 0
2618                            || *blur_texture_dims != target_dims
2619                        {
2620                            release_native_gpu_object(*blur_scene_texture_handle);
2621                            release_native_gpu_object(*blur_half_texture_handle);
2622                            release_native_gpu_object(*blur_full_texture_handle);
2623                            let unified_mem: bool = cfg!(target_arch = "aarch64");
2624                            *blur_scene_texture_handle = metal_create_offscreen_render_texture(
2625                                device_handle,
2626                                target_dims.0,
2627                                target_dims.1,
2628                                unified_mem,
2629                            );
2630                            *blur_half_texture_handle = metal_create_offscreen_render_texture(
2631                                device_handle,
2632                                half_w_u32,
2633                                half_h_u32,
2634                                unified_mem,
2635                            );
2636                            *blur_full_texture_handle = metal_create_offscreen_render_texture(
2637                                device_handle,
2638                                target_dims.0,
2639                                target_dims.1,
2640                                unified_mem,
2641                            );
2642                            *blur_texture_dims = target_dims;
2643                        }
2644                        scene_tex_ptr = *blur_scene_texture_handle as *mut c_void;
2645                        half_tex_ptr = *blur_half_texture_handle as *mut c_void;
2646                        full_tex_ptr = *blur_full_texture_handle as *mut c_void;
2647                        use_blur_offscreen = !scene_tex_ptr.is_null()
2648                            && !half_tex_ptr.is_null()
2649                            && !full_tex_ptr.is_null();
2650                    }
2651                    let primary_target: *mut c_void = if use_blur_offscreen {
2652                        scene_tex_ptr
2653                    } else {
2654                        drawable_tex
2655                    };
2656                    if let Some(scene_pass) = frame_scene_pass.as_ref() {
2657                        let mut scene_buf_handles: [usize; 6] = [
2658                            *scene_3d_vertex_buffer_handle,
2659                            *scene_3d_vertex_capacity,
2660                            scene_3d_instance_buffer_handles[slot_idx],
2661                            scene_3d_instance_capacities[slot_idx],
2662                            scene_boat_buffer_handles[slot_idx],
2663                            scene_boat_capacities[slot_idx],
2664                        ];
2665                        let maybe_scene_tex: Option<*mut c_void> = metal_encode_gpu_scene_pass(
2666                            [cmd_buf, pass_cls, device],
2667                            scene_pipelines,
2668                            (
2669                                scene_color_texture_handle,
2670                                scene_depth_texture_handle,
2671                                &mut scene_wake_texture_handles[slot_idx],
2672                                scene_texture_dims,
2673                            ),
2674                            (&mut scene_buf_handles, scene_3d_vertex_revision),
2675                            (pbr_scene_resources, slot_idx, tex_rgba8),
2676                            scene_pass,
2677                        );
2678                        *scene_wake_texture_handle = scene_wake_texture_handles[slot_idx];
2679                        *scene_3d_vertex_buffer_handle = scene_buf_handles[0];
2680                        *scene_3d_vertex_capacity = scene_buf_handles[1];
2681                        scene_3d_instance_buffer_handles[slot_idx] = scene_buf_handles[2];
2682                        scene_3d_instance_capacities[slot_idx] = scene_buf_handles[3];
2683                        scene_boat_buffer_handles[slot_idx] = scene_buf_handles[4];
2684                        scene_boat_capacities[slot_idx] = scene_buf_handles[5];
2685                        *scene_3d_instance_buffer_handle = scene_buf_handles[2];
2686                        *scene_3d_instance_capacity = scene_buf_handles[3];
2687                        *scene_boat_buffer_handle = scene_buf_handles[4];
2688                        *scene_boat_capacity = scene_buf_handles[5];
2689                        if let Some(rendered_scene_tex) = maybe_scene_tex {
2690                            tex_ext = rendered_scene_tex;
2691                        }
2692                    }
2693                    let mut active_encoder: *mut c_void = metal_begin_ui_render_encoder(
2694                        cmd_buf,
2695                        pass_cls,
2696                        primary_target,
2697                        (MTL_LOAD_ACTION_CLEAR, mtl_clear),
2698                        (draw_w, draw_h),
2699                        (pipeline, buf_handle as *mut c_void),
2700                        [tex_r8, tex_rgba8, tex_img, tex_ext],
2701                    );
2702                    let mut base_instance: usize = 0;
2703                    for batch in batches.iter() {
2704                        let count: usize = batch
2705                            .get_primitives()
2706                            .len()
2707                            .max(batch.get_instances().len());
2708                        if count == 0 || buf_handle == 0 {
2709                            continue;
2710                        }
2711                        let is_blur_batch: bool = use_blur_offscreen
2712                            && batch.get_primitives().iter().any(
2713                                |prim_item: &GpuPrimitiveInstance| {
2714                                    prim_item.prim_kind() == PrimKind::BackdropBlur
2715                                },
2716                            );
2717                        if is_blur_batch {
2718                            if !active_encoder.is_null() {
2719                                mtl_send_void0(active_encoder, sel.end_encoding as *mut c_void);
2720                            }
2721                            let blur_offset: f32 = 2.5;
2722                            let down_uniform: [f32; 4] = [
2723                                1.0 / (draw_w.max(1) as f32),
2724                                1.0 / (draw_h.max(1) as f32),
2725                                blur_offset,
2726                                0.0,
2727                            ];
2728                            let up_uniform: [f32; 4] = [
2729                                1.0 / (half_w_u32 as f32),
2730                                1.0 / (half_h_u32 as f32),
2731                                blur_offset,
2732                                1.0,
2733                            ];
2734                            let _: bool = metal_encode_fullscreen_blur_pass(
2735                                cmd_buf,
2736                                pass_cls,
2737                                half_tex_ptr,
2738                                blur_down_pso,
2739                                scene_tex_ptr,
2740                                &down_uniform,
2741                            );
2742                            let _: bool = metal_encode_fullscreen_blur_pass(
2743                                cmd_buf,
2744                                pass_cls,
2745                                full_tex_ptr,
2746                                blur_up_pso,
2747                                half_tex_ptr,
2748                                &up_uniform,
2749                            );
2750                            active_encoder = metal_begin_ui_render_encoder(
2751                                cmd_buf,
2752                                pass_cls,
2753                                scene_tex_ptr,
2754                                (MTL_LOAD_ACTION_LOAD, mtl_clear),
2755                                (draw_w, draw_h),
2756                                (pipeline, buf_handle as *mut c_void),
2757                                [tex_r8, tex_rgba8, tex_img, full_tex_ptr],
2758                            );
2759                        }
2760                        if !active_encoder.is_null() {
2761                            metal_encode_ui_batch_draw(
2762                                active_encoder,
2763                                (draw_w, draw_h),
2764                                batch,
2765                                count,
2766                                base_instance,
2767                            );
2768                            if is_blur_batch && !tex_ext.is_null() {
2769                                unsafe {
2770                                    let send_ftex: unsafe extern "C" fn(
2771                                        *mut c_void,
2772                                        *mut c_void,
2773                                        *mut c_void,
2774                                        usize,
2775                                    ) = transmute(objc_msgSend as *const c_void);
2776                                    send_ftex(
2777                                        active_encoder,
2778                                        sel.set_fragment_texture as *mut c_void,
2779                                        tex_ext,
2780                                        3,
2781                                    );
2782                                }
2783                            }
2784                        }
2785                        base_instance = base_instance.saturating_add(count);
2786                    }
2787                    if !active_encoder.is_null() {
2788                        mtl_send_void0(active_encoder, sel.end_encoding as *mut c_void);
2789                    }
2790                    if use_blur_offscreen {
2791                        let copy_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
2792                            rect: [0.0, 0.0, draw_w as f32, draw_h as f32],
2793                            clip_rect: [0.0, 0.0, draw_w as f32, draw_h as f32],
2794                            color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
2795                            aux_color_rgba: 0,
2796                            uv_rect: [0, 0, u16::MAX, u16::MAX],
2797                            radii_border: [0; 4],
2798                            kind_flags: GpuPrimitiveInstance::pack_kind_flags(
2799                                PrimKind::ExternalGpuSurface,
2800                                0,
2801                                0,
2802                                0,
2803                            ),
2804                            extra_param: 0,
2805                        };
2806                        let copy_enc: *mut c_void = metal_begin_ui_render_encoder(
2807                            cmd_buf,
2808                            pass_cls,
2809                            drawable_tex,
2810                            (MTL_LOAD_ACTION_CLEAR, mtl_clear),
2811                            (draw_w, draw_h),
2812                            (pipeline, null_mut()),
2813                            [tex_r8, tex_rgba8, tex_img, scene_tex_ptr],
2814                        );
2815                        if !copy_enc.is_null() {
2816                            let uniform: GpuLayerUniform =
2817                                GpuLayerUniform::new(draw_w as f32, draw_h as f32, [0.0, 0.0]);
2818                            unsafe {
2819                                let send_vbytes: unsafe extern "C" fn(
2820                                    *mut c_void,
2821                                    *mut c_void,
2822                                    *const c_void,
2823                                    usize,
2824                                    usize,
2825                                ) = transmute(objc_msgSend as *const c_void);
2826                                let send_scissor: unsafe extern "C" fn(
2827                                    *mut c_void,
2828                                    *mut c_void,
2829                                    MtlScissorRect,
2830                                ) = transmute(objc_msgSend as *const c_void);
2831                                let send_draw: unsafe extern "C" fn(
2832                                    *mut c_void,
2833                                    *mut c_void,
2834                                    usize,
2835                                    usize,
2836                                    usize,
2837                                    usize,
2838                                    usize,
2839                                ) = transmute(objc_msgSend as *const c_void);
2840                                send_vbytes(
2841                                    copy_enc,
2842                                    sel.set_vertex_bytes as *mut c_void,
2843                                    (&copy_prim as *const GpuPrimitiveInstance).cast::<c_void>(),
2844                                    size_of::<GpuPrimitiveInstance>(),
2845                                    0,
2846                                );
2847                                send_vbytes(
2848                                    copy_enc,
2849                                    sel.set_vertex_bytes as *mut c_void,
2850                                    (&uniform as *const GpuLayerUniform).cast::<c_void>(),
2851                                    size_of::<GpuLayerUniform>(),
2852                                    1,
2853                                );
2854                                send_scissor(
2855                                    copy_enc,
2856                                    sel.set_scissor_rect as *mut c_void,
2857                                    MtlScissorRect {
2858                                        x: 0,
2859                                        y: 0,
2860                                        width: draw_w,
2861                                        height: draw_h,
2862                                    },
2863                                );
2864                                send_draw(
2865                                    copy_enc,
2866                                    sel.draw_primitives_instanced as *mut c_void,
2867                                    MTL_PRIMITIVE_TYPE_TRIANGLE,
2868                                    0,
2869                                    6,
2870                                    1,
2871                                    0,
2872                                );
2873                            }
2874                            mtl_send_void0(copy_enc, sel.end_encoding as *mut c_void);
2875                        }
2876                    }
2877                    #[cfg(not(target_abi = "sim"))]
2878                    {
2879                        let sel_pres: *mut c_void = sel.add_presented_handler as *mut c_void;
2880                        if mtl_responds_to_sel(drawable, sel_pres) {
2881                            mtl_send_void_ptr1(drawable, sel_pres, metal_presented_block_ptr());
2882                        }
2883                    }
2884                    mtl_send_void_ptr1(cmd_buf, sel.present_drawable as *mut c_void, drawable);
2885                }
2886            }
2887        }
2888        let retained_cmd: usize = mtl_retain_handle(cmd_buf as usize);
2889        slot.set_in_flight_cmd_buffer(retained_cmd);
2890        let _: u64 = SUBMITTED_GPU_FENCE.fetch_add(1, Ordering::AcqRel);
2891        mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
2892    }
2893    *ring_cursor = (slot_idx + 1) % GPU_DRIVER_RING_SLOTS;
2894    unsafe { objc_autoreleasePoolPop(pool) };
2895    total_instances
2896}
2897
2898/// Executes Dual-Kawase `blur_down` and `blur_up` ping-pong passes on Apple Metal into persistent offscreen textures.
2899///
2900/// # Arguments
2901///
2902/// - `&mut NativeGpuDriver` - Mutable Apple Metal GPU driver retaining both `blur_pipeline` and `blur_up_pipeline`.
2903/// - `u32` - Physical surface width in pixels.
2904/// - `u32` - Physical surface height in pixels.
2905/// - `&[GpuBackdropBlurPass]` - Active Dual-Kawase blur regions.
2906///
2907/// # Returns
2908///
2909/// - `usize` - Number of Dual-Kawase blur regions executed on hardware Metal (`0` when unsupported).
2910#[cfg(any(target_os = "macos", target_os = "ios"))]
2911fn metal_execute_dual_kawase_blur_passes(
2912    driver: &mut NativeGpuDriver,
2913    width: u32,
2914    height: u32,
2915    blur_passes: &[GpuBackdropBlurPass],
2916) -> usize {
2917    let device_handle: usize = driver.get_device_handle();
2918    let queue_handle: usize = driver.get_queue_handle();
2919    let blur_down_pso: usize = driver.get_blur_pipeline_handle();
2920    let blur_up_pso: usize = driver.get_blur_up_pipeline_handle();
2921    if device_handle == 0
2922        || queue_handle == 0
2923        || blur_down_pso == 0
2924        || blur_up_pso == 0
2925        || blur_passes.is_empty()
2926    {
2927        return 0;
2928    }
2929    let full_w: u32 = width.max(2);
2930    let full_h: u32 = height.max(2);
2931    let half_w: u32 = (full_w / 2).max(1);
2932    let half_h: u32 = (full_h / 2).max(1);
2933    let src_tex_handle: usize = if driver.get_external_texture_handle() != 0 {
2934        driver.get_external_texture_handle()
2935    } else if driver.get_image_texture_handle() != 0 {
2936        driver.get_image_texture_handle()
2937    } else {
2938        driver.get_glyph_rgba8_texture_handle()
2939    };
2940    if src_tex_handle == 0 {
2941        return 0;
2942    }
2943    let NativeGpuDriver {
2944        blur_half_texture_handle,
2945        blur_full_texture_handle,
2946        blur_texture_dims,
2947        ..
2948    } = driver;
2949    if *blur_half_texture_handle == 0
2950        || *blur_full_texture_handle == 0
2951        || *blur_texture_dims != (full_w, full_h)
2952    {
2953        release_native_gpu_object(*blur_half_texture_handle);
2954        release_native_gpu_object(*blur_full_texture_handle);
2955        let unified_mem: bool = cfg!(target_arch = "aarch64");
2956        *blur_half_texture_handle =
2957            metal_create_offscreen_render_texture(device_handle, half_w, half_h, unified_mem);
2958        *blur_full_texture_handle =
2959            metal_create_offscreen_render_texture(device_handle, full_w, full_h, unified_mem);
2960        *blur_texture_dims = (full_w, full_h);
2961    }
2962    let half_tex: *mut c_void = *blur_half_texture_handle as *mut c_void;
2963    let full_tex: *mut c_void = *blur_full_texture_handle as *mut c_void;
2964    if half_tex.is_null() || full_tex.is_null() {
2965        return 0;
2966    }
2967    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2968    let sel: &MetalSelectors = cached_metal_selectors();
2969    let queue: *mut c_void = queue_handle as *mut c_void;
2970    let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
2971    if cmd_buf.is_null() {
2972        unsafe { objc_autoreleasePoolPop(pool) };
2973        return 0;
2974    }
2975    let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
2976    if mtl_responds_to_sel(cmd_buf, sel_completed) {
2977        mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
2978    }
2979    let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
2980    let mut executed: usize = 0;
2981    let max_regions: usize = blur_passes.len().min(RENDER_GRAPH_MAX_BLUR_PASSES);
2982    for pass in blur_passes.iter().take(max_regions) {
2983        let blur_offset: f32 = (pass.get_blur_radius() * 0.25).clamp(0.5, 8.0);
2984        let down_uniform: [f32; 4] = [
2985            1.0 / (full_w as f32),
2986            1.0 / (full_h as f32),
2987            blur_offset,
2988            0.0,
2989        ];
2990        let up_uniform: [f32; 4] = [
2991            1.0 / (half_w as f32),
2992            1.0 / (half_h as f32),
2993            blur_offset,
2994            1.0,
2995        ];
2996        let down_ok: bool = metal_encode_fullscreen_blur_pass(
2997            cmd_buf,
2998            pass_cls,
2999            half_tex,
3000            blur_down_pso as *mut c_void,
3001            src_tex_handle as *mut c_void,
3002            &down_uniform,
3003        );
3004        let up_ok: bool = if down_ok {
3005            metal_encode_fullscreen_blur_pass(
3006                cmd_buf,
3007                pass_cls,
3008                full_tex,
3009                blur_up_pso as *mut c_void,
3010                half_tex,
3011                &up_uniform,
3012            )
3013        } else {
3014            false
3015        };
3016        if down_ok && up_ok {
3017            executed = executed.saturating_add(1);
3018        }
3019    }
3020    let _: u64 = SUBMITTED_GPU_FENCE.fetch_add(1, Ordering::AcqRel);
3021    mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
3022    unsafe { objc_autoreleasePoolPop(pool) };
3023    executed
3024}
3025
3026/// Encodes one fullscreen triangle Dual-Kawase blur render pass (`blur_down` or `blur_up`) into `dst_tex`.
3027///
3028/// # Arguments
3029///
3030/// - `*mut c_void` - Active `id<MTLCommandBuffer>`.
3031/// - `*mut c_void` - `MTLRenderPassDescriptor` class pointer.
3032/// - `*mut c_void` - Destination `id<MTLTexture>` render target.
3033/// - `*mut c_void` - Compiled Dual-Kawase `id<MTLRenderPipelineState>`.
3034/// - `*mut c_void` - Source `id<MTLTexture>` sampled at fragment texture index `0`.
3035/// - `&[f32; 4]` - 16-byte `BlurUniforms` payload bound at fragment buffer index `0`.
3036///
3037/// # Returns
3038///
3039/// - `bool` - `true` when the render pass encoded cleanly.
3040#[cfg(any(target_os = "macos", target_os = "ios"))]
3041fn metal_encode_fullscreen_blur_pass(
3042    cmd_buf: *mut c_void,
3043    pass_cls: *mut c_void,
3044    dst_tex: *mut c_void,
3045    pso: *mut c_void,
3046    src_tex: *mut c_void,
3047    uniform: &[f32; 4],
3048) -> bool {
3049    let sel: &MetalSelectors = cached_metal_selectors();
3050    let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
3051    if pass_desc.is_null() {
3052        return false;
3053    }
3054    let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
3055    let att0: *mut c_void = unsafe {
3056        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
3057            transmute(objc_msgSend as *const c_void);
3058        send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
3059    };
3060    if att0.is_null() {
3061        return false;
3062    }
3063    mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, dst_tex);
3064    mtl_send_void_usize(
3065        att0,
3066        sel.set_load_action as *mut c_void,
3067        MTL_LOAD_ACTION_CLEAR,
3068    );
3069    unsafe {
3070        let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
3071            transmute(objc_msgSend as *const c_void);
3072        send_clear(
3073            att0,
3074            sel.set_clear_color as *mut c_void,
3075            MtlClearColor {
3076                red: 0.0,
3077                green: 0.0,
3078                blue: 0.0,
3079                alpha: 1.0,
3080            },
3081        );
3082    }
3083    mtl_send_void_usize(
3084        att0,
3085        sel.set_store_action as *mut c_void,
3086        MTL_STORE_ACTION_STORE,
3087    );
3088    let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
3089    if encoder.is_null() {
3090        return false;
3091    }
3092    mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, pso);
3093    unsafe {
3094        let send_fbytes: unsafe extern "C" fn(
3095            *mut c_void,
3096            *mut c_void,
3097            *const c_void,
3098            usize,
3099            usize,
3100        ) = transmute(objc_msgSend as *const c_void);
3101        let send_ftex: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, usize) =
3102            transmute(objc_msgSend as *const c_void);
3103        let send_draw: unsafe extern "C" fn(
3104            *mut c_void,
3105            *mut c_void,
3106            usize,
3107            usize,
3108            usize,
3109            usize,
3110            usize,
3111        ) = transmute(objc_msgSend as *const c_void);
3112        send_fbytes(
3113            encoder,
3114            sel.set_fragment_bytes as *mut c_void,
3115            uniform.as_ptr().cast::<c_void>(),
3116            size_of::<[f32; 4]>(),
3117            0,
3118        );
3119        send_ftex(encoder, sel.set_fragment_texture as *mut c_void, src_tex, 0);
3120        send_draw(
3121            encoder,
3122            sel.draw_primitives_instanced as *mut c_void,
3123            MTL_PRIMITIVE_TYPE_TRIANGLE,
3124            0,
3125            3,
3126            1,
3127            0,
3128        );
3129    }
3130    mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
3131    true
3132}
3133
3134/// Encodes an inline offscreen hardware GPU `DirectGpuScenePass` (`OceanFluid`, `World3d`, or `PbrScene`) before UI compositing.
3135///
3136/// # Arguments
3137///
3138/// - `[*mut c_void; 3]` - Active Metal handles `[cmd_buf, pass_cls, device]`.
3139/// - `[*mut c_void; 5]` - Pipeline handles `[ocean_pso, boat_pso, sky_pso, mesh_pso, depth_stencil]`.
3140/// - `(&mut usize, &mut usize, &mut usize, &mut (u32, u32))` - Offscreen color, depth, wake textures, and dimensions.
3141/// - `(&mut [usize; 6], &mut u64)` - Legacy `World3d`/boat vertex and instance buffers plus mesh revision.
3142/// - `(&mut MetalPbrSceneResources, usize, *mut c_void)` - Resident `PbrScene` pipelines/buffers/mip pool, ring slot index, and fallback 1x1 RGBA8 texture.
3143/// - `&DirectGpuScenePass` - Hardware scene pass payload to encode.
3144///
3145/// # Returns
3146///
3147/// - `Option<*mut c_void>` - Offscreen rendered color `MTLTexture` bound into UI compositor slot `3`, or `None` on setup failure.
3148#[cfg(any(target_os = "macos", target_os = "ios"))]
3149fn metal_encode_gpu_scene_pass(
3150    mtl_handles: [*mut c_void; 3],
3151    pipelines: [*mut c_void; 5],
3152    textures: (&mut usize, &mut usize, &mut usize, &mut (u32, u32)),
3153    buffers: (&mut [usize; 6], &mut u64),
3154    pbr_ctx: (&mut MetalPbrSceneResources, usize, *mut c_void),
3155    scene_pass: &DirectGpuScenePass,
3156) -> Option<*mut c_void> {
3157    let [cmd_buf, pass_cls, device]: [*mut c_void; 3] = mtl_handles;
3158    let (color_tex_h, depth_tex_h, wake_tex_h, tex_dims): (
3159        &mut usize,
3160        &mut usize,
3161        &mut usize,
3162        &mut (u32, u32),
3163    ) = textures;
3164    let (buf_arr, v3d_rev): (&mut [usize; 6], &mut u64) = buffers;
3165    let [v3d_buf_h, v3d_cap, i3d_buf_h, i3d_cap, boat_buf_h, boat_cap]: &mut [usize; 6] = buf_arr;
3166    let sel: &MetalSelectors = cached_metal_selectors();
3167    let (req_w, req_h, needs_depth): (u32, u32, bool) = match scene_pass {
3168        DirectGpuScenePass::OceanFluid(ocean) => (
3169            ocean.get_target_width().clamp(64, 16384),
3170            ocean.get_target_height().clamp(64, 16384),
3171            true,
3172        ),
3173        DirectGpuScenePass::World3d(world) => (
3174            world.get_target_width().clamp(64, 16384),
3175            world.get_target_height().clamp(64, 16384),
3176            true,
3177        ),
3178        DirectGpuScenePass::PbrScene(pbr) => (
3179            pbr.get_target_width().clamp(64, 16384),
3180            pbr.get_target_height().clamp(64, 16384),
3181            true,
3182        ),
3183    };
3184    if *color_tex_h == 0 || *tex_dims != (req_w, req_h) || (needs_depth && *depth_tex_h == 0) {
3185        release_native_gpu_object(*color_tex_h);
3186        release_native_gpu_object(*depth_tex_h);
3187        let unified_mem: bool = cfg!(target_arch = "aarch64");
3188        *color_tex_h =
3189            metal_create_offscreen_render_texture(device as usize, req_w, req_h, unified_mem);
3190        *depth_tex_h = if needs_depth {
3191            metal_create_depth_texture(device, req_w, req_h)
3192        } else {
3193            0
3194        };
3195        *tex_dims = (req_w, req_h);
3196    }
3197    let color_tex: *mut c_void = *color_tex_h as *mut c_void;
3198    if color_tex.is_null() {
3199        return None;
3200    }
3201    let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
3202    if pass_desc.is_null() {
3203        return None;
3204    }
3205    let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
3206    let att0: *mut c_void = unsafe {
3207        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
3208            transmute(objc_msgSend as *const c_void);
3209        send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
3210    };
3211    if att0.is_null() {
3212        return None;
3213    }
3214    mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, color_tex);
3215    mtl_send_void_usize(
3216        att0,
3217        sel.set_load_action as *mut c_void,
3218        MTL_LOAD_ACTION_CLEAR,
3219    );
3220    unsafe {
3221        let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
3222            transmute(objc_msgSend as *const c_void);
3223        send_clear(
3224            att0,
3225            sel.set_clear_color as *mut c_void,
3226            MtlClearColor {
3227                red: 0.0,
3228                green: 0.0,
3229                blue: 0.0,
3230                alpha: 1.0,
3231            },
3232        );
3233    }
3234    mtl_send_void_usize(
3235        att0,
3236        sel.set_store_action as *mut c_void,
3237        MTL_STORE_ACTION_STORE,
3238    );
3239    if needs_depth {
3240        let depth_tex: *mut c_void = *depth_tex_h as *mut c_void;
3241        if depth_tex.is_null() {
3242            return None;
3243        }
3244        let depth_att: *mut c_void = mtl_send_ptr0(pass_desc, sel.depth_attachment as *mut c_void);
3245        if depth_att.is_null() {
3246            return None;
3247        }
3248        mtl_send_void_ptr1(depth_att, sel.set_texture as *mut c_void, depth_tex);
3249        mtl_send_void_usize(
3250            depth_att,
3251            sel.set_load_action as *mut c_void,
3252            MTL_LOAD_ACTION_CLEAR,
3253        );
3254        mtl_send_void_usize(
3255            depth_att,
3256            sel.set_store_action as *mut c_void,
3257            MTL_STORE_ACTION_DONT_CARE,
3258        );
3259        unsafe {
3260            let send_clear_d: unsafe extern "C" fn(*mut c_void, *mut c_void, f64) =
3261                transmute(objc_msgSend as *const c_void);
3262            send_clear_d(depth_att, sel.set_clear_depth as *mut c_void, 1.0);
3263        }
3264    }
3265    let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
3266    if encoder.is_null() {
3267        return None;
3268    }
3269    let viewport: MtlViewport = MtlViewport {
3270        origin_x: 0.0,
3271        origin_y: 0.0,
3272        width: f64::from(req_w),
3273        height: f64::from(req_h),
3274        znear: 0.0,
3275        zfar: 1.0,
3276    };
3277    unsafe {
3278        let send_vp: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlViewport) =
3279            transmute(objc_msgSend as *const c_void);
3280        send_vp(encoder, sel.set_viewport as *mut c_void, viewport);
3281    }
3282    match scene_pass {
3283        DirectGpuScenePass::OceanFluid(ocean) => {
3284            let ocean_pso: *mut c_void = pipelines[0];
3285            let boat_pso: *mut c_void = pipelines[1];
3286            if !ocean_pso.is_null() {
3287                let wake_w: u32 = ocean.get_wake_width().max(1);
3288                let wake_h: u32 = ocean.get_wake_height().max(1);
3289                if (*wake_tex_h == 0 || ocean.get_has_active_wake())
3290                    && ocean.get_wake_rgba8().len() >= (wake_w as usize) * (wake_h as usize) * 4
3291                {
3292                    let _: bool = metal_upload_texture_dirty_rect(
3293                        device as usize,
3294                        wake_tex_h,
3295                        GpuAtlasPixelFormat::Rgba8Unorm,
3296                        (wake_w, wake_h),
3297                        (0, 0, wake_w, wake_h),
3298                        ocean.get_wake_rgba8().as_slice(),
3299                        (wake_w as usize) * 4,
3300                    );
3301                }
3302                let sun: [f32; 3] = ocean.get_sun_dir();
3303                let boat_uv: [f32; 2] = ocean.get_boat_uv();
3304                let wf: f32 = req_w as f32;
3305                let hf: f32 = req_h as f32;
3306                let ocean_uniform: [f32; 16] = [
3307                    ocean.get_sim_time(),
3308                    ocean.get_agitation(),
3309                    ocean.get_horizon_v(),
3310                    ocean.get_aspect(),
3311                    ocean.get_roll_cos(),
3312                    ocean.get_roll_sin(),
3313                    boat_uv[0],
3314                    boat_uv[1],
3315                    sun[0],
3316                    sun[1],
3317                    sun[2],
3318                    if ocean.get_has_active_wake() && *wake_tex_h != 0 {
3319                        1.0
3320                    } else {
3321                        0.0
3322                    },
3323                    wf,
3324                    hf,
3325                    1.0 / wf.max(1.0),
3326                    1.0 / hf.max(1.0),
3327                ];
3328                mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, ocean_pso);
3329                unsafe {
3330                    let send_fbytes: unsafe extern "C" fn(
3331                        *mut c_void,
3332                        *mut c_void,
3333                        *const c_void,
3334                        usize,
3335                        usize,
3336                    ) = transmute(objc_msgSend as *const c_void);
3337                    let send_ftex: unsafe extern "C" fn(
3338                        *mut c_void,
3339                        *mut c_void,
3340                        *mut c_void,
3341                        usize,
3342                    ) = transmute(objc_msgSend as *const c_void);
3343                    let send_draw: unsafe extern "C" fn(
3344                        *mut c_void,
3345                        *mut c_void,
3346                        usize,
3347                        usize,
3348                        usize,
3349                        usize,
3350                        usize,
3351                    ) = transmute(objc_msgSend as *const c_void);
3352                    send_fbytes(
3353                        encoder,
3354                        sel.set_fragment_bytes as *mut c_void,
3355                        ocean_uniform.as_ptr().cast::<c_void>(),
3356                        size_of::<[f32; 16]>(),
3357                        0,
3358                    );
3359                    if *wake_tex_h != 0 {
3360                        send_ftex(
3361                            encoder,
3362                            sel.set_fragment_texture as *mut c_void,
3363                            *wake_tex_h as *mut c_void,
3364                            0,
3365                        );
3366                    }
3367                    send_draw(
3368                        encoder,
3369                        sel.draw_primitives_instanced as *mut c_void,
3370                        MTL_PRIMITIVE_TYPE_TRIANGLE,
3371                        0,
3372                        3,
3373                        1,
3374                        0,
3375                    );
3376                }
3377            }
3378            let boat_verts: &[GpuOceanBoatVertex] = ocean.get_boat_vertices().as_slice();
3379            let depth_state: *mut c_void = pipelines[4];
3380            if !boat_pso.is_null() && !boat_verts.is_empty() {
3381                let boat_bytes: &[u8] = unsafe {
3382                    from_raw_parts(boat_verts.as_ptr().cast::<u8>(), size_of_val(boat_verts))
3383                };
3384                let boat_buf: *mut c_void =
3385                    metal_ensure_and_upload_shared_buffer(device, boat_buf_h, boat_cap, boat_bytes);
3386                if !boat_buf.is_null() {
3387                    mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, boat_pso);
3388                    if !depth_state.is_null() {
3389                        mtl_send_void_ptr1(
3390                            encoder,
3391                            sel.set_depth_stencil_state as *mut c_void,
3392                            depth_state,
3393                        );
3394                    }
3395                    unsafe {
3396                        let send_vbuf: unsafe extern "C" fn(
3397                            *mut c_void,
3398                            *mut c_void,
3399                            *mut c_void,
3400                            usize,
3401                            usize,
3402                        ) = transmute(objc_msgSend as *const c_void);
3403                        let send_draw: unsafe extern "C" fn(
3404                            *mut c_void,
3405                            *mut c_void,
3406                            usize,
3407                            usize,
3408                            usize,
3409                            usize,
3410                            usize,
3411                        ) = transmute(objc_msgSend as *const c_void);
3412                        send_vbuf(
3413                            encoder,
3414                            sel.set_vertex_buffer as *mut c_void,
3415                            boat_buf,
3416                            0,
3417                            0,
3418                        );
3419                        send_draw(
3420                            encoder,
3421                            sel.draw_primitives_instanced as *mut c_void,
3422                            MTL_PRIMITIVE_TYPE_TRIANGLE,
3423                            0,
3424                            boat_verts.len(),
3425                            1,
3426                            0,
3427                        );
3428                    }
3429                }
3430            }
3431        }
3432        DirectGpuScenePass::World3d(world) => {
3433            let sky_pso: *mut c_void = pipelines[2];
3434            let mesh_pso: *mut c_void = pipelines[3];
3435            let depth_state: *mut c_void = pipelines[4];
3436            let mut uniform: [f32; 36] = [0.0; 36];
3437            uniform[0..16].copy_from_slice(&world.get_view_proj());
3438            uniform[16..20].copy_from_slice(&world.get_camera_pos());
3439            uniform[20..24].copy_from_slice(&world.get_sun_dir_fog());
3440            uniform[24..28].copy_from_slice(&world.get_sun_color_ambient());
3441            uniform[28..32].copy_from_slice(&world.get_sky_horizon_tod());
3442            uniform[32..36].copy_from_slice(&world.get_sky_zenith_aspect());
3443            if !sky_pso.is_null() {
3444                mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, sky_pso);
3445                unsafe {
3446                    let send_fbytes: unsafe extern "C" fn(
3447                        *mut c_void,
3448                        *mut c_void,
3449                        *const c_void,
3450                        usize,
3451                        usize,
3452                    ) = transmute(objc_msgSend as *const c_void);
3453                    let send_draw: unsafe extern "C" fn(
3454                        *mut c_void,
3455                        *mut c_void,
3456                        usize,
3457                        usize,
3458                        usize,
3459                        usize,
3460                        usize,
3461                    ) = transmute(objc_msgSend as *const c_void);
3462                    send_fbytes(
3463                        encoder,
3464                        sel.set_fragment_bytes as *mut c_void,
3465                        uniform.as_ptr().cast::<c_void>(),
3466                        size_of::<[f32; 36]>(),
3467                        0,
3468                    );
3469                    send_draw(
3470                        encoder,
3471                        sel.draw_primitives_instanced as *mut c_void,
3472                        MTL_PRIMITIVE_TYPE_TRIANGLE,
3473                        0,
3474                        3,
3475                        1,
3476                        0,
3477                    );
3478                }
3479            }
3480            let mesh_verts: &[GpuWorld3dVertex] = world.get_mesh_buffer().get_vertices().as_slice();
3481            let mesh_insts: &[GpuWorld3dInstance] = world.get_instances().as_slice();
3482            if !mesh_pso.is_null() && !mesh_verts.is_empty() && !mesh_insts.is_empty() {
3483                let mesh_rev: u64 = world.get_mesh_buffer().get_revision();
3484                let vbuf: *mut c_void = if *v3d_buf_h == 0 || *v3d_rev != mesh_rev {
3485                    let vert_bytes: &[u8] = unsafe {
3486                        from_raw_parts(mesh_verts.as_ptr().cast::<u8>(), size_of_val(mesh_verts))
3487                    };
3488                    let uploaded: *mut c_void = metal_ensure_and_upload_shared_buffer(
3489                        device, v3d_buf_h, v3d_cap, vert_bytes,
3490                    );
3491                    if !uploaded.is_null() {
3492                        *v3d_rev = mesh_rev;
3493                    }
3494                    uploaded
3495                } else {
3496                    *v3d_buf_h as *mut c_void
3497                };
3498                let inst_bytes: &[u8] = unsafe {
3499                    from_raw_parts(mesh_insts.as_ptr().cast::<u8>(), size_of_val(mesh_insts))
3500                };
3501                let ibuf: *mut c_void =
3502                    metal_ensure_and_upload_shared_buffer(device, i3d_buf_h, i3d_cap, inst_bytes);
3503                if !vbuf.is_null() && !ibuf.is_null() {
3504                    mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, mesh_pso);
3505                    if !depth_state.is_null() {
3506                        mtl_send_void_ptr1(
3507                            encoder,
3508                            sel.set_depth_stencil_state as *mut c_void,
3509                            depth_state,
3510                        );
3511                    }
3512                    unsafe {
3513                        let send_vbytes: unsafe extern "C" fn(
3514                            *mut c_void,
3515                            *mut c_void,
3516                            *const c_void,
3517                            usize,
3518                            usize,
3519                        ) = transmute(objc_msgSend as *const c_void);
3520                        let send_fbytes: unsafe extern "C" fn(
3521                            *mut c_void,
3522                            *mut c_void,
3523                            *const c_void,
3524                            usize,
3525                            usize,
3526                        ) = transmute(objc_msgSend as *const c_void);
3527                        let send_vbuf: unsafe extern "C" fn(
3528                            *mut c_void,
3529                            *mut c_void,
3530                            *mut c_void,
3531                            usize,
3532                            usize,
3533                        ) = transmute(objc_msgSend as *const c_void);
3534                        let send_draw: unsafe extern "C" fn(
3535                            *mut c_void,
3536                            *mut c_void,
3537                            usize,
3538                            usize,
3539                            usize,
3540                            usize,
3541                            usize,
3542                        ) = transmute(objc_msgSend as *const c_void);
3543                        send_vbytes(
3544                            encoder,
3545                            sel.set_vertex_bytes as *mut c_void,
3546                            uniform.as_ptr().cast::<c_void>(),
3547                            size_of::<[f32; 36]>(),
3548                            0,
3549                        );
3550                        send_fbytes(
3551                            encoder,
3552                            sel.set_fragment_bytes as *mut c_void,
3553                            uniform.as_ptr().cast::<c_void>(),
3554                            size_of::<[f32; 36]>(),
3555                            0,
3556                        );
3557                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, vbuf, 0, 1);
3558                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, ibuf, 0, 2);
3559                        for batch in world.get_draw_batches().iter() {
3560                            if batch.get_vertex_count() == 0 || batch.get_instance_count() == 0 {
3561                                continue;
3562                            }
3563                            send_draw(
3564                                encoder,
3565                                sel.draw_primitives_instanced as *mut c_void,
3566                                MTL_PRIMITIVE_TYPE_TRIANGLE,
3567                                batch.get_vertex_start() as usize,
3568                                batch.get_vertex_count() as usize,
3569                                batch.get_instance_count() as usize,
3570                                batch.get_instance_start() as usize,
3571                            );
3572                        }
3573                    }
3574                }
3575            }
3576        }
3577        DirectGpuScenePass::PbrScene(pbr) => {
3578            let (pbr_res, ring_slot, fallback_tex): (
3579                &mut MetalPbrSceneResources,
3580                usize,
3581                *mut c_void,
3582            ) = pbr_ctx;
3583            let ring_idx: usize = ring_slot % GPU_DRIVER_RING_SLOTS;
3584            metal_apply_pbr_mip_uploads(device, pbr_res, pbr.get_texture_uploads().as_slice());
3585            let sky_pso: *mut c_void = pbr_res.pipelines[0] as *mut c_void;
3586            let opaque_pso: *mut c_void = pbr_res.pipelines[1] as *mut c_void;
3587            let skinned_pso: *mut c_void = pbr_res.pipelines[2] as *mut c_void;
3588            let alpha_pso: *mut c_void = pbr_res.pipelines[3] as *mut c_void;
3589            let depth_write_state: *mut c_void = pipelines[4];
3590            let depth_ro_state: *mut c_void = pbr_res.pipelines[4] as *mut c_void;
3591            let base_uniform: PbrSceneUniformBlock =
3592                build_pbr_scene_uniform_block(pbr, 0, 0, [0, 0, 0, 0]);
3593            if !sky_pso.is_null() {
3594                mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, sky_pso);
3595                if !depth_ro_state.is_null() {
3596                    mtl_send_void_ptr1(
3597                        encoder,
3598                        sel.set_depth_stencil_state as *mut c_void,
3599                        depth_ro_state,
3600                    );
3601                }
3602                unsafe {
3603                    let send_fbytes: unsafe extern "C" fn(
3604                        *mut c_void,
3605                        *mut c_void,
3606                        *const c_void,
3607                        usize,
3608                        usize,
3609                    ) = transmute(objc_msgSend as *const c_void);
3610                    let send_draw: unsafe extern "C" fn(
3611                        *mut c_void,
3612                        *mut c_void,
3613                        usize,
3614                        usize,
3615                        usize,
3616                        usize,
3617                        usize,
3618                    ) = transmute(objc_msgSend as *const c_void);
3619                    send_fbytes(
3620                        encoder,
3621                        sel.set_fragment_bytes as *mut c_void,
3622                        (&base_uniform as *const PbrSceneUniformBlock).cast::<c_void>(),
3623                        size_of::<PbrSceneUniformBlock>(),
3624                        0,
3625                    );
3626                    send_draw(
3627                        encoder,
3628                        sel.draw_primitives_instanced as *mut c_void,
3629                        MTL_PRIMITIVE_TYPE_TRIANGLE,
3630                        0,
3631                        3,
3632                        1,
3633                        0,
3634                    );
3635                }
3636            }
3637            let mesh_buf: &GpuPbrMeshBuffer = pbr.get_mesh_buffer();
3638            let q_verts: &[QuantizedVertex3D] = mesh_buf.get_vertices().as_slice();
3639            let q_indices: &[u32] = mesh_buf.get_indices().as_slice();
3640            let insts: &[GpuPbrInstance3D] = pbr.get_instances().as_slice();
3641            let batches: &[GpuPbrDrawBatch] = pbr.get_draw_batches().as_slice();
3642            if !opaque_pso.is_null()
3643                && !q_verts.is_empty()
3644                && !q_indices.is_empty()
3645                && !insts.is_empty()
3646                && !batches.is_empty()
3647            {
3648                let rev: u64 = mesh_buf.get_revision();
3649                if pbr_res.vert_buf == 0 || pbr_res.idx_buf == 0 || pbr_res.mesh_rev != rev {
3650                    let vbytes: &[u8] = unsafe {
3651                        from_raw_parts(q_verts.as_ptr().cast::<u8>(), size_of_val(q_verts))
3652                    };
3653                    let ibytes: &[u8] = unsafe {
3654                        from_raw_parts(q_indices.as_ptr().cast::<u8>(), size_of_val(q_indices))
3655                    };
3656                    let vb_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3657                        device,
3658                        &mut pbr_res.vert_buf,
3659                        &mut pbr_res.vert_cap,
3660                        vbytes,
3661                    );
3662                    let ib_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3663                        device,
3664                        &mut pbr_res.idx_buf,
3665                        &mut pbr_res.idx_cap,
3666                        ibytes,
3667                    );
3668                    let skin_slice: &[QuantizedSkinVertex3D] =
3669                        mesh_buf.get_skin_vertices().as_slice();
3670                    if !skin_slice.is_empty() {
3671                        let sbytes: &[u8] = unsafe {
3672                            from_raw_parts(
3673                                skin_slice.as_ptr().cast::<u8>(),
3674                                size_of_val(skin_slice),
3675                            )
3676                        };
3677                        let _: *mut c_void = metal_ensure_and_upload_shared_buffer(
3678                            device,
3679                            &mut pbr_res.skin_buf,
3680                            &mut pbr_res.skin_cap,
3681                            sbytes,
3682                        );
3683                    }
3684                    let morph_slice: &[[f32; 4]] = mesh_buf.get_morph_deltas().as_slice();
3685                    if !morph_slice.is_empty() {
3686                        let mbytes: &[u8] = unsafe {
3687                            from_raw_parts(
3688                                morph_slice.as_ptr().cast::<u8>(),
3689                                size_of_val(morph_slice),
3690                            )
3691                        };
3692                        let _: *mut c_void = metal_ensure_and_upload_shared_buffer(
3693                            device,
3694                            &mut pbr_res.morph_delta_buf,
3695                            &mut pbr_res.morph_delta_cap,
3696                            mbytes,
3697                        );
3698                    }
3699                    if !vb_ptr.is_null() && !ib_ptr.is_null() {
3700                        pbr_res.mesh_rev = rev;
3701                    }
3702                }
3703                let inst_bytes: &[u8] =
3704                    unsafe { from_raw_parts(insts.as_ptr().cast::<u8>(), size_of_val(insts)) };
3705                let inst_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3706                    device,
3707                    &mut pbr_res.inst_bufs[ring_idx],
3708                    &mut pbr_res.inst_caps[ring_idx],
3709                    inst_bytes,
3710                );
3711                let default_mat: [GpuMaterialData3D; 1] = [GpuMaterialData3D::default()];
3712                let mats_slice: &[GpuMaterialData3D] = if pbr.get_materials().is_empty() {
3713                    &default_mat
3714                } else {
3715                    pbr.get_materials().as_slice()
3716                };
3717                let mat_bytes: &[u8] = unsafe {
3718                    from_raw_parts(mats_slice.as_ptr().cast::<u8>(), size_of_val(mats_slice))
3719                };
3720                let mat_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3721                    device,
3722                    &mut pbr_res.mat_bufs[ring_idx],
3723                    &mut pbr_res.mat_caps[ring_idx],
3724                    mat_bytes,
3725                );
3726                let default_bone: [[f32; 16]; 1] = [Mat4::identity().get_elements()];
3727                let bones_slice: &[[f32; 16]] = if pbr.get_bone_matrices().is_empty() {
3728                    &default_bone
3729                } else {
3730                    pbr.get_bone_matrices().as_slice()
3731                };
3732                let bone_bytes: &[u8] = unsafe {
3733                    from_raw_parts(bones_slice.as_ptr().cast::<u8>(), size_of_val(bones_slice))
3734                };
3735                let bone_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3736                    device,
3737                    &mut pbr_res.bone_bufs[ring_idx],
3738                    &mut pbr_res.bone_caps[ring_idx],
3739                    bone_bytes,
3740                );
3741                let default_mw: [f32; 4] = [0.0; 4];
3742                let mw_slice: &[f32] = if pbr.get_morph_weights().is_empty() {
3743                    &default_mw
3744                } else {
3745                    pbr.get_morph_weights().as_slice()
3746                };
3747                let mw_bytes: &[u8] = unsafe {
3748                    from_raw_parts(mw_slice.as_ptr().cast::<u8>(), size_of_val(mw_slice))
3749                };
3750                let mw_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3751                    device,
3752                    &mut pbr_res.morph_w_bufs[ring_idx],
3753                    &mut pbr_res.morph_w_caps[ring_idx],
3754                    mw_bytes,
3755                );
3756                let default_light: [GpuPackedLocalLight; 1] = [GpuPackedLocalLight::default()];
3757                let lights_slice: &[GpuPackedLocalLight] = if pbr.get_local_lights().is_empty() {
3758                    &default_light
3759                } else {
3760                    pbr.get_local_lights().as_slice()
3761                };
3762                let light_bytes: &[u8] = unsafe {
3763                    from_raw_parts(
3764                        lights_slice.as_ptr().cast::<u8>(),
3765                        size_of_val(lights_slice),
3766                    )
3767                };
3768                let light_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3769                    device,
3770                    &mut pbr_res.light_bufs[ring_idx],
3771                    &mut pbr_res.light_caps[ring_idx],
3772                    light_bytes,
3773                );
3774                let vbuf: *mut c_void = pbr_res.vert_buf as *mut c_void;
3775                let ibuf: *mut c_void = pbr_res.idx_buf as *mut c_void;
3776                let sbuf: *mut c_void = if pbr_res.skin_buf != 0 {
3777                    pbr_res.skin_buf as *mut c_void
3778                } else {
3779                    inst_ptr
3780                };
3781                let mdbuf: *mut c_void = if pbr_res.morph_delta_buf != 0 {
3782                    pbr_res.morph_delta_buf as *mut c_void
3783                } else {
3784                    bone_ptr
3785                };
3786                if !vbuf.is_null()
3787                    && !ibuf.is_null()
3788                    && !inst_ptr.is_null()
3789                    && !mat_ptr.is_null()
3790                    && !bone_ptr.is_null()
3791                    && !mw_ptr.is_null()
3792                    && !light_ptr.is_null()
3793                {
3794                    let morph_stride: u32 = if !mesh_buf.get_morph_deltas().is_empty() {
3795                        q_verts.len() as u32
3796                    } else {
3797                        0
3798                    };
3799                    let mut bound_pso: *mut c_void = null_mut();
3800                    let mut bound_depth: *mut c_void = null_mut();
3801                    unsafe {
3802                        let send_vbytes: unsafe extern "C" fn(
3803                            *mut c_void,
3804                            *mut c_void,
3805                            *const c_void,
3806                            usize,
3807                            usize,
3808                        ) = transmute(objc_msgSend as *const c_void);
3809                        let send_fbytes: unsafe extern "C" fn(
3810                            *mut c_void,
3811                            *mut c_void,
3812                            *const c_void,
3813                            usize,
3814                            usize,
3815                        ) = transmute(objc_msgSend as *const c_void);
3816                        let send_vbuf: unsafe extern "C" fn(
3817                            *mut c_void,
3818                            *mut c_void,
3819                            *mut c_void,
3820                            usize,
3821                            usize,
3822                        ) = transmute(objc_msgSend as *const c_void);
3823                        let send_fbuf: unsafe extern "C" fn(
3824                            *mut c_void,
3825                            *mut c_void,
3826                            *mut c_void,
3827                            usize,
3828                            usize,
3829                        ) = transmute(objc_msgSend as *const c_void);
3830                        let send_ftex: unsafe extern "C" fn(
3831                            *mut c_void,
3832                            *mut c_void,
3833                            *mut c_void,
3834                            usize,
3835                        ) = transmute(objc_msgSend as *const c_void);
3836                        let send_draw_idx: unsafe extern "C" fn(
3837                            *mut c_void,
3838                            *mut c_void,
3839                            usize,
3840                            usize,
3841                            usize,
3842                            *mut c_void,
3843                            usize,
3844                            usize,
3845                            isize,
3846                            usize,
3847                        ) = transmute(objc_msgSend as *const c_void);
3848                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, vbuf, 0, 1);
3849                        send_vbuf(
3850                            encoder,
3851                            sel.set_vertex_buffer as *mut c_void,
3852                            inst_ptr,
3853                            0,
3854                            2,
3855                        );
3856                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, sbuf, 0, 3);
3857                        send_vbuf(
3858                            encoder,
3859                            sel.set_vertex_buffer as *mut c_void,
3860                            bone_ptr,
3861                            0,
3862                            4,
3863                        );
3864                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, mdbuf, 0, 5);
3865                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, mw_ptr, 0, 6);
3866                        send_fbuf(
3867                            encoder,
3868                            sel.set_fragment_buffer as *mut c_void,
3869                            mat_ptr,
3870                            0,
3871                            1,
3872                        );
3873                        send_fbuf(
3874                            encoder,
3875                            sel.set_fragment_buffer as *mut c_void,
3876                            light_ptr,
3877                            0,
3878                            2,
3879                        );
3880                        for batch in batches.iter() {
3881                            if batch.get_index_count() == 0 || batch.get_instance_count() == 0 {
3882                                continue;
3883                            }
3884                            let target_pso: *mut c_void = match batch.get_pso_variant() {
3885                                PBR_PSO_VARIANT_SKINNED if !skinned_pso.is_null() => skinned_pso,
3886                                PBR_PSO_VARIANT_ALPHA_BLEND if !alpha_pso.is_null() => alpha_pso,
3887                                _ => opaque_pso,
3888                            };
3889                            if target_pso != bound_pso {
3890                                mtl_send_void_ptr1(
3891                                    encoder,
3892                                    sel.set_pipeline_state as *mut c_void,
3893                                    target_pso,
3894                                );
3895                                bound_pso = target_pso;
3896                            }
3897                            let target_depth: *mut c_void = if batch.get_pso_variant()
3898                                == PBR_PSO_VARIANT_ALPHA_BLEND
3899                                && !depth_ro_state.is_null()
3900                            {
3901                                depth_ro_state
3902                            } else {
3903                                depth_write_state
3904                            };
3905                            if !target_depth.is_null() && target_depth != bound_depth {
3906                                mtl_send_void_ptr1(
3907                                    encoder,
3908                                    sel.set_depth_stencil_state as *mut c_void,
3909                                    target_depth,
3910                                );
3911                                bound_depth = target_depth;
3912                            }
3913                            let mat_idx: u32 = batch
3914                                .get_material_index()
3915                                .min(mats_slice.len().saturating_sub(1) as u32);
3916                            let mat_ref: &GpuMaterialData3D = &mats_slice[mat_idx as usize];
3917                            let tex_slots: [u32; 5] = [
3918                                mat_ref.get_tex_indices_a()[0],
3919                                mat_ref.get_tex_indices_a()[1],
3920                                mat_ref.get_tex_indices_a()[2],
3921                                mat_ref.get_tex_indices_a()[3],
3922                                mat_ref.get_tex_indices_b()[0],
3923                            ];
3924                            let mut tex_mask: u32 = 0;
3925                            let mut mip_tier: u32 = 3;
3926                            for (unit, &slot_id) in tex_slots.iter().enumerate() {
3927                                let bound_tex: *mut c_void = if slot_id != GPU_MATERIAL_NO_TEXTURE
3928                                    && let Some(res_tex) = pbr_res.textures.get(&slot_id)
3929                                    && res_tex.tex_handle != 0
3930                                {
3931                                    tex_mask |= 1u32 << unit;
3932                                    if unit == 0 {
3933                                        mip_tier = if res_tex.min_lod_clamp == 0 {
3934                                            0
3935                                        } else if res_tex.min_lod_clamp <= 2 {
3936                                            1
3937                                        } else {
3938                                            2
3939                                        };
3940                                    }
3941                                    if res_tex.view_handle != 0 {
3942                                        res_tex.view_handle as *mut c_void
3943                                    } else {
3944                                        res_tex.tex_handle as *mut c_void
3945                                    }
3946                                } else {
3947                                    fallback_tex
3948                                };
3949                                send_ftex(
3950                                    encoder,
3951                                    sel.set_fragment_texture as *mut c_void,
3952                                    bound_tex,
3953                                    unit,
3954                                );
3955                            }
3956                            let lod_mip_mask: u32 = u32::from(batch.get_lod_level() & 3)
3957                                | ((mip_tier & 255) << 8)
3958                                | ((tex_mask & 31) << 16);
3959                            let uniform: PbrSceneUniformBlock = build_pbr_scene_uniform_block(
3960                                pbr,
3961                                lod_mip_mask,
3962                                mat_idx,
3963                                [
3964                                    batch.get_base_vertex(),
3965                                    batch.get_instance_start(),
3966                                    morph_stride,
3967                                    batch.get_index_start(),
3968                                ],
3969                            );
3970                            send_vbytes(
3971                                encoder,
3972                                sel.set_vertex_bytes as *mut c_void,
3973                                (&uniform as *const PbrSceneUniformBlock).cast::<c_void>(),
3974                                size_of::<PbrSceneUniformBlock>(),
3975                                0,
3976                            );
3977                            send_fbytes(
3978                                encoder,
3979                                sel.set_fragment_bytes as *mut c_void,
3980                                (&uniform as *const PbrSceneUniformBlock).cast::<c_void>(),
3981                                size_of::<PbrSceneUniformBlock>(),
3982                                0,
3983                            );
3984                            let idx_byte_offset: usize =
3985                                (batch.get_index_start() as usize).saturating_mul(size_of::<u32>());
3986                            send_draw_idx(
3987                                encoder,
3988                                sel.draw_indexed_instanced as *mut c_void,
3989                                MTL_PRIMITIVE_TYPE_TRIANGLE,
3990                                batch.get_index_count() as usize,
3991                                MTL_INDEX_TYPE_UINT32,
3992                                ibuf,
3993                                idx_byte_offset,
3994                                batch.get_instance_count() as usize,
3995                                batch.get_base_vertex() as isize,
3996                                batch.get_instance_start() as usize,
3997                            );
3998                        }
3999                    }
4000                }
4001            }
4002        }
4003    }
4004    mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
4005    Some(color_tex)
4006}
4007
4008/// Begins a Metal UI uber-shader `MTLRenderCommandEncoder` targeting `target_tex` with viewport, vertex buffer, and 4 texture slots bound.
4009///
4010/// # Arguments
4011///
4012/// - `*mut c_void` - Active `id<MTLCommandBuffer>`.
4013/// - `*mut c_void` - `MTLRenderPassDescriptor` class pointer.
4014/// - `*mut c_void` - Destination color attachment `id<MTLTexture>`.
4015/// - `(usize, MtlClearColor)` - Tuple of `(load_action, clear_color)`.
4016/// - `(usize, usize)` - Viewport dimensions `(draw_w, draw_h)`.
4017/// - `(*mut c_void, *mut c_void)` - Tuple of `(pipeline_state, vertex_instance_buffer)`.
4018/// - `[*mut c_void; 4]` - Fragment texture bindings `[glyph_r8, glyph_rgba8, image_atlas, external_or_blur]`.
4019///
4020/// # Returns
4021///
4022/// - `*mut c_void` - Active `id<MTLRenderCommandEncoder>` pointer, or null on failure.
4023#[cfg(any(target_os = "macos", target_os = "ios"))]
4024fn metal_begin_ui_render_encoder(
4025    cmd_buf: *mut c_void,
4026    pass_cls: *mut c_void,
4027    target_tex: *mut c_void,
4028    load_spec: (usize, MtlClearColor),
4029    draw_dims: (usize, usize),
4030    pipe_buf: (*mut c_void, *mut c_void),
4031    textures: [*mut c_void; 4],
4032) -> *mut c_void {
4033    let sel: &MetalSelectors = cached_metal_selectors();
4034    let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
4035    if pass_desc.is_null() {
4036        return null_mut();
4037    }
4038    let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
4039    let att0: *mut c_void = unsafe {
4040        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
4041            transmute(objc_msgSend as *const c_void);
4042        send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
4043    };
4044    if att0.is_null() {
4045        return null_mut();
4046    }
4047    mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, target_tex);
4048    mtl_send_void_usize(att0, sel.set_load_action as *mut c_void, load_spec.0);
4049    mtl_send_void_usize(
4050        att0,
4051        sel.set_store_action as *mut c_void,
4052        MTL_STORE_ACTION_STORE,
4053    );
4054    if load_spec.0 == MTL_LOAD_ACTION_CLEAR {
4055        unsafe {
4056            let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
4057                transmute(objc_msgSend as *const c_void);
4058            send_clear(att0, sel.set_clear_color as *mut c_void, load_spec.1);
4059        }
4060    }
4061    let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
4062    if encoder.is_null() {
4063        return null_mut();
4064    }
4065    mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, pipe_buf.0);
4066    unsafe {
4067        let send_viewport: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlViewport) =
4068            transmute(objc_msgSend as *const c_void);
4069        send_viewport(
4070            encoder,
4071            sel.set_viewport as *mut c_void,
4072            MtlViewport {
4073                origin_x: 0.0,
4074                origin_y: 0.0,
4075                width: draw_dims.0 as f64,
4076                height: draw_dims.1 as f64,
4077                znear: 0.0,
4078                zfar: 1.0,
4079            },
4080        );
4081        if !pipe_buf.1.is_null() {
4082            let send_vbuf: unsafe extern "C" fn(
4083                *mut c_void,
4084                *mut c_void,
4085                *mut c_void,
4086                usize,
4087                usize,
4088            ) = transmute(objc_msgSend as *const c_void);
4089            send_vbuf(
4090                encoder,
4091                sel.set_vertex_buffer as *mut c_void,
4092                pipe_buf.1,
4093                0,
4094                0,
4095            );
4096        }
4097        let send_ftex: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, usize) =
4098            transmute(objc_msgSend as *const c_void);
4099        for (slot_idx, tex_ptr) in textures.iter().enumerate() {
4100            if !tex_ptr.is_null() {
4101                send_ftex(
4102                    encoder,
4103                    sel.set_fragment_texture as *mut c_void,
4104                    *tex_ptr,
4105                    slot_idx,
4106                );
4107            }
4108        }
4109    }
4110    encoder
4111}
4112
4113/// Encodes one instanced `GpuBatch` draw call onto an active Metal UI `MTLRenderCommandEncoder`.
4114///
4115/// # Arguments
4116///
4117/// - `*mut c_void` - Active `id<MTLRenderCommandEncoder>`.
4118/// - `(usize, usize)` - Active render target dimensions `(draw_w, draw_h)`.
4119/// - `&GpuBatch` - Source GPU draw batch.
4120/// - `usize` - Instance count inside the bound vertex buffer.
4121/// - `usize` - Starting base instance index inside the bound vertex buffer.
4122#[cfg(any(target_os = "macos", target_os = "ios"))]
4123fn metal_encode_ui_batch_draw(
4124    encoder: *mut c_void,
4125    draw_dims: (usize, usize),
4126    batch: &GpuBatch,
4127    count: usize,
4128    base_instance: usize,
4129) {
4130    let sel: &MetalSelectors = cached_metal_selectors();
4131    let (draw_w, draw_h): (usize, usize) = draw_dims;
4132    let uniform: GpuLayerUniform =
4133        GpuLayerUniform::new(draw_w as f32, draw_h as f32, batch.get_scroll_offset());
4134    let rect_bounds: Rect = batch.get_scissor();
4135    let sx: usize = (rect_bounds.get_x().max(0.0).floor() as usize).min(draw_w.saturating_sub(1));
4136    let sy: usize = (rect_bounds.get_y().max(0.0).floor() as usize).min(draw_h.saturating_sub(1));
4137    let sw: usize = (rect_bounds.get_width().max(1.0).ceil() as usize)
4138        .min(draw_w.saturating_sub(sx))
4139        .max(1);
4140    let sh: usize = (rect_bounds.get_height().max(1.0).ceil() as usize)
4141        .min(draw_h.saturating_sub(sy))
4142        .max(1);
4143    unsafe {
4144        let send_vbytes: unsafe extern "C" fn(
4145            *mut c_void,
4146            *mut c_void,
4147            *const c_void,
4148            usize,
4149            usize,
4150        ) = transmute(objc_msgSend as *const c_void);
4151        let send_scissor: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlScissorRect) =
4152            transmute(objc_msgSend as *const c_void);
4153        let send_draw: unsafe extern "C" fn(
4154            *mut c_void,
4155            *mut c_void,
4156            usize,
4157            usize,
4158            usize,
4159            usize,
4160            usize,
4161        ) = transmute(objc_msgSend as *const c_void);
4162        send_vbytes(
4163            encoder,
4164            sel.set_vertex_bytes as *mut c_void,
4165            (&uniform as *const GpuLayerUniform).cast::<c_void>(),
4166            size_of::<GpuLayerUniform>(),
4167            1,
4168        );
4169        send_scissor(
4170            encoder,
4171            sel.set_scissor_rect as *mut c_void,
4172            MtlScissorRect {
4173                x: sx,
4174                y: sy,
4175                width: sw,
4176                height: sh,
4177            },
4178        );
4179        send_draw(
4180            encoder,
4181            sel.draw_primitives_instanced as *mut c_void,
4182            MTL_PRIMITIVE_TYPE_TRIANGLE,
4183            0,
4184            6,
4185            count,
4186            base_instance,
4187        );
4188    }
4189}
4190
4191/// Uploads `GpuPrimitiveInstance` buffers to Metal GPU memory and commits a command buffer.
4192///
4193/// # Arguments
4194///
4195/// - `usize` - Retained `id<MTLDevice>` pointer.
4196/// - `usize` - Retained `id<MTLCommandQueue>` pointer.
4197/// - `&[GpuBatch]` - Ordered GPU batches to upload.
4198///
4199/// # Returns
4200///
4201/// - `usize` - Total instances uploaded into Metal buffers.
4202#[cfg(any(target_os = "macos", target_os = "ios"))]
4203fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
4204    let total_instances: usize = batches
4205        .iter()
4206        .map(|blue_val: &GpuBatch| {
4207            blue_val
4208                .get_primitives()
4209                .len()
4210                .max(blue_val.get_instances().len())
4211        })
4212        .sum();
4213    if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
4214        return total_instances;
4215    }
4216    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
4217    let device: *mut c_void = device_handle as *mut c_void;
4218    let queue: *mut c_void = queue_handle as *mut c_void;
4219    let sel: &MetalSelectors = cached_metal_selectors();
4220    let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
4221    let sel_rel: *mut c_void = sel.release as *mut c_void;
4222    unsafe {
4223        let send_buf: unsafe extern "C" fn(
4224            *mut c_void,
4225            *mut c_void,
4226            *const c_void,
4227            usize,
4228            usize,
4229        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
4230        for batch in batches.iter() {
4231            let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
4232            if !prims.is_empty() {
4233                let byte_len: usize = size_of_val(prims);
4234                let mtl_buf: *mut c_void = send_buf(
4235                    device,
4236                    sel_buf,
4237                    prims.as_ptr().cast::<c_void>(),
4238                    byte_len,
4239                    0,
4240                );
4241                if !mtl_buf.is_null() {
4242                    mtl_send_void0(mtl_buf, sel_rel);
4243                }
4244            } else {
4245                let instances: &[GpuQuadInstance] = batch.get_instances();
4246                if instances.is_empty() {
4247                    continue;
4248                }
4249                let byte_len: usize = size_of_val(instances);
4250                let mtl_buf: *mut c_void = send_buf(
4251                    device,
4252                    sel_buf,
4253                    instances.as_ptr().cast::<c_void>(),
4254                    byte_len,
4255                    0,
4256                );
4257                if !mtl_buf.is_null() {
4258                    mtl_send_void0(mtl_buf, sel_rel);
4259                }
4260            }
4261        }
4262        let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
4263        if !cmd_buf.is_null() {
4264            mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
4265        }
4266        objc_autoreleasePoolPop(pool);
4267    }
4268    total_instances
4269}
4270
4271/// Releases retained Apple Metal Objective-C objects cleanly on drop.
4272///
4273/// # Arguments
4274///
4275/// - `usize` - `id<MTLDevice>` pointer.
4276/// - `usize` - `id<MTLCommandQueue>` pointer.
4277/// - `usize` - `id<MTLLibrary>` pointer.
4278#[cfg(any(target_os = "macos", target_os = "ios"))]
4279fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
4280    let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
4281    if library_handle != 0 {
4282        mtl_send_void0(library_handle as *mut c_void, sel_rel);
4283    }
4284    if queue_handle != 0 {
4285        mtl_send_void0(queue_handle as *mut c_void, sel_rel);
4286    }
4287    if device_handle != 0 {
4288        mtl_send_void0(device_handle as *mut c_void, sel_rel);
4289    }
4290}
4291
4292#[cfg(target_os = "windows")]
4293#[link(name = "kernel32")]
4294unsafe extern "system" {
4295    /// Dynamically loads a Windows DLL by ANSI path.
4296    ///
4297    /// # Arguments
4298    ///
4299    /// - `*const u8` - Null-terminated ANSI DLL path.
4300    ///
4301    /// # Returns
4302    ///
4303    /// - `*mut c_void` - Loaded `HMODULE` handle or null.
4304    fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
4305    /// Looks up an exported procedure address from a loaded Windows DLL.
4306    ///
4307    /// # Arguments
4308    ///
4309    /// - `*mut c_void` - Loaded `HMODULE` handle.
4310    /// - `*const u8` - Null-terminated ASCII export name.
4311    ///
4312    /// # Returns
4313    ///
4314    /// - `*mut c_void` - Exported function address or null.
4315    fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
4316}
4317
4318/// Probes Windows Direct3D 12 and `d3dcompiler_47.dll` once per process (caching handles in `OnceLock`).
4319///
4320/// # Arguments
4321///
4322/// - `GraphicsBackend` - Requested graphics backend.
4323///
4324/// # Returns
4325///
4326/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Direct3D 12 availability metadata.
4327#[cfg(target_os = "windows")]
4328fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
4329    let cached: &WindowsD3d12ProbeCache = WINDOWS_D3D12_CACHE.get_or_init(|| unsafe {
4330        let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
4331        let has_d3d12: bool = if !d3d12_mod.is_null() {
4332            !GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr()).is_null()
4333        } else {
4334            false
4335        };
4336        let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
4337        let has_compiler: bool = if !compiler_mod.is_null() {
4338            !GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr()).is_null()
4339        } else {
4340            false
4341        };
4342        WindowsD3d12ProbeCache {
4343            has_d3d12,
4344            has_compiler,
4345        }
4346    });
4347    let has_runtime: bool = cached.has_d3d12 && cached.has_compiler;
4348    let label: &str = if cached.has_d3d12 {
4349        GPU_DEVICE_D3D12
4350    } else {
4351        GPU_DEVICE_FALLBACK
4352    };
4353    (
4354        GpuAdapterInfo::new(backend, label.to_string(), has_runtime, false),
4355        0,
4356        0,
4357        0,
4358    )
4359}
4360
4361#[cfg(any(target_os = "linux", target_os = "android"))]
4362unsafe extern "C" {
4363    /// Dynamically opens a shared library object by name.
4364    ///
4365    /// # Arguments
4366    ///
4367    /// - `*const c_char` - Null-terminated library name.
4368    /// - `i32` - POSIX `RTLD_*` resolution flags.
4369    ///
4370    /// # Returns
4371    ///
4372    /// - `*mut c_void` - Shared library handle or null.
4373    fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
4374    /// Resolves a symbol address from an open shared library handle.
4375    ///
4376    /// # Arguments
4377    ///
4378    /// - `*mut c_void` - Open shared library handle.
4379    /// - `*const c_char` - Null-terminated symbol name.
4380    ///
4381    /// # Returns
4382    ///
4383    /// - `*mut c_void` - Resolved symbol pointer or null.
4384    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
4385}
4386
4387/// Probes Linux or Android Vulkan loader once per process and retains the library handle in `OnceLock`.
4388///
4389/// # Arguments
4390///
4391/// - `GraphicsBackend` - Requested graphics backend.
4392///
4393/// # Returns
4394///
4395/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Vulkan runtime status.
4396#[cfg(any(target_os = "linux", target_os = "android"))]
4397fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
4398    let cached: &VulkanProbeCache = VULKAN_PROBE_CACHE.get_or_init(|| {
4399        let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
4400            return VulkanProbeCache {
4401                available: false,
4402                lib_handle: 0,
4403            };
4404        };
4405        let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
4406            return VulkanProbeCache {
4407                available: false,
4408                lib_handle: 0,
4409            };
4410        };
4411        let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
4412            return VulkanProbeCache {
4413                available: false,
4414                lib_handle: 0,
4415            };
4416        };
4417        unsafe {
4418            let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
4419            if handle.is_null() {
4420                VulkanProbeCache {
4421                    available: false,
4422                    lib_handle: 0,
4423                }
4424            } else {
4425                let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
4426                let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
4427                VulkanProbeCache {
4428                    available: !p1.is_null() && !p2.is_null(),
4429                    lib_handle: handle as usize,
4430                }
4431            }
4432        }
4433    });
4434    let name: &str = if cached.available {
4435        GPU_DEVICE_VULKAN
4436    } else {
4437        GPU_DEVICE_FALLBACK
4438    };
4439    (
4440        GpuAdapterInfo::new(backend, name.to_string(), cached.available, false),
4441        cached.lib_handle,
4442        0,
4443        0,
4444    )
4445}
4446
4447/// Compiles and links the WebGL 2 64-byte instanced uber-shader program on `wasm32`.
4448///
4449/// # Arguments
4450///
4451/// - `&WebGl2RenderingContext` - Active WebGL 2 canvas context.
4452///
4453/// # Returns
4454///
4455/// - `Option<WebGlProgram>` - Linked shader program when compilation succeeds.
4456#[cfg(target_arch = "wasm32")]
4457pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
4458    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
4459    gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
4460    gl.compile_shader(&vs);
4461    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
4462    gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
4463    gl.compile_shader(&fs);
4464    let program: WebGlProgram = gl.create_program()?;
4465    gl.attach_shader(&program, &vs);
4466    gl.attach_shader(&program, &fs);
4467    gl.link_program(&program);
4468    Some(program)
4469}
4470
4471/// Returns the canonical 5-attribute GLES 3.0 instanced vertex layout matching `GLSL_ES3_UI_VERTEX_SHADER` and 64-byte `GpuPrimitiveInstance`.
4472///
4473/// # Returns
4474///
4475/// - `[Gles3InstanceAttribSpec; 5]` - Ordered instanced vertex attribute bindings (`locations 1..=5`, stride `64`).
4476#[must_use]
4477pub const fn gles3_ui_instance_attribs() -> [Gles3InstanceAttribSpec; 5] {
4478    let stride: i32 = GPU_PRIMITIVE_INSTANCE_BYTES as i32;
4479    [
4480        Gles3InstanceAttribSpec {
4481            location: 1,
4482            components: 4,
4483            is_integer: false,
4484            byte_offset: 0,
4485            stride,
4486        },
4487        Gles3InstanceAttribSpec {
4488            location: 2,
4489            components: 4,
4490            is_integer: false,
4491            byte_offset: 16,
4492            stride,
4493        },
4494        Gles3InstanceAttribSpec {
4495            location: 3,
4496            components: 2,
4497            is_integer: true,
4498            byte_offset: 32,
4499            stride,
4500        },
4501        Gles3InstanceAttribSpec {
4502            location: 4,
4503            components: 4,
4504            is_integer: true,
4505            byte_offset: 40,
4506            stride,
4507        },
4508        Gles3InstanceAttribSpec {
4509            location: 5,
4510            components: 2,
4511            is_integer: true,
4512            byte_offset: 56,
4513            stride,
4514        },
4515    ]
4516}
4517
4518/// Converts a top-left physical scissor rectangle into an OpenGL ES bottom-left scissor tuple `(x, y, width, height)`.
4519///
4520/// # Arguments
4521///
4522/// - `u32` - Surface height in physical pixels.
4523/// - `u32` - Top-left scissor X coordinate.
4524/// - `u32` - Top-left scissor Y coordinate.
4525/// - `u32` - Scissor width in physical pixels.
4526/// - `u32` - Scissor height in physical pixels.
4527///
4528/// # Returns
4529///
4530/// - `[i32; 4]` - OpenGL ES `[x, y_bottom_up, width, height]` scissor rectangle.
4531#[must_use]
4532pub fn gles3_scissor_from_top_down(
4533    surface_h: u32,
4534    sx: u32,
4535    sy: u32,
4536    stroke_width: u32,
4537    sh: u32,
4538) -> [i32; 4] {
4539    let y1: u32 = sy.saturating_add(sh).min(surface_h);
4540    let y_bottom: u32 = surface_h.saturating_sub(y1);
4541    [sx as i32, y_bottom as i32, stroke_width as i32, sh as i32]
4542}
4543
4544/// Selects the lowest-cost texture upload strategy (`MultiRect`, `MergedBbox`, `FullFrame`, or `None`) from dirty rectangles and surface dimensions.
4545///
4546/// # Arguments
4547///
4548/// - `u32` - Framebuffer width in pixels.
4549/// - `u32` - Framebuffer height in pixels.
4550/// - `&[PixelDirtyRect]` - Candidate damaged sub-rectangles in physical pixels.
4551/// - `bool` - When `true`, forces a `FullFrame` upload (e.g. surface resize or first frame).
4552///
4553/// # Returns
4554///
4555/// - `AdaptiveUploadPlan` - Selected strategy, coalesced rectangle list, and byte/cost metrics.
4556#[must_use]
4557pub fn select_adaptive_upload_plan(
4558    fb_w: u32,
4559    fb_h: u32,
4560    dirty_rects: &[PixelDirtyRect],
4561    force_full: bool,
4562) -> AdaptiveUploadPlan {
4563    if fb_w == 0 || fb_h == 0 {
4564        return AdaptiveUploadPlan {
4565            strategy: MobileUploadStrategy::None,
4566            rects: Vec::new(),
4567            total_upload_bytes: 0,
4568            merged_bbox_bytes: 0,
4569            full_frame_bytes: 0,
4570            estimated_cost_score: 0.0,
4571        };
4572    }
4573    let full_rect: PixelDirtyRect = PixelDirtyRect::new(0, 0, fb_w, fb_h);
4574    let full_bytes: usize = full_rect.byte_size_rgba8();
4575    if force_full {
4576        return AdaptiveUploadPlan {
4577            strategy: MobileUploadStrategy::FullFrame,
4578            rects: vec![full_rect],
4579            total_upload_bytes: full_bytes,
4580            merged_bbox_bytes: full_bytes,
4581            full_frame_bytes: full_bytes,
4582            estimated_cost_score: (full_bytes + MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES) as f32,
4583        };
4584    }
4585    let mut coalesced: Vec<PixelDirtyRect> = Vec::with_capacity(dirty_rects.len().min(16));
4586    for rect in dirty_rects.iter() {
4587        let Some(mut clamped) = rect.clamp_to(fb_w, fb_h) else {
4588            continue;
4589        };
4590        let mut merged_any: bool = true;
4591        while merged_any {
4592            merged_any = false;
4593            let mut idx: usize = 0;
4594            while idx < coalesced.len() {
4595                if coalesced[idx].intersects_or_adjacent(clamped, MOBILE_UPLOAD_COALESCE_PAD_PX) {
4596                    let existing: PixelDirtyRect = coalesced.swap_remove(idx);
4597                    clamped = clamped.union_with(existing);
4598                    merged_any = true;
4599                } else {
4600                    idx += 1;
4601                }
4602            }
4603        }
4604        coalesced.push(clamped);
4605    }
4606    if coalesced.is_empty() {
4607        return AdaptiveUploadPlan {
4608            strategy: MobileUploadStrategy::None,
4609            rects: Vec::new(),
4610            total_upload_bytes: 0,
4611            merged_bbox_bytes: 0,
4612            full_frame_bytes: full_bytes,
4613            estimated_cost_score: 0.0,
4614        };
4615    }
4616    let mut merged_bbox: PixelDirtyRect = coalesced[0];
4617    let mut multi_bytes: usize = 0;
4618    for red_val in coalesced.iter() {
4619        merged_bbox = merged_bbox.union_with(*red_val);
4620        multi_bytes = multi_bytes.saturating_add(red_val.byte_size_rgba8());
4621    }
4622    let merged_bytes: usize = merged_bbox.byte_size_rgba8();
4623    let multi_cost: usize = multi_bytes.saturating_add(
4624        coalesced
4625            .len()
4626            .saturating_mul(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES),
4627    );
4628    let merged_cost: usize = merged_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
4629    let full_threshold_bytes: usize =
4630        ((full_bytes as f32) * MOBILE_UPLOAD_FULL_FRAME_COVERAGE_THRESHOLD).round() as usize;
4631    let full_cost: usize = full_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
4632    let multi_eligible: bool = coalesced.len() >= 2
4633        && coalesced.len() <= MOBILE_MAX_MULTI_UPLOAD_RECTS
4634        && multi_bytes <= full_threshold_bytes
4635        && multi_cost < merged_cost
4636        && multi_cost < full_cost;
4637    if multi_eligible {
4638        return AdaptiveUploadPlan {
4639            strategy: MobileUploadStrategy::MultiRect,
4640            rects: coalesced,
4641            total_upload_bytes: multi_bytes,
4642            merged_bbox_bytes: merged_bytes,
4643            full_frame_bytes: full_bytes,
4644            estimated_cost_score: multi_cost as f32,
4645        };
4646    }
4647    if merged_bytes <= full_threshold_bytes && merged_cost < full_cost {
4648        return AdaptiveUploadPlan {
4649            strategy: MobileUploadStrategy::MergedBbox,
4650            rects: vec![merged_bbox],
4651            total_upload_bytes: merged_bytes,
4652            merged_bbox_bytes: merged_bytes,
4653            full_frame_bytes: full_bytes,
4654            estimated_cost_score: merged_cost as f32,
4655        };
4656    }
4657    AdaptiveUploadPlan {
4658        strategy: MobileUploadStrategy::FullFrame,
4659        rects: vec![full_rect],
4660        total_upload_bytes: full_bytes,
4661        merged_bbox_bytes: merged_bytes,
4662        full_frame_bytes: full_bytes,
4663        estimated_cost_score: full_cost as f32,
4664    }
4665}
4666
4667/// Converts a `DamageRegion` into physical `PixelDirtyRect` entries clamped to `(fb_w, fb_h)`.
4668///
4669/// # Arguments
4670///
4671/// - `DamageRegion` - Frame damage region from layout/paint.
4672/// - `u32` - Surface width in physical pixels.
4673/// - `u32` - Surface height in physical pixels.
4674///
4675/// # Returns
4676///
4677/// - `Vec<PixelDirtyRect>` - Clamped physical dirty rectangles (`empty` when no damage).
4678#[must_use]
4679pub fn damage_region_to_pixel_dirty_rects(
4680    damage: DamageRegion,
4681    fb_w: u32,
4682    fb_h: u32,
4683) -> Vec<PixelDirtyRect> {
4684    if fb_w == 0 || fb_h == 0 {
4685        return Vec::new();
4686    }
4687    if damage.get_full_damage() {
4688        return vec![PixelDirtyRect::new(0, 0, fb_w, fb_h)];
4689    }
4690    let Some(red_val) = damage.resolve(fb_w, fb_h) else {
4691        return Vec::new();
4692    };
4693    let rx0: u32 = (red_val.get_x().floor().max(0.0) as u32).min(fb_w);
4694    let ry0: u32 = (red_val.get_y().floor().max(0.0) as u32).min(fb_h);
4695    let rx1: u32 = (red_val.right().ceil().max(0.0) as u32).clamp(rx0, fb_w);
4696    let ry1: u32 = (red_val.bottom().ceil().max(0.0) as u32).clamp(ry0, fb_h);
4697    if rx1 > rx0 && ry1 > ry0 {
4698        vec![PixelDirtyRect::new(rx0, ry0, rx1 - rx0, ry1 - ry0)]
4699    } else {
4700        Vec::new()
4701    }
4702}
4703
4704/// Flattens pre-compiled `HardwareRenderer` `GpuBatch` and `GpuBackdropBlurPass` slices into a single direct-GPU frame payload.
4705///
4706/// # Arguments
4707///
4708/// - `u32` - Physical surface width in pixels.
4709/// - `u32` - Physical surface height in pixels.
4710/// - `Color` - Surface clear color.
4711/// - `&[GpuBatch]` - Ordered GPU batches from `HardwareRenderer::active_batches_slice()`.
4712/// - `&[GpuBackdropBlurPass]` - Ordered Dual-Kawase backdrop blur passes.
4713///
4714/// # Returns
4715///
4716/// - `DirectGpuFrameBatch` - Flat 64-byte primitive stream and scissor draw ranges with `cpu_mirror_active = false`.
4717#[must_use]
4718pub fn build_direct_gpu_frame_batch_from_batches(
4719    viewport_width: u32,
4720    viewport_height: u32,
4721    clear_color: Color,
4722    batches: &[GpuBatch],
4723    blur_passes: &[GpuBackdropBlurPass],
4724) -> DirectGpuFrameBatch {
4725    let total_prims: usize = batches
4726        .iter()
4727        .map(|blue_val: &GpuBatch| {
4728            blue_val
4729                .get_primitives()
4730                .len()
4731                .max(blue_val.get_instances().len())
4732        })
4733        .sum();
4734    let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
4735    let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(batches.len());
4736    let vw: u32 = viewport_width.max(1);
4737    let vh: u32 = viewport_height.max(1);
4738    for batch in batches.iter() {
4739        let base_instance: u32 = primitives.len() as u32;
4740        if !batch.get_primitives().is_empty() {
4741            primitives.extend_from_slice(batch.get_primitives());
4742        } else {
4743            for quad in batch.get_instances().iter() {
4744                primitives.push(GpuPrimitiveInstance::from_quad_instance(
4745                    quad,
4746                    batch.get_texture_slot(),
4747                    batch.get_layer_id(),
4748                ));
4749            }
4750        }
4751        let instance_count: u32 = (primitives.len() as u32).saturating_sub(base_instance);
4752        if instance_count == 0 {
4753            continue;
4754        }
4755        let rect_bounds: Rect = batch.get_scissor();
4756        let sx: u32 = (rect_bounds.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
4757        let sy: u32 = (rect_bounds.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
4758        let stroke_width: u32 = (rect_bounds.get_width().max(1.0).ceil() as u32)
4759            .min(vw.saturating_sub(sx))
4760            .max(1);
4761        let sh: u32 = (rect_bounds.get_height().max(1.0).ceil() as u32)
4762            .min(vh.saturating_sub(sy))
4763            .max(1);
4764        let scroll: [f32; 2] = batch.get_scroll_offset();
4765        draw_ranges.push(DirectGpuBatchRange {
4766            base_instance,
4767            instance_count,
4768            scissor_x: sx,
4769            scissor_y: sy,
4770            scissor_w: stroke_width,
4771            scissor_h: sh,
4772            scroll_x: scroll[0],
4773            scroll_y: scroll[1],
4774            texture_slot: batch.get_texture_slot(),
4775            layer_id: batch.get_layer_id(),
4776            pad: [0, 0],
4777        });
4778    }
4779    let instance_upload_bytes: usize = primitives
4780        .len()
4781        .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
4782    DirectGpuFrameBatch {
4783        viewport_width: vw,
4784        viewport_height: vh,
4785        clear_rgba: clear_color.to_f32_array(),
4786        primitives,
4787        draw_ranges,
4788        backdrop_blurs: blur_passes.to_vec(),
4789        glyph_r8_atlas: None,
4790        image_rgba8_atlas: None,
4791        instance_upload_bytes,
4792        cpu_mirror_active: false,
4793        upload_strategy: MobileUploadStrategy::DirectGpu,
4794    }
4795}
4796
4797/// Appends one `GpuPrimitiveInstance` into `primitives` and extends or opens a scissor-matched `DirectGpuBatchRange`.
4798///
4799/// # Arguments
4800///
4801/// - `&mut Vec<GpuPrimitiveInstance>` - Flat primitive stream.
4802/// - `&mut Vec<DirectGpuBatchRange>` - Ordered draw ranges.
4803/// - `GpuPrimitiveInstance` - Primitive to emit.
4804/// - `Rect` - Active physical scissor clip rectangle.
4805/// - `u32` - Surface width in physical pixels.
4806/// - `u32` - Surface height in physical pixels.
4807fn push_direct_gpu_primitive(
4808    primitives: &mut Vec<GpuPrimitiveInstance>,
4809    draw_ranges: &mut Vec<DirectGpuBatchRange>,
4810    prim: GpuPrimitiveInstance,
4811    clip: Rect,
4812    vw: u32,
4813    vh: u32,
4814) {
4815    if clip.get_width() <= 0.0 || clip.get_height() <= 0.0 {
4816        return;
4817    }
4818    let sx: u32 = (clip.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
4819    let sy: u32 = (clip.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
4820    let stroke_width: u32 = (clip.get_width().max(1.0).ceil() as u32)
4821        .min(vw.saturating_sub(sx))
4822        .max(1);
4823    let sh: u32 = (clip.get_height().max(1.0).ceil() as u32)
4824        .min(vh.saturating_sub(sy))
4825        .max(1);
4826    let layer_id: u8 = prim.layer_id();
4827    let base: u32 = primitives.len() as u32;
4828    primitives.push(prim);
4829    if let Some(last) = draw_ranges.last_mut()
4830        && last.get_scissor_x() == sx
4831        && last.get_scissor_y() == sy
4832        && last.get_scissor_w() == stroke_width
4833        && last.get_scissor_h() == sh
4834        && last.get_layer_id() == layer_id
4835        && last.get_instance_count() < MAX_QUADS_PER_BATCH as u32
4836    {
4837        last.set_instance_count(last.get_instance_count().saturating_add(1));
4838        return;
4839    }
4840    draw_ranges.push(DirectGpuBatchRange {
4841        base_instance: base,
4842        instance_count: 1,
4843        scissor_x: sx,
4844        scissor_y: sy,
4845        scissor_w: stroke_width,
4846        scissor_h: sh,
4847        scroll_x: 0.0,
4848        scroll_y: 0.0,
4849        texture_slot: 0,
4850        layer_id,
4851        pad: [0, 0],
4852    });
4853}
4854
4855/// Encodes normalized `[u0, v0, u1, v1]` texel bounds inside an `(atlas_w, atlas_h)` sheet into `[u16; 4]`.
4856///
4857/// # Arguments
4858///
4859/// - `u32` - Atlas width in texels.
4860/// - `u32` - Atlas height in texels.
4861/// - `u32` - Sub-rectangle X coordinate in texels.
4862/// - `u32` - Sub-rectangle Y coordinate in texels.
4863/// - `u32` - Sub-rectangle width in texels.
4864/// - `u32` - Sub-rectangle height in texels.
4865///
4866/// # Returns
4867///
4868/// - `[u16; 4]` - Normalized UV coordinates in `[0..=65535]`.
4869fn encode_atlas_uv_rect(
4870    atlas_w: u32,
4871    atlas_h: u32,
4872    pos_x: u32,
4873    pos_y: u32,
4874    width_val: u32,
4875    height_val: u32,
4876) -> [u16; 4] {
4877    let inv_w: f32 = 1.0 / (atlas_w.max(1) as f32);
4878    let inv_h: f32 = 1.0 / (atlas_h.max(1) as f32);
4879    let u0: u16 = (((pos_x as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
4880    let v0: u16 = (((pos_y as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
4881    let u1: u16 = ((((pos_x + width_val) as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
4882    let v1: u16 =
4883        ((((pos_y + height_val) as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
4884    [u0, v0, u1, v1]
4885}
4886
4887/// Packs frame RGBA8 image/sprite slices into a single shelf-packed RGBA8 texture atlas and resolves UV rectangles.
4888///
4889/// # Arguments
4890///
4891/// - `&[DirectGpuImageSlice<'_>]` - Borrowed RGBA8 image and sprite crop descriptors.
4892/// - `u64` - Revision tag stamped onto the output atlas.
4893///
4894/// # Returns
4895///
4896/// - `(Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>)` - Packed RGBA8 image sheet and per-entry normalized UVs.
4897fn pack_frame_image_atlas(
4898    images: &[DirectGpuImageSlice<'_>],
4899    revision: u64,
4900) -> (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) {
4901    if images.is_empty() {
4902        return (None, Vec::new());
4903    }
4904    let mut max_w: u32 = 1;
4905    let mut sum_w: u32 = 1;
4906    for entry in images.iter() {
4907        let cw: u32 = entry.crop.get_width();
4908        max_w = max_w.max(cw.saturating_add(2));
4909        sum_w = sum_w.saturating_add(cw.saturating_add(1));
4910    }
4911    let atlas_w: u32 = sum_w
4912        .clamp(64, 2048)
4913        .max(max_w)
4914        .next_power_of_two()
4915        .min(16384);
4916    let mut placements: Vec<(u32, u32, u32, u32)> = Vec::with_capacity(images.len());
4917    let mut cx: u32 = 1;
4918    let mut cy: u32 = 1;
4919    let mut shelf_h: u32 = 0;
4920    for entry in images.iter() {
4921        let clamped_w: u32 = entry.crop.get_width().min(atlas_w.saturating_sub(2)).max(1);
4922        let clamped_h: u32 = entry.crop.get_height().max(1);
4923        if cx + clamped_w + 1 > atlas_w {
4924            cx = 1;
4925            cy = cy.saturating_add(shelf_h).saturating_add(1);
4926            shelf_h = 0;
4927        }
4928        placements.push((cx, cy, clamped_w, clamped_h));
4929        cx = cx.saturating_add(clamped_w).saturating_add(1);
4930        shelf_h = shelf_h.max(clamped_h);
4931    }
4932    let atlas_h: u32 = cy.saturating_add(shelf_h).saturating_add(1).max(64);
4933    let mut pixels: Vec<u8> = vec![0; (atlas_w as usize) * (atlas_h as usize) * 4];
4934    let mut uvs: Vec<[u16; 4]> = Vec::with_capacity(images.len());
4935    for (idx, entry) in images.iter().enumerate() {
4936        let (dx, dy, copy_w, copy_h): (u32, u32, u32, u32) = placements[idx];
4937        let sx: u32 = entry.crop.get_x();
4938        let sy: u32 = entry.crop.get_y();
4939        let valid_w: u32 = copy_w.min(entry.src_w.saturating_sub(sx));
4940        let valid_h: u32 = copy_h.min(entry.src_h.saturating_sub(sy));
4941        for row in 0..valid_h {
4942            let src_off: usize =
4943                (((sy + row) as usize) * (entry.src_w as usize) + (sx as usize)) * 4;
4944            let dst_off: usize = (((dy + row) as usize) * (atlas_w as usize) + (dx as usize)) * 4;
4945            let row_bytes: usize = (valid_w as usize) * 4;
4946            if src_off + row_bytes <= entry.pixels.len() && dst_off + row_bytes <= pixels.len() {
4947                pixels[dst_off..dst_off + row_bytes]
4948                    .copy_from_slice(&entry.pixels[src_off..src_off + row_bytes]);
4949            }
4950        }
4951        uvs.push(encode_atlas_uv_rect(
4952            atlas_w, atlas_h, dx, dy, valid_w, valid_h,
4953        ));
4954    }
4955    (
4956        Some(DirectGpuAtlasUpload {
4957            width: atlas_w,
4958            height: atlas_h,
4959            revision,
4960            pixels,
4961        }),
4962        uvs,
4963    )
4964}
4965
4966/// Compiles a complete `DisplayList` directly into a zero-CPU-mirror `DirectGpuFrameBatch` with R8 glyph atlas and RGBA8 image sheet uploads for Android GLES 3.0 and iOS Metal.
4967///
4968/// # Arguments
4969///
4970/// - `&DisplayList` - Scene draw command stream for the current frame.
4971/// - `Option<&mut GlyphAtlas>` - Shared glyph atlas used to rasterize and pack `PrimKind::GlyphAlpha8` quads.
4972/// - `Option<&NativeSystemFont>` - Optional native OS font provider for glyph rasterization.
4973/// - `u64` - Previously uploaded glyph atlas revision (`0` forces initial upload).
4974///
4975/// # Returns
4976///
4977/// - `DirectGpuFrameBatch` - Self-contained direct-GPU primitive, range, blur, and atlas payload (`cpu_mirror_active = false`).
4978#[must_use]
4979pub fn compile_display_list_direct_gpu_batch(
4980    display_list: &DisplayList,
4981    mut glyph_atlas: Option<&mut GlyphAtlas>,
4982    font_provider: Option<&NativeSystemFont>,
4983    last_glyph_revision: u64,
4984) -> DirectGpuFrameBatch {
4985    let scale: f32 = display_list.get_scale_factor().max(0.5);
4986    let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
4987    let phys_h: u32 = ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
4988    let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
4989    let mut clip_stack: Vec<(Rect, Rect, u16)> = Vec::with_capacity(16);
4990    clip_stack.push((full_clip, full_clip, 0));
4991    let mut primitives: Vec<GpuPrimitiveInstance> =
4992        Vec::with_capacity(display_list.get_commands().len().saturating_mul(2));
4993    let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(16);
4994    let mut backdrop_blurs: Vec<GpuBackdropBlurPass> = Vec::new();
4995    let mut glyph_fixups: Vec<(usize, GlyphKey)> = Vec::new();
4996    let mut image_entries: Vec<DirectGpuImageSlice<'_>> = Vec::new();
4997    let mut image_fixups: Vec<(usize, usize)> = Vec::new();
4998    let mut clear_rgba: [f32; 4] = COLOR_WHITE.to_f32_array();
4999    let mut active_layer_id: u8 = 0;
5000    for cmd in display_list.get_commands().iter() {
5001        let (active_clip, safe_inner_clip, active_rounded_bits): (Rect, Rect, u16) = clip_stack
5002            .last()
5003            .copied()
5004            .unwrap_or((full_clip, full_clip, 0));
5005        let clip_arr: [f32; 4] = [
5006            active_clip.get_x(),
5007            active_clip.get_y(),
5008            active_clip.right(),
5009            active_clip.bottom(),
5010        ];
5011        let cmd_prim_start: usize = primitives.len();
5012        match cmd {
5013            DrawCommand::Clear(char_item) => {
5014                clear_rgba = char_item.to_f32_array();
5015            }
5016            DrawCommand::PushClip(rect) => {
5017                let phys: Rect = snap_physical_rect(*rect, scale);
5018                let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
5019                let next_safe: Rect = safe_inner_clip.intersect(phys).unwrap_or_default();
5020                let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
5021                    active_clip,
5022                    active_rounded_bits,
5023                    next_scissor,
5024                    phys,
5025                    None,
5026                );
5027                clip_stack.push((next_scissor, next_safe, next_bits));
5028            }
5029            DrawCommand::PushRoundedClip { rect, radius } => {
5030                let phys: Rect = snap_physical_rect(*rect, scale);
5031                let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
5032                let phys_radius: CornerRadius = CornerRadius::new(
5033                    radius.get_top_left() * scale,
5034                    radius.get_top_right() * scale,
5035                    radius.get_bottom_right() * scale,
5036                    radius.get_bottom_left() * scale,
5037                );
5038                let max_r: f32 = phys_radius.max_radius().ceil();
5039                let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
5040                let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
5041                let rounded_safe: Rect =
5042                    Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
5043                let next_safe: Rect = safe_inner_clip.intersect(rounded_safe).unwrap_or_default();
5044                let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
5045                    active_clip,
5046                    active_rounded_bits,
5047                    next_scissor,
5048                    phys,
5049                    Some(phys_radius),
5050                );
5051                clip_stack.push((next_scissor, next_safe, next_bits));
5052            }
5053            DrawCommand::PopClip => {
5054                if clip_stack.len() > 1 {
5055                    let _: Option<(Rect, Rect, u16)> = clip_stack.pop();
5056                }
5057            }
5058            DrawCommand::FillRoundedRect {
5059                rect,
5060                color,
5061                radius,
5062                border,
5063            } => {
5064                let snapped: Rect = snap_physical_rect(*rect, scale);
5065                let quad: [f32; 4] = [
5066                    snapped.get_x(),
5067                    snapped.get_y(),
5068                    snapped.get_width(),
5069                    snapped.get_height(),
5070                ];
5071                if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
5072                    continue;
5073                }
5074                let border_width: f32 = if border.get_width() > 0.0 {
5075                    (border.get_width() * scale).round().max(1.0)
5076                } else {
5077                    0.0
5078                };
5079                let query_val: GpuQuadInstance = GpuQuadInstance {
5080                    rect: quad,
5081                    clip: clip_arr,
5082                    color: color.to_f32_array(),
5083                    secondary_color: border.get_color().to_f32_array(),
5084                    radii: [
5085                        radius.get_top_left() * scale,
5086                        radius.get_top_right() * scale,
5087                        radius.get_bottom_right() * scale,
5088                        radius.get_bottom_left() * scale,
5089                    ],
5090                    stroke_or_blur: border_width,
5091                    angle_rad: 0.0,
5092                    kind: GpuPrimitiveKind::RoundedRect as u32,
5093                    reserved: 0,
5094                };
5095                push_direct_gpu_primitive(
5096                    &mut primitives,
5097                    &mut draw_ranges,
5098                    GpuPrimitiveInstance::from_quad_instance(&query_val, 0, active_layer_id),
5099                    active_clip,
5100                    phys_w,
5101                    phys_h,
5102                );
5103            }
5104            DrawCommand::LinearGradientRect {
5105                rect,
5106                gradient,
5107                radius,
5108            } => {
5109                let snapped: Rect = snap_physical_rect(*rect, scale);
5110                let quad: [f32; 4] = [
5111                    snapped.get_x(),
5112                    snapped.get_y(),
5113                    snapped.get_width(),
5114                    snapped.get_height(),
5115                ];
5116                if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
5117                    continue;
5118                }
5119                let quat_val: GpuQuadInstance = GpuQuadInstance {
5120                    rect: quad,
5121                    clip: clip_arr,
5122                    color: gradient.get_start_color().to_f32_array(),
5123                    secondary_color: gradient.get_end_color().to_f32_array(),
5124                    radii: [
5125                        radius.get_top_left() * scale,
5126                        radius.get_top_right() * scale,
5127                        radius.get_bottom_right() * scale,
5128                        radius.get_bottom_left() * scale,
5129                    ],
5130                    stroke_or_blur: 0.0,
5131                    angle_rad: gradient.get_angle_deg().to_radians(),
5132                    kind: GpuPrimitiveKind::Gradient as u32,
5133                    reserved: 0,
5134                };
5135                push_direct_gpu_primitive(
5136                    &mut primitives,
5137                    &mut draw_ranges,
5138                    GpuPrimitiveInstance::from_quad_instance(&quat_val, 0, active_layer_id),
5139                    active_clip,
5140                    phys_w,
5141                    phys_h,
5142                );
5143            }
5144            DrawCommand::BoxShadow {
5145                rect,
5146                radius,
5147                shadow,
5148            } => {
5149                let spread: f32 = shadow.get_spread_radius() * scale;
5150                let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
5151                let sigma: f32 = (blur * 0.5).max(0.75);
5152                let pad: f32 = (sigma * 3.0).ceil();
5153                let base_rect: Rect = snap_physical_rect(*rect, scale);
5154                let cx: f32 = base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
5155                let cy: f32 = base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
5156                let cw: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
5157                let ch: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
5158                let corner_vec: GpuQuadInstance = GpuQuadInstance {
5159                    rect: [cx - pad, cy - pad, cw + pad * 2.0, ch + pad * 2.0],
5160                    clip: clip_arr,
5161                    color: shadow.get_color().to_f32_array(),
5162                    secondary_color: [0.0; 4],
5163                    radii: [
5164                        (radius.get_top_left() * scale + spread).max(0.0),
5165                        (radius.get_top_right() * scale + spread).max(0.0),
5166                        (radius.get_bottom_right() * scale + spread).max(0.0),
5167                        (radius.get_bottom_left() * scale + spread).max(0.0),
5168                    ],
5169                    stroke_or_blur: sigma,
5170                    angle_rad: pad,
5171                    kind: GpuPrimitiveKind::Shadow as u32,
5172                    reserved: 0,
5173                };
5174                push_direct_gpu_primitive(
5175                    &mut primitives,
5176                    &mut draw_ranges,
5177                    GpuPrimitiveInstance::from_quad_instance(&corner_vec, 0, active_layer_id),
5178                    active_clip,
5179                    phys_w,
5180                    phys_h,
5181                );
5182            }
5183            DrawCommand::BackdropBlur {
5184                rect,
5185                radius,
5186                blur_radius,
5187            } => {
5188                let snapped: Rect = snap_physical_rect(*rect, scale);
5189                let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 96.0);
5190                let radii_px: [f32; 4] = [
5191                    radius.get_top_left() * scale,
5192                    radius.get_top_right() * scale,
5193                    radius.get_bottom_right() * scale,
5194                    radius.get_bottom_left() * scale,
5195                ];
5196                let halo: Rect = Rect::new(
5197                    (snapped.get_x() - phys_blur).max(0.0),
5198                    (snapped.get_y() - phys_blur).max(0.0),
5199                    (snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
5200                    (snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
5201                );
5202                backdrop_blurs.push(GpuBackdropBlurPass {
5203                    bounds: snapped,
5204                    input_bounds: halo,
5205                    clip_rect: active_clip,
5206                    radii: radii_px,
5207                    blur_radius: phys_blur,
5208                    layer_id: active_layer_id,
5209                });
5210                active_layer_id = active_layer_id.saturating_add(1);
5211            }
5212            DrawCommand::TextRun { rect, text, style } => {
5213                if text.is_empty()
5214                    || active_clip.get_width() <= 0.0
5215                    || active_clip.get_height() <= 0.0
5216                {
5217                    continue;
5218                }
5219                if let Some(atlas) = glyph_atlas.as_deref_mut() {
5220                    let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
5221                    let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
5222                        text,
5223                        *style,
5224                        Some(rect.get_width().max(1.0)),
5225                    );
5226                    let line_h: f32 = meas.get_line_height_px() * scale;
5227                    let letter_sp: f32 = style.get_letter_spacing() * scale;
5228                    let rect_w_px: f32 = rect.get_width() * scale;
5229                    let color_rgba: u32 = GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
5230                    let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
5231                        PrimKind::GlyphAlpha8,
5232                        0,
5233                        0,
5234                        active_layer_id,
5235                    );
5236                    let mut line_glyphs: Vec<(Option<GlyphKey>, u32, u32, f32)> = Vec::new();
5237                    for (line_idx, line) in meas.get_lines().iter().enumerate() {
5238                        line_glyphs.clear();
5239                        let mut line_w_px: f32 = 0.0;
5240                        for ch in line.get_text().chars() {
5241                            if ch == ' ' || ch == '\t' {
5242                                let sp_adv: f32 = measure_char_advance(ch, *style) * scale;
5243                                line_glyphs.push((None, 0, 0, sp_adv));
5244                                line_w_px += sp_adv;
5245                                continue;
5246                            }
5247                            let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_px, *style);
5248                            let (gw, gh, adv): (u32, u32, f32) = {
5249                                let green_val: &RasterizedGlyph = match font_provider {
5250                                    Some(fp) => atlas.get_or_rasterize_with(key, fp),
5251                                    None => atlas.get_or_rasterize(key),
5252                                };
5253                                (
5254                                    green_val.get_width(),
5255                                    green_val.get_height(),
5256                                    (green_val.get_advance() as f32).max(1.0) + letter_sp,
5257                                )
5258                            };
5259                            line_glyphs.push((Some(key), gw, gh, adv));
5260                            line_w_px += adv;
5261                        }
5262                        let fit_scale: f32 = if rect_w_px > 1.0 && line_w_px > rect_w_px + 1.0 {
5263                            (rect_w_px / line_w_px).clamp(0.72, 1.0)
5264                        } else {
5265                            1.0
5266                        };
5267                        let fitted_line_w: f32 = line_w_px * fit_scale;
5268                        let align_offset: f32 = match style.get_align() {
5269                            TextAlign::Center => ((rect_w_px - fitted_line_w) * 0.5).max(0.0),
5270                            TextAlign::Right => (rect_w_px - fitted_line_w).max(0.0),
5271                            TextAlign::Left => 0.0,
5272                        };
5273                        let base_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h;
5274                        let mut pen_x: f32 = rect.get_x() * scale + align_offset;
5275                        for &(key_opt, gw, gh, adv) in line_glyphs.iter() {
5276                            if let Some(key) = key_opt
5277                                && gw > 0
5278                                && gh > 0
5279                            {
5280                                let y_off: f32 = ((line_h - (gh as f32)) * 0.5).round();
5281                                let prim_idx: usize = primitives.len();
5282                                let prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
5283                                    rect: [
5284                                        pen_x.round(),
5285                                        (base_y + y_off).round(),
5286                                        gw as f32,
5287                                        gh as f32,
5288                                    ],
5289                                    clip_rect: clip_arr,
5290                                    color_rgba,
5291                                    aux_color_rgba: 0,
5292                                    uv_rect: [0, 0, 0, 0],
5293                                    radii_border: [0; 4],
5294                                    kind_flags,
5295                                    extra_param: 0,
5296                                };
5297                                push_direct_gpu_primitive(
5298                                    &mut primitives,
5299                                    &mut draw_ranges,
5300                                    prim,
5301                                    active_clip,
5302                                    phys_w,
5303                                    phys_h,
5304                                );
5305                                glyph_fixups.push((prim_idx, key));
5306                            }
5307                            pen_x += adv * fit_scale;
5308                        }
5309                    }
5310                } else {
5311                    let queue_entry: GpuQuadInstance = GpuQuadInstance {
5312                        rect: [
5313                            rect.get_x() * scale,
5314                            rect.get_y() * scale,
5315                            rect.get_width() * scale,
5316                            rect.get_height() * scale,
5317                        ],
5318                        clip: clip_arr,
5319                        color: style.get_color().to_f32_array(),
5320                        secondary_color: [0.0; 4],
5321                        radii: [0.0; 4],
5322                        stroke_or_blur: style.get_font_size() * scale,
5323                        angle_rad: 0.0,
5324                        kind: GpuPrimitiveKind::Glyph as u32,
5325                        reserved: text.chars().count() as u32,
5326                    };
5327                    push_direct_gpu_primitive(
5328                        &mut primitives,
5329                        &mut draw_ranges,
5330                        GpuPrimitiveInstance::from_quad_instance(&queue_entry, 0, active_layer_id),
5331                        active_clip,
5332                        phys_w,
5333                        phys_h,
5334                    );
5335                }
5336            }
5337            DrawCommand::TextCaret {
5338                text_rect,
5339                content_rect,
5340                text,
5341                style,
5342                caret_height,
5343                color,
5344                multiline,
5345            } => {
5346                if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
5347                    continue;
5348                }
5349                let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
5350                    text,
5351                    *style,
5352                    if *multiline {
5353                        Some(content_rect.get_width().max(1.0))
5354                    } else {
5355                        None
5356                    },
5357                );
5358                let last_w_phys: f32 = if let Some(atlas) = glyph_atlas.as_deref_mut() {
5359                    let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
5360                    let letter_sp: f32 = style.get_letter_spacing() * scale;
5361                    if let Some(line) = meas.get_lines().last() {
5362                        let mut acc: f32 = 0.0;
5363                        for ch in line.get_text().chars() {
5364                            if ch == ' ' || ch == '\t' {
5365                                acc += measure_char_advance(ch, *style) * scale + letter_sp;
5366                            } else {
5367                                let key: GlyphKey =
5368                                    GlyphKey::from_text_style(ch, phys_font_px, *style);
5369                                let geometry_val: &RasterizedGlyph = match font_provider {
5370                                    Some(fp) => atlas.get_or_rasterize_with(key, fp),
5371                                    None => atlas.get_or_rasterize(key),
5372                                };
5373                                acc += (geometry_val.get_advance() as f32).max(1.0) + letter_sp;
5374                            }
5375                        }
5376                        acc
5377                    } else {
5378                        0.0
5379                    }
5380                } else {
5381                    meas.get_lines()
5382                        .last()
5383                        .map(TextLine::get_width)
5384                        .unwrap_or(0.0)
5385                        * scale
5386                };
5387                let line_idx: usize = meas.get_lines().len().saturating_sub(1);
5388                let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
5389                let caret_x_phys: f32 =
5390                    (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys).clamp(
5391                        content_rect.get_x() * scale,
5392                        ((content_rect.right() - 2.0) * scale).max(content_rect.get_x() * scale),
5393                    );
5394                let caret_y: f32 = if *multiline {
5395                    (content_rect.get_y()
5396                        + (line_idx as f32) * meas.get_line_height_px()
5397                        + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
5398                    .clamp(
5399                        content_rect.get_y(),
5400                        (content_rect.bottom() - caret_height).max(content_rect.get_y()),
5401                    )
5402                } else {
5403                    content_rect.get_y()
5404                        + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
5405                };
5406                let query_val_primary: GpuQuadInstance = GpuQuadInstance {
5407                    rect: [
5408                        caret_x_phys.round(),
5409                        (caret_y * scale).round(),
5410                        (1.5 * scale).max(1.0),
5411                        (caret_height * scale).max(2.0),
5412                    ],
5413                    clip: clip_arr,
5414                    color: color.to_f32_array(),
5415                    secondary_color: [0.0; 4],
5416                    radii: [0.5 * scale; 4],
5417                    stroke_or_blur: 0.0,
5418                    angle_rad: 0.0,
5419                    kind: GpuPrimitiveKind::RoundedRect as u32,
5420                    reserved: 0,
5421                };
5422                push_direct_gpu_primitive(
5423                    &mut primitives,
5424                    &mut draw_ranges,
5425                    GpuPrimitiveInstance::from_quad_instance(
5426                        &query_val_primary,
5427                        0,
5428                        active_layer_id,
5429                    ),
5430                    active_clip,
5431                    phys_w,
5432                    phys_h,
5433                );
5434            }
5435            DrawCommand::Image {
5436                rect,
5437                buffer,
5438                radius,
5439            } => {
5440                let snapped: Rect = snap_physical_rect(*rect, scale);
5441                let img_w: u32 = buffer.get_width();
5442                let img_h: u32 = buffer.get_height();
5443                if img_w == 0
5444                    || img_h == 0
5445                    || snapped.get_width() <= 0.0
5446                    || snapped.get_height() <= 0.0
5447                {
5448                    continue;
5449                }
5450                let img_idx: usize = image_entries.len();
5451                image_entries.push(DirectGpuImageSlice {
5452                    src_w: img_w,
5453                    src_h: img_h,
5454                    pixels: buffer.get_pixels(),
5455                    crop: PixelDirtyRect::new(0, 0, img_w, img_h),
5456                });
5457                let query_val_secondary: GpuQuadInstance = GpuQuadInstance {
5458                    rect: [
5459                        snapped.get_x(),
5460                        snapped.get_y(),
5461                        snapped.get_width(),
5462                        snapped.get_height(),
5463                    ],
5464                    clip: clip_arr,
5465                    color: [1.0, 1.0, 1.0, 1.0],
5466                    secondary_color: [0.0; 4],
5467                    radii: [
5468                        radius.get_top_left() * scale,
5469                        radius.get_top_right() * scale,
5470                        radius.get_bottom_right() * scale,
5471                        radius.get_bottom_left() * scale,
5472                    ],
5473                    stroke_or_blur: 0.0,
5474                    angle_rad: 0.0,
5475                    kind: GpuPrimitiveKind::TexturedQuad as u32,
5476                    reserved: 0,
5477                };
5478                let prim_idx: usize = primitives.len();
5479                push_direct_gpu_primitive(
5480                    &mut primitives,
5481                    &mut draw_ranges,
5482                    GpuPrimitiveInstance::from_quad_instance(
5483                        &query_val_secondary,
5484                        0,
5485                        active_layer_id,
5486                    ),
5487                    active_clip,
5488                    phys_w,
5489                    phys_h,
5490                );
5491                image_fixups.push((prim_idx, img_idx));
5492            }
5493            DrawCommand::SharedImage {
5494                rect,
5495                width,
5496                height,
5497                pixels,
5498                radius,
5499            } => {
5500                let snapped: Rect = snap_physical_rect(*rect, scale);
5501                if *width == 0
5502                    || *height == 0
5503                    || snapped.get_width() <= 0.0
5504                    || snapped.get_height() <= 0.0
5505                {
5506                    continue;
5507                }
5508                let img_idx: usize = image_entries.len();
5509                image_entries.push(DirectGpuImageSlice {
5510                    src_w: *width,
5511                    src_h: *height,
5512                    pixels: pixels.as_slice(),
5513                    crop: PixelDirtyRect::new(0, 0, *width, *height),
5514                });
5515                let query_val_next: GpuQuadInstance = GpuQuadInstance {
5516                    rect: [
5517                        snapped.get_x(),
5518                        snapped.get_y(),
5519                        snapped.get_width(),
5520                        snapped.get_height(),
5521                    ],
5522                    clip: clip_arr,
5523                    color: [1.0, 1.0, 1.0, 1.0],
5524                    secondary_color: [0.0; 4],
5525                    radii: [
5526                        radius.get_top_left() * scale,
5527                        radius.get_top_right() * scale,
5528                        radius.get_bottom_right() * scale,
5529                        radius.get_bottom_left() * scale,
5530                    ],
5531                    stroke_or_blur: 0.0,
5532                    angle_rad: 0.0,
5533                    kind: GpuPrimitiveKind::TexturedQuad as u32,
5534                    reserved: 0,
5535                };
5536                let prim_idx: usize = primitives.len();
5537                push_direct_gpu_primitive(
5538                    &mut primitives,
5539                    &mut draw_ranges,
5540                    GpuPrimitiveInstance::from_quad_instance(&query_val_next, 0, active_layer_id),
5541                    active_clip,
5542                    phys_w,
5543                    phys_h,
5544                );
5545                image_fixups.push((prim_idx, img_idx));
5546            }
5547            DrawCommand::SpriteRegion {
5548                rect,
5549                buffer,
5550                src_rect,
5551                tint,
5552            } => {
5553                let snapped: Rect = snap_physical_rect(*rect, scale);
5554                let img_w: u32 = buffer.get_width();
5555                let img_h: u32 = buffer.get_height();
5556                let sx: u32 = (src_rect.get_x().max(0.0).floor() as u32).min(img_w);
5557                let sy: u32 = (src_rect.get_y().max(0.0).floor() as u32).min(img_h);
5558                let stroke_width: u32 =
5559                    (src_rect.get_width().max(1.0).ceil() as u32).min(img_w.saturating_sub(sx));
5560                let sh: u32 =
5561                    (src_rect.get_height().max(1.0).ceil() as u32).min(img_h.saturating_sub(sy));
5562                if stroke_width == 0
5563                    || sh == 0
5564                    || snapped.get_width() <= 0.0
5565                    || snapped.get_height() <= 0.0
5566                {
5567                    continue;
5568                }
5569                let img_idx: usize = image_entries.len();
5570                image_entries.push(DirectGpuImageSlice {
5571                    src_w: img_w,
5572                    src_h: img_h,
5573                    pixels: buffer.get_pixels(),
5574                    crop: PixelDirtyRect::new(sx, sy, stroke_width, sh),
5575                });
5576                let query_val_alt: GpuQuadInstance = GpuQuadInstance {
5577                    rect: [
5578                        snapped.get_x(),
5579                        snapped.get_y(),
5580                        snapped.get_width(),
5581                        snapped.get_height(),
5582                    ],
5583                    clip: clip_arr,
5584                    color: tint.to_f32_array(),
5585                    secondary_color: [0.0; 4],
5586                    radii: [0.0; 4],
5587                    stroke_or_blur: 0.0,
5588                    angle_rad: 0.0,
5589                    kind: GpuPrimitiveKind::TexturedQuad as u32,
5590                    reserved: 1,
5591                };
5592                let prim_idx: usize = primitives.len();
5593                push_direct_gpu_primitive(
5594                    &mut primitives,
5595                    &mut draw_ranges,
5596                    GpuPrimitiveInstance::from_quad_instance(&query_val_alt, 0, active_layer_id),
5597                    active_clip,
5598                    phys_w,
5599                    phys_h,
5600                );
5601                image_fixups.push((prim_idx, img_idx));
5602            }
5603            DrawCommand::ExternalSurface { rect, radius } => {
5604                let snapped: Rect = snap_physical_rect(*rect, scale);
5605                if snapped.get_width() <= 0.0 || snapped.get_height() <= 0.0 {
5606                    continue;
5607                }
5608                let ext_quad: GpuQuadInstance = GpuQuadInstance {
5609                    rect: [
5610                        snapped.get_x(),
5611                        snapped.get_y(),
5612                        snapped.get_width(),
5613                        snapped.get_height(),
5614                    ],
5615                    clip: clip_arr,
5616                    color: [1.0, 1.0, 1.0, 1.0],
5617                    secondary_color: [0.0; 4],
5618                    radii: [
5619                        radius.get_top_left() * scale,
5620                        radius.get_top_right() * scale,
5621                        radius.get_bottom_right() * scale,
5622                        radius.get_bottom_left() * scale,
5623                    ],
5624                    stroke_or_blur: 0.0,
5625                    angle_rad: 0.0,
5626                    kind: GpuPrimitiveKind::ExternalSurface as u32,
5627                    reserved: 0,
5628                };
5629                push_direct_gpu_primitive(
5630                    &mut primitives,
5631                    &mut draw_ranges,
5632                    GpuPrimitiveInstance::from_quad_instance(&ext_quad, 3, active_layer_id),
5633                    active_clip,
5634                    phys_w,
5635                    phys_h,
5636                );
5637            }
5638            DrawCommand::Circle {
5639                center,
5640                radius,
5641                color,
5642            } => {
5643                let red_val: f32 = radius * scale;
5644                let pad: f32 = 1.5;
5645                let extent: f32 = red_val + pad;
5646                let query_val_inner: GpuQuadInstance = GpuQuadInstance {
5647                    rect: [
5648                        center.get_x() * scale - extent,
5649                        center.get_y() * scale - extent,
5650                        extent * 2.0,
5651                        extent * 2.0,
5652                    ],
5653                    clip: clip_arr,
5654                    color: color.to_f32_array(),
5655                    secondary_color: [0.0; 4],
5656                    radii: [red_val; 4],
5657                    stroke_or_blur: red_val,
5658                    angle_rad: 0.0,
5659                    kind: GpuPrimitiveKind::Circle as u32,
5660                    reserved: 0,
5661                };
5662                push_direct_gpu_primitive(
5663                    &mut primitives,
5664                    &mut draw_ranges,
5665                    GpuPrimitiveInstance::from_quad_instance(&query_val_inner, 0, active_layer_id),
5666                    active_clip,
5667                    phys_w,
5668                    phys_h,
5669                );
5670            }
5671            DrawCommand::Line {
5672                from,
5673                to,
5674                color,
5675                width,
5676            } => {
5677                let fx0: f32 = from.get_x() * scale;
5678                let fy0: f32 = from.get_y() * scale;
5679                let fx1: f32 = to.get_x() * scale;
5680                let fy1: f32 = to.get_y() * scale;
5681                let dx: f32 = fx1 - fx0;
5682                let dy: f32 = fy1 - fy0;
5683                let stroke_px: f32 = (width * scale).max(1.0);
5684                let pad: f32 = stroke_px * 0.5 + 1.5;
5685                let min_x: f32 = fx0.min(fx1) - pad;
5686                let min_y: f32 = fy0.min(fy1) - pad;
5687                let max_x: f32 = fx0.max(fx1) + pad;
5688                let max_y: f32 = fy0.max(fy1) + pad;
5689                let query_val_local: GpuQuadInstance = GpuQuadInstance {
5690                    rect: [
5691                        min_x,
5692                        min_y,
5693                        (max_x - min_x).max(2.0),
5694                        (max_y - min_y).max(2.0),
5695                    ],
5696                    clip: clip_arr,
5697                    color: color.to_f32_array(),
5698                    secondary_color: [0.0; 4],
5699                    radii: [fx0, fy0, fx1, fy1],
5700                    stroke_or_blur: stroke_px,
5701                    angle_rad: dy.atan2(dx),
5702                    kind: GpuPrimitiveKind::Line as u32,
5703                    reserved: 0,
5704                };
5705                push_direct_gpu_primitive(
5706                    &mut primitives,
5707                    &mut draw_ranges,
5708                    GpuPrimitiveInstance::from_quad_instance(&query_val_local, 0, active_layer_id),
5709                    active_clip,
5710                    phys_w,
5711                    phys_h,
5712                );
5713            }
5714            DrawCommand::Triangle { p0, p1, p2, color } => {
5715                let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
5716                let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
5717                let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
5718                let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
5719                let query_val_cur: GpuQuadInstance = GpuQuadInstance {
5720                    rect: [
5721                        min_x,
5722                        min_y,
5723                        (max_x - min_x).max(2.0),
5724                        (max_y - min_y).max(2.0),
5725                    ],
5726                    clip: clip_arr,
5727                    color: color.to_f32_array(),
5728                    secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
5729                    radii: [
5730                        p1.get_x() * scale,
5731                        p1.get_y() * scale,
5732                        p2.get_x() * scale,
5733                        p2.get_y() * scale,
5734                    ],
5735                    stroke_or_blur: 0.0,
5736                    angle_rad: 0.0,
5737                    kind: GpuPrimitiveKind::Triangle as u32,
5738                    reserved: 3,
5739                };
5740                push_direct_gpu_primitive(
5741                    &mut primitives,
5742                    &mut draw_ranges,
5743                    GpuPrimitiveInstance::from_quad_instance(&query_val_cur, 0, active_layer_id),
5744                    active_clip,
5745                    phys_w,
5746                    phys_h,
5747                );
5748            }
5749        }
5750        if active_rounded_bits != 0 && primitives.len() > cmd_prim_start {
5751            for prim_item in primitives[cmd_prim_start..].iter_mut() {
5752                let quad_rect: [f32; 4] = prim_item.get_rect();
5753                let safe_non_empty: bool =
5754                    safe_inner_clip.get_width() > 0.0 && safe_inner_clip.get_height() > 0.0;
5755                let inside_safe: bool = safe_non_empty
5756                    && quad_rect[0] >= safe_inner_clip.get_x()
5757                    && quad_rect[1] >= safe_inner_clip.get_y()
5758                    && (quad_rect[0] + quad_rect[2]) <= safe_inner_clip.right()
5759                    && (quad_rect[1] + quad_rect[3]) <= safe_inner_clip.bottom();
5760                if !inside_safe {
5761                    *prim_item = prim_item.with_rounded_clip_bits(active_rounded_bits);
5762                }
5763            }
5764        }
5765    }
5766    let mut glyph_r8_atlas: Option<DirectGpuAtlasUpload> = None;
5767    if let Some(atlas) = glyph_atlas.as_deref()
5768        && (!glyph_fixups.is_empty() || atlas.get_revision() != last_glyph_revision)
5769        && !atlas.is_empty()
5770    {
5771        let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
5772        let aw: u32 = packed.get_width();
5773        let ah: u32 = packed.get_height();
5774        for &(prim_idx, key) in glyph_fixups.iter() {
5775            if let Some(&(gx, gy, gw, gh)) = packed.get_regions().get(&key) {
5776                primitives[prim_idx].set_uv_rect(encode_atlas_uv_rect(aw, ah, gx, gy, gw, gh));
5777            }
5778        }
5779        if packed.get_revision() != last_glyph_revision {
5780            let rgba: &[u8] = packed.get_pixels().as_slice();
5781            let mut r8: Vec<u8> = Vec::with_capacity((aw as usize).saturating_mul(ah as usize));
5782            for px in rgba.as_chunks::<4>().0 {
5783                r8.push(px[3]);
5784            }
5785            glyph_r8_atlas = Some(DirectGpuAtlasUpload {
5786                width: aw,
5787                height: ah,
5788                revision: packed.get_revision(),
5789                pixels: r8,
5790            });
5791        }
5792    }
5793    let (image_rgba8_atlas, img_uvs): (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) =
5794        pack_frame_image_atlas(&image_entries, display_list.fast_hash());
5795    for &(prim_idx, img_idx) in image_fixups.iter() {
5796        if let Some(&uv) = img_uvs.get(img_idx) {
5797            primitives[prim_idx].set_uv_rect(uv);
5798        }
5799    }
5800    let glyph_bytes: usize = glyph_r8_atlas
5801        .as_ref()
5802        .map(|alpha_val: &DirectGpuAtlasUpload| alpha_val.get_pixels().len())
5803        .unwrap_or(0);
5804    let image_bytes: usize = image_rgba8_atlas
5805        .as_ref()
5806        .map(|first_val: &DirectGpuAtlasUpload| first_val.get_pixels().len())
5807        .unwrap_or(0);
5808    let instance_upload_bytes: usize = primitives
5809        .len()
5810        .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES)
5811        .saturating_add(glyph_bytes)
5812        .saturating_add(image_bytes);
5813    DirectGpuFrameBatch {
5814        viewport_width: phys_w,
5815        viewport_height: phys_h,
5816        clear_rgba,
5817        primitives,
5818        draw_ranges,
5819        backdrop_blurs,
5820        glyph_r8_atlas,
5821        image_rgba8_atlas,
5822        instance_upload_bytes,
5823        cpu_mirror_active: false,
5824        upload_strategy: MobileUploadStrategy::DirectGpu,
5825    }
5826}
5827
5828/// Returns the preferred native hardware `GraphicsBackend` for the active compilation target.
5829///
5830/// # Returns
5831///
5832/// - `GraphicsBackend` - Host-native GPU graphics backend (`Metal`, `Direct3D12`, `Vulkan`, `WebGl2`, or `Headless`).
5833#[must_use]
5834pub const fn default_native_gpu_backend() -> GraphicsBackend {
5835    #[cfg(any(target_os = "macos", target_os = "ios"))]
5836    {
5837        GraphicsBackend::Metal
5838    }
5839    #[cfg(target_os = "windows")]
5840    {
5841        GraphicsBackend::Direct3D12
5842    }
5843    #[cfg(any(target_os = "linux", target_os = "android"))]
5844    {
5845        GraphicsBackend::Vulkan
5846    }
5847    #[cfg(target_arch = "wasm32")]
5848    {
5849        GraphicsBackend::WebGl2
5850    }
5851    #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
5852    #[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
5853    {
5854        GraphicsBackend::Headless
5855    }
5856}
5857
5858/// Computes a deterministic 64-bit FNV-1a cache digest over a shader program's source pair and target GPU device label.
5859///
5860/// # Arguments
5861///
5862/// - `&str` - Probed GPU adapter or fallback device label.
5863/// - `&str` - Primary shader source string.
5864/// - `&str` - Optional secondary fragment shader source string.
5865///
5866/// # Returns
5867///
5868/// - `u64` - Deterministic 64-bit FNV-1a content key.
5869#[must_use]
5870pub fn shader_program_cache_hash(device_name: &str, primary_src: &str, secondary_src: &str) -> u64 {
5871    let mut hash: u64 = FNV1A_OFFSET_BASIS;
5872    for chunk in [
5873        device_name.as_bytes(),
5874        primary_src.as_bytes(),
5875        secondary_src.as_bytes(),
5876    ]
5877    .iter()
5878    {
5879        for &byte in chunk.iter() {
5880            hash ^= byte as u64;
5881            hash = hash.wrapping_mul(FNV1A_PRIME);
5882        }
5883    }
5884    hash
5885}
5886
5887/// Executes cold shader pipeline precompilation and optical LUT warm-up for `backend` without consulting the outer report cache.
5888///
5889/// # Arguments
5890///
5891/// - `GraphicsBackend` - Graphics API backend to precompile shaders for.
5892///
5893/// # Returns
5894///
5895/// - `ShaderPrecompileReport` - Measured compilation telemetry across all built-in shader programs.
5896fn run_shader_precompile_uncached(backend: GraphicsBackend) -> ShaderPrecompileReport {
5897    #[cfg(not(target_arch = "wasm32"))]
5898    let total_start: Instant = Instant::now();
5899    let _: Vec<u8> = build_aces_srgb_lut();
5900    let lang_label: &str = ShaderProgramId::language_for_backend(backend);
5901    #[cfg(any(target_os = "macos", target_os = "ios"))]
5902    if backend == GraphicsBackend::Metal {
5903        let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
5904        let device_name: String = cached.adapter.get_device_name().clone();
5905        let hardware_gpu: bool = cached.adapter.get_hardware_verified();
5906        let archive_enabled: bool = cached.binary_archive_enabled;
5907        let archive_hit: bool = cached.binary_archive_hit;
5908        let handles_and_us: [(ShaderProgramId, usize, u64); 4] = [
5909            (
5910                ShaderProgramId::UiUber,
5911                cached.pipeline,
5912                cached.ui_compile_us,
5913            ),
5914            (
5915                ShaderProgramId::BackdropBlur,
5916                if cached.blur_pipeline != 0 && cached.blur_up_pipeline != 0 {
5917                    cached.blur_pipeline
5918                } else {
5919                    0
5920                },
5921                cached.blur_compile_us,
5922            ),
5923            (
5924                ShaderProgramId::Engine3dPbr,
5925                cached.engine3d_pipeline,
5926                cached.engine3d_compile_us,
5927            ),
5928            (
5929                ShaderProgramId::FluidOceanOptical,
5930                cached.ocean_pipeline,
5931                cached.ocean_compile_us,
5932            ),
5933        ];
5934        let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(handles_and_us.len());
5935        let mut ready_count: usize = 0;
5936        let mut hw_compiled: usize = 0;
5937        for (program, pso_handle, compile_us) in handles_and_us {
5938            let (src_a, src_b): (&str, &str) = program.source_pair(backend);
5939            let src_bytes: usize = src_a.len().saturating_add(src_b.len());
5940            let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
5941            let state: ShaderCompileState = if pso_handle != 0 {
5942                hw_compiled += 1;
5943                ready_count += 1;
5944                if archive_hit {
5945                    ShaderCompileState::LoadedFromBinaryArchive
5946                } else {
5947                    ShaderCompileState::CompiledHardware
5948                }
5949            } else if !src_a.is_empty() {
5950                ready_count += 1;
5951                ShaderCompileState::ValidatedFallback
5952            } else {
5953                ShaderCompileState::Failed
5954            };
5955            entries.push(ShaderProgramCacheEntry {
5956                program,
5957                name: program.label().to_string(),
5958                language: lang_label.to_string(),
5959                state,
5960                source_hash: src_hash,
5961                source_bytes: src_bytes,
5962                compile_time_us: compile_us,
5963                pipeline_ready: state.is_ready(),
5964            });
5965        }
5966        let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
5967        let cold_us: u64 = cached.total_compile_us.max(elapsed_us);
5968        return ShaderPrecompileReport {
5969            backend,
5970            device_name,
5971            hardware_gpu,
5972            binary_archive_enabled: archive_enabled,
5973            binary_archive_hit: archive_hit,
5974            cache_hit: false,
5975            total_programs: entries.len(),
5976            ready_programs: ready_count,
5977            hardware_compiled_programs: hw_compiled,
5978            cold_compile_us: cold_us,
5979            last_call_us: elapsed_us,
5980            entries,
5981        };
5982    }
5983    let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
5984    let device_name: String = probed.adapter.get_device_name().clone();
5985    let hardware_gpu: bool = probed.adapter.get_hardware_verified();
5986    let hw_shader_ok: bool = probed.adapter.get_shader_compiled();
5987    let has_compiled_pso: bool = probed.device_handle != 0 && probed.pipeline_handle != 0;
5988    for handle in probed.scene_pbr_pipelines.iter() {
5989        release_native_gpu_object(*handle);
5990    }
5991    release_native_gpu_object(probed.dummy_r8_tex);
5992    release_native_gpu_object(probed.dummy_rgba8_tex);
5993    release_native_gpu_object(probed.ocean_pipeline_handle);
5994    release_native_gpu_object(probed.engine3d_pipeline_handle);
5995    release_native_gpu_object(probed.blur_up_pipeline_handle);
5996    release_native_gpu_object(probed.blur_pipeline_handle);
5997    release_native_gpu_object(probed.pipeline_handle);
5998    release_native_gpu_handles(
5999        probed.device_handle,
6000        probed.queue_handle,
6001        probed.library_handle,
6002    );
6003    let programs: [ShaderProgramId; 4] = ShaderProgramId::all();
6004    let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(programs.len());
6005    let mut ready_count: usize = 0;
6006    let mut hw_compiled: usize = 0;
6007    for program in programs {
6008        #[cfg(not(target_arch = "wasm32"))]
6009        let item_start: Instant = Instant::now();
6010        let (src_a, src_b): (&str, &str) = program.source_pair(backend);
6011        let src_bytes: usize = src_a.len().saturating_add(src_b.len());
6012        let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
6013        let is_valid: bool = !src_a.is_empty();
6014        let state: ShaderCompileState =
6015            if has_compiled_pso && hardware_gpu && hw_shader_ok && is_valid {
6016                hw_compiled += 1;
6017                ready_count += 1;
6018                ShaderCompileState::CompiledHardware
6019            } else if is_valid {
6020                ready_count += 1;
6021                ShaderCompileState::ValidatedFallback
6022            } else {
6023                ShaderCompileState::Failed
6024            };
6025        #[cfg(not(target_arch = "wasm32"))]
6026        let item_us: u64 = item_start.elapsed().as_micros() as u64;
6027        #[cfg(target_arch = "wasm32")]
6028        let item_us: u64 = 0;
6029        entries.push(ShaderProgramCacheEntry {
6030            program,
6031            name: program.label().to_string(),
6032            language: lang_label.to_string(),
6033            state,
6034            source_hash: src_hash,
6035            source_bytes: src_bytes,
6036            compile_time_us: item_us,
6037            pipeline_ready: state.is_ready(),
6038        });
6039    }
6040    #[cfg(not(target_arch = "wasm32"))]
6041    let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
6042    #[cfg(target_arch = "wasm32")]
6043    let elapsed_us: u64 = 0;
6044    ShaderPrecompileReport {
6045        backend,
6046        device_name,
6047        hardware_gpu,
6048        binary_archive_enabled: false,
6049        binary_archive_hit: false,
6050        cache_hit: false,
6051        total_programs: entries.len(),
6052        ready_programs: ready_count,
6053        hardware_compiled_programs: hw_compiled,
6054        cold_compile_us: elapsed_us,
6055        last_call_us: elapsed_us,
6056        entries,
6057    }
6058}
6059
6060/// Precompiles all built-in GPU shader programs (`UiUber`, `BackdropBlur`, `Engine3dPbr`, `FluidOceanOptical`) and warms optical LUTs for `backend`, returning cached results in `< 5 us` on subsequent calls.
6061///
6062/// # Arguments
6063///
6064/// - `GraphicsBackend` - Target graphics backend (`default_native_gpu_backend()` for active OS hardware).
6065///
6066/// # Returns
6067///
6068/// - `ShaderPrecompileReport` - Detailed precompilation status, cache-hit flag, and cold vs warm timing telemetry.
6069#[must_use]
6070pub fn precompile_shaders(backend: GraphicsBackend) -> ShaderPrecompileReport {
6071    #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
6072    {
6073        let call_start: Instant = Instant::now();
6074        let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
6075            SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
6076        if let Ok(guard) = cache_mutex.lock()
6077            && let Some(existing) = guard.get(&backend)
6078        {
6079            let mut hit_report: ShaderPrecompileReport = existing.clone();
6080            hit_report.set_cache_hit(true);
6081            hit_report.set_last_call_us(call_start.elapsed().as_micros() as u64);
6082            return hit_report;
6083        }
6084        let fresh: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
6085        if let Ok(mut guard) = cache_mutex.lock() {
6086            let _: Option<ShaderPrecompileReport> = guard.insert(backend, fresh.clone());
6087        }
6088        fresh
6089    }
6090    #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
6091    {
6092        run_shader_precompile_uncached(backend)
6093    }
6094}
6095
6096/// Launches non-blocking background-thread GPU shader precompilation for `backend` to eliminate 40-180ms cold-start main-thread frame hitches.
6097///
6098/// # Arguments
6099///
6100/// - `GraphicsBackend` - Target graphics backend to warm on a background worker thread.
6101pub fn precompile_shaders_async(backend: GraphicsBackend) {
6102    #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
6103    {
6104        let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
6105            SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
6106        if let Ok(guard) = cache_mutex.lock()
6107            && guard.contains_key(&backend)
6108        {
6109            return;
6110        }
6111        if SHADER_PRECOMPILE_IN_FLIGHT
6112            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
6113            .is_err()
6114        {
6115            return;
6116        }
6117        let spawn_result: io::Result<JoinHandle<()>> = Builder::new()
6118            .name("euv-shader-precompile".to_string())
6119            .spawn(move || {
6120                let _: ShaderPrecompileReport = precompile_shaders(backend);
6121                SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
6122            });
6123        if spawn_result.is_err() {
6124            SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
6125            let _: ShaderPrecompileReport = precompile_shaders(backend);
6126        }
6127    }
6128    #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
6129    {
6130        let _: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
6131    }
6132}
6133
6134/// Returns the latest cached `ShaderPrecompileReport` without triggering compilation if precompilation has not completed yet.
6135///
6136/// # Returns
6137///
6138/// - `Option<ShaderPrecompileReport>` - Cached precompile report prioritizing the active native GPU backend, or `None`.
6139#[must_use]
6140pub fn shader_precompile_status() -> Option<ShaderPrecompileReport> {
6141    #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
6142    {
6143        let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
6144            SHADER_PRECOMPILE_CACHE.get()?;
6145        let guard: MutexGuard<'_, HashMap<GraphicsBackend, ShaderPrecompileReport>> =
6146            cache_mutex.lock().ok()?;
6147        let native_backend: GraphicsBackend = default_native_gpu_backend();
6148        if let Some(native_report) = guard.get(&native_backend) {
6149            return Some(native_report.clone());
6150        }
6151        guard.values().next().cloned()
6152    }
6153    #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
6154    {
6155        None
6156    }
6157}
6158
6159/// Returns `true` while an asynchronous background shader precompilation worker thread is actively compiling PSOs.
6160///
6161/// # Returns
6162///
6163/// - `bool` - `true` when background precompilation is currently in flight.
6164#[must_use]
6165pub fn is_shader_precompile_in_flight() -> bool {
6166    #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
6167    {
6168        SHADER_PRECOMPILE_IN_FLIGHT.load(Ordering::Acquire)
6169    }
6170    #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
6171    {
6172        false
6173    }
6174}