concinnity-device 0.19.24

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
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
//! The device-backend crate (rlib). Three jobs, the first two behind one
//! `setup_graphics_backend` call into the shared concinnity-toolchain helper:
//!
//! 1. Resolve the rendering backend once and expose it as a single cfg the crate
//!    gates on (backend_metal / backend_dx / backend_vk).
//!
//! 2. Detect the optional upscaler SDKs and emit the cfgs the backends gate on.
//!    This crate produces only an rlib (consumed by the client) plus its own test
//!    binaries, so it does NOT bundle runtime DLLs next to a binary (that belongs
//!    to whichever package owns the final artifact).
//!
//! 3. Derive the hash of the shader-compile sources that `shader_cache` folds
//!    into every artifact key (see `emit_shader_compile_source_hash`).

use concinnity_slang as slang;
use concinnity_toolchain::{
    Backend, SlangLibSpec, hash_sources, precompile_metal_shaders, setup_graphics_backend,
};
use std::path::PathBuf;

// Metal shaders that only ever compile from source at runtime. None since the
// raymarch templates became `raymarch.slang`.
const SOURCE_ONLY_METAL_SHADERS: &[&str] = &[];

// The Metal bindless texture-pool capacity and reflection-probe array length,
// baked into the single-source shaders at build time. Must match
// `metal::context::BINDLESS_TEXTURE_COUNT` and `metal::uniforms::MAX_PROBES`;
// the generated `slang_metal_defines.rs` consts let a unit test lock them.
const SLANG_METAL_POOL_SIZE: usize = 1024;
const SLANG_METAL_MAX_PROBES: usize = 8;

const SLANG_MAIN_DEFINES: &[(&str, &str)] = &[
    ("METAL_ABI", "1"),
    ("POOL_SIZE", "1024"),
    ("MAX_PROBES", "8"),
];

// The DirectX counterpart, matching `directx/slang_builtins.rs::MAIN_DEFINES`.
// No POOL_SIZE: the DXIL pool is an unbounded array.
const SLANG_DXIL_MAIN_DEFINES: &[(&str, &str)] = &[("DXIL_ABI", "1"), ("MAX_PROBES", "8")];

// The SSR resolve is the one post pass that reads the reflection-probe array,
// so it needs the same probe count the main pass bakes in. `METAL_ABI` selects
// the argument-buffer form of that array.
const SLANG_PROBE_DEFINES: &[(&str, &str)] = &[("METAL_ABI", "1"), ("MAX_PROBES", "8")];

// Every register the bindless main root signature in
// `src/directx/init/pipelines.rs` declares, as (parameter, HLSL register). The
// vertex stage reads only the first three; the rest are the fragment's.
const DXIL_ABI_REGISTERS: &[(&str, &str)] = &[
    ("objid_cb", "b0"),
    ("view_cb", "b1"),
    ("lights_cb", "b2"),
    ("shadow_cb", "b3"),
    ("probe_set_cb", "b4"),
    ("cluster_cb", "b5"),
    ("shadow_map", "t0"),
    ("local_lights_sb", "t1"),
    ("cluster_list_sb", "t2"),
    ("objects_sb", "t3"),
    ("ssao_tex", "t4"),
    ("irradiance_cube", "t5"),
    ("prefilter_cube", "t6"),
    ("probe_cubes", "t7"),
    ("spot_shadows_sb", "t15"),
    ("spot_shadow_map", "t16"),
    ("area_lights_sb", "t17"),
    ("ltc_matrix", "t18"),
    ("ltc_magnitude", "t19"),
    ("tex_pool", "t0, space1"),
    ("shadow_sampler", "s0"),
    ("linear_sampler", "s1"),
    ("cube_sampler", "s2"),
];

// One shader variant and the registers its DirectX root signature declares.
struct DxilAbi {
    file: &'static str,
    // Variant gates, injected as `#define <gate> 1` alongside DXIL_ABI.
    gates: &'static [&'static str],
    entry: &'static str,
    profile: &'static str,
    registers: &'static [(&'static str, &'static str)],
}

// The G-buffer pre-pass, shadow, ray-traced reflection and glass root
// signatures, from `src/directx/post/gbuffer.rs`, `post/rt_reflections.rs`,
// `glass.rs`, `init/pipelines.rs` and `resources.rs`. These
// layouts are engine-internal rather than a world-shader contract, but they are
// pinned for a sharper reason: the `.slang` files are shared with Metal and
// Vulkan, whose hosts bind the same declarations at entirely different slots,
// so an edit made on either of those platforms cannot see a DirectX root
// signature at all. `dx_crosscheck.sh` runs this script's DirectX branch, which
// is where such an edit gets caught.
const SLANG_DXIL_ENTRY_ABI: &[DxilAbi] = &[
    // The draw cull. Its registers are pinned in the source because declaration
    // order would hand `cull_status` u0 and `commands` u1, the reverse of what
    // `directx/cull.rs` binds; the shadow variant declares no status or Hi-Z.
    DxilAbi {
        file: "cull.slang",
        gates: &[],
        entry: "cull_kernel",
        profile: "cs_6_0",
        registers: &[
            ("cull", "b0"),
            ("objects", "t0"),
            ("draw_args", "t1"),
            ("hiz_tex", "t2"),
            ("commands", "u0"),
            ("cull_status", "u1"),
        ],
    },
    DxilAbi {
        file: "cull.slang",
        gates: &["CULL_PHASE2"],
        entry: "cull_kernel",
        profile: "cs_6_0",
        registers: &[
            ("cull", "b0"),
            ("objects", "t0"),
            ("draw_args", "t1"),
            ("hiz_tex", "t2"),
            ("commands", "u0"),
            ("cull_status", "u1"),
        ],
    },
    DxilAbi {
        file: "cull.slang",
        gates: &["SHADOW_CULL"],
        entry: "cull_kernel",
        profile: "cs_6_0",
        registers: &[
            ("cull", "b0"),
            ("objects", "t0"),
            ("draw_args", "t1"),
            ("commands", "u0"),
        ],
    },
    DxilAbi {
        file: "gbuffer_prepass.slang",
        gates: &["GB_BINDLESS"],
        entry: "gbuffer_prepass_vertex_bindless",
        profile: "vs_6_0",
        registers: &[
            ("objid_cb", "b0"),
            ("gb_view", "b1"),
            ("objects", "t0"),
            ("prev_models", "t1"),
            ("draw_args", "t2"),
        ],
    },
    DxilAbi {
        file: "gbuffer_prepass.slang",
        gates: &["GB_FRAGMENT_BINDLESS"],
        entry: "gbuffer_prepass_fragment_bindless",
        profile: "ps_6_0",
        registers: &[],
    },
    DxilAbi {
        file: "shadow.slang",
        gates: &["SHADOW_STATIC"],
        entry: "shadow_vertex_main",
        profile: "vs_6_0",
        registers: &[("push", "b0"), ("shadow_cb", "b1")],
    },
    DxilAbi {
        file: "shadow.slang",
        gates: &["SHADOW_SKINNED"],
        entry: "shadow_vertex_main_skinned",
        profile: "vs_6_0",
        registers: &[("push", "b0"), ("shadow_cb", "b1"), ("joints", "t0")],
    },
    DxilAbi {
        file: "shadow.slang",
        gates: &["SHADOW_BINDLESS"],
        entry: "shadow_vertex_bindless",
        profile: "vs_6_0",
        registers: &[
            ("objid_cb", "b0"),
            ("shadow_cb", "b1"),
            ("push", "b2"),
            ("objects", "t0"),
        ],
    },
    // Ray query needs shader model 6.5, above the 6.0 floor the rest of the
    // single-source shaders compile at.
    DxilAbi {
        file: "rt_reflections.slang",
        gates: &[],
        entry: "rt_reflections_fragment",
        profile: "ps_6_5",
        registers: RT_REFLECTIONS_REGISTERS,
    },
    DxilAbi {
        file: "rt_reflections.slang",
        gates: &["RT_TEXTURED"],
        entry: "rt_reflections_fragment",
        profile: "ps_6_5",
        registers: RT_REFLECTIONS_TEXTURED_REGISTERS,
    },
    DxilAbi {
        file: "glass.slang",
        gates: &[],
        entry: "glass_vertex",
        profile: "vs_6_0",
        registers: &[("view", "b0")],
    },
    DxilAbi {
        file: "glass.slang",
        gates: &[],
        entry: "glass_fragment",
        profile: "ps_6_0",
        registers: GLASS_REGISTERS,
    },
    DxilAbi {
        file: "glass.slang",
        gates: &["GLASS_RT"],
        entry: "glass_rt_fragment",
        profile: "ps_6_5",
        registers: GLASS_RT_REGISTERS,
    },
    DxilAbi {
        file: "glass.slang",
        gates: &["GLASS_RT", "RT_TEXTURED"],
        entry: "glass_rt_fragment",
        profile: "ps_6_5",
        registers: GLASS_RT_TEXTURED_REGISTERS,
    },
    // The see-through glass MESH producer. Ray-traced only, so it declares the
    // RT register set unconditionally; its vertex stage reads the model matrix
    // out of b1, which is why b1 is visible to every stage in the root
    // signature.
    DxilAbi {
        file: "glass_mesh.slang",
        gates: &[],
        entry: "glass_mesh_vertex",
        profile: "vs_6_0",
        registers: &[("view", "b0"), ("params", "b1")],
    },
    DxilAbi {
        file: "glass_mesh.slang",
        gates: &[],
        entry: "glass_mesh_rt_fragment",
        profile: "ps_6_5",
        registers: GLASS_MESH_RT_REGISTERS,
    },
    DxilAbi {
        file: "glass_mesh.slang",
        gates: &["RT_TEXTURED"],
        entry: "glass_mesh_rt_fragment",
        profile: "ps_6_5",
        registers: GLASS_RT_TEXTURED_REGISTERS,
    },
    // Water shares every register glass declares, which is what lets one root
    // signature per path serve both producers of the transparent pass. The RT
    // pair additionally reads the planar resolve at t3 (see
    // WATER_RT_REGISTERS), which the shared RT signature has a table for.
    DxilAbi {
        file: "water.slang",
        gates: &[],
        entry: "water_vertex",
        profile: "vs_6_0",
        registers: &[("view", "b0"), ("params", "b1")],
    },
    DxilAbi {
        file: "water.slang",
        gates: &[],
        entry: "water_fragment",
        profile: "ps_6_0",
        registers: GLASS_REGISTERS,
    },
    DxilAbi {
        file: "water.slang",
        gates: &["WATER_RT"],
        entry: "water_rt_fragment",
        profile: "ps_6_5",
        registers: WATER_RT_REGISTERS,
    },
    DxilAbi {
        file: "water.slang",
        gates: &["WATER_RT", "RT_TEXTURED"],
        entry: "water_rt_fragment",
        profile: "ps_6_5",
        registers: WATER_RT_TEXTURED_REGISTERS,
    },
    // The RT skinning kernel, from `create_skin_root_signature` in
    // `src/directx/raytrace.rs`. Its buffers carry `register()` annotations, but
    // the push constant deliberately does not: a bare `[[vk::push_constant]]`
    // lands on b0 by declaration order, which is where the root signature puts
    // its constants, and this row is the only thing holding it there.
    DxilAbi {
        file: "rt_skin.slang",
        gates: &[],
        entry: "rt_skin",
        profile: "cs_6_5",
        registers: &[
            ("src", "t0"),
            ("palette", "t1"),
            ("dst", "u0"),
            ("morph_data", "t2"),
            ("morph_weights", "t3"),
            ("params", "b0"),
        ],
    },
    // The raster remainder, from `src/directx/{particle,decal,line}.rs` and
    // `pipeline.rs`. Only the particle pair carries a `DXIL_ABI` block, and only
    // to swap the two constant buffers; the rest are here because slangc
    // assigns their registers from declaration order, which is a weaker
    // guarantee than a `register()` annotation and nothing else would catch a
    // release that changed it.
    DxilAbi {
        file: "particle.slang",
        gates: &[],
        entry: "particle_vertex",
        profile: "vs_6_0",
        registers: &[("view", "b0"), ("params", "b1"), ("pool", "t0")],
    },
    DxilAbi {
        file: "particle.slang",
        gates: &[],
        entry: "particle_fragment",
        profile: "ps_6_0",
        registers: &[("albedo_texture", "t1"), ("albedo_sampler", "s0")],
    },
    DxilAbi {
        file: "decal.slang",
        gates: &[],
        entry: "decal_vertex",
        profile: "vs_6_0",
        registers: &[("view", "b0"), ("params", "b1")],
    },
    DxilAbi {
        file: "decal.slang",
        gates: &[],
        entry: "decal_fragment",
        profile: "ps_6_0",
        registers: &[
            ("view", "b0"),
            ("params", "b1"),
            ("scene_depth", "t0"),
            ("decal_tex_texture", "t1"),
            ("decal_tex_sampler", "s0"),
        ],
    },
    DxilAbi {
        file: "line.slang",
        gates: &[],
        entry: "line_vertex",
        profile: "vs_6_0",
        registers: &[("view", "b0")],
    },
    DxilAbi {
        file: "line.slang",
        gates: &[],
        entry: "line_fragment",
        profile: "ps_6_0",
        registers: &[("view", "b0"), ("scene_depth", "t0")],
    },
    DxilAbi {
        file: "text.slang",
        gates: &[],
        entry: "text_vertex_main",
        profile: "vs_6_0",
        registers: &[("uni", "b0")],
    },
    DxilAbi {
        file: "text.slang",
        gates: &[],
        entry: "text_fragment_main",
        profile: "ps_6_0",
        registers: &[("atlas_texture", "t0"), ("atlas_sampler", "s0")],
    },
];

// The ray-traced reflection resolve's root signature, from
// `src/directx/post/rt_reflections.rs`. The probe cube array is remapped clear
// of the screen-space SRVs, which is what the hand-written HLSL used its
// PROBE_CUBES_REGISTER define for.
const RT_REFLECTIONS_REGISTERS: &[(&str, &str)] = &[
    ("rt_params", "b0"),
    ("probe_set", "b4"),
    ("scene_tlas", "t0"),
    ("verts", "t1"),
    ("indices", "t2"),
    ("geom", "t3"),
    ("scene_tex", "t4"),
    ("gbuffer", "t5"),
    ("rough_tex", "t6"),
    ("prefilter", "t7"),
    ("sverts", "t8"),
    ("sidx", "t9"),
    ("probe_cubes", "t10"),
    ("screen_sampler", "s0"),
    ("cube_sampler", "s1"),
    ("probe_cube_sampler", "s3"),
];

const RT_REFLECTIONS_TEXTURED_REGISTERS: &[(&str, &str)] =
    &[("tex_pool", "t0, space1"), ("pool_sampler", "s2")];

// The transparent pass's root signatures, from `src/directx/transparent.rs`,
// which glass and water both draw under. The base pass leaves the probe cubes at
// their default t7; the RT variant moves them to t20 because the array spans
// MAX_PROBES registers and the trace's SRVs sit at t4..t10.
const GLASS_REGISTERS: &[(&str, &str)] = &[
    ("view", "b0"),
    ("params", "b1"),
    ("probe_set", "b4"),
    ("scene_color", "t0"),
    ("scene_depth", "t1"),
    ("prefilter_cube", "t2"),
    ("planar_reflection", "t3"),
    ("probe_cubes", "t7"),
    ("post_samp", "s0"),
    ("cube_sampler", "s2"),
];

const GLASS_RT_REGISTERS: &[(&str, &str)] = &[
    ("view", "b0"),
    ("params", "b1"),
    ("rt_params", "b5"),
    ("probe_set", "b4"),
    ("scene_color", "t0"),
    ("scene_depth", "t1"),
    ("prefilter_cube", "t2"),
    ("scene_tlas", "t4"),
    ("verts", "t5"),
    ("indices", "t6"),
    ("sverts", "t8"),
    ("sidx", "t9"),
    ("geom", "t10"),
    ("probe_cubes", "t20"),
];

const GLASS_RT_TEXTURED_REGISTERS: &[(&str, &str)] =
    &[("tex_pool", "t0, space1"), ("pool_sampler", "s1")];

// Water's RT fragments, which are glass's set plus the planar resolve at t3: a
// water surface with a mirror plane samples it in place of tracing, so unlike
// glass the register survives into the RT variant and the RT root signature
// carries a table for it.
const WATER_RT_REGISTERS: &[(&str, &str)] = &[
    ("view", "b0"),
    ("params", "b1"),
    ("rt_params", "b5"),
    ("probe_set", "b4"),
    ("scene_color", "t0"),
    ("scene_depth", "t1"),
    ("prefilter_cube", "t2"),
    ("planar_reflection", "t3"),
    ("scene_tlas", "t4"),
    ("verts", "t5"),
    ("indices", "t6"),
    ("sverts", "t8"),
    ("sidx", "t9"),
    ("geom", "t10"),
    ("probe_cubes", "t20"),
];

const WATER_RT_TEXTURED_REGISTERS: &[(&str, &str)] = &[
    ("planar_reflection", "t3"),
    ("tex_pool", "t0, space1"),
    ("pool_sampler", "s1"),
];

// The see-through glass mesh fragment: the RT set above, minus the planar
// resolve at t3 (a curved mesh has no mirror plane) and with the same t20 probe
// cube base, so the pass's RT root signature covers it unchanged.
const GLASS_MESH_RT_REGISTERS: &[(&str, &str)] = &[
    ("view", "b0"),
    ("params", "b1"),
    ("rt_params", "b5"),
    ("probe_set", "b4"),
    ("scene_color", "t0"),
    ("scene_depth", "t1"),
    ("prefilter_cube", "t2"),
    ("scene_tlas", "t4"),
    ("verts", "t5"),
    ("indices", "t6"),
    ("sverts", "t8"),
    ("sidx", "t9"),
    ("geom", "t10"),
    ("probe_cubes", "t20"),
    ("post_samp", "s0"),
    ("cube_sampler", "s2"),
];

// The single-source engine shaders the Metal backend precompiles to metallibs.
// One spec per variant library; `name` is the renderer's lookup key.
const SLANG_METAL_LIBS: &[SlangLibSpec] = &[
    SlangLibSpec {
        name: "main_bindless_vert.slang",
        file: "main_bindless.slang",
        entries: &["vertex_main_bindless"],
        defines: SLANG_MAIN_DEFINES,
    },
    SlangLibSpec {
        name: "main_bindless_frag.slang",
        file: "main_bindless.slang",
        entries: &["fragment_main_bindless"],
        defines: SLANG_MAIN_DEFINES,
    },
    SlangLibSpec {
        name: "cull_phase1.slang",
        file: "cull.slang",
        entries: &["cull_kernel"],
        defines: &[("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "cull_phase2.slang",
        file: "cull.slang",
        entries: &["cull_kernel"],
        defines: &[("CULL_PHASE2", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "cull_shadow.slang",
        file: "cull.slang",
        entries: &["cull_kernel"],
        defines: &[("SHADOW_CULL", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "light_cull.slang",
        file: "light_cull.slang",
        entries: &["light_cull_kernel"],
        defines: &[],
    },
    SlangLibSpec {
        name: "model_history.slang",
        file: "model_history.slang",
        entries: &["model_history_kernel"],
        defines: &[],
    },
    SlangLibSpec {
        name: "hiz_init_msaa.slang",
        file: "hiz_build.slang",
        entries: &["hiz_init_msaa"],
        defines: &[("HIZ_INIT_MSAA", "1")],
    },
    SlangLibSpec {
        name: "hiz_downsample.slang",
        file: "hiz_build.slang",
        entries: &["hiz_downsample"],
        defines: &[("HIZ_DOWNSAMPLE", "1")],
    },
    SlangLibSpec {
        name: "probe_mip0.slang",
        file: "probe_prefilter.slang",
        entries: &["probe_mip0"],
        defines: &[("PROBE_MIP0", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "probe_downsample.slang",
        file: "probe_prefilter.slang",
        entries: &["probe_downsample"],
        defines: &[("PROBE_DOWNSAMPLE", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "probe_ggx.slang",
        file: "probe_prefilter.slang",
        entries: &["probe_ggx"],
        defines: &[("PROBE_GGX", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "gbuffer_prepass_vert_bindless.slang",
        file: "gbuffer_prepass.slang",
        entries: &["gbuffer_prepass_vertex_bindless"],
        defines: &[("GB_BINDLESS", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "gbuffer_prepass_frag_bindless.slang",
        file: "gbuffer_prepass.slang",
        entries: &["gbuffer_prepass_fragment_bindless"],
        defines: &[("GB_FRAGMENT_BINDLESS", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "shadow_vert.slang",
        file: "shadow.slang",
        entries: &["shadow_vertex_main"],
        defines: &[("SHADOW_STATIC", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "shadow_vert_skinned.slang",
        file: "shadow.slang",
        entries: &["shadow_vertex_main_skinned"],
        defines: &[("SHADOW_SKINNED", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "shadow_vert_bindless.slang",
        file: "shadow.slang",
        entries: &["shadow_vertex_bindless"],
        defines: &[("SHADOW_BINDLESS", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "fullscreen_vert.slang",
        file: "fullscreen.slang",
        entries: &["fullscreen_vertex"],
        defines: &[],
    },
    SlangLibSpec {
        name: "taa_frag.slang",
        file: "taa.slang",
        entries: &["taa_fragment_main"],
        defines: &[],
    },
    SlangLibSpec {
        name: "bloom_prefilter.slang",
        file: "bloom.slang",
        entries: &["bloom_prefilter_fragment"],
        defines: &[("BLOOM_PREFILTER", "1")],
    },
    SlangLibSpec {
        name: "bloom_downsample.slang",
        file: "bloom.slang",
        entries: &["bloom_downsample_fragment"],
        defines: &[("BLOOM_DOWNSAMPLE", "1")],
    },
    SlangLibSpec {
        name: "bloom_upsample.slang",
        file: "bloom.slang",
        entries: &["bloom_upsample_fragment"],
        defines: &[("BLOOM_UPSAMPLE", "1")],
    },
    SlangLibSpec {
        name: "composite_frag.slang",
        file: "composite.slang",
        entries: &["composite_fragment"],
        defines: &[],
    },
    SlangLibSpec {
        name: "ssao_kernel.slang",
        file: "ssao.slang",
        entries: &["ssao_kernel_fragment"],
        defines: &[("SSAO_KERNEL", "1")],
    },
    SlangLibSpec {
        name: "ssao_blur.slang",
        file: "ssao.slang",
        entries: &["ssao_blur_fragment"],
        defines: &[("SSAO_BLUR", "1")],
    },
    SlangLibSpec {
        name: "ssr_resolve.slang",
        file: "ssr.slang",
        entries: &["ssr_resolve_fragment"],
        defines: SLANG_PROBE_DEFINES,
    },
    SlangLibSpec {
        name: "ssgi_gather.slang",
        file: "ssgi.slang",
        entries: &["ssgi_gather_fragment"],
        defines: &[("SSGI_GATHER", "1")],
    },
    SlangLibSpec {
        name: "ssgi_composite.slang",
        file: "ssgi.slang",
        entries: &["ssgi_composite_fragment"],
        defines: &[("SSGI_COMPOSITE", "1")],
    },
    SlangLibSpec {
        name: "reflection_blur.slang",
        file: "reflection.slang",
        entries: &["reflection_blur_fragment"],
        defines: &[("REFLECTION_BLUR", "1")],
    },
    SlangLibSpec {
        name: "reflection_composite.slang",
        file: "reflection.slang",
        entries: &["reflection_composite_fragment"],
        defines: &[("REFLECTION_COMPOSITE", "1")],
    },
    SlangLibSpec {
        name: "fog_froxel.slang",
        file: "fog.slang",
        entries: &["fog_froxel_kernel"],
        defines: &[("FOG_FROXEL", "1")],
    },
    SlangLibSpec {
        name: "fog_frag.slang",
        file: "fog.slang",
        entries: &["fog_fragment"],
        defines: &[("USE_MSAA", "0")],
    },
    SlangLibSpec {
        name: "auto_exposure_build.slang",
        file: "auto_exposure.slang",
        entries: &["histogram_build"],
        defines: &[("AE_BUILD", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "auto_exposure_average.slang",
        file: "auto_exposure.slang",
        entries: &["histogram_average"],
        defines: &[("AE_AVERAGE", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "rt_skin.slang",
        file: "rt_skin.slang",
        entries: &["rt_skin"],
        defines: &[("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "particle_simulate.slang",
        file: "particle_simulate.slang",
        entries: &["particle_simulate"],
        defines: &[("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "particle_vert.slang",
        file: "particle.slang",
        entries: &["particle_vertex"],
        defines: &[("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "particle_frag.slang",
        file: "particle.slang",
        entries: &["particle_fragment"],
        defines: &[("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "decal_vert.slang",
        file: "decal.slang",
        entries: &["decal_vertex"],
        defines: &[],
    },
    SlangLibSpec {
        name: "decal_frag.slang",
        file: "decal.slang",
        entries: &["decal_fragment"],
        defines: &[("USE_MSAA", "0")],
    },
    SlangLibSpec {
        name: "line_vert.slang",
        file: "line.slang",
        entries: &["line_vertex"],
        defines: &[],
    },
    SlangLibSpec {
        name: "line_frag.slang",
        file: "line.slang",
        entries: &["line_fragment"],
        defines: &[("USE_MSAA", "0")],
    },
    SlangLibSpec {
        name: "text_vert.slang",
        file: "text.slang",
        entries: &["text_vertex_main"],
        defines: &[("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "text_frag.slang",
        file: "text.slang",
        entries: &["text_fragment_main"],
        defines: &[("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "rt_reflections_frag.slang",
        file: "rt_reflections.slang",
        entries: &["rt_reflections_fragment"],
        defines: SLANG_RT_DEFINES,
    },
    SlangLibSpec {
        name: "rt_reflections_frag_textured.slang",
        file: "rt_reflections.slang",
        entries: &["rt_reflections_fragment"],
        defines: SLANG_RT_TEXTURED_DEFINES,
    },
    SlangLibSpec {
        name: "glass_vert.slang",
        file: "glass.slang",
        entries: &["glass_vertex"],
        defines: SLANG_GLASS_DEFINES,
    },
    SlangLibSpec {
        name: "glass_frag.slang",
        file: "glass.slang",
        entries: &["glass_fragment"],
        defines: SLANG_GLASS_DEFINES,
    },
    SlangLibSpec {
        name: "glass_frag_rt.slang",
        file: "glass.slang",
        entries: &["glass_rt_fragment"],
        defines: SLANG_GLASS_RT_DEFINES,
    },
    SlangLibSpec {
        name: "glass_frag_rt_textured.slang",
        file: "glass.slang",
        entries: &["glass_rt_fragment"],
        defines: SLANG_GLASS_RT_TEXTURED_DEFINES,
    },
    SlangLibSpec {
        name: "glass_mesh_vert.slang",
        file: "glass_mesh.slang",
        entries: &["glass_mesh_vertex"],
        defines: SLANG_GLASS_MESH_DEFINES,
    },
    SlangLibSpec {
        name: "glass_mesh_frag_rt.slang",
        file: "glass_mesh.slang",
        entries: &["glass_mesh_rt_fragment"],
        defines: SLANG_GLASS_MESH_DEFINES,
    },
    SlangLibSpec {
        name: "glass_mesh_frag_rt_textured.slang",
        file: "glass_mesh.slang",
        entries: &["glass_mesh_rt_fragment"],
        defines: SLANG_GLASS_MESH_TEXTURED_DEFINES,
    },
    SlangLibSpec {
        name: "water_vert.slang",
        file: "water.slang",
        entries: &["water_vertex"],
        defines: SLANG_WATER_DEFINES,
    },
    SlangLibSpec {
        name: "water_frag.slang",
        file: "water.slang",
        entries: &["water_fragment"],
        defines: SLANG_WATER_DEFINES,
    },
    SlangLibSpec {
        name: "water_frag_rt.slang",
        file: "water.slang",
        entries: &["water_rt_fragment"],
        defines: SLANG_WATER_RT_DEFINES,
    },
    SlangLibSpec {
        name: "water_frag_rt_textured.slang",
        file: "water.slang",
        entries: &["water_rt_fragment"],
        defines: SLANG_WATER_RT_TEXTURED_DEFINES,
    },
];

// The ray-traced families. Both bake the Metal binding layout in; the textured
// variants additionally read the bindless pool, so they take its capacity.
const SLANG_RT_DEFINES: &[(&str, &str)] = &[("METAL_ABI", "1"), ("MAX_PROBES", "8")];
const SLANG_RT_TEXTURED_DEFINES: &[(&str, &str)] = &[
    ("METAL_ABI", "1"),
    ("RT_TEXTURED", "1"),
    ("POOL_SIZE", "1024"),
    ("MAX_PROBES", "8"),
];
const SLANG_GLASS_DEFINES: &[(&str, &str)] = &[("METAL_ABI", "1"), ("MAX_PROBES", "8")];
const SLANG_GLASS_RT_DEFINES: &[(&str, &str)] =
    &[("METAL_ABI", "1"), ("GLASS_RT", "1"), ("MAX_PROBES", "8")];
const SLANG_GLASS_RT_TEXTURED_DEFINES: &[(&str, &str)] = &[
    ("METAL_ABI", "1"),
    ("GLASS_RT", "1"),
    ("RT_TEXTURED", "1"),
    ("POOL_SIZE", "1024"),
    ("MAX_PROBES", "8"),
];
// The glass mesh family is ray-traced only, so there is no non-RT gate to set.
const SLANG_GLASS_MESH_DEFINES: &[(&str, &str)] = &[("METAL_ABI", "1"), ("MAX_PROBES", "8")];
const SLANG_GLASS_MESH_TEXTURED_DEFINES: &[(&str, &str)] = &[
    ("METAL_ABI", "1"),
    ("RT_TEXTURED", "1"),
    ("POOL_SIZE", "1024"),
    ("MAX_PROBES", "8"),
];
const SLANG_WATER_DEFINES: &[(&str, &str)] = &[("METAL_ABI", "1"), ("MAX_PROBES", "8")];
const SLANG_WATER_RT_DEFINES: &[(&str, &str)] =
    &[("METAL_ABI", "1"), ("WATER_RT", "1"), ("MAX_PROBES", "8")];
const SLANG_WATER_RT_TEXTURED_DEFINES: &[(&str, &str)] = &[
    ("METAL_ABI", "1"),
    ("WATER_RT", "1"),
    ("RT_TEXTURED", "1"),
    ("POOL_SIZE", "1024"),
    ("MAX_PROBES", "8"),
];

// The modules that decide how a shader artifact is produced: the cache itself
// (the key layout, and what an entry stores) and each backend's compiler
// invocation. A cache key already covers the assembled shader source, the entry
// point, the target and the caller's option word, so what it cannot see is a
// change to the invocation around them -- a different optimisation level, an
// added flag, a reworked entry format. Hashing these sources in closes that
// gap, so such a change misses instead of loading bytes the old invocation
// produced. Every backend's module participates on every build, which keeps the
// hash independent of the resolved backend; the key's `compiler` field is what
// keeps one toolchain's artifacts away from another's.
//
// A host toolchain upgrade (a new Xcode, a new Windows SDK) changes no source
// here and so is not covered: deleting the cache directory remains the way to
// force a full recompile.
//
// The slangc invocation is the tenth participant and lives in another crate, so
// it arrives as `concinnity_slang::SOURCE_HASH` (folded in by `shader_cache`)
// rather than being read out of that crate's directory: a registry checkout of
// this crate has no sibling copy to read.
const SHADER_COMPILE_SOURCES: &[&str] = &[
    "src/shader_cache.rs",
    "src/runtime_cache.rs",
    "src/slang_source.rs",
    "src/directx/pipeline.rs",
    "src/directx/slang_builtins.rs",
    "src/metal/msl_cache.rs",
    "src/metal/slang_shaders.rs",
    "src/vulkan/pipeline.rs",
    "src/vulkan/slang_builtins.rs",
];

// Compile every declared Vulkan program to SPIR-V now, for the same reason the
// DirectX leg does: so the binary carries its shaders rather than needing slangc
// on the host that runs it.
//
// Two things vary per program and neither depends on the world, which is what
// makes them enumerable here. `USE_MSAA` is the host's sample count, so a
// program that reads the main pass's depth gets both variants. `POOL_SIZE` and
// `MAX_PROBES` are baked at the ceilings a desktop driver affords; a device that
// seats less falls back to sizing them itself, and that source then matches no
// artifact and compiles -- see `vulkan::builtins::bindless_pool_size`.
fn precompile_spirv() {
    use concinnity_core::render::slang_programs::vk::{self, Sizes};
    use concinnity_core::render::uniforms::{BINDLESS_POOL_SIZE, MAX_PROBES};

    let pool = BINDLESS_POOL_SIZE.to_string();
    let probes = MAX_PROBES.to_string();
    let mut artifacts = Vec::new();
    for program in vk::ALL {
        for msaa in msaa_variants(program.msaa) {
            let mut defines: Vec<(&str, &str)> = program.gates.iter().map(|g| (*g, "1")).collect();
            if program.msaa {
                defines.push(("USE_MSAA", if *msaa { "1" } else { "0" }));
            }
            if program.sizes == Sizes::PoolAndProbes {
                defines.push(("POOL_SIZE", pool.as_str()));
            }
            if program.sizes != Sizes::None {
                defines.push(("MAX_PROBES", probes.as_str()));
            }
            artifacts.push(concinnity_toolchain::SlangArtifact {
                name: spirv_artifact_name(program.label, *msaa),
                source: concinnity_core::render::slang_source::assemble(program.file, &defines),
                entry: program.entry,
                file_name: program.file,
                target: slang::SlangTarget::Spirv,
            });
        }
    }
    concinnity_toolchain::precompile_slang_artifacts(
        &artifacts,
        "engine_spirv.rs",
        "embedded_spirv",
    );
}

fn msaa_variants(takes_msaa: bool) -> &'static [bool] {
    if takes_msaa { &[false, true] } else { &[false] }
}

// The lookup key for one Vulkan program's artifact. A program that reads the
// sample count yields two, so the label alone would collide between them.
// Mirrored by `vulkan::slang_builtins::spirv_artifact_name`.
fn spirv_artifact_name(label: &str, msaa: bool) -> String {
    if msaa {
        format!("{label}.msaa")
    } else {
        label.to_string()
    }
}

// Compile every declared DirectX program to DXIL now, so the binary carries its
// shaders instead of needing slangc on whatever host runs it. The declarations
// and the assembly both come from `core::render`, the same ones the renderer
// uses, so the text compiled here is the text it would have compiled -- which is
// what lets `directx::slang_builtins` serve these bytes without re-deriving the
// cache key.
//
// DXIL is the one target slangc cannot emit alone: it hands the HLSL to dxc,
// loaded as `dxcompiler.dll`, which only a Windows host has. The DirectX branch
// runs on any other host only under `dx_crosscheck.sh`, which type-checks the
// backend and never runs the binary, so that host embeds nothing and the lookup
// answers `None` for everything.
fn precompile_dxil() {
    use concinnity_core::render::slang_programs::dx;

    if !cfg!(windows) {
        concinnity_toolchain::precompile_slang_artifacts(&[], "engine_dxil.rs", "embedded_dxil");
        return;
    }
    let artifacts: Vec<_> = dx::ALL
        .iter()
        .map(|p| concinnity_toolchain::SlangArtifact {
            name: p.label.to_string(),
            source: concinnity_core::render::slang_source::assemble(p.file, p.defines),
            entry: p.entry,
            file_name: p.file,
            target: slang::SlangTarget::Dxil(p.profile),
        })
        .collect();
    concinnity_toolchain::precompile_slang_artifacts(&artifacts, "engine_dxil.rs", "embedded_dxil");
}

fn main() {
    let backend = setup_graphics_backend();
    if backend == Some(Backend::Metal) {
        let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let shaders_dir = manifest.join("src/metal/shaders");
        precompile_metal_shaders(&shaders_dir, SOURCE_ONLY_METAL_SHADERS, SLANG_METAL_LIBS);
        assert_slang_metal_abi();
        emit_slang_metal_defines();
    }
    if backend == Some(Backend::Dx) {
        assert_slang_dxil_abi();
        precompile_dxil();
    }
    if backend == Some(Backend::Vk) {
        precompile_spirv();
    }
    emit_shader_compile_source_hash();
}

// The Metal main-pass binding layout is what the encoders in `metal/draw/`
// write, and a world Shader's stages compile from the same declarations. The
// `.slang` sources pin the loose buffers with register()
// numbers, but the bindless pair's two parameter blocks and every per-draw
// texture and sampler land on first-free slot assignment, which is compiler
// behaviour rather than an annotation. Assert the emitted MSL here so a slangc
// upgrade that moves a slot fails the build instead of binding garbage at draw
// time. Skipped when slangc is absent (the runtime compile path reports its own
// error then).
fn assert_slang_metal_abi() {
    if slang::slangc_path().is_none() {
        return;
    }
    let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
    for abi in SLANG_METAL_ENTRY_ABI {
        let source = concinnity_core::render::slang_source::assemble(abi.file, abi.defines);
        let job = slang::SlangJob {
            source: &source,
            file_name: "metal_abi_check.slang",
            entries: &[abi.entry],
            target: slang::SlangTarget::Metal,
        };
        let msl = slang::compile(&job, &out_dir).expect("slang ABI check compile");
        let msl = String::from_utf8_lossy(&msl);
        assert_every_param_is_attributed(abi, &msl_entry_params(&msl, abi.entry));
        for (param, attribute) in abi.slots {
            assert!(
                msl_binds(&msl, param, attribute),
                "{}: Metal ABI drifted at `{}`: expected `{param}` on [[{attribute}]] in the \
                 emitted MSL. \
                 The Metal binding layout is what the encoder writes and what world shaders \
                 compile from; fix the .slang declarations or the slot assignment \
                 before shipping.",
                abi.file,
                abi.entry
            );
        }
    }
}

// slangc emits a resource array declared at *global* scope with no
// `[[texture(n)]]` / `[[sampler(n)]]` at all, leaving the Metal compiler to
// place it at whatever slot happens to be unused -- a placement the emitted MSL
// cannot be read for, and one an unrelated declaration silently moves. Nothing
// in the tree may take that shape: the reflection-probe cube arrays that used
// to are `ParameterBlock`s now, one pinned buffer slot each, which the rows
// above assert like any other.
fn assert_every_param_is_attributed(abi: &MetalAbi, params: &[String]) {
    let unattributed: Vec<&str> = params
        .iter()
        .filter(|p| !p.contains("[["))
        .map(|p| msl_param_name(p))
        .collect();
    assert!(
        unattributed.is_empty(),
        "{} ({}): the emitted MSL has entry parameters with no binding attribute: \
         {unattributed:?}. slangc gives a global-scope resource array no [[texture(n)]] / \
         [[sampler(n)]], so the Metal compiler places it at the next unused slot and no host \
         binding can be checked against it. Declare it inside a ParameterBlock instead (see \
         main_bindless.slang's METAL_ABI block, or `ProbeCubes` in this file's five \
         probe-sampling shaders).",
        abi.file,
        abi.entry,
    );
}

// Whether the emitted MSL binds `param` at `attribute`. Emitted parameter names
// carry a `_<n>` suffix whose number is the compiler's own (`joints_3`), so the
// name is matched up to it.
fn msl_binds(msl: &str, param: &str, attribute: &str) -> bool {
    let marker = format!(" [[{attribute}]]");
    msl.match_indices(&marker).any(|(at, _)| {
        msl[..at]
            .rsplit(|c: char| c.is_whitespace())
            .next()
            .and_then(|name| name.rsplit_once('_'))
            .is_some_and(|(head, tail)| head == param && tail.chars().all(|c| c.is_ascii_digit()))
    })
}

// The parameter list of the one entry point in an emitted MSL translation unit,
// split at top-level commas.
fn msl_entry_params(msl: &str, entry: &str) -> Vec<String> {
    let stage = ["[[fragment]]", "[[vertex]]", "[[kernel]]"]
        .iter()
        .find_map(|tag| msl.find(tag))
        .unwrap_or_else(|| panic!("emitted MSL declares no entry point for `{entry}`"));
    let open = stage
        + msl[stage..]
            .find('(')
            .unwrap_or_else(|| panic!("emitted MSL entry point `{entry}` has no parameter list"));
    assert!(
        msl[stage..open].trim_end().ends_with(entry),
        "emitted MSL entry point is not `{entry}`: {}",
        &msl[stage..open]
    );

    let mut params = Vec::new();
    let mut depth = 0i32;
    let mut start = open + 1;
    for (at, ch) in msl[open..].char_indices().map(|(i, c)| (open + i, c)) {
        match ch {
            '(' | '<' | '[' => depth += 1,
            ')' | '>' | ']' => {
                depth -= 1;
                if depth == 0 {
                    params.push(msl[start..at].trim().to_string());
                    break;
                }
            }
            ',' if depth == 1 => {
                params.push(msl[start..at].trim().to_string());
                start = at + 1;
            }
            _ => {}
        }
    }
    params
}

// An emitted parameter's source name. The `_<n>` suffix is the compiler's own
// (`probe_cubes_texture_1`), so it is trimmed off.
fn msl_param_name(param: &str) -> &str {
    let name = param
        .rsplit(|c: char| c.is_whitespace())
        .next()
        .unwrap_or(param);
    match name.rsplit_once('_') {
        Some((head, tail)) if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) => head,
        _ => name,
    }
}

// One entry point and the Metal slots its host encoder writes, as
// (parameter, attribute) pairs.
struct MetalAbi {
    file: &'static str,
    entry: &'static str,
    defines: &'static [(&'static str, &'static str)],
    slots: &'static [(&'static str, &'static str)],
}

const SLANG_METAL_ENTRY_ABI: &[MetalAbi] = &[
    // The draw cull's decision half. Its buffers are pinned by register() and
    // the Hi-Z texture takes texture(0) from declaration order; the slots are
    // what `metal/cull.rs` binds once for this dispatch and the ICB encode
    // dispatch that follows it on the same encoder.
    MetalAbi {
        file: "cull.slang",
        entry: "cull_kernel",
        defines: &[("METAL_BINDINGS", "1")],
        slots: &[
            ("objects", "buffer(0)"),
            ("draw_args", "buffer(1)"),
            ("cull", "buffer(2)"),
            ("cull_status", "buffer(5)"),
            ("hiz_tex", "texture(0)"),
        ],
    },
    // Phase 2 re-tests candidates only, so it never reads `draw_args`; the
    // encode dispatch after it does, from the same binding.
    MetalAbi {
        file: "cull.slang",
        entry: "cull_kernel",
        defines: &[("CULL_PHASE2", "1"), ("METAL_BINDINGS", "1")],
        slots: &[
            ("objects", "buffer(0)"),
            ("cull", "buffer(2)"),
            ("cull_status", "buffer(5)"),
            ("hiz_tex", "texture(0)"),
        ],
    },
    MetalAbi {
        file: "cull.slang",
        entry: "cull_kernel",
        defines: &[("SHADOW_CULL", "1"), ("METAL_BINDINGS", "1")],
        slots: &[
            ("objects", "buffer(0)"),
            ("draw_args", "buffer(1)"),
            ("cull", "buffer(2)"),
            ("cull_status", "buffer(5)"),
        ],
    },
    // The model-history snapshot: params, the object buffer it reads and the
    // ring slot it writes take buffer(0..2) from declaration order, which is
    // what `metal/model_history.rs` binds.
    MetalAbi {
        file: "model_history.slang",
        entry: "model_history_kernel",
        defines: &[],
        slots: &[
            ("params", "buffer(0)"),
            ("objects", "buffer(1)"),
            ("history", "buffer(2)"),
        ],
    },
    // The GPU-driven G-buffer pre-pass vertex. Its buffers are pinned by
    // register() numbers so they clear the vertex descriptor's streams at
    // buffer(1) and buffer(2); the slots are what `metal/post/gbuffer.rs`
    // binds once for every ICB-executed draw.
    MetalAbi {
        file: "gbuffer_prepass.slang",
        entry: "gbuffer_prepass_vertex_bindless",
        defines: &[("GB_BINDLESS", "1")],
        slots: &[
            ("gb_view", "buffer(0)"),
            ("objects", "buffer(9)"),
            ("prev_models", "buffer(10)"),
            ("draw_args", "buffer(11)"),
        ],
    },
    MetalAbi {
        file: "main_bindless.slang",
        entry: "fragment_main_bindless",
        defines: SLANG_MAIN_DEFINES,
        slots: &[
            ("view_cb", "buffer(0)"),
            ("lights_cb", "buffer(4)"),
            ("shadow_cb", "buffer(5)"),
            ("probe_set_cb", "buffer(6)"),
            ("tex", "buffer(7)"),
            ("local_lights_sb", "buffer(8)"),
            ("objects_sb", "buffer(9)"),
            ("samps", "buffer(10)"),
            ("cluster_cb", "buffer(11)"),
            ("cluster_list_sb", "buffer(12)"),
            ("spot_shadows_sb", "buffer(13)"),
            ("area_lights_sb", "buffer(14)"),
        ],
    },
    // The five shaders that sample the reflection-probe cube set. Every slot
    // here is what `metal/post/ssr.rs`, `metal/post/rt_reflections.rs` and
    // `metal/transparent.rs` bind, and all of them are order-assigned rather
    // than pinned in the source -- only the buffers carry register() numbers.
    // The probe block is the exception and the reason these rows exist: it is
    // the one array in the set, and putting it at a pinned buffer slot is what
    // keeps it out of the texture namespace entirely.
    MetalAbi {
        file: "ssr.slang",
        entry: "ssr_resolve_fragment",
        defines: SLANG_PROBE_DEFINES,
        slots: &[
            ("params", "buffer(0)"),
            ("probe_set", "buffer(1)"),
            ("scene_texture", "texture(0)"),
            ("scene_sampler", "sampler(0)"),
            ("gbuffer_texture", "texture(1)"),
            ("gbuffer_sampler", "sampler(1)"),
            ("rough_tex_texture", "texture(2)"),
            ("rough_tex_sampler", "sampler(2)"),
            ("prefilter_texture", "texture(3)"),
            ("prefilter_sampler", "sampler(3)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(4)"),
        ],
    },
    MetalAbi {
        file: "rt_reflections.slang",
        entry: "rt_reflections_fragment",
        defines: SLANG_RT_DEFINES,
        slots: &[
            ("rt_params", "buffer(0)"),
            ("verts", "buffer(1)"),
            ("indices", "buffer(2)"),
            ("geom", "buffer(3)"),
            ("scene_tlas", "buffer(4)"),
            ("sverts", "buffer(5)"),
            ("sidx", "buffer(6)"),
            ("probe_set", "buffer(8)"),
            ("scene_tex_texture", "texture(0)"),
            ("scene_tex_sampler", "sampler(0)"),
            ("gbuffer_texture", "texture(1)"),
            ("gbuffer_sampler", "sampler(1)"),
            ("rough_tex_texture", "texture(2)"),
            ("rough_tex_sampler", "sampler(2)"),
            ("prefilter_texture", "texture(3)"),
            ("prefilter_sampler", "sampler(3)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(4)"),
        ],
    },
    MetalAbi {
        file: "rt_reflections.slang",
        entry: "rt_reflections_fragment",
        defines: SLANG_RT_TEXTURED_DEFINES,
        slots: &[
            ("rt_params", "buffer(0)"),
            ("verts", "buffer(1)"),
            ("indices", "buffer(2)"),
            ("geom", "buffer(3)"),
            ("scene_tlas", "buffer(4)"),
            ("sverts", "buffer(5)"),
            ("sidx", "buffer(6)"),
            ("pool", "buffer(7)"),
            ("pool_sampler", "sampler(5)"),
            ("probe_set", "buffer(8)"),
            ("scene_tex_texture", "texture(0)"),
            ("scene_tex_sampler", "sampler(0)"),
            ("gbuffer_texture", "texture(1)"),
            ("gbuffer_sampler", "sampler(1)"),
            ("rough_tex_texture", "texture(2)"),
            ("rough_tex_sampler", "sampler(2)"),
            ("prefilter_texture", "texture(3)"),
            ("prefilter_sampler", "sampler(3)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(4)"),
        ],
    },
    MetalAbi {
        file: "glass.slang",
        entry: "glass_fragment",
        defines: SLANG_GLASS_DEFINES,
        slots: &[
            ("view", "buffer(5)"),
            ("params", "buffer(6)"),
            ("probe_set", "buffer(7)"),
            ("scene_color_texture", "texture(0)"),
            ("scene_color_sampler", "sampler(0)"),
            ("scene_depth", "texture(1)"),
            ("prefilter_cube_texture", "texture(2)"),
            ("prefilter_cube_sampler", "sampler(1)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(2)"),
            ("planar_reflection_texture", "texture(3)"),
            ("planar_reflection_sampler", "sampler(3)"),
        ],
    },
    MetalAbi {
        file: "glass.slang",
        entry: "glass_rt_fragment",
        defines: SLANG_GLASS_RT_DEFINES,
        slots: &[
            ("view", "buffer(5)"),
            ("params", "buffer(6)"),
            ("probe_set", "buffer(7)"),
            ("scene_color_texture", "texture(0)"),
            ("scene_color_sampler", "sampler(0)"),
            ("scene_depth", "texture(1)"),
            ("prefilter_cube_texture", "texture(2)"),
            ("prefilter_cube_sampler", "sampler(1)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(2)"),
            ("rt_params", "buffer(0)"),
            ("verts", "buffer(1)"),
            ("indices", "buffer(2)"),
            ("geom", "buffer(3)"),
            ("scene_tlas", "buffer(4)"),
            ("sverts", "buffer(8)"),
            ("sidx", "buffer(9)"),
        ],
    },
    MetalAbi {
        file: "glass.slang",
        entry: "glass_rt_fragment",
        defines: SLANG_GLASS_RT_TEXTURED_DEFINES,
        slots: &[
            ("view", "buffer(5)"),
            ("params", "buffer(6)"),
            ("probe_set", "buffer(7)"),
            ("scene_color_texture", "texture(0)"),
            ("scene_color_sampler", "sampler(0)"),
            ("scene_depth", "texture(1)"),
            ("prefilter_cube_texture", "texture(2)"),
            ("prefilter_cube_sampler", "sampler(1)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(2)"),
            ("rt_params", "buffer(0)"),
            ("verts", "buffer(1)"),
            ("indices", "buffer(2)"),
            ("geom", "buffer(3)"),
            ("scene_tlas", "buffer(4)"),
            ("sverts", "buffer(8)"),
            ("sidx", "buffer(9)"),
            ("pool", "buffer(10)"),
            ("pool_sampler", "sampler(4)"),
        ],
    },
    MetalAbi {
        file: "glass_mesh.slang",
        entry: "glass_mesh_rt_fragment",
        defines: SLANG_GLASS_MESH_DEFINES,
        slots: &[
            ("view", "buffer(5)"),
            ("params", "buffer(6)"),
            ("probe_set", "buffer(7)"),
            ("scene_color_texture", "texture(0)"),
            ("scene_color_sampler", "sampler(0)"),
            ("scene_depth", "texture(1)"),
            ("prefilter_cube_texture", "texture(2)"),
            ("prefilter_cube_sampler", "sampler(1)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(2)"),
            ("rt_params", "buffer(0)"),
            ("verts", "buffer(1)"),
            ("indices", "buffer(2)"),
            ("geom", "buffer(3)"),
            ("scene_tlas", "buffer(4)"),
            ("sverts", "buffer(8)"),
            ("sidx", "buffer(9)"),
        ],
    },
    MetalAbi {
        file: "glass_mesh.slang",
        entry: "glass_mesh_rt_fragment",
        defines: SLANG_GLASS_MESH_TEXTURED_DEFINES,
        slots: &[
            ("view", "buffer(5)"),
            ("params", "buffer(6)"),
            ("probe_set", "buffer(7)"),
            ("scene_color_texture", "texture(0)"),
            ("scene_color_sampler", "sampler(0)"),
            ("scene_depth", "texture(1)"),
            ("prefilter_cube_texture", "texture(2)"),
            ("prefilter_cube_sampler", "sampler(1)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(2)"),
            ("rt_params", "buffer(0)"),
            ("verts", "buffer(1)"),
            ("indices", "buffer(2)"),
            ("geom", "buffer(3)"),
            ("scene_tlas", "buffer(4)"),
            ("sverts", "buffer(8)"),
            ("sidx", "buffer(9)"),
            ("pool", "buffer(10)"),
            ("pool_sampler", "sampler(4)"),
        ],
    },
    MetalAbi {
        file: "water.slang",
        entry: "water_fragment",
        defines: SLANG_WATER_DEFINES,
        slots: &[
            ("view", "buffer(5)"),
            ("params", "buffer(6)"),
            ("probe_set", "buffer(7)"),
            ("scene_color_texture", "texture(0)"),
            ("scene_color_sampler", "sampler(0)"),
            ("scene_depth", "texture(1)"),
            ("prefilter_cube_texture", "texture(2)"),
            ("prefilter_cube_sampler", "sampler(1)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(2)"),
            ("planar_reflection_texture", "texture(3)"),
            ("planar_reflection_sampler", "sampler(3)"),
        ],
    },
    MetalAbi {
        file: "water.slang",
        entry: "water_rt_fragment",
        defines: SLANG_WATER_RT_DEFINES,
        slots: &[
            ("view", "buffer(5)"),
            ("params", "buffer(6)"),
            ("probe_set", "buffer(7)"),
            ("scene_color_texture", "texture(0)"),
            ("scene_color_sampler", "sampler(0)"),
            ("scene_depth", "texture(1)"),
            ("prefilter_cube_texture", "texture(2)"),
            ("prefilter_cube_sampler", "sampler(1)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(2)"),
            ("planar_reflection_texture", "texture(3)"),
            ("planar_reflection_sampler", "sampler(3)"),
            ("rt_params", "buffer(0)"),
            ("verts", "buffer(1)"),
            ("indices", "buffer(2)"),
            ("geom", "buffer(3)"),
            ("scene_tlas", "buffer(4)"),
            ("sverts", "buffer(8)"),
            ("sidx", "buffer(9)"),
        ],
    },
    MetalAbi {
        file: "water.slang",
        entry: "water_rt_fragment",
        defines: SLANG_WATER_RT_TEXTURED_DEFINES,
        slots: &[
            ("view", "buffer(5)"),
            ("params", "buffer(6)"),
            ("probe_set", "buffer(7)"),
            ("scene_color_texture", "texture(0)"),
            ("scene_color_sampler", "sampler(0)"),
            ("scene_depth", "texture(1)"),
            ("prefilter_cube_texture", "texture(2)"),
            ("prefilter_cube_sampler", "sampler(1)"),
            ("probe_cube_set", "buffer(11)"),
            ("probe_cube_sampler", "sampler(2)"),
            ("planar_reflection_texture", "texture(3)"),
            ("planar_reflection_sampler", "sampler(3)"),
            ("rt_params", "buffer(0)"),
            ("verts", "buffer(1)"),
            ("indices", "buffer(2)"),
            ("geom", "buffer(3)"),
            ("scene_tlas", "buffer(4)"),
            ("sverts", "buffer(8)"),
            ("sidx", "buffer(9)"),
            ("pool", "buffer(10)"),
            ("pool_sampler", "sampler(4)"),
        ],
    },
];

// The DirectX bindless main-pass binding layout is a stable contract for the
// same reason Metal's is: a world Shader asset builds its own PSO against the
// bindless root signature (see directx/world_shaders.rs), so a register that
// moves silently misbinds every world shader. The `.slang` source pins each one
// with register(), but a Slang release that mis-lowered an annotation would
// bind garbage at draw time with no compile-time signal. Emit HLSL and assert
// the annotations survive. Skipped when slangc is absent (the runtime compile
// path reports its own error then).
fn assert_slang_dxil_abi() {
    if slang::slangc_path().is_none() {
        return;
    }
    let source = concinnity_core::render::slang_source::assemble(
        "main_bindless.slang",
        SLANG_DXIL_MAIN_DEFINES,
    );
    let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
    // The two stages compile separately and each drops the resources it does
    // not read, so a register only has to hold in the stage that declares it.
    let mut emitted = String::new();
    for (entry, profile) in [
        ("vertex_main_bindless", "vs_6_0"),
        ("fragment_main_bindless", "ps_6_0"),
    ] {
        emitted.push_str(&emit_dxil_hlsl(
            &out_dir,
            "main_bindless_abi_check.slang",
            &source,
            entry,
            profile,
        ));
    }
    for (param, register) in DXIL_ABI_REGISTERS {
        assert_dxil_register(
            &emitted,
            param,
            register,
            "The DirectX bindless binding layout is frozen (world Shader assets build PSOs \
             against the same root signature); fix the .slang declarations or the root \
             signature in src/directx/init/pipelines.rs before shipping.",
        );
    }
    assert_slang_dxil_entry_abi(&out_dir);
}

// The same check over every other single-source family. Each variant compiles
// alone, so a register only has to hold in the entry that declares it. A file
// with no `DXIL_ABI` block is still worth a row: `DXIL_ABI` is simply inert
// there and the check reads back slangc's declaration-order assignment.
fn assert_slang_dxil_entry_abi(out_dir: &std::path::Path) {
    for abi in SLANG_DXIL_ENTRY_ABI {
        let mut defines: Vec<(&str, &str)> = vec![("DXIL_ABI", "1")];
        defines.extend(abi.gates.iter().map(|gate| (*gate, "1")));
        let source = concinnity_core::render::slang_source::assemble(abi.file, &defines);
        let emitted = emit_dxil_hlsl(out_dir, abi.file, &source, abi.entry, abi.profile);
        for (param, register) in abi.registers {
            assert_dxil_register(
                &emitted,
                param,
                register,
                "Fix the .slang declaration or the matching root signature under \
                 src/directx before shipping.",
            );
        }
    }
}

// One entry point's emitted HLSL, for reading register annotations back out.
fn emit_dxil_hlsl(
    out_dir: &std::path::Path,
    file_name: &str,
    source: &str,
    entry: &str,
    profile: &'static str,
) -> String {
    let job = slang::SlangJob {
        source,
        file_name,
        entries: &[entry],
        target: slang::SlangTarget::Hlsl(profile),
    };
    let hlsl = slang::compile(&job, out_dir)
        .unwrap_or_else(|e| panic!("slang DXIL ABI check ({entry}): {e}"));
    String::from_utf8_lossy(&hlsl).into_owned()
}

fn assert_dxil_register(emitted: &str, param: &str, register: &str, remedy: &str) {
    // Emitted parameter names carry a `_<n>` suffix (e.g. `view_cb_0`).
    let expected = format!("{param}_0 : register({register})");
    // Resource arrays emit as `name_0[int(N)] : register(...)`.
    let expected_array = format!("{param}_0[");
    assert!(
        emitted.contains(&expected)
            || emitted.lines().any(
                |l| l.contains(&expected_array) && l.contains(&format!("register({register})"))
            ),
        "slang DXIL ABI drifted: expected `{param}` at register({register}). {remedy}"
    );
}

// Expose the define values baked into the precompiled slang metallibs so a
// unit test can lock them to the crate's own constants.
fn emit_slang_metal_defines() {
    let value = |key: &str| {
        SLANG_MAIN_DEFINES
            .iter()
            .find(|(k, _)| *k == key)
            .map(|(_, v)| *v)
            .unwrap_or_default()
    };
    assert_eq!(value("POOL_SIZE"), SLANG_METAL_POOL_SIZE.to_string());
    assert_eq!(value("MAX_PROBES"), SLANG_METAL_MAX_PROBES.to_string());
    let out = PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("slang_metal_defines.rs");
    std::fs::write(
        &out,
        format!(
            "pub(crate) const SLANG_METAL_POOL_SIZE: usize = {SLANG_METAL_POOL_SIZE};\n\
             pub(crate) const SLANG_METAL_MAX_PROBES: usize = {SLANG_METAL_MAX_PROBES};\n"
        ),
    )
    .expect("write slang_metal_defines.rs");
}

fn emit_shader_compile_source_hash() {
    let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
    let roots: Vec<PathBuf> = SHADER_COMPILE_SOURCES
        .iter()
        .map(|p| manifest.join(p))
        .collect();
    let hash = hash_sources(&roots);

    let out =
        PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("shader_compile_source_hash.rs");
    std::fs::write(
        &out,
        format!("const SHADER_COMPILE_SOURCE_HASH: u32 = {hash:#010x};\n"),
    )
    .expect("write shader_compile_source_hash.rs");
}