euv-core 0.47.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
use super::*;

/// Probes the host OS for a physical GPU adapter, compiles or loads cached native UI pipelines, and returns handles.
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested graphics backend.
///
/// # Returns
///
/// - `(GpuAdapterInfo, usize, usize, usize)` - Adapter info plus `(device, queue, library)` raw handles.
#[must_use]
pub fn probe_native_gpu(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
    let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
    (
        probed.adapter,
        probed.device_handle,
        probed.queue_handle,
        probed.library_handle,
    )
}

/// Probes the host OS for a physical GPU adapter, cached uber-shader & blur pipelines, and fallback textures.
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested graphics backend.
///
/// # Returns
///
/// - `NativeGpuProbeOutput` - Adapter info plus retained device, queue, library, pipeline, and dummy texture handles.
#[must_use]
pub(crate) fn probe_native_gpu_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
    if backend == GraphicsBackend::Headless || backend == GraphicsBackend::SoftwareCpu {
        return NativeGpuProbeOutput {
            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
            device_handle: 0,
            queue_handle: 0,
            library_handle: 0,
            pipeline_handle: 0,
            blur_pipeline_handle: 0,
            dummy_r8_tex: 0,
            dummy_rgba8_tex: 0,
        };
    }
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        probe_apple_metal_full(backend)
    }
    #[cfg(target_os = "windows")]
    {
        let (adapter, device_handle, queue_handle, library_handle): (
            GpuAdapterInfo,
            usize,
            usize,
            usize,
        ) = probe_windows_d3d12(backend);
        NativeGpuProbeOutput {
            adapter,
            device_handle,
            queue_handle,
            library_handle,
            pipeline_handle: 0,
            blur_pipeline_handle: 0,
            dummy_r8_tex: 0,
            dummy_rgba8_tex: 0,
        }
    }
    #[cfg(any(target_os = "linux", target_os = "android"))]
    {
        let (adapter, device_handle, queue_handle, library_handle): (
            GpuAdapterInfo,
            usize,
            usize,
            usize,
        ) = probe_vulkan_runtime(backend);
        NativeGpuProbeOutput {
            adapter,
            device_handle,
            queue_handle,
            library_handle,
            pipeline_handle: 0,
            blur_pipeline_handle: 0,
            dummy_r8_tex: 0,
            dummy_rgba8_tex: 0,
        }
    }
    #[cfg(target_arch = "wasm32")]
    {
        NativeGpuProbeOutput {
            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
            device_handle: 0,
            queue_handle: 0,
            library_handle: 0,
            pipeline_handle: 0,
            blur_pipeline_handle: 0,
            dummy_r8_tex: 0,
            dummy_rgba8_tex: 0,
        }
    }
    #[cfg(not(any(target_arch = "wasm32", unix, windows)))]
    {
        NativeGpuProbeOutput {
            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
            device_handle: 0,
            queue_handle: 0,
            library_handle: 0,
            pipeline_handle: 0,
            blur_pipeline_handle: 0,
            dummy_r8_tex: 0,
            dummy_rgba8_tex: 0,
        }
    }
}

/// Uploads instanced quad buffers and submits a command buffer to the active physical GPU.
///
/// # Arguments
///
/// - `usize` - Raw OS device handle.
/// - `usize` - Raw OS command queue handle.
/// - `&[GpuBatch]` - Compiled instanced draw batches.
///
/// # Returns
///
/// - `usize` - Total GPU instances uploaded and submitted.
pub fn submit_native_gpu_batches(
    device_handle: usize,
    queue_handle: usize,
    batches: &[GpuBatch],
) -> usize {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        metal_submit_batches(device_handle, queue_handle, batches)
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _: (usize, usize) = (device_handle, queue_handle);
        batches
            .iter()
            .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
            .sum()
    }
}

/// Uploads packed 64-byte `GpuPrimitiveInstance` streams into a fenced 3-slot ring, encodes real instanced draw calls when a `CAMetalLayer` is bound, and commits.
///
/// # Arguments
///
/// - `&mut NativeGpuDriver` - Mutable GPU driver holding ring slots, pipelines, textures, and surface handle.
/// - `u32` - Physical surface width in pixels.
/// - `u32` - Physical surface height in pixels.
/// - `Color` - Surface clear color.
/// - `&[GpuBatch]` - Ordered instanced draw batches.
///
/// # Returns
///
/// - `usize` - Total 64-byte `GpuPrimitiveInstance` records uploaded and submitted.
pub(crate) fn submit_native_gpu_ring_frame(
    driver: &mut NativeGpuDriver,
    width: u32,
    height: u32,
    clear_color: Color,
    batches: &[GpuBatch],
) -> usize {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        metal_submit_ring_frame(driver, width, height, clear_color, batches)
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _: (&mut NativeGpuDriver, u32, u32, Color) = (driver, width, height, clear_color);
        batches
            .iter()
            .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
            .sum()
    }
}

/// Configures a native `CAMetalLayer` for triple-buffered direct-draw presentation (`framebufferOnly = YES`, `maximumDrawableCount = 3`).
///
/// # Arguments
///
/// - `usize` - Raw OS device handle (`id<MTLDevice>`).
/// - `usize` - Raw `CAMetalLayer*` pointer.
pub(crate) fn configure_native_metal_layer(device_handle: usize, layer_handle: usize) {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        metal_configure_layer(device_handle, layer_handle);
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _: (usize, usize) = (device_handle, layer_handle);
    }
}

/// Uploads a dirty sub-rectangle of R8 or RGBA8 texels into a resident native GPU texture without full-texture reallocation.
///
/// # Arguments
///
/// - `usize` - Raw OS GPU device handle.
/// - `&mut usize` - Resident native texture handle (`0` triggers lazy creation).
/// - `GpuAtlasPixelFormat` - Target texture format (`R8Unorm` or `Rgba8Unorm`).
/// - `(u32, u32)` - Full backing texture dimensions `(tex_w, tex_h)`.
/// - `(u32, u32, u32, u32)` - Dirty rectangle `(x, y, width, height)`.
/// - `&[u8]` - Tightly or stride-packed source texel bytes.
/// - `usize` - Row stride in bytes of `bytes`.
///
/// # Returns
///
/// - `bool` - `true` when the dirty sub-rectangle was uploaded cleanly.
pub(crate) fn upload_native_texture_dirty_rect(
    device_handle: usize,
    texture_handle: &mut usize,
    format: GpuAtlasPixelFormat,
    tex_dims: (u32, u32),
    dirty_rect: (u32, u32, u32, u32),
    bytes: &[u8],
    bytes_per_row: usize,
) -> bool {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        metal_upload_texture_dirty_rect(
            device_handle,
            texture_handle,
            format,
            tex_dims,
            dirty_rect,
            bytes,
            bytes_per_row,
        )
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _: usize = device_handle;
        let _: &mut usize = texture_handle;
        let _: GpuAtlasPixelFormat = format;
        let _: (u32, u32) = tex_dims;
        let _: (u32, u32, u32, u32) = dirty_rect;
        let _: &[u8] = bytes;
        let _: usize = bytes_per_row;
        false
    }
}

/// Retains a single native GPU object handle cleanly so each owning slot holds an independent reference.
///
/// # Arguments
///
/// - `usize` - Raw OS GPU object handle (`0` returns `0`).
///
/// # Returns
///
/// - `usize` - Independently retained GPU object handle.
pub(crate) fn retain_native_gpu_object(handle: usize) -> usize {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        mtl_retain_handle(handle)
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        handle
    }
}

/// Releases a single retained native GPU object handle cleanly on teardown.
///
/// # Arguments
///
/// - `usize` - Retained OS GPU handle (`0` is a no-op).
pub(crate) fn release_native_gpu_object(handle: usize) {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        if handle != 0 {
            let sel: &MetalSelectors = cached_metal_selectors();
            mtl_send_void0(handle as *mut c_void, sel.release as *mut c_void);
        }
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _: usize = handle;
    }
}

/// Releases native GPU handles on driver teardown.
///
/// # Arguments
///
/// - `usize` - Raw device handle.
/// - `usize` - Raw command queue handle.
/// - `usize` - Raw shader library handle.
pub fn release_native_gpu_handles(
    device_handle: usize,
    queue_handle: usize,
    library_handle: usize,
) {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        metal_release_handles(device_handle, queue_handle, library_handle);
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
    }
}

/// Returns the latest hardware presentation timestamp in nanoseconds recorded by the GPU driver.
///
/// # Returns
///
/// - `u64` - Presentation timestamp in nanoseconds (`0` before first hardware present).
#[must_use]
pub fn native_gpu_last_presented_ns() -> u64 {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        METAL_LAST_PRESENTED_NS.load(Ordering::Relaxed)
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        0
    }
}

/// Returns the latest hardware GPU command execution duration in nanoseconds.
///
/// # Returns
///
/// - `u64` - GPU execution duration in nanoseconds (`0` before first completed GPU command buffer).
#[must_use]
pub fn native_gpu_last_exec_ns() -> u64 {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        METAL_LAST_GPU_EXEC_NS.load(Ordering::Relaxed)
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        0
    }
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "Metal", kind = "framework")]
unsafe extern "C" {
    /// Creates the default Apple Metal GPU device handle.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Retained `id<MTLDevice>` pointer or null.
    fn MTLCreateSystemDefaultDevice() -> *mut c_void;
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "objc")]
unsafe extern "C" {
    /// Looks up an Objective-C class pointer by null-terminated C name.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Null-terminated class name.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Objective-C class pointer or null.
    fn objc_getClass(name: *const c_char) -> *mut c_void;
    /// Registers an Objective-C selector by null-terminated C name.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Null-terminated selector name.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Registered selector pointer.
    fn sel_registerName(name: *const c_char) -> *mut c_void;
    /// Pushes a scoped Objective-C autorelease pool frame.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Autorelease pool token to pop via `objc_autoreleasePoolPop`.
    fn objc_autoreleasePoolPush() -> *mut c_void;
    /// Pops and drains a scoped Objective-C autorelease pool frame.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Pool token returned by `objc_autoreleasePoolPush`.
    fn objc_autoreleasePoolPop(pool: *mut c_void);
    /// Objective-C dynamic message dispatch entry point.
    fn objc_msgSend();
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" {
    /// Standard Apple `libSystem` class symbol identifying static global Objective-C blocks.
    static _NSConcreteGlobalBlock: c_void;
}

/// Registers an Objective-C selector from a static null-terminated string literal.
///
/// # Arguments
///
/// - `&'static str` - Null-terminated selector name.
///
/// # Returns
///
/// - `*mut c_void` - Registered Objective-C selector pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_sel_cstr(name: &'static str) -> *mut c_void {
    unsafe { sel_registerName(name.as_ptr().cast::<c_char>()) }
}

/// Looks up an Objective-C class from a static null-terminated string literal.
///
/// # Arguments
///
/// - `&'static str` - Null-terminated class name.
///
/// # Returns
///
/// - `*mut c_void` - Objective-C class pointer or null.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_cls_cstr(name: &'static str) -> *mut c_void {
    unsafe { objc_getClass(name.as_ptr().cast::<c_char>()) }
}

/// Allocates an autoreleased `NSString` from a UTF-8 Rust slice.
///
/// # Arguments
///
/// - `&str` - Source UTF-8 string.
///
/// # Returns
///
/// - `*mut c_void` - Objective-C `NSString` pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_ns_string(text: &str) -> *mut c_void {
    let Ok(c_text) = CString::new(text) else {
        return null_mut();
    };
    unsafe {
        let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_STRING);
        if cls.is_null() {
            return null_mut();
        }
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
            transmute(objc_msgSend as *const c_void);
        send(cls, mtl_sel_cstr(MTL_SEL_STRING_UTF8), c_text.as_ptr())
    }
}

/// Sends a zero-argument Objective-C message returning a pointer.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
///
/// # Returns
///
/// - `*mut c_void` - Returned Objective-C object pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
    if obj.is_null() || sel.is_null() {
        return null_mut();
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel)
    }
}

/// Sends a one-pointer-argument Objective-C message returning a pointer.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
/// - `*mut c_void` - Pointer argument.
///
/// # Returns
///
/// - `*mut c_void` - Returned Objective-C object pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) -> *mut c_void {
    if obj.is_null() || sel.is_null() {
        return null_mut();
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel, arg0)
    }
}

/// Sends a zero-argument Objective-C message returning void.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
    if obj.is_null() || sel.is_null() {
        return;
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel);
    }
}

/// Sends a one-pointer-argument Objective-C message returning void.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
/// - `*mut c_void` - Pointer argument.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) {
    if obj.is_null() || sel.is_null() {
        return;
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel, arg0);
    }
}

/// Sends a one-`usize`-argument Objective-C message returning void.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
/// - `usize` - Unsigned integer argument (`NSUInteger`).
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_usize(obj: *mut c_void, sel: *mut c_void, val: usize) {
    if obj.is_null() || sel.is_null() {
        return;
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel, val);
    }
}

/// Sends a one-boolean Objective-C message returning void.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
/// - `bool` - Boolean flag converted to Objective-C `BOOL`.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_bool(obj: *mut c_void, sel: *mut c_void, val: bool) {
    if obj.is_null() || sel.is_null() {
        return;
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel, if val { 1 } else { 0 });
    }
}

/// Sends a zero-argument Objective-C message returning `usize` (`NSUInteger`).
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
///
/// # Returns
///
/// - `usize` - Returned `NSUInteger`.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_usize0(obj: *mut c_void, sel: *mut c_void) -> usize {
    if obj.is_null() || sel.is_null() {
        return 0;
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel)
    }
}

/// Sends a zero-argument Objective-C message returning `f64` (`CFTimeInterval`).
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
///
/// # Returns
///
/// - `f64` - Returned floating-point timestamp or duration in seconds.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_f64_0(obj: *mut c_void, sel: *mut c_void) -> f64 {
    if obj.is_null() || sel.is_null() {
        return 0.0;
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel)
    }
}

/// Checks whether an Objective-C object responds to `sel`.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector to query.
///
/// # Returns
///
/// - `bool` - `true` when the object implements `sel`.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_responds_to_sel(obj: *mut c_void, sel: *mut c_void) -> bool {
    if obj.is_null() || sel.is_null() {
        return false;
    }
    let responds_sel: *mut c_void = cached_metal_selectors().responds_to_sel as *mut c_void;
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
            transmute(objc_msgSend as *const c_void);
        send(obj, responds_sel, sel) != 0
    }
}

/// Retains a non-zero Objective-C handle and returns it as `usize`.
///
/// # Arguments
///
/// - `usize` - Raw Objective-C object handle (`0` returns `0`).
///
/// # Returns
///
/// - `usize` - Retained handle.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_retain_handle(handle: usize) -> usize {
    if handle == 0 {
        return 0;
    }
    let sel_retain: *mut c_void = cached_metal_selectors().retain as *mut c_void;
    mtl_send_ptr0(handle as *mut c_void, sel_retain) as usize
}

/// Objective-C global block callback invoked by `-[MTLDrawable addPresentedHandler:]` upon display scan-out.
///
/// # Arguments
///
/// - `*mut c_void` - Global block pointer (unused).
/// - `*mut c_void` - Presented `id<MTLDrawable>` pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" fn metal_presented_handler_invoke(_block: *mut c_void, drawable: *mut c_void) {
    if drawable.is_null() {
        return;
    }
    let sel: &MetalSelectors = cached_metal_selectors();
    let presented_secs: f64 = mtl_send_f64_0(drawable, sel.presented_time as *mut c_void);
    if presented_secs.is_finite() && presented_secs > 0.0 {
        let ns: u64 = (presented_secs * 1_000_000_000.0).round() as u64;
        METAL_LAST_PRESENTED_NS.store(ns, Ordering::Relaxed);
    }
}

/// Objective-C global block callback invoked by `-[MTLCommandBuffer addCompletedHandler:]` on GPU completion.
///
/// # Arguments
///
/// - `*mut c_void` - Global block pointer (unused).
/// - `*mut c_void` - Completed `id<MTLCommandBuffer>` pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" fn metal_completed_handler_invoke(_block: *mut c_void, cmd_buf: *mut c_void) {
    if cmd_buf.is_null() {
        return;
    }
    let sel: &MetalSelectors = cached_metal_selectors();
    let start_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_start_time as *mut c_void);
    let end_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_end_time as *mut c_void);
    if start_s.is_finite() && end_s.is_finite() && end_s >= start_s {
        let exec_ns: u64 = ((end_s - start_s) * 1_000_000_000.0).round() as u64;
        METAL_LAST_GPU_EXEC_NS.store(exec_ns, Ordering::Relaxed);
    }
}

/// Returns the process-lifetime pinned global Objective-C block pointer for `addPresentedHandler:`.
///
/// # Returns
///
/// - `*mut c_void` - Pointer to static `ObjcGlobalBlock`.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_presented_block_ptr() -> *mut c_void {
    let addr: usize = *METAL_PRESENTED_BLOCK_ADDR.get_or_init(|| {
        let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
            isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
            flags: OBJC_BLOCK_IS_GLOBAL,
            reserved: 0,
            invoke: metal_presented_handler_invoke,
            descriptor: &METAL_BLOCK_DESCRIPTOR,
        });
        Box::into_raw(block) as usize
    });
    addr as *mut c_void
}

/// Returns the process-lifetime pinned global Objective-C block pointer for `addCompletedHandler:`.
///
/// # Returns
///
/// - `*mut c_void` - Pointer to static `ObjcGlobalBlock`.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_completed_block_ptr() -> *mut c_void {
    let addr: usize = *METAL_COMPLETED_BLOCK_ADDR.get_or_init(|| {
        let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
            isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
            flags: OBJC_BLOCK_IS_GLOBAL,
            reserved: 0,
            invoke: metal_completed_handler_invoke,
            descriptor: &METAL_BLOCK_DESCRIPTOR,
        });
        Box::into_raw(block) as usize
    });
    addr as *mut c_void
}

/// Computes a deterministic 64-bit FNV-1a cache key over shader sources and GPU device name for `MTLBinaryArchive`.
///
/// # Arguments
///
/// - `&str` - Probed GPU device name.
///
/// # Returns
///
/// - `u64` - Deterministic cache key hash.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_pipeline_cache_hash(device_name: &str) -> u64 {
    let mut hash: u64 = FNV1A_OFFSET_BASIS;
    for chunk in [
        device_name.as_bytes(),
        MSL_UI_SHADER.as_bytes(),
        MSL_BACKDROP_BLUR_SHADER.as_bytes(),
    ]
    .iter()
    {
        for &byte in chunk.iter() {
            hash ^= byte as u64;
            hash = hash.wrapping_mul(FNV1A_PRIME);
        }
    }
    hash
}

/// Creates a Metal `MTLTexture` (`R8Unorm` or `RGBA8Unorm`) with explicit dimensions for atlases or fallback slots.
///
/// # Arguments
///
/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
/// - `GpuAtlasPixelFormat` - Pixel format to allocate.
/// - `u32` - Texture width in pixels.
/// - `u32` - Texture height in pixels.
///
/// # Returns
///
/// - `usize` - Retained `id<MTLTexture>` pointer or `0` on failure.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_create_texture(
    device: *mut c_void,
    format: GpuAtlasPixelFormat,
    width: u32,
    height: u32,
) -> usize {
    if device.is_null() {
        return 0;
    }
    let px_fmt: usize = match format {
        GpuAtlasPixelFormat::R8Unorm => MTL_PIXEL_FORMAT_R8_UNORM,
        GpuAtlasPixelFormat::Rgba8Unorm => MTL_PIXEL_FORMAT_RGBA8_UNORM,
    };
    let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
    if cls_desc.is_null() {
        return 0;
    }
    unsafe {
        let send_desc: unsafe extern "C" fn(
            *mut c_void,
            *mut c_void,
            usize,
            usize,
            usize,
            i8,
        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
        let desc: *mut c_void = send_desc(
            cls_desc,
            mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
            px_fmt,
            width.max(1) as usize,
            height.max(1) as usize,
            0,
        );
        if desc.is_null() {
            return 0;
        }
        mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
        let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
        tex as usize
    }
}

/// Builds a real `MTLRenderPipelineState` with optional `MTLBinaryArchive` disk caching and straight-alpha blending.
///
/// # Arguments
///
/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
/// - `*mut c_void` - Compiled `id<MTLLibrary>` handle.
/// - `&str` - Vertex shader entry function name.
/// - `&str` - Fragment shader entry function name.
/// - `*mut c_void` - Optional `id<MTLBinaryArchive>` handle (null if unsupported).
/// - `bool` - Whether alpha blending should be enabled on color attachment 0.
///
/// # Returns
///
/// - `(usize, bool)` - Tuple `(pipeline_state_handle, functions_found)`.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_build_render_pipeline(
    device: *mut c_void,
    library: *mut c_void,
    vs_name: &str,
    fs_name: &str,
    archive: *mut c_void,
    enable_blend: bool,
) -> (usize, bool) {
    if device.is_null() || library.is_null() {
        return (0, false);
    }
    let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
    let vs_fn: *mut c_void = mtl_send_ptr1(
        library,
        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
        mtl_ns_string(vs_name),
    );
    let fs_fn: *mut c_void = mtl_send_ptr1(
        library,
        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
        mtl_ns_string(fs_name),
    );
    let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
    if !functions_ok {
        if !vs_fn.is_null() {
            mtl_send_void0(vs_fn, sel_rel);
        }
        if !fs_fn.is_null() {
            mtl_send_void0(fs_fn, sel_rel);
        }
        return (0, false);
    }
    let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
    let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
    let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
    if desc.is_null() {
        mtl_send_void0(vs_fn, sel_rel);
        mtl_send_void0(fs_fn, sel_rel);
        return (0, functions_ok);
    }
    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
    let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
    let att0: *mut c_void = unsafe {
        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
            transmute(objc_msgSend as *const c_void);
        send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
    };
    if !att0.is_null() {
        mtl_send_void_usize(
            att0,
            mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
            MTL_PIXEL_FORMAT_BGRA8_UNORM,
        );
        if enable_blend {
            mtl_send_void_bool(att0, mtl_sel_cstr(MTL_SEL_SET_BLENDING_ENABLED), true);
            mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_RGB_BLEND_OP), 0);
            mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_ALPHA_BLEND_OP), 0);
            mtl_send_void_usize(
                att0,
                mtl_sel_cstr(MTL_SEL_SET_SRC_RGB_BLEND),
                MTL_BLEND_FACTOR_SRC_ALPHA,
            );
            mtl_send_void_usize(
                att0,
                mtl_sel_cstr(MTL_SEL_SET_DST_RGB_BLEND),
                MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
            );
            mtl_send_void_usize(
                att0,
                mtl_sel_cstr(MTL_SEL_SET_SRC_ALPHA_BLEND),
                MTL_BLEND_FACTOR_ONE,
            );
            mtl_send_void_usize(
                att0,
                mtl_sel_cstr(MTL_SEL_SET_DST_ALPHA_BLEND),
                MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
            );
        }
    }
    if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
        let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
        let arr: *mut c_void =
            mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
        if !arr.is_null() {
            mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
        }
    }
    let mut err_ptr: *mut c_void = null_mut();
    let pipeline: *mut c_void = unsafe {
        let send_pso: unsafe extern "C" fn(
            *mut c_void,
            *mut c_void,
            *mut c_void,
            *mut *mut c_void,
        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
        send_pso(
            device,
            mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
            desc,
            &mut err_ptr,
        )
    };
    if !archive.is_null() && !pipeline.is_null() {
        let mut add_err: *mut c_void = null_mut();
        unsafe {
            let send_add: unsafe extern "C" fn(
                *mut c_void,
                *mut c_void,
                *mut c_void,
                *mut *mut c_void,
            ) -> i8 = transmute(objc_msgSend as *const c_void);
            let _: i8 = send_add(
                archive,
                mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
                desc,
                &mut add_err,
            );
        }
    }
    mtl_send_void0(desc, sel_rel);
    mtl_send_void0(vs_fn, sel_rel);
    mtl_send_void0(fs_fn, sel_rel);
    (pipeline as usize, functions_ok)
}

/// Opens or initializes a disk-backed `MTLBinaryArchive` keyed by shader source hash and GPU device name.
///
/// # Arguments
///
/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
/// - `&str` - Detected physical GPU device name.
///
/// # Returns
///
/// - `(*mut c_void, *mut c_void, bool)` - Tuple `(archive_handle, ns_url_handle, existed_on_disk)`.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_open_binary_archive(
    device: *mut c_void,
    device_name: &str,
) -> (*mut c_void, *mut c_void, bool) {
    let arch_desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_BINARY_ARCHIVE_DESC);
    if arch_desc_cls.is_null() {
        return (null_mut(), null_mut(), false);
    }
    let cache_hash: u64 = metal_pipeline_cache_hash(device_name);
    let archive_path: String = env::temp_dir()
        .join(format!(
            "{MTL_ARCHIVE_FILE_PREFIX}{cache_hash:016x}{MTL_ARCHIVE_FILE_SUFFIX}"
        ))
        .to_string_lossy()
        .into_owned();
    let existed: bool = fs::metadata(&archive_path).is_ok();
    let ns_path: *mut c_void = mtl_ns_string(&archive_path);
    let url_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_URL);
    let ns_url: *mut c_void =
        mtl_send_ptr1(url_cls, mtl_sel_cstr(MTL_SEL_FILE_URL_WITH_PATH), ns_path);
    let arch_desc_alloc: *mut c_void = mtl_send_ptr0(arch_desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
    let arch_desc: *mut c_void = mtl_send_ptr0(arch_desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
    if arch_desc.is_null() {
        return (null_mut(), ns_url, existed);
    }
    if existed && !ns_url.is_null() {
        mtl_send_void_ptr1(arch_desc, mtl_sel_cstr(MTL_SEL_SET_URL), ns_url);
    }
    let mut err_ptr: *mut c_void = null_mut();
    let archive: *mut c_void = unsafe {
        let send_new: unsafe extern "C" fn(
            *mut c_void,
            *mut c_void,
            *mut c_void,
            *mut *mut c_void,
        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
        send_new(
            device,
            mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE),
            arch_desc,
            &mut err_ptr,
        )
    };
    mtl_send_void0(arch_desc, mtl_sel_cstr(MTL_SEL_RELEASE));
    (archive, ns_url, existed)
}

/// Initializes or returns the process-wide cached Apple Metal GPU device, command queue, binary-archived pipelines, and fallback textures.
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested graphics backend.
///
/// # Returns
///
/// - `NativeGpuProbeOutput` - Retained handles for a `NativeGpuDriver` instance.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
    let cached: &MetalSharedPipelineCache = METAL_SHARED_PIPELINE.get_or_init(|| {
        let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
        let result: MetalSharedPipelineCache = unsafe {
            let device: *mut c_void = MTLCreateSystemDefaultDevice();
            if device.is_null() {
                MetalSharedPipelineCache {
                    adapter: GpuAdapterInfo::new(
                        backend,
                        GPU_DEVICE_FALLBACK.to_string(),
                        false,
                        false,
                    ),
                    device: 0,
                    queue: 0,
                    library: 0,
                    pipeline: 0,
                    blur_pipeline: 0,
                    dummy_r8_tex: 0,
                    dummy_rgba8_tex: 0,
                }
            } else {
                let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NAME));
                let utf8_ptr: *const c_char =
                    mtl_send_ptr0(ns_name, mtl_sel_cstr(MTL_SEL_UTF8_STRING)).cast::<c_char>();
                let device_name: String = if utf8_ptr.is_null() {
                    GPU_DEVICE_APPLE_METAL.to_string()
                } else {
                    CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
                };
                let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NEW_CMD_QUEUE));
                let (archive, archive_url, archive_existed): (*mut c_void, *mut c_void, bool) =
                    metal_open_binary_archive(device, &device_name);
                let send_lib: unsafe extern "C" fn(
                    *mut c_void,
                    *mut c_void,
                    *mut c_void,
                    *mut c_void,
                    *mut *mut c_void,
                ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
                let mut err_ptr: *mut c_void = null_mut();
                let library: *mut c_void = send_lib(
                    device,
                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
                    mtl_ns_string(MSL_UI_SHADER),
                    null_mut(),
                    &mut err_ptr,
                );
                let (pipeline, ui_fns_ok): (usize, bool) = metal_build_render_pipeline(
                    device,
                    library,
                    MTL_FN_VERTEX,
                    MTL_FN_FRAGMENT,
                    archive,
                    true,
                );
                let mut blur_err: *mut c_void = null_mut();
                let blur_lib: *mut c_void = send_lib(
                    device,
                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
                    mtl_ns_string(MSL_BACKDROP_BLUR_SHADER),
                    null_mut(),
                    &mut blur_err,
                );
                let (blur_pipeline, _): (usize, bool) = metal_build_render_pipeline(
                    device,
                    blur_lib,
                    MTL_FN_BLUR_VERTEX,
                    MTL_FN_BLUR_DOWN,
                    archive,
                    false,
                );
                let (blur_up_pipeline, _): (usize, bool) = metal_build_render_pipeline(
                    device,
                    blur_lib,
                    MTL_FN_BLUR_VERTEX,
                    MTL_FN_BLUR_UP,
                    archive,
                    false,
                );
                if blur_up_pipeline != 0 {
                    mtl_send_void0(
                        blur_up_pipeline as *mut c_void,
                        mtl_sel_cstr(MTL_SEL_RELEASE),
                    );
                }
                if !blur_lib.is_null() {
                    mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
                }
                if !archive.is_null() {
                    if !archive_existed && !archive_url.is_null() && pipeline != 0 {
                        let mut ser_err: *mut c_void = null_mut();
                        let send_ser: unsafe extern "C" fn(
                            *mut c_void,
                            *mut c_void,
                            *mut c_void,
                            *mut *mut c_void,
                        ) -> i8 = transmute(objc_msgSend as *const c_void);
                        let _: i8 = send_ser(
                            archive,
                            mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL),
                            archive_url,
                            &mut ser_err,
                        );
                    }
                    mtl_send_void0(archive, mtl_sel_cstr(MTL_SEL_RELEASE));
                }
                let dummy_r8_tex: usize =
                    metal_create_texture(device, GpuAtlasPixelFormat::R8Unorm, 1, 1);
                let dummy_rgba8_tex: usize =
                    metal_create_texture(device, GpuAtlasPixelFormat::Rgba8Unorm, 1, 1);
                let shader_compiled: bool = ui_fns_ok && pipeline != 0;
                MetalSharedPipelineCache {
                    adapter: GpuAdapterInfo::new(
                        GraphicsBackend::Metal,
                        device_name,
                        !queue.is_null(),
                        shader_compiled,
                    ),
                    device: device as usize,
                    queue: queue as usize,
                    library: library as usize,
                    pipeline,
                    blur_pipeline,
                    dummy_r8_tex,
                    dummy_rgba8_tex,
                }
            }
        };
        unsafe { objc_autoreleasePoolPop(pool) };
        result
    });
    NativeGpuProbeOutput {
        adapter: cached.adapter.clone(),
        device_handle: mtl_retain_handle(cached.device),
        queue_handle: mtl_retain_handle(cached.queue),
        library_handle: mtl_retain_handle(cached.library),
        pipeline_handle: mtl_retain_handle(cached.pipeline),
        blur_pipeline_handle: mtl_retain_handle(cached.blur_pipeline),
        dummy_r8_tex: mtl_retain_handle(cached.dummy_r8_tex),
        dummy_rgba8_tex: mtl_retain_handle(cached.dummy_rgba8_tex),
    }
}

/// Returns the process-wide `OnceLock`-cached Objective-C selector pointers for Metal hot-path submission and encoding.
///
/// # Returns
///
/// - `&'static MetalSelectors` - Cached Metal selector addresses.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn cached_metal_selectors() -> &'static MetalSelectors {
    METAL_SELECTORS.get_or_init(|| MetalSelectors {
        retain: mtl_sel_cstr(MTL_SEL_RETAIN) as usize,
        new_buffer_with_bytes: mtl_sel_cstr(MTL_SEL_NEW_BUFFER) as usize,
        new_buffer_with_length: mtl_sel_cstr(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
        contents: mtl_sel_cstr(MTL_SEL_CONTENTS) as usize,
        command_buffer: mtl_sel_cstr(MTL_SEL_CMD_BUFFER) as usize,
        render_encoder: mtl_sel_cstr(MTL_SEL_RENDER_ENCODER) as usize,
        set_pipeline_state: mtl_sel_cstr(MTL_SEL_SET_PIPELINE_STATE) as usize,
        set_vertex_buffer: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BUFFER) as usize,
        set_vertex_bytes: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BYTES) as usize,
        set_fragment_texture: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_TEXTURE) as usize,
        set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
        draw_primitives_instanced: mtl_sel_cstr(MTL_SEL_DRAW_PRIMITIVES_INSTANCED) as usize,
        end_encoding: mtl_sel_cstr(MTL_SEL_END_ENCODING) as usize,
        present_drawable: mtl_sel_cstr(MTL_SEL_PRESENT_DRAWABLE) as usize,
        add_presented_handler: mtl_sel_cstr(MTL_SEL_ADD_PRESENTED_HANDLER) as usize,
        add_completed_handler: mtl_sel_cstr(MTL_SEL_ADD_COMPLETED_HANDLER) as usize,
        presented_time: mtl_sel_cstr(MTL_SEL_PRESENTED_TIME) as usize,
        responds_to_sel: mtl_sel_cstr(MTL_SEL_RESPONDS_TO_SEL) as usize,
        status: mtl_sel_cstr(MTL_SEL_STATUS) as usize,
        wait_until_completed: mtl_sel_cstr(MTL_SEL_WAIT_UNTIL_COMPLETED) as usize,
        gpu_start_time: mtl_sel_cstr(MTL_SEL_GPU_START_TIME) as usize,
        gpu_end_time: mtl_sel_cstr(MTL_SEL_GPU_END_TIME) as usize,
        next_drawable: mtl_sel_cstr(MTL_SEL_NEXT_DRAWABLE) as usize,
        texture: mtl_sel_cstr(MTL_SEL_TEXTURE) as usize,
        width: mtl_sel_cstr(MTL_SEL_WIDTH) as usize,
        height: mtl_sel_cstr(MTL_SEL_HEIGHT) as usize,
        render_pass_desc: mtl_sel_cstr(MTL_SEL_RENDER_PASS_DESC) as usize,
        color_attachments: mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS) as usize,
        object_at_index: mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX) as usize,
        set_texture: mtl_sel_cstr(MTL_SEL_SET_TEXTURE) as usize,
        set_load_action: mtl_sel_cstr(MTL_SEL_SET_LOAD_ACTION) as usize,
        set_store_action: mtl_sel_cstr(MTL_SEL_SET_STORE_ACTION) as usize,
        set_clear_color: mtl_sel_cstr(MTL_SEL_SET_CLEAR_COLOR) as usize,
        replace_region: mtl_sel_cstr(MTL_SEL_REPLACE_REGION) as usize,
        commit: mtl_sel_cstr(MTL_SEL_COMMIT) as usize,
        release: mtl_sel_cstr(MTL_SEL_RELEASE) as usize,
    })
}

/// Configures a `CAMetalLayer*` for direct triple-buffered GPU draw (`BGRA8Unorm`, `framebufferOnly = YES`, `maximumDrawableCount = 3`).
///
/// # Arguments
///
/// - `usize` - Retained `id<MTLDevice>` handle.
/// - `usize` - Target `CAMetalLayer*` pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_configure_layer(device_handle: usize, layer_handle: usize) {
    if device_handle == 0 || layer_handle == 0 {
        return;
    }
    let layer: *mut c_void = layer_handle as *mut c_void;
    mtl_send_void_ptr1(
        layer,
        mtl_sel_cstr(MTL_SEL_SET_DEVICE),
        device_handle as *mut c_void,
    );
    mtl_send_void_usize(
        layer,
        mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
        MTL_PIXEL_FORMAT_BGRA8_UNORM,
    );
    mtl_send_void_bool(layer, mtl_sel_cstr(MTL_SEL_SET_FRAMEBUFFER_ONLY), true);
    let sel_max: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_MAX_DRAWABLE_COUNT);
    if mtl_responds_to_sel(layer, sel_max) {
        mtl_send_void_usize(layer, sel_max, GPU_DRIVER_RING_SLOTS);
    }
    let sel_sync: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_DISPLAY_SYNC);
    if mtl_responds_to_sel(layer, sel_sync) {
        mtl_send_void_bool(layer, sel_sync, true);
    }
}

/// Uploads a dirty R8 or RGBA8 sub-rectangle into a Metal `MTLTexture` via `replaceRegion:mipmapLevel:withBytes:bytesPerRow:`.
///
/// # Arguments
///
/// - `usize` - Retained `id<MTLDevice>` handle.
/// - `&mut usize` - Resident `id<MTLTexture>` handle (`0` lazily allocates a new texture).
/// - `GpuAtlasPixelFormat` - Target Metal pixel format.
/// - `(u32, u32)` - Backing texture dimensions `(width, height)`.
/// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
/// - `&[u8]` - Source pixel slice.
/// - `usize` - Row stride in bytes.
///
/// # Returns
///
/// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_upload_texture_dirty_rect(
    device_handle: usize,
    texture_handle: &mut usize,
    format: GpuAtlasPixelFormat,
    tex_dims: (u32, u32),
    dirty_rect: (u32, u32, u32, u32),
    bytes: &[u8],
    bytes_per_row: usize,
) -> bool {
    if device_handle == 0 || dirty_rect.2 == 0 || dirty_rect.3 == 0 || bytes.is_empty() {
        return false;
    }
    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
    let (tex_w, tex_h): (u32, u32) = (tex_dims.0.max(1), tex_dims.1.max(1));
    let sel: &MetalSelectors = cached_metal_selectors();
    let cur_w: usize = if *texture_handle != 0 {
        mtl_send_usize0(*texture_handle as *mut c_void, sel.width as *mut c_void)
    } else {
        0
    };
    let cur_h: usize = if *texture_handle != 0 {
        mtl_send_usize0(*texture_handle as *mut c_void, sel.height as *mut c_void)
    } else {
        0
    };
    if *texture_handle == 0 || cur_w != tex_w as usize || cur_h != tex_h as usize {
        if *texture_handle != 0 {
            mtl_send_void0(*texture_handle as *mut c_void, sel.release as *mut c_void);
        }
        *texture_handle = metal_create_texture(device_handle as *mut c_void, format, tex_w, tex_h);
    }
    if *texture_handle == 0 {
        unsafe { objc_autoreleasePoolPop(pool) };
        return false;
    }
    let region: MtlRegion = MtlRegion {
        origin: MtlOrigin {
            x: dirty_rect.0 as usize,
            y: dirty_rect.1 as usize,
            z: 0,
        },
        size: MtlSize {
            width: dirty_rect.2 as usize,
            height: dirty_rect.3 as usize,
            depth: 1,
        },
    };
    unsafe {
        let send_replace: unsafe extern "C" fn(
            *mut c_void,
            *mut c_void,
            MtlRegion,
            usize,
            *const c_void,
            usize,
        ) = transmute(objc_msgSend as *const c_void);
        send_replace(
            *texture_handle as *mut c_void,
            sel.replace_region as *mut c_void,
            region,
            0,
            bytes.as_ptr().cast::<c_void>(),
            bytes_per_row,
        );
        objc_autoreleasePoolPop(pool);
    }
    true
}

/// 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.
///
/// # Arguments
///
/// - `&mut NativeGpuDriver` - Mutable GPU driver holding ring slots, pipelines, textures, and layer handle.
/// - `u32` - Physical surface width in pixels.
/// - `u32` - Physical surface height in pixels.
/// - `Color` - Surface clear color.
/// - `&[GpuBatch]` - Ordered GPU batches to encode and submit.
///
/// # Returns
///
/// - `usize` - Total 64-byte `GpuPrimitiveInstance` records uploaded and submitted.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_submit_ring_frame(
    driver: &mut NativeGpuDriver,
    width: u32,
    height: u32,
    clear_color: Color,
    batches: &[GpuBatch],
) -> usize {
    let total_instances: usize = batches
        .iter()
        .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
        .sum();
    let device_handle: usize = driver.get_device_handle();
    let queue_handle: usize = driver.get_queue_handle();
    if device_handle == 0 || queue_handle == 0 {
        return total_instances;
    }
    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
    let sel: &MetalSelectors = cached_metal_selectors();
    let sel_rel: *mut c_void = sel.release as *mut c_void;
    let slot_idx: usize = driver.get_ring_cursor() % GPU_DRIVER_RING_SLOTS;
    let device: *mut c_void = device_handle as *mut c_void;
    let queue: *mut c_void = queue_handle as *mut c_void;
    let pipeline: *mut c_void = driver.get_pipeline_handle() as *mut c_void;
    let layer_ptr: *mut c_void = driver.get_surface_layer_handle() as *mut c_void;
    let tex_r8: *mut c_void = driver.get_glyph_r8_texture_handle() as *mut c_void;
    let tex_rgba8: *mut c_void = driver.get_glyph_rgba8_texture_handle() as *mut c_void;
    let tex_img: *mut c_void = driver.get_image_texture_handle() as *mut c_void;
    let raw_ext: usize = driver.get_external_texture_handle();
    let tex_ext: *mut c_void = if raw_ext != 0 {
        raw_ext as *mut c_void
    } else {
        tex_rgba8
    };
    let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuPrimitiveInstance>());
    let NativeGpuDriver {
        ring_slots,
        ring_cursor,
        staging_buffer_handle,
        staging_contents_ptr,
        staging_buffer_capacity,
        staging_reallocations,
        scratch_primitives,
        ..
    } = driver;
    let slot: &mut NativeGpuRingSlot = &mut ring_slots[slot_idx];
    let prev_cmd: usize = slot.get_in_flight_cmd_buffer();
    if prev_cmd != 0 {
        let status: usize = mtl_send_usize0(prev_cmd as *mut c_void, sel.status as *mut c_void);
        if status < MTL_CMD_BUFFER_STATUS_COMPLETED {
            mtl_send_void0(
                prev_cmd as *mut c_void,
                sel.wait_until_completed as *mut c_void,
            );
        }
        mtl_send_void0(prev_cmd as *mut c_void, sel_rel);
        slot.set_in_flight_cmd_buffer(0);
    }
    if total_bytes > 0
        && (slot.get_buffer_handle() == 0
            || slot.get_contents_ptr() == 0
            || total_bytes > slot.get_capacity_bytes())
    {
        if slot.get_buffer_handle() != 0 {
            mtl_send_void0(slot.get_buffer_handle() as *mut c_void, sel_rel);
            slot.set_buffer_handle(0);
            slot.set_contents_ptr(0);
            slot.set_capacity_bytes(0);
        }
        let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
        unsafe {
            let send_new_len: unsafe extern "C" fn(
                *mut c_void,
                *mut c_void,
                usize,
                usize,
            ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
            let new_buf: *mut c_void = send_new_len(
                device,
                sel.new_buffer_with_length as *mut c_void,
                alloc_bytes,
                0,
            );
            if !new_buf.is_null() {
                let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
                if !ptr.is_null() {
                    slot.set_buffer_handle(new_buf as usize);
                    slot.set_contents_ptr(ptr as usize);
                    slot.set_capacity_bytes(alloc_bytes);
                    *staging_reallocations = staging_reallocations.wrapping_add(1);
                } else {
                    mtl_send_void0(new_buf, sel_rel);
                }
            }
        }
    }
    let buf_handle: usize = slot.get_buffer_handle();
    let contents_ptr: usize = slot.get_contents_ptr();
    let capacity_bytes: usize = slot.get_capacity_bytes();
    *staging_buffer_handle = buf_handle;
    *staging_contents_ptr = contents_ptr;
    *staging_buffer_capacity = capacity_bytes;
    if contents_ptr != 0 && total_bytes > 0 && total_bytes <= capacity_bytes {
        unsafe {
            let mut dst: *mut u8 = (contents_ptr as *mut c_void).cast::<u8>();
            for batch in batches.iter() {
                let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
                if !prims.is_empty() {
                    let byte_len: usize = size_of_val(prims);
                    dst.copy_from_nonoverlapping(prims.as_ptr().cast::<u8>(), byte_len);
                    dst = dst.add(byte_len);
                } else if !batch.get_instances().is_empty() {
                    scratch_primitives.clear();
                    for quad in batch.get_instances().iter() {
                        scratch_primitives.push(GpuPrimitiveInstance::from_quad_instance(
                            quad,
                            batch.get_texture_slot(),
                            batch.get_layer_id(),
                        ));
                    }
                    let byte_len: usize = size_of_val(scratch_primitives.as_slice());
                    dst.copy_from_nonoverlapping(
                        scratch_primitives.as_ptr().cast::<u8>(),
                        byte_len,
                    );
                    dst = dst.add(byte_len);
                }
            }
        }
    }
    let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
    if !cmd_buf.is_null() {
        let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
        if mtl_responds_to_sel(cmd_buf, sel_completed) {
            mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
        }
        if !layer_ptr.is_null() && !pipeline.is_null() {
            let drawable: *mut c_void = mtl_send_ptr0(layer_ptr, sel.next_drawable as *mut c_void);
            if !drawable.is_null() {
                let drawable_tex: *mut c_void = mtl_send_ptr0(drawable, sel.texture as *mut c_void);
                let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
                let pass_desc: *mut c_void =
                    mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
                if !drawable_tex.is_null() && !pass_desc.is_null() {
                    let draw_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void)
                        .max(width.max(1) as usize);
                    let draw_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void)
                        .max(height.max(1) as usize);
                    let color_atts: *mut c_void =
                        mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
                    let att0: *mut c_void = unsafe {
                        let send_idx: unsafe extern "C" fn(
                            *mut c_void,
                            *mut c_void,
                            usize,
                        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
                        send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
                    };
                    if !att0.is_null() {
                        mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, drawable_tex);
                        mtl_send_void_usize(
                            att0,
                            sel.set_load_action as *mut c_void,
                            MTL_LOAD_ACTION_CLEAR,
                        );
                        mtl_send_void_usize(
                            att0,
                            sel.set_store_action as *mut c_void,
                            MTL_STORE_ACTION_STORE,
                        );
                        let clear_rgba: [f32; 4] = clear_color.to_f32_array();
                        let mtl_clear: MtlClearColor = MtlClearColor {
                            red: clear_rgba[0] as f64,
                            green: clear_rgba[1] as f64,
                            blue: clear_rgba[2] as f64,
                            alpha: clear_rgba[3] as f64,
                        };
                        unsafe {
                            let send_clear: unsafe extern "C" fn(
                                *mut c_void,
                                *mut c_void,
                                MtlClearColor,
                            ) = transmute(objc_msgSend as *const c_void);
                            send_clear(att0, sel.set_clear_color as *mut c_void, mtl_clear);
                        }
                    }
                    let encoder: *mut c_void =
                        mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
                    if !encoder.is_null() {
                        mtl_send_void_ptr1(
                            encoder,
                            sel.set_pipeline_state as *mut c_void,
                            pipeline,
                        );
                        unsafe {
                            let send_vbuf: unsafe extern "C" fn(
                                *mut c_void,
                                *mut c_void,
                                *mut c_void,
                                usize,
                                usize,
                            ) = transmute(objc_msgSend as *const c_void);
                            let send_vbytes: unsafe extern "C" fn(
                                *mut c_void,
                                *mut c_void,
                                *const c_void,
                                usize,
                                usize,
                            ) = transmute(objc_msgSend as *const c_void);
                            let send_ftex: unsafe extern "C" fn(
                                *mut c_void,
                                *mut c_void,
                                *mut c_void,
                                usize,
                            ) = transmute(objc_msgSend as *const c_void);
                            let send_scissor: unsafe extern "C" fn(
                                *mut c_void,
                                *mut c_void,
                                MtlScissorRect,
                            ) = transmute(objc_msgSend as *const c_void);
                            let send_draw: unsafe extern "C" fn(
                                *mut c_void,
                                *mut c_void,
                                usize,
                                usize,
                                usize,
                                usize,
                                usize,
                            ) = transmute(objc_msgSend as *const c_void);
                            if buf_handle != 0 {
                                send_vbuf(
                                    encoder,
                                    sel.set_vertex_buffer as *mut c_void,
                                    buf_handle as *mut c_void,
                                    0,
                                    0,
                                );
                            }
                            if !tex_r8.is_null() {
                                send_ftex(
                                    encoder,
                                    sel.set_fragment_texture as *mut c_void,
                                    tex_r8,
                                    0,
                                );
                            }
                            if !tex_rgba8.is_null() {
                                send_ftex(
                                    encoder,
                                    sel.set_fragment_texture as *mut c_void,
                                    tex_rgba8,
                                    1,
                                );
                            }
                            if !tex_img.is_null() {
                                send_ftex(
                                    encoder,
                                    sel.set_fragment_texture as *mut c_void,
                                    tex_img,
                                    2,
                                );
                            }
                            if !tex_ext.is_null() {
                                send_ftex(
                                    encoder,
                                    sel.set_fragment_texture as *mut c_void,
                                    tex_ext,
                                    3,
                                );
                            }
                            let mut base_instance: usize = 0;
                            for batch in batches.iter() {
                                let count: usize = batch
                                    .get_primitives()
                                    .len()
                                    .max(batch.get_instances().len());
                                if count == 0 || buf_handle == 0 {
                                    continue;
                                }
                                let uniform: GpuLayerUniform = GpuLayerUniform::new(
                                    draw_w as f32,
                                    draw_h as f32,
                                    batch.get_scroll_offset(),
                                );
                                send_vbytes(
                                    encoder,
                                    sel.set_vertex_bytes as *mut c_void,
                                    (&uniform as *const GpuLayerUniform).cast::<c_void>(),
                                    size_of::<GpuLayerUniform>(),
                                    1,
                                );
                                let sc: Rect = batch.get_scissor();
                                let sx: usize = (sc.get_x().max(0.0).floor() as usize)
                                    .min(draw_w.saturating_sub(1));
                                let sy: usize = (sc.get_y().max(0.0).floor() as usize)
                                    .min(draw_h.saturating_sub(1));
                                let sw: usize = (sc.get_width().max(1.0).ceil() as usize)
                                    .min(draw_w.saturating_sub(sx))
                                    .max(1);
                                let sh: usize = (sc.get_height().max(1.0).ceil() as usize)
                                    .min(draw_h.saturating_sub(sy))
                                    .max(1);
                                send_scissor(
                                    encoder,
                                    sel.set_scissor_rect as *mut c_void,
                                    MtlScissorRect {
                                        x: sx,
                                        y: sy,
                                        width: sw,
                                        height: sh,
                                    },
                                );
                                send_draw(
                                    encoder,
                                    sel.draw_primitives_instanced as *mut c_void,
                                    MTL_PRIMITIVE_TYPE_TRIANGLE,
                                    0,
                                    6,
                                    count,
                                    base_instance,
                                );
                                base_instance = base_instance.saturating_add(count);
                            }
                        }
                        mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
                    }
                    let sel_pres: *mut c_void = sel.add_presented_handler as *mut c_void;
                    if mtl_responds_to_sel(drawable, sel_pres) {
                        mtl_send_void_ptr1(drawable, sel_pres, metal_presented_block_ptr());
                    }
                    mtl_send_void_ptr1(cmd_buf, sel.present_drawable as *mut c_void, drawable);
                }
            }
        }
        let retained_cmd: usize = mtl_retain_handle(cmd_buf as usize);
        slot.set_in_flight_cmd_buffer(retained_cmd);
        mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
    }
    *ring_cursor = (slot_idx + 1) % GPU_DRIVER_RING_SLOTS;
    unsafe { objc_autoreleasePoolPop(pool) };
    total_instances
}

/// Uploads `GpuPrimitiveInstance` buffers to Metal GPU memory and commits a command buffer.
///
/// # Arguments
///
/// - `usize` - Retained `id<MTLDevice>` pointer.
/// - `usize` - Retained `id<MTLCommandQueue>` pointer.
/// - `&[GpuBatch]` - Ordered GPU batches to upload.
///
/// # Returns
///
/// - `usize` - Total instances uploaded into Metal buffers.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
    let total_instances: usize = batches
        .iter()
        .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
        .sum();
    if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
        return total_instances;
    }
    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
    let device: *mut c_void = device_handle as *mut c_void;
    let queue: *mut c_void = queue_handle as *mut c_void;
    let sel: &MetalSelectors = cached_metal_selectors();
    let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
    let sel_rel: *mut c_void = sel.release as *mut c_void;
    unsafe {
        let send_buf: unsafe extern "C" fn(
            *mut c_void,
            *mut c_void,
            *const c_void,
            usize,
            usize,
        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
        for batch in batches.iter() {
            let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
            if !prims.is_empty() {
                let byte_len: usize = size_of_val(prims);
                let mtl_buf: *mut c_void = send_buf(
                    device,
                    sel_buf,
                    prims.as_ptr().cast::<c_void>(),
                    byte_len,
                    0,
                );
                if !mtl_buf.is_null() {
                    mtl_send_void0(mtl_buf, sel_rel);
                }
            } else {
                let instances: &[GpuQuadInstance] = batch.get_instances();
                if instances.is_empty() {
                    continue;
                }
                let byte_len: usize = size_of_val(instances);
                let mtl_buf: *mut c_void = send_buf(
                    device,
                    sel_buf,
                    instances.as_ptr().cast::<c_void>(),
                    byte_len,
                    0,
                );
                if !mtl_buf.is_null() {
                    mtl_send_void0(mtl_buf, sel_rel);
                }
            }
        }
        let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
        if !cmd_buf.is_null() {
            mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
        }
        objc_autoreleasePoolPop(pool);
    }
    total_instances
}

/// Releases retained Apple Metal Objective-C objects cleanly on drop.
///
/// # Arguments
///
/// - `usize` - `id<MTLDevice>` pointer.
/// - `usize` - `id<MTLCommandQueue>` pointer.
/// - `usize` - `id<MTLLibrary>` pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
    let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
    if library_handle != 0 {
        mtl_send_void0(library_handle as *mut c_void, sel_rel);
    }
    if queue_handle != 0 {
        mtl_send_void0(queue_handle as *mut c_void, sel_rel);
    }
    if device_handle != 0 {
        mtl_send_void0(device_handle as *mut c_void, sel_rel);
    }
}

#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
    /// Dynamically loads a Windows DLL by ANSI path.
    ///
    /// # Arguments
    ///
    /// - `*const u8` - Null-terminated ANSI DLL path.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Loaded `HMODULE` handle or null.
    fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
    /// Looks up an exported procedure address from a loaded Windows DLL.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Loaded `HMODULE` handle.
    /// - `*const u8` - Null-terminated ASCII export name.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Exported function address or null.
    fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
}

/// Probes Windows Direct3D 12 and `d3dcompiler_47.dll` once per process (caching handles in `OnceLock`).
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested graphics backend.
///
/// # Returns
///
/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Direct3D 12 availability metadata.
#[cfg(target_os = "windows")]
fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
    let cached: &WindowsD3d12ProbeCache = WINDOWS_D3D12_CACHE.get_or_init(|| unsafe {
        let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
        let has_d3d12: bool = if !d3d12_mod.is_null() {
            !GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr()).is_null()
        } else {
            false
        };
        let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
        let has_compiler: bool = if !compiler_mod.is_null() {
            !GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr()).is_null()
        } else {
            false
        };
        WindowsD3d12ProbeCache {
            has_d3d12,
            has_compiler,
        }
    });
    let label: &str = if cached.has_d3d12 {
        GPU_DEVICE_D3D12
    } else {
        GPU_DEVICE_FALLBACK
    };
    (
        GpuAdapterInfo::new(
            backend,
            label.to_string(),
            cached.has_d3d12,
            cached.has_compiler,
        ),
        0,
        0,
        0,
    )
}

#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe extern "C" {
    /// Dynamically opens a shared library object by name.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Null-terminated library name.
    /// - `i32` - POSIX `RTLD_*` resolution flags.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Shared library handle or null.
    fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
    /// Resolves a symbol address from an open shared library handle.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Open shared library handle.
    /// - `*const c_char` - Null-terminated symbol name.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Resolved symbol pointer or null.
    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}

/// Probes Linux or Android Vulkan loader once per process and retains the library handle in `OnceLock`.
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested graphics backend.
///
/// # Returns
///
/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Vulkan runtime status.
#[cfg(any(target_os = "linux", target_os = "android"))]
fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
    let cached: &VulkanProbeCache = VULKAN_PROBE_CACHE.get_or_init(|| {
        let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
            return VulkanProbeCache {
                available: false,
                lib_handle: 0,
            };
        };
        let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
            return VulkanProbeCache {
                available: false,
                lib_handle: 0,
            };
        };
        let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
            return VulkanProbeCache {
                available: false,
                lib_handle: 0,
            };
        };
        unsafe {
            let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
            if handle.is_null() {
                VulkanProbeCache {
                    available: false,
                    lib_handle: 0,
                }
            } else {
                let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
                let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
                VulkanProbeCache {
                    available: !p1.is_null() && !p2.is_null(),
                    lib_handle: handle as usize,
                }
            }
        }
    });
    let name: &str = if cached.available {
        GPU_DEVICE_VULKAN
    } else {
        GPU_DEVICE_FALLBACK
    };
    (
        GpuAdapterInfo::new(
            backend,
            name.to_string(),
            cached.available,
            cached.available,
        ),
        cached.lib_handle,
        0,
        0,
    )
}

/// Compiles and links the WebGL 2 64-byte instanced uber-shader program on `wasm32`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL 2 canvas context.
///
/// # Returns
///
/// - `Option<WebGlProgram>` - Linked shader program when compilation succeeds.
#[cfg(target_arch = "wasm32")]
pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
    gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
    gl.compile_shader(&vs);
    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
    gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
    gl.compile_shader(&fs);
    let program: WebGlProgram = gl.create_program()?;
    gl.attach_shader(&program, &vs);
    gl.attach_shader(&program, &fs);
    gl.link_program(&program);
    Some(program)
}