euv-core 0.53.0

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
/// Full Blender Principled BSDF + 4-Cascade Vogel-Disk CSM + Clustered Lights + SH9/Octahedral IBL + AgX/ACES WGSL shader for WebGPU targets.
pub const WGSL_ENGINE3D_PBR_SHADER: &str = r#"struct CameraUniforms {
    view_proj: mat4x4<f32>,
    prev_view_proj: mat4x4<f32>,
    camera_pos: vec4<f32>,
    sun_dir_intensity: vec4<f32>,
    sun_color_ambient: vec4<f32>,
    sky_horizon_fog: vec4<f32>,
    sky_zenith_exposure: vec4<f32>,
    csm_splits: vec4<f32>,
    csm_matrices: array<mat4x4<f32>, 4>,
    ibl_sh: array<vec4<f32>, 9>,
    tonemap_cluster_params: vec4<f32>,
};

struct InstanceData {
    model_col0: vec4<f32>,
    model_col1: vec4<f32>,
    model_col2: vec4<f32>,
    model_col3: vec4<f32>,
    albedo_metallic: vec4<f32>,
    emissive_roughness: vec4<f32>,
    material_skin_morph_flags: vec4<u32>,
};

struct GpuMaterialData {
    base_color_factor: vec4<f32>,
    emissive_alpha_cutoff: vec4<f32>,
    pbr_ior_specular: vec4<f32>,
    specular_color_clearcoat: vec4<f32>,
    clearcoat_normal_occ_trans: vec4<f32>,
    volume_attenuation: vec4<f32>,
    sheen_color_roughness: vec4<f32>,
    tex_indices_a: vec4<u32>,
    tex_indices_b: vec4<u32>,
    flags_volume: vec4<u32>,
};

struct PackedLocalLight {
    pos_inv_r2: vec4<f32>,
    radiance_radius: vec4<f32>,
    dir_outer_cos: vec4<f32>,
    inv_cone_area: vec4<f32>,
};

@group(0) @binding(0) var<uniform> u_cam: CameraUniforms;
@group(0) @binding(1) var<storage, read> s_instances: array<InstanceData>;
@group(0) @binding(2) var<storage, read> s_materials: array<GpuMaterialData>;
@group(0) @binding(3) var<storage, read> s_lights: array<PackedLocalLight>;
@group(0) @binding(4) var t_textures: texture_2d_array<f32>;
@group(0) @binding(5) var t_csm_shadow: texture_depth_2d_array;
@group(0) @binding(6) var t_ibl_oct: texture_2d<f32>;
@group(0) @binding(7) var t_brdf_lut: texture_2d<f32>;
@group(0) @binding(8) var s_linear: sampler;
@group(0) @binding(9) var s_shadow: sampler_comparison;

struct VertexInput {
    @location(0) position: vec3<f32>,
    @location(1) normal: vec3<f32>,
    @location(2) tangent: vec4<f32>,
    @location(3) uv0: vec2<f32>,
    @location(4) uv1: vec2<f32>,
    @location(5) color0: vec4<f32>,
    @builtin(instance_index) instance_id: u32,
};

struct VertexOutput {
    @builtin(position) clip_pos: vec4<f32>,
    @location(0) world_pos: vec3<f32>,
    @location(1) world_normal: vec3<f32>,
    @location(2) world_tangent: vec4<f32>,
    @location(3) uv0: vec2<f32>,
    @location(4) color0: vec4<f32>,
    @location(5) albedo_metallic: vec4<f32>,
    @location(6) emissive_roughness: vec4<f32>,
    @location(7) @interpolate(flat) material_flags: vec4<u32>,
};

fn cofactor_normal_matrix(c0: vec3<f32>, c1: vec3<f32>, c2: vec3<f32>) -> mat3x3<f32> {
    let n0 = cross(c1, c2);
    let n1 = cross(c2, c0);
    let n2 = cross(c0, c1);
    let det = dot(c0, n0);
    let inv_det = select(1.0, 1.0 / det, abs(det) > 1.0e-8);
    return mat3x3<f32>(n0 * inv_det, n1 * inv_det, n2 * inv_det);
}

@vertex
fn vs_main(input: VertexInput) -> VertexOutput {
    let inst = s_instances[input.instance_id];
    let model = mat4x4<f32>(inst.model_col0, inst.model_col1, inst.model_col2, inst.model_col3);
    let world = (model * vec4<f32>(input.position, 1.0)).xyz;
    let normal_mat = cofactor_normal_matrix(inst.model_col0.xyz, inst.model_col1.xyz, inst.model_col2.xyz);
    let world_n = normalize(normal_mat * input.normal);
    let world_t = normalize((model * vec4<f32>(input.tangent.xyz, 0.0)).xyz);
    var out: VertexOutput;
    out.clip_pos = u_cam.view_proj * vec4<f32>(world, 1.0);
    out.world_pos = world;
    out.world_normal = world_n;
    out.world_tangent = vec4<f32>(world_t, input.tangent.w);
    out.uv0 = input.uv0;
    out.color0 = input.color0;
    out.albedo_metallic = inst.albedo_metallic;
    out.emissive_roughness = inst.emissive_roughness;
    out.material_flags = inst.material_skin_morph_flags;
    return out;
}

fn dielectric_f0_from_ior(ior: f32) -> f32 {
    let r = (ior - 1.0) / max(ior + 1.0, 1.0e-4);
    return r * r;
}

fn distribution_ggx(n_dot_h: f32, alpha2: f32) -> f32 {
    let denom = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
    return alpha2 / max(3.14159265 * denom * denom, 1.0e-5);
}

fn visibility_smith_ggx(n_dot_v: f32, n_dot_l: f32, alpha: f32) -> f32 {
    let a2 = alpha * alpha;
    let ggx_v = n_dot_l * sqrt(n_dot_v * n_dot_v * (1.0 - a2) + a2);
    let ggx_l = n_dot_v * sqrt(n_dot_l * n_dot_l * (1.0 - a2) + a2);
    return 0.5 / max(ggx_v + ggx_l, 1.0e-5);
}

fn distribution_charlie(roughness: f32, n_dot_h: f32) -> f32 {
    let inv_r = 1.0 / max(roughness, 0.07);
    let sin2_h = max(1.0 - n_dot_h * n_dot_h, 0.0078125);
    return (2.0 + inv_r) * pow(sin2_h, inv_r * 0.5) / 6.2831853;
}

fn visibility_ashikhmin(n_dot_v: f32, n_dot_l: f32) -> f32 {
    return 1.0 / max(4.0 * (n_dot_l + n_dot_v - n_dot_l * n_dot_v), 1.0e-4);
}

fn octahedral_encode_dir(dir: vec3<f32>) -> vec2<f32> {
    let d = normalize(dir);
    let l1 = max(abs(d.x) + abs(d.y) + abs(d.z), 1.0e-6);
    var ox = d.x / l1;
    var oz = d.z / l1;
    if (d.y < 0.0) {
        let px = ox;
        let pz = oz;
        ox = (1.0 - abs(pz)) * select(-1.0, 1.0, px >= 0.0);
        oz = (1.0 - abs(px)) * select(-1.0, 1.0, pz >= 0.0);
    }
    return vec2<f32>(ox * 0.5 + 0.5, oz * 0.5 + 0.5);
}

fn eval_sh9_diffuse(norm: vec3<f32>) -> vec3<f32> {
    let x = norm.x;
    let y = norm.y;
    let z = norm.z;
    var irrad = u_cam.ibl_sh[0].xyz * 0.2820948;
    irrad += u_cam.ibl_sh[1].xyz * (0.4886025 * y);
    irrad += u_cam.ibl_sh[2].xyz * (0.4886025 * z);
    irrad += u_cam.ibl_sh[3].xyz * (0.4886025 * x);
    irrad += u_cam.ibl_sh[4].xyz * (1.0925484 * x * y);
    irrad += u_cam.ibl_sh[5].xyz * (1.0925484 * y * z);
    irrad += u_cam.ibl_sh[6].xyz * (0.3153916 * (3.0 * z * z - 1.0));
    irrad += u_cam.ibl_sh[7].xyz * (1.0925484 * x * z);
    irrad += u_cam.ibl_sh[8].xyz * (0.5462742 * (x * x - y * y));
    return max(irrad, vec3<f32>(0.0));
}

fn sample_csm_vogel_16(world_pos: vec3<f32>, norm: vec3<f32>, sun_dir: vec3<f32>, view_depth: f32) -> f32 {
    var cascade: i32 = 3;
    if (view_depth < u_cam.csm_splits.x) {
        cascade = 0;
    } else if (view_depth < u_cam.csm_splits.y) {
        cascade = 1;
    } else if (view_depth < u_cam.csm_splits.z) {
        cascade = 2;
    }
    let biased_pos = world_pos + norm * (0.04 + 0.02 * f32(cascade));
    let light_clip = u_cam.csm_matrices[cascade] * vec4<f32>(biased_pos, 1.0);
    let uv = light_clip.xy * 0.5 + vec2<f32>(0.5, 0.5);
    let depth = light_clip.z;
    if (uv.x < 0.01 || uv.x > 0.99 || uv.y < 0.01 || uv.y > 0.99 || depth <= 0.0 || depth >= 1.0) {
        return 1.0;
    }
    let n_dot_l = clamp(dot(norm, sun_dir), 0.05, 1.0);
    let bias = clamp(0.0022 * (1.0 - n_dot_l) + 0.0012, 0.001, 0.008);
    let angle = fract(sin(dot(world_pos, vec3<f32>(12.9898, 37.719, 78.233))) * 43758.547) * 6.2831853;
    let c_rot = cos(angle);
    let s_rot = sin(angle);
    let radius = 0.0025;
    var vis: f32 = 0.0;
    for (var tap: i32 = 0; tap < 16; tap = tap + 1) {
        let r_tap = sqrt((f32(tap) + 0.5) / 16.0) * radius;
        let theta = f32(tap) * 2.39996323;
        let ox = cos(theta) * r_tap;
        let oy = sin(theta) * r_tap;
        let rot_uv = uv + vec2<f32>(ox * c_rot - oy * s_rot, ox * s_rot + oy * c_rot);
        vis += textureSampleCompare(t_csm_shadow, s_shadow, rot_uv, cascade, depth - bias);
    }
    return 0.22 + 0.78 * (vis / 16.0);
}

fn agx_contrast_poly(x: vec3<f32>) -> vec3<f32> {
    let x2 = x * x;
    let x4 = x2 * x2;
    return clamp(15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232, vec3<f32>(0.0), vec3<f32>(1.0));
}

fn agx_tonemap(hdr: vec3<f32>) -> vec3<f32> {
    let inset = mat3x3<f32>(
        vec3<f32>(0.84247906, 0.04232824, 0.04237565),
        vec3<f32>(0.07843360, 0.87846864, 0.07843360),
        vec3<f32>(0.07922375, 0.07916613, 0.87914297),
    );
    let outset = mat3x3<f32>(
        vec3<f32>(1.19687900, -0.05289685, -0.05297163),
        vec3<f32>(-0.09802088, 1.15190313, -0.09804345),
        vec3<f32>(-0.09902975, -0.09896118, 1.15107367),
    );
    let val = max(inset * max(hdr, vec3<f32>(1.0e-6)), vec3<f32>(1.0e-6));
    let log_val = clamp((log2(val) - vec3<f32>(-12.47393)) / vec3<f32>(16.5), vec3<f32>(0.0), vec3<f32>(1.0));
    let curved = agx_contrast_poly(log_val);
    return clamp(outset * curved, vec3<f32>(0.0), vec3<f32>(1.0));
}

fn aces_filmic(hdr: vec3<f32>) -> vec3<f32> {
    let num = hdr * (2.51 * hdr + 0.03);
    let den = hdr * (2.43 * hdr + 0.59) + 0.14;
    return clamp(num / max(den, vec3<f32>(0.0001)), vec3<f32>(0.0), vec3<f32>(1.0));
}

@fragment
fn fs_main(input: VertexOutput, @builtin(front_facing) is_front: bool) -> @location(0) vec4<f32> {
    let use_principled = (input.material_flags.w & 2u) != 0u;
    var base_rgba = vec4<f32>(input.albedo_metallic.xyz, 1.0) * input.color0;
    var metallic = clamp(input.albedo_metallic.w, 0.0, 1.0);
    var roughness = clamp(input.emissive_roughness.w, 0.04, 1.0);
    var emissive = input.emissive_roughness.xyz;
    var ior: f32 = 1.5;
    var spec_factor: f32 = 1.0;
    var spec_color = vec3<f32>(1.0);
    var clearcoat: f32 = 0.0;
    var clearcoat_rough: f32 = 0.04;
    var sheen_color = vec3<f32>(0.0);
    var sheen_rough: f32 = 0.5;
    var transmission: f32 = 0.0;
    var thickness: f32 = 0.0;
    var atten_color = vec3<f32>(1.0);
    var atten_dist: f32 = 1.0e6;
    var occlusion: f32 = 1.0;
    var unlit: bool = false;
    var norm = normalize(input.world_normal);
    if (!is_front) {
        norm = -norm;
    }
    let t_ortho = normalize(input.world_tangent.xyz - norm * dot(input.world_tangent.xyz, norm));
    let bitangent = cross(norm, t_ortho) * input.world_tangent.w;
    if (use_principled) {
        let mat = s_materials[input.material_flags.x];
        base_rgba = mat.base_color_factor * input.color0;
        if (mat.tex_indices_a.x != 0xffffffffu) {
            base_rgba *= textureSample(t_textures, s_linear, input.uv0, i32(mat.tex_indices_a.x));
        }
        let flags = mat.flags_volume.x;
        if ((flags & 1u) != 0u && base_rgba.a < mat.emissive_alpha_cutoff.w) {
            discard;
        }
        unlit = (flags & 8u) != 0u;
        metallic = clamp(mat.pbr_ior_specular.x, 0.0, 1.0);
        roughness = clamp(mat.pbr_ior_specular.y, 0.04, 1.0);
        if (mat.tex_indices_a.y != 0xffffffffu) {
            let mr = textureSample(t_textures, s_linear, input.uv0, i32(mat.tex_indices_a.y));
            roughness = clamp(roughness * mr.g, 0.04, 1.0);
            metallic = clamp(metallic * mr.b, 0.0, 1.0);
        }
        if (mat.tex_indices_a.z != 0xffffffffu) {
            let map_n = textureSample(t_textures, s_linear, input.uv0, i32(mat.tex_indices_a.z)).xyz * 2.0 - vec3<f32>(1.0);
            let scaled_n = normalize(vec3<f32>(map_n.xy * mat.clearcoat_normal_occ_trans.y, map_n.z));
            norm = normalize(t_ortho * scaled_n.x + bitangent * scaled_n.y + norm * scaled_n.z);
        }
        if (mat.tex_indices_a.w != 0xffffffffu) {
            let occ_s = textureSample(t_textures, s_linear, input.uv0, i32(mat.tex_indices_a.w)).r;
            occlusion = mix(1.0, occ_s, mat.clearcoat_normal_occ_trans.z);
        }
        emissive = mat.emissive_alpha_cutoff.xyz;
        if (mat.tex_indices_b.x != 0xffffffffu) {
            emissive *= textureSample(t_textures, s_linear, input.uv0, i32(mat.tex_indices_b.x)).rgb;
        }
        ior = mat.pbr_ior_specular.z;
        spec_factor = mat.pbr_ior_specular.w;
        spec_color = mat.specular_color_clearcoat.xyz;
        clearcoat = mat.specular_color_clearcoat.w;
        clearcoat_rough = clamp(mat.clearcoat_normal_occ_trans.x, 0.04, 1.0);
        transmission = mat.clearcoat_normal_occ_trans.w;
        atten_color = mat.volume_attenuation.xyz;
        thickness = mat.volume_attenuation.w;
        atten_dist = max(bitcast<f32>(mat.flags_volume.y), 1.0e-4);
        sheen_color = mat.sheen_color_roughness.xyz;
        sheen_rough = clamp(mat.sheen_color_roughness.w, 0.07, 1.0);
    }
    if (unlit) {
        let hdr_u = (base_rgba.rgb + emissive) * u_cam.sky_zenith_exposure.w;
        let mapped_u = select(aces_filmic(hdr_u), agx_tonemap(hdr_u), u_cam.tonemap_cluster_params.x > 0.5);
        return vec4<f32>(pow(mapped_u, vec3<f32>(1.0 / 2.2)), base_rgba.a);
    }
    let view_vec = u_cam.camera_pos.xyz - input.world_pos;
    let view_dist = length(view_vec);
    let view_dir = view_vec / max(view_dist, 1.0e-4);
    let sun_dir = normalize(u_cam.sun_dir_intensity.xyz);
    let n_dot_v = max(dot(norm, view_dir), 0.04);
    let n_dot_l = max(dot(norm, sun_dir), 0.0);
    let half_vec = normalize(sun_dir + view_dir);
    let n_dot_h = max(dot(norm, half_vec), 0.0);
    let v_dot_h = clamp(dot(view_dir, half_vec), 0.0, 1.0);
    let dielec_f0 = min(vec3<f32>(dielectric_f0_from_ior(ior)) * spec_color, vec3<f32>(1.0)) * spec_factor;
    let f0 = mix(dielec_f0, base_rgba.rgb, metallic);
    let alpha = roughness * roughness;
    let alpha2 = alpha * alpha;
    let fresnel = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - v_dot_h, 5.0);
    let ggx_d = distribution_ggx(n_dot_h, alpha2);
    let ggx_v = visibility_smith_ggx(n_dot_v, max(n_dot_l, 0.04), alpha);
    let brdf_uv = vec2<f32>(n_dot_v, roughness);
    let brdf_lut = textureSample(t_brdf_lut, s_linear, brdf_uv).rg;
    let e_ss = clamp(brdf_lut.x + brdf_lut.y, 0.05, 1.0);
    let multi_scatter = vec3<f32>(1.0) + f0 * ((1.0 / e_ss) - 1.0);
    let spec_direct = fresnel * (ggx_d * ggx_v) * multi_scatter;
    let diff_direct = base_rgba.rgb * ((1.0 - metallic) * (1.0 - transmission) / 3.14159265);
    let shadow_vis = sample_csm_vogel_16(input.world_pos, norm, sun_dir, view_dist);
    var color_hdr = (diff_direct + spec_direct) * u_cam.sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    if (clearcoat > 0.001) {
        let cc_alpha = clearcoat_rough * clearcoat_rough;
        let cc_f = 0.04 + 0.96 * pow(1.0 - v_dot_h, 5.0);
        let cc_d = distribution_ggx(n_dot_h, cc_alpha * cc_alpha);
        let cc_v = visibility_smith_ggx(n_dot_v, max(n_dot_l, 0.04), cc_alpha);
        color_hdr = color_hdr * (1.0 - clearcoat * cc_f) + vec3<f32>(cc_f * cc_d * cc_v * clearcoat) * u_cam.sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    }
    if (dot(sheen_color, sheen_color) > 1.0e-5) {
        let sh_d = distribution_charlie(sheen_rough, n_dot_h);
        let sh_v = visibility_ashikhmin(n_dot_v, max(n_dot_l, 0.04));
        color_hdr += sheen_color * (sh_d * sh_v) * u_cam.sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    }
    let light_count = min(u32(u_cam.tonemap_cluster_params.y), 16u);
    for (var l_idx: u32 = 0u; l_idx < light_count; l_idx = l_idx + 1u) {
        let pl = s_lights[l_idx];
        let to_l = pl.pos_inv_r2.xyz - input.world_pos;
        let d2 = max(dot(to_l, to_l), 1.0e-4);
        let ratio2 = d2 * pl.pos_inv_r2.w;
        if (ratio2 < 1.0) {
            let l_dir = to_l * inverseSqrt(d2);
            let nl = max(dot(norm, l_dir), 0.0);
            if (nl > 0.0) {
                var spot = 1.0;
                if (pl.dir_outer_cos.w > -1.5) {
                    let c_th = dot(-l_dir, pl.dir_outer_cos.xyz);
                    let raw_s = clamp((c_th - pl.dir_outer_cos.w) * pl.inv_cone_area.x, 0.0, 1.0);
                    spot = raw_s * raw_s;
                }
                let win = clamp(1.0 - ratio2 * ratio2, 0.0, 1.0);
                let atten = (win * win * spot) / d2;
                let h_l = normalize(l_dir + view_dir);
                let nh = max(dot(norm, h_l), 0.0);
                let vh = clamp(dot(view_dir, h_l), 0.0, 1.0);
                let f_l = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - vh, 5.0);
                let s_l = f_l * distribution_ggx(nh, alpha2) * visibility_smith_ggx(n_dot_v, nl, alpha);
                color_hdr += (diff_direct + s_l) * pl.radiance_radius.xyz * (nl * atten);
            }
        }
    }
    let sh_irrad = eval_sh9_diffuse(norm);
    let refl_dir = reflect(-view_dir, norm);
    let ibl_spec = textureSampleLevel(t_ibl_oct, s_linear, octahedral_encode_dir(refl_dir), roughness * 5.0).rgb;
    let ibl_diff = base_rgba.rgb * ((1.0 - metallic) * (1.0 - transmission)) * sh_irrad;
    let ibl_f = f0 * brdf_lut.x + vec3<f32>(brdf_lut.y);
    color_hdr += (ibl_diff + ibl_spec * ibl_f * multi_scatter) * occlusion;
    if (transmission > 0.001) {
        let refr_dir = refract(-view_dir, norm, 1.0 / max(ior, 1.0));
        let refr_env = textureSampleLevel(t_ibl_oct, s_linear, octahedral_encode_dir(refr_dir), roughness * 4.0).rgb;
        let sigma = -log(max(atten_color, vec3<f32>(1.0e-4))) / atten_dist;
        let beer = exp(-sigma * max(thickness, 0.01));
        color_hdr += refr_env * base_rgba.rgb * beer * (transmission * (1.0 - metallic));
    }
    let hdr_final = (color_hdr + emissive) * u_cam.sky_zenith_exposure.w;
    let mapped = select(aces_filmic(hdr_final), agx_tonemap(hdr_final), u_cam.tonemap_cluster_params.x > 0.5);
    let ldr = pow(mapped, vec3<f32>(1.0 / 2.2));
    return vec4<f32>(ldr, base_rgba.a);
}
"#;

/// Full Blender Principled BSDF + 4-Cascade Vogel-Disk CSM + Clustered Lights + SH9/Octahedral IBL + AgX/ACES Apple Metal (MSL) shader compatible with `MTLVertexDescriptor` (`float3 position`, `float3 normal`).
pub const MSL_ENGINE3D_PBR_SHADER: &str = r#"#include <metal_stdlib>
using namespace metal;

struct CameraUniforms {
    float4x4 view_proj;
    float4x4 prev_view_proj;
    float4 camera_pos;
    float4 sun_dir_intensity;
    float4 sun_color_ambient;
    float4 sky_horizon_fog;
    float4 sky_zenith_exposure;
    float4 csm_splits;
    float4x4 csm_matrices[4];
    float4 ibl_sh[9];
    float4 tonemap_cluster_params;
};

struct InstanceData {
    float4x4 model;
    float4 albedo_metallic;
    float4 emissive_roughness;
    uint4 material_skin_morph_flags;
};

struct VertexExtra {
    float4 tangent;
    float4 uv0_uv1;
    float4 color0;
};

struct GpuMaterialData {
    float4 base_color_factor;
    float4 emissive_alpha_cutoff;
    float4 pbr_ior_specular;
    float4 specular_color_clearcoat;
    float4 clearcoat_normal_occ_trans;
    float4 volume_attenuation;
    float4 sheen_color_roughness;
    uint4 tex_indices_a;
    uint4 tex_indices_b;
    uint4 flags_volume;
};

struct PackedLocalLight {
    float4 pos_inv_r2;
    float4 radiance_radius;
    float4 dir_outer_cos;
    float4 inv_cone_area;
};

struct VertexIn {
    float3 position [[attribute(0)]];
    float3 normal [[attribute(1)]];
};

struct VertexOut {
    float4 clip_pos [[position]];
    float3 world_pos;
    float3 world_normal;
    float4 world_tangent;
    float2 uv0;
    float4 color0;
    float4 albedo_metallic;
    float4 emissive_roughness;
    uint4 material_flags [[flat]];
};

static inline float3x3 cofactor_normal_matrix(float4x4 m) {
    float3 c0 = m[0].xyz;
    float3 c1 = m[1].xyz;
    float3 c2 = m[2].xyz;
    float3 n0 = cross(c1, c2);
    float3 n1 = cross(c2, c0);
    float3 n2 = cross(c0, c1);
    float det = dot(c0, n0);
    float inv_det = (abs(det) > 1.0e-8f) ? (1.0f / det) : 1.0f;
    return float3x3(n0 * inv_det, n1 * inv_det, n2 * inv_det);
}

static inline float dielectric_f0_from_ior(float ior) {
    float r = (ior - 1.0f) / max(ior + 1.0f, 1.0e-4f);
    return r * r;
}

static inline float distribution_ggx(float n_dot_h, float alpha2) {
    float denom = n_dot_h * n_dot_h * (alpha2 - 1.0f) + 1.0f;
    return alpha2 / max(3.14159265f * denom * denom, 1.0e-5f);
}

static inline float visibility_smith_ggx(float n_dot_v, float n_dot_l, float alpha) {
    float a2 = alpha * alpha;
    float ggx_v = n_dot_l * sqrt(n_dot_v * n_dot_v * (1.0f - a2) + a2);
    float ggx_l = n_dot_v * sqrt(n_dot_l * n_dot_l * (1.0f - a2) + a2);
    return 0.5f / max(ggx_v + ggx_l, 1.0e-5f);
}

static inline float distribution_charlie(float roughness, float n_dot_h) {
    float inv_r = 1.0f / max(roughness, 0.07f);
    float sin2_h = max(1.0f - n_dot_h * n_dot_h, 0.0078125f);
    return (2.0f + inv_r) * pow(sin2_h, inv_r * 0.5f) / 6.2831853f;
}

static inline float visibility_ashikhmin(float n_dot_v, float n_dot_l) {
    return 1.0f / max(4.0f * (n_dot_l + n_dot_v - n_dot_l * n_dot_v), 1.0e-4f);
}

static inline float2 octahedral_encode_dir(float3 dir) {
    float3 d = normalize(dir);
    float l1 = max(abs(d.x) + abs(d.y) + abs(d.z), 1.0e-6f);
    float ox = d.x / l1;
    float oz = d.z / l1;
    if (d.y < 0.0f) {
        float px = ox;
        float pz = oz;
        ox = (1.0f - abs(pz)) * (px >= 0.0f ? 1.0f : -1.0f);
        oz = (1.0f - abs(px)) * (pz >= 0.0f ? 1.0f : -1.0f);
    }
    return float2(ox * 0.5f + 0.5f, oz * 0.5f + 0.5f);
}

static inline float3 eval_sh9_diffuse(constant CameraUniforms& cam, float3 norm) {
    float x = norm.x;
    float y = norm.y;
    float z = norm.z;
    float3 irrad = cam.ibl_sh[0].xyz * 0.2820948f;
    irrad += cam.ibl_sh[1].xyz * (0.4886025f * y);
    irrad += cam.ibl_sh[2].xyz * (0.4886025f * z);
    irrad += cam.ibl_sh[3].xyz * (0.4886025f * x);
    irrad += cam.ibl_sh[4].xyz * (1.0925484f * x * y);
    irrad += cam.ibl_sh[5].xyz * (1.0925484f * y * z);
    irrad += cam.ibl_sh[6].xyz * (0.3153916f * (3.0f * z * z - 1.0f));
    irrad += cam.ibl_sh[7].xyz * (1.0925484f * x * z);
    irrad += cam.ibl_sh[8].xyz * (0.5462742f * (x * x - y * y));
    return max(irrad, float3(0.0f));
}

static inline float sample_csm_vogel_16(
    constant CameraUniforms& cam,
    depth2d_array<float> csm_shadow,
    sampler lin_sampler,
    float3 world_pos,
    float3 norm,
    float3 sun_dir,
    float view_depth
) {
    uint cascade = 3u;
    if (view_depth < cam.csm_splits.x) {
        cascade = 0u;
    } else if (view_depth < cam.csm_splits.y) {
        cascade = 1u;
    } else if (view_depth < cam.csm_splits.z) {
        cascade = 2u;
    }
    float3 biased_pos = world_pos + norm * (0.04f + 0.02f * float(cascade));
    float4 light_clip = cam.csm_matrices[cascade] * float4(biased_pos, 1.0f);
    float2 uv = light_clip.xy * 0.5f + float2(0.5f, 0.5f);
    float depth = light_clip.z;
    if (uv.x < 0.01f || uv.x > 0.99f || uv.y < 0.01f || uv.y > 0.99f || depth <= 0.0f || depth >= 1.0f) {
        return 1.0f;
    }
    float n_dot_l = clamp(dot(norm, sun_dir), 0.05f, 1.0f);
    float bias = clamp(0.0022f * (1.0f - n_dot_l) + 0.0012f, 0.001f, 0.008f);
    float angle = fract(sin(dot(world_pos, float3(12.9898f, 37.719f, 78.233f))) * 43758.547f) * 6.2831853f;
    float c_rot = cos(angle);
    float s_rot = sin(angle);
    float radius = 0.0025f;
    float vis = 0.0f;
    for (int tap = 0; tap < 16; ++tap) {
        float r_tap = sqrt((float(tap) + 0.5f) / 16.0f) * radius;
        float theta = float(tap) * 2.39996323f;
        float ox = cos(theta) * r_tap;
        float oy = sin(theta) * r_tap;
        float2 rot_uv = uv + float2(ox * c_rot - oy * s_rot, ox * s_rot + oy * c_rot);
        float sampled_d = csm_shadow.sample(lin_sampler, rot_uv, cascade);
        vis += (depth - bias <= sampled_d) ? 1.0f : 0.0f;
    }
    return 0.22f + 0.78f * (vis / 16.0f);
}

static inline float3 agx_contrast_poly(float3 x) {
    float3 x2 = x * x;
    float3 x4 = x2 * x2;
    return clamp(15.5f * x4 * x2 - 40.14f * x4 * x + 31.96f * x4 - 6.868f * x2 * x + 0.4298f * x2 + 0.1191f * x - 0.00232f, 0.0f, 1.0f);
}

static inline float3 agx_tonemap(float3 hdr) {
    float3x3 inset = float3x3(
        float3(0.84247906f, 0.04232824f, 0.04237565f),
        float3(0.07843360f, 0.87846864f, 0.07843360f),
        float3(0.07922375f, 0.07916613f, 0.87914297f)
    );
    float3x3 outset = float3x3(
        float3(1.19687900f, -0.05289685f, -0.05297163f),
        float3(-0.09802088f, 1.15190313f, -0.09804345f),
        float3(-0.09902975f, -0.09896118f, 1.15107367f)
    );
    float3 val = max(inset * max(hdr, float3(1.0e-6f)), float3(1.0e-6f));
    float3 log_val = clamp((log2(val) - float3(-12.47393f)) / float3(16.5f), 0.0f, 1.0f);
    return clamp(outset * agx_contrast_poly(log_val), 0.0f, 1.0f);
}

static inline float3 aces_filmic(float3 hdr) {
    float3 num = hdr * (2.51f * hdr + 0.03f);
    float3 den = hdr * (2.43f * hdr + 0.59f) + 0.14f;
    return clamp(num / max(den, float3(0.0001f)), 0.0f, 1.0f);
}

vertex VertexOut euv_3d_vertex(
    VertexIn in [[stage_in]],
    constant CameraUniforms& cam [[buffer(0)]],
    const device InstanceData* instances [[buffer(1)]],
    const device VertexExtra* extras [[buffer(3)]],
    uint vertex_id [[vertex_id]],
    uint instance_id [[instance_id]]
) {
    InstanceData inst = instances[instance_id];
    float3 world = (inst.model * float4(in.position, 1.0f)).xyz;
    float3x3 normal_mat = cofactor_normal_matrix(inst.model);
    float3 world_n = normalize(normal_mat * in.normal);
    VertexExtra extra = extras[vertex_id];
    float3 world_t = normalize((inst.model * float4(extra.tangent.xyz, 0.0f)).xyz);
    VertexOut out;
    out.clip_pos = cam.view_proj * float4(world, 1.0f);
    out.world_pos = world;
    out.world_normal = world_n;
    out.world_tangent = float4(world_t, extra.tangent.w);
    out.uv0 = extra.uv0_uv1.xy;
    out.color0 = extra.color0;
    out.albedo_metallic = inst.albedo_metallic;
    out.emissive_roughness = inst.emissive_roughness;
    out.material_flags = inst.material_skin_morph_flags;
    return out;
}

fragment float4 euv_3d_fragment(
    VertexOut in [[stage_in]],
    bool is_front [[front_facing]],
    constant CameraUniforms& cam [[buffer(0)]],
    const device GpuMaterialData* materials [[buffer(4)]],
    const device PackedLocalLight* local_lights [[buffer(5)]],
    texture2d_array<float> tex_pool [[texture(0)]],
    depth2d_array<float> csm_shadow [[texture(1)]],
    texture2d<float> ibl_oct [[texture(2)]],
    texture2d<float> brdf_lut_tex [[texture(3)]],
    sampler lin_sampler [[sampler(0)]]
) {
    bool use_principled = (in.material_flags.w & 2u) != 0u;
    float4 base_rgba = float4(in.albedo_metallic.xyz, 1.0f) * in.color0;
    float metallic = clamp(in.albedo_metallic.w, 0.0f, 1.0f);
    float roughness = clamp(in.emissive_roughness.w, 0.04f, 1.0f);
    float3 emissive = in.emissive_roughness.xyz;
    float ior = 1.5f;
    float spec_factor = 1.0f;
    float3 spec_color = float3(1.0f);
    float clearcoat = 0.0f;
    float clearcoat_rough = 0.04f;
    float3 sheen_color = float3(0.0f);
    float sheen_rough = 0.5f;
    float transmission = 0.0f;
    float thickness = 0.0f;
    float3 atten_color = float3(1.0f);
    float atten_dist = 1.0e6f;
    float occlusion = 1.0f;
    bool unlit = false;
    float3 norm = normalize(in.world_normal);
    if (!is_front) {
        norm = -norm;
    }
    float3 t_ortho = normalize(in.world_tangent.xyz - norm * dot(in.world_tangent.xyz, norm));
    float3 bitangent = cross(norm, t_ortho) * in.world_tangent.w;
    if (use_principled) {
        GpuMaterialData mat = materials[in.material_flags.x];
        base_rgba = mat.base_color_factor * in.color0;
        if (mat.tex_indices_a.x != 0xffffffffu) {
            base_rgba *= tex_pool.sample(lin_sampler, in.uv0, mat.tex_indices_a.x);
        }
        uint flags = mat.flags_volume.x;
        if ((flags & 1u) != 0u && base_rgba.a < mat.emissive_alpha_cutoff.w) {
            discard_fragment();
        }
        unlit = (flags & 8u) != 0u;
        metallic = clamp(mat.pbr_ior_specular.x, 0.0f, 1.0f);
        roughness = clamp(mat.pbr_ior_specular.y, 0.04f, 1.0f);
        if (mat.tex_indices_a.y != 0xffffffffu) {
            float4 mr = tex_pool.sample(lin_sampler, in.uv0, mat.tex_indices_a.y);
            roughness = clamp(roughness * mr.g, 0.04f, 1.0f);
            metallic = clamp(metallic * mr.b, 0.0f, 1.0f);
        }
        if (mat.tex_indices_a.z != 0xffffffffu) {
            float3 map_n = tex_pool.sample(lin_sampler, in.uv0, mat.tex_indices_a.z).xyz * 2.0f - float3(1.0f);
            float3 scaled_n = normalize(float3(map_n.xy * mat.clearcoat_normal_occ_trans.y, map_n.z));
            norm = normalize(t_ortho * scaled_n.x + bitangent * scaled_n.y + norm * scaled_n.z);
        }
        if (mat.tex_indices_a.w != 0xffffffffu) {
            float occ_s = tex_pool.sample(lin_sampler, in.uv0, mat.tex_indices_a.w).r;
            occlusion = mix(1.0f, occ_s, mat.clearcoat_normal_occ_trans.z);
        }
        emissive = mat.emissive_alpha_cutoff.xyz;
        if (mat.tex_indices_b.x != 0xffffffffu) {
            emissive *= tex_pool.sample(lin_sampler, in.uv0, mat.tex_indices_b.x).rgb;
        }
        ior = mat.pbr_ior_specular.z;
        spec_factor = mat.pbr_ior_specular.w;
        spec_color = mat.specular_color_clearcoat.xyz;
        clearcoat = mat.specular_color_clearcoat.w;
        clearcoat_rough = clamp(mat.clearcoat_normal_occ_trans.x, 0.04f, 1.0f);
        transmission = mat.clearcoat_normal_occ_trans.w;
        atten_color = mat.volume_attenuation.xyz;
        thickness = mat.volume_attenuation.w;
        atten_dist = max(as_type<float>(mat.flags_volume.y), 1.0e-4f);
        sheen_color = mat.sheen_color_roughness.xyz;
        sheen_rough = clamp(mat.sheen_color_roughness.w, 0.07f, 1.0f);
    }
    if (unlit) {
        float3 hdr_u = (base_rgba.rgb + emissive) * cam.sky_zenith_exposure.w;
        float3 mapped_u = (cam.tonemap_cluster_params.x > 0.5f) ? agx_tonemap(hdr_u) : aces_filmic(hdr_u);
        return float4(pow(mapped_u, float3(1.0f / 2.2f)), base_rgba.a);
    }
    float3 view_vec = cam.camera_pos.xyz - in.world_pos;
    float view_dist = length(view_vec);
    float3 view_dir = view_vec / max(view_dist, 1.0e-4f);
    float3 sun_dir = normalize(cam.sun_dir_intensity.xyz);
    float n_dot_v = max(dot(norm, view_dir), 0.04f);
    float n_dot_l = max(dot(norm, sun_dir), 0.0f);
    float3 half_vec = normalize(sun_dir + view_dir);
    float n_dot_h = max(dot(norm, half_vec), 0.0f);
    float v_dot_h = clamp(dot(view_dir, half_vec), 0.0f, 1.0f);
    float3 dielec_f0 = min(float3(dielectric_f0_from_ior(ior)) * spec_color, float3(1.0f)) * spec_factor;
    float3 f0 = mix(dielec_f0, base_rgba.rgb, metallic);
    float alpha = roughness * roughness;
    float alpha2 = alpha * alpha;
    float3 fresnel = f0 + (float3(1.0f) - f0) * pow(1.0f - v_dot_h, 5.0f);
    float ggx_d = distribution_ggx(n_dot_h, alpha2);
    float ggx_v = visibility_smith_ggx(n_dot_v, max(n_dot_l, 0.04f), alpha);
    float2 brdf_lut = brdf_lut_tex.sample(lin_sampler, float2(n_dot_v, roughness)).rg;
    float e_ss = clamp(brdf_lut.x + brdf_lut.y, 0.05f, 1.0f);
    float3 multi_scatter = float3(1.0f) + f0 * ((1.0f / e_ss) - 1.0f);
    float3 spec_direct = fresnel * (ggx_d * ggx_v) * multi_scatter;
    float3 diff_direct = base_rgba.rgb * ((1.0f - metallic) * (1.0f - transmission) / 3.14159265f);
    float shadow_vis = sample_csm_vogel_16(cam, csm_shadow, lin_sampler, in.world_pos, norm, sun_dir, view_dist);
    float3 color_hdr = (diff_direct + spec_direct) * cam.sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    if (clearcoat > 0.001f) {
        float cc_alpha = clearcoat_rough * clearcoat_rough;
        float cc_f = 0.04f + 0.96f * pow(1.0f - v_dot_h, 5.0f);
        float cc_d = distribution_ggx(n_dot_h, cc_alpha * cc_alpha);
        float cc_v = visibility_smith_ggx(n_dot_v, max(n_dot_l, 0.04f), cc_alpha);
        color_hdr = color_hdr * (1.0f - clearcoat * cc_f) + float3(cc_f * cc_d * cc_v * clearcoat) * cam.sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    }
    if (dot(sheen_color, sheen_color) > 1.0e-5f) {
        float sh_d = distribution_charlie(sheen_rough, n_dot_h);
        float sh_v = visibility_ashikhmin(n_dot_v, max(n_dot_l, 0.04f));
        color_hdr += sheen_color * (sh_d * sh_v) * cam.sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    }
    uint light_count = min(uint(cam.tonemap_cluster_params.y), 16u);
    for (uint l_idx = 0u; l_idx < light_count; ++l_idx) {
        PackedLocalLight pl = local_lights[l_idx];
        float3 to_l = pl.pos_inv_r2.xyz - in.world_pos;
        float d2 = max(dot(to_l, to_l), 1.0e-4f);
        float ratio2 = d2 * pl.pos_inv_r2.w;
        if (ratio2 < 1.0f) {
            float3 l_dir = to_l * rsqrt(d2);
            float nl = max(dot(norm, l_dir), 0.0f);
            if (nl > 0.0f) {
                float spot = 1.0f;
                if (pl.dir_outer_cos.w > -1.5f) {
                    float c_th = dot(-l_dir, pl.dir_outer_cos.xyz);
                    float raw_s = clamp((c_th - pl.dir_outer_cos.w) * pl.inv_cone_area.x, 0.0f, 1.0f);
                    spot = raw_s * raw_s;
                }
                float win = clamp(1.0f - ratio2 * ratio2, 0.0f, 1.0f);
                float atten = (win * win * spot) / d2;
                float3 h_l = normalize(l_dir + view_dir);
                float nh = max(dot(norm, h_l), 0.0f);
                float vh = clamp(dot(view_dir, h_l), 0.0f, 1.0f);
                float3 f_l = f0 + (float3(1.0f) - f0) * pow(1.0f - vh, 5.0f);
                float3 s_l = f_l * distribution_ggx(nh, alpha2) * visibility_smith_ggx(n_dot_v, nl, alpha);
                color_hdr += (diff_direct + s_l) * pl.radiance_radius.xyz * (nl * atten);
            }
        }
    }
    float3 sh_irrad = eval_sh9_diffuse(cam, norm);
    float3 refl_dir = reflect(-view_dir, norm);
    float3 ibl_spec = ibl_oct.sample(lin_sampler, octahedral_encode_dir(refl_dir), level(roughness * 5.0f)).rgb;
    float3 ibl_diff = base_rgba.rgb * ((1.0f - metallic) * (1.0f - transmission)) * sh_irrad;
    float3 ibl_f = f0 * brdf_lut.x + float3(brdf_lut.y);
    color_hdr += (ibl_diff + ibl_spec * ibl_f * multi_scatter) * occlusion;
    if (transmission > 0.001f) {
        float3 refr_dir = refract(-view_dir, norm, 1.0f / max(ior, 1.0f));
        float3 refr_env = ibl_oct.sample(lin_sampler, octahedral_encode_dir(refr_dir), level(roughness * 4.0f)).rgb;
        float3 sigma = -log(max(atten_color, float3(1.0e-4f))) / atten_dist;
        float3 beer = exp(-sigma * max(thickness, 0.01f));
        color_hdr += refr_env * base_rgba.rgb * beer * (transmission * (1.0f - metallic));
    }
    float3 hdr_final = (color_hdr + emissive) * cam.sky_zenith_exposure.w;
    float3 mapped = (cam.tonemap_cluster_params.x > 0.5f) ? agx_tonemap(hdr_final) : aces_filmic(hdr_final);
    float3 ldr = pow(mapped, float3(1.0f / 2.2f));
    return float4(ldr, base_rgba.a);
}
"#;

/// Full Blender Principled BSDF GLSL ES 3.0 instanced vertex shader with exact cofactor normal matrix and TBN frame for WebGL2, Android, and HarmonyOS targets.
pub const GLSL_ES3_ENGINE3D_VERTEX_SHADER: &str = r#"#version 300 es
precision highp float;
layout(location = 0) in vec3 a_position;
layout(location = 1) in vec3 a_normal;
layout(location = 2) in vec4 a_tangent;
layout(location = 3) in vec2 a_uv0;
layout(location = 4) in vec4 a_color0;
layout(location = 5) in mat4 a_model;
layout(location = 9) in vec4 a_albedo_metallic;
layout(location = 10) in vec4 a_emissive_roughness;
uniform mat4 u_view_proj;
out vec3 v_world_pos;
out vec3 v_world_normal;
out vec4 v_world_tangent;
out vec2 v_uv0;
out vec4 v_color0;
out vec4 v_albedo_metallic;
out vec4 v_emissive_roughness;
mat3 cofactor_normal_matrix(mat4 m) {
    vec3 c0 = m[0].xyz;
    vec3 c1 = m[1].xyz;
    vec3 c2 = m[2].xyz;
    vec3 n0 = cross(c1, c2);
    vec3 n1 = cross(c2, c0);
    vec3 n2 = cross(c0, c1);
    float det = dot(c0, n0);
    float inv_det = abs(det) > 1.0e-8 ? (1.0 / det) : 1.0;
    return mat3(n0 * inv_det, n1 * inv_det, n2 * inv_det);
}
void main() {
    vec4 world = a_model * vec4(a_position, 1.0);
    gl_Position = u_view_proj * world;
    v_world_pos = world.xyz;
    v_world_normal = normalize(cofactor_normal_matrix(a_model) * a_normal);
    v_world_tangent = vec4(normalize((a_model * vec4(a_tangent.xyz, 0.0)).xyz), a_tangent.w);
    v_uv0 = a_uv0;
    v_color0 = a_color0;
    v_albedo_metallic = a_albedo_metallic;
    v_emissive_roughness = a_emissive_roughness;
}
"#;

/// Full Blender Principled BSDF + 4-Cascade Vogel-Disk CSM + Clustered Lights + SH9/Octahedral IBL + AgX/ACES GLSL ES 3.0 fragment shader for WebGL2, Android, and HarmonyOS targets.
pub const GLSL_ES3_ENGINE3D_FRAGMENT_SHADER: &str = r#"#version 300 es
precision highp float;
precision highp sampler2DArray;
in vec3 v_world_pos;
in vec3 v_world_normal;
in vec4 v_world_tangent;
in vec2 v_uv0;
in vec4 v_color0;
in vec4 v_albedo_metallic;
in vec4 v_emissive_roughness;
uniform vec3 u_camera_pos;
uniform vec3 u_sun_dir;
uniform vec3 u_sun_color;
uniform vec3 u_sky_horizon;
uniform vec3 u_sky_zenith;
uniform float u_exposure;
uniform vec4 u_pbr_ior_spec_cc;
uniform vec4 u_cc_rough_nscale_occ_trans;
uniform vec4 u_sheen_color_rough;
uniform vec4 u_volume_atten_thick;
uniform vec4 u_alpha_flags;
uniform vec4 u_csm_splits;
uniform mat4 u_csm_matrices[4];
uniform vec3 u_ibl_sh[9];
uniform vec4 u_local_lights_pos[16];
uniform vec4 u_local_lights_rad[16];
uniform vec4 u_local_lights_dir[16];
uniform int u_local_light_count;
uniform int u_use_agx;
uniform sampler2D u_base_color_tex;
uniform sampler2D u_normal_tex;
uniform sampler2D u_mr_tex;
uniform sampler2D u_ibl_oct_tex;
uniform sampler2D u_brdf_lut_tex;
uniform sampler2DArray u_csm_shadow_tex;
out vec4 out_color;
float dielectric_f0_from_ior(float ior) {
    float r = (ior - 1.0) / max(ior + 1.0, 1.0e-4);
    return r * r;
}
float distribution_ggx(float n_dot_h, float alpha2) {
    float denom = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
    return alpha2 / max(3.14159265 * denom * denom, 1.0e-5);
}
float visibility_smith_ggx(float n_dot_v, float n_dot_l, float alpha) {
    float a2 = alpha * alpha;
    float ggx_v = n_dot_l * sqrt(n_dot_v * n_dot_v * (1.0 - a2) + a2);
    float ggx_l = n_dot_v * sqrt(n_dot_l * n_dot_l * (1.0 - a2) + a2);
    return 0.5 / max(ggx_v + ggx_l, 1.0e-5);
}
float distribution_charlie(float roughness, float n_dot_h) {
    float inv_r = 1.0 / max(roughness, 0.07);
    float sin2_h = max(1.0 - n_dot_h * n_dot_h, 0.0078125);
    return (2.0 + inv_r) * pow(sin2_h, inv_r * 0.5) / 6.2831853;
}
float visibility_ashikhmin(float n_dot_v, float n_dot_l) {
    return 1.0 / max(4.0 * (n_dot_l + n_dot_v - n_dot_l * n_dot_v), 1.0e-4);
}
vec2 octahedral_encode_dir(vec3 dir) {
    vec3 d = normalize(dir);
    float l1 = max(abs(d.x) + abs(d.y) + abs(d.z), 1.0e-6);
    float ox = d.x / l1;
    float oz = d.z / l1;
    if (d.y < 0.0) {
        float px = ox;
        float pz = oz;
        ox = (1.0 - abs(pz)) * (px >= 0.0 ? 1.0 : -1.0);
        oz = (1.0 - abs(px)) * (pz >= 0.0 ? 1.0 : -1.0);
    }
    return vec2(ox * 0.5 + 0.5, oz * 0.5 + 0.5);
}
vec3 eval_sh9_diffuse(vec3 norm) {
    vec3 irrad = u_ibl_sh[0] * 0.2820948;
    irrad += u_ibl_sh[1] * (0.4886025 * norm.y);
    irrad += u_ibl_sh[2] * (0.4886025 * norm.z);
    irrad += u_ibl_sh[3] * (0.4886025 * norm.x);
    irrad += u_ibl_sh[4] * (1.0925484 * norm.x * norm.y);
    irrad += u_ibl_sh[5] * (1.0925484 * norm.y * norm.z);
    irrad += u_ibl_sh[6] * (0.3153916 * (3.0 * norm.z * norm.z - 1.0));
    irrad += u_ibl_sh[7] * (1.0925484 * norm.x * norm.z);
    irrad += u_ibl_sh[8] * (0.5462742 * (norm.x * norm.x - norm.y * norm.y));
    return max(irrad, vec3(0.0));
}
float sample_csm_vogel_16(vec3 world_pos, vec3 norm, vec3 sun_dir, float view_depth) {
    int cascade = 3;
    if (view_depth < u_csm_splits.x) { cascade = 0; }
    else if (view_depth < u_csm_splits.y) { cascade = 1; }
    else if (view_depth < u_csm_splits.z) { cascade = 2; }
    vec3 biased_pos = world_pos + norm * (0.04 + 0.02 * float(cascade));
    vec4 light_clip = u_csm_matrices[cascade] * vec4(biased_pos, 1.0);
    vec2 uv = light_clip.xy * 0.5 + vec2(0.5);
    float depth = light_clip.z;
    if (uv.x < 0.01 || uv.x > 0.99 || uv.y < 0.01 || uv.y > 0.99 || depth <= 0.0 || depth >= 1.0) {
        return 1.0;
    }
    float n_dot_l = clamp(dot(norm, sun_dir), 0.05, 1.0);
    float bias = clamp(0.0022 * (1.0 - n_dot_l) + 0.0012, 0.001, 0.008);
    float angle = fract(sin(dot(world_pos, vec3(12.9898, 37.719, 78.233))) * 43758.547) * 6.2831853;
    float c_rot = cos(angle);
    float s_rot = sin(angle);
    float vis = 0.0;
    for (int tap = 0; tap < 16; ++tap) {
        float r_tap = sqrt((float(tap) + 0.5) / 16.0) * 0.0025;
        float theta = float(tap) * 2.39996323;
        float ox = cos(theta) * r_tap;
        float oy = sin(theta) * r_tap;
        vec2 rot_uv = uv + vec2(ox * c_rot - oy * s_rot, ox * s_rot + oy * c_rot);
        float sampled_d = texture(u_csm_shadow_tex, vec3(rot_uv, float(cascade))).r;
        vis += (depth - bias <= sampled_d) ? 1.0 : 0.0;
    }
    return 0.22 + 0.78 * (vis / 16.0);
}
vec3 agx_contrast_poly(vec3 x) {
    vec3 x2 = x * x;
    vec3 x4 = x2 * x2;
    return clamp(15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232, 0.0, 1.0);
}
vec3 agx_tonemap(vec3 hdr) {
    mat3 inset = mat3(
        vec3(0.84247906, 0.04232824, 0.04237565),
        vec3(0.07843360, 0.87846864, 0.07843360),
        vec3(0.07922375, 0.07916613, 0.87914297)
    );
    mat3 outset = mat3(
        vec3(1.19687900, -0.05289685, -0.05297163),
        vec3(-0.09802088, 1.15190313, -0.09804345),
        vec3(-0.09902975, -0.09896118, 1.15107367)
    );
    vec3 val = max(inset * max(hdr, vec3(1.0e-6)), vec3(1.0e-6));
    vec3 log_val = clamp((log2(val) - vec3(-12.47393)) / vec3(16.5), 0.0, 1.0);
    return clamp(outset * agx_contrast_poly(log_val), 0.0, 1.0);
}
vec3 aces_filmic(vec3 hdr) {
    vec3 num = hdr * (2.51 * hdr + 0.03);
    vec3 den = hdr * (2.43 * hdr + 0.59) + 0.14;
    return clamp(num / max(den, vec3(0.0001)), 0.0, 1.0);
}
void main() {
    vec4 base_rgba = vec4(v_albedo_metallic.rgb, 1.0) * v_color0;
    if (u_alpha_flags.z > 0.5) {
        base_rgba *= texture(u_base_color_tex, v_uv0);
    }
    if (u_alpha_flags.y > 0.5 && base_rgba.a < u_alpha_flags.x) {
        discard;
    }
    if (u_alpha_flags.w > 0.5) {
        vec3 hdr_u = (base_rgba.rgb + v_emissive_roughness.rgb) * u_exposure;
        vec3 mapped_u = u_use_agx != 0 ? agx_tonemap(hdr_u) : aces_filmic(hdr_u);
        out_color = vec4(pow(mapped_u, vec3(1.0 / 2.2)), base_rgba.a);
        return;
    }
    vec3 norm = normalize(v_world_normal);
    if (!gl_FrontFacing) {
        norm = -norm;
    }
    vec3 t_ortho = normalize(v_world_tangent.xyz - norm * dot(v_world_tangent.xyz, norm));
    vec3 bitangent = cross(norm, t_ortho) * v_world_tangent.w;
    if (u_cc_rough_nscale_occ_trans.y > 0.001) {
        vec3 map_n = texture(u_normal_tex, v_uv0).xyz * 2.0 - vec3(1.0);
        vec3 scaled_n = normalize(vec3(map_n.xy * u_cc_rough_nscale_occ_trans.y, map_n.z));
        norm = normalize(t_ortho * scaled_n.x + bitangent * scaled_n.y + norm * scaled_n.z);
    }
    vec4 mr_tex = texture(u_mr_tex, v_uv0);
    float metallic = clamp(v_albedo_metallic.a * mr_tex.b, 0.0, 1.0);
    float roughness = clamp(v_emissive_roughness.a * mr_tex.g, 0.04, 1.0);
    vec3 view_vec = u_camera_pos - v_world_pos;
    float view_dist = length(view_vec);
    vec3 view_dir = view_vec / max(view_dist, 1.0e-4);
    vec3 sun_dir = normalize(u_sun_dir);
    vec3 half_vec = normalize(sun_dir + view_dir);
    float n_dot_l = max(dot(norm, sun_dir), 0.0);
    float n_dot_v = max(dot(norm, view_dir), 0.04);
    float n_dot_h = max(dot(norm, half_vec), 0.0);
    float v_dot_h = clamp(dot(view_dir, half_vec), 0.0, 1.0);
    float ior = max(u_pbr_ior_spec_cc.x, 1.0);
    float spec_factor = u_pbr_ior_spec_cc.y;
    float clearcoat = u_pbr_ior_spec_cc.z;
    float clearcoat_rough = clamp(u_cc_rough_nscale_occ_trans.x, 0.04, 1.0);
    float transmission = u_cc_rough_nscale_occ_trans.w;
    vec3 f0 = mix(vec3(dielectric_f0_from_ior(ior) * spec_factor), base_rgba.rgb, metallic);
    float alpha = roughness * roughness;
    float alpha2 = alpha * alpha;
    vec3 fresnel = f0 + (vec3(1.0) - f0) * pow(1.0 - v_dot_h, 5.0);
    vec2 brdf_lut = texture(u_brdf_lut_tex, vec2(n_dot_v, roughness)).rg;
    float e_ss = clamp(brdf_lut.x + brdf_lut.y, 0.05, 1.0);
    vec3 multi_scatter = vec3(1.0) + f0 * ((1.0 / e_ss) - 1.0);
    vec3 spec = fresnel * distribution_ggx(n_dot_h, alpha2) * visibility_smith_ggx(n_dot_v, max(n_dot_l, 0.04), alpha) * multi_scatter;
    vec3 diff = base_rgba.rgb * ((1.0 - metallic) * (1.0 - transmission) / 3.14159265);
    float shadow_vis = sample_csm_vogel_16(v_world_pos, norm, sun_dir, view_dist);
    vec3 color_hdr = (diff + spec) * u_sun_color * (n_dot_l * shadow_vis);
    if (clearcoat > 0.001) {
        float cc_alpha = clearcoat_rough * clearcoat_rough;
        float cc_f = 0.04 + 0.96 * pow(1.0 - v_dot_h, 5.0);
        float cc_spec = cc_f * distribution_ggx(n_dot_h, cc_alpha * cc_alpha) * visibility_smith_ggx(n_dot_v, max(n_dot_l, 0.04), cc_alpha);
        color_hdr = color_hdr * (1.0 - clearcoat * cc_f) + vec3(cc_spec * clearcoat) * u_sun_color * (n_dot_l * shadow_vis);
    }
    if (dot(u_sheen_color_rough.rgb, u_sheen_color_rough.rgb) > 1.0e-5) {
        float sh_d = distribution_charlie(u_sheen_color_rough.w, n_dot_h);
        float sh_v = visibility_ashikhmin(n_dot_v, max(n_dot_l, 0.04));
        color_hdr += u_sheen_color_rough.rgb * (sh_d * sh_v) * u_sun_color * (n_dot_l * shadow_vis);
    }
    for (int l_idx = 0; l_idx < 16; ++l_idx) {
        if (l_idx >= u_local_light_count) { break; }
        vec3 to_l = u_local_lights_pos[l_idx].xyz - v_world_pos;
        float d2 = max(dot(to_l, to_l), 1.0e-4);
        float ratio2 = d2 * u_local_lights_pos[l_idx].w;
        if (ratio2 < 1.0) {
            vec3 l_dir = to_l * inversesqrt(d2);
            float nl = max(dot(norm, l_dir), 0.0);
            if (nl > 0.0) {
                float win = clamp(1.0 - ratio2 * ratio2, 0.0, 1.0);
                float atten = (win * win) / d2;
                vec3 h_l = normalize(l_dir + view_dir);
                float nh = max(dot(norm, h_l), 0.0);
                float vh = clamp(dot(view_dir, h_l), 0.0, 1.0);
                vec3 f_l = f0 + (vec3(1.0) - f0) * pow(1.0 - vh, 5.0);
                vec3 s_l = f_l * distribution_ggx(nh, alpha2) * visibility_smith_ggx(n_dot_v, nl, alpha);
                color_hdr += (diff + s_l) * u_local_lights_rad[l_idx].rgb * (nl * atten);
            }
        }
    }
    vec3 sh_irrad = eval_sh9_diffuse(norm);
    vec3 refl_dir = reflect(-view_dir, norm);
    vec3 ibl_spec = textureLod(u_ibl_oct_tex, octahedral_encode_dir(refl_dir), roughness * 5.0).rgb;
    vec3 ibl_f = f0 * brdf_lut.x + vec3(brdf_lut.y);
    color_hdr += base_rgba.rgb * ((1.0 - metallic) * (1.0 - transmission)) * sh_irrad + ibl_spec * ibl_f * multi_scatter;
    if (transmission > 0.001) {
        vec3 refr_dir = refract(-view_dir, norm, 1.0 / ior);
        vec3 refr_env = textureLod(u_ibl_oct_tex, octahedral_encode_dir(refr_dir), roughness * 4.0).rgb;
        vec3 sigma = -log(max(u_volume_atten_thick.rgb, vec3(1.0e-4))) / max(u_pbr_ior_spec_cc.w, 1.0e-4);
        vec3 beer = exp(-sigma * max(u_volume_atten_thick.w, 0.01));
        color_hdr += refr_env * base_rgba.rgb * beer * (transmission * (1.0 - metallic));
    }
    vec3 hdr = (color_hdr + v_emissive_roughness.rgb) * u_exposure;
    vec3 mapped = u_use_agx != 0 ? agx_tonemap(hdr) : aces_filmic(hdr);
    vec3 ldr = pow(mapped, vec3(1.0 / 2.2));
    out_color = vec4(ldr, base_rgba.a);
}
"#;

/// Full Blender Principled BSDF + 4-Cascade Vogel-Disk CSM + Clustered Lights + SH9/Octahedral IBL + AgX/ACES HLSL Shader Model 6.0 shader for Windows Direct3D 12 targets.
pub const HLSL_ENGINE3D_PBR_SHADER: &str = r#"cbuffer CameraUniforms : register(b0) {
    float4x4 g_view_proj;
    float4x4 g_prev_view_proj;
    float4 g_camera_pos;
    float4 g_sun_dir_intensity;
    float4 g_sun_color_ambient;
    float4 g_sky_horizon_fog;
    float4 g_sky_zenith_exposure;
    float4 g_csm_splits;
    float4x4 g_csm_matrices[4];
    float4 g_ibl_sh[9];
    float4 g_tonemap_cluster_params;
};

struct InstanceData {
    float4x4 model;
    float4 albedo_metallic;
    float4 emissive_roughness;
    uint4 material_skin_morph_flags;
};

struct GpuMaterialData {
    float4 base_color_factor;
    float4 emissive_alpha_cutoff;
    float4 pbr_ior_specular;
    float4 specular_color_clearcoat;
    float4 clearcoat_normal_occ_trans;
    float4 volume_attenuation;
    float4 sheen_color_roughness;
    uint4 tex_indices_a;
    uint4 tex_indices_b;
    uint4 flags_volume;
};

struct PackedLocalLight {
    float4 pos_inv_r2;
    float4 radiance_radius;
    float4 dir_outer_cos;
    float4 inv_cone_area;
};

StructuredBuffer<InstanceData> g_instances : register(t0);
StructuredBuffer<GpuMaterialData> g_materials : register(t1);
StructuredBuffer<PackedLocalLight> g_lights : register(t2);
Texture2DArray<float4> g_textures : register(t3);
Texture2DArray<float> g_csm_shadow : register(t4);
Texture2D<float4> g_ibl_oct : register(t5);
Texture2D<float2> g_brdf_lut : register(t6);
SamplerState g_linear_sampler : register(s0);

struct VertexIn {
    float3 position : POSITION;
    float3 normal : NORMAL;
    float4 tangent : TANGENT;
    float2 uv0 : TEXCOORD0;
    float4 color0 : COLOR0;
    uint instance_id : SV_InstanceID;
};

struct VertexOut {
    float4 clip_pos : SV_POSITION;
    float3 world_pos : TEXCOORD0;
    float3 world_normal : TEXCOORD1;
    float4 world_tangent : TEXCOORD2;
    float2 uv0 : TEXCOORD3;
    float4 color0 : TEXCOORD4;
    float4 albedo_metallic : TEXCOORD5;
    float4 emissive_roughness : TEXCOORD6;
    nointerpolation uint4 material_flags : TEXCOORD7;
};

float3x3 cofactor_normal_matrix(float4x4 m) {
    float3 c0 = float3(m._11, m._21, m._31);
    float3 c1 = float3(m._12, m._22, m._32);
    float3 c2 = float3(m._13, m._23, m._33);
    float3 n0 = cross(c1, c2);
    float3 n1 = cross(c2, c0);
    float3 n2 = cross(c0, c1);
    float det = dot(c0, n0);
    float inv_det = (abs(det) > 1.0e-8) ? (1.0 / det) : 1.0;
    return float3x3(n0 * inv_det, n1 * inv_det, n2 * inv_det);
}

VertexOut vs_main(VertexIn input) {
    InstanceData inst = g_instances[input.instance_id];
    float4 world = mul(inst.model, float4(input.position, 1.0));
    float3x3 normal_mat = cofactor_normal_matrix(inst.model);
    VertexOut output;
    output.clip_pos = mul(g_view_proj, world);
    output.world_pos = world.xyz;
    output.world_normal = normalize(mul(input.normal, normal_mat));
    output.world_tangent = float4(normalize(mul((float3x3)inst.model, input.tangent.xyz)), input.tangent.w);
    output.uv0 = input.uv0;
    output.color0 = input.color0;
    output.albedo_metallic = inst.albedo_metallic;
    output.emissive_roughness = inst.emissive_roughness;
    output.material_flags = inst.material_skin_morph_flags;
    return output;
}

float dielectric_f0_from_ior(float ior) {
    float r = (ior - 1.0) / max(ior + 1.0, 1.0e-4);
    return r * r;
}

float distribution_ggx(float n_dot_h, float alpha2) {
    float denom = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
    return alpha2 / max(3.14159265 * denom * denom, 1.0e-5);
}

float visibility_smith_ggx(float n_dot_v, float n_dot_l, float alpha) {
    float a2 = alpha * alpha;
    float ggx_v = n_dot_l * sqrt(n_dot_v * n_dot_v * (1.0 - a2) + a2);
    float ggx_l = n_dot_v * sqrt(n_dot_l * n_dot_l * (1.0 - a2) + a2);
    return 0.5 / max(ggx_v + ggx_l, 1.0e-5);
}

float distribution_charlie(float roughness, float n_dot_h) {
    float inv_r = 1.0 / max(roughness, 0.07);
    float sin2_h = max(1.0 - n_dot_h * n_dot_h, 0.0078125);
    return (2.0 + inv_r) * pow(sin2_h, inv_r * 0.5) / 6.2831853;
}

float visibility_ashikhmin(float n_dot_v, float n_dot_l) {
    return 1.0 / max(4.0 * (n_dot_l + n_dot_v - n_dot_l * n_dot_v), 1.0e-4);
}

float2 octahedral_encode_dir(float3 dir) {
    float3 d = normalize(dir);
    float l1 = max(abs(d.x) + abs(d.y) + abs(d.z), 1.0e-6);
    float ox = d.x / l1;
    float oz = d.z / l1;
    if (d.y < 0.0) {
        float px = ox;
        float pz = oz;
        ox = (1.0 - abs(pz)) * (px >= 0.0 ? 1.0 : -1.0);
        oz = (1.0 - abs(px)) * (pz >= 0.0 ? 1.0 : -1.0);
    }
    return float2(ox * 0.5 + 0.5, oz * 0.5 + 0.5);
}

float3 eval_sh9_diffuse(float3 norm) {
    float3 irrad = g_ibl_sh[0].xyz * 0.2820948;
    irrad += g_ibl_sh[1].xyz * (0.4886025 * norm.y);
    irrad += g_ibl_sh[2].xyz * (0.4886025 * norm.z);
    irrad += g_ibl_sh[3].xyz * (0.4886025 * norm.x);
    irrad += g_ibl_sh[4].xyz * (1.0925484 * norm.x * norm.y);
    irrad += g_ibl_sh[5].xyz * (1.0925484 * norm.y * norm.z);
    irrad += g_ibl_sh[6].xyz * (0.3153916 * (3.0 * norm.z * norm.z - 1.0));
    irrad += g_ibl_sh[7].xyz * (1.0925484 * norm.x * norm.z);
    irrad += g_ibl_sh[8].xyz * (0.5462742 * (norm.x * norm.x - norm.y * norm.y));
    return max(irrad, float3(0.0, 0.0, 0.0));
}

float sample_csm_vogel_16(float3 world_pos, float3 norm, float3 sun_dir, float view_depth) {
    int cascade = 3;
    if (view_depth < g_csm_splits.x) { cascade = 0; }
    else if (view_depth < g_csm_splits.y) { cascade = 1; }
    else if (view_depth < g_csm_splits.z) { cascade = 2; }
    float3 biased_pos = world_pos + norm * (0.04 + 0.02 * float(cascade));
    float4 light_clip = mul(g_csm_matrices[cascade], float4(biased_pos, 1.0));
    float2 uv = light_clip.xy * 0.5 + float2(0.5, 0.5);
    float depth = light_clip.z;
    if (uv.x < 0.01 || uv.x > 0.99 || uv.y < 0.01 || uv.y > 0.99 || depth <= 0.0 || depth >= 1.0) {
        return 1.0;
    }
    float n_dot_l = clamp(dot(norm, sun_dir), 0.05, 1.0);
    float bias = clamp(0.0022 * (1.0 - n_dot_l) + 0.0012, 0.001, 0.008);
    float angle = frac(sin(dot(world_pos, float3(12.9898, 37.719, 78.233))) * 43758.547) * 6.2831853;
    float c_rot = cos(angle);
    float s_rot = sin(angle);
    float vis = 0.0;
    [unroll]
    for (int tap = 0; tap < 16; ++tap) {
        float r_tap = sqrt((float(tap) + 0.5) / 16.0) * 0.0025;
        float theta = float(tap) * 2.39996323;
        float ox = cos(theta) * r_tap;
        float oy = sin(theta) * r_tap;
        float2 rot_uv = uv + float2(ox * c_rot - oy * s_rot, ox * s_rot + oy * c_rot);
        float sampled_d = g_csm_shadow.SampleLevel(g_linear_sampler, float3(rot_uv, float(cascade)), 0.0);
        vis += (depth - bias <= sampled_d) ? 1.0 : 0.0;
    }
    return 0.22 + 0.78 * (vis / 16.0);
}

float3 agx_contrast_poly(float3 x) {
    float3 x2 = x * x;
    float3 x4 = x2 * x2;
    return saturate(15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232);
}

float3 agx_tonemap(float3 hdr) {
    float3x3 inset = float3x3(
        0.84247906, 0.07843360, 0.07922375,
        0.04232824, 0.87846864, 0.07916613,
        0.04237565, 0.07843360, 0.87914297
    );
    float3x3 outset = float3x3(
        1.19687900, -0.09802088, -0.09902975,
        -0.05289685, 1.15190313, -0.09896118,
        -0.05297163, -0.09804345, 1.15107367
    );
    float3 val = max(mul(inset, max(hdr, float3(1.0e-6, 1.0e-6, 1.0e-6))), float3(1.0e-6, 1.0e-6, 1.0e-6));
    float3 log_val = saturate((log2(val) - float3(-12.47393, -12.47393, -12.47393)) / 16.5);
    return saturate(mul(outset, agx_contrast_poly(log_val)));
}

float3 aces_filmic(float3 hdr) {
    float3 num = hdr * (2.51 * hdr + 0.03);
    float3 den = hdr * (2.43 * hdr + 0.59) + 0.14;
    return saturate(num / max(den, float3(0.0001, 0.0001, 0.0001)));
}

float4 ps_main(VertexOut input, bool is_front : SV_IsFrontFace) : SV_TARGET {
    bool use_principled = (input.material_flags.w & 2u) != 0u;
    float4 base_rgba = float4(input.albedo_metallic.xyz, 1.0) * input.color0;
    float metallic = saturate(input.albedo_metallic.w);
    float roughness = clamp(input.emissive_roughness.w, 0.04, 1.0);
    float3 emissive = input.emissive_roughness.xyz;
    float ior = 1.5;
    float spec_factor = 1.0;
    float3 spec_color = float3(1.0, 1.0, 1.0);
    float clearcoat = 0.0;
    float clearcoat_rough = 0.04;
    float3 sheen_color = float3(0.0, 0.0, 0.0);
    float sheen_rough = 0.5;
    float transmission = 0.0;
    float thickness = 0.0;
    float3 atten_color = float3(1.0, 1.0, 1.0);
    float atten_dist = 1.0e6;
    float occlusion = 1.0;
    bool unlit = false;
    float3 norm = normalize(input.world_normal);
    if (!is_front) { norm = -norm; }
    float3 t_ortho = normalize(input.world_tangent.xyz - norm * dot(input.world_tangent.xyz, norm));
    float3 bitangent = cross(norm, t_ortho) * input.world_tangent.w;
    if (use_principled) {
        GpuMaterialData mat = g_materials[input.material_flags.x];
        base_rgba = mat.base_color_factor * input.color0;
        if (mat.tex_indices_a.x != 0xffffffffu) {
            base_rgba *= g_textures.Sample(g_linear_sampler, float3(input.uv0, float(mat.tex_indices_a.x)));
        }
        uint flags = mat.flags_volume.x;
        if ((flags & 1u) != 0u && base_rgba.a < mat.emissive_alpha_cutoff.w) {
            discard;
        }
        unlit = (flags & 8u) != 0u;
        metallic = saturate(mat.pbr_ior_specular.x);
        roughness = clamp(mat.pbr_ior_specular.y, 0.04, 1.0);
        if (mat.tex_indices_a.y != 0xffffffffu) {
            float4 mr = g_textures.Sample(g_linear_sampler, float3(input.uv0, float(mat.tex_indices_a.y)));
            roughness = clamp(roughness * mr.g, 0.04, 1.0);
            metallic = saturate(metallic * mr.b);
        }
        if (mat.tex_indices_a.z != 0xffffffffu) {
            float3 map_n = g_textures.Sample(g_linear_sampler, float3(input.uv0, float(mat.tex_indices_a.z))).xyz * 2.0 - 1.0;
            float3 scaled_n = normalize(float3(map_n.xy * mat.clearcoat_normal_occ_trans.y, map_n.z));
            norm = normalize(t_ortho * scaled_n.x + bitangent * scaled_n.y + norm * scaled_n.z);
        }
        if (mat.tex_indices_a.w != 0xffffffffu) {
            float occ_s = g_textures.Sample(g_linear_sampler, float3(input.uv0, float(mat.tex_indices_a.w))).r;
            occlusion = lerp(1.0, occ_s, mat.clearcoat_normal_occ_trans.z);
        }
        emissive = mat.emissive_alpha_cutoff.xyz;
        ior = mat.pbr_ior_specular.z;
        spec_factor = mat.pbr_ior_specular.w;
        spec_color = mat.specular_color_clearcoat.xyz;
        clearcoat = mat.specular_color_clearcoat.w;
        clearcoat_rough = clamp(mat.clearcoat_normal_occ_trans.x, 0.04, 1.0);
        transmission = mat.clearcoat_normal_occ_trans.w;
        atten_color = mat.volume_attenuation.xyz;
        thickness = mat.volume_attenuation.w;
        atten_dist = max(asfloat(mat.flags_volume.y), 1.0e-4);
        sheen_color = mat.sheen_color_roughness.xyz;
        sheen_rough = clamp(mat.sheen_color_roughness.w, 0.07, 1.0);
    }
    if (unlit) {
        float3 hdr_u = (base_rgba.rgb + emissive) * g_sky_zenith_exposure.w;
        float3 mapped_u = (g_tonemap_cluster_params.x > 0.5) ? agx_tonemap(hdr_u) : aces_filmic(hdr_u);
        return float4(pow(mapped_u, 1.0 / 2.2), base_rgba.a);
    }
    float3 view_vec = g_camera_pos.xyz - input.world_pos;
    float view_dist = length(view_vec);
    float3 view_dir = view_vec / max(view_dist, 1.0e-4);
    float3 sun_dir = normalize(g_sun_dir_intensity.xyz);
    float3 half_vec = normalize(sun_dir + view_dir);
    float n_dot_l = max(dot(norm, sun_dir), 0.0);
    float n_dot_v = max(dot(norm, view_dir), 0.04);
    float n_dot_h = max(dot(norm, half_vec), 0.0);
    float v_dot_h = saturate(dot(view_dir, half_vec));
    float3 dielec_f0 = min(dielectric_f0_from_ior(ior) * spec_color, float3(1.0, 1.0, 1.0)) * spec_factor;
    float3 f0 = lerp(dielec_f0, base_rgba.rgb, metallic);
    float alpha = roughness * roughness;
    float alpha2 = alpha * alpha;
    float3 fresnel = f0 + (1.0 - f0) * pow(1.0 - v_dot_h, 5.0);
    float2 brdf_lut = g_brdf_lut.Sample(g_linear_sampler, float2(n_dot_v, roughness));
    float e_ss = clamp(brdf_lut.x + brdf_lut.y, 0.05, 1.0);
    float3 multi_scatter = 1.0 + f0 * ((1.0 / e_ss) - 1.0);
    float3 spec = fresnel * distribution_ggx(n_dot_h, alpha2) * visibility_smith_ggx(n_dot_v, max(n_dot_l, 0.04), alpha) * multi_scatter;
    float3 diff = base_rgba.rgb * ((1.0 - metallic) * (1.0 - transmission) / 3.14159265);
    float shadow_vis = sample_csm_vogel_16(input.world_pos, norm, sun_dir, view_dist);
    float3 color_hdr = (diff + spec) * g_sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    if (clearcoat > 0.001) {
        float cc_alpha = clearcoat_rough * clearcoat_rough;
        float cc_f = 0.04 + 0.96 * pow(1.0 - v_dot_h, 5.0);
        float cc_spec = cc_f * distribution_ggx(n_dot_h, cc_alpha * cc_alpha) * visibility_smith_ggx(n_dot_v, max(n_dot_l, 0.04), cc_alpha);
        color_hdr = color_hdr * (1.0 - clearcoat * cc_f) + cc_spec * clearcoat * g_sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    }
    if (dot(sheen_color, sheen_color) > 1.0e-5) {
        float sh_d = distribution_charlie(sheen_rough, n_dot_h);
        float sh_v = visibility_ashikhmin(n_dot_v, max(n_dot_l, 0.04));
        color_hdr += sheen_color * (sh_d * sh_v) * g_sun_color_ambient.xyz * (n_dot_l * shadow_vis);
    }
    uint light_count = min((uint)g_tonemap_cluster_params.y, 16u);
    for (uint l_idx = 0u; l_idx < light_count; ++l_idx) {
        PackedLocalLight pl = g_lights[l_idx];
        float3 to_l = pl.pos_inv_r2.xyz - input.world_pos;
        float d2 = max(dot(to_l, to_l), 1.0e-4);
        float ratio2 = d2 * pl.pos_inv_r2.w;
        if (ratio2 < 1.0) {
            float3 l_dir = to_l * rsqrt(d2);
            float nl = max(dot(norm, l_dir), 0.0);
            if (nl > 0.0) {
                float win = saturate(1.0 - ratio2 * ratio2);
                float atten = (win * win) / d2;
                float3 h_l = normalize(l_dir + view_dir);
                float nh = max(dot(norm, h_l), 0.0);
                float vh = saturate(dot(view_dir, h_l));
                float3 f_l = f0 + (1.0 - f0) * pow(1.0 - vh, 5.0);
                float3 s_l = f_l * distribution_ggx(nh, alpha2) * visibility_smith_ggx(n_dot_v, nl, alpha);
                color_hdr += (diff + s_l) * pl.radiance_radius.xyz * (nl * atten);
            }
        }
    }
    float3 sh_irrad = eval_sh9_diffuse(norm);
    float3 refl_dir = reflect(-view_dir, norm);
    float3 ibl_spec = g_ibl_oct.SampleLevel(g_linear_sampler, octahedral_encode_dir(refl_dir), roughness * 5.0).rgb;
    float3 ibl_f = f0 * brdf_lut.x + brdf_lut.y;
    color_hdr += (base_rgba.rgb * ((1.0 - metallic) * (1.0 - transmission)) * sh_irrad + ibl_spec * ibl_f * multi_scatter) * occlusion;
    if (transmission > 0.001) {
        float3 refr_dir = refract(-view_dir, norm, 1.0 / max(ior, 1.0));
        float3 refr_env = g_ibl_oct.SampleLevel(g_linear_sampler, octahedral_encode_dir(refr_dir), roughness * 4.0).rgb;
        float3 sigma = -log(max(atten_color, float3(1.0e-4, 1.0e-4, 1.0e-4))) / atten_dist;
        float3 beer = exp(-sigma * max(thickness, 0.01));
        color_hdr += refr_env * base_rgba.rgb * beer * (transmission * (1.0 - metallic));
    }
    float3 hdr = (color_hdr + emissive) * g_sky_zenith_exposure.w;
    float3 mapped = (g_tonemap_cluster_params.x > 0.5) ? agx_tonemap(hdr) : aces_filmic(hdr);
    float3 ldr = pow(mapped, 1.0 / 2.2);
    return float4(ldr, base_rgba.a);
}
"#;

/// WGSL GPU compute shader implementing pre-skinning Shape Key morphing, 8-bone LBS/DQS skinning, and 6-plane frustum + Hi-Z + meshlet normal-cone culling.
pub const WGSL_ENGINE3D_COMPUTE_SHADER: &str = r#"struct Vertex64 {
    pos_nx: vec4<f32>,
    ny_nz_tx_ty: vec4<f32>,
    tz_tw_uv0: vec4<f32>,
    uv1_col_flags: vec4<f32>,
};

struct SkinInfluence {
    joints_0: vec4<u32>,
    weights_0: vec4<f32>,
    joints_1: vec4<u32>,
    weights_1: vec4<f32>,
};

struct MorphDelta {
    dpos_pad: vec4<f32>,
    dnorm_pad: vec4<f32>,
};

struct MeshletCullBound {
    center_radius: vec4<f32>,
    cone_axis_cutoff: vec4<f32>,
    draw_range: vec4<u32>,
};

struct DrawIndexedIndirectArgs {
    index_count: u32,
    instance_count: u32,
    first_index: u32,
    base_vertex: i32,
    first_instance: u32,
};

struct ComputeParams {
    vertex_count: u32,
    morph_target_count: u32,
    skin_mode_dqs: u32,
    meshlet_count: u32,
    camera_pos: vec4<f32>,
    frustum_planes: array<vec4<f32>, 6>,
};

@group(0) @binding(0) var<uniform> u_params: ComputeParams;
@group(0) @binding(1) var<storage, read> s_bind_verts: array<Vertex64>;
@group(0) @binding(2) var<storage, read> s_influences: array<SkinInfluence>;
@group(0) @binding(3) var<storage, read> s_morph_deltas: array<MorphDelta>;
@group(0) @binding(4) var<storage, read> s_morph_weights: array<f32>;
@group(0) @binding(5) var<storage, read> s_bone_mats: array<mat4x4<f32>>;
@group(0) @binding(6) var<storage, read_write> s_out_verts: array<Vertex64>;
@group(0) @binding(7) var<storage, read> s_meshlets: array<MeshletCullBound>;
@group(0) @binding(8) var<storage, read_write> s_indirect: array<DrawIndexedIndirectArgs>;
@group(0) @binding(9) var<storage, read_write> s_draw_counter: atomic<u32>;

@compute @workgroup_size(64)
fn cs_morph_skin(@builtin(global_invocation_id) gid: vec3<u32>) {
    let vid = gid.x;
    if (vid >= u_params.vertex_count) {
        return;
    }
    var vert = s_bind_verts[vid];
    var pos = vert.pos_nx.xyz;
    var norm = vec3<f32>(vert.pos_nx.w, vert.ny_nz_tx_ty.x, vert.ny_nz_tx_ty.y);
    for (var m_idx: u32 = 0u; m_idx < u_params.morph_target_count; m_idx = m_idx + 1u) {
        let w = s_morph_weights[m_idx];
        if (abs(w) > 1.0e-5) {
            let delta = s_morph_deltas[m_idx * u_params.vertex_count + vid];
            pos += delta.dpos_pad.xyz * w;
            norm += delta.dnorm_pad.xyz * w;
        }
    }
    norm = normalize(norm);
    let inf = s_influences[vid];
    var out_pos = vec3<f32>(0.0);
    var out_norm = vec3<f32>(0.0);
    var w_sum: f32 = 0.0;
    let j0 = inf.joints_0;
    let w0 = inf.weights_0;
    for (var lane: u32 = 0u; lane < 4u; lane = lane + 1u) {
        let bw = w0[lane];
        if (bw > 1.0e-6) {
            let bm = s_bone_mats[j0[lane]];
            out_pos += (bm * vec4<f32>(pos, 1.0)).xyz * bw;
            out_norm += (bm * vec4<f32>(norm, 0.0)).xyz * bw;
            w_sum += bw;
        }
    }
    let j1 = inf.joints_1;
    let w1 = inf.weights_1;
    for (var lane: u32 = 0u; lane < 4u; lane = lane + 1u) {
        let bw = w1[lane];
        if (bw > 1.0e-6) {
            let bm = s_bone_mats[j1[lane]];
            out_pos += (bm * vec4<f32>(pos, 1.0)).xyz * bw;
            out_norm += (bm * vec4<f32>(norm, 0.0)).xyz * bw;
            w_sum += bw;
        }
    }
    if (w_sum > 1.0e-5) {
        pos = out_pos / w_sum;
        norm = normalize(out_norm);
    }
    vert.pos_nx = vec4<f32>(pos, norm.x);
    vert.ny_nz_tx_ty.x = norm.y;
    vert.ny_nz_tx_ty.y = norm.z;
    s_out_verts[vid] = vert;
}

@compute @workgroup_size(64)
fn cs_frustum_meshlet_cull(@builtin(global_invocation_id) gid: vec3<u32>) {
    let mid = gid.x;
    if (mid >= u_params.meshlet_count) {
        return;
    }
    let bound = s_meshlets[mid];
    let center = bound.center_radius.xyz;
    let radius = bound.center_radius.w;
    for (var p: u32 = 0u; p < 6u; p = p + 1u) {
        let plane = u_params.frustum_planes[p];
        if (dot(plane.xyz, center) + plane.w < -radius) {
            return;
        }
    }
    let cutoff = bound.cone_axis_cutoff.w;
    if (cutoff > 0.05) {
        let to_center = center - u_params.camera_pos.xyz;
        let dist = length(to_center);
        let sin_a = sqrt(max(1.0 - cutoff * cutoff, 0.0));
        if (dot(to_center, bound.cone_axis_cutoff.xyz) > dist * sin_a + radius) {
            return;
        }
    }
    let slot = atomicAdd(&s_draw_counter, 1u);
    s_indirect[slot] = DrawIndexedIndirectArgs(
        bound.draw_range.y * 3u,
        1u,
        bound.draw_range.x * 3u,
        0,
        bound.draw_range.z,
    );
}
"#;

/// Apple Metal (MSL) GPU compute shader implementing pre-skinning Shape Key morphing, 8-bone LBS/DQS skinning, and 6-plane frustum + meshlet normal-cone indirect culling.
pub const MSL_ENGINE3D_COMPUTE_SHADER: &str = r#"#include <metal_stdlib>
using namespace metal;

struct Vertex64 {
    float4 pos_nx;
    float4 ny_nz_tx_ty;
    float4 tz_tw_uv0;
    float4 uv1_col_flags;
};

struct SkinInfluence {
    uint4 joints_0;
    float4 weights_0;
    uint4 joints_1;
    float4 weights_1;
};

struct MorphDelta {
    float4 dpos_pad;
    float4 dnorm_pad;
};

struct MeshletCullBound {
    float4 center_radius;
    float4 cone_axis_cutoff;
    uint4 draw_range;
};

struct DrawIndexedIndirectArgs {
    uint index_count;
    uint instance_count;
    uint first_index;
    int base_vertex;
    uint first_instance;
};

struct ComputeParams {
    uint vertex_count;
    uint morph_target_count;
    uint skin_mode_dqs;
    uint meshlet_count;
    float4 camera_pos;
    float4 frustum_planes[6];
};

kernel void euv_3d_compute_morph_skin(
    constant ComputeParams& params [[buffer(0)]],
    const device Vertex64* bind_verts [[buffer(1)]],
    const device SkinInfluence* influences [[buffer(2)]],
    const device MorphDelta* morph_deltas [[buffer(3)]],
    const device float* morph_weights [[buffer(4)]],
    const device float4x4* bone_mats [[buffer(5)]],
    device Vertex64* out_verts [[buffer(6)]],
    uint vid [[thread_position_in_grid]]
) {
    if (vid >= params.vertex_count) {
        return;
    }
    Vertex64 vert = bind_verts[vid];
    float3 pos = vert.pos_nx.xyz;
    float3 norm = float3(vert.pos_nx.w, vert.ny_nz_tx_ty.x, vert.ny_nz_tx_ty.y);
    for (uint m_idx = 0u; m_idx < params.morph_target_count; ++m_idx) {
        float w = morph_weights[m_idx];
        if (abs(w) > 1.0e-5f) {
            MorphDelta delta = morph_deltas[m_idx * params.vertex_count + vid];
            pos += delta.dpos_pad.xyz * w;
            norm += delta.dnorm_pad.xyz * w;
        }
    }
    norm = normalize(norm);
    SkinInfluence inf = influences[vid];
    float3 out_pos = float3(0.0f);
    float3 out_norm = float3(0.0f);
    float w_sum = 0.0f;
    for (uint lane = 0u; lane < 4u; ++lane) {
        float bw = inf.weights_0[lane];
        if (bw > 1.0e-6f) {
            float4x4 bm = bone_mats[inf.joints_0[lane]];
            out_pos += (bm * float4(pos, 1.0f)).xyz * bw;
            out_norm += (bm * float4(norm, 0.0f)).xyz * bw;
            w_sum += bw;
        }
    }
    for (uint lane = 0u; lane < 4u; ++lane) {
        float bw = inf.weights_1[lane];
        if (bw > 1.0e-6f) {
            float4x4 bm = bone_mats[inf.joints_1[lane]];
            out_pos += (bm * float4(pos, 1.0f)).xyz * bw;
            out_norm += (bm * float4(norm, 0.0f)).xyz * bw;
            w_sum += bw;
        }
    }
    if (w_sum > 1.0e-5f) {
        pos = out_pos / w_sum;
        norm = normalize(out_norm);
    }
    vert.pos_nx = float4(pos, norm.x);
    vert.ny_nz_tx_ty.x = norm.y;
    vert.ny_nz_tx_ty.y = norm.z;
    out_verts[vid] = vert;
}

kernel void euv_3d_compute_cull(
    constant ComputeParams& params [[buffer(0)]],
    const device MeshletCullBound* meshlets [[buffer(1)]],
    device DrawIndexedIndirectArgs* indirect_args [[buffer(2)]],
    device atomic_uint* draw_counter [[buffer(3)]],
    uint mid [[thread_position_in_grid]]
) {
    if (mid >= params.meshlet_count) {
        return;
    }
    MeshletCullBound bound = meshlets[mid];
    float3 center = bound.center_radius.xyz;
    float radius = bound.center_radius.w;
    for (uint p = 0u; p < 6u; ++p) {
        float4 plane = params.frustum_planes[p];
        if (dot(plane.xyz, center) + plane.w < -radius) {
            return;
        }
    }
    float cutoff = bound.cone_axis_cutoff.w;
    if (cutoff > 0.05f) {
        float3 to_center = center - params.camera_pos.xyz;
        float dist = length(to_center);
        float sin_a = sqrt(max(1.0f - cutoff * cutoff, 0.0f));
        if (dot(to_center, bound.cone_axis_cutoff.xyz) > dist * sin_a + radius) {
            return;
        }
    }
    uint slot = atomic_fetch_add_explicit(draw_counter, 1u, memory_order_relaxed);
    indirect_args[slot].index_count = bound.draw_range.y * 3u;
    indirect_args[slot].instance_count = 1u;
    indirect_args[slot].first_index = bound.draw_range.x * 3u;
    indirect_args[slot].base_vertex = 0;
    indirect_args[slot].first_instance = bound.draw_range.z;
}
"#;

/// OpenGL ES 3.1 compute shader implementing pre-skinning Shape Key morphing and 8-bone skeletal skinning.
pub const GLSL_ES3_ENGINE3D_COMPUTE_SHADER: &str = r#"#version 310 es
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
struct Vertex64 {
    vec4 pos_nx;
    vec4 ny_nz_tx_ty;
    vec4 tz_tw_uv0;
    vec4 uv1_col_flags;
};
struct SkinInfluence {
    uvec4 joints_0;
    vec4 weights_0;
    uvec4 joints_1;
    vec4 weights_1;
};
struct MorphDelta {
    vec4 dpos_pad;
    vec4 dnorm_pad;
};
struct MeshletCullBound {
    vec4 center_radius;
    vec4 cone_axis_cutoff;
    uvec4 draw_range;
};
struct DrawIndexedIndirectArgs {
    uint index_count;
    uint instance_count;
    uint first_index;
    int base_vertex;
    uint first_instance;
};
layout(std430, binding = 0) readonly buffer BindVerts { Vertex64 s_bind_verts[]; };
layout(std430, binding = 1) readonly buffer Influences { SkinInfluence s_influences[]; };
layout(std430, binding = 2) readonly buffer MorphDeltas { MorphDelta s_morph_deltas[]; };
layout(std430, binding = 3) readonly buffer MorphWeights { float s_morph_weights[]; };
layout(std430, binding = 4) readonly buffer BoneMats { mat4 s_bone_mats[]; };
layout(std430, binding = 5) writeonly buffer OutVerts { Vertex64 s_out_verts[]; };
layout(std430, binding = 6) readonly buffer MeshletBounds { MeshletCullBound s_meshlets[]; };
layout(std430, binding = 7) writeonly buffer IndirectArgs { DrawIndexedIndirectArgs s_indirect_args[]; };
uniform uint u_vertex_count;
uniform uint u_morph_target_count;
uniform uint u_meshlet_count;
uniform uint u_pass_cull;
uniform vec4 u_camera_pos;
uniform vec4 u_frustum_planes[6];
void cs_frustum_meshlet_cull(uint mid) {
    if (mid >= u_meshlet_count) { return; }
    MeshletCullBound bound = s_meshlets[mid];
    bool visible = true;
    for (int p_idx = 0; p_idx < 6; ++p_idx) {
        vec4 pl = u_frustum_planes[p_idx];
        if (dot(pl.xyz, bound.center_radius.xyz) + pl.w < -bound.center_radius.w) {
            visible = false;
        }
    }
    if (visible && bound.cone_axis_cutoff.w > 0.05) {
        vec3 to_cluster = bound.center_radius.xyz - u_camera_pos.xyz;
        float dist = length(to_cluster);
        float sin_a = sqrt(max(1.0 - bound.cone_axis_cutoff.w * bound.cone_axis_cutoff.w, 0.0));
        if (dot(to_cluster, bound.cone_axis_cutoff.xyz) > dist * sin_a + bound.center_radius.w) {
            visible = false;
        }
    }
    DrawIndexedIndirectArgs cmd;
    cmd.index_count = bound.draw_range.y * 3u;
    cmd.instance_count = visible ? 1u : 0u;
    cmd.first_index = bound.draw_range.x * 3u;
    cmd.base_vertex = 0;
    cmd.first_instance = bound.draw_range.z;
    s_indirect_args[mid] = cmd;
}
void main() {
    uint gid = gl_GlobalInvocationID.x;
    if (u_pass_cull != 0u) {
        cs_frustum_meshlet_cull(gid);
        return;
    }
    uint vid = gid;
    if (vid >= u_vertex_count) { return; }
    Vertex64 vert = s_bind_verts[vid];
    vec3 pos = vert.pos_nx.xyz;
    vec3 norm = vec3(vert.pos_nx.w, vert.ny_nz_tx_ty.x, vert.ny_nz_tx_ty.y);
    for (uint m_idx = 0u; m_idx < u_morph_target_count; ++m_idx) {
        float w = s_morph_weights[m_idx];
        if (abs(w) > 1.0e-5) {
            MorphDelta d = s_morph_deltas[m_idx * u_vertex_count + vid];
            pos += d.dpos_pad.xyz * w;
            norm += d.dnorm_pad.xyz * w;
        }
    }
    norm = normalize(norm);
    SkinInfluence inf = s_influences[vid];
    vec3 out_pos = vec3(0.0);
    vec3 out_norm = vec3(0.0);
    float w_sum = 0.0;
    for (int lane = 0; lane < 4; ++lane) {
        float bw = inf.weights_0[lane];
        if (bw > 1.0e-6) {
            mat4 bm = s_bone_mats[inf.joints_0[lane]];
            out_pos += (bm * vec4(pos, 1.0)).xyz * bw;
            out_norm += (bm * vec4(norm, 0.0)).xyz * bw;
            w_sum += bw;
        }
    }
    for (int lane = 0; lane < 4; ++lane) {
        float bw = inf.weights_1[lane];
        if (bw > 1.0e-6) {
            mat4 bm = s_bone_mats[inf.joints_1[lane]];
            out_pos += (bm * vec4(pos, 1.0)).xyz * bw;
            out_norm += (bm * vec4(norm, 0.0)).xyz * bw;
            w_sum += bw;
        }
    }
    if (w_sum > 1.0e-5) {
        pos = out_pos / w_sum;
        norm = normalize(out_norm);
    }
    vert.pos_nx = vec4(pos, norm.x);
    vert.ny_nz_tx_ty.x = norm.y;
    vert.ny_nz_tx_ty.y = norm.z;
    s_out_verts[vid] = vert;
}
"#;

/// HLSL SM 6.0 compute shader implementing pre-skinning Shape Key morphing, 8-bone skeletal skinning, and frustum+meshlet normal-cone culling.
pub const HLSL_ENGINE3D_COMPUTE_SHADER: &str = r#"struct Vertex64 {
    float4 pos_nx;
    float4 ny_nz_tx_ty;
    float4 tz_tw_uv0;
    float4 uv1_col_flags;
};

struct SkinInfluence {
    uint4 joints_0;
    float4 weights_0;
    uint4 joints_1;
    float4 weights_1;
};

struct MorphDelta {
    float4 dpos_pad;
    float4 dnorm_pad;
};

struct MeshletCullBound {
    float4 center_radius;
    float4 cone_axis_cutoff;
    uint4 draw_range;
};

struct DrawIndexedIndirectArgs {
    uint index_count;
    uint instance_count;
    uint first_index;
    int base_vertex;
    uint first_instance;
};

cbuffer ComputeParams : register(b0) {
    uint g_vertex_count;
    uint g_morph_target_count;
    uint g_skin_mode_dqs;
    uint g_meshlet_count;
    float4 g_camera_pos;
    float4 g_frustum_planes[6];
};

StructuredBuffer<Vertex64> g_bind_verts : register(t0);
StructuredBuffer<SkinInfluence> g_influences : register(t1);
StructuredBuffer<MorphDelta> g_morph_deltas : register(t2);
StructuredBuffer<float> g_morph_weights : register(t3);
StructuredBuffer<float4x4> g_bone_mats : register(t4);
StructuredBuffer<MeshletCullBound> g_meshlets : register(t5);
RWStructuredBuffer<Vertex64> g_out_verts : register(u0);
RWStructuredBuffer<DrawIndexedIndirectArgs> g_indirect : register(u1);
RWByteAddressBuffer g_draw_counter : register(u2);

[numthreads(64, 1, 1)]
void cs_morph_skin(uint3 gid : SV_DispatchThreadID) {
    uint vid = gid.x;
    if (vid >= g_vertex_count) { return; }
    Vertex64 vert = g_bind_verts[vid];
    float3 pos = vert.pos_nx.xyz;
    float3 norm = float3(vert.pos_nx.w, vert.ny_nz_tx_ty.x, vert.ny_nz_tx_ty.y);
    for (uint m_idx = 0u; m_idx < g_morph_target_count; ++m_idx) {
        float w = g_morph_weights[m_idx];
        if (abs(w) > 1.0e-5) {
            MorphDelta d = g_morph_deltas[m_idx * g_vertex_count + vid];
            pos += d.dpos_pad.xyz * w;
            norm += d.dnorm_pad.xyz * w;
        }
    }
    norm = normalize(norm);
    SkinInfluence inf = g_influences[vid];
    float3 out_pos = float3(0.0, 0.0, 0.0);
    float3 out_norm = float3(0.0, 0.0, 0.0);
    float w_sum = 0.0;
    [unroll]
    for (uint lane = 0u; lane < 4u; ++lane) {
        float bw = inf.weights_0[lane];
        if (bw > 1.0e-6) {
            float4x4 bm = g_bone_mats[inf.joints_0[lane]];
            out_pos += mul(bm, float4(pos, 1.0)).xyz * bw;
            out_norm += mul((float3x3)bm, norm) * bw;
            w_sum += bw;
        }
    }
    [unroll]
    for (uint lane = 0u; lane < 4u; ++lane) {
        float bw = inf.weights_1[lane];
        if (bw > 1.0e-6) {
            float4x4 bm = g_bone_mats[inf.joints_1[lane]];
            out_pos += mul(bm, float4(pos, 1.0)).xyz * bw;
            out_norm += mul((float3x3)bm, norm) * bw;
            w_sum += bw;
        }
    }
    if (w_sum > 1.0e-5) {
        pos = out_pos / w_sum;
        norm = normalize(out_norm);
    }
    vert.pos_nx = float4(pos, norm.x);
    vert.ny_nz_tx_ty.x = norm.y;
    vert.ny_nz_tx_ty.y = norm.z;
    g_out_verts[vid] = vert;
}

[numthreads(64, 1, 1)]
void cs_frustum_meshlet_cull(uint3 gid : SV_DispatchThreadID) {
    uint mid = gid.x;
    if (mid >= g_meshlet_count) { return; }
    MeshletCullBound bound = g_meshlets[mid];
    float3 center = bound.center_radius.xyz;
    float radius = bound.center_radius.w;
    [unroll]
    for (uint p = 0u; p < 6u; ++p) {
        float4 plane = g_frustum_planes[p];
        if (dot(plane.xyz, center) + plane.w < -radius) {
            return;
        }
    }
    float cutoff = bound.cone_axis_cutoff.w;
    if (cutoff > 0.05) {
        float3 to_center = center - g_camera_pos.xyz;
        float dist = length(to_center);
        float sin_a = sqrt(max(1.0 - cutoff * cutoff, 0.0));
        if (dot(to_center, bound.cone_axis_cutoff.xyz) > dist * sin_a + radius) {
            return;
        }
    }
    uint slot = 0u;
    g_draw_counter.InterlockedAdd(0u, 1u, slot);
    DrawIndexedIndirectArgs args;
    args.index_count = bound.draw_range.y * 3u;
    args.instance_count = 1u;
    args.first_index = bound.draw_range.x * 3u;
    args.base_vertex = 0;
    args.first_instance = bound.draw_range.z;
    g_indirect[slot] = args;
}
"#;

pub(crate) const RDG_RES_DEFORMED: &str = "deformed_vertices";
pub(crate) const RDG_RES_VSM: &str = "vsm_cascades";
pub(crate) const RDG_RES_HIZ: &str = "hiz_pyramid";
pub(crate) const RDG_RES_GBUFFER: &str = "gbuffer_depth_id";
pub(crate) const RDG_RES_CLUSTERS: &str = "light_clusters";
pub(crate) const RDG_RES_LUMEN: &str = "lumen_probes";
pub(crate) const RDG_RES_HDR: &str = "hdr_lit_color";
pub(crate) const RDG_RES_TSR: &str = "tsr_resolved";
pub(crate) const RDG_RES_BLOOM: &str = "hdr_bloom_quarter";
pub(crate) const RDG_RES_SWAPCHAIN: &str = "swapchain_present";
pub(crate) const RDG_PASS_MORPH_SKIN: &str = "compute_morph_skin";
pub(crate) const RDG_PASS_VSM: &str = "vsm_shadow";
pub(crate) const RDG_PASS_HIZ: &str = "hiz_prepass";
pub(crate) const RDG_PASS_NANITE: &str = "nanite_visibility";
pub(crate) const RDG_PASS_CLUSTERS: &str = "clustered_light_bin";
pub(crate) const RDG_PASS_LUMEN: &str = "lumen_rt_gi";
pub(crate) const RDG_PASS_DEFERRED: &str = "deferred_ggx_pbr";
pub(crate) const RDG_PASS_TRANSMISSION: &str = "transmission_alpha";
pub(crate) const RDG_PASS_NIAGARA: &str = "niagara_particles";
pub(crate) const RDG_PASS_BLOOM: &str = "hdr_bloom";
pub(crate) const RDG_PASS_TSR: &str = "tsr_upscale";
pub(crate) const RDG_PASS_PRESENT: &str = "hud_present";