concinnity-device 0.19.9

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
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
//! The device-backend crate (rlib). Three jobs, all delegated to the shared
//! concinnity-toolchain build 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, emit_backend_cfg, emit_check_cfgs, hash_sources,
    precompile_metal_shaders, setup_graphics_sdks,
};
use std::path::PathBuf;

// The raymarch SDF fragments are not standalone shaders: they are text
// templates assembled with the user's SdfVolume source at runtime (see
// src/metal/raymarch.rs), so they can only ever compile from source.
const SOURCE_ONLY_METAL_SHADERS: &[&str] = &[
    "raymarch_helpers.metal",
    "raymarch_shadow.metal",
    "raymarch_template.metal",
    "raymarch_volumetric_template.metal",
];

// Shared declarations spliced into the shaders that carry the marker, matching
// what `metal::pipeline::shader_source` substitutes when the same shader
// compiles from source. The `.msl` extension keeps a fragment out of the
// `.metal` precompile scan: it is not a standalone library.
const METAL_SHADER_FRAGMENTS: &[(&str, &str)] = &[("{OBJECT_DATA}", "object_common.msl")];

// 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.
const SLANG_PROBE_DEFINES: &[(&str, &str)] = &[("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] = &[
    DxilAbi {
        file: "gbuffer_prepass.slang",
        gates: &["GB_STATIC"],
        entry: "gbuffer_prepass_vertex",
        profile: "vs_6_0",
        registers: &[("gb_view", "b0"), ("gb_model", "b1")],
    },
    DxilAbi {
        file: "gbuffer_prepass.slang",
        gates: &["GB_INSTANCED"],
        entry: "gbuffer_prepass_vertex_instanced",
        profile: "vs_6_0",
        registers: &[("gb_view", "b0"), ("instances", "t0")],
    },
    DxilAbi {
        file: "gbuffer_prepass.slang",
        gates: &["GB_SKINNED"],
        entry: "gbuffer_prepass_vertex_skinned",
        profile: "vs_6_0",
        registers: &[
            ("gb_view", "b0"),
            ("gb_model", "b1"),
            ("cur_joints", "t0"),
            ("prev_joints", "t1"),
        ],
    },
    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"),
        ],
    },
    DxilAbi {
        file: "gbuffer_prepass.slang",
        gates: &["GB_FRAGMENT"],
        entry: "gbuffer_prepass_fragment",
        profile: "ps_6_0",
        registers: &[("gb_mat", "b0")],
    },
    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: "light_cull.slang",
        file: "light_cull.slang",
        entries: &["light_cull_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.slang",
        file: "gbuffer_prepass.slang",
        entries: &["gbuffer_prepass_vertex"],
        defines: &[("GB_STATIC", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "gbuffer_prepass_vert_instanced.slang",
        file: "gbuffer_prepass.slang",
        entries: &["gbuffer_prepass_vertex_instanced"],
        defines: &[("GB_INSTANCED", "1"), ("METAL_BINDINGS", "1")],
    },
    SlangLibSpec {
        name: "gbuffer_prepass_vert_skinned.slang",
        file: "gbuffer_prepass.slang",
        entries: &["gbuffer_prepass_vertex_skinned"],
        defines: &[("GB_SKINNED", "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.slang",
        file: "gbuffer_prepass.slang",
        entries: &["gbuffer_prepass_fragment"],
        defines: &[("GB_FRAGMENT", "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.
fn precompile_dxil() {
    use concinnity_core::render::slang_programs::dx;

    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() {
    emit_check_cfgs();
    let backend = emit_backend_cfg();
    setup_graphics_sdks(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,
            METAL_SHADER_FRAGMENTS,
            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 a stable contract: world-authored
// Shader assets hand-write MSL against it. The `.slang` source pins the loose
// buffers with register() numbers, but the two parameter blocks (the texture
// argument buffer and the sampler block) 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 source =
        concinnity_core::render::slang_source::assemble("main_bindless.slang", SLANG_MAIN_DEFINES);
    let job = slang::SlangJob {
        source: &source,
        file_name: "main_bindless_abi_check.slang",
        entries: &["fragment_main_bindless"],
        target: slang::SlangTarget::Metal,
    };
    let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
    let msl = slang::compile(&job, &out_dir).expect("slang ABI check compile");
    let msl = String::from_utf8_lossy(&msl);
    for (param, index) in [
        ("view_cb", 0),
        ("lights_cb", 4),
        ("shadow_cb", 5),
        ("probe_set_cb", 6),
        ("tex", 7),
        ("local_lights_sb", 8),
        ("objects_sb", 9),
        ("samps", 10),
        ("cluster_cb", 11),
        ("cluster_list_sb", 12),
        ("spot_shadows_sb", 13),
        ("area_lights_sb", 14),
    ] {
        // Emitted parameter names carry a `_<n>` suffix (e.g. `tex_1`).
        let re = format!("{param}_1 [[buffer({index})]]");
        assert!(
            msl.contains(&re),
            "main_bindless.slang Metal ABI drifted: expected `{re}` in the emitted MSL. \
             The Metal binding layout is frozen (world shaders hand-write against it); \
             fix the .slang declarations or the slangc slot assignment before shipping."
        );
    }
}

// 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");
}