primase-core 0.2.0

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

use serde::Serialize;
use serde_json::Value;

use crate::shader::{
    BufferBinding, BufferSource, BufferTable, ConstantBinding, ConstantRole, FrameTexture, InputBinding,
    ObjectParameter, OutputBinding, OutputRole, VariantKey,
};
use iridia_interface::{
    BufferKind, ConstantBufferBinding, Interface, Label, MatrixLines, RenderState, ResourceId, ResourceKind,
    SamplerState, ScalarType, Stage, SystemValue, Unshown,
};

use super::Shader;
use crate::TextureLayers;
use crate::components::{Texture, TextureFile};
use crate::json::JsonError;
use crate::world::{Component, Entity};

/// What a texture slot samples.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TextureSource {
    /// A texture entity (`core.texture`, `core.texture_layers` or `core.texture_file`), with the sampler state stored
    /// with it.
    Texture { texture: Entity, sampler: SamplerState },
    /// No texture; the slot reads this value everywhere, and why.
    Default { value: [f32; 4], why: String },
    /// An image of the frame being drawn, which the consumer supplies.
    Frame(FrameTexture),
    /// Nothing is bound and the source says no default: a consumer must not invent one. The reason retains the
    /// source's resource identity and the missing evidence, so consumers can explain the refusal.
    Missing { why: String },
    /// A view of one of the frame's own targets: only in the binding of a step of the frame's `core.render_graph`
    /// ([`crate::render_graph`]), whose targets these are. A material's binding never states one. It is read through the
    /// program's samplers, whose states the stage states ([`StageBinding::samplers`]): a sampler's state belongs to the
    /// sampler, which one texture may be read through several of.
    Target { view: crate::render_graph::TargetView },
}
/// Where a stage binding stands, which decides what its texture slots may bind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BindingPlace {
    /// A material's `core.shader_binding`.
    Material,
    /// A step of the frame's `core.render_graph`, which may bind the graph's targets.
    GraphStep,
}
/// One texture slot: the texture resource of the shader, the sampler resource it is read through, and what is bound.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct TextureBinding {
    pub resource: ResourceId,
    /// The sampler resource of the shader the program reads this texture through, where it reads it through exactly
    /// one. `None` where the program only loads it (no sampler), reads it through several (each sampler's state is the
    /// stage's, [`StageBinding::samplers`]), or the source does not say.
    pub sampler: Option<ResourceId>,
    pub source: TextureSource,
}
/// The state of one sampler resource of a program, as the source binds it ([`StageBinding::samplers`]).
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct SamplerBinding {
    /// The sampler resource of the shader.
    pub resource: ResourceId,
    /// Its filters, addressing, border colour, comparison and level range, each as the source states it.
    pub state: SamplerState,
}
/// One shader program in a material, with the role of everything it reads and writes.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct StageBinding {
    pub stage: Stage,
    /// The variant of the draw this stage is for, where the source draws one material with different programs of a
    /// stage depending on the mesh (its vertex layout, whether it is skinned): the key the mesh's own data must equal
    /// ([`VariantKey`]). A binding holds one stage of each kind, or several of one kind each for a distinct value of one
    /// key.
    pub variant: Option<VariantKey>,
    /// The `core.shader` entity.
    pub shader: Entity,
    pub inputs: Vec<InputBinding>,
    pub constants: Vec<ConstantBinding>,
    pub textures: Vec<TextureBinding>,
    /// The state of each sampler resource of the program, where the source binds the program's samplers itself (a step
    /// of the frame's `core.render_graph`): each a sampler of the shader, once. A sampler with no entry has no state the
    /// source states. A material's binding states none: its sampler states are its textures'
    /// ([`TextureSource::Texture`]).
    pub samplers: Vec<SamplerBinding>,
    /// The buffers the program indexes at run time (tables of the draw's matrices and instances). A stage that states
    /// any states every buffer resource of its program (a table, or [`BufferSource::Unknown`] with why); empty for a
    /// source that states none, whose buffers a consumer takes as [`StageBinding::buffer`] says: unknown, with the
    /// reason it prints.
    pub buffers: Vec<BufferBinding>,
    /// The constant buffers the source binds at other than their declared size ([`ConstantBufferBinding`]); a buffer
    /// with no entry is bound at its declared size.
    pub constant_buffers: Vec<ConstantBufferBinding>,
    pub outputs: Vec<OutputBinding>,
}
/// `core.shader_binding`, on a material entity: the shader programs it is drawn with, one per stage, what each reads
/// and writes, and its render state. Everything a program reads has a role, never a frozen value: textures are the
/// entities bound, constants are roles with the material's own words as stored, views and frames are named, not
/// valued. What can't be resolved is `Unknown` with the reason, or `Missing`, so nothing is silently made up.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ShaderBinding {
    /// At most one binding per stage.
    pub stages: Vec<StageBinding>,
    pub state: RenderState,
}
impl ShaderBinding {
    /// The binding of this stage.
    pub fn stage(&self, stage: Stage) -> Option<&StageBinding> {
        self.stages.iter().find(|s| s.stage == stage)
    }
}
impl StageBinding {
    /// The `stage` program `shader` with nothing bound yet: no variant, inputs, constants, textures, samplers, buffers,
    /// constant buffers or outputs. A source fills what it states: `StageBinding { textures, ..StageBinding::new(stage,
    /// shader) }`.
    pub fn new(stage: Stage, shader: Entity) -> StageBinding {
        StageBinding {
            stage,
            variant: None,
            shader,
            inputs: Vec::new(),
            constants: Vec::new(),
            textures: Vec::new(),
            samplers: Vec::new(),
            buffers: Vec::new(),
            constant_buffers: Vec::new(),
            outputs: Vec::new(),
        }
    }

    /// The exact uniform words the source states for this material. Runtime roles and unknown
    /// fields contribute no words, including padding: a consumer may specialise only this map.
    pub fn known_words(&self) -> std::collections::BTreeMap<(ResourceId, u32), u32> {
        let mut out = std::collections::BTreeMap::new();
        for constant in &self.constants {
            let words = match &constant.role {
                ConstantRole::Material(words) | ConstantRole::Default { words, .. } => words,
                _ => continue,
            };
            for (index, word) in words.iter().enumerate() {
                if let Ok(index) = u32::try_from(index)
                    && let Some(offset) = index.checked_mul(4)
                    && offset < constant.size
                    && let Some(offset) = constant.offset.checked_add(offset)
                {
                    out.insert((constant.resource, offset), *word);
                }
            }
        }
        out
    }

    /// The state the stage states for sampler `resource` ([`StageBinding::samplers`]).
    pub fn sampler_state(&self, resource: ResourceId) -> Option<&SamplerState> {
        self.samplers
            .iter()
            .find(|s| s.resource == resource)
            .map(|s| &s.state)
    }

    /// The constants whose role is [`ConstantRole::Unknown`], by name (or offset when the source names none) and why.
    /// A consumer that evaluates the stage uses it to refuse, or to say which values it left out, where zero is not a
    /// neutral value (a scale, say): it never reads an unknown constant as zero without naming it.
    pub fn unknown_constants(&self) -> impl Iterator<Item = (String, &str)> {
        self.constants.iter().filter_map(|c| match &c.role {
            ConstantRole::Unknown { why } => Some((
                c.name.clone().unwrap_or_else(|| format!("+{}", c.offset)),
                why.as_str(),
            )),
            _ => None,
        })
    }

    /// The lanes the program writes that no output binding states, per output of `interface` (the stage's program's):
    /// written as its source states it, the D3D signature's lanes less those it never writes (DXBC's `OSGN`, DXIL's
    /// `OSG1`), in the output's own lanes (bit k its lane k). An output whose source states no written lanes (no D3D
    /// signature: MojoShader's, SPIR-V's and GLSL's programs) has none here, nor a system value other than a render
    /// target (a depth, a coverage mask), which states what it is itself.
    pub fn unbound_written_lanes<'i>(&self, interface: &'i Interface) -> Vec<(&'i Label, u8)> {
        let mut out = Vec::new();
        for v in &interface.outputs {
            if v.system.is_some_and(|s| !matches!(s, SystemValue::Target(_))) {
                continue;
            }
            let Some(d3d) = v.provenance.d3d else {
                continue;
            };
            // the element's own lanes: the register's from its first, as many as it is wide
            let first = d3d.mask.trailing_zeros();
            let width = u32::from(v.value.width).min(4);
            let written = ((d3d.mask & !d3d.read_write_mask) >> first) & ((1u8 << width) - 1);
            let bound = self
                .outputs
                .iter()
                .filter(|o| o.label == v.label)
                .fold(0u8, |acc, o| acc | o.lanes);
            let unbound = written & !bound;
            if unbound != 0 {
                out.push((&v.label, unbound));
            }
        }
        out
    }

    /// The binding agrees with its program: a material's ([`BindingPlace::Material`]) binds no target of a render graph
    /// and states no sampler of its own.
    pub(crate) fn verify_in(&self, w: &crate::World, place: BindingPlace) -> Result<(), String> {
        let shader = w
            .get::<Shader>(self.shader)
            .ok_or_else(|| format!("the {:?} stage's shader entity has no core.shader", self.stage))?;
        let interface: &Interface = &shader.interface;
        let at = |detail: String| format!("{:?} stage: {detail}", self.stage);
        if interface.stage != self.stage {
            return Err(at(format!("its shader is a {:?} program", interface.stage)));
        }
        for (n, i) in self.inputs.iter().enumerate() {
            let Some(varying) = interface.inputs.iter().find(|v| v.label == i.label) else {
                return Err(at(format!(
                    "input {}{} is not in the shader",
                    i.label.name, i.label.index
                )));
            };
            if self.inputs[..n].iter().any(|before| before.label == i.label) {
                return Err(at(format!(
                    "input {}{} is bound twice",
                    i.label.name, i.label.index
                )));
            }
            if let super::InputRole::PreviousOr { fallback, why } = &i.role {
                if self.stage != Stage::Pixel
                    || varying.system.is_some()
                    || varying.value.scalar != ScalarType::Float
                {
                    return Err(at("a replacement input must be a float pixel varying".into()));
                }
                if why.trim().is_empty() {
                    return Err(at("a replacement input has no reason".into()));
                }
                fallback.check().map_err(at)?;
            }
        }
        for (n, o) in self.outputs.iter().enumerate() {
            let Some(v) = interface.outputs.iter().find(|v| v.label == o.label) else {
                return Err(at(format!(
                    "output {}{} is not in the shader",
                    o.label.name, o.label.index
                )));
            };
            if o.lanes == 0 || u32::from(o.lanes) >> v.value.width != 0 {
                return Err(at(format!(
                    "output {}{} has {} lanes, not the mask {:#x}",
                    o.label.name, o.label.index, v.value.width, o.lanes
                )));
            }
            if let Some(Err(why)) = o.role.scalar_encoding().map(|e| e.check()) {
                return Err(at(format!("output {}{}: {why}", o.label.name, o.label.index)));
            }
            if let OutputRole::Unknown { why } = &o.role
                && why.trim().is_empty()
            {
                return Err(at(format!(
                    "output {}{} is Unknown with no why",
                    o.label.name, o.label.index
                )));
            }
            // one label may carry several roles, each on its own lanes
            if let Some(before) = self.outputs[..n]
                .iter()
                .find(|before| before.label == o.label && before.lanes & o.lanes != 0)
            {
                return Err(at(format!(
                    "output {}{} has two roles on lanes {:#x}",
                    o.label.name,
                    o.label.index,
                    before.lanes & o.lanes
                )));
            }
        }
        // a pixel program's outputs are the draw's targets: each lane it writes has a role, or is Unknown with why. Any
        // other stage's outputs are the next stage's inputs, bound there.
        if self.stage == Stage::Pixel
            && let Some((label, lanes)) = self.unbound_written_lanes(interface).first()
        {
            return Err(at(format!(
                "output {}{} lanes {lanes:#06b} are written and have no binding",
                label.name, label.index
            )));
        }
        for c in &self.constants {
            let Some(ResourceKind::ConstantBuffer { layout }) =
                interface.resource(c.resource).map(|r| &r.kind)
            else {
                return Err(at(format!(
                    "constant resource {} is not a constant buffer",
                    c.resource.0
                )));
            };
            if c.size == 0 || c.offset.checked_add(c.size).is_none_or(|end| end > layout.size) {
                return Err(at(format!(
                    "constant of {} bytes at {} is outside buffer {} of {} bytes",
                    c.size, c.offset, c.resource.0, layout.size
                )));
            }
            let named = c.name.as_deref().map_or(String::new(), |n| format!("{n} "));
            match (c.role.is_matrix(), &c.lines) {
                (true, None) => {
                    return Err(at(format!(
                        "constant {named}at {} is a matrix ({:?}) whose lines are not stated",
                        c.offset, c.role
                    )));
                }
                (true, Some(MatrixLines::Unshown(Unshown::Unexamined { why }))) if why.trim().is_empty() => {
                    return Err(at(format!(
                        "constant {named}at {} is a matrix whose lines are unshown with no reason",
                        c.offset
                    )));
                }
                (false, Some(lines)) => {
                    return Err(at(format!(
                        "constant {named}at {} states lines ({lines:?}) for a role that is no matrix ({:?})",
                        c.offset, c.role
                    )));
                }
                _ => {}
            }
            if let ConstantRole::AlphaReference { value: r, .. } = c.role
                && (!r.is_finite() || c.size != 4)
            {
                return Err(at(format!(
                    "the alpha reference {r} at {} is not one finite float ({} bytes)",
                    c.offset, c.size
                )));
            }
            if let ConstantRole::Material(words) = &c.role
                && words.len() as u64 * 4 > u64::from(c.size)
            {
                return Err(at(format!(
                    "{} material words for a constant of {} bytes at {}",
                    words.len(),
                    c.size,
                    c.offset
                )));
            }
            if let ConstantRole::Default { words, why } = &c.role {
                if words.len() as u64 * 4 > u64::from(c.size) {
                    return Err(at(format!(
                        "{} default words for a constant of {} bytes at {}",
                        words.len(),
                        c.size,
                        c.offset
                    )));
                }
                if why.trim().is_empty() {
                    return Err(at(format!(
                        "the default of the constant at {} says no why",
                        c.offset
                    )));
                }
            }
        }
        // the bytes of a constant buffer belong to one constant
        let mut spans: Vec<(u32, u32, u32)> = self
            .constants
            .iter()
            .map(|c| (c.resource.0, c.offset, c.offset + c.size))
            .collect();
        spans.sort_unstable();
        if let Some(pair) = spans.windows(2).find(|p| p[0].0 == p[1].0 && p[1].1 < p[0].2) {
            return Err(at(format!(
                "constants overlap in buffer {}: bytes {}..{} and {}..{}",
                pair[0].0, pair[0].1, pair[0].2, pair[1].1, pair[1].2
            )));
        }
        for (n, t) in self.textures.iter().enumerate() {
            if let TextureSource::Missing { why } = &t.source
                && why.trim().is_empty()
            {
                return Err(at(format!(
                    "texture slot {} is missing without a reason",
                    t.resource.0
                )));
            }
            let Some(ResourceKind::Texture { dim, arrayed, .. }) =
                interface.resource(t.resource).map(|r| &r.kind)
            else {
                return Err(at(format!("resource {} is not a texture", t.resource.0)));
            };
            if self.textures[..n]
                .iter()
                .any(|before| before.resource == t.resource)
            {
                return Err(at(format!("texture slot {} is bound twice", t.resource.0)));
            }
            if place == BindingPlace::Material && matches!(t.source, TextureSource::Target { .. }) {
                return Err(at(format!(
                    "texture slot {} binds a render graph target, which only a step of a core.render_graph may",
                    t.resource.0
                )));
            }
            if let TextureSource::Frame(frame) = &t.source
                && *dim != frame.dim()
            {
                return Err(at(format!(
                    "texture slot {} is a {dim:?} texture and binds the frame's {frame:?}, a {:?} image",
                    t.resource.0,
                    frame.dim()
                )));
            }
            if let Some(s) = t.sampler
                && !matches!(
                    interface.resource(s).map(|r| &r.kind),
                    Some(ResourceKind::Sampler { .. })
                )
            {
                return Err(at(format!("resource {} is not a sampler", s.0)));
            }
            if let TextureSource::Texture { texture, .. } = &t.source {
                if !(w.has::<Texture>(*texture)
                    || w.has::<TextureLayers>(*texture)
                    || w.has::<TextureFile>(*texture))
                {
                    return Err(at(format!(
                        "texture slot {} binds an entity that is neither core.texture, core.texture_layers nor core.texture_file",
                        t.resource.0
                    )));
                }
                // a texture of several images is read as the dimension its shape is
                if let Some(layers) = w.get::<TextureLayers>(*texture)
                    && layers.shape.dimension() != (*dim, *arrayed)
                {
                    return Err(at(format!(
                        "texture slot {} is a {dim:?} resource (arrayed {arrayed}) and binds a {:?} texture",
                        t.resource.0, layers.shape
                    )));
                }
            }
        }
        self.verify_samplers(interface, place).map_err(at)?;
        self.verify_buffers(w, interface, place).map_err(at)?;
        self.verify_constant_buffers(interface).map_err(at)
    }

    /// The samplers' states: each a sampler of the shader, once, and a state that agrees with itself
    /// ([`SamplerState::verify`]); a material's binding states none (its states are its textures').
    fn verify_samplers(&self, interface: &Interface, place: BindingPlace) -> Result<(), String> {
        if place == BindingPlace::Material
            && let Some(first) = self.samplers.first()
        {
            return Err(format!(
                "sampler {} states its own state, which only a step of a core.render_graph may (a material's sampler states are its textures')",
                first.resource.0
            ));
        }
        for (n, s) in self.samplers.iter().enumerate() {
            if !matches!(
                interface.resource(s.resource).map(|r| &r.kind),
                Some(ResourceKind::Sampler { .. })
            ) {
                return Err(format!("resource {} is not a sampler", s.resource.0));
            }
            if self.samplers[..n]
                .iter()
                .any(|before| before.resource == s.resource)
            {
                return Err(format!("sampler {} is stated twice", s.resource.0));
            }
            s.state
                .verify()
                .map_err(|why| format!("sampler {}: {why}", s.resource.0))?;
        }
        Ok(())
    }

    /// What buffer `resource` of the program holds: its entry, or, where the source states no buffers for the stage,
    /// unknown with that reason (never zeros without saying so).
    pub fn buffer(&self, resource: ResourceId) -> BufferSource {
        self.buffers
            .iter()
            .find(|b| b.resource == resource)
            .map(|b| b.source.clone())
            .unwrap_or_else(|| BufferSource::Unknown {
                why: "the source states no buffers for this stage".into(),
            })
    }

    /// The constant buffers the source states a binding for: each a constant buffer of the shader, once, bound at a whole
    /// number of rows no smaller than the program declares.
    fn verify_constant_buffers(&self, interface: &Interface) -> Result<(), String> {
        for (n, c) in self.constant_buffers.iter().enumerate() {
            let Some(ResourceKind::ConstantBuffer { layout }) =
                interface.resource(c.resource).map(|r| &r.kind)
            else {
                return Err(format!("resource {} is not a constant buffer", c.resource.0));
            };
            if self.constant_buffers[..n]
                .iter()
                .any(|before| before.resource == c.resource)
            {
                return Err(format!("constant buffer {} is bound twice", c.resource.0));
            }
            if let Some(bytes) = c.bound_size
                && (bytes % 16 != 0 || bytes < layout.size)
            {
                return Err(format!(
                    "constant buffer {} is bound at {bytes} bytes: not a whole number of 16-byte rows, or smaller than the {} the program declares",
                    c.resource.0, layout.size
                ));
            }
        }
        Ok(())
    }

    /// The bytes the constant buffer `resource` is bound with where the source states a size, else `None` (its
    /// declared size).
    pub fn bound_size(&self, resource: ResourceId) -> Option<u32> {
        self.constant_buffers
            .iter()
            .find(|c| c.resource == resource)
            .and_then(|c| c.bound_size)
    }

    /// How many matrices the joint palette constant holds as the program reads it: the stage's
    /// [`ObjectParameter::BonePalette`] constant held as rows (three 16-byte lines a matrix, 48 bytes), at its size or, where
    /// the source binds its buffer larger than the program declares ([`Self::bound_size`]), the bytes from its offset to the
    /// bound size, whichever is more. `None` where the stage has no such constant, or holds it as columns or does not show
    /// which (the lab and the census fill rows only).
    pub fn bone_palette_matrices(&self) -> Option<u32> {
        let c = self.constants.iter().find(|c| {
            matches!(c.role, ConstantRole::Object(ObjectParameter::BonePalette))
                && matches!(c.lines, Some(MatrixLines::Rows))
        })?;
        let bound = self
            .bound_size(c.resource)
            .map_or(0, |b| b.saturating_sub(c.offset));
        Some(c.size.max(bound) / 48)
    }

    /// The buffer slots: each a buffer of the shader, bound once, a matrix table of 16-byte elements, an instance
    /// table whose records fit its stride and name a matrix table of this stage, a light table that agrees with
    /// itself and its buffer's elements, in a world whose lights of its kind have their unit (`core.light_unit`, which
    /// its colours are in), and light lists that agree with themselves and their buffers, a lookup and an index list
    /// together, with a light table of each kind the lookup counts; a stage that states any buffer states every buffer
    /// of its program.
    fn verify_buffers(
        &self,
        w: &crate::World,
        interface: &Interface,
        place: BindingPlace,
    ) -> Result<(), String> {
        let kind = |id: ResourceId| match interface.resource(id).map(|r| &r.kind) {
            Some(ResourceKind::Buffer(kind)) => Some(*kind),
            _ => None,
        };
        let lists: Vec<&super::LightListPart> = self
            .buffers
            .iter()
            .filter_map(|b| match &b.source {
                BufferSource::LightLists(part) => Some(part),
                _ => None,
            })
            .collect();
        if !lists.is_empty() {
            let lookups: Vec<_> = lists
                .iter()
                .filter_map(|p| match p {
                    super::LightListPart::Lookup(l) => Some(l),
                    super::LightListPart::Indices(_) => None,
                })
                .collect();
            let [lookup] = lookups.as_slice() else {
                return Err(format!(
                    "light lists with {} lookups: a stage's lists are one lookup and one index list",
                    lookups.len()
                ));
            };
            if lists.len() != 2 {
                return Err(format!(
                    "{} light list buffers: a stage's lists are one lookup and one index list",
                    lists.len()
                ));
            }
            for (counted, _) in &lookup.counts {
                if !self
                    .buffers
                    .iter()
                    .any(|b| matches!(&b.source, BufferSource::Lights(t) if t.kind == *counted))
                {
                    return Err(format!(
                        "light lists count {counted:?} lights and the stage binds no {counted:?} light table"
                    ));
                }
            }
        }
        for (n, b) in self.buffers.iter().enumerate() {
            let Some(buffer) = kind(b.resource) else {
                return Err(format!("resource {} is not a buffer", b.resource.0));
            };
            if self.buffers[..n]
                .iter()
                .any(|before| before.resource == b.resource)
            {
                return Err(format!("buffer slot {} is bound twice", b.resource.0));
            }
            match &b.source {
                BufferSource::Unknown { why } if why.is_empty() => {
                    return Err(format!(
                        "buffer slot {} is unknown and says not why",
                        b.resource.0
                    ));
                }
                BufferSource::Unknown { .. } => {}
                BufferSource::Graph(_) if place == BindingPlace::Material => {
                    return Err(format!(
                        "buffer slot {} binds a render graph buffer, which only a step of a core.render_graph may",
                        b.resource.0
                    ));
                }
                BufferSource::Graph(_) => {}
                BufferSource::LightLists(part) => {
                    let stride = match buffer {
                        BufferKind::Structured { stride } => Some(stride),
                        _ => None,
                    };
                    part.verify(stride)
                        .map_err(|why| format!("buffer slot {}: {why}", b.resource.0))?;
                }
                BufferSource::Lights(table) => {
                    let stride = match buffer {
                        BufferKind::Structured { stride } => Some(stride),
                        _ => None,
                    };
                    table
                        .verify(stride)
                        .map_err(|why| format!("buffer slot {}: {why}", b.resource.0))?;
                    if w.resource::<crate::LightUnit>().is_none()
                        && w.iter::<crate::components::Light>().any(|(_, l)| table.holds(l))
                    {
                        return Err(format!(
                            "buffer slot {} is a light table in a world whose lights have no core.light_unit: its \
                             colours have no value",
                            b.resource.0
                        ));
                    }
                }
                BufferSource::Table(
                    BufferTable::ObjectMatrices { rows }
                    | BufferTable::HeaderedMatrices { rows }
                    | BufferTable::SkinnedMatrices { rows, .. },
                ) => {
                    if !(3..=4).contains(rows) {
                        return Err(format!(
                            "buffer slot {} holds matrices of {rows} rows, not 3 or 4",
                            b.resource.0
                        ));
                    }
                    if let BufferKind::Structured { stride } = buffer
                        && stride != 16
                    {
                        return Err(format!(
                            "buffer slot {} holds matrix rows of 16 bytes and has elements of {stride}",
                            b.resource.0
                        ));
                    }
                    if let BufferSource::Table(BufferTable::SkinnedMatrices {
                        joint_stride, prefix, ..
                    }) = &b.source
                    {
                        if joint_stride < rows {
                            return Err(format!(
                                "buffer slot {} holds joints {joint_stride} elements apart with {rows} rows each",
                                b.resource.0
                            ));
                        }
                        if *prefix == 0 {
                            return Err(format!(
                                "buffer slot {} holds skinned matrices with no prefix element to say what the first one holds",
                                b.resource.0
                            ));
                        }
                    }
                }
                BufferSource::Table(BufferTable::Instances {
                    stride,
                    matrix_start,
                    matrices,
                }) => {
                    if *stride == 0 || matrix_start >= stride {
                        return Err(format!(
                            "buffer slot {} holds instance records of {stride} words and names word {matrix_start}",
                            b.resource.0
                        ));
                    }
                    if let BufferKind::Structured { stride: bytes } = buffer
                        && bytes != u32::from(*stride) * 4
                    {
                        return Err(format!(
                            "buffer slot {} holds instance records of {stride} words and has elements of {bytes} bytes",
                            b.resource.0
                        ));
                    }
                    let is_matrices = |other: &BufferBinding| {
                        other.resource == *matrices
                            && matches!(
                                other.source,
                                BufferSource::Table(
                                    BufferTable::ObjectMatrices { .. }
                                        | BufferTable::HeaderedMatrices { .. }
                                        | BufferTable::SkinnedMatrices { .. }
                                )
                            )
                    };
                    if !self.buffers.iter().any(is_matrices) {
                        return Err(format!(
                            "buffer slot {} names slot {} for its matrices, which is no matrix table of this stage",
                            b.resource.0, matrices.0
                        ));
                    }
                }
            }
        }
        if !self.buffers.is_empty()
            && let Some(r) = interface.resources.iter().find(|r| {
                matches!(r.kind, ResourceKind::Buffer(_)) && !self.buffers.iter().any(|b| b.resource == r.id)
            })
        {
            return Err(format!(
                "buffer slot {} has no entry: a stage that states buffers states every one (a table, or unknown with \
                 why)",
                r.id.0
            ));
        }
        Ok(())
    }
}
impl Component for ShaderBinding {
    const NAME: &'static str = "core.shader_binding";
    const GEOMETRY: crate::Geometry = crate::Geometry::None;
    fn to_json(&self) -> Result<Option<Value>, JsonError> {
        crate::json::to_value(self).map(Some)
    }
    fn verify(&self, _e: Entity, w: &crate::World) -> Result<(), String> {
        for (i, s) in self.stages.iter().enumerate() {
            if let Some(k) = &s.variant {
                if k.field.is_empty() {
                    return Err(format!("the {:?} stage's variant key names no field", s.stage));
                }
                if let Some(p) = k.parts.iter().enumerate().find_map(|(n, p)| {
                    k.parts[..n]
                        .iter()
                        .any(|before| before.name == p.name)
                        .then_some(&p.name)
                }) {
                    return Err(format!(
                        "the variant key {} = {} describes {p:?} twice",
                        k.field, k.value
                    ));
                }
                // the stages of one variant describe it the same way
                if let Some(other) = self.stages[..i].iter().find(|o| {
                    o.variant
                        .as_ref()
                        .is_some_and(|b| b.field == k.field && b.value == k.value && b.parts != k.parts)
                }) {
                    return Err(format!(
                        "the {:?} and {:?} stages of {} = {} describe it differently",
                        other.stage, s.stage, k.field, k.value
                    ));
                }
            }
            // a stage kind may repeat only under distinct values of one key
            for other in self.stages[..i].iter().filter(|o| o.stage == s.stage) {
                let distinct = match (&other.variant, &s.variant) {
                    (Some(a), Some(b)) => a.field == b.field && a.value != b.value,
                    _ => false,
                };
                if !distinct {
                    return Err(match &s.variant {
                        None => format!("the {:?} stage is bound twice", s.stage),
                        Some(k) => format!(
                            "the {:?} stage is bound twice for {} = {} (several need distinct values of one key)",
                            s.stage, k.field, k.value
                        ),
                    });
                }
            }
            s.verify_in(w, BindingPlace::Material)?;
        }
        self.state.verify()
    }
    fn references(&self, out: &mut Vec<Entity>) {
        for s in &self.stages {
            out.push(s.shader);
            for t in &s.textures {
                if let TextureSource::Texture { texture, .. } = &t.source {
                    out.push(*texture);
                }
            }
        }
    }
    fn apply_linear(&self, _l: &crate::Linear) -> crate::world::Linearity<Self> {
        crate::world::Linearity::Invariant
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::World;
    use crate::shader::Attribute;
    use crate::shader::{InputRole, KeyPart, Occluded, ScalarEncoding, SkinPrefix, ViewParameter};
    use iridia_interface::AddressMode;
    use iridia_interface::{
        BufferLayout, Constant, ConstantType, ResourceProvenance, SampleType, ScalarType, ShaderFormat,
        TextureDim, Value as Lanes, Varying, VaryingProvenance,
    };
    use iridia_interface::{Resource, ResourceKind as Kind};
    fn varying(name: &str, width: u8) -> Varying {
        Varying {
            label: Label {
                name: name.into(),
                index: 0,
            },
            system: None,
            value: Lanes {
                scalar: ScalarType::Float,
                width,
            },
            interp: None,
            used: true,
            provenance: VaryingProvenance::default(),
        }
    }
    fn resource(id: u32, kind: Kind) -> Resource {
        Resource {
            id: ResourceId(id),
            kind,
            count: 1,
            provenance: ResourceProvenance::default(),
        }
    }
    /// A pixel shader with a constant buffer (0), a texture (1) and a sampler (2).
    fn shader() -> Shader {
        Shader {
            format: ShaderFormat::Dxbc,
            bytecode: vec![0; 8],
            interface: Interface {
                stage: Stage::Pixel,
                inputs: vec![varying("TEXCOORD", 2)],
                outputs: vec![varying("SV_Target", 4)],
                resources: vec![
                    resource(
                        0,
                        Kind::ConstantBuffer {
                            layout: BufferLayout {
                                size: 32,
                                constants: vec![Constant {
                                    name: "tint".into(),
                                    offset: 0,
                                    ty: ConstantType::Vector(Lanes {
                                        scalar: ScalarType::Float,
                                        width: 4,
                                    }),
                                    default: None,
                                }],
                            },
                        },
                    ),
                    resource(
                        1,
                        Kind::Texture {
                            dim: TextureDim::D2,
                            arrayed: false,
                            multisampled: false,
                            sample: SampleType::Float,
                        },
                    ),
                    resource(2, Kind::Sampler { comparison: false }),
                ],
                facts: Default::default(),
            },
        }
    }
    fn binding(shader: Entity, texture: Entity) -> ShaderBinding {
        ShaderBinding {
            stages: vec![StageBinding {
                inputs: vec![InputBinding {
                    label: Label {
                        name: "TEXCOORD".into(),
                        index: 0,
                    },
                    role: InputRole::Stream(Attribute::TexCoord(0)),
                }],
                constants: vec![
                    ConstantBinding {
                        resource: ResourceId(0),
                        offset: 0,
                        size: 16,
                        name: Some("tint".into()),
                        role: ConstantRole::Material(vec![1.0f32.to_bits(); 4]),
                        lines: None,
                    },
                    ConstantBinding {
                        resource: ResourceId(0),
                        offset: 16,
                        size: 16,
                        name: None,
                        role: ConstantRole::Unknown {
                            why: "cb0[1] is not in the recipe".into(),
                        },
                        lines: None,
                    },
                ],
                textures: vec![TextureBinding {
                    resource: ResourceId(1),
                    sampler: Some(ResourceId(2)),
                    source: TextureSource::Texture {
                        texture,
                        sampler: SamplerState {
                            wrap: [Some(AddressMode::Repeat); 3],
                            ..SamplerState::default()
                        },
                    },
                }],
                outputs: vec![
                    OutputBinding {
                        label: Label {
                            name: "SV_Target".into(),
                            index: 0,
                        },
                        lanes: 0b0111,
                        role: OutputRole::Albedo,
                    },
                    OutputBinding {
                        label: Label {
                            name: "SV_Target".into(),
                            index: 0,
                        },
                        lanes: 0b1000,
                        role: OutputRole::Occlusion {
                            of: Occluded::AllLight,
                            encoding: ScalarEncoding::LINEAR,
                        },
                    },
                ],
                ..StageBinding::new(Stage::Pixel, shader)
            }],
            state: RenderState::default(),
        }
    }
    /// A vertex shader with a constant buffer (0) and structured buffers of 16 (10), 8 (11) and 12 (12) bytes an element.
    fn buffer_shader() -> Shader {
        let structured = |id, stride| {
            resource(
                id,
                Kind::Buffer(iridia_interface::BufferKind::Structured { stride }),
            )
        };
        Shader {
            format: ShaderFormat::Dxbc,
            bytecode: vec![0; 8],
            interface: Interface {
                stage: Stage::Vertex,
                inputs: Vec::new(),
                outputs: Vec::new(),
                resources: vec![
                    resource(
                        0,
                        Kind::ConstantBuffer {
                            layout: BufferLayout {
                                size: 16,
                                constants: Vec::new(),
                            },
                        },
                    ),
                    structured(10, 16),
                    structured(11, 8),
                    structured(12, 12),
                ],
                facts: Default::default(),
            },
        }
    }
    fn buffer_binding(shader: Entity, buffers: Vec<BufferBinding>) -> ShaderBinding {
        ShaderBinding {
            stages: vec![StageBinding {
                buffers,
                ..StageBinding::new(Stage::Vertex, shader)
            }],
            state: RenderState::default(),
        }
    }
    fn matrices(resource: u32, rows: u8) -> BufferBinding {
        BufferBinding {
            resource: ResourceId(resource),
            source: BufferSource::Table(BufferTable::ObjectMatrices { rows }),
        }
    }
    fn headered(resource: u32, rows: u8) -> BufferBinding {
        BufferBinding {
            resource: ResourceId(resource),
            source: BufferSource::Table(BufferTable::HeaderedMatrices { rows }),
        }
    }
    fn skinned(resource: u32, rows: u8, joint_stride: u8, prefix: u8) -> BufferBinding {
        BufferBinding {
            resource: ResourceId(resource),
            source: BufferSource::Table(BufferTable::SkinnedMatrices {
                rows,
                joint_stride,
                prefix,
                first: SkinPrefix::Translation,
            }),
        }
    }
    fn instances(resource: u32, stride: u8, matrix_start: u8, table: u32) -> BufferBinding {
        BufferBinding {
            resource: ResourceId(resource),
            source: BufferSource::Table(BufferTable::Instances {
                stride,
                matrix_start,
                matrices: ResourceId(table),
            }),
        }
    }
    /// A render graph's buffer is a buffer only a step of the graph binds: a material's binding that states one is refused,
    /// and the same stage verifies in a graph step's place.
    #[test]
    fn a_material_binds_no_render_graph_buffer() {
        let mut w = World::new();
        let (s, m) = (w.spawn(), w.spawn());
        w.insert(s, buffer_shader());
        let graph = |resource: u32| BufferBinding {
            resource: ResourceId(resource),
            source: BufferSource::Graph(0),
        };
        let b = buffer_binding(s, vec![graph(10), graph(11), graph(12)]);
        w.insert(m, b.clone());
        let err = w.get::<ShaderBinding>(m).unwrap().verify(m, &w).unwrap_err();
        assert!(
            err.contains(
                "buffer slot 10 binds a render graph buffer, which only a step of a core.render_graph may"
            ),
            "{err}"
        );
        assert_eq!(b.stages[0].verify_in(&w, BindingPlace::GraphStep), Ok(()));
    }
    /// The buffer slots: a matrix table and the instance records that index it verify, each rule broken once is named,
    /// and the roles serialize under their own names.
    #[test]
    fn buffer_slots_name_the_tables_the_program_indexes() {
        let mut w = World::new();
        let (s, m) = (w.spawn(), w.spawn());
        w.insert(s, buffer_shader());
        // every buffer named: 12 is unknown with a reason
        let rest = || BufferBinding {
            resource: ResourceId(12),
            source: BufferSource::Unknown {
                why: "not read here".into(),
            },
        };
        let good = vec![matrices(10, 3), instances(11, 2, 0, 10), rest()];
        w.insert(m, buffer_binding(s, good.clone()));
        assert_eq!(w.get::<ShaderBinding>(m).unwrap().verify(m, &w), Ok(()));
        let json = w.get::<ShaderBinding>(m).unwrap().to_json().unwrap().unwrap();
        assert_eq!(
            json["stages"][0]["buffers"][0]["source"],
            serde_json::json!({"table": {"object_matrices": {"rows": 3}}})
        );
        assert_eq!(
            json["stages"][0]["buffers"][1]["source"],
            serde_json::json!({"table": {"instances": {"stride": 2, "matrix_start": 0, "matrices": 10}}})
        );
        let unknown = |why: &str| BufferBinding {
            resource: ResourceId(12),
            source: BufferSource::Unknown { why: why.into() },
        };
        let cases: Vec<(Vec<BufferBinding>, &str)> = vec![
            (vec![matrices(0, 3)], "is not a buffer"),
            (vec![matrices(99, 3)], "is not a buffer"),
            (vec![matrices(10, 3), matrices(10, 4)], "bound twice"),
            (vec![matrices(10, 5)], "not 3 or 4"),
            (vec![matrices(11, 3)], "has elements of 8"),
            (vec![matrices(10, 3), instances(11, 2, 2, 10)], "names word 2"),
            (vec![matrices(10, 3), instances(11, 0, 0, 10)], "names word 0"),
            (
                vec![matrices(10, 3), instances(11, 3, 0, 10)],
                "has elements of 8 bytes",
            ),
            (
                vec![matrices(10, 3), instances(11, 2, 0, 12)],
                "no matrix table of this stage",
            ),
            (vec![instances(11, 2, 0, 10)], "no matrix table of this stage"),
            (
                vec![matrices(10, 3), instances(11, 2, 0, 11)],
                "no matrix table of this stage",
            ),
            (vec![unknown("")], "says not why"),
        ];
        for (buffers, message) in cases {
            w.insert(m, buffer_binding(s, buffers.clone()));
            let err = w.get::<ShaderBinding>(m).unwrap().verify(m, &w).unwrap_err();
            assert!(err.contains(message), "{buffers:?}: {err}");
        }
        // an unknown buffer with a reason, beside a table, is a binding
        w.insert(
            m,
            buffer_binding(
                s,
                vec![
                    matrices(10, 4),
                    instances(11, 2, 0, 10),
                    unknown("the engine fills it"),
                ],
            ),
        );
        assert_eq!(w.get::<ShaderBinding>(m).unwrap().verify(m, &w), Ok(()));
        // a headered table is a matrix table: records may name it, and it has the same rows and element rules
        w.insert(
            m,
            buffer_binding(s, vec![headered(10, 3), instances(11, 2, 1, 10), rest()]),
        );
        assert_eq!(w.get::<ShaderBinding>(m).unwrap().verify(m, &w), Ok(()));
        let json = w.get::<ShaderBinding>(m).unwrap().to_json().unwrap().unwrap();
        assert_eq!(
            json["stages"][0]["buffers"][0]["source"],
            serde_json::json!({"table": {"headered_matrices": {"rows": 3}}})
        );
        // a skinned block is a matrix table too, with the joints no closer than their rows and a prefix to describe
        w.insert(
            m,
            buffer_binding(s, vec![skinned(10, 3, 3, 3), instances(11, 2, 1, 10), rest()]),
        );
        assert_eq!(w.get::<ShaderBinding>(m).unwrap().verify(m, &w), Ok(()));
        let json = w.get::<ShaderBinding>(m).unwrap().to_json().unwrap().unwrap();
        assert_eq!(
            json["stages"][0]["buffers"][0]["source"],
            serde_json::json!({"table": {"skinned_matrices": {
                "rows": 3, "joint_stride": 3, "prefix": 3, "first": "translation"
            }}})
        );
        for (buffers, message) in [
            (
                vec![skinned(10, 3, 2, 3), instances(11, 2, 1, 10), rest()],
                "elements apart with 3 rows",
            ),
            (
                vec![skinned(10, 3, 3, 0), instances(11, 2, 1, 10), rest()],
                "no prefix element to say what the first one holds",
            ),
            (
                vec![skinned(10, 5, 5, 3), instances(11, 2, 1, 10), rest()],
                "not 3 or 4",
            ),
        ] {
            w.insert(m, buffer_binding(s, buffers.clone()));
            let err = w.get::<ShaderBinding>(m).unwrap().verify(m, &w).unwrap_err();
            assert!(err.contains(message), "{buffers:?}: {err}");
            // no message holds a run of spaces (a line continuation once ate a newline inside one)
            assert!(!err.contains("  "), "{err}");
        }
        // a stage that states buffers states every one; one that states none leaves each unknown with that reason
        w.insert(
            m,
            buffer_binding(s, vec![matrices(10, 3), instances(11, 2, 0, 10)]),
        );
        let err = w.get::<ShaderBinding>(m).unwrap().verify(m, &w).unwrap_err();
        assert!(err.contains("buffer slot 12 has no entry"), "{err}");
        w.insert(m, buffer_binding(s, Vec::new()));
        let binding = w.get::<ShaderBinding>(m).unwrap();
        assert_eq!(binding.verify(m, &w), Ok(()));
        assert_eq!(
            binding.stages[0].buffer(ResourceId(10)),
            BufferSource::Unknown {
                why: "the source states no buffers for this stage".into()
            }
        );
        w.insert(m, buffer_binding(s, good.clone()));
        assert_eq!(
            w.get::<ShaderBinding>(m).unwrap().stages[0].buffer(ResourceId(10)),
            BufferSource::Table(BufferTable::ObjectMatrices { rows: 3 })
        );
        for (buffers, message) in [
            (vec![headered(10, 5)], "not 3 or 4"),
            (vec![headered(11, 3)], "has elements of 8"),
            (vec![headered(10, 3), matrices(10, 3)], "bound twice"),
            (vec![headered(0, 3)], "is not a buffer"),
        ] {
            w.insert(m, buffer_binding(s, buffers.clone()));
            let err = w.get::<ShaderBinding>(m).unwrap().verify(m, &w).unwrap_err();
            assert!(err.contains(message), "{buffers:?}: {err}");
        }
    }
    /// The constant buffers a source binds larger than the program declares: a constant buffer of the shader, once, in whole
    /// rows and no smaller than the declaration (16 bytes here); `None` is the declared size.
    #[test]
    fn a_constant_buffer_is_bound_at_a_whole_number_of_rows_no_smaller_than_declared() {
        let mut w = World::new();
        let (s, m) = (w.spawn(), w.spawn());
        w.insert(s, buffer_shader());
        let bound = |resource: u32, bound_size| ConstantBufferBinding {
            resource: ResourceId(resource),
            bound_size,
        };
        let with = |constant_buffers: Vec<ConstantBufferBinding>| {
            let mut b = buffer_binding(s, Vec::new());
            b.stages[0].constant_buffers = constant_buffers;
            b
        };
        w.insert(m, with(vec![bound(0, Some(12_288))]));
        let binding = w.get::<ShaderBinding>(m).unwrap();
        assert_eq!(binding.verify(m, &w), Ok(()));
        assert_eq!(binding.stages[0].bound_size(ResourceId(0)), Some(12_288));
        let json = binding.to_json().unwrap().unwrap();
        assert_eq!(
            json["stages"][0]["constant_buffers"][0],
            serde_json::json!({"resource": 0, "bound_size": 12288})
        );
        // the joint palette constant's matrices: its size, or the bound size where the source states one; none when it is
        // held as columns
        let palette = |lines| ConstantBinding {
            resource: ResourceId(0),
            offset: 0,
            size: 96,
            name: None,
            role: ConstantRole::Object(ObjectParameter::BonePalette),
            lines,
        };
        let mut stage = binding.stages[0].clone();
        stage.constants = vec![palette(Some(MatrixLines::Rows))];
        assert_eq!(stage.bone_palette_matrices(), Some(256));
        stage.constant_buffers.clear();
        assert_eq!(stage.bone_palette_matrices(), Some(2));
        stage.constants = vec![palette(Some(MatrixLines::Columns))];
        assert_eq!(stage.bone_palette_matrices(), None);
        stage.constants.clear();
        assert_eq!(stage.bone_palette_matrices(), None);
        // the declared size, and a buffer with no entry
        w.insert(m, with(vec![bound(0, None)]));
        let binding = w.get::<ShaderBinding>(m).unwrap();
        assert_eq!(binding.verify(m, &w), Ok(()));
        assert_eq!(binding.stages[0].bound_size(ResourceId(0)), None);
        assert_eq!(binding.stages[0].bound_size(ResourceId(10)), None);
        for (buffers, message) in [
            (vec![bound(10, Some(64))], "is not a constant buffer"),
            (vec![bound(99, Some(64))], "is not a constant buffer"),
            (vec![bound(0, Some(32)), bound(0, None)], "bound twice"),
            (vec![bound(0, Some(40))], "not a whole number of 16-byte rows"),
            (
                vec![bound(0, Some(0))],
                "smaller than the 16 the program declares",
            ),
        ] {
            w.insert(m, with(buffers.clone()));
            let err = w.get::<ShaderBinding>(m).unwrap().verify(m, &w).unwrap_err();
            assert!(err.contains(message), "{buffers:?}: {err}");
        }
    }
    /// A world with a shader, a texture and a material carrying the binding built from them.
    fn world() -> (World, Entity, Entity, Entity) {
        let mut w = World::new();
        let (s, t, m) = (w.spawn(), w.spawn(), w.spawn());
        w.insert(s, shader());
        w.insert(
            t,
            TextureFile {
                path: "albedo.png".into(),
            },
        );
        w.insert(m, binding(s, t));
        (w, s, t, m)
    }
    #[test]
    fn an_unfilled_texture_retains_its_reason_and_cannot_omit_it() {
        let (w, _, _, material) = world();
        let mut binding = w.get::<ShaderBinding>(material).unwrap().clone();
        let reason = "engine texture t3 space 0: the runtime image is not stored in the material";
        binding.stages[0].textures[0].source = TextureSource::Missing { why: reason.into() };
        assert_eq!(binding.verify(material, &w), Ok(()));
        let json = serde_json::to_value(&binding).unwrap();
        assert_eq!(
            json["stages"][0]["textures"][0]["source"]["missing"]["why"],
            reason
        );
        for why in ["", "  \n"] {
            binding.stages[0].textures[0].source = TextureSource::Missing { why: why.into() };
            let error = binding.verify(material, &w).unwrap_err();
            assert!(
                error.contains("texture slot 1 is missing without a reason"),
                "{error}"
            );
        }
    }

    /// An output's encoding of power or root 0, or of a scale that isn't finite, is refused, naming the output.
    #[test]
    fn an_encoding_of_no_power_no_root_or_no_finite_scale_is_refused() {
        let one = 1f32.to_bits();
        for bad in [
            ScalarEncoding {
                power: 0,
                root: 1,
                scale_bits: one,
            },
            ScalarEncoding {
                power: 1,
                root: 0,
                scale_bits: one,
            },
            ScalarEncoding {
                power: 1,
                root: 1,
                scale_bits: f32::INFINITY.to_bits(),
            },
        ] {
            assert!(bad.check().is_err(), "{bad:?}");
            let (mut w, _, _, m) = world();
            let mut b = w.get::<ShaderBinding>(m).unwrap().clone();
            b.stages[0].outputs[1].role = OutputRole::Occlusion {
                of: Occluded::AllLight,
                encoding: bad,
            };
            w.insert(m, b);
            let err = w.get::<ShaderBinding>(m).unwrap().verify(m, &w).unwrap_err();
            assert!(err.contains("output SV_Target0: an encoding of"), "{err}");
        }
        assert_eq!(ScalarEncoding::square_of(0.95).check(), Ok(()));
        assert_eq!(ScalarEncoding::LINEAR.check(), Ok(()));
    }
    /// A matrix role's binding states how its lines hold the matrix, and no other role's does: either missing or
    /// misplaced is refused, naming the constant.
    #[test]
    fn a_matrix_role_states_its_lines_and_no_other_role_does() {
        let (mut w, _, _, m) = world();
        let verify = |w: &mut World, role: ConstantRole, lines: Option<MatrixLines>| {
            let mut b = w.get::<ShaderBinding>(m).unwrap().clone();
            b.stages[0].constants[0].role = role;
            b.stages[0].constants[0].lines = lines;
            w.insert(m, b);
            w.get::<ShaderBinding>(m).unwrap().verify(m, w)
        };
        let view_projection = ConstantRole::View(ViewParameter::ViewProjection);
        let err = verify(&mut w, view_projection.clone(), None).unwrap_err();
        assert!(
            err.contains("constant tint at 0 is a matrix") && err.contains("lines are not stated"),
            "{err}"
        );
        let unexamined = |why: &str| MatrixLines::Unshown(Unshown::Unexamined { why: why.into() });
        for lines in [
            MatrixLines::Rows,
            MatrixLines::Columns,
            MatrixLines::Unshown(Unshown::NotApplied),
            unexamined("no value graph"),
        ] {
            assert_eq!(verify(&mut w, view_projection.clone(), Some(lines)), Ok(()));
        }
        let err = verify(&mut w, view_projection.clone(), Some(unexamined(" "))).unwrap_err();
        assert!(err.contains("unshown with no reason"), "{err}");
        assert_eq!(
            verify(
                &mut w,
                ConstantRole::Object(ObjectParameter::BonePalette),
                Some(MatrixLines::Rows)
            ),
            Ok(())
        );
        let err = verify(
            &mut w,
            ConstantRole::Material(vec![0; 4]),
            Some(MatrixLines::Rows),
        )
        .unwrap_err();
        assert!(
            err.contains("states lines (Rows) for a role that is no matrix"),
            "{err}"
        );
        assert!(!ConstantRole::Object(ObjectParameter::TextureTransformRow(0)).is_matrix());
    }
    #[test]
    fn a_binding_names_what_it_refers_to_and_verifies() {
        let (w, s, t, m) = world();
        let b = w.get::<ShaderBinding>(m).unwrap();
        assert_eq!(b.verify(m, &w), Ok(()));
        let mut refs = Vec::new();
        b.references(&mut refs);
        assert_eq!(refs, [s, t]);
        let json = b.to_json().unwrap().unwrap();
        assert_eq!(json["stages"][0]["stage"], "pixel");
        // the role names what it occludes and how it is stored, the scale as a number
        assert_eq!(
            json["stages"][0]["outputs"][1]["role"],
            serde_json::json!({
                "occlusion": {"of": "all_light", "encoding": {"power": 1, "scale": 1.0}}
            })
        );
        assert_eq!(
            json["stages"][0]["constants"][1]["role"]["unknown"]["why"],
            "cb0[1] is not in the recipe"
        );
        assert!(b.stage(Stage::Vertex).is_none() && b.stage(Stage::Pixel).is_some());
    }
    /// Each rule of `verify`, broken once.
    #[test]
    fn each_broken_reference_is_named() {
        let (w, _, _, m) = world();
        let good = w.get::<ShaderBinding>(m).unwrap().clone();
        type Break = Box<dyn Fn(&mut ShaderBinding)>;
        let cases: Vec<(Break, &str)> = vec![
            (Box::new(|b| b.stages.push(b.stages[0].clone())), "bound twice"),
            (
                Box::new(|b| b.stages[0].inputs[0].label.index = 7),
                "input TEXCOORD7",
            ),
            (Box::new(|b| b.stages[0].outputs[0].lanes = 0b10000), "lanes"),
            (
                Box::new(|b| b.stages[0].constants[0].resource = ResourceId(1)),
                "not a constant buffer",
            ),
            (
                Box::new(|b| b.stages[0].constants[1].offset = 24),
                "outside buffer",
            ),
            (
                Box::new(|b| b.stages[0].constants[0].role = ConstantRole::Material(vec![0; 5])),
                "material words",
            ),
            (
                Box::new(|b| {
                    b.stages[0].constants[0].role = ConstantRole::Default {
                        words: vec![0; 5],
                        why: "a policy".into(),
                    }
                }),
                "default words",
            ),
            (
                Box::new(|b| {
                    b.stages[0].constants[0].role = ConstantRole::Default {
                        words: vec![0],
                        why: " ".into(),
                    }
                }),
                "says no why",
            ),
            (
                Box::new(|b| b.stages[0].textures[0].resource = ResourceId(0)),
                "not a texture",
            ),
            (
                Box::new(|b| b.stages[0].textures[0].sampler = Some(ResourceId(1))),
                "not a sampler",
            ),
            (
                Box::new(|b| {
                    let first = b.stages[0].inputs[0].clone();
                    b.stages[0].inputs.push(first);
                }),
                "input TEXCOORD0 is bound twice",
            ),
            (
                // the fixture's two roles on SV_Target0 are lanes 0b0111 and 0b1000: widening the second overlaps
                Box::new(|b| b.stages[0].outputs[1].lanes = 0b1100),
                "two roles on lanes 0x4",
            ),
            (
                Box::new(|b| b.stages[0].constants[1].offset = 8),
                "constants overlap in buffer 0: bytes 0..16 and 8..24",
            ),
            (
                Box::new(|b| {
                    let first = b.stages[0].textures[0].clone();
                    b.stages[0].textures.push(first);
                }),
                "texture slot 1 is bound twice",
            ),
            (
                Box::new(|b| {
                    b.stages[0].textures[0].source = TextureSource::Frame(FrameTexture::ReflectionProbe)
                }),
                "binds the frame's ReflectionProbe, a Cube image",
            ),
        ];
        for (break_it, expect) in cases {
            let mut b = good.clone();
            break_it(&mut b);
            let message = b.verify(m, &w).unwrap_err();
            assert!(message.contains(expect), "{expect}: {message}");
        }
        // an entity that is not a shader, a shader of another stage, a texture slot that binds a non-texture
        let mut b = good.clone();
        b.stages[0].shader = m;
        assert!(b.verify(m, &w).unwrap_err().contains("no core.shader"));
        let mut b = good.clone();
        b.stages[0].stage = Stage::Vertex;
        assert!(b.verify(m, &w).unwrap_err().contains("Pixel program"));
        let mut b = good;
        if let TextureSource::Texture { texture, .. } = &mut b.stages[0].textures[0].source {
            *texture = m;
        }
        assert!(b.verify(m, &w).unwrap_err().contains("neither core.texture"));
    }
    /// A pixel program's written lanes each have a binding: lanes its D3D signature writes and no binding states are
    /// refused, but not the lanes it never writes, nor a system value other than a target, nor a vertex program's
    /// outputs (the next stage's inputs); an Unknown output states why.
    #[test]
    fn a_pixel_programs_written_lanes_each_have_a_binding() {
        let (mut w, s, _, m) = world();
        let signature = |w: &mut World, read_write_mask: u8, system: Option<SystemValue>, stage: Stage| {
            let mut shader = w.get::<Shader>(s).unwrap().clone();
            shader.interface.stage = stage;
            let out = &mut shader.interface.outputs[0];
            out.system = system;
            out.provenance.d3d = Some(iridia_interface::D3dSignature {
                register: 0,
                mask: 0b1111,
                read_write_mask,
            });
            w.insert(s, shader);
        };
        let verify = |w: &World, b: &ShaderBinding| b.verify(m, w);
        let good = w.get::<ShaderBinding>(m).unwrap().clone();
        // the fixture binds lanes 0b0111 and 0b1000 of SV_Target0, all four written
        signature(&mut w, 0, None, Stage::Pixel);
        assert_eq!(verify(&w, &good), Ok(()));
        let mut rgb = good.clone();
        rgb.stages[0].outputs.truncate(1);
        assert_eq!(
            rgb.stages[0].unbound_written_lanes(&w.get::<Shader>(s).unwrap().interface),
            [(&good.stages[0].outputs[0].label, 0b1000)]
        );
        let err = verify(&w, &rgb).unwrap_err();
        assert!(
            err.contains("output SV_Target0 lanes 0b1000 are written and have no binding"),
            "{err}"
        );
        // the program never writes w
        signature(&mut w, 0b1000, None, Stage::Pixel);
        assert_eq!(verify(&w, &rgb), Ok(()));
        // a target stated as a system value is held the same; a depth is not a target
        signature(&mut w, 0, Some(SystemValue::Target(0)), Stage::Pixel);
        assert!(verify(&w, &rgb).is_err());
        signature(&mut w, 0, Some(SystemValue::Depth), Stage::Pixel);
        assert_eq!(verify(&w, &rgb), Ok(()));
        // a vertex program's outputs are bound as the pixel program's inputs
        signature(&mut w, 0, None, Stage::Vertex);
        let mut vertex = rgb.clone();
        vertex.stages[0].stage = Stage::Vertex;
        assert_eq!(verify(&w, &vertex), Ok(()));
        // the w lane Unknown, with why and without
        signature(&mut w, 0, None, Stage::Pixel);
        let mut unknown = good;
        unknown.stages[0].outputs[1].role = OutputRole::unknown("read by nothing examined");
        assert_eq!(verify(&w, &unknown), Ok(()));
        unknown.stages[0].outputs[1].role = OutputRole::unknown(" ");
        let err = verify(&w, &unknown).unwrap_err();
        assert!(err.contains("output SV_Target0 is Unknown with no why"), "{err}");
    }
    /// A frame image on a slot of its own dimension, and a constant colour on any, verify.
    #[test]
    fn a_frame_image_fits_the_slot_it_is_bound_to() {
        let (w, _, _, m) = world();
        let mut b = w.get::<ShaderBinding>(m).unwrap().clone();
        b.stages[0].textures[0].source = TextureSource::Frame(FrameTexture::SceneColour);
        assert_eq!(b.verify(m, &w), Ok(()));
        b.stages[0].textures[0].source = TextureSource::Default {
            value: [0.5; 4],
            why: "a constant".into(),
        };
        assert_eq!(b.verify(m, &w), Ok(()));
        assert_eq!(FrameTexture::LightProbeVolume.dim(), TextureDim::D3);
        assert_eq!(FrameTexture::ShadowMap.dim(), TextureDim::D2);
    }
    /// A render graph's target is a texture only a step of the graph binds: a material's binding that states one is
    /// refused, and the same stage verifies in a graph step's place.
    #[test]
    fn a_material_binds_no_render_graph_target() {
        let (w, _, _, m) = world();
        let mut b = w.get::<ShaderBinding>(m).unwrap().clone();
        b.stages[0].textures[0].source = TextureSource::Target {
            view: crate::render_graph::TargetView {
                target: 0,
                mip: 0,
                first_layer: 0,
                layers: 0,
            },
        };
        let err = b.verify(m, &w).unwrap_err();
        assert!(
            err.contains("binds a render graph target, which only a step of a core.render_graph may"),
            "{err}"
        );
        assert_eq!(b.stages[0].verify_in(&w, BindingPlace::GraphStep), Ok(()));
    }
    /// A sampler's state is stated by a graph step, for a sampler of the shader, once, with a state that agrees with
    /// itself; a material's binding states none (its sampler states are its textures'), and a stated state is found by
    /// its sampler.
    #[test]
    fn a_graph_step_states_its_samplers() {
        let (w, _, _, m) = world();
        let mut b = w.get::<ShaderBinding>(m).unwrap().clone();
        let shadow = SamplerState {
            wrap: [Some(AddressMode::Border); 3],
            compare: Some(iridia_interface::Compare::LessEqual),
            border: Some([0.0; 4]),
            lod: Some([0.0, 0.0]),
            ..SamplerState::default()
        };
        b.stages[0].samplers = vec![SamplerBinding {
            resource: ResourceId(2),
            state: shadow,
        }];
        assert_eq!(b.stages[0].verify_in(&w, BindingPlace::GraphStep), Ok(()));
        assert_eq!(b.stages[0].sampler_state(ResourceId(2)), Some(&shadow));
        assert_eq!(b.stages[0].sampler_state(ResourceId(1)), None);
        let err = b.verify(m, &w).unwrap_err();
        assert!(
            err.contains("sampler 2 states its own state, which only a step of a core.render_graph may"),
            "{err}"
        );
        let step = |samplers: Vec<SamplerBinding>| {
            let mut s = b.stages[0].clone();
            s.samplers = samplers;
            s.verify_in(&w, BindingPlace::GraphStep)
        };
        let at = |resource: u32, state: SamplerState| SamplerBinding {
            resource: ResourceId(resource),
            state,
        };
        // the texture is no sampler
        let err = step(vec![at(1, shadow)]).unwrap_err();
        assert!(err.contains("resource 1 is not a sampler"), "{err}");
        let err = step(vec![at(2, shadow), at(2, SamplerState::default())]).unwrap_err();
        assert!(err.contains("sampler 2 is stated twice"), "{err}");
        let reversed = SamplerState {
            lod: Some([1.0, 0.0]),
            ..shadow
        };
        let err = step(vec![at(2, reversed)]).unwrap_err();
        assert!(err.contains("sampler 2: level range"), "{err}");
        // the state belongs to the sampler: it serializes with it
        let json = serde_json::to_value(&b.stages[0].samplers[0]).unwrap();
        assert_eq!(json["resource"], serde_json::json!(2));
        assert_eq!(json["state"]["border"], serde_json::json!([0.0, 0.0, 0.0, 0.0]));
        assert_eq!(json["state"]["compare"], serde_json::json!("less_equal"));
    }
    /// A texture of several images fits a slot read as the dimension its shape is, and no other.
    #[test]
    fn a_layered_texture_fits_the_slot_of_its_shape() {
        use crate::{TexFormat, TextureLayers, TextureShape};
        let layers = |shape: TextureShape| TextureLayers {
            shape,
            width: 1,
            height: 1,
            format: TexFormat::Rgba8Unorm,
            levels: vec![(0..shape.layers_at(0)).map(|_| vec![0; 4]).collect()],
            color_space: crate::ColorSpace::Linear,
            role: crate::TexRole::Other,
            normal: None,
        };
        let (mut w, s, t, m) = world();
        let b = w.get::<ShaderBinding>(m).unwrap().clone();
        w.remove::<TextureFile>(t);
        // the fixture's slot is a plain 2D texture: no layered shape is that
        for shape in [
            TextureShape::Array { layers: 2 },
            TextureShape::Cube { cubes: 1 },
            TextureShape::Volume { depth: 1 },
        ] {
            w.insert(t, layers(shape));
            let why = b.verify(m, &w).unwrap_err();
            assert!(
                why.contains("is a D2 resource (arrayed false) and binds"),
                "{why}"
            );
        }
        // the slot read as an arrayed 2D texture takes an array and nothing else
        let Kind::Texture { arrayed, .. } = &mut w.get_mut::<Shader>(s).unwrap().interface.resources[1].kind
        else {
            panic!("the fixture's second resource is a texture");
        };
        *arrayed = true;
        w.insert(t, layers(TextureShape::Array { layers: 3 }));
        assert_eq!(b.verify(m, &w), Ok(()));
        w.insert(t, layers(TextureShape::Cube { cubes: 2 }));
        assert!(b.verify(m, &w).is_err());
    }
    /// A variant key names a field, describes each part once, and describes one variant the same way on all its stages.
    #[test]
    fn a_variant_keys_description_is_consistent() {
        let (w, _, _, m) = world();
        let part = |name: &str, value: u64| KeyPart {
            name: name.into(),
            value,
        };
        let key = |field: &str, value: u32, parts: Vec<KeyPart>| {
            Some(VariantKey {
                field: field.into(),
                value,
                parts,
            })
        };
        let good = w.get::<ShaderBinding>(m).unwrap().clone();
        let with = |a: Option<VariantKey>| {
            let mut b = good.clone();
            b.stages[0].variant = a;
            b
        };
        assert_eq!(
            with(key("f.variant", 0, vec![part("program", 1), part("outputs", 5)])).verify(m, &w),
            Ok(())
        );
        let message = with(key("", 0, Vec::new())).verify(m, &w).unwrap_err();
        assert!(message.contains("names no field"), "{message}");
        let message = with(key("f.variant", 0, vec![part("program", 1), part("program", 2)]))
            .verify(m, &w)
            .unwrap_err();
        assert!(message.contains("describes \"program\" twice"), "{message}");
        // two stages of one variant (a vertex and a pixel stage share the key) must describe it alike; the pixel
        // fixture stands for both, a second stage of another kind is built from it
        let mut b = with(key("f.variant", 3, vec![part("program", 1)]));
        let mut other = b.stages[0].clone();
        other.stage = Stage::Vertex;
        other.variant = key("f.variant", 3, vec![part("program", 2)]);
        b.stages.push(other);
        let message = b.verify(m, &w).unwrap_err();
        assert!(message.contains("describe it differently"), "{message}");
    }
    /// A stage kind repeats only under distinct values of one key: two pixel stages with keys `k = 1` and `k = 2` verify,
    /// the same value twice, a key and no key, and two different fields do not.
    #[test]
    fn a_stage_repeats_only_under_distinct_values_of_one_key() {
        let (w, _, _, m) = world();
        let good = w.get::<ShaderBinding>(m).unwrap().clone();
        let key = |field: &str, value: u32| {
            Some(VariantKey {
                field: field.to_owned(),
                value,
                parts: Vec::new(),
            })
        };
        let with = |a: Option<VariantKey>, b: Option<VariantKey>| {
            let mut x = good.clone();
            x.stages[0].variant = a;
            let mut y = x.stages[0].clone();
            y.variant = b;
            x.stages.push(y);
            x
        };
        assert_eq!(
            with(key("g.mesh.kind", 1), key("g.mesh.kind", 2)).verify(m, &w),
            Ok(())
        );
        let same = with(key("g.mesh.kind", 1), key("g.mesh.kind", 1))
            .verify(m, &w)
            .unwrap_err();
        assert!(same.contains("g.mesh.kind = 1"), "{same}");
        assert!(with(key("g.mesh.kind", 1), None).verify(m, &w).is_err());
        assert!(with(None, key("g.mesh.kind", 1)).verify(m, &w).is_err());
        assert!(
            with(None, None)
                .verify(m, &w)
                .unwrap_err()
                .contains("bound twice")
        );
        assert!(
            with(key("g.mesh.kind", 1), key("g.mesh.other", 2))
                .verify(m, &w)
                .is_err()
        );
        // a third stage repeating the first one's value is refused though it differs from the second's (it is compared
        // with every earlier stage of its kind)
        let mut three = with(key("g.mesh.kind", 1), key("g.mesh.kind", 2));
        let mut z = three.stages[0].clone();
        z.variant = key("g.mesh.kind", 1);
        three.stages.push(z);
        assert!(three.verify(m, &w).is_err());
    }
}