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            dummy_r8_tex: 0,
43            dummy_rgba8_tex: 0,
44        };
45    }
46    #[cfg(any(target_os = "macos", target_os = "ios"))]
47    {
48        probe_apple_metal_full(backend)
49    }
50    #[cfg(target_os = "windows")]
51    {
52        let (adapter, device_handle, queue_handle, library_handle): (
53            GpuAdapterInfo,
54            usize,
55            usize,
56            usize,
57        ) = probe_windows_d3d12(backend);
58        NativeGpuProbeOutput {
59            adapter,
60            device_handle,
61            queue_handle,
62            library_handle,
63            pipeline_handle: 0,
64            blur_pipeline_handle: 0,
65            dummy_r8_tex: 0,
66            dummy_rgba8_tex: 0,
67        }
68    }
69    #[cfg(any(target_os = "linux", target_os = "android"))]
70    {
71        let (adapter, device_handle, queue_handle, library_handle): (
72            GpuAdapterInfo,
73            usize,
74            usize,
75            usize,
76        ) = probe_vulkan_runtime(backend);
77        NativeGpuProbeOutput {
78            adapter,
79            device_handle,
80            queue_handle,
81            library_handle,
82            pipeline_handle: 0,
83            blur_pipeline_handle: 0,
84            dummy_r8_tex: 0,
85            dummy_rgba8_tex: 0,
86        }
87    }
88    #[cfg(target_arch = "wasm32")]
89    {
90        NativeGpuProbeOutput {
91            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
92            device_handle: 0,
93            queue_handle: 0,
94            library_handle: 0,
95            pipeline_handle: 0,
96            blur_pipeline_handle: 0,
97            dummy_r8_tex: 0,
98            dummy_rgba8_tex: 0,
99        }
100    }
101    #[cfg(not(any(target_arch = "wasm32", unix, windows)))]
102    {
103        NativeGpuProbeOutput {
104            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
105            device_handle: 0,
106            queue_handle: 0,
107            library_handle: 0,
108            pipeline_handle: 0,
109            blur_pipeline_handle: 0,
110            dummy_r8_tex: 0,
111            dummy_rgba8_tex: 0,
112        }
113    }
114}
115
116/// Uploads instanced quad buffers and submits a command buffer to the active physical GPU.
117///
118/// # Arguments
119///
120/// - `usize` - Raw OS device handle.
121/// - `usize` - Raw OS command queue handle.
122/// - `&[GpuBatch]` - Compiled instanced draw batches.
123///
124/// # Returns
125///
126/// - `usize` - Total GPU instances uploaded and submitted.
127pub fn submit_native_gpu_batches(
128    device_handle: usize,
129    queue_handle: usize,
130    batches: &[GpuBatch],
131) -> usize {
132    #[cfg(any(target_os = "macos", target_os = "ios"))]
133    {
134        metal_submit_batches(device_handle, queue_handle, batches)
135    }
136    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
137    {
138        let _: (usize, usize) = (device_handle, queue_handle);
139        batches
140            .iter()
141            .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
142            .sum()
143    }
144}
145
146/// Uploads packed 64-byte `GpuPrimitiveInstance` streams into a fenced 3-slot ring, encodes real instanced draw calls when a `CAMetalLayer` is bound, and commits.
147///
148/// # Arguments
149///
150/// - `&mut NativeGpuDriver` - Mutable GPU driver holding ring slots, pipelines, textures, and surface handle.
151/// - `u32` - Physical surface width in pixels.
152/// - `u32` - Physical surface height in pixels.
153/// - `Color` - Surface clear color.
154/// - `&[GpuBatch]` - Ordered instanced draw batches.
155///
156/// # Returns
157///
158/// - `usize` - Total 64-byte `GpuPrimitiveInstance` records uploaded and submitted.
159pub(crate) fn submit_native_gpu_ring_frame(
160    driver: &mut NativeGpuDriver,
161    width: u32,
162    height: u32,
163    clear_color: Color,
164    batches: &[GpuBatch],
165) -> usize {
166    #[cfg(any(target_os = "macos", target_os = "ios"))]
167    {
168        metal_submit_ring_frame(driver, width, height, clear_color, batches)
169    }
170    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
171    {
172        let _: (&mut NativeGpuDriver, u32, u32, Color) = (driver, width, height, clear_color);
173        batches
174            .iter()
175            .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
176            .sum()
177    }
178}
179
180/// Configures a native `CAMetalLayer` for triple-buffered direct-draw presentation (`framebufferOnly = YES`, `maximumDrawableCount = 3`).
181///
182/// # Arguments
183///
184/// - `usize` - Raw OS device handle (`id<MTLDevice>`).
185/// - `usize` - Raw `CAMetalLayer*` pointer.
186pub(crate) fn configure_native_metal_layer(device_handle: usize, layer_handle: usize) {
187    #[cfg(any(target_os = "macos", target_os = "ios"))]
188    {
189        metal_configure_layer(device_handle, layer_handle);
190    }
191    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
192    {
193        let _: (usize, usize) = (device_handle, layer_handle);
194    }
195}
196
197/// Uploads a dirty sub-rectangle of R8 or RGBA8 texels into a resident native GPU texture without full-texture reallocation.
198///
199/// # Arguments
200///
201/// - `usize` - Raw OS GPU device handle.
202/// - `&mut usize` - Resident native texture handle (`0` triggers lazy creation).
203/// - `GpuAtlasPixelFormat` - Target texture format (`R8Unorm` or `Rgba8Unorm`).
204/// - `(u32, u32)` - Full backing texture dimensions `(tex_w, tex_h)`.
205/// - `(u32, u32, u32, u32)` - Dirty rectangle `(x, y, width, height)`.
206/// - `&[u8]` - Tightly or stride-packed source texel bytes.
207/// - `usize` - Row stride in bytes of `bytes`.
208///
209/// # Returns
210///
211/// - `bool` - `true` when the dirty sub-rectangle was uploaded cleanly.
212pub(crate) fn upload_native_texture_dirty_rect(
213    device_handle: usize,
214    texture_handle: &mut usize,
215    format: GpuAtlasPixelFormat,
216    tex_dims: (u32, u32),
217    dirty_rect: (u32, u32, u32, u32),
218    bytes: &[u8],
219    bytes_per_row: usize,
220) -> bool {
221    #[cfg(any(target_os = "macos", target_os = "ios"))]
222    {
223        metal_upload_texture_dirty_rect(
224            device_handle,
225            texture_handle,
226            format,
227            tex_dims,
228            dirty_rect,
229            bytes,
230            bytes_per_row,
231        )
232    }
233    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
234    {
235        let _: usize = device_handle;
236        let _: &mut usize = texture_handle;
237        let _: GpuAtlasPixelFormat = format;
238        let _: (u32, u32) = tex_dims;
239        let _: (u32, u32, u32, u32) = dirty_rect;
240        let _: &[u8] = bytes;
241        let _: usize = bytes_per_row;
242        false
243    }
244}
245
246/// Retains a single native GPU object handle cleanly so each owning slot holds an independent reference.
247///
248/// # Arguments
249///
250/// - `usize` - Raw OS GPU object handle (`0` returns `0`).
251///
252/// # Returns
253///
254/// - `usize` - Independently retained GPU object handle.
255pub(crate) fn retain_native_gpu_object(handle: usize) -> usize {
256    #[cfg(any(target_os = "macos", target_os = "ios"))]
257    {
258        mtl_retain_handle(handle)
259    }
260    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
261    {
262        handle
263    }
264}
265
266/// Releases a single retained native GPU object handle cleanly on teardown.
267///
268/// # Arguments
269///
270/// - `usize` - Retained OS GPU handle (`0` is a no-op).
271pub(crate) fn release_native_gpu_object(handle: usize) {
272    #[cfg(any(target_os = "macos", target_os = "ios"))]
273    {
274        if handle != 0 {
275            let sel: &MetalSelectors = cached_metal_selectors();
276            mtl_send_void0(handle as *mut c_void, sel.release as *mut c_void);
277        }
278    }
279    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
280    {
281        let _: usize = handle;
282    }
283}
284
285/// Releases native GPU handles on driver teardown.
286///
287/// # Arguments
288///
289/// - `usize` - Raw device handle.
290/// - `usize` - Raw command queue handle.
291/// - `usize` - Raw shader library handle.
292pub fn release_native_gpu_handles(
293    device_handle: usize,
294    queue_handle: usize,
295    library_handle: usize,
296) {
297    #[cfg(any(target_os = "macos", target_os = "ios"))]
298    {
299        metal_release_handles(device_handle, queue_handle, library_handle);
300    }
301    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
302    {
303        let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
304    }
305}
306
307/// Returns the latest hardware presentation timestamp in nanoseconds recorded by the GPU driver.
308///
309/// # Returns
310///
311/// - `u64` - Presentation timestamp in nanoseconds (`0` before first hardware present).
312#[must_use]
313pub fn native_gpu_last_presented_ns() -> u64 {
314    #[cfg(any(target_os = "macos", target_os = "ios"))]
315    {
316        METAL_LAST_PRESENTED_NS.load(Ordering::Relaxed)
317    }
318    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
319    {
320        0
321    }
322}
323
324/// Returns the latest hardware GPU command execution duration in nanoseconds.
325///
326/// # Returns
327///
328/// - `u64` - GPU execution duration in nanoseconds (`0` before first completed GPU command buffer).
329#[must_use]
330pub fn native_gpu_last_exec_ns() -> u64 {
331    #[cfg(any(target_os = "macos", target_os = "ios"))]
332    {
333        METAL_LAST_GPU_EXEC_NS.load(Ordering::Relaxed)
334    }
335    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
336    {
337        0
338    }
339}
340
341#[cfg(any(target_os = "macos", target_os = "ios"))]
342#[link(name = "Metal", kind = "framework")]
343unsafe extern "C" {
344    /// Creates the default Apple Metal GPU device handle.
345    ///
346    /// # Returns
347    ///
348    /// - `*mut c_void` - Retained `id<MTLDevice>` pointer or null.
349    fn MTLCreateSystemDefaultDevice() -> *mut c_void;
350}
351
352#[cfg(any(target_os = "macos", target_os = "ios"))]
353#[link(name = "objc")]
354unsafe extern "C" {
355    /// Looks up an Objective-C class pointer by null-terminated C name.
356    ///
357    /// # Arguments
358    ///
359    /// - `*const c_char` - Null-terminated class name.
360    ///
361    /// # Returns
362    ///
363    /// - `*mut c_void` - Objective-C class pointer or null.
364    fn objc_getClass(name: *const c_char) -> *mut c_void;
365    /// Registers an Objective-C selector by null-terminated C name.
366    ///
367    /// # Arguments
368    ///
369    /// - `*const c_char` - Null-terminated selector name.
370    ///
371    /// # Returns
372    ///
373    /// - `*mut c_void` - Registered selector pointer.
374    fn sel_registerName(name: *const c_char) -> *mut c_void;
375    /// Pushes a scoped Objective-C autorelease pool frame.
376    ///
377    /// # Returns
378    ///
379    /// - `*mut c_void` - Autorelease pool token to pop via `objc_autoreleasePoolPop`.
380    fn objc_autoreleasePoolPush() -> *mut c_void;
381    /// Pops and drains a scoped Objective-C autorelease pool frame.
382    ///
383    /// # Arguments
384    ///
385    /// - `*mut c_void` - Pool token returned by `objc_autoreleasePoolPush`.
386    fn objc_autoreleasePoolPop(pool: *mut c_void);
387    /// Objective-C dynamic message dispatch entry point.
388    fn objc_msgSend();
389}
390
391#[cfg(any(target_os = "macos", target_os = "ios"))]
392unsafe extern "C" {
393    /// Standard Apple `libSystem` class symbol identifying static global Objective-C blocks.
394    static _NSConcreteGlobalBlock: c_void;
395}
396
397/// Registers an Objective-C selector from a static null-terminated string literal.
398///
399/// # Arguments
400///
401/// - `&'static str` - Null-terminated selector name.
402///
403/// # Returns
404///
405/// - `*mut c_void` - Registered Objective-C selector pointer.
406#[cfg(any(target_os = "macos", target_os = "ios"))]
407fn mtl_sel_cstr(name: &'static str) -> *mut c_void {
408    unsafe { sel_registerName(name.as_ptr().cast::<c_char>()) }
409}
410
411/// Looks up an Objective-C class from a static null-terminated string literal.
412///
413/// # Arguments
414///
415/// - `&'static str` - Null-terminated class name.
416///
417/// # Returns
418///
419/// - `*mut c_void` - Objective-C class pointer or null.
420#[cfg(any(target_os = "macos", target_os = "ios"))]
421fn mtl_cls_cstr(name: &'static str) -> *mut c_void {
422    unsafe { objc_getClass(name.as_ptr().cast::<c_char>()) }
423}
424
425/// Allocates an autoreleased `NSString` from a UTF-8 Rust slice.
426///
427/// # Arguments
428///
429/// - `&str` - Source UTF-8 string.
430///
431/// # Returns
432///
433/// - `*mut c_void` - Objective-C `NSString` pointer.
434#[cfg(any(target_os = "macos", target_os = "ios"))]
435fn mtl_ns_string(text: &str) -> *mut c_void {
436    let Ok(c_text) = CString::new(text) else {
437        return null_mut();
438    };
439    unsafe {
440        let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_STRING);
441        if cls.is_null() {
442            return null_mut();
443        }
444        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
445            transmute(objc_msgSend as *const c_void);
446        send(cls, mtl_sel_cstr(MTL_SEL_STRING_UTF8), c_text.as_ptr())
447    }
448}
449
450/// Sends a zero-argument Objective-C message returning a pointer.
451///
452/// # Arguments
453///
454/// - `*mut c_void` - Target Objective-C object.
455/// - `*mut c_void` - Selector pointer.
456///
457/// # Returns
458///
459/// - `*mut c_void` - Returned Objective-C object pointer.
460#[cfg(any(target_os = "macos", target_os = "ios"))]
461fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
462    if obj.is_null() || sel.is_null() {
463        return null_mut();
464    }
465    unsafe {
466        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
467            transmute(objc_msgSend as *const c_void);
468        send(obj, sel)
469    }
470}
471
472/// Sends a one-pointer-argument Objective-C message returning a pointer.
473///
474/// # Arguments
475///
476/// - `*mut c_void` - Target Objective-C object.
477/// - `*mut c_void` - Selector pointer.
478/// - `*mut c_void` - Pointer argument.
479///
480/// # Returns
481///
482/// - `*mut c_void` - Returned Objective-C object pointer.
483#[cfg(any(target_os = "macos", target_os = "ios"))]
484fn mtl_send_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) -> *mut c_void {
485    if obj.is_null() || sel.is_null() {
486        return null_mut();
487    }
488    unsafe {
489        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
490            transmute(objc_msgSend as *const c_void);
491        send(obj, sel, arg0)
492    }
493}
494
495/// Sends a zero-argument Objective-C message returning void.
496///
497/// # Arguments
498///
499/// - `*mut c_void` - Target Objective-C object.
500/// - `*mut c_void` - Selector pointer.
501#[cfg(any(target_os = "macos", target_os = "ios"))]
502fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
503    if obj.is_null() || sel.is_null() {
504        return;
505    }
506    unsafe {
507        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
508            transmute(objc_msgSend as *const c_void);
509        send(obj, sel);
510    }
511}
512
513/// Sends a one-pointer-argument Objective-C message returning void.
514///
515/// # Arguments
516///
517/// - `*mut c_void` - Target Objective-C object.
518/// - `*mut c_void` - Selector pointer.
519/// - `*mut c_void` - Pointer argument.
520#[cfg(any(target_os = "macos", target_os = "ios"))]
521fn mtl_send_void_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) {
522    if obj.is_null() || sel.is_null() {
523        return;
524    }
525    unsafe {
526        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
527            transmute(objc_msgSend as *const c_void);
528        send(obj, sel, arg0);
529    }
530}
531
532/// Sends a one-`usize`-argument Objective-C message returning void.
533///
534/// # Arguments
535///
536/// - `*mut c_void` - Target Objective-C object.
537/// - `*mut c_void` - Selector pointer.
538/// - `usize` - Unsigned integer argument (`NSUInteger`).
539#[cfg(any(target_os = "macos", target_os = "ios"))]
540fn mtl_send_void_usize(obj: *mut c_void, sel: *mut c_void, val: usize) {
541    if obj.is_null() || sel.is_null() {
542        return;
543    }
544    unsafe {
545        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
546            transmute(objc_msgSend as *const c_void);
547        send(obj, sel, val);
548    }
549}
550
551/// Sends a one-boolean Objective-C message returning void.
552///
553/// # Arguments
554///
555/// - `*mut c_void` - Target Objective-C object.
556/// - `*mut c_void` - Selector pointer.
557/// - `bool` - Boolean flag converted to Objective-C `BOOL`.
558#[cfg(any(target_os = "macos", target_os = "ios"))]
559fn mtl_send_void_bool(obj: *mut c_void, sel: *mut c_void, val: bool) {
560    if obj.is_null() || sel.is_null() {
561        return;
562    }
563    unsafe {
564        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
565            transmute(objc_msgSend as *const c_void);
566        send(obj, sel, if val { 1 } else { 0 });
567    }
568}
569
570/// Sends a zero-argument Objective-C message returning `usize` (`NSUInteger`).
571///
572/// # Arguments
573///
574/// - `*mut c_void` - Target Objective-C object.
575/// - `*mut c_void` - Selector pointer.
576///
577/// # Returns
578///
579/// - `usize` - Returned `NSUInteger`.
580#[cfg(any(target_os = "macos", target_os = "ios"))]
581fn mtl_send_usize0(obj: *mut c_void, sel: *mut c_void) -> usize {
582    if obj.is_null() || sel.is_null() {
583        return 0;
584    }
585    unsafe {
586        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
587            transmute(objc_msgSend as *const c_void);
588        send(obj, sel)
589    }
590}
591
592/// Sends a zero-argument Objective-C message returning `f64` (`CFTimeInterval`).
593///
594/// # Arguments
595///
596/// - `*mut c_void` - Target Objective-C object.
597/// - `*mut c_void` - Selector pointer.
598///
599/// # Returns
600///
601/// - `f64` - Returned floating-point timestamp or duration in seconds.
602#[cfg(any(target_os = "macos", target_os = "ios"))]
603fn mtl_send_f64_0(obj: *mut c_void, sel: *mut c_void) -> f64 {
604    if obj.is_null() || sel.is_null() {
605        return 0.0;
606    }
607    unsafe {
608        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
609            transmute(objc_msgSend as *const c_void);
610        send(obj, sel)
611    }
612}
613
614/// Checks whether an Objective-C object responds to `sel`.
615///
616/// # Arguments
617///
618/// - `*mut c_void` - Target Objective-C object.
619/// - `*mut c_void` - Selector to query.
620///
621/// # Returns
622///
623/// - `bool` - `true` when the object implements `sel`.
624#[cfg(any(target_os = "macos", target_os = "ios"))]
625fn mtl_responds_to_sel(obj: *mut c_void, sel: *mut c_void) -> bool {
626    if obj.is_null() || sel.is_null() {
627        return false;
628    }
629    let responds_sel: *mut c_void = cached_metal_selectors().responds_to_sel as *mut c_void;
630    unsafe {
631        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
632            transmute(objc_msgSend as *const c_void);
633        send(obj, responds_sel, sel) != 0
634    }
635}
636
637/// Retains a non-zero Objective-C handle and returns it as `usize`.
638///
639/// # Arguments
640///
641/// - `usize` - Raw Objective-C object handle (`0` returns `0`).
642///
643/// # Returns
644///
645/// - `usize` - Retained handle.
646#[cfg(any(target_os = "macos", target_os = "ios"))]
647fn mtl_retain_handle(handle: usize) -> usize {
648    if handle == 0 {
649        return 0;
650    }
651    let sel_retain: *mut c_void = cached_metal_selectors().retain as *mut c_void;
652    mtl_send_ptr0(handle as *mut c_void, sel_retain) as usize
653}
654
655/// Objective-C global block callback invoked by `-[MTLDrawable addPresentedHandler:]` upon display scan-out.
656///
657/// # Arguments
658///
659/// - `*mut c_void` - Global block pointer (unused).
660/// - `*mut c_void` - Presented `id<MTLDrawable>` pointer.
661#[cfg(any(target_os = "macos", target_os = "ios"))]
662unsafe extern "C" fn metal_presented_handler_invoke(_block: *mut c_void, drawable: *mut c_void) {
663    if drawable.is_null() {
664        return;
665    }
666    let sel: &MetalSelectors = cached_metal_selectors();
667    let presented_secs: f64 = mtl_send_f64_0(drawable, sel.presented_time as *mut c_void);
668    if presented_secs.is_finite() && presented_secs > 0.0 {
669        let ns: u64 = (presented_secs * 1_000_000_000.0).round() as u64;
670        METAL_LAST_PRESENTED_NS.store(ns, Ordering::Relaxed);
671    }
672}
673
674/// Objective-C global block callback invoked by `-[MTLCommandBuffer addCompletedHandler:]` on GPU completion.
675///
676/// # Arguments
677///
678/// - `*mut c_void` - Global block pointer (unused).
679/// - `*mut c_void` - Completed `id<MTLCommandBuffer>` pointer.
680#[cfg(any(target_os = "macos", target_os = "ios"))]
681unsafe extern "C" fn metal_completed_handler_invoke(_block: *mut c_void, cmd_buf: *mut c_void) {
682    if cmd_buf.is_null() {
683        return;
684    }
685    let sel: &MetalSelectors = cached_metal_selectors();
686    let start_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_start_time as *mut c_void);
687    let end_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_end_time as *mut c_void);
688    if start_s.is_finite() && end_s.is_finite() && end_s >= start_s {
689        let exec_ns: u64 = ((end_s - start_s) * 1_000_000_000.0).round() as u64;
690        METAL_LAST_GPU_EXEC_NS.store(exec_ns, Ordering::Relaxed);
691    }
692}
693
694/// Returns the process-lifetime pinned global Objective-C block pointer for `addPresentedHandler:`.
695///
696/// # Returns
697///
698/// - `*mut c_void` - Pointer to static `ObjcGlobalBlock`.
699#[cfg(any(target_os = "macos", target_os = "ios"))]
700fn metal_presented_block_ptr() -> *mut c_void {
701    let addr: usize = *METAL_PRESENTED_BLOCK_ADDR.get_or_init(|| {
702        let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
703            isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
704            flags: OBJC_BLOCK_IS_GLOBAL,
705            reserved: 0,
706            invoke: metal_presented_handler_invoke,
707            descriptor: &METAL_BLOCK_DESCRIPTOR,
708        });
709        Box::into_raw(block) as usize
710    });
711    addr as *mut c_void
712}
713
714/// Returns the process-lifetime pinned global Objective-C block pointer for `addCompletedHandler:`.
715///
716/// # Returns
717///
718/// - `*mut c_void` - Pointer to static `ObjcGlobalBlock`.
719#[cfg(any(target_os = "macos", target_os = "ios"))]
720fn metal_completed_block_ptr() -> *mut c_void {
721    let addr: usize = *METAL_COMPLETED_BLOCK_ADDR.get_or_init(|| {
722        let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
723            isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
724            flags: OBJC_BLOCK_IS_GLOBAL,
725            reserved: 0,
726            invoke: metal_completed_handler_invoke,
727            descriptor: &METAL_BLOCK_DESCRIPTOR,
728        });
729        Box::into_raw(block) as usize
730    });
731    addr as *mut c_void
732}
733
734/// Computes a deterministic 64-bit FNV-1a cache key over shader sources and GPU device name for `MTLBinaryArchive`.
735///
736/// # Arguments
737///
738/// - `&str` - Probed GPU device name.
739///
740/// # Returns
741///
742/// - `u64` - Deterministic cache key hash.
743#[cfg(any(target_os = "macos", target_os = "ios"))]
744fn metal_pipeline_cache_hash(device_name: &str) -> u64 {
745    let mut hash: u64 = FNV1A_OFFSET_BASIS;
746    for chunk in [
747        device_name.as_bytes(),
748        MSL_UI_SHADER.as_bytes(),
749        MSL_BACKDROP_BLUR_SHADER.as_bytes(),
750    ]
751    .iter()
752    {
753        for &byte in chunk.iter() {
754            hash ^= byte as u64;
755            hash = hash.wrapping_mul(FNV1A_PRIME);
756        }
757    }
758    hash
759}
760
761/// Creates a Metal `MTLTexture` (`R8Unorm` or `RGBA8Unorm`) with explicit dimensions for atlases or fallback slots.
762///
763/// # Arguments
764///
765/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
766/// - `GpuAtlasPixelFormat` - Pixel format to allocate.
767/// - `u32` - Texture width in pixels.
768/// - `u32` - Texture height in pixels.
769///
770/// # Returns
771///
772/// - `usize` - Retained `id<MTLTexture>` pointer or `0` on failure.
773#[cfg(any(target_os = "macos", target_os = "ios"))]
774fn metal_create_texture(
775    device: *mut c_void,
776    format: GpuAtlasPixelFormat,
777    width: u32,
778    height: u32,
779) -> usize {
780    if device.is_null() {
781        return 0;
782    }
783    let px_fmt: usize = match format {
784        GpuAtlasPixelFormat::R8Unorm => MTL_PIXEL_FORMAT_R8_UNORM,
785        GpuAtlasPixelFormat::Rgba8Unorm => MTL_PIXEL_FORMAT_RGBA8_UNORM,
786    };
787    let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
788    if cls_desc.is_null() {
789        return 0;
790    }
791    unsafe {
792        let send_desc: unsafe extern "C" fn(
793            *mut c_void,
794            *mut c_void,
795            usize,
796            usize,
797            usize,
798            i8,
799        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
800        let desc: *mut c_void = send_desc(
801            cls_desc,
802            mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
803            px_fmt,
804            width.max(1) as usize,
805            height.max(1) as usize,
806            0,
807        );
808        if desc.is_null() {
809            return 0;
810        }
811        mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
812        let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
813        tex as usize
814    }
815}
816
817/// Builds a real `MTLRenderPipelineState` with optional `MTLBinaryArchive` disk caching and straight-alpha blending.
818///
819/// # Arguments
820///
821/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
822/// - `*mut c_void` - Compiled `id<MTLLibrary>` handle.
823/// - `&str` - Vertex shader entry function name.
824/// - `&str` - Fragment shader entry function name.
825/// - `*mut c_void` - Optional `id<MTLBinaryArchive>` handle (null if unsupported).
826/// - `bool` - Whether alpha blending should be enabled on color attachment 0.
827///
828/// # Returns
829///
830/// - `(usize, bool)` - Tuple `(pipeline_state_handle, functions_found)`.
831#[cfg(any(target_os = "macos", target_os = "ios"))]
832fn metal_build_render_pipeline(
833    device: *mut c_void,
834    library: *mut c_void,
835    vs_name: &str,
836    fs_name: &str,
837    archive: *mut c_void,
838    enable_blend: bool,
839) -> (usize, bool) {
840    if device.is_null() || library.is_null() {
841        return (0, false);
842    }
843    let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
844    let vs_fn: *mut c_void = mtl_send_ptr1(
845        library,
846        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
847        mtl_ns_string(vs_name),
848    );
849    let fs_fn: *mut c_void = mtl_send_ptr1(
850        library,
851        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
852        mtl_ns_string(fs_name),
853    );
854    let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
855    if !functions_ok {
856        if !vs_fn.is_null() {
857            mtl_send_void0(vs_fn, sel_rel);
858        }
859        if !fs_fn.is_null() {
860            mtl_send_void0(fs_fn, sel_rel);
861        }
862        return (0, false);
863    }
864    let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
865    let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
866    let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
867    if desc.is_null() {
868        mtl_send_void0(vs_fn, sel_rel);
869        mtl_send_void0(fs_fn, sel_rel);
870        return (0, functions_ok);
871    }
872    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
873    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
874    let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
875    let att0: *mut c_void = unsafe {
876        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
877            transmute(objc_msgSend as *const c_void);
878        send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
879    };
880    if !att0.is_null() {
881        mtl_send_void_usize(
882            att0,
883            mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
884            MTL_PIXEL_FORMAT_BGRA8_UNORM,
885        );
886        if enable_blend {
887            mtl_send_void_bool(att0, mtl_sel_cstr(MTL_SEL_SET_BLENDING_ENABLED), true);
888            mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_RGB_BLEND_OP), 0);
889            mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_ALPHA_BLEND_OP), 0);
890            mtl_send_void_usize(
891                att0,
892                mtl_sel_cstr(MTL_SEL_SET_SRC_RGB_BLEND),
893                MTL_BLEND_FACTOR_SRC_ALPHA,
894            );
895            mtl_send_void_usize(
896                att0,
897                mtl_sel_cstr(MTL_SEL_SET_DST_RGB_BLEND),
898                MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
899            );
900            mtl_send_void_usize(
901                att0,
902                mtl_sel_cstr(MTL_SEL_SET_SRC_ALPHA_BLEND),
903                MTL_BLEND_FACTOR_ONE,
904            );
905            mtl_send_void_usize(
906                att0,
907                mtl_sel_cstr(MTL_SEL_SET_DST_ALPHA_BLEND),
908                MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
909            );
910        }
911    }
912    if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
913        let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
914        let arr: *mut c_void =
915            mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
916        if !arr.is_null() {
917            mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
918        }
919    }
920    let mut err_ptr: *mut c_void = null_mut();
921    let pipeline: *mut c_void = unsafe {
922        let send_pso: unsafe extern "C" fn(
923            *mut c_void,
924            *mut c_void,
925            *mut c_void,
926            *mut *mut c_void,
927        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
928        send_pso(
929            device,
930            mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
931            desc,
932            &mut err_ptr,
933        )
934    };
935    if !archive.is_null() && !pipeline.is_null() {
936        let mut add_err: *mut c_void = null_mut();
937        unsafe {
938            let send_add: unsafe extern "C" fn(
939                *mut c_void,
940                *mut c_void,
941                *mut c_void,
942                *mut *mut c_void,
943            ) -> i8 = transmute(objc_msgSend as *const c_void);
944            let _: i8 = send_add(
945                archive,
946                mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
947                desc,
948                &mut add_err,
949            );
950        }
951    }
952    mtl_send_void0(desc, sel_rel);
953    mtl_send_void0(vs_fn, sel_rel);
954    mtl_send_void0(fs_fn, sel_rel);
955    (pipeline as usize, functions_ok)
956}
957
958/// Opens or initializes a disk-backed `MTLBinaryArchive` keyed by shader source hash and GPU device name.
959///
960/// # Arguments
961///
962/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
963/// - `&str` - Detected physical GPU device name.
964///
965/// # Returns
966///
967/// - `(*mut c_void, *mut c_void, bool)` - Tuple `(archive_handle, ns_url_handle, existed_on_disk)`.
968#[cfg(any(target_os = "macos", target_os = "ios"))]
969fn metal_open_binary_archive(
970    device: *mut c_void,
971    device_name: &str,
972) -> (*mut c_void, *mut c_void, bool) {
973    let arch_desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_BINARY_ARCHIVE_DESC);
974    if arch_desc_cls.is_null() {
975        return (null_mut(), null_mut(), false);
976    }
977    let cache_hash: u64 = metal_pipeline_cache_hash(device_name);
978    let archive_path: String = env::temp_dir()
979        .join(format!(
980            "{MTL_ARCHIVE_FILE_PREFIX}{cache_hash:016x}{MTL_ARCHIVE_FILE_SUFFIX}"
981        ))
982        .to_string_lossy()
983        .into_owned();
984    let existed: bool = fs::metadata(&archive_path).is_ok();
985    let ns_path: *mut c_void = mtl_ns_string(&archive_path);
986    let url_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_URL);
987    let ns_url: *mut c_void =
988        mtl_send_ptr1(url_cls, mtl_sel_cstr(MTL_SEL_FILE_URL_WITH_PATH), ns_path);
989    let arch_desc_alloc: *mut c_void = mtl_send_ptr0(arch_desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
990    let arch_desc: *mut c_void = mtl_send_ptr0(arch_desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
991    if arch_desc.is_null() {
992        return (null_mut(), ns_url, existed);
993    }
994    if existed && !ns_url.is_null() {
995        mtl_send_void_ptr1(arch_desc, mtl_sel_cstr(MTL_SEL_SET_URL), ns_url);
996    }
997    let mut err_ptr: *mut c_void = null_mut();
998    let archive: *mut c_void = unsafe {
999        let send_new: unsafe extern "C" fn(
1000            *mut c_void,
1001            *mut c_void,
1002            *mut c_void,
1003            *mut *mut c_void,
1004        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1005        send_new(
1006            device,
1007            mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE),
1008            arch_desc,
1009            &mut err_ptr,
1010        )
1011    };
1012    mtl_send_void0(arch_desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1013    (archive, ns_url, existed)
1014}
1015
1016/// Initializes or returns the process-wide cached Apple Metal GPU device, command queue, binary-archived pipelines, and fallback textures.
1017///
1018/// # Arguments
1019///
1020/// - `GraphicsBackend` - Requested graphics backend.
1021///
1022/// # Returns
1023///
1024/// - `NativeGpuProbeOutput` - Retained handles for a `NativeGpuDriver` instance.
1025#[cfg(any(target_os = "macos", target_os = "ios"))]
1026fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
1027    let cached: &MetalSharedPipelineCache = METAL_SHARED_PIPELINE.get_or_init(|| {
1028        let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1029        let result: MetalSharedPipelineCache = unsafe {
1030            let device: *mut c_void = MTLCreateSystemDefaultDevice();
1031            if device.is_null() {
1032                MetalSharedPipelineCache {
1033                    adapter: GpuAdapterInfo::new(
1034                        backend,
1035                        GPU_DEVICE_FALLBACK.to_string(),
1036                        false,
1037                        false,
1038                    ),
1039                    device: 0,
1040                    queue: 0,
1041                    library: 0,
1042                    pipeline: 0,
1043                    blur_pipeline: 0,
1044                    dummy_r8_tex: 0,
1045                    dummy_rgba8_tex: 0,
1046                }
1047            } else {
1048                let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NAME));
1049                let utf8_ptr: *const c_char =
1050                    mtl_send_ptr0(ns_name, mtl_sel_cstr(MTL_SEL_UTF8_STRING)).cast::<c_char>();
1051                let device_name: String = if utf8_ptr.is_null() {
1052                    GPU_DEVICE_APPLE_METAL.to_string()
1053                } else {
1054                    CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
1055                };
1056                let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NEW_CMD_QUEUE));
1057                let (archive, archive_url, archive_existed): (*mut c_void, *mut c_void, bool) =
1058                    metal_open_binary_archive(device, &device_name);
1059                let send_lib: unsafe extern "C" fn(
1060                    *mut c_void,
1061                    *mut c_void,
1062                    *mut c_void,
1063                    *mut c_void,
1064                    *mut *mut c_void,
1065                ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1066                let mut err_ptr: *mut c_void = null_mut();
1067                let library: *mut c_void = send_lib(
1068                    device,
1069                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1070                    mtl_ns_string(MSL_UI_SHADER),
1071                    null_mut(),
1072                    &mut err_ptr,
1073                );
1074                let (pipeline, ui_fns_ok): (usize, bool) = metal_build_render_pipeline(
1075                    device,
1076                    library,
1077                    MTL_FN_VERTEX,
1078                    MTL_FN_FRAGMENT,
1079                    archive,
1080                    true,
1081                );
1082                let mut blur_err: *mut c_void = null_mut();
1083                let blur_lib: *mut c_void = send_lib(
1084                    device,
1085                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1086                    mtl_ns_string(MSL_BACKDROP_BLUR_SHADER),
1087                    null_mut(),
1088                    &mut blur_err,
1089                );
1090                let (blur_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1091                    device,
1092                    blur_lib,
1093                    MTL_FN_BLUR_VERTEX,
1094                    MTL_FN_BLUR_DOWN,
1095                    archive,
1096                    false,
1097                );
1098                let (blur_up_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1099                    device,
1100                    blur_lib,
1101                    MTL_FN_BLUR_VERTEX,
1102                    MTL_FN_BLUR_UP,
1103                    archive,
1104                    false,
1105                );
1106                if blur_up_pipeline != 0 {
1107                    mtl_send_void0(
1108                        blur_up_pipeline as *mut c_void,
1109                        mtl_sel_cstr(MTL_SEL_RELEASE),
1110                    );
1111                }
1112                if !blur_lib.is_null() {
1113                    mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1114                }
1115                if !archive.is_null() {
1116                    if !archive_existed && !archive_url.is_null() && pipeline != 0 {
1117                        let mut ser_err: *mut c_void = null_mut();
1118                        let send_ser: unsafe extern "C" fn(
1119                            *mut c_void,
1120                            *mut c_void,
1121                            *mut c_void,
1122                            *mut *mut c_void,
1123                        ) -> i8 = transmute(objc_msgSend as *const c_void);
1124                        let _: i8 = send_ser(
1125                            archive,
1126                            mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL),
1127                            archive_url,
1128                            &mut ser_err,
1129                        );
1130                    }
1131                    mtl_send_void0(archive, mtl_sel_cstr(MTL_SEL_RELEASE));
1132                }
1133                let dummy_r8_tex: usize =
1134                    metal_create_texture(device, GpuAtlasPixelFormat::R8Unorm, 1, 1);
1135                let dummy_rgba8_tex: usize =
1136                    metal_create_texture(device, GpuAtlasPixelFormat::Rgba8Unorm, 1, 1);
1137                let shader_compiled: bool = ui_fns_ok && pipeline != 0;
1138                MetalSharedPipelineCache {
1139                    adapter: GpuAdapterInfo::new(
1140                        GraphicsBackend::Metal,
1141                        device_name,
1142                        !queue.is_null(),
1143                        shader_compiled,
1144                    ),
1145                    device: device as usize,
1146                    queue: queue as usize,
1147                    library: library as usize,
1148                    pipeline,
1149                    blur_pipeline,
1150                    dummy_r8_tex,
1151                    dummy_rgba8_tex,
1152                }
1153            }
1154        };
1155        unsafe { objc_autoreleasePoolPop(pool) };
1156        result
1157    });
1158    NativeGpuProbeOutput {
1159        adapter: cached.adapter.clone(),
1160        device_handle: mtl_retain_handle(cached.device),
1161        queue_handle: mtl_retain_handle(cached.queue),
1162        library_handle: mtl_retain_handle(cached.library),
1163        pipeline_handle: mtl_retain_handle(cached.pipeline),
1164        blur_pipeline_handle: mtl_retain_handle(cached.blur_pipeline),
1165        dummy_r8_tex: mtl_retain_handle(cached.dummy_r8_tex),
1166        dummy_rgba8_tex: mtl_retain_handle(cached.dummy_rgba8_tex),
1167    }
1168}
1169
1170/// Returns the process-wide `OnceLock`-cached Objective-C selector pointers for Metal hot-path submission and encoding.
1171///
1172/// # Returns
1173///
1174/// - `&'static MetalSelectors` - Cached Metal selector addresses.
1175#[cfg(any(target_os = "macos", target_os = "ios"))]
1176fn cached_metal_selectors() -> &'static MetalSelectors {
1177    METAL_SELECTORS.get_or_init(|| MetalSelectors {
1178        retain: mtl_sel_cstr(MTL_SEL_RETAIN) as usize,
1179        new_buffer_with_bytes: mtl_sel_cstr(MTL_SEL_NEW_BUFFER) as usize,
1180        new_buffer_with_length: mtl_sel_cstr(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
1181        contents: mtl_sel_cstr(MTL_SEL_CONTENTS) as usize,
1182        command_buffer: mtl_sel_cstr(MTL_SEL_CMD_BUFFER) as usize,
1183        render_encoder: mtl_sel_cstr(MTL_SEL_RENDER_ENCODER) as usize,
1184        set_pipeline_state: mtl_sel_cstr(MTL_SEL_SET_PIPELINE_STATE) as usize,
1185        set_vertex_buffer: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BUFFER) as usize,
1186        set_vertex_bytes: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BYTES) as usize,
1187        set_fragment_texture: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_TEXTURE) as usize,
1188        set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
1189        draw_primitives_instanced: mtl_sel_cstr(MTL_SEL_DRAW_PRIMITIVES_INSTANCED) as usize,
1190        end_encoding: mtl_sel_cstr(MTL_SEL_END_ENCODING) as usize,
1191        present_drawable: mtl_sel_cstr(MTL_SEL_PRESENT_DRAWABLE) as usize,
1192        add_presented_handler: mtl_sel_cstr(MTL_SEL_ADD_PRESENTED_HANDLER) as usize,
1193        add_completed_handler: mtl_sel_cstr(MTL_SEL_ADD_COMPLETED_HANDLER) as usize,
1194        presented_time: mtl_sel_cstr(MTL_SEL_PRESENTED_TIME) as usize,
1195        responds_to_sel: mtl_sel_cstr(MTL_SEL_RESPONDS_TO_SEL) as usize,
1196        status: mtl_sel_cstr(MTL_SEL_STATUS) as usize,
1197        wait_until_completed: mtl_sel_cstr(MTL_SEL_WAIT_UNTIL_COMPLETED) as usize,
1198        gpu_start_time: mtl_sel_cstr(MTL_SEL_GPU_START_TIME) as usize,
1199        gpu_end_time: mtl_sel_cstr(MTL_SEL_GPU_END_TIME) as usize,
1200        next_drawable: mtl_sel_cstr(MTL_SEL_NEXT_DRAWABLE) as usize,
1201        drawable_size: mtl_sel_cstr(MTL_SEL_DRAWABLE_SIZE) as usize,
1202        set_drawable_size: mtl_sel_cstr(MTL_SEL_SET_DRAWABLE_SIZE) as usize,
1203        texture: mtl_sel_cstr(MTL_SEL_TEXTURE) as usize,
1204        width: mtl_sel_cstr(MTL_SEL_WIDTH) as usize,
1205        height: mtl_sel_cstr(MTL_SEL_HEIGHT) as usize,
1206        render_pass_desc: mtl_sel_cstr(MTL_SEL_RENDER_PASS_DESC) as usize,
1207        color_attachments: mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS) as usize,
1208        object_at_index: mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX) as usize,
1209        set_texture: mtl_sel_cstr(MTL_SEL_SET_TEXTURE) as usize,
1210        set_load_action: mtl_sel_cstr(MTL_SEL_SET_LOAD_ACTION) as usize,
1211        set_store_action: mtl_sel_cstr(MTL_SEL_SET_STORE_ACTION) as usize,
1212        set_clear_color: mtl_sel_cstr(MTL_SEL_SET_CLEAR_COLOR) as usize,
1213        replace_region: mtl_sel_cstr(MTL_SEL_REPLACE_REGION) as usize,
1214        commit: mtl_sel_cstr(MTL_SEL_COMMIT) as usize,
1215        release: mtl_sel_cstr(MTL_SEL_RELEASE) as usize,
1216    })
1217}
1218
1219/// Configures a `CAMetalLayer*` for direct triple-buffered GPU draw (`BGRA8Unorm`, `framebufferOnly = YES`, `maximumDrawableCount = 3`).
1220///
1221/// # Arguments
1222///
1223/// - `usize` - Retained `id<MTLDevice>` handle.
1224/// - `usize` - Target `CAMetalLayer*` pointer.
1225#[cfg(any(target_os = "macos", target_os = "ios"))]
1226fn metal_configure_layer(device_handle: usize, layer_handle: usize) {
1227    if device_handle == 0 || layer_handle == 0 {
1228        return;
1229    }
1230    let layer: *mut c_void = layer_handle as *mut c_void;
1231    mtl_send_void_ptr1(
1232        layer,
1233        mtl_sel_cstr(MTL_SEL_SET_DEVICE),
1234        device_handle as *mut c_void,
1235    );
1236    mtl_send_void_usize(
1237        layer,
1238        mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1239        MTL_PIXEL_FORMAT_BGRA8_UNORM,
1240    );
1241    mtl_send_void_bool(layer, mtl_sel_cstr(MTL_SEL_SET_FRAMEBUFFER_ONLY), true);
1242    let sel_max: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_MAX_DRAWABLE_COUNT);
1243    if mtl_responds_to_sel(layer, sel_max) {
1244        mtl_send_void_usize(layer, sel_max, GPU_DRIVER_RING_SLOTS);
1245    }
1246    let sel_sync: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_DISPLAY_SYNC);
1247    if mtl_responds_to_sel(layer, sel_sync) {
1248        mtl_send_void_bool(layer, sel_sync, true);
1249    }
1250}
1251
1252/// Uploads a dirty R8 or RGBA8 sub-rectangle into a Metal `MTLTexture` via `replaceRegion:mipmapLevel:withBytes:bytesPerRow:`.
1253///
1254/// # Arguments
1255///
1256/// - `usize` - Retained `id<MTLDevice>` handle.
1257/// - `&mut usize` - Resident `id<MTLTexture>` handle (`0` lazily allocates a new texture).
1258/// - `GpuAtlasPixelFormat` - Target Metal pixel format.
1259/// - `(u32, u32)` - Backing texture dimensions `(width, height)`.
1260/// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
1261/// - `&[u8]` - Source pixel slice.
1262/// - `usize` - Row stride in bytes.
1263///
1264/// # Returns
1265///
1266/// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly.
1267#[cfg(any(target_os = "macos", target_os = "ios"))]
1268fn metal_upload_texture_dirty_rect(
1269    device_handle: usize,
1270    texture_handle: &mut usize,
1271    format: GpuAtlasPixelFormat,
1272    tex_dims: (u32, u32),
1273    dirty_rect: (u32, u32, u32, u32),
1274    bytes: &[u8],
1275    bytes_per_row: usize,
1276) -> bool {
1277    if device_handle == 0 || dirty_rect.2 == 0 || dirty_rect.3 == 0 || bytes.is_empty() {
1278        return false;
1279    }
1280    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1281    let (tex_w, tex_h): (u32, u32) = (tex_dims.0.max(1), tex_dims.1.max(1));
1282    let sel: &MetalSelectors = cached_metal_selectors();
1283    let cur_w: usize = if *texture_handle != 0 {
1284        mtl_send_usize0(*texture_handle as *mut c_void, sel.width as *mut c_void)
1285    } else {
1286        0
1287    };
1288    let cur_h: usize = if *texture_handle != 0 {
1289        mtl_send_usize0(*texture_handle as *mut c_void, sel.height as *mut c_void)
1290    } else {
1291        0
1292    };
1293    if *texture_handle == 0 || cur_w != tex_w as usize || cur_h != tex_h as usize {
1294        if *texture_handle != 0 {
1295            mtl_send_void0(*texture_handle as *mut c_void, sel.release as *mut c_void);
1296        }
1297        *texture_handle = metal_create_texture(device_handle as *mut c_void, format, tex_w, tex_h);
1298    }
1299    if *texture_handle == 0 {
1300        unsafe { objc_autoreleasePoolPop(pool) };
1301        return false;
1302    }
1303    let region: MtlRegion = MtlRegion {
1304        origin: MtlOrigin {
1305            x: dirty_rect.0 as usize,
1306            y: dirty_rect.1 as usize,
1307            z: 0,
1308        },
1309        size: MtlSize {
1310            width: dirty_rect.2 as usize,
1311            height: dirty_rect.3 as usize,
1312            depth: 1,
1313        },
1314    };
1315    unsafe {
1316        let send_replace: unsafe extern "C" fn(
1317            *mut c_void,
1318            *mut c_void,
1319            MtlRegion,
1320            usize,
1321            *const c_void,
1322            usize,
1323        ) = transmute(objc_msgSend as *const c_void);
1324        send_replace(
1325            *texture_handle as *mut c_void,
1326            sel.replace_region as *mut c_void,
1327            region,
1328            0,
1329            bytes.as_ptr().cast::<c_void>(),
1330            bytes_per_row,
1331        );
1332        objc_autoreleasePoolPop(pool);
1333    }
1334    true
1335}
1336
1337/// 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.
1338///
1339/// # Arguments
1340///
1341/// - `&mut NativeGpuDriver` - Mutable GPU driver holding ring slots, pipelines, textures, and layer handle.
1342/// - `u32` - Physical surface width in pixels.
1343/// - `u32` - Physical surface height in pixels.
1344/// - `Color` - Surface clear color.
1345/// - `&[GpuBatch]` - Ordered GPU batches to encode and submit.
1346///
1347/// # Returns
1348///
1349/// - `usize` - Total 64-byte `GpuPrimitiveInstance` records uploaded and submitted.
1350#[cfg(any(target_os = "macos", target_os = "ios"))]
1351fn metal_submit_ring_frame(
1352    driver: &mut NativeGpuDriver,
1353    width: u32,
1354    height: u32,
1355    clear_color: Color,
1356    batches: &[GpuBatch],
1357) -> usize {
1358    let total_instances: usize = batches
1359        .iter()
1360        .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
1361        .sum();
1362    let device_handle: usize = driver.get_device_handle();
1363    let queue_handle: usize = driver.get_queue_handle();
1364    if device_handle == 0 || queue_handle == 0 {
1365        return total_instances;
1366    }
1367    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1368    let sel: &MetalSelectors = cached_metal_selectors();
1369    let sel_rel: *mut c_void = sel.release as *mut c_void;
1370    let slot_idx: usize = driver.get_ring_cursor() % GPU_DRIVER_RING_SLOTS;
1371    let device: *mut c_void = device_handle as *mut c_void;
1372    let queue: *mut c_void = queue_handle as *mut c_void;
1373    let pipeline: *mut c_void = driver.get_pipeline_handle() as *mut c_void;
1374    let layer_ptr: *mut c_void = driver.get_surface_layer_handle() as *mut c_void;
1375    let tex_r8: *mut c_void = driver.get_glyph_r8_texture_handle() as *mut c_void;
1376    let tex_rgba8: *mut c_void = driver.get_glyph_rgba8_texture_handle() as *mut c_void;
1377    let tex_img: *mut c_void = driver.get_image_texture_handle() as *mut c_void;
1378    let raw_ext: usize = driver.get_external_texture_handle();
1379    let tex_ext: *mut c_void = if raw_ext != 0 {
1380        raw_ext as *mut c_void
1381    } else {
1382        tex_rgba8
1383    };
1384    let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuPrimitiveInstance>());
1385    let NativeGpuDriver {
1386        ring_slots,
1387        ring_cursor,
1388        staging_buffer_handle,
1389        staging_contents_ptr,
1390        staging_buffer_capacity,
1391        staging_reallocations,
1392        scratch_primitives,
1393        ..
1394    } = driver;
1395    let slot: &mut NativeGpuRingSlot = &mut ring_slots[slot_idx];
1396    let prev_cmd: usize = slot.get_in_flight_cmd_buffer();
1397    if prev_cmd != 0 {
1398        let status: usize = mtl_send_usize0(prev_cmd as *mut c_void, sel.status as *mut c_void);
1399        if status < MTL_CMD_BUFFER_STATUS_COMPLETED {
1400            mtl_send_void0(
1401                prev_cmd as *mut c_void,
1402                sel.wait_until_completed as *mut c_void,
1403            );
1404        }
1405        mtl_send_void0(prev_cmd as *mut c_void, sel_rel);
1406        slot.set_in_flight_cmd_buffer(0);
1407    }
1408    if total_bytes > 0
1409        && (slot.get_buffer_handle() == 0
1410            || slot.get_contents_ptr() == 0
1411            || total_bytes > slot.get_capacity_bytes())
1412    {
1413        if slot.get_buffer_handle() != 0 {
1414            mtl_send_void0(slot.get_buffer_handle() as *mut c_void, sel_rel);
1415            slot.set_buffer_handle(0);
1416            slot.set_contents_ptr(0);
1417            slot.set_capacity_bytes(0);
1418        }
1419        let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
1420        unsafe {
1421            let send_new_len: unsafe extern "C" fn(
1422                *mut c_void,
1423                *mut c_void,
1424                usize,
1425                usize,
1426            ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1427            let new_buf: *mut c_void = send_new_len(
1428                device,
1429                sel.new_buffer_with_length as *mut c_void,
1430                alloc_bytes,
1431                0,
1432            );
1433            if !new_buf.is_null() {
1434                let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
1435                if !ptr.is_null() {
1436                    slot.set_buffer_handle(new_buf as usize);
1437                    slot.set_contents_ptr(ptr as usize);
1438                    slot.set_capacity_bytes(alloc_bytes);
1439                    *staging_reallocations = staging_reallocations.wrapping_add(1);
1440                } else {
1441                    mtl_send_void0(new_buf, sel_rel);
1442                }
1443            }
1444        }
1445    }
1446    let buf_handle: usize = slot.get_buffer_handle();
1447    let contents_ptr: usize = slot.get_contents_ptr();
1448    let capacity_bytes: usize = slot.get_capacity_bytes();
1449    *staging_buffer_handle = buf_handle;
1450    *staging_contents_ptr = contents_ptr;
1451    *staging_buffer_capacity = capacity_bytes;
1452    if contents_ptr != 0 && total_bytes > 0 && total_bytes <= capacity_bytes {
1453        unsafe {
1454            let mut dst: *mut u8 = (contents_ptr as *mut c_void).cast::<u8>();
1455            for batch in batches.iter() {
1456                let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
1457                if !prims.is_empty() {
1458                    let byte_len: usize = size_of_val(prims);
1459                    dst.copy_from_nonoverlapping(prims.as_ptr().cast::<u8>(), byte_len);
1460                    dst = dst.add(byte_len);
1461                } else if !batch.get_instances().is_empty() {
1462                    scratch_primitives.clear();
1463                    for quad in batch.get_instances().iter() {
1464                        scratch_primitives.push(GpuPrimitiveInstance::from_quad_instance(
1465                            quad,
1466                            batch.get_texture_slot(),
1467                            batch.get_layer_id(),
1468                        ));
1469                    }
1470                    let byte_len: usize = size_of_val(scratch_primitives.as_slice());
1471                    dst.copy_from_nonoverlapping(
1472                        scratch_primitives.as_ptr().cast::<u8>(),
1473                        byte_len,
1474                    );
1475                    dst = dst.add(byte_len);
1476                }
1477            }
1478        }
1479    }
1480    let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
1481    if !cmd_buf.is_null() {
1482        let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
1483        if mtl_responds_to_sel(cmd_buf, sel_completed) {
1484            mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
1485        }
1486        if !layer_ptr.is_null() && !pipeline.is_null() {
1487            if width > 0
1488                && height > 0
1489                && mtl_responds_to_sel(layer_ptr, sel.set_drawable_size as *mut c_void)
1490            {
1491                let target_w: f64 = f64::from(width);
1492                let target_h: f64 = f64::from(height);
1493                let needs_resize: bool =
1494                    if mtl_responds_to_sel(layer_ptr, sel.drawable_size as *mut c_void) {
1495                        // SAFETY: `-[CAMetalLayer drawableSize]` returns a 16-byte `CGSize` in FP registers on 64-bit Apple targets.
1496                        let cur: MtlCgSize = unsafe {
1497                            let get_size: unsafe extern "C" fn(
1498                                *mut c_void,
1499                                *mut c_void,
1500                            )
1501                                -> MtlCgSize = transmute(objc_msgSend as *const c_void);
1502                            get_size(layer_ptr, sel.drawable_size as *mut c_void)
1503                        };
1504                        (cur.width - target_w).abs() > 0.5 || (cur.height - target_h).abs() > 0.5
1505                    } else {
1506                        true
1507                    };
1508                if needs_resize {
1509                    // SAFETY: `-[CAMetalLayer setDrawableSize:]` takes a single `CGSize` (`{ f64, f64 }`) value.
1510                    unsafe {
1511                        let set_size: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlCgSize) =
1512                            transmute(objc_msgSend as *const c_void);
1513                        set_size(
1514                            layer_ptr,
1515                            sel.set_drawable_size as *mut c_void,
1516                            MtlCgSize {
1517                                width: target_w,
1518                                height: target_h,
1519                            },
1520                        );
1521                    }
1522                }
1523            }
1524            let drawable: *mut c_void = mtl_send_ptr0(layer_ptr, sel.next_drawable as *mut c_void);
1525            if !drawable.is_null() {
1526                let drawable_tex: *mut c_void = mtl_send_ptr0(drawable, sel.texture as *mut c_void);
1527                let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
1528                let pass_desc: *mut c_void =
1529                    mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
1530                if !drawable_tex.is_null() && !pass_desc.is_null() {
1531                    let draw_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void)
1532                        .max(width.max(1) as usize);
1533                    let draw_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void)
1534                        .max(height.max(1) as usize);
1535                    let color_atts: *mut c_void =
1536                        mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
1537                    let att0: *mut c_void = unsafe {
1538                        let send_idx: unsafe extern "C" fn(
1539                            *mut c_void,
1540                            *mut c_void,
1541                            usize,
1542                        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1543                        send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
1544                    };
1545                    if !att0.is_null() {
1546                        mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, drawable_tex);
1547                        mtl_send_void_usize(
1548                            att0,
1549                            sel.set_load_action as *mut c_void,
1550                            MTL_LOAD_ACTION_CLEAR,
1551                        );
1552                        mtl_send_void_usize(
1553                            att0,
1554                            sel.set_store_action as *mut c_void,
1555                            MTL_STORE_ACTION_STORE,
1556                        );
1557                        let clear_rgba: [f32; 4] = clear_color.to_f32_array();
1558                        let mtl_clear: MtlClearColor = MtlClearColor {
1559                            red: clear_rgba[0] as f64,
1560                            green: clear_rgba[1] as f64,
1561                            blue: clear_rgba[2] as f64,
1562                            alpha: clear_rgba[3] as f64,
1563                        };
1564                        unsafe {
1565                            let send_clear: unsafe extern "C" fn(
1566                                *mut c_void,
1567                                *mut c_void,
1568                                MtlClearColor,
1569                            ) = transmute(objc_msgSend as *const c_void);
1570                            send_clear(att0, sel.set_clear_color as *mut c_void, mtl_clear);
1571                        }
1572                    }
1573                    let encoder: *mut c_void =
1574                        mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
1575                    if !encoder.is_null() {
1576                        mtl_send_void_ptr1(
1577                            encoder,
1578                            sel.set_pipeline_state as *mut c_void,
1579                            pipeline,
1580                        );
1581                        unsafe {
1582                            let send_vbuf: unsafe extern "C" fn(
1583                                *mut c_void,
1584                                *mut c_void,
1585                                *mut c_void,
1586                                usize,
1587                                usize,
1588                            ) = transmute(objc_msgSend as *const c_void);
1589                            let send_vbytes: unsafe extern "C" fn(
1590                                *mut c_void,
1591                                *mut c_void,
1592                                *const c_void,
1593                                usize,
1594                                usize,
1595                            ) = transmute(objc_msgSend as *const c_void);
1596                            let send_ftex: unsafe extern "C" fn(
1597                                *mut c_void,
1598                                *mut c_void,
1599                                *mut c_void,
1600                                usize,
1601                            ) = transmute(objc_msgSend as *const c_void);
1602                            let send_scissor: unsafe extern "C" fn(
1603                                *mut c_void,
1604                                *mut c_void,
1605                                MtlScissorRect,
1606                            ) = transmute(objc_msgSend as *const c_void);
1607                            let send_draw: unsafe extern "C" fn(
1608                                *mut c_void,
1609                                *mut c_void,
1610                                usize,
1611                                usize,
1612                                usize,
1613                                usize,
1614                                usize,
1615                            ) = transmute(objc_msgSend as *const c_void);
1616                            if buf_handle != 0 {
1617                                send_vbuf(
1618                                    encoder,
1619                                    sel.set_vertex_buffer as *mut c_void,
1620                                    buf_handle as *mut c_void,
1621                                    0,
1622                                    0,
1623                                );
1624                            }
1625                            if !tex_r8.is_null() {
1626                                send_ftex(
1627                                    encoder,
1628                                    sel.set_fragment_texture as *mut c_void,
1629                                    tex_r8,
1630                                    0,
1631                                );
1632                            }
1633                            if !tex_rgba8.is_null() {
1634                                send_ftex(
1635                                    encoder,
1636                                    sel.set_fragment_texture as *mut c_void,
1637                                    tex_rgba8,
1638                                    1,
1639                                );
1640                            }
1641                            if !tex_img.is_null() {
1642                                send_ftex(
1643                                    encoder,
1644                                    sel.set_fragment_texture as *mut c_void,
1645                                    tex_img,
1646                                    2,
1647                                );
1648                            }
1649                            if !tex_ext.is_null() {
1650                                send_ftex(
1651                                    encoder,
1652                                    sel.set_fragment_texture as *mut c_void,
1653                                    tex_ext,
1654                                    3,
1655                                );
1656                            }
1657                            let mut base_instance: usize = 0;
1658                            for batch in batches.iter() {
1659                                let count: usize = batch
1660                                    .get_primitives()
1661                                    .len()
1662                                    .max(batch.get_instances().len());
1663                                if count == 0 || buf_handle == 0 {
1664                                    continue;
1665                                }
1666                                let uniform: GpuLayerUniform = GpuLayerUniform::new(
1667                                    draw_w as f32,
1668                                    draw_h as f32,
1669                                    batch.get_scroll_offset(),
1670                                );
1671                                send_vbytes(
1672                                    encoder,
1673                                    sel.set_vertex_bytes as *mut c_void,
1674                                    (&uniform as *const GpuLayerUniform).cast::<c_void>(),
1675                                    size_of::<GpuLayerUniform>(),
1676                                    1,
1677                                );
1678                                let sc: Rect = batch.get_scissor();
1679                                let sx: usize = (sc.get_x().max(0.0).floor() as usize)
1680                                    .min(draw_w.saturating_sub(1));
1681                                let sy: usize = (sc.get_y().max(0.0).floor() as usize)
1682                                    .min(draw_h.saturating_sub(1));
1683                                let sw: usize = (sc.get_width().max(1.0).ceil() as usize)
1684                                    .min(draw_w.saturating_sub(sx))
1685                                    .max(1);
1686                                let sh: usize = (sc.get_height().max(1.0).ceil() as usize)
1687                                    .min(draw_h.saturating_sub(sy))
1688                                    .max(1);
1689                                send_scissor(
1690                                    encoder,
1691                                    sel.set_scissor_rect as *mut c_void,
1692                                    MtlScissorRect {
1693                                        x: sx,
1694                                        y: sy,
1695                                        width: sw,
1696                                        height: sh,
1697                                    },
1698                                );
1699                                send_draw(
1700                                    encoder,
1701                                    sel.draw_primitives_instanced as *mut c_void,
1702                                    MTL_PRIMITIVE_TYPE_TRIANGLE,
1703                                    0,
1704                                    6,
1705                                    count,
1706                                    base_instance,
1707                                );
1708                                base_instance = base_instance.saturating_add(count);
1709                            }
1710                        }
1711                        mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
1712                    }
1713                    let sel_pres: *mut c_void = sel.add_presented_handler as *mut c_void;
1714                    if mtl_responds_to_sel(drawable, sel_pres) {
1715                        mtl_send_void_ptr1(drawable, sel_pres, metal_presented_block_ptr());
1716                    }
1717                    mtl_send_void_ptr1(cmd_buf, sel.present_drawable as *mut c_void, drawable);
1718                }
1719            }
1720        }
1721        let retained_cmd: usize = mtl_retain_handle(cmd_buf as usize);
1722        slot.set_in_flight_cmd_buffer(retained_cmd);
1723        mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
1724    }
1725    *ring_cursor = (slot_idx + 1) % GPU_DRIVER_RING_SLOTS;
1726    unsafe { objc_autoreleasePoolPop(pool) };
1727    total_instances
1728}
1729
1730/// Uploads `GpuPrimitiveInstance` buffers to Metal GPU memory and commits a command buffer.
1731///
1732/// # Arguments
1733///
1734/// - `usize` - Retained `id<MTLDevice>` pointer.
1735/// - `usize` - Retained `id<MTLCommandQueue>` pointer.
1736/// - `&[GpuBatch]` - Ordered GPU batches to upload.
1737///
1738/// # Returns
1739///
1740/// - `usize` - Total instances uploaded into Metal buffers.
1741#[cfg(any(target_os = "macos", target_os = "ios"))]
1742fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
1743    let total_instances: usize = batches
1744        .iter()
1745        .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
1746        .sum();
1747    if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
1748        return total_instances;
1749    }
1750    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1751    let device: *mut c_void = device_handle as *mut c_void;
1752    let queue: *mut c_void = queue_handle as *mut c_void;
1753    let sel: &MetalSelectors = cached_metal_selectors();
1754    let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
1755    let sel_rel: *mut c_void = sel.release as *mut c_void;
1756    unsafe {
1757        let send_buf: unsafe extern "C" fn(
1758            *mut c_void,
1759            *mut c_void,
1760            *const c_void,
1761            usize,
1762            usize,
1763        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1764        for batch in batches.iter() {
1765            let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
1766            if !prims.is_empty() {
1767                let byte_len: usize = size_of_val(prims);
1768                let mtl_buf: *mut c_void = send_buf(
1769                    device,
1770                    sel_buf,
1771                    prims.as_ptr().cast::<c_void>(),
1772                    byte_len,
1773                    0,
1774                );
1775                if !mtl_buf.is_null() {
1776                    mtl_send_void0(mtl_buf, sel_rel);
1777                }
1778            } else {
1779                let instances: &[GpuQuadInstance] = batch.get_instances();
1780                if instances.is_empty() {
1781                    continue;
1782                }
1783                let byte_len: usize = size_of_val(instances);
1784                let mtl_buf: *mut c_void = send_buf(
1785                    device,
1786                    sel_buf,
1787                    instances.as_ptr().cast::<c_void>(),
1788                    byte_len,
1789                    0,
1790                );
1791                if !mtl_buf.is_null() {
1792                    mtl_send_void0(mtl_buf, sel_rel);
1793                }
1794            }
1795        }
1796        let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
1797        if !cmd_buf.is_null() {
1798            mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
1799        }
1800        objc_autoreleasePoolPop(pool);
1801    }
1802    total_instances
1803}
1804
1805/// Releases retained Apple Metal Objective-C objects cleanly on drop.
1806///
1807/// # Arguments
1808///
1809/// - `usize` - `id<MTLDevice>` pointer.
1810/// - `usize` - `id<MTLCommandQueue>` pointer.
1811/// - `usize` - `id<MTLLibrary>` pointer.
1812#[cfg(any(target_os = "macos", target_os = "ios"))]
1813fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
1814    let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
1815    if library_handle != 0 {
1816        mtl_send_void0(library_handle as *mut c_void, sel_rel);
1817    }
1818    if queue_handle != 0 {
1819        mtl_send_void0(queue_handle as *mut c_void, sel_rel);
1820    }
1821    if device_handle != 0 {
1822        mtl_send_void0(device_handle as *mut c_void, sel_rel);
1823    }
1824}
1825
1826#[cfg(target_os = "windows")]
1827#[link(name = "kernel32")]
1828unsafe extern "system" {
1829    /// Dynamically loads a Windows DLL by ANSI path.
1830    ///
1831    /// # Arguments
1832    ///
1833    /// - `*const u8` - Null-terminated ANSI DLL path.
1834    ///
1835    /// # Returns
1836    ///
1837    /// - `*mut c_void` - Loaded `HMODULE` handle or null.
1838    fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
1839    /// Looks up an exported procedure address from a loaded Windows DLL.
1840    ///
1841    /// # Arguments
1842    ///
1843    /// - `*mut c_void` - Loaded `HMODULE` handle.
1844    /// - `*const u8` - Null-terminated ASCII export name.
1845    ///
1846    /// # Returns
1847    ///
1848    /// - `*mut c_void` - Exported function address or null.
1849    fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
1850}
1851
1852/// Probes Windows Direct3D 12 and `d3dcompiler_47.dll` once per process (caching handles in `OnceLock`).
1853///
1854/// # Arguments
1855///
1856/// - `GraphicsBackend` - Requested graphics backend.
1857///
1858/// # Returns
1859///
1860/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Direct3D 12 availability metadata.
1861#[cfg(target_os = "windows")]
1862fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
1863    let cached: &WindowsD3d12ProbeCache = WINDOWS_D3D12_CACHE.get_or_init(|| unsafe {
1864        let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
1865        let has_d3d12: bool = if !d3d12_mod.is_null() {
1866            !GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr()).is_null()
1867        } else {
1868            false
1869        };
1870        let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
1871        let has_compiler: bool = if !compiler_mod.is_null() {
1872            !GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr()).is_null()
1873        } else {
1874            false
1875        };
1876        WindowsD3d12ProbeCache {
1877            has_d3d12,
1878            has_compiler,
1879        }
1880    });
1881    let label: &str = if cached.has_d3d12 {
1882        GPU_DEVICE_D3D12
1883    } else {
1884        GPU_DEVICE_FALLBACK
1885    };
1886    (
1887        GpuAdapterInfo::new(
1888            backend,
1889            label.to_string(),
1890            cached.has_d3d12,
1891            cached.has_compiler,
1892        ),
1893        0,
1894        0,
1895        0,
1896    )
1897}
1898
1899#[cfg(any(target_os = "linux", target_os = "android"))]
1900unsafe extern "C" {
1901    /// Dynamically opens a shared library object by name.
1902    ///
1903    /// # Arguments
1904    ///
1905    /// - `*const c_char` - Null-terminated library name.
1906    /// - `i32` - POSIX `RTLD_*` resolution flags.
1907    ///
1908    /// # Returns
1909    ///
1910    /// - `*mut c_void` - Shared library handle or null.
1911    fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
1912    /// Resolves a symbol address from an open shared library handle.
1913    ///
1914    /// # Arguments
1915    ///
1916    /// - `*mut c_void` - Open shared library handle.
1917    /// - `*const c_char` - Null-terminated symbol name.
1918    ///
1919    /// # Returns
1920    ///
1921    /// - `*mut c_void` - Resolved symbol pointer or null.
1922    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
1923}
1924
1925/// Probes Linux or Android Vulkan loader once per process and retains the library handle in `OnceLock`.
1926///
1927/// # Arguments
1928///
1929/// - `GraphicsBackend` - Requested graphics backend.
1930///
1931/// # Returns
1932///
1933/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Vulkan runtime status.
1934#[cfg(any(target_os = "linux", target_os = "android"))]
1935fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
1936    let cached: &VulkanProbeCache = VULKAN_PROBE_CACHE.get_or_init(|| {
1937        let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
1938            return VulkanProbeCache {
1939                available: false,
1940                lib_handle: 0,
1941            };
1942        };
1943        let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
1944            return VulkanProbeCache {
1945                available: false,
1946                lib_handle: 0,
1947            };
1948        };
1949        let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
1950            return VulkanProbeCache {
1951                available: false,
1952                lib_handle: 0,
1953            };
1954        };
1955        unsafe {
1956            let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
1957            if handle.is_null() {
1958                VulkanProbeCache {
1959                    available: false,
1960                    lib_handle: 0,
1961                }
1962            } else {
1963                let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
1964                let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
1965                VulkanProbeCache {
1966                    available: !p1.is_null() && !p2.is_null(),
1967                    lib_handle: handle as usize,
1968                }
1969            }
1970        }
1971    });
1972    let name: &str = if cached.available {
1973        GPU_DEVICE_VULKAN
1974    } else {
1975        GPU_DEVICE_FALLBACK
1976    };
1977    (
1978        GpuAdapterInfo::new(
1979            backend,
1980            name.to_string(),
1981            cached.available,
1982            cached.available,
1983        ),
1984        cached.lib_handle,
1985        0,
1986        0,
1987    )
1988}
1989
1990/// Compiles and links the WebGL 2 64-byte instanced uber-shader program on `wasm32`.
1991///
1992/// # Arguments
1993///
1994/// - `&WebGl2RenderingContext` - Active WebGL 2 canvas context.
1995///
1996/// # Returns
1997///
1998/// - `Option<WebGlProgram>` - Linked shader program when compilation succeeds.
1999#[cfg(target_arch = "wasm32")]
2000pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
2001    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
2002    gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
2003    gl.compile_shader(&vs);
2004    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
2005    gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
2006    gl.compile_shader(&fs);
2007    let program: WebGlProgram = gl.create_program()?;
2008    gl.attach_shader(&program, &vs);
2009    gl.attach_shader(&program, &fs);
2010    gl.link_program(&program);
2011    Some(program)
2012}
2013
2014/// Returns the canonical 5-attribute GLES 3.0 instanced vertex layout matching `GLSL_ES3_UI_VERTEX_SHADER` and 64-byte `GpuPrimitiveInstance`.
2015///
2016/// # Returns
2017///
2018/// - `[Gles3InstanceAttribSpec; 5]` - Ordered instanced vertex attribute bindings (`locations 1..=5`, stride `64`).
2019#[must_use]
2020pub const fn gles3_ui_instance_attribs() -> [Gles3InstanceAttribSpec; 5] {
2021    let stride: i32 = GPU_PRIMITIVE_INSTANCE_BYTES as i32;
2022    [
2023        Gles3InstanceAttribSpec {
2024            location: 1,
2025            components: 4,
2026            is_integer: false,
2027            byte_offset: 0,
2028            stride,
2029        },
2030        Gles3InstanceAttribSpec {
2031            location: 2,
2032            components: 4,
2033            is_integer: false,
2034            byte_offset: 16,
2035            stride,
2036        },
2037        Gles3InstanceAttribSpec {
2038            location: 3,
2039            components: 2,
2040            is_integer: true,
2041            byte_offset: 32,
2042            stride,
2043        },
2044        Gles3InstanceAttribSpec {
2045            location: 4,
2046            components: 4,
2047            is_integer: true,
2048            byte_offset: 40,
2049            stride,
2050        },
2051        Gles3InstanceAttribSpec {
2052            location: 5,
2053            components: 2,
2054            is_integer: true,
2055            byte_offset: 56,
2056            stride,
2057        },
2058    ]
2059}
2060
2061/// Converts a top-left physical scissor rectangle into an OpenGL ES bottom-left scissor tuple `(x, y, width, height)`.
2062///
2063/// # Arguments
2064///
2065/// - `u32` - Surface height in physical pixels.
2066/// - `u32` - Top-left scissor X coordinate.
2067/// - `u32` - Top-left scissor Y coordinate.
2068/// - `u32` - Scissor width in physical pixels.
2069/// - `u32` - Scissor height in physical pixels.
2070///
2071/// # Returns
2072///
2073/// - `[i32; 4]` - OpenGL ES `[x, y_bottom_up, width, height]` scissor rectangle.
2074#[must_use]
2075pub fn gles3_scissor_from_top_down(surface_h: u32, sx: u32, sy: u32, sw: u32, sh: u32) -> [i32; 4] {
2076    let y1: u32 = sy.saturating_add(sh).min(surface_h);
2077    let y_bottom: u32 = surface_h.saturating_sub(y1);
2078    [sx as i32, y_bottom as i32, sw as i32, sh as i32]
2079}
2080
2081/// Selects the lowest-cost texture upload strategy (`MultiRect`, `MergedBbox`, `FullFrame`, or `None`) from dirty rectangles and surface dimensions.
2082///
2083/// # Arguments
2084///
2085/// - `u32` - Framebuffer width in pixels.
2086/// - `u32` - Framebuffer height in pixels.
2087/// - `&[PixelDirtyRect]` - Candidate damaged sub-rectangles in physical pixels.
2088/// - `bool` - When `true`, forces a `FullFrame` upload (e.g. surface resize or first frame).
2089///
2090/// # Returns
2091///
2092/// - `AdaptiveUploadPlan` - Selected strategy, coalesced rectangle list, and byte/cost metrics.
2093#[must_use]
2094pub fn select_adaptive_upload_plan(
2095    fb_w: u32,
2096    fb_h: u32,
2097    dirty_rects: &[PixelDirtyRect],
2098    force_full: bool,
2099) -> AdaptiveUploadPlan {
2100    if fb_w == 0 || fb_h == 0 {
2101        return AdaptiveUploadPlan {
2102            strategy: MobileUploadStrategy::None,
2103            rects: Vec::new(),
2104            total_upload_bytes: 0,
2105            merged_bbox_bytes: 0,
2106            full_frame_bytes: 0,
2107            estimated_cost_score: 0.0,
2108        };
2109    }
2110    let full_rect: PixelDirtyRect = PixelDirtyRect::new(0, 0, fb_w, fb_h);
2111    let full_bytes: usize = full_rect.byte_size_rgba8();
2112    if force_full {
2113        return AdaptiveUploadPlan {
2114            strategy: MobileUploadStrategy::FullFrame,
2115            rects: vec![full_rect],
2116            total_upload_bytes: full_bytes,
2117            merged_bbox_bytes: full_bytes,
2118            full_frame_bytes: full_bytes,
2119            estimated_cost_score: (full_bytes + MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES) as f32,
2120        };
2121    }
2122    let mut coalesced: Vec<PixelDirtyRect> = Vec::with_capacity(dirty_rects.len().min(16));
2123    for rect in dirty_rects.iter() {
2124        let Some(mut clamped) = rect.clamp_to(fb_w, fb_h) else {
2125            continue;
2126        };
2127        let mut merged_any: bool = true;
2128        while merged_any {
2129            merged_any = false;
2130            let mut idx: usize = 0;
2131            while idx < coalesced.len() {
2132                if coalesced[idx].intersects_or_adjacent(clamped, MOBILE_UPLOAD_COALESCE_PAD_PX) {
2133                    let existing: PixelDirtyRect = coalesced.swap_remove(idx);
2134                    clamped = clamped.union_with(existing);
2135                    merged_any = true;
2136                } else {
2137                    idx += 1;
2138                }
2139            }
2140        }
2141        coalesced.push(clamped);
2142    }
2143    if coalesced.is_empty() {
2144        return AdaptiveUploadPlan {
2145            strategy: MobileUploadStrategy::None,
2146            rects: Vec::new(),
2147            total_upload_bytes: 0,
2148            merged_bbox_bytes: 0,
2149            full_frame_bytes: full_bytes,
2150            estimated_cost_score: 0.0,
2151        };
2152    }
2153    let mut merged_bbox: PixelDirtyRect = coalesced[0];
2154    let mut multi_bytes: usize = 0;
2155    for r in coalesced.iter() {
2156        merged_bbox = merged_bbox.union_with(*r);
2157        multi_bytes = multi_bytes.saturating_add(r.byte_size_rgba8());
2158    }
2159    let merged_bytes: usize = merged_bbox.byte_size_rgba8();
2160    let multi_cost: usize = multi_bytes.saturating_add(
2161        coalesced
2162            .len()
2163            .saturating_mul(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES),
2164    );
2165    let merged_cost: usize = merged_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
2166    let full_threshold_bytes: usize =
2167        ((full_bytes as f32) * MOBILE_UPLOAD_FULL_FRAME_COVERAGE_THRESHOLD).round() as usize;
2168    let full_cost: usize = full_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
2169    let multi_eligible: bool = coalesced.len() >= 2
2170        && coalesced.len() <= MOBILE_MAX_MULTI_UPLOAD_RECTS
2171        && multi_bytes <= full_threshold_bytes
2172        && multi_cost < merged_cost
2173        && multi_cost < full_cost;
2174    if multi_eligible {
2175        return AdaptiveUploadPlan {
2176            strategy: MobileUploadStrategy::MultiRect,
2177            rects: coalesced,
2178            total_upload_bytes: multi_bytes,
2179            merged_bbox_bytes: merged_bytes,
2180            full_frame_bytes: full_bytes,
2181            estimated_cost_score: multi_cost as f32,
2182        };
2183    }
2184    if merged_bytes <= full_threshold_bytes && merged_cost < full_cost {
2185        return AdaptiveUploadPlan {
2186            strategy: MobileUploadStrategy::MergedBbox,
2187            rects: vec![merged_bbox],
2188            total_upload_bytes: merged_bytes,
2189            merged_bbox_bytes: merged_bytes,
2190            full_frame_bytes: full_bytes,
2191            estimated_cost_score: merged_cost as f32,
2192        };
2193    }
2194    AdaptiveUploadPlan {
2195        strategy: MobileUploadStrategy::FullFrame,
2196        rects: vec![full_rect],
2197        total_upload_bytes: full_bytes,
2198        merged_bbox_bytes: merged_bytes,
2199        full_frame_bytes: full_bytes,
2200        estimated_cost_score: full_cost as f32,
2201    }
2202}
2203
2204/// Converts a `DamageRegion` into physical `PixelDirtyRect` entries clamped to `(fb_w, fb_h)`.
2205///
2206/// # Arguments
2207///
2208/// - `DamageRegion` - Frame damage region from layout/paint.
2209/// - `u32` - Surface width in physical pixels.
2210/// - `u32` - Surface height in physical pixels.
2211///
2212/// # Returns
2213///
2214/// - `Vec<PixelDirtyRect>` - Clamped physical dirty rectangles (`empty` when no damage).
2215#[must_use]
2216pub fn damage_region_to_pixel_dirty_rects(
2217    damage: DamageRegion,
2218    fb_w: u32,
2219    fb_h: u32,
2220) -> Vec<PixelDirtyRect> {
2221    if fb_w == 0 || fb_h == 0 {
2222        return Vec::new();
2223    }
2224    if damage.get_full_damage() {
2225        return vec![PixelDirtyRect::new(0, 0, fb_w, fb_h)];
2226    }
2227    let Some(r) = damage.resolve(fb_w, fb_h) else {
2228        return Vec::new();
2229    };
2230    let rx0: u32 = (r.get_x().floor().max(0.0) as u32).min(fb_w);
2231    let ry0: u32 = (r.get_y().floor().max(0.0) as u32).min(fb_h);
2232    let rx1: u32 = (r.right().ceil().max(0.0) as u32).clamp(rx0, fb_w);
2233    let ry1: u32 = (r.bottom().ceil().max(0.0) as u32).clamp(ry0, fb_h);
2234    if rx1 > rx0 && ry1 > ry0 {
2235        vec![PixelDirtyRect::new(rx0, ry0, rx1 - rx0, ry1 - ry0)]
2236    } else {
2237        Vec::new()
2238    }
2239}
2240
2241/// Flattens pre-compiled `HardwareRenderer` `GpuBatch` and `GpuBackdropBlurPass` slices into a single direct-GPU frame payload.
2242///
2243/// # Arguments
2244///
2245/// - `u32` - Physical surface width in pixels.
2246/// - `u32` - Physical surface height in pixels.
2247/// - `Color` - Surface clear color.
2248/// - `&[GpuBatch]` - Ordered GPU batches from `HardwareRenderer::active_batches_slice()`.
2249/// - `&[GpuBackdropBlurPass]` - Ordered Dual-Kawase backdrop blur passes.
2250///
2251/// # Returns
2252///
2253/// - `DirectGpuFrameBatch` - Flat 64-byte primitive stream and scissor draw ranges with `cpu_mirror_active = false`.
2254#[must_use]
2255pub fn build_direct_gpu_frame_batch_from_batches(
2256    viewport_width: u32,
2257    viewport_height: u32,
2258    clear_color: Color,
2259    batches: &[GpuBatch],
2260    blur_passes: &[GpuBackdropBlurPass],
2261) -> DirectGpuFrameBatch {
2262    let total_prims: usize = batches
2263        .iter()
2264        .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
2265        .sum();
2266    let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
2267    let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(batches.len());
2268    let vw: u32 = viewport_width.max(1);
2269    let vh: u32 = viewport_height.max(1);
2270    for batch in batches.iter() {
2271        let base_instance: u32 = primitives.len() as u32;
2272        if !batch.get_primitives().is_empty() {
2273            primitives.extend_from_slice(batch.get_primitives());
2274        } else {
2275            for quad in batch.get_instances().iter() {
2276                primitives.push(GpuPrimitiveInstance::from_quad_instance(
2277                    quad,
2278                    batch.get_texture_slot(),
2279                    batch.get_layer_id(),
2280                ));
2281            }
2282        }
2283        let instance_count: u32 = (primitives.len() as u32).saturating_sub(base_instance);
2284        if instance_count == 0 {
2285            continue;
2286        }
2287        let sc: Rect = batch.get_scissor();
2288        let sx: u32 = (sc.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
2289        let sy: u32 = (sc.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
2290        let sw: u32 = (sc.get_width().max(1.0).ceil() as u32)
2291            .min(vw.saturating_sub(sx))
2292            .max(1);
2293        let sh: u32 = (sc.get_height().max(1.0).ceil() as u32)
2294            .min(vh.saturating_sub(sy))
2295            .max(1);
2296        let scroll: [f32; 2] = batch.get_scroll_offset();
2297        draw_ranges.push(DirectGpuBatchRange {
2298            base_instance,
2299            instance_count,
2300            scissor_x: sx,
2301            scissor_y: sy,
2302            scissor_w: sw,
2303            scissor_h: sh,
2304            scroll_x: scroll[0],
2305            scroll_y: scroll[1],
2306            texture_slot: batch.get_texture_slot(),
2307            layer_id: batch.get_layer_id(),
2308            pad: [0, 0],
2309        });
2310    }
2311    let instance_upload_bytes: usize = primitives
2312        .len()
2313        .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
2314    DirectGpuFrameBatch {
2315        viewport_width: vw,
2316        viewport_height: vh,
2317        clear_rgba: clear_color.to_f32_array(),
2318        primitives,
2319        draw_ranges,
2320        backdrop_blurs: blur_passes.to_vec(),
2321        glyph_r8_atlas: None,
2322        image_rgba8_atlas: None,
2323        instance_upload_bytes,
2324        cpu_mirror_active: false,
2325        upload_strategy: MobileUploadStrategy::DirectGpu,
2326    }
2327}
2328
2329/// Appends one `GpuPrimitiveInstance` into `primitives` and extends or opens a scissor-matched `DirectGpuBatchRange`.
2330///
2331/// # Arguments
2332///
2333/// - `&mut Vec<GpuPrimitiveInstance>` - Flat primitive stream.
2334/// - `&mut Vec<DirectGpuBatchRange>` - Ordered draw ranges.
2335/// - `GpuPrimitiveInstance` - Primitive to emit.
2336/// - `Rect` - Active physical scissor clip rectangle.
2337/// - `u32` - Surface width in physical pixels.
2338/// - `u32` - Surface height in physical pixels.
2339fn push_direct_gpu_primitive(
2340    primitives: &mut Vec<GpuPrimitiveInstance>,
2341    draw_ranges: &mut Vec<DirectGpuBatchRange>,
2342    prim: GpuPrimitiveInstance,
2343    clip: Rect,
2344    vw: u32,
2345    vh: u32,
2346) {
2347    let sx: u32 = (clip.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
2348    let sy: u32 = (clip.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
2349    let sw: u32 = (clip.get_width().max(1.0).ceil() as u32)
2350        .min(vw.saturating_sub(sx))
2351        .max(1);
2352    let sh: u32 = (clip.get_height().max(1.0).ceil() as u32)
2353        .min(vh.saturating_sub(sy))
2354        .max(1);
2355    let layer_id: u8 = prim.layer_id();
2356    let base: u32 = primitives.len() as u32;
2357    primitives.push(prim);
2358    if let Some(last) = draw_ranges.last_mut()
2359        && last.get_scissor_x() == sx
2360        && last.get_scissor_y() == sy
2361        && last.get_scissor_w() == sw
2362        && last.get_scissor_h() == sh
2363        && last.get_layer_id() == layer_id
2364        && last.get_instance_count() < MAX_QUADS_PER_BATCH as u32
2365    {
2366        last.set_instance_count(last.get_instance_count().saturating_add(1));
2367        return;
2368    }
2369    draw_ranges.push(DirectGpuBatchRange {
2370        base_instance: base,
2371        instance_count: 1,
2372        scissor_x: sx,
2373        scissor_y: sy,
2374        scissor_w: sw,
2375        scissor_h: sh,
2376        scroll_x: 0.0,
2377        scroll_y: 0.0,
2378        texture_slot: 0,
2379        layer_id,
2380        pad: [0, 0],
2381    });
2382}
2383
2384/// Encodes normalized `[u0, v0, u1, v1]` texel bounds inside an `(atlas_w, atlas_h)` sheet into `[u16; 4]`.
2385///
2386/// # Arguments
2387///
2388/// - `u32` - Atlas width in texels.
2389/// - `u32` - Atlas height in texels.
2390/// - `u32` - Sub-rectangle X coordinate in texels.
2391/// - `u32` - Sub-rectangle Y coordinate in texels.
2392/// - `u32` - Sub-rectangle width in texels.
2393/// - `u32` - Sub-rectangle height in texels.
2394///
2395/// # Returns
2396///
2397/// - `[u16; 4]` - Normalized UV coordinates in `[0..=65535]`.
2398fn encode_atlas_uv_rect(atlas_w: u32, atlas_h: u32, x: u32, y: u32, w: u32, h: u32) -> [u16; 4] {
2399    let inv_w: f32 = 1.0 / (atlas_w.max(1) as f32);
2400    let inv_h: f32 = 1.0 / (atlas_h.max(1) as f32);
2401    let u0: u16 = (((x as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
2402    let v0: u16 = (((y as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
2403    let u1: u16 = ((((x + w) as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
2404    let v1: u16 = ((((y + h) as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
2405    [u0, v0, u1, v1]
2406}
2407
2408/// Packs frame RGBA8 image/sprite slices into a single shelf-packed RGBA8 texture atlas and resolves UV rectangles.
2409///
2410/// # Arguments
2411///
2412/// - `&[DirectGpuImageSlice<'_>]` - Borrowed RGBA8 image and sprite crop descriptors.
2413/// - `u64` - Revision tag stamped onto the output atlas.
2414///
2415/// # Returns
2416///
2417/// - `(Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>)` - Packed RGBA8 image sheet and per-entry normalized UVs.
2418fn pack_frame_image_atlas(
2419    images: &[DirectGpuImageSlice<'_>],
2420    revision: u64,
2421) -> (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) {
2422    if images.is_empty() {
2423        return (None, Vec::new());
2424    }
2425    let mut max_w: u32 = 1;
2426    let mut sum_w: u32 = 1;
2427    for entry in images.iter() {
2428        let cw: u32 = entry.crop.get_width();
2429        max_w = max_w.max(cw.saturating_add(2));
2430        sum_w = sum_w.saturating_add(cw.saturating_add(1));
2431    }
2432    let atlas_w: u32 = sum_w
2433        .clamp(64, 2048)
2434        .max(max_w)
2435        .next_power_of_two()
2436        .min(4096);
2437    let mut placements: Vec<(u32, u32, u32, u32)> = Vec::with_capacity(images.len());
2438    let mut cx: u32 = 1;
2439    let mut cy: u32 = 1;
2440    let mut shelf_h: u32 = 0;
2441    for entry in images.iter() {
2442        let clamped_w: u32 = entry.crop.get_width().min(atlas_w.saturating_sub(2)).max(1);
2443        let clamped_h: u32 = entry.crop.get_height().max(1);
2444        if cx + clamped_w + 1 > atlas_w {
2445            cx = 1;
2446            cy = cy.saturating_add(shelf_h).saturating_add(1);
2447            shelf_h = 0;
2448        }
2449        placements.push((cx, cy, clamped_w, clamped_h));
2450        cx = cx.saturating_add(clamped_w).saturating_add(1);
2451        shelf_h = shelf_h.max(clamped_h);
2452    }
2453    let atlas_h: u32 = cy.saturating_add(shelf_h).saturating_add(1).max(64);
2454    let mut pixels: Vec<u8> = vec![0; (atlas_w as usize) * (atlas_h as usize) * 4];
2455    let mut uvs: Vec<[u16; 4]> = Vec::with_capacity(images.len());
2456    for (idx, entry) in images.iter().enumerate() {
2457        let (dx, dy, copy_w, copy_h): (u32, u32, u32, u32) = placements[idx];
2458        let sx: u32 = entry.crop.get_x();
2459        let sy: u32 = entry.crop.get_y();
2460        let valid_w: u32 = copy_w.min(entry.src_w.saturating_sub(sx));
2461        let valid_h: u32 = copy_h.min(entry.src_h.saturating_sub(sy));
2462        for row in 0..valid_h {
2463            let src_off: usize =
2464                (((sy + row) as usize) * (entry.src_w as usize) + (sx as usize)) * 4;
2465            let dst_off: usize = (((dy + row) as usize) * (atlas_w as usize) + (dx as usize)) * 4;
2466            let row_bytes: usize = (valid_w as usize) * 4;
2467            if src_off + row_bytes <= entry.pixels.len() && dst_off + row_bytes <= pixels.len() {
2468                pixels[dst_off..dst_off + row_bytes]
2469                    .copy_from_slice(&entry.pixels[src_off..src_off + row_bytes]);
2470            }
2471        }
2472        uvs.push(encode_atlas_uv_rect(
2473            atlas_w, atlas_h, dx, dy, valid_w, valid_h,
2474        ));
2475    }
2476    (
2477        Some(DirectGpuAtlasUpload {
2478            width: atlas_w,
2479            height: atlas_h,
2480            revision,
2481            pixels,
2482        }),
2483        uvs,
2484    )
2485}
2486
2487/// 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.
2488///
2489/// # Arguments
2490///
2491/// - `&DisplayList` - Scene draw command stream for the current frame.
2492/// - `Option<&mut GlyphAtlas>` - Shared glyph atlas used to rasterize and pack `PrimKind::GlyphAlpha8` quads.
2493/// - `Option<&NativeSystemFont>` - Optional native OS font provider for glyph rasterization.
2494/// - `u64` - Previously uploaded glyph atlas revision (`0` forces initial upload).
2495///
2496/// # Returns
2497///
2498/// - `DirectGpuFrameBatch` - Self-contained direct-GPU primitive, range, blur, and atlas payload (`cpu_mirror_active = false`).
2499#[must_use]
2500pub fn compile_display_list_direct_gpu_batch(
2501    display_list: &DisplayList,
2502    mut glyph_atlas: Option<&mut GlyphAtlas>,
2503    font_provider: Option<&NativeSystemFont>,
2504    last_glyph_revision: u64,
2505) -> DirectGpuFrameBatch {
2506    let scale: f32 = display_list.get_scale_factor().max(0.5);
2507    let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
2508    let phys_h: u32 = ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
2509    let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
2510    let mut clip_stack: Vec<Rect> = Vec::with_capacity(16);
2511    clip_stack.push(full_clip);
2512    let mut primitives: Vec<GpuPrimitiveInstance> =
2513        Vec::with_capacity(display_list.get_commands().len().saturating_mul(2));
2514    let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(16);
2515    let mut backdrop_blurs: Vec<GpuBackdropBlurPass> = Vec::new();
2516    let mut glyph_fixups: Vec<(usize, GlyphKey)> = Vec::new();
2517    let mut image_entries: Vec<DirectGpuImageSlice<'_>> = Vec::new();
2518    let mut image_fixups: Vec<(usize, usize)> = Vec::new();
2519    let mut clear_rgba: [f32; 4] = COLOR_WHITE.to_f32_array();
2520    let mut active_layer_id: u8 = 0;
2521    for cmd in display_list.get_commands().iter() {
2522        let active_clip: Rect = clip_stack.last().copied().unwrap_or(full_clip);
2523        let clip_arr: [f32; 4] = [
2524            active_clip.get_x(),
2525            active_clip.get_y(),
2526            active_clip.right(),
2527            active_clip.bottom(),
2528        ];
2529        match cmd {
2530            DrawCommand::Clear(c) => {
2531                clear_rgba = c.to_f32_array();
2532            }
2533            DrawCommand::PushClip(rect) => {
2534                let phys: Rect = snap_physical_rect(*rect, scale);
2535                clip_stack.push(active_clip.intersect(phys).unwrap_or_default());
2536            }
2537            DrawCommand::PushRoundedClip { rect, .. } => {
2538                let phys: Rect = snap_physical_rect(*rect, scale);
2539                clip_stack.push(active_clip.intersect(phys).unwrap_or_default());
2540            }
2541            DrawCommand::PopClip => {
2542                if clip_stack.len() > 1 {
2543                    let _: Option<Rect> = clip_stack.pop();
2544                }
2545            }
2546            DrawCommand::FillRoundedRect {
2547                rect,
2548                color,
2549                radius,
2550                border,
2551            } => {
2552                let snapped: Rect = snap_physical_rect(*rect, scale);
2553                let quad: [f32; 4] = [
2554                    snapped.get_x(),
2555                    snapped.get_y(),
2556                    snapped.get_width(),
2557                    snapped.get_height(),
2558                ];
2559                if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
2560                    continue;
2561                }
2562                let bw: f32 = if border.get_width() > 0.0 {
2563                    (border.get_width() * scale).max(1.0)
2564                } else {
2565                    0.0
2566                };
2567                let q: GpuQuadInstance = GpuQuadInstance {
2568                    rect: quad,
2569                    clip: clip_arr,
2570                    color: color.to_f32_array(),
2571                    secondary_color: border.get_color().to_f32_array(),
2572                    radii: [
2573                        radius.get_top_left() * scale,
2574                        radius.get_top_right() * scale,
2575                        radius.get_bottom_right() * scale,
2576                        radius.get_bottom_left() * scale,
2577                    ],
2578                    stroke_or_blur: bw,
2579                    angle_rad: 0.0,
2580                    kind: GpuPrimitiveKind::RoundedRect as u32,
2581                    reserved: 0,
2582                };
2583                push_direct_gpu_primitive(
2584                    &mut primitives,
2585                    &mut draw_ranges,
2586                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
2587                    active_clip,
2588                    phys_w,
2589                    phys_h,
2590                );
2591            }
2592            DrawCommand::LinearGradientRect {
2593                rect,
2594                gradient,
2595                radius,
2596            } => {
2597                let snapped: Rect = snap_physical_rect(*rect, scale);
2598                let quad: [f32; 4] = [
2599                    snapped.get_x(),
2600                    snapped.get_y(),
2601                    snapped.get_width(),
2602                    snapped.get_height(),
2603                ];
2604                if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
2605                    continue;
2606                }
2607                let q: GpuQuadInstance = GpuQuadInstance {
2608                    rect: quad,
2609                    clip: clip_arr,
2610                    color: gradient.get_start_color().to_f32_array(),
2611                    secondary_color: gradient.get_end_color().to_f32_array(),
2612                    radii: [
2613                        radius.get_top_left() * scale,
2614                        radius.get_top_right() * scale,
2615                        radius.get_bottom_right() * scale,
2616                        radius.get_bottom_left() * scale,
2617                    ],
2618                    stroke_or_blur: 0.0,
2619                    angle_rad: gradient.get_angle_deg().to_radians(),
2620                    kind: GpuPrimitiveKind::Gradient as u32,
2621                    reserved: 0,
2622                };
2623                push_direct_gpu_primitive(
2624                    &mut primitives,
2625                    &mut draw_ranges,
2626                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
2627                    active_clip,
2628                    phys_w,
2629                    phys_h,
2630                );
2631            }
2632            DrawCommand::BoxShadow {
2633                rect,
2634                radius,
2635                shadow,
2636            } => {
2637                let spread: f32 = shadow.get_spread_radius() * scale;
2638                let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
2639                let sigma: f32 = (blur * 0.5).max(0.75);
2640                let pad: f32 = (sigma * 3.0).ceil();
2641                let base_rect: Rect = snap_physical_rect(*rect, scale);
2642                let cx: f32 = base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
2643                let cy: f32 = base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
2644                let cw: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
2645                let ch: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
2646                let q: GpuQuadInstance = GpuQuadInstance {
2647                    rect: [cx - pad, cy - pad, cw + pad * 2.0, ch + pad * 2.0],
2648                    clip: clip_arr,
2649                    color: shadow.get_color().to_f32_array(),
2650                    secondary_color: [0.0; 4],
2651                    radii: [
2652                        (radius.get_top_left() * scale + spread).max(0.0),
2653                        (radius.get_top_right() * scale + spread).max(0.0),
2654                        (radius.get_bottom_right() * scale + spread).max(0.0),
2655                        (radius.get_bottom_left() * scale + spread).max(0.0),
2656                    ],
2657                    stroke_or_blur: sigma,
2658                    angle_rad: pad,
2659                    kind: GpuPrimitiveKind::Shadow as u32,
2660                    reserved: 0,
2661                };
2662                push_direct_gpu_primitive(
2663                    &mut primitives,
2664                    &mut draw_ranges,
2665                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
2666                    active_clip,
2667                    phys_w,
2668                    phys_h,
2669                );
2670            }
2671            DrawCommand::BackdropBlur {
2672                rect,
2673                radius,
2674                blur_radius,
2675            } => {
2676                let snapped: Rect = snap_physical_rect(*rect, scale);
2677                let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 96.0);
2678                let radii_px: [f32; 4] = [
2679                    radius.get_top_left() * scale,
2680                    radius.get_top_right() * scale,
2681                    radius.get_bottom_right() * scale,
2682                    radius.get_bottom_left() * scale,
2683                ];
2684                let halo: Rect = Rect::new(
2685                    (snapped.get_x() - phys_blur).max(0.0),
2686                    (snapped.get_y() - phys_blur).max(0.0),
2687                    (snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
2688                    (snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
2689                );
2690                backdrop_blurs.push(GpuBackdropBlurPass {
2691                    bounds: snapped,
2692                    input_bounds: halo,
2693                    clip_rect: active_clip,
2694                    radii: radii_px,
2695                    blur_radius: phys_blur,
2696                    layer_id: active_layer_id,
2697                });
2698                active_layer_id = active_layer_id.saturating_add(1);
2699            }
2700            DrawCommand::TextRun { rect, text, style } => {
2701                if text.is_empty()
2702                    || active_clip.get_width() <= 0.0
2703                    || active_clip.get_height() <= 0.0
2704                {
2705                    continue;
2706                }
2707                if let Some(atlas) = glyph_atlas.as_deref_mut() {
2708                    let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
2709                    let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
2710                        text,
2711                        *style,
2712                        Some(rect.get_width().max(1.0)),
2713                    );
2714                    let line_h: f32 = meas.get_line_height_px() * scale;
2715                    let letter_sp: f32 = style.get_letter_spacing() * scale;
2716                    let rect_w_px: f32 = rect.get_width() * scale;
2717                    let color_rgba: u32 = GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
2718                    let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
2719                        PrimKind::GlyphAlpha8,
2720                        0,
2721                        0,
2722                        active_layer_id,
2723                    );
2724                    let mut line_glyphs: Vec<(Option<GlyphKey>, u32, u32, f32)> = Vec::new();
2725                    for (line_idx, line) in meas.get_lines().iter().enumerate() {
2726                        line_glyphs.clear();
2727                        let mut line_w_px: f32 = 0.0;
2728                        for ch in line.get_text().chars() {
2729                            if ch == ' ' || ch == '\t' {
2730                                let sp_adv: f32 = measure_char_advance(ch, *style) * scale;
2731                                line_glyphs.push((None, 0, 0, sp_adv));
2732                                line_w_px += sp_adv;
2733                                continue;
2734                            }
2735                            let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_px, *style);
2736                            let (gw, gh, adv): (u32, u32, f32) = {
2737                                let g: &RasterizedGlyph = match font_provider {
2738                                    Some(fp) => atlas.get_or_rasterize_with(key, fp),
2739                                    None => atlas.get_or_rasterize(key),
2740                                };
2741                                (
2742                                    g.get_width(),
2743                                    g.get_height(),
2744                                    (g.get_advance() as f32).max(1.0) + letter_sp,
2745                                )
2746                            };
2747                            line_glyphs.push((Some(key), gw, gh, adv));
2748                            line_w_px += adv;
2749                        }
2750                        let align_offset: f32 = match style.get_align() {
2751                            TextAlign::Center => ((rect_w_px - line_w_px) * 0.5).max(0.0),
2752                            TextAlign::Right => (rect_w_px - line_w_px).max(0.0),
2753                            TextAlign::Left => 0.0,
2754                        };
2755                        let base_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h;
2756                        let mut pen_x: f32 = rect.get_x() * scale + align_offset;
2757                        for &(key_opt, gw, gh, adv) in line_glyphs.iter() {
2758                            if let Some(key) = key_opt
2759                                && gw > 0
2760                                && gh > 0
2761                            {
2762                                let y_off: f32 = ((line_h - (gh as f32)) * 0.5).max(0.0);
2763                                let prim_idx: usize = primitives.len();
2764                                let prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
2765                                    rect: [
2766                                        pen_x.round(),
2767                                        (base_y + y_off).round(),
2768                                        gw as f32,
2769                                        gh as f32,
2770                                    ],
2771                                    clip_rect: clip_arr,
2772                                    color_rgba,
2773                                    aux_color_rgba: 0,
2774                                    uv_rect: [0, 0, 0, 0],
2775                                    radii_border: [0; 4],
2776                                    kind_flags,
2777                                    extra_param: 0,
2778                                };
2779                                push_direct_gpu_primitive(
2780                                    &mut primitives,
2781                                    &mut draw_ranges,
2782                                    prim,
2783                                    active_clip,
2784                                    phys_w,
2785                                    phys_h,
2786                                );
2787                                glyph_fixups.push((prim_idx, key));
2788                            }
2789                            pen_x += adv;
2790                        }
2791                    }
2792                } else {
2793                    let q: GpuQuadInstance = GpuQuadInstance {
2794                        rect: [
2795                            rect.get_x() * scale,
2796                            rect.get_y() * scale,
2797                            rect.get_width() * scale,
2798                            rect.get_height() * scale,
2799                        ],
2800                        clip: clip_arr,
2801                        color: style.get_color().to_f32_array(),
2802                        secondary_color: [0.0; 4],
2803                        radii: [0.0; 4],
2804                        stroke_or_blur: style.get_font_size() * scale,
2805                        angle_rad: 0.0,
2806                        kind: GpuPrimitiveKind::Glyph as u32,
2807                        reserved: text.chars().count() as u32,
2808                    };
2809                    push_direct_gpu_primitive(
2810                        &mut primitives,
2811                        &mut draw_ranges,
2812                        GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
2813                        active_clip,
2814                        phys_w,
2815                        phys_h,
2816                    );
2817                }
2818            }
2819            DrawCommand::TextCaret {
2820                text_rect,
2821                content_rect,
2822                text,
2823                style,
2824                caret_height,
2825                color,
2826                multiline,
2827            } => {
2828                if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
2829                    continue;
2830                }
2831                let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
2832                    text,
2833                    *style,
2834                    if *multiline {
2835                        Some(content_rect.get_width().max(1.0))
2836                    } else {
2837                        None
2838                    },
2839                );
2840                let last_w: f32 = meas
2841                    .get_lines()
2842                    .last()
2843                    .map(TextLine::get_width)
2844                    .unwrap_or(0.0);
2845                let line_idx: usize = meas.get_lines().len().saturating_sub(1);
2846                let caret_x: f32 =
2847                    (text_rect.get_x() + last_w + if last_w > 0.0 { 1.5 } else { 0.0 }).clamp(
2848                        content_rect.get_x(),
2849                        (content_rect.right() - 2.0).max(content_rect.get_x()),
2850                    );
2851                let caret_y: f32 = if *multiline {
2852                    (content_rect.get_y()
2853                        + (line_idx as f32) * meas.get_line_height_px()
2854                        + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
2855                    .clamp(
2856                        content_rect.get_y(),
2857                        (content_rect.bottom() - caret_height).max(content_rect.get_y()),
2858                    )
2859                } else {
2860                    content_rect.get_y()
2861                        + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
2862                };
2863                let q: GpuQuadInstance = GpuQuadInstance {
2864                    rect: [
2865                        caret_x * scale,
2866                        caret_y * scale,
2867                        (1.5 * scale).max(1.0),
2868                        (caret_height * scale).max(2.0),
2869                    ],
2870                    clip: clip_arr,
2871                    color: color.to_f32_array(),
2872                    secondary_color: [0.0; 4],
2873                    radii: [0.5 * scale; 4],
2874                    stroke_or_blur: 0.0,
2875                    angle_rad: 0.0,
2876                    kind: GpuPrimitiveKind::RoundedRect as u32,
2877                    reserved: 0,
2878                };
2879                push_direct_gpu_primitive(
2880                    &mut primitives,
2881                    &mut draw_ranges,
2882                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
2883                    active_clip,
2884                    phys_w,
2885                    phys_h,
2886                );
2887            }
2888            DrawCommand::Image {
2889                rect,
2890                buffer,
2891                radius,
2892            } => {
2893                let snapped: Rect = snap_physical_rect(*rect, scale);
2894                let img_w: u32 = buffer.get_width();
2895                let img_h: u32 = buffer.get_height();
2896                if img_w == 0
2897                    || img_h == 0
2898                    || snapped.get_width() <= 0.0
2899                    || snapped.get_height() <= 0.0
2900                {
2901                    continue;
2902                }
2903                let img_idx: usize = image_entries.len();
2904                image_entries.push(DirectGpuImageSlice {
2905                    src_w: img_w,
2906                    src_h: img_h,
2907                    pixels: buffer.get_pixels(),
2908                    crop: PixelDirtyRect::new(0, 0, img_w, img_h),
2909                });
2910                let q: GpuQuadInstance = GpuQuadInstance {
2911                    rect: [
2912                        snapped.get_x(),
2913                        snapped.get_y(),
2914                        snapped.get_width(),
2915                        snapped.get_height(),
2916                    ],
2917                    clip: clip_arr,
2918                    color: [1.0, 1.0, 1.0, 1.0],
2919                    secondary_color: [0.0; 4],
2920                    radii: [
2921                        radius.get_top_left() * scale,
2922                        radius.get_top_right() * scale,
2923                        radius.get_bottom_right() * scale,
2924                        radius.get_bottom_left() * scale,
2925                    ],
2926                    stroke_or_blur: 0.0,
2927                    angle_rad: 0.0,
2928                    kind: GpuPrimitiveKind::TexturedQuad as u32,
2929                    reserved: 0,
2930                };
2931                let prim_idx: usize = primitives.len();
2932                push_direct_gpu_primitive(
2933                    &mut primitives,
2934                    &mut draw_ranges,
2935                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
2936                    active_clip,
2937                    phys_w,
2938                    phys_h,
2939                );
2940                image_fixups.push((prim_idx, img_idx));
2941            }
2942            DrawCommand::SharedImage {
2943                rect,
2944                width,
2945                height,
2946                pixels,
2947                radius,
2948            } => {
2949                let snapped: Rect = snap_physical_rect(*rect, scale);
2950                if *width == 0
2951                    || *height == 0
2952                    || snapped.get_width() <= 0.0
2953                    || snapped.get_height() <= 0.0
2954                {
2955                    continue;
2956                }
2957                let img_idx: usize = image_entries.len();
2958                image_entries.push(DirectGpuImageSlice {
2959                    src_w: *width,
2960                    src_h: *height,
2961                    pixels: pixels.as_slice(),
2962                    crop: PixelDirtyRect::new(0, 0, *width, *height),
2963                });
2964                let q: GpuQuadInstance = GpuQuadInstance {
2965                    rect: [
2966                        snapped.get_x(),
2967                        snapped.get_y(),
2968                        snapped.get_width(),
2969                        snapped.get_height(),
2970                    ],
2971                    clip: clip_arr,
2972                    color: [1.0, 1.0, 1.0, 1.0],
2973                    secondary_color: [0.0; 4],
2974                    radii: [
2975                        radius.get_top_left() * scale,
2976                        radius.get_top_right() * scale,
2977                        radius.get_bottom_right() * scale,
2978                        radius.get_bottom_left() * scale,
2979                    ],
2980                    stroke_or_blur: 0.0,
2981                    angle_rad: 0.0,
2982                    kind: GpuPrimitiveKind::TexturedQuad as u32,
2983                    reserved: 0,
2984                };
2985                let prim_idx: usize = primitives.len();
2986                push_direct_gpu_primitive(
2987                    &mut primitives,
2988                    &mut draw_ranges,
2989                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
2990                    active_clip,
2991                    phys_w,
2992                    phys_h,
2993                );
2994                image_fixups.push((prim_idx, img_idx));
2995            }
2996            DrawCommand::SpriteRegion {
2997                rect,
2998                buffer,
2999                src_rect,
3000                tint,
3001            } => {
3002                let snapped: Rect = snap_physical_rect(*rect, scale);
3003                let img_w: u32 = buffer.get_width();
3004                let img_h: u32 = buffer.get_height();
3005                let sx: u32 = (src_rect.get_x().max(0.0).floor() as u32).min(img_w);
3006                let sy: u32 = (src_rect.get_y().max(0.0).floor() as u32).min(img_h);
3007                let sw: u32 =
3008                    (src_rect.get_width().max(1.0).ceil() as u32).min(img_w.saturating_sub(sx));
3009                let sh: u32 =
3010                    (src_rect.get_height().max(1.0).ceil() as u32).min(img_h.saturating_sub(sy));
3011                if sw == 0 || sh == 0 || snapped.get_width() <= 0.0 || snapped.get_height() <= 0.0 {
3012                    continue;
3013                }
3014                let img_idx: usize = image_entries.len();
3015                image_entries.push(DirectGpuImageSlice {
3016                    src_w: img_w,
3017                    src_h: img_h,
3018                    pixels: buffer.get_pixels(),
3019                    crop: PixelDirtyRect::new(sx, sy, sw, sh),
3020                });
3021                let q: GpuQuadInstance = GpuQuadInstance {
3022                    rect: [
3023                        snapped.get_x(),
3024                        snapped.get_y(),
3025                        snapped.get_width(),
3026                        snapped.get_height(),
3027                    ],
3028                    clip: clip_arr,
3029                    color: tint.to_f32_array(),
3030                    secondary_color: [0.0; 4],
3031                    radii: [0.0; 4],
3032                    stroke_or_blur: 0.0,
3033                    angle_rad: 0.0,
3034                    kind: GpuPrimitiveKind::TexturedQuad as u32,
3035                    reserved: 1,
3036                };
3037                let prim_idx: usize = primitives.len();
3038                push_direct_gpu_primitive(
3039                    &mut primitives,
3040                    &mut draw_ranges,
3041                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
3042                    active_clip,
3043                    phys_w,
3044                    phys_h,
3045                );
3046                image_fixups.push((prim_idx, img_idx));
3047            }
3048            DrawCommand::Circle {
3049                center,
3050                radius,
3051                color,
3052            } => {
3053                let r: f32 = radius * scale;
3054                let q: GpuQuadInstance = GpuQuadInstance {
3055                    rect: [
3056                        center.get_x() * scale - r,
3057                        center.get_y() * scale - r,
3058                        r * 2.0,
3059                        r * 2.0,
3060                    ],
3061                    clip: clip_arr,
3062                    color: color.to_f32_array(),
3063                    secondary_color: [0.0; 4],
3064                    radii: [r; 4],
3065                    stroke_or_blur: 0.0,
3066                    angle_rad: 0.0,
3067                    kind: GpuPrimitiveKind::Circle as u32,
3068                    reserved: 0,
3069                };
3070                push_direct_gpu_primitive(
3071                    &mut primitives,
3072                    &mut draw_ranges,
3073                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
3074                    active_clip,
3075                    phys_w,
3076                    phys_h,
3077                );
3078            }
3079            DrawCommand::Line {
3080                from,
3081                to,
3082                color,
3083                width,
3084            } => {
3085                let dx: f32 = (to.get_x() - from.get_x()) * scale;
3086                let dy: f32 = (to.get_y() - from.get_y()) * scale;
3087                let q: GpuQuadInstance = GpuQuadInstance {
3088                    rect: [
3089                        from.get_x().min(to.get_x()) * scale,
3090                        from.get_y().min(to.get_y()) * scale,
3091                        dx.abs().max(width * scale),
3092                        dy.abs().max(width * scale),
3093                    ],
3094                    clip: clip_arr,
3095                    color: color.to_f32_array(),
3096                    secondary_color: [0.0; 4],
3097                    radii: [
3098                        from.get_x() * scale,
3099                        from.get_y() * scale,
3100                        to.get_x() * scale,
3101                        to.get_y() * scale,
3102                    ],
3103                    stroke_or_blur: width * scale,
3104                    angle_rad: dy.atan2(dx),
3105                    kind: GpuPrimitiveKind::Line as u32,
3106                    reserved: 0,
3107                };
3108                push_direct_gpu_primitive(
3109                    &mut primitives,
3110                    &mut draw_ranges,
3111                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
3112                    active_clip,
3113                    phys_w,
3114                    phys_h,
3115                );
3116            }
3117            DrawCommand::Triangle { p0, p1, p2, color } => {
3118                let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale;
3119                let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale;
3120                let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale;
3121                let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale;
3122                let q: GpuQuadInstance = GpuQuadInstance {
3123                    rect: [
3124                        min_x,
3125                        min_y,
3126                        (max_x - min_x).max(1.0),
3127                        (max_y - min_y).max(1.0),
3128                    ],
3129                    clip: clip_arr,
3130                    color: color.to_f32_array(),
3131                    secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
3132                    radii: [
3133                        p1.get_x() * scale,
3134                        p1.get_y() * scale,
3135                        p2.get_x() * scale,
3136                        p2.get_y() * scale,
3137                    ],
3138                    stroke_or_blur: 0.0,
3139                    angle_rad: 0.0,
3140                    kind: GpuPrimitiveKind::Triangle as u32,
3141                    reserved: 3,
3142                };
3143                push_direct_gpu_primitive(
3144                    &mut primitives,
3145                    &mut draw_ranges,
3146                    GpuPrimitiveInstance::from_quad_instance(&q, 0, active_layer_id),
3147                    active_clip,
3148                    phys_w,
3149                    phys_h,
3150                );
3151            }
3152        }
3153    }
3154    let mut glyph_r8_atlas: Option<DirectGpuAtlasUpload> = None;
3155    if let Some(atlas) = glyph_atlas.as_deref()
3156        && (!glyph_fixups.is_empty() || atlas.get_revision() != last_glyph_revision)
3157        && !atlas.is_empty()
3158    {
3159        let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
3160        let aw: u32 = packed.get_width();
3161        let ah: u32 = packed.get_height();
3162        for &(prim_idx, key) in glyph_fixups.iter() {
3163            if let Some(&(gx, gy, gw, gh)) = packed.get_regions().get(&key) {
3164                primitives[prim_idx].set_uv_rect(encode_atlas_uv_rect(aw, ah, gx, gy, gw, gh));
3165            }
3166        }
3167        if packed.get_revision() != last_glyph_revision {
3168            let rgba: &[u8] = packed.get_pixels().as_slice();
3169            let mut r8: Vec<u8> = Vec::with_capacity((aw as usize).saturating_mul(ah as usize));
3170            for px in rgba.as_chunks::<4>().0 {
3171                r8.push(px[3]);
3172            }
3173            glyph_r8_atlas = Some(DirectGpuAtlasUpload {
3174                width: aw,
3175                height: ah,
3176                revision: packed.get_revision(),
3177                pixels: r8,
3178            });
3179        }
3180    }
3181    let (image_rgba8_atlas, img_uvs): (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) =
3182        pack_frame_image_atlas(&image_entries, display_list.fast_hash());
3183    for &(prim_idx, img_idx) in image_fixups.iter() {
3184        if let Some(&uv) = img_uvs.get(img_idx) {
3185            primitives[prim_idx].set_uv_rect(uv);
3186        }
3187    }
3188    let glyph_bytes: usize = glyph_r8_atlas
3189        .as_ref()
3190        .map(|a: &DirectGpuAtlasUpload| a.get_pixels().len())
3191        .unwrap_or(0);
3192    let image_bytes: usize = image_rgba8_atlas
3193        .as_ref()
3194        .map(|a: &DirectGpuAtlasUpload| a.get_pixels().len())
3195        .unwrap_or(0);
3196    let instance_upload_bytes: usize = primitives
3197        .len()
3198        .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES)
3199        .saturating_add(glyph_bytes)
3200        .saturating_add(image_bytes);
3201    DirectGpuFrameBatch {
3202        viewport_width: phys_w,
3203        viewport_height: phys_h,
3204        clear_rgba,
3205        primitives,
3206        draw_ranges,
3207        backdrop_blurs,
3208        glyph_r8_atlas,
3209        image_rgba8_atlas,
3210        instance_upload_bytes,
3211        cpu_mirror_active: false,
3212        upload_strategy: MobileUploadStrategy::DirectGpu,
3213    }
3214}