euv-core 0.48.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
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
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,
        drawable_size: mtl_sel_cstr(MTL_SEL_DRAWABLE_SIZE) as usize,
        set_drawable_size: mtl_sel_cstr(MTL_SEL_SET_DRAWABLE_SIZE) 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() {
            if width > 0
                && height > 0
                && mtl_responds_to_sel(layer_ptr, sel.set_drawable_size as *mut c_void)
            {
                let target_w: f64 = f64::from(width);
                let target_h: f64 = f64::from(height);
                let needs_resize: bool =
                    if mtl_responds_to_sel(layer_ptr, sel.drawable_size as *mut c_void) {
                        // SAFETY: `-[CAMetalLayer drawableSize]` returns a 16-byte `CGSize` in FP registers on 64-bit Apple targets.
                        let cur: MtlCgSize = unsafe {
                            let get_size: unsafe extern "C" fn(
                                *mut c_void,
                                *mut c_void,
                            )
                                -> MtlCgSize = transmute(objc_msgSend as *const c_void);
                            get_size(layer_ptr, sel.drawable_size as *mut c_void)
                        };
                        (cur.width - target_w).abs() > 0.5 || (cur.height - target_h).abs() > 0.5
                    } else {
                        true
                    };
                if needs_resize {
                    // SAFETY: `-[CAMetalLayer setDrawableSize:]` takes a single `CGSize` (`{ f64, f64 }`) value.
                    unsafe {
                        let set_size: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlCgSize) =
                            transmute(objc_msgSend as *const c_void);
                        set_size(
                            layer_ptr,
                            sel.set_drawable_size as *mut c_void,
                            MtlCgSize {
                                width: target_w,
                                height: target_h,
                            },
                        );
                    }
                }
            }
            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)
}

/// Returns the canonical 5-attribute GLES 3.0 instanced vertex layout matching `GLSL_ES3_UI_VERTEX_SHADER` and 64-byte `GpuPrimitiveInstance`.
///
/// # Returns
///
/// - `[Gles3InstanceAttribSpec; 5]` - Ordered instanced vertex attribute bindings (`locations 1..=5`, stride `64`).
#[must_use]
pub const fn gles3_ui_instance_attribs() -> [Gles3InstanceAttribSpec; 5] {
    let stride: i32 = GPU_PRIMITIVE_INSTANCE_BYTES as i32;
    [
        Gles3InstanceAttribSpec {
            location: 1,
            components: 4,
            is_integer: false,
            byte_offset: 0,
            stride,
        },
        Gles3InstanceAttribSpec {
            location: 2,
            components: 4,
            is_integer: false,
            byte_offset: 16,
            stride,
        },
        Gles3InstanceAttribSpec {
            location: 3,
            components: 2,
            is_integer: true,
            byte_offset: 32,
            stride,
        },
        Gles3InstanceAttribSpec {
            location: 4,
            components: 4,
            is_integer: true,
            byte_offset: 40,
            stride,
        },
        Gles3InstanceAttribSpec {
            location: 5,
            components: 2,
            is_integer: true,
            byte_offset: 56,
            stride,
        },
    ]
}

/// Converts a top-left physical scissor rectangle into an OpenGL ES bottom-left scissor tuple `(x, y, width, height)`.
///
/// # Arguments
///
/// - `u32` - Surface height in physical pixels.
/// - `u32` - Top-left scissor X coordinate.
/// - `u32` - Top-left scissor Y coordinate.
/// - `u32` - Scissor width in physical pixels.
/// - `u32` - Scissor height in physical pixels.
///
/// # Returns
///
/// - `[i32; 4]` - OpenGL ES `[x, y_bottom_up, width, height]` scissor rectangle.
#[must_use]
pub fn gles3_scissor_from_top_down(surface_h: u32, sx: u32, sy: u32, sw: u32, sh: u32) -> [i32; 4] {
    let y1: u32 = sy.saturating_add(sh).min(surface_h);
    let y_bottom: u32 = surface_h.saturating_sub(y1);
    [sx as i32, y_bottom as i32, sw as i32, sh as i32]
}

/// Selects the lowest-cost texture upload strategy (`MultiRect`, `MergedBbox`, `FullFrame`, or `None`) from dirty rectangles and surface dimensions.
///
/// # Arguments
///
/// - `u32` - Framebuffer width in pixels.
/// - `u32` - Framebuffer height in pixels.
/// - `&[PixelDirtyRect]` - Candidate damaged sub-rectangles in physical pixels.
/// - `bool` - When `true`, forces a `FullFrame` upload (e.g. surface resize or first frame).
///
/// # Returns
///
/// - `AdaptiveUploadPlan` - Selected strategy, coalesced rectangle list, and byte/cost metrics.
#[must_use]
pub fn select_adaptive_upload_plan(
    fb_w: u32,
    fb_h: u32,
    dirty_rects: &[PixelDirtyRect],
    force_full: bool,
) -> AdaptiveUploadPlan {
    if fb_w == 0 || fb_h == 0 {
        return AdaptiveUploadPlan {
            strategy: MobileUploadStrategy::None,
            rects: Vec::new(),
            total_upload_bytes: 0,
            merged_bbox_bytes: 0,
            full_frame_bytes: 0,
            estimated_cost_score: 0.0,
        };
    }
    let full_rect: PixelDirtyRect = PixelDirtyRect::new(0, 0, fb_w, fb_h);
    let full_bytes: usize = full_rect.byte_size_rgba8();
    if force_full {
        return AdaptiveUploadPlan {
            strategy: MobileUploadStrategy::FullFrame,
            rects: vec![full_rect],
            total_upload_bytes: full_bytes,
            merged_bbox_bytes: full_bytes,
            full_frame_bytes: full_bytes,
            estimated_cost_score: (full_bytes + MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES) as f32,
        };
    }
    let mut coalesced: Vec<PixelDirtyRect> = Vec::with_capacity(dirty_rects.len().min(16));
    for rect in dirty_rects.iter() {
        let Some(mut clamped) = rect.clamp_to(fb_w, fb_h) else {
            continue;
        };
        let mut merged_any: bool = true;
        while merged_any {
            merged_any = false;
            let mut idx: usize = 0;
            while idx < coalesced.len() {
                if coalesced[idx].intersects_or_adjacent(clamped, MOBILE_UPLOAD_COALESCE_PAD_PX) {
                    let existing: PixelDirtyRect = coalesced.swap_remove(idx);
                    clamped = clamped.union_with(existing);
                    merged_any = true;
                } else {
                    idx += 1;
                }
            }
        }
        coalesced.push(clamped);
    }
    if coalesced.is_empty() {
        return AdaptiveUploadPlan {
            strategy: MobileUploadStrategy::None,
            rects: Vec::new(),
            total_upload_bytes: 0,
            merged_bbox_bytes: 0,
            full_frame_bytes: full_bytes,
            estimated_cost_score: 0.0,
        };
    }
    let mut merged_bbox: PixelDirtyRect = coalesced[0];
    let mut multi_bytes: usize = 0;
    for r in coalesced.iter() {
        merged_bbox = merged_bbox.union_with(*r);
        multi_bytes = multi_bytes.saturating_add(r.byte_size_rgba8());
    }
    let merged_bytes: usize = merged_bbox.byte_size_rgba8();
    let multi_cost: usize = multi_bytes.saturating_add(
        coalesced
            .len()
            .saturating_mul(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES),
    );
    let merged_cost: usize = merged_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
    let full_threshold_bytes: usize =
        ((full_bytes as f32) * MOBILE_UPLOAD_FULL_FRAME_COVERAGE_THRESHOLD).round() as usize;
    let full_cost: usize = full_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
    let multi_eligible: bool = coalesced.len() >= 2
        && coalesced.len() <= MOBILE_MAX_MULTI_UPLOAD_RECTS
        && multi_bytes <= full_threshold_bytes
        && multi_cost < merged_cost
        && multi_cost < full_cost;
    if multi_eligible {
        return AdaptiveUploadPlan {
            strategy: MobileUploadStrategy::MultiRect,
            rects: coalesced,
            total_upload_bytes: multi_bytes,
            merged_bbox_bytes: merged_bytes,
            full_frame_bytes: full_bytes,
            estimated_cost_score: multi_cost as f32,
        };
    }
    if merged_bytes <= full_threshold_bytes && merged_cost < full_cost {
        return AdaptiveUploadPlan {
            strategy: MobileUploadStrategy::MergedBbox,
            rects: vec![merged_bbox],
            total_upload_bytes: merged_bytes,
            merged_bbox_bytes: merged_bytes,
            full_frame_bytes: full_bytes,
            estimated_cost_score: merged_cost as f32,
        };
    }
    AdaptiveUploadPlan {
        strategy: MobileUploadStrategy::FullFrame,
        rects: vec![full_rect],
        total_upload_bytes: full_bytes,
        merged_bbox_bytes: merged_bytes,
        full_frame_bytes: full_bytes,
        estimated_cost_score: full_cost as f32,
    }
}

/// Converts a `DamageRegion` into physical `PixelDirtyRect` entries clamped to `(fb_w, fb_h)`.
///
/// # Arguments
///
/// - `DamageRegion` - Frame damage region from layout/paint.
/// - `u32` - Surface width in physical pixels.
/// - `u32` - Surface height in physical pixels.
///
/// # Returns
///
/// - `Vec<PixelDirtyRect>` - Clamped physical dirty rectangles (`empty` when no damage).
#[must_use]
pub fn damage_region_to_pixel_dirty_rects(
    damage: DamageRegion,
    fb_w: u32,
    fb_h: u32,
) -> Vec<PixelDirtyRect> {
    if fb_w == 0 || fb_h == 0 {
        return Vec::new();
    }
    if damage.get_full_damage() {
        return vec![PixelDirtyRect::new(0, 0, fb_w, fb_h)];
    }
    let Some(r) = damage.resolve(fb_w, fb_h) else {
        return Vec::new();
    };
    let rx0: u32 = (r.get_x().floor().max(0.0) as u32).min(fb_w);
    let ry0: u32 = (r.get_y().floor().max(0.0) as u32).min(fb_h);
    let rx1: u32 = (r.right().ceil().max(0.0) as u32).clamp(rx0, fb_w);
    let ry1: u32 = (r.bottom().ceil().max(0.0) as u32).clamp(ry0, fb_h);
    if rx1 > rx0 && ry1 > ry0 {
        vec![PixelDirtyRect::new(rx0, ry0, rx1 - rx0, ry1 - ry0)]
    } else {
        Vec::new()
    }
}

/// Flattens pre-compiled `HardwareRenderer` `GpuBatch` and `GpuBackdropBlurPass` slices into a single direct-GPU frame payload.
///
/// # Arguments
///
/// - `u32` - Physical surface width in pixels.
/// - `u32` - Physical surface height in pixels.
/// - `Color` - Surface clear color.
/// - `&[GpuBatch]` - Ordered GPU batches from `HardwareRenderer::active_batches_slice()`.
/// - `&[GpuBackdropBlurPass]` - Ordered Dual-Kawase backdrop blur passes.
///
/// # Returns
///
/// - `DirectGpuFrameBatch` - Flat 64-byte primitive stream and scissor draw ranges with `cpu_mirror_active = false`.
#[must_use]
pub fn build_direct_gpu_frame_batch_from_batches(
    viewport_width: u32,
    viewport_height: u32,
    clear_color: Color,
    batches: &[GpuBatch],
    blur_passes: &[GpuBackdropBlurPass],
) -> DirectGpuFrameBatch {
    let total_prims: usize = batches
        .iter()
        .map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
        .sum();
    let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
    let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(batches.len());
    let vw: u32 = viewport_width.max(1);
    let vh: u32 = viewport_height.max(1);
    for batch in batches.iter() {
        let base_instance: u32 = primitives.len() as u32;
        if !batch.get_primitives().is_empty() {
            primitives.extend_from_slice(batch.get_primitives());
        } else {
            for quad in batch.get_instances().iter() {
                primitives.push(GpuPrimitiveInstance::from_quad_instance(
                    quad,
                    batch.get_texture_slot(),
                    batch.get_layer_id(),
                ));
            }
        }
        let instance_count: u32 = (primitives.len() as u32).saturating_sub(base_instance);
        if instance_count == 0 {
            continue;
        }
        let sc: Rect = batch.get_scissor();
        let sx: u32 = (sc.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
        let sy: u32 = (sc.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
        let sw: u32 = (sc.get_width().max(1.0).ceil() as u32)
            .min(vw.saturating_sub(sx))
            .max(1);
        let sh: u32 = (sc.get_height().max(1.0).ceil() as u32)
            .min(vh.saturating_sub(sy))
            .max(1);
        let scroll: [f32; 2] = batch.get_scroll_offset();
        draw_ranges.push(DirectGpuBatchRange {
            base_instance,
            instance_count,
            scissor_x: sx,
            scissor_y: sy,
            scissor_w: sw,
            scissor_h: sh,
            scroll_x: scroll[0],
            scroll_y: scroll[1],
            texture_slot: batch.get_texture_slot(),
            layer_id: batch.get_layer_id(),
            pad: [0, 0],
        });
    }
    let instance_upload_bytes: usize = primitives
        .len()
        .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
    DirectGpuFrameBatch {
        viewport_width: vw,
        viewport_height: vh,
        clear_rgba: clear_color.to_f32_array(),
        primitives,
        draw_ranges,
        backdrop_blurs: blur_passes.to_vec(),
        glyph_r8_atlas: None,
        image_rgba8_atlas: None,
        instance_upload_bytes,
        cpu_mirror_active: false,
        upload_strategy: MobileUploadStrategy::DirectGpu,
    }
}

/// Appends one `GpuPrimitiveInstance` into `primitives` and extends or opens a scissor-matched `DirectGpuBatchRange`.
///
/// # Arguments
///
/// - `&mut Vec<GpuPrimitiveInstance>` - Flat primitive stream.
/// - `&mut Vec<DirectGpuBatchRange>` - Ordered draw ranges.
/// - `GpuPrimitiveInstance` - Primitive to emit.
/// - `Rect` - Active physical scissor clip rectangle.
/// - `u32` - Surface width in physical pixels.
/// - `u32` - Surface height in physical pixels.
fn push_direct_gpu_primitive(
    primitives: &mut Vec<GpuPrimitiveInstance>,
    draw_ranges: &mut Vec<DirectGpuBatchRange>,
    prim: GpuPrimitiveInstance,
    clip: Rect,
    vw: u32,
    vh: u32,
) {
    let sx: u32 = (clip.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
    let sy: u32 = (clip.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
    let sw: u32 = (clip.get_width().max(1.0).ceil() as u32)
        .min(vw.saturating_sub(sx))
        .max(1);
    let sh: u32 = (clip.get_height().max(1.0).ceil() as u32)
        .min(vh.saturating_sub(sy))
        .max(1);
    let base: u32 = primitives.len() as u32;
    primitives.push(prim);
    if let Some(last) = draw_ranges.last_mut()
        && last.get_scissor_x() == sx
        && last.get_scissor_y() == sy
        && last.get_scissor_w() == sw
        && last.get_scissor_h() == sh
        && last.get_instance_count() < MAX_QUADS_PER_BATCH as u32
    {
        last.set_instance_count(last.get_instance_count().saturating_add(1));
        return;
    }
    draw_ranges.push(DirectGpuBatchRange {
        base_instance: base,
        instance_count: 1,
        scissor_x: sx,
        scissor_y: sy,
        scissor_w: sw,
        scissor_h: sh,
        scroll_x: 0.0,
        scroll_y: 0.0,
        texture_slot: 0,
        layer_id: 0,
        pad: [0, 0],
    });
}

/// Encodes normalized `[u0, v0, u1, v1]` texel bounds inside an `(atlas_w, atlas_h)` sheet into `[u16; 4]`.
///
/// # Arguments
///
/// - `u32` - Atlas width in texels.
/// - `u32` - Atlas height in texels.
/// - `u32` - Sub-rectangle X coordinate in texels.
/// - `u32` - Sub-rectangle Y coordinate in texels.
/// - `u32` - Sub-rectangle width in texels.
/// - `u32` - Sub-rectangle height in texels.
///
/// # Returns
///
/// - `[u16; 4]` - Normalized UV coordinates in `[0..=65535]`.
fn encode_atlas_uv_rect(atlas_w: u32, atlas_h: u32, x: u32, y: u32, w: u32, h: u32) -> [u16; 4] {
    let inv_w: f32 = 1.0 / (atlas_w.max(1) as f32);
    let inv_h: f32 = 1.0 / (atlas_h.max(1) as f32);
    let u0: u16 = (((x as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
    let v0: u16 = (((y as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
    let u1: u16 = ((((x + w) as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
    let v1: u16 = ((((y + h) as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
    [u0, v0, u1, v1]
}

/// Packs frame RGBA8 image/sprite slices into a single shelf-packed RGBA8 texture atlas and resolves UV rectangles.
///
/// # Arguments
///
/// - `&[DirectGpuImageSlice<'_>]` - Borrowed RGBA8 image and sprite crop descriptors.
/// - `u64` - Revision tag stamped onto the output atlas.
///
/// # Returns
///
/// - `(Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>)` - Packed RGBA8 image sheet and per-entry normalized UVs.
fn pack_frame_image_atlas(
    images: &[DirectGpuImageSlice<'_>],
    revision: u64,
) -> (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) {
    if images.is_empty() {
        return (None, Vec::new());
    }
    let mut max_w: u32 = 1;
    let mut sum_w: u32 = 1;
    for entry in images.iter() {
        let cw: u32 = entry.crop.get_width();
        max_w = max_w.max(cw.saturating_add(2));
        sum_w = sum_w.saturating_add(cw.saturating_add(1));
    }
    let atlas_w: u32 = sum_w
        .clamp(64, 2048)
        .max(max_w)
        .next_power_of_two()
        .min(4096);
    let mut placements: Vec<(u32, u32, u32, u32)> = Vec::with_capacity(images.len());
    let mut cx: u32 = 1;
    let mut cy: u32 = 1;
    let mut shelf_h: u32 = 0;
    for entry in images.iter() {
        let clamped_w: u32 = entry.crop.get_width().min(atlas_w.saturating_sub(2)).max(1);
        let clamped_h: u32 = entry.crop.get_height().max(1);
        if cx + clamped_w + 1 > atlas_w {
            cx = 1;
            cy = cy.saturating_add(shelf_h).saturating_add(1);
            shelf_h = 0;
        }
        placements.push((cx, cy, clamped_w, clamped_h));
        cx = cx.saturating_add(clamped_w).saturating_add(1);
        shelf_h = shelf_h.max(clamped_h);
    }
    let atlas_h: u32 = cy.saturating_add(shelf_h).saturating_add(1).max(64);
    let mut pixels: Vec<u8> = vec![0; (atlas_w as usize) * (atlas_h as usize) * 4];
    let mut uvs: Vec<[u16; 4]> = Vec::with_capacity(images.len());
    for (idx, entry) in images.iter().enumerate() {
        let (dx, dy, copy_w, copy_h): (u32, u32, u32, u32) = placements[idx];
        let sx: u32 = entry.crop.get_x();
        let sy: u32 = entry.crop.get_y();
        let valid_w: u32 = copy_w.min(entry.src_w.saturating_sub(sx));
        let valid_h: u32 = copy_h.min(entry.src_h.saturating_sub(sy));
        for row in 0..valid_h {
            let src_off: usize =
                (((sy + row) as usize) * (entry.src_w as usize) + (sx as usize)) * 4;
            let dst_off: usize = (((dy + row) as usize) * (atlas_w as usize) + (dx as usize)) * 4;
            let row_bytes: usize = (valid_w as usize) * 4;
            if src_off + row_bytes <= entry.pixels.len() && dst_off + row_bytes <= pixels.len() {
                pixels[dst_off..dst_off + row_bytes]
                    .copy_from_slice(&entry.pixels[src_off..src_off + row_bytes]);
            }
        }
        uvs.push(encode_atlas_uv_rect(
            atlas_w, atlas_h, dx, dy, valid_w, valid_h,
        ));
    }
    (
        Some(DirectGpuAtlasUpload {
            width: atlas_w,
            height: atlas_h,
            revision,
            pixels,
        }),
        uvs,
    )
}

/// 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.
///
/// # Arguments
///
/// - `&DisplayList` - Scene draw command stream for the current frame.
/// - `Option<&mut GlyphAtlas>` - Shared glyph atlas used to rasterize and pack `PrimKind::GlyphAlpha8` quads.
/// - `Option<&NativeSystemFont>` - Optional native OS font provider for glyph rasterization.
/// - `u64` - Previously uploaded glyph atlas revision (`0` forces initial upload).
///
/// # Returns
///
/// - `DirectGpuFrameBatch` - Self-contained direct-GPU primitive, range, blur, and atlas payload (`cpu_mirror_active = false`).
#[must_use]
pub fn compile_display_list_direct_gpu_batch(
    display_list: &DisplayList,
    mut glyph_atlas: Option<&mut GlyphAtlas>,
    font_provider: Option<&NativeSystemFont>,
    last_glyph_revision: u64,
) -> DirectGpuFrameBatch {
    let scale: f32 = display_list.get_scale_factor().max(0.5);
    let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
    let phys_h: u32 = ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
    let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
    let mut clip_stack: Vec<Rect> = Vec::with_capacity(16);
    clip_stack.push(full_clip);
    let mut primitives: Vec<GpuPrimitiveInstance> =
        Vec::with_capacity(display_list.get_commands().len().saturating_mul(2));
    let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(16);
    let mut backdrop_blurs: Vec<GpuBackdropBlurPass> = Vec::new();
    let mut glyph_fixups: Vec<(usize, GlyphKey)> = Vec::new();
    let mut image_entries: Vec<DirectGpuImageSlice<'_>> = Vec::new();
    let mut image_fixups: Vec<(usize, usize)> = Vec::new();
    let mut clear_rgba: [f32; 4] = COLOR_WHITE.to_f32_array();
    for cmd in display_list.get_commands().iter() {
        let active_clip: Rect = clip_stack.last().copied().unwrap_or(full_clip);
        let clip_arr: [f32; 4] = [
            active_clip.get_x(),
            active_clip.get_y(),
            active_clip.right(),
            active_clip.bottom(),
        ];
        match cmd {
            DrawCommand::Clear(c) => {
                clear_rgba = c.to_f32_array();
            }
            DrawCommand::PushClip(rect) => {
                let phys: Rect = snap_physical_rect(*rect, scale);
                clip_stack.push(active_clip.intersect(phys).unwrap_or_default());
            }
            DrawCommand::PushRoundedClip { rect, .. } => {
                let phys: Rect = snap_physical_rect(*rect, scale);
                clip_stack.push(active_clip.intersect(phys).unwrap_or_default());
            }
            DrawCommand::PopClip => {
                if clip_stack.len() > 1 {
                    let _: Option<Rect> = clip_stack.pop();
                }
            }
            DrawCommand::FillRoundedRect {
                rect,
                color,
                radius,
                border,
            } => {
                let snapped: Rect = snap_physical_rect(*rect, scale);
                let quad: [f32; 4] = [
                    snapped.get_x(),
                    snapped.get_y(),
                    snapped.get_width(),
                    snapped.get_height(),
                ];
                if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
                    continue;
                }
                let bw: f32 = if border.get_width() > 0.0 {
                    (border.get_width() * scale).max(1.0)
                } else {
                    0.0
                };
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: quad,
                    clip: clip_arr,
                    color: color.to_f32_array(),
                    secondary_color: border.get_color().to_f32_array(),
                    radii: [
                        radius.get_top_left() * scale,
                        radius.get_top_right() * scale,
                        radius.get_bottom_right() * scale,
                        radius.get_bottom_left() * scale,
                    ],
                    stroke_or_blur: bw,
                    angle_rad: 0.0,
                    kind: GpuPrimitiveKind::RoundedRect as u32,
                    reserved: 0,
                };
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
            }
            DrawCommand::LinearGradientRect {
                rect,
                gradient,
                radius,
            } => {
                let snapped: Rect = snap_physical_rect(*rect, scale);
                let quad: [f32; 4] = [
                    snapped.get_x(),
                    snapped.get_y(),
                    snapped.get_width(),
                    snapped.get_height(),
                ];
                if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
                    continue;
                }
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: quad,
                    clip: clip_arr,
                    color: gradient.get_start_color().to_f32_array(),
                    secondary_color: gradient.get_end_color().to_f32_array(),
                    radii: [
                        radius.get_top_left() * scale,
                        radius.get_top_right() * scale,
                        radius.get_bottom_right() * scale,
                        radius.get_bottom_left() * scale,
                    ],
                    stroke_or_blur: 0.0,
                    angle_rad: gradient.get_angle_deg().to_radians(),
                    kind: GpuPrimitiveKind::Gradient as u32,
                    reserved: 0,
                };
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
            }
            DrawCommand::BoxShadow {
                rect,
                radius,
                shadow,
            } => {
                let spread: f32 = shadow.get_spread_radius() * scale;
                let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
                let sigma: f32 = (blur * 0.5).max(0.75);
                let pad: f32 = (sigma * 3.0).ceil();
                let base_rect: Rect = snap_physical_rect(*rect, scale);
                let cx: f32 = base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
                let cy: f32 = base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
                let cw: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
                let ch: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: [cx - pad, cy - pad, cw + pad * 2.0, ch + pad * 2.0],
                    clip: clip_arr,
                    color: shadow.get_color().to_f32_array(),
                    secondary_color: [0.0; 4],
                    radii: [
                        (radius.get_top_left() * scale + spread).max(0.0),
                        (radius.get_top_right() * scale + spread).max(0.0),
                        (radius.get_bottom_right() * scale + spread).max(0.0),
                        (radius.get_bottom_left() * scale + spread).max(0.0),
                    ],
                    stroke_or_blur: sigma,
                    angle_rad: pad,
                    kind: GpuPrimitiveKind::Shadow as u32,
                    reserved: 0,
                };
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
            }
            DrawCommand::BackdropBlur {
                rect,
                radius,
                blur_radius,
            } => {
                let snapped: Rect = snap_physical_rect(*rect, scale);
                let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 96.0);
                let radii_px: [f32; 4] = [
                    radius.get_top_left() * scale,
                    radius.get_top_right() * scale,
                    radius.get_bottom_right() * scale,
                    radius.get_bottom_left() * scale,
                ];
                let halo: Rect = Rect::new(
                    (snapped.get_x() - phys_blur).max(0.0),
                    (snapped.get_y() - phys_blur).max(0.0),
                    (snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
                    (snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
                );
                backdrop_blurs.push(GpuBackdropBlurPass {
                    bounds: snapped,
                    input_bounds: halo,
                    clip_rect: active_clip,
                    radii: radii_px,
                    blur_radius: phys_blur,
                    layer_id: 0,
                });
            }
            DrawCommand::TextRun { rect, text, style } => {
                if text.is_empty()
                    || active_clip.get_width() <= 0.0
                    || active_clip.get_height() <= 0.0
                {
                    continue;
                }
                if let Some(atlas) = glyph_atlas.as_deref_mut() {
                    let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
                    let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
                        text,
                        *style,
                        Some(rect.get_width().max(1.0)),
                    );
                    let line_h: f32 = meas.get_line_height_px() * scale;
                    let color_rgba: u32 = GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
                    let kind_flags: u32 =
                        GpuPrimitiveInstance::pack_kind_flags(PrimKind::GlyphAlpha8, 0, 0, 0);
                    for (line_idx, line) in meas.get_lines().iter().enumerate() {
                        let base_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h;
                        let mut pen_x: f32 = rect.get_x() * scale;
                        for ch in line.get_text().chars() {
                            if ch == ' ' || ch == '\t' {
                                pen_x += measure_char_advance(ch, *style) * scale;
                                continue;
                            }
                            let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_px, *style);
                            let (gw, gh, adv): (u32, u32, f32) = {
                                let g: &RasterizedGlyph = match font_provider {
                                    Some(fp) => atlas.get_or_rasterize_with(key, fp),
                                    None => atlas.get_or_rasterize(key),
                                };
                                (
                                    g.get_width(),
                                    g.get_height(),
                                    (g.get_advance() as f32)
                                        .max(measure_char_advance(ch, *style) * scale),
                                )
                            };
                            if gw > 0 && gh > 0 {
                                let y_off: f32 = ((line_h - (gh as f32)) * 0.5).max(0.0);
                                let prim_idx: usize = primitives.len();
                                let prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
                                    rect: [
                                        pen_x.round(),
                                        (base_y + y_off).round(),
                                        gw as f32,
                                        gh as f32,
                                    ],
                                    clip_rect: clip_arr,
                                    color_rgba,
                                    aux_color_rgba: 0,
                                    uv_rect: [0, 0, 0, 0],
                                    radii_border: [0; 4],
                                    kind_flags,
                                    extra_param: 0,
                                };
                                push_direct_gpu_primitive(
                                    &mut primitives,
                                    &mut draw_ranges,
                                    prim,
                                    active_clip,
                                    phys_w,
                                    phys_h,
                                );
                                glyph_fixups.push((prim_idx, key));
                            }
                            pen_x += adv;
                        }
                    }
                } else {
                    let q: GpuQuadInstance = GpuQuadInstance {
                        rect: [
                            rect.get_x() * scale,
                            rect.get_y() * scale,
                            rect.get_width() * scale,
                            rect.get_height() * scale,
                        ],
                        clip: clip_arr,
                        color: style.get_color().to_f32_array(),
                        secondary_color: [0.0; 4],
                        radii: [0.0; 4],
                        stroke_or_blur: style.get_font_size() * scale,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::Glyph as u32,
                        reserved: text.chars().count() as u32,
                    };
                    push_direct_gpu_primitive(
                        &mut primitives,
                        &mut draw_ranges,
                        GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                        active_clip,
                        phys_w,
                        phys_h,
                    );
                }
            }
            DrawCommand::TextCaret {
                text_rect,
                content_rect,
                text,
                style,
                caret_height,
                color,
                multiline,
            } => {
                if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
                    continue;
                }
                let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
                    text,
                    *style,
                    if *multiline {
                        Some(content_rect.get_width().max(1.0))
                    } else {
                        None
                    },
                );
                let last_w: f32 = meas
                    .get_lines()
                    .last()
                    .map(TextLine::get_width)
                    .unwrap_or(0.0);
                let line_idx: usize = meas.get_lines().len().saturating_sub(1);
                let caret_x: f32 =
                    (text_rect.get_x() + last_w + if last_w > 0.0 { 1.5 } else { 0.0 }).clamp(
                        content_rect.get_x(),
                        (content_rect.right() - 2.0).max(content_rect.get_x()),
                    );
                let caret_y: f32 = if *multiline {
                    (content_rect.get_y()
                        + (line_idx as f32) * meas.get_line_height_px()
                        + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
                    .clamp(
                        content_rect.get_y(),
                        (content_rect.bottom() - caret_height).max(content_rect.get_y()),
                    )
                } else {
                    content_rect.get_y()
                        + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
                };
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: [
                        caret_x * scale,
                        caret_y * scale,
                        (1.5 * scale).max(1.0),
                        (caret_height * scale).max(2.0),
                    ],
                    clip: clip_arr,
                    color: color.to_f32_array(),
                    secondary_color: [0.0; 4],
                    radii: [0.5 * scale; 4],
                    stroke_or_blur: 0.0,
                    angle_rad: 0.0,
                    kind: GpuPrimitiveKind::RoundedRect as u32,
                    reserved: 0,
                };
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
            }
            DrawCommand::Image {
                rect,
                buffer,
                radius,
            } => {
                let snapped: Rect = snap_physical_rect(*rect, scale);
                let img_w: u32 = buffer.get_width();
                let img_h: u32 = buffer.get_height();
                if img_w == 0
                    || img_h == 0
                    || snapped.get_width() <= 0.0
                    || snapped.get_height() <= 0.0
                {
                    continue;
                }
                let img_idx: usize = image_entries.len();
                image_entries.push(DirectGpuImageSlice {
                    src_w: img_w,
                    src_h: img_h,
                    pixels: buffer.get_pixels(),
                    crop: PixelDirtyRect::new(0, 0, img_w, img_h),
                });
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: [
                        snapped.get_x(),
                        snapped.get_y(),
                        snapped.get_width(),
                        snapped.get_height(),
                    ],
                    clip: clip_arr,
                    color: [1.0, 1.0, 1.0, 1.0],
                    secondary_color: [0.0; 4],
                    radii: [
                        radius.get_top_left() * scale,
                        radius.get_top_right() * scale,
                        radius.get_bottom_right() * scale,
                        radius.get_bottom_left() * scale,
                    ],
                    stroke_or_blur: 0.0,
                    angle_rad: 0.0,
                    kind: GpuPrimitiveKind::TexturedQuad as u32,
                    reserved: 0,
                };
                let prim_idx: usize = primitives.len();
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
                image_fixups.push((prim_idx, img_idx));
            }
            DrawCommand::SharedImage {
                rect,
                width,
                height,
                pixels,
                radius,
            } => {
                let snapped: Rect = snap_physical_rect(*rect, scale);
                if *width == 0
                    || *height == 0
                    || snapped.get_width() <= 0.0
                    || snapped.get_height() <= 0.0
                {
                    continue;
                }
                let img_idx: usize = image_entries.len();
                image_entries.push(DirectGpuImageSlice {
                    src_w: *width,
                    src_h: *height,
                    pixels: pixels.as_slice(),
                    crop: PixelDirtyRect::new(0, 0, *width, *height),
                });
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: [
                        snapped.get_x(),
                        snapped.get_y(),
                        snapped.get_width(),
                        snapped.get_height(),
                    ],
                    clip: clip_arr,
                    color: [1.0, 1.0, 1.0, 1.0],
                    secondary_color: [0.0; 4],
                    radii: [
                        radius.get_top_left() * scale,
                        radius.get_top_right() * scale,
                        radius.get_bottom_right() * scale,
                        radius.get_bottom_left() * scale,
                    ],
                    stroke_or_blur: 0.0,
                    angle_rad: 0.0,
                    kind: GpuPrimitiveKind::TexturedQuad as u32,
                    reserved: 0,
                };
                let prim_idx: usize = primitives.len();
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
                image_fixups.push((prim_idx, img_idx));
            }
            DrawCommand::SpriteRegion {
                rect,
                buffer,
                src_rect,
                tint,
            } => {
                let snapped: Rect = snap_physical_rect(*rect, scale);
                let img_w: u32 = buffer.get_width();
                let img_h: u32 = buffer.get_height();
                let sx: u32 = (src_rect.get_x().max(0.0).floor() as u32).min(img_w);
                let sy: u32 = (src_rect.get_y().max(0.0).floor() as u32).min(img_h);
                let sw: u32 =
                    (src_rect.get_width().max(1.0).ceil() as u32).min(img_w.saturating_sub(sx));
                let sh: u32 =
                    (src_rect.get_height().max(1.0).ceil() as u32).min(img_h.saturating_sub(sy));
                if sw == 0 || sh == 0 || snapped.get_width() <= 0.0 || snapped.get_height() <= 0.0 {
                    continue;
                }
                let img_idx: usize = image_entries.len();
                image_entries.push(DirectGpuImageSlice {
                    src_w: img_w,
                    src_h: img_h,
                    pixels: buffer.get_pixels(),
                    crop: PixelDirtyRect::new(sx, sy, sw, sh),
                });
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: [
                        snapped.get_x(),
                        snapped.get_y(),
                        snapped.get_width(),
                        snapped.get_height(),
                    ],
                    clip: clip_arr,
                    color: tint.to_f32_array(),
                    secondary_color: [0.0; 4],
                    radii: [0.0; 4],
                    stroke_or_blur: 0.0,
                    angle_rad: 0.0,
                    kind: GpuPrimitiveKind::TexturedQuad as u32,
                    reserved: 1,
                };
                let prim_idx: usize = primitives.len();
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
                image_fixups.push((prim_idx, img_idx));
            }
            DrawCommand::Circle {
                center,
                radius,
                color,
            } => {
                let r: f32 = radius * scale;
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: [
                        center.get_x() * scale - r,
                        center.get_y() * scale - r,
                        r * 2.0,
                        r * 2.0,
                    ],
                    clip: clip_arr,
                    color: color.to_f32_array(),
                    secondary_color: [0.0; 4],
                    radii: [r; 4],
                    stroke_or_blur: 0.0,
                    angle_rad: 0.0,
                    kind: GpuPrimitiveKind::Circle as u32,
                    reserved: 0,
                };
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
            }
            DrawCommand::Line {
                from,
                to,
                color,
                width,
            } => {
                let dx: f32 = (to.get_x() - from.get_x()) * scale;
                let dy: f32 = (to.get_y() - from.get_y()) * scale;
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: [
                        from.get_x().min(to.get_x()) * scale,
                        from.get_y().min(to.get_y()) * scale,
                        dx.abs().max(width * scale),
                        dy.abs().max(width * scale),
                    ],
                    clip: clip_arr,
                    color: color.to_f32_array(),
                    secondary_color: [0.0; 4],
                    radii: [
                        from.get_x() * scale,
                        from.get_y() * scale,
                        to.get_x() * scale,
                        to.get_y() * scale,
                    ],
                    stroke_or_blur: width * scale,
                    angle_rad: dy.atan2(dx),
                    kind: GpuPrimitiveKind::Line as u32,
                    reserved: 0,
                };
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
            }
            DrawCommand::Triangle { p0, p1, p2, color } => {
                let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale;
                let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale;
                let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale;
                let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale;
                let q: GpuQuadInstance = GpuQuadInstance {
                    rect: [
                        min_x,
                        min_y,
                        (max_x - min_x).max(1.0),
                        (max_y - min_y).max(1.0),
                    ],
                    clip: clip_arr,
                    color: color.to_f32_array(),
                    secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
                    radii: [
                        p1.get_x() * scale,
                        p1.get_y() * scale,
                        p2.get_x() * scale,
                        p2.get_y() * scale,
                    ],
                    stroke_or_blur: 0.0,
                    angle_rad: 0.0,
                    kind: GpuPrimitiveKind::Triangle as u32,
                    reserved: 3,
                };
                push_direct_gpu_primitive(
                    &mut primitives,
                    &mut draw_ranges,
                    GpuPrimitiveInstance::from_quad_instance(&q, 0, 0),
                    active_clip,
                    phys_w,
                    phys_h,
                );
            }
        }
    }
    let mut glyph_r8_atlas: Option<DirectGpuAtlasUpload> = None;
    if let Some(atlas) = glyph_atlas.as_deref()
        && (!glyph_fixups.is_empty() || atlas.get_revision() != last_glyph_revision)
        && !atlas.is_empty()
    {
        let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
        let aw: u32 = packed.get_width();
        let ah: u32 = packed.get_height();
        for &(prim_idx, key) in glyph_fixups.iter() {
            if let Some(&(gx, gy, gw, gh)) = packed.get_regions().get(&key) {
                primitives[prim_idx].set_uv_rect(encode_atlas_uv_rect(aw, ah, gx, gy, gw, gh));
            }
        }
        if packed.get_revision() != last_glyph_revision {
            let rgba: &[u8] = packed.get_pixels().as_slice();
            let mut r8: Vec<u8> = Vec::with_capacity((aw as usize).saturating_mul(ah as usize));
            for px in rgba.as_chunks::<4>().0 {
                r8.push(px[3]);
            }
            glyph_r8_atlas = Some(DirectGpuAtlasUpload {
                width: aw,
                height: ah,
                revision: packed.get_revision(),
                pixels: r8,
            });
        }
    }
    let (image_rgba8_atlas, img_uvs): (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) =
        pack_frame_image_atlas(&image_entries, display_list.fast_hash());
    for &(prim_idx, img_idx) in image_fixups.iter() {
        if let Some(&uv) = img_uvs.get(img_idx) {
            primitives[prim_idx].set_uv_rect(uv);
        }
    }
    let glyph_bytes: usize = glyph_r8_atlas
        .as_ref()
        .map(|a: &DirectGpuAtlasUpload| a.get_pixels().len())
        .unwrap_or(0);
    let image_bytes: usize = image_rgba8_atlas
        .as_ref()
        .map(|a: &DirectGpuAtlasUpload| a.get_pixels().len())
        .unwrap_or(0);
    let instance_upload_bytes: usize = primitives
        .len()
        .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES)
        .saturating_add(glyph_bytes)
        .saturating_add(image_bytes);
    DirectGpuFrameBatch {
        viewport_width: phys_w,
        viewport_height: phys_h,
        clear_rgba,
        primitives,
        draw_ranges,
        backdrop_blurs,
        glyph_r8_atlas,
        image_rgba8_atlas,
        instance_upload_bytes,
        cpu_mirror_active: false,
        upload_strategy: MobileUploadStrategy::DirectGpu,
    }
}