crcbl-render 0.11.0

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

use crcbl_hal::{
    Barriers, BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc,
    BindGroupLayoutEntry, BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource,
    BufferBarrier, BufferDesc, BufferHandle, BufferImageCopy, BufferUsage, ClearValue,
    ColorAttachment, ColorTargetState, ColorWrites, CommandEncoder, CommandEncoderDesc, CompareOp,
    ComputePassDesc, ComputePipelineHandle, CullMode, DepthBias, DepthStencilAttachment,
    DepthStencilState, Device, Extent3d, Format, GraphicsPipelineDesc, GraphicsPipelineHandle,
    HalError, ImageAspect, ImageBarrier, ImageDesc, ImageHandle, ImageSubresourceLayers,
    ImageSubresourceRange, ImageType, ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType,
    LoadOp, MemoryLocation, MultisampleState, Offset3d, PipelineLayoutDesc, PipelineLayoutHandle,
    PrimitiveState, QueueHandle, Rect2d, RenderPassDesc, ResourceState, SampleType, ShaderEntry,
    ShaderModuleDesc, ShaderStages, StoreOp, SubmitInfo, Viewport, check_portable_storage_buffers,
};
use crcbl_shaders::probe::ProbeVolume;
use crcbl_shaders::probe_visibility::{EXTENT, TEXEL_BYTES, texel_direction};
use crcbl_shaders::{PROBE_CAPTURE, PROBE_OCTAHEDRAL, Stage};
use glam::{Mat4, Vec3};

use crate::probe_visibility::{Occluder, Occluders, world_triangles};
use crate::texture::UploadedTexture;

/// Faces of a cube, and therefore tiles a probe takes in the atlas.
///
/// [`crate::shadow::POINT_FACES`]' number, and the same six directions in the
/// same order. Written out here rather than imported because this atlas is not
/// that one and a change to the shadow budget must not silently reshape a
/// visibility capture.
const FACES: u32 = 6;

/// Texels along one side of a cube-face tile.
///
/// **Four times the octahedral map's own resolution, and that ratio is the
/// point.** A layer's interior is
/// [`SIDE`](crcbl_shaders::probe_visibility::SIDE) texels across the whole
/// sphere, so one of its texels spans about `sqrt(4π / SIDE²)` steradians —
/// roughly thirteen degrees. The resolve takes one *point* sample of a face per
/// direction, so the distance it records is the distance in a direction up to
/// half a face texel away from the one the layer means: at ninety degrees
/// across `FACE` texels that is under a degree, a twentieth of the octahedral
/// texel the value stands for, and well inside
/// [`SURFACE_BIAS`](crcbl_shaders::probe_visibility::SURFACE_BIAS) for any
/// surface a metre-scale room puts near a probe. Doubling it again would halve
/// an error already an order under the quantity it perturbs, for four times the
/// pixels.
const FACE: u32 = 64;

/// Tiles across the distance atlas, and therefore its width in tiles.
const ATLAS_COLUMNS: u32 = 32;

/// The most tile rows one atlas holds. With [`ATLAS_COLUMNS`] and [`FACE`] this
/// is what caps the atlas at 2048 × 2048 — inside every device's
/// `max_image_2d`, and 16 MiB of `R32Float` beside as much `D32Float`, which is
/// a transient a load path can afford.
const ATLAS_ROWS: u32 = 32;

/// Probes captured in one atlas full of tiles.
///
/// A capture of more than this is split into chunks that share one encoder and
/// one submission and take turns in the same atlas — which is what keeps the
/// memory constant as the probe count grows, and is the shape the clipmap's
/// thousands of probes need.
const PROBES_PER_CHUNK: u32 = ATLAS_COLUMNS * ATLAS_ROWS / FACES;

/// The near plane of a face's frustum, in world units.
///
/// **Small on purpose**: geometry nearer than this is clipped away and the
/// texel it would have filled reads as open space, which is a probe that leaks
/// through the wall it is touching. A millimetre in a metre-scale world is
/// under any surface bias, and reversed-Z carries the resulting far/near ratio
/// without complaint because the depth here only decides *which* surface a
/// pixel keeps, never how far away it is — that number is the colour target's.
const NEAR: f32 = 1.0e-3;

/// The least a face's far plane may be, in world units, for a scene whose
/// geometry is all but on top of its probes.
const MIN_FAR: f32 = 1.0;

/// Threads per workgroup in `probe_octahedral.slang`.
const WORKGROUP: u32 = 64;

/// Bytes of `probe_capture.slang`'s `CaptureFace`: a `float4x4` and a `float4`.
const FACE_BLOCK_BYTES: u64 = 64 + 16;

/// Bytes of `probe_octahedral.slang`'s `OctahedralParams`: eight `uint`s.
const PARAMS_BYTES: u64 = 8 * 4;

/// Bytes one `float4x4` occupies in the face-matrix buffer.
const MATRIX_BYTES: u64 = 64;

/// The direction point-light face `face` looks along —
/// [`crate::shadow::face_axis`]' convention, which [`face_of`] indexes and
/// [`face_matrix`] looks down.
///
/// # Panics
///
/// If `face` is not one of [`FACES`] faces.
fn face_axis(face: u32) -> Vec3 {
    match face {
        0 => Vec3::X,
        1 => Vec3::NEG_X,
        2 => Vec3::Y,
        3 => Vec3::NEG_Y,
        4 => Vec3::Z,
        5 => Vec3::NEG_Z,
        _ => panic!("a cube has {FACES} faces, not a face {face}"),
    }
}

/// Which face of the cube around a probe a direction falls in.
///
/// The six 90° frusta partition space by the major axis, so this is exact
/// rather than approximate; `probe_octahedral.slang`'s header says why. **The
/// shader does not transcribe this**: the answer travels with the direction in
/// the table [`record`] uploads, on the same terms the octahedral mapping does
/// — one place writes the rule, and the device reads data.
#[must_use]
fn face_of(direction: [f32; 3]) -> u32 {
    let axis = direction.map(f32::abs);
    if axis[0] >= axis[1] && axis[0] >= axis[2] {
        return u32::from(direction[0] < 0.0);
    }
    if axis[1] >= axis[2] {
        return 2 + u32::from(direction[1] < 0.0);
    }
    4 + u32::from(direction[2] < 0.0)
}

/// A probe's world → face-clip matrix: a **90° perspective** down that face's
/// axis, reversed-Z.
///
/// [`crate::shadow::point_matrix`]'s arithmetic, including its choice of up
/// vector, and for its reasons: at 90° with a square aspect the frustum's edge
/// planes are the diagonals where the major axis changes, so six of these tile
/// the sphere exactly. `far` is shared by every face of every probe, because it
/// only has to reach past the scene.
///
/// # Panics
///
/// If `face` is not one of [`FACES`] faces.
fn face_matrix(origin: Vec3, face: u32, far: f32) -> Mat4 {
    let axis = face_axis(face);
    // Not parallel to the axis. Which of the two it is only has to be
    // consistent, because the matrix that draws the tile and the matrix that
    // reads it are this one.
    let up = if axis.y == 0.0 { Vec3::Y } else { Vec3::Z };
    let view = glam::camera::rh::view::look_at_mat4(origin, origin + axis, up);
    glam::camera::rh::proj::directx::perspective(std::f32::consts::FRAC_PI_2, 1.0, far, NEAR) * view
}

/// Where tile `tile` of a chunk sits in the atlas.
fn tile_rect(tile: u32) -> Rect2d {
    let column = tile % ATLAS_COLUMNS;
    let row = tile / ATLAS_COLUMNS;
    Rect2d {
        x: (column * FACE) as i32,
        y: (row * FACE) as i32,
        width: FACE,
        height: FACE,
    }
}

/// The far plane every face uses: far enough that no triangle in the scene is
/// clipped away from any probe.
///
/// The scene's own bounding box against the volume's, so it is a fact about
/// this capture rather than a constant that a large room would silently
/// outgrow. [`MIN_FAR`] is the floor for a degenerate scene, where the box is a
/// point.
fn scene_far(triangles: &[[[f32; 3]; 3]], probes: &[Vec3]) -> f32 {
    let mut low = [f32::MAX; 3];
    let mut high = [f32::MIN; 3];
    for triangle in triangles {
        for corner in triangle {
            for axis in 0..3 {
                low[axis] = low[axis].min(corner[axis]);
                high[axis] = high[axis].max(corner[axis]);
            }
        }
    }
    let mut far = MIN_FAR;
    for probe in probes {
        // The farthest corner of the box from this probe, which is the farthest
        // point of it: for each axis, whichever end is further away.
        let mut reach = 0.0f32;
        for axis in 0..3 {
            let span = (probe[axis] - low[axis])
                .abs()
                .max((probe[axis] - high[axis]).abs());
            reach += span * span;
        }
        far = far.max(reach.sqrt());
    }
    // A hair past the box, so a triangle exactly on the far plane is kept.
    far * 1.01
}

/// Where the probe in each row of `volume`'s table stands — entry `i` is row
/// `i`, which is also layer `i` of the image.
///
/// **The clipmap's levels one after another, finest first**, each of them
/// `x`-fastest within itself and **wrapped by that level's scroll offset**.
/// That is
/// [`ProbeVolume::row`](crcbl_shaders::probe::ProbeVolume::row)'s order and
/// `mesh.slang`'s `probe_row` reads it, which is what makes a row and a layer
/// one probe across the whole volume rather than only within a level — and what
/// makes a scrolled level's rows still name the probes they held.
///
/// Indexed by row rather than pushed in cell order, because a scrolled level's
/// cell order is not its row order: cell `(0, 0, 0)` of a level that has stepped
/// once along `x` stands in the row cell `(1, 0, 0)` had.
fn probe_positions(volume: &ProbeVolume) -> Vec<Vec3> {
    let mut positions = vec![Vec3::ZERO; volume.total() as usize];
    for level in 0..volume.level_count() {
        for z in 0..volume.counts[2].max(1) {
            for y in 0..volume.counts[1].max(1) {
                for x in 0..volume.counts[0].max(1) {
                    let cell = [x, y, z];
                    let row = volume.row(level, cell) as usize;
                    if let Some(slot) = positions.get_mut(row) {
                        *slot = Vec3::from_array(volume.position(level, cell));
                    }
                }
            }
        }
    }
    positions
}

/// The row pitch of one layer of the moments buffer, in **bytes**: at least a
/// row of texels, on the device's copy alignment, and a whole number of texels.
///
/// [`crate::texture`]'s `padded_row_pitch` for the same reason it exists there
/// — the copy expresses its pitch in texels, so a byte pitch that is not
/// divisible by the texel size cannot be expressed at all.
fn padded_row_pitch(row_bytes: u64, texel: u64, alignment: u64) -> u64 {
    let mut a = texel;
    let mut b = alignment;
    while b != 0 {
        (a, b) = (b, a % b);
    }
    let step = texel / a * alignment;
    row_bytes.next_multiple_of(step.max(1))
}

/// Everything [`capture`] created, so one path releases it whether the
/// capture succeeded or failed part-way.
#[derive(Default)]
struct Transients {
    buffers: Vec<BufferHandle>,
    images: Vec<ImageHandle>,
    views: Vec<ImageViewHandle>,
    bind_groups: Vec<BindGroupHandle>,
    bind_group_layouts: Vec<BindGroupLayoutHandle>,
    pipeline_layouts: Vec<PipelineLayoutHandle>,
    graphics: Vec<GraphicsPipelineHandle>,
    compute: Vec<ComputePipelineHandle>,
}

impl Transients {
    /// Releases everything, dependants before what they name. The device must
    /// be idle.
    fn run(self, device: &dyn Device) {
        for handle in self.bind_groups {
            device.destroy_bind_group(handle);
        }
        for handle in self.graphics {
            device.destroy_graphics_pipeline(handle);
        }
        for handle in self.compute {
            device.destroy_compute_pipeline(handle);
        }
        for handle in self.pipeline_layouts {
            device.destroy_pipeline_layout(handle);
        }
        for handle in self.bind_group_layouts {
            device.destroy_bind_group_layout(handle);
        }
        for handle in self.views {
            device.destroy_image_view(handle);
        }
        for handle in self.images {
            device.destroy_image(handle);
        }
        for handle in self.buffers {
            device.destroy_buffer(handle);
        }
    }
}

/// The shapes every step of one capture agrees on: how the probes are split
/// into chunks, how big the atlas that serves a chunk is, and where a probe's
/// moments sit in the buffer the copy reads.
///
/// One struct rather than a dozen locals threaded through five functions,
/// because every one of them is derived from the probe count and the device's
/// copy alignment and none of them may disagree between the pass that writes
/// and the copy that reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Layout {
    /// Probes in the whole capture, which is layers in the image.
    probes: u32,
    /// Probes in one chunk — [`PROBES_PER_CHUNK`], or fewer if that is all
    /// there are.
    chunk_probes: u32,
    /// Chunks the capture is split into.
    chunks: u32,
    /// The distance atlas's extent, in texels.
    atlas_width: u32,
    atlas_height: u32,
    /// Bytes between two rows of one layer of the moments buffer.
    row_pitch: u64,
    /// Bytes between two layers of it.
    layer_pitch: u64,
}

impl Layout {
    /// The layout `probes` probes take on `device`.
    fn new(device: &dyn Device, probes: u32) -> Self {
        let chunk_probes = probes.clamp(1, PROBES_PER_CHUNK);
        let chunk_tiles = chunk_probes * FACES;
        let copy_alignment = device
            .caps()
            .limits
            .optimal_buffer_copy_offset_alignment
            .max(1);
        let row_bytes = u64::from(EXTENT) * TEXEL_BYTES as u64;
        let row_pitch = padded_row_pitch(row_bytes, TEXEL_BYTES as u64, copy_alignment);
        Self {
            probes,
            chunk_probes,
            chunks: probes.div_ceil(chunk_probes),
            atlas_width: ATLAS_COLUMNS * FACE,
            atlas_height: chunk_tiles.div_ceil(ATLAS_COLUMNS).max(1) * FACE,
            row_pitch,
            layer_pitch: row_pitch * u64::from(EXTENT),
        }
    }

    /// The `buffer_row_length` a copy of one layer names, in texels.
    fn row_texels(&self) -> u32 {
        u32::try_from(self.row_pitch / TEXEL_BYTES as u64).unwrap_or(u32::MAX)
    }

    /// The chunk-local probe count and the capture-global index its probe 0 is.
    fn chunk(&self, chunk: u32) -> (u32, u32) {
        let base = chunk * self.chunk_probes;
        (base, (self.probes - base).min(self.chunk_probes))
    }
}

/// The host-visible buffers a capture reads, written once before the encoder
/// opens.
#[derive(Clone, Copy, Debug)]
struct Inputs {
    /// The world-space triangle soup the cube pass pulls its vertices from.
    geometry: BufferHandle,
    /// Vertices in that soup — three per triangle.
    vertices: u32,
    /// One `float4` per texel of a layer: the direction, and its cube face in
    /// `w`.
    directions: BufferHandle,
    /// Every probe's six world → face-clip matrices.
    matrices: BufferHandle,
    /// Every tile's `CaptureFace` block, one dynamic offset apart.
    blocks: BufferHandle,
    /// Bytes between two of those blocks.
    face_stride: u32,
    /// Every chunk's `OctahedralParams` block, one dynamic offset apart.
    params: BufferHandle,
    /// Bytes between two of those.
    params_stride: u32,
}

/// The distance atlas and the depth buffer that resolves it.
#[derive(Clone, Copy, Debug)]
struct Atlas {
    colour: ImageHandle,
    colour_view: ImageViewHandle,
    depth: ImageHandle,
    depth_view: ImageViewHandle,
}

/// One pipeline and the single group it binds.
#[derive(Clone, Copy, Debug)]
struct Bound<Pipeline> {
    pipeline: Pipeline,
    layout: PipelineLayoutHandle,
    group: BindGroupHandle,
}

/// Captures a visibility map for every probe of `volume` on the device, and
/// returns the `Rg32Float` array image `mesh.slang` binds.
///
/// [`None`] when there is nothing to capture — a volume with no probes, or a
/// scene with nothing placed. There is no geometry for a map to be about, and
/// leaving the caller's placeholder bound is the value that occludes nothing.
///
/// **The device must be idle and stays idle**: this records its own barriers,
/// submits, and blocks on [`Device::wait_idle`], on [`crate::texture`]'s terms.
/// It is a load path, not a frame path.
///
/// # Errors
///
/// [`HalError`] from any seam call. Everything created is released on every
/// path out, including the failing ones.
pub(crate) fn capture(
    device: &dyn Device,
    queue: QueueHandle,
    volume: &ProbeVolume,
    geometry: &Occluders,
    occluders: &[Occluder],
) -> Result<Option<UploadedTexture>, HalError> {
    let probes = volume.total();
    if probes == 0 {
        return Ok(None);
    }
    let rows: Vec<u32> = (0..probes).collect();
    let Some(triangles) = capture_triangles(geometry, occluders) else {
        return Ok(None);
    };

    let mut transients = Transients::default();
    let result = record(
        device,
        queue,
        volume,
        &triangles,
        &rows,
        None,
        &mut transients,
    );
    transients.run(device);
    // `record` created an image because this call passed no destination to
    // write into.
    result
}

/// Captures the maps of **only** `rows` and writes them into the layers of
/// `image` those rows name.
///
/// The irradiance probes' slab recapture: a level that scrolled
/// `k` probes along an axis has `k` slabs holding a map about where their probe
/// used to stand, and
/// [`ProbeVolume::exposed`](crcbl_shaders::probe::ProbeVolume::exposed) is which
/// — so what this pays for is the probes the step exposed and not the level.
/// Every other row of `image` is left exactly as it was, which is what makes the
/// addressing toroidal rather than merely wrapped.
///
/// `image` must be the one a [`capture`] of this volume's row count returned:
/// the copy names its layers by row, and a row past its layers is a copy no
/// backend accepts. Nothing to capture — no rows, or no geometry for a map to be
/// about — leaves it untouched.
///
/// **The device must be idle and stays idle**, on [`capture`]'s terms exactly.
///
/// # Errors
///
/// [`HalError`] from any seam call. Everything created is released on every path
/// out, including the failing ones; `image` is the caller's and is never
/// destroyed here.
pub(crate) fn recapture(
    device: &dyn Device,
    queue: QueueHandle,
    volume: &ProbeVolume,
    geometry: &Occluders,
    occluders: &[Occluder],
    rows: &[u32],
    image: ImageHandle,
) -> Result<(), HalError> {
    if rows.is_empty() || volume.total() == 0 {
        return Ok(());
    }
    let Some(triangles) = capture_triangles(geometry, occluders) else {
        return Ok(());
    };

    let mut transients = Transients::default();
    let result = record(
        device,
        queue,
        volume,
        &triangles,
        rows,
        Some(image),
        &mut transients,
    );
    transients.run(device);
    result.map(|_| ())
}

/// The world-space triangle soup a capture draws, or [`None`] when there is
/// nothing for a map to be about.
///
/// One place rather than two, because "a scene with nothing placed leaves the
/// maps alone" has to mean the same thing on both entry points.
fn capture_triangles(geometry: &Occluders, occluders: &[Occluder]) -> Option<Vec<[[f32; 3]; 3]>> {
    if geometry.is_empty() {
        return None;
    }
    let triangles = world_triangles(geometry, occluders);
    if triangles.is_empty() {
        return None;
    }
    Some(triangles)
}

/// [`capture`]'s and [`recapture`]'s shared body, recording what it creates into
/// `transients` as it goes.
///
/// `rows` are the table rows to fill, in the order the atlas draws them; `into`
/// is the image whose layers they name, or [`None`] to create one of
/// `volume.total()` layers and hand it back — which is what makes the answer an
/// [`Option`]: a call that was given a destination has nothing to give back.
///
/// The image it returns is deliberately **not** in `transients`: it is the one
/// object that outlives the call.
fn record(
    device: &dyn Device,
    queue: QueueHandle,
    volume: &ProbeVolume,
    triangles: &[[[f32; 3]; 3]],
    rows: &[u32],
    into: Option<ImageHandle>,
    transients: &mut Transients,
) -> Result<Option<UploadedTexture>, HalError> {
    let captured = u32::try_from(rows.len()).map_err(|_| {
        HalError::InvalidDescriptor(format!(
            "a probe visibility capture of {} rows is past what one image can hold",
            rows.len()
        ))
    })?;
    let layout = Layout::new(device, captured);
    // Where the probe in each row stands, then the rows this call is about.
    let table = probe_positions(volume);
    let positions: Vec<Vec3> = rows
        .iter()
        .map(|&row| table.get(row as usize).copied().unwrap_or(Vec3::ZERO))
        .collect();
    let far = scene_far(triangles, &positions);
    let inputs = upload_inputs(device, transients, &layout, &positions, triangles, far)?;
    let atlas = build_atlas(device, transients, &layout)?;

    let moments = make_buffer(
        device,
        transients,
        "probe visibility moments",
        layout.layer_pitch * u64::from(layout.probes),
        // Written by a shader, so **device local** — see
        // `crcbl_hal::MemoryLocation`, which refuses the alternative by name.
        BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
        MemoryLocation::DeviceLocal,
    )?;

    let raster = build_raster(device, transients, &inputs)?;
    let resolve = build_resolve(device, transients, &inputs, atlas.colour_view, moments)?;
    let fresh = match into {
        Some(_) => None,
        None => Some(build_target(device, volume.total())?),
    };
    let image = match (into, &fresh) {
        (Some(image), _) => image,
        (None, Some(texture)) => texture.image,
        (None, None) => unreachable!("a call with no destination built one"),
    };

    let plan = Recording {
        layout,
        inputs,
        atlas,
        raster,
        resolve,
        moments,
        image,
        image_layers: volume.total(),
        // **`Undefined` only for an image created a moment ago**, which is the
        // one place it is right: there is no earlier access to order against and
        // nothing in it worth preserving. A recapture's destination is a
        // fragment stage's, and a barrier naming `Undefined` there would carry
        // no source scope and discard every layer the step did not expose.
        from: if into.is_some() {
            ResourceState::ShaderRead
        } else {
            ResourceState::Undefined
        },
        rows,
    };
    match encode(device, queue, &plan) {
        Ok(()) => Ok(fresh),
        Err(error) => {
            if let Some(texture) = fresh {
                texture.destroy(device);
            }
            Err(error)
        }
    }
}

/// Writes the triangle soup, the direction table, the face matrices, the
/// per-tile blocks and the per-chunk parameters.
///
/// **Every buffer spans the whole capture rather than one chunk**, and that is
/// what lets the chunks share an encoder: a host-visible buffer rewritten
/// between two recorded passes would hold only its last contents by the time
/// either of them ran.
fn upload_inputs(
    device: &dyn Device,
    transients: &mut Transients,
    layout: &Layout,
    positions: &[Vec3],
    triangles: &[[[f32; 3]; 3]],
    far: f32,
) -> Result<Inputs, HalError> {
    let vertices = u32::try_from(triangles.len() * 3).map_err(|_| {
        HalError::InvalidDescriptor(format!(
            "a probe visibility capture of {} triangles is past what one draw can name",
            triangles.len()
        ))
    })?;
    let mut soup = Vec::with_capacity(vertices as usize * 3 * size_of::<f32>());
    for triangle in triangles {
        for corner in triangle {
            for value in corner {
                soup.extend_from_slice(&value.to_le_bytes());
            }
        }
    }
    let geometry = make_buffer(
        device,
        transients,
        "probe capture geometry",
        soup.len() as u64,
        BufferUsage::STORAGE,
        MemoryLocation::HostUpload,
    )?;
    device.write_buffer(geometry, 0, &soup)?;

    // `texel_direction` for every texel of a layer, once, with the cube face it
    // falls in beside it: the table is the same for every probe because the
    // layout is, and evaluating it on the host is what keeps
    // `crcbl_shaders::probe_visibility` the only place the octahedral mapping
    // and the border rule are written, and this module the only place the face
    // order is.
    let mut table = Vec::with_capacity((EXTENT * EXTENT) as usize * 4 * size_of::<f32>());
    for y in 0..EXTENT {
        for x in 0..EXTENT {
            let direction = texel_direction(x, y);
            let face = face_of(direction) as f32;
            for value in direction.iter().chain(std::iter::once(&face)) {
                table.extend_from_slice(&value.to_le_bytes());
            }
        }
    }
    let directions = make_buffer(
        device,
        transients,
        "probe capture directions",
        table.len() as u64,
        BufferUsage::STORAGE,
        MemoryLocation::HostUpload,
    )?;
    device.write_buffer(directions, 0, &table)?;

    let alignment = device
        .caps()
        .limits
        .min_uniform_buffer_offset_alignment
        .max(1);
    let face_stride = u32::try_from(FACE_BLOCK_BYTES.next_multiple_of(alignment))
        .map_err(|_| dynamic_offset_refusal(alignment))?;
    let params_stride = u32::try_from(PARAMS_BYTES.next_multiple_of(alignment))
        .map_err(|_| dynamic_offset_refusal(alignment))?;

    let tiles = positions.len() * FACES as usize;
    let mut matrix_bytes = Vec::with_capacity(tiles * MATRIX_BYTES as usize);
    let mut block_bytes = vec![0u8; tiles * face_stride as usize];
    for (probe, origin) in positions.iter().enumerate() {
        for face in 0..FACES {
            let columns = face_matrix(*origin, face, far).to_cols_array();
            for value in columns {
                matrix_bytes.extend_from_slice(&value.to_le_bytes());
            }
            let at = (probe * FACES as usize + face as usize) * face_stride as usize;
            write_floats(&mut block_bytes, at, &columns);
            write_floats(
                &mut block_bytes,
                at + MATRIX_BYTES as usize,
                &origin.to_array(),
            );
        }
    }
    let matrices = make_buffer(
        device,
        transients,
        "probe capture matrices",
        matrix_bytes.len() as u64,
        BufferUsage::STORAGE,
        MemoryLocation::HostUpload,
    )?;
    device.write_buffer(matrices, 0, &matrix_bytes)?;
    let blocks = make_buffer(
        device,
        transients,
        "probe capture faces",
        block_bytes.len() as u64,
        BufferUsage::UNIFORM,
        MemoryLocation::HostUpload,
    )?;
    device.write_buffer(blocks, 0, &block_bytes)?;

    let mut param_bytes = vec![0u8; layout.chunks as usize * params_stride as usize];
    for chunk in 0..layout.chunks {
        let (base, count) = layout.chunk(chunk);
        let at = chunk as usize * params_stride as usize;
        // `probe_octahedral.slang`'s `OctahedralParams`, in declaration order.
        write_words(
            &mut param_bytes,
            at,
            &[
                count,
                base,
                EXTENT,
                FACE,
                ATLAS_COLUMNS,
                u32::try_from(layout.row_pitch / size_of::<f32>() as u64).unwrap_or(u32::MAX),
                u32::try_from(layout.layer_pitch / size_of::<f32>() as u64).unwrap_or(u32::MAX),
                0,
            ],
        );
    }
    let params = make_buffer(
        device,
        transients,
        "probe capture params",
        param_bytes.len() as u64,
        BufferUsage::UNIFORM,
        MemoryLocation::HostUpload,
    )?;
    device.write_buffer(params, 0, &param_bytes)?;

    Ok(Inputs {
        geometry,
        vertices,
        directions,
        matrices,
        blocks,
        face_stride,
        params,
        params_stride,
    })
}

/// The `R32Float` distance atlas one chunk's tiles are drawn into, and the
/// `D32Float` buffer that decides which surface keeps each pixel.
fn build_atlas(
    device: &dyn Device,
    transients: &mut Transients,
    layout: &Layout,
) -> Result<Atlas, HalError> {
    let extent = Extent3d::d2(layout.atlas_width, layout.atlas_height);
    let colour = device.create_image(&ImageDesc {
        label: Some("probe capture distance"),
        image_type: ImageType::D2,
        format: Format::R32Float,
        extent,
        mip_levels: 1,
        samples: 1,
        usage: ImageUsage::COLOR_ATTACHMENT | ImageUsage::SAMPLED,
    })?;
    transients.images.push(colour);
    let colour_view = device.create_image_view(&ImageViewDesc {
        label: Some("probe capture distance"),
        image: colour,
        view_type: ImageViewType::D2,
        format: Format::R32Float,
        range: color_range(1),
    })?;
    transients.views.push(colour_view);

    let depth = device.create_image(&ImageDesc {
        label: Some("probe capture depth"),
        image_type: ImageType::D2,
        format: Format::D32Float,
        extent,
        mip_levels: 1,
        samples: 1,
        usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT,
    })?;
    transients.images.push(depth);
    let depth_view = device.create_image_view(&ImageViewDesc {
        label: Some("probe capture depth"),
        image: depth,
        view_type: ImageViewType::D2,
        format: Format::D32Float,
        range: depth_range(),
    })?;
    transients.views.push(depth_view);

    Ok(Atlas {
        colour,
        colour_view,
        depth,
        depth_view,
    })
}

/// `probe_capture.slang`'s pipeline: the tile's block at 0 and the triangle
/// soup at 1, in that source's declaration order.
fn build_raster(
    device: &dyn Device,
    transients: &mut Transients,
    inputs: &Inputs,
) -> Result<Bound<GraphicsPipelineHandle>, HalError> {
    let entries = [
        BindGroupLayoutEntry {
            binding: 0,
            // The fragment stage reads the probe's origin out of the same
            // block, so both stages see it.
            visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
            // Dynamic, which is how a tile says which face it is on a device
            // with no push constants.
            kind: BindingKind::UniformBuffer { dynamic: true },
            count: 1,
            flags: BindingFlags::empty(),
        },
        BindGroupLayoutEntry {
            binding: 1,
            visibility: ShaderStages::VERTEX,
            kind: BindingKind::StorageBuffer {
                read_only: true,
                dynamic: false,
                stride: size_of::<u32>() as u32,
            },
            count: 1,
            flags: BindingFlags::empty(),
        },
    ];
    let desc = BindGroupLayoutDesc {
        label: Some("probe capture"),
        entries: &entries,
    };
    check_portable_storage_buffers(Some("probe capture"), &[&desc])?;
    let group_layout = device.create_bind_group_layout(&desc)?;
    transients.bind_group_layouts.push(group_layout);
    let layout = device.create_pipeline_layout(&PipelineLayoutDesc {
        label: Some("probe capture"),
        bind_group_layouts: &[group_layout],
        push_constants: None,
    })?;
    transients.pipeline_layouts.push(layout);
    let group = device.create_bind_group(&BindGroupDesc {
        label: Some("probe capture"),
        layout: group_layout,
        entries: &[
            BindGroupEntry {
                binding: 0,
                array_index: 0,
                // **One block, not the whole buffer.** The binding is dynamic,
                // so the offset the bind adds is on top of this one, and both
                // Vulkan and WebGPU require the sum to stay inside the buffer.
                resource: BindingResource::Buffer {
                    buffer: inputs.blocks,
                    offset: 0,
                    size: FACE_BLOCK_BYTES,
                },
            },
            BindGroupEntry {
                binding: 1,
                array_index: 0,
                resource: BindingResource::whole_buffer(inputs.geometry),
            },
        ],
        variable_count: None,
    })?;
    transients.bind_groups.push(group);

    // Entry points resolved before the module exists, for `crate::grid`'s
    // reason: a manifest that disagreed with the artifact would otherwise fail
    // inside the descriptor literal, with the module already created and
    // nothing holding it.
    let vertex = entry_point(&PROBE_CAPTURE, Stage::Vertex)?;
    let fragment = entry_point(&PROBE_CAPTURE, Stage::Fragment)?;
    let module = device.create_shader_module(&ShaderModuleDesc {
        label: Some(PROBE_CAPTURE.source()),
        spirv: PROBE_CAPTURE.spirv(),
        wgsl: PROBE_CAPTURE.wgsl(),
        msl: PROBE_CAPTURE.msl(),
        dxil: &PROBE_CAPTURE.dxil_containers(),
    })?;
    let targets = [ColorTargetState {
        format: Format::R32Float,
        // No blend: the nearest surface replaces what a further one wrote, and
        // `R32Float` is not a blendable format on a WebGPU core device anyway.
        blend: None,
        write_mask: ColorWrites::ALL,
    }];
    let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
        label: Some("probe capture"),
        layout,
        vertex: ShaderEntry {
            module,
            entry_point: vertex,
        },
        fragment: Some(ShaderEntry {
            module,
            entry_point: fragment,
        }),
        primitive: PrimitiveState {
            // **Two-sided**, matching what this capture replaced: a probe
            // standing inside geometry sees that geometry's back faces, and the
            // distance to them is exactly what says it is inside.
            cull_mode: CullMode::None,
            ..PrimitiveState::default()
        },
        depth_stencil: Some(DepthStencilState {
            format: Format::D32Float,
            depth_write: true,
            // `Greater` under reversed-Z: the nearest surface wins the pixel,
            // and along one pixel's own ray nearest in `z` is nearest in
            // distance, which is what lets the colour target carry the second
            // while the test is on the first.
            depth_compare: CompareOp::Greater,
            stencil: None,
            bias: DepthBias::default(),
        }),
        multisample: MultisampleState::default(),
        color_targets: &targets,
    });
    device.destroy_shader_module(module);
    let pipeline = pipeline?;
    transients.graphics.push(pipeline);
    Ok(Bound {
        pipeline,
        layout,
        group,
    })
}

/// `probe_octahedral.slang`'s pipeline, in that source's declaration order:
/// the chunk's parameters, the direction table, the face matrices, the atlas
/// and the moments.
fn build_resolve(
    device: &dyn Device,
    transients: &mut Transients,
    inputs: &Inputs,
    atlas: ImageViewHandle,
    moments: BufferHandle,
) -> Result<Bound<ComputePipelineHandle>, HalError> {
    // `stride` is the element each read declares: the probe directions are
    // `float4`s and the cube faces `float4x4`s.
    let readable = |binding: u32, stride: u32| BindGroupLayoutEntry {
        binding,
        visibility: ShaderStages::COMPUTE,
        kind: BindingKind::StorageBuffer {
            read_only: true,
            dynamic: false,
            stride,
        },
        count: 1,
        flags: BindingFlags::empty(),
    };
    let entries = [
        BindGroupLayoutEntry {
            binding: 0,
            visibility: ShaderStages::COMPUTE,
            kind: BindingKind::UniformBuffer { dynamic: true },
            count: 1,
            flags: BindingFlags::empty(),
        },
        readable(1, size_of::<[f32; 4]>() as u32),
        readable(2, size_of::<[[f32; 4]; 4]>() as u32),
        BindGroupLayoutEntry {
            binding: 3,
            visibility: ShaderStages::COMPUTE,
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2,
                // `R32Float` is unfilterable without a device feature, and
                // WebGPU checks the layout against the view's format at bind
                // time however the shader goes on to read it — this one only
                // ever `Load`s.
                sample_type: SampleType::UnfilterableFloat,
            },
            count: 1,
            flags: BindingFlags::empty(),
        },
        BindGroupLayoutEntry {
            binding: 4,
            visibility: ShaderStages::COMPUTE,
            kind: BindingKind::StorageBuffer {
                read_only: false,
                dynamic: false,
                stride: size_of::<f32>() as u32,
            },
            count: 1,
            flags: BindingFlags::empty(),
        },
    ];
    let desc = BindGroupLayoutDesc {
        label: Some("probe octahedral"),
        entries: &entries,
    };
    check_portable_storage_buffers(Some("probe octahedral"), &[&desc])?;
    let group_layout = device.create_bind_group_layout(&desc)?;
    transients.bind_group_layouts.push(group_layout);
    let layout = device.create_pipeline_layout(&PipelineLayoutDesc {
        label: Some("probe octahedral"),
        bind_group_layouts: &[group_layout],
        push_constants: None,
    })?;
    transients.pipeline_layouts.push(layout);
    let group = device.create_bind_group(&BindGroupDesc {
        label: Some("probe octahedral"),
        layout: group_layout,
        entries: &[
            BindGroupEntry {
                binding: 0,
                array_index: 0,
                resource: BindingResource::Buffer {
                    buffer: inputs.params,
                    offset: 0,
                    size: PARAMS_BYTES,
                },
            },
            BindGroupEntry {
                binding: 1,
                array_index: 0,
                resource: BindingResource::whole_buffer(inputs.directions),
            },
            BindGroupEntry {
                binding: 2,
                array_index: 0,
                resource: BindingResource::whole_buffer(inputs.matrices),
            },
            BindGroupEntry {
                binding: 3,
                array_index: 0,
                resource: BindingResource::ImageView(atlas),
            },
            BindGroupEntry {
                binding: 4,
                array_index: 0,
                resource: BindingResource::whole_buffer(moments),
            },
        ],
        variable_count: None,
    })?;
    transients.bind_groups.push(group);
    let pipeline = crate::draw_gen::compute_pipeline(
        device,
        "probe octahedral",
        &PROBE_OCTAHEDRAL,
        layout,
        WORKGROUP,
    )?;
    transients.compute.push(pipeline);
    Ok(Bound {
        pipeline,
        layout,
        group,
    })
}

/// The `Rg32Float` array image the frame binds — the one object a capture
/// leaves behind.
///
/// `layers` is the **volume's** row count rather than the rows this call draws:
/// a recapture writes into an image of every row and a first capture creates
/// one, and the two have to be the same image.
fn build_target(device: &dyn Device, layers: u32) -> Result<UploadedTexture, HalError> {
    let image = device.create_image(&ImageDesc {
        label: Some("probe visibility"),
        image_type: ImageType::D2,
        format: Format::Rg32Float,
        extent: Extent3d {
            width: EXTENT,
            height: EXTENT,
            // A `D2` image's `depth_or_layers` is its array length.
            depth_or_layers: layers,
        },
        mip_levels: 1,
        samples: 1,
        usage: ImageUsage::TRANSFER_SRC | ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED,
    })?;
    match device.create_image_view(&ImageViewDesc {
        label: Some("probe visibility"),
        image,
        view_type: ImageViewType::D2Array,
        format: Format::Rg32Float,
        range: color_range(layers),
    }) {
        Ok(view) => Ok(UploadedTexture { image, view }),
        Err(error) => {
            device.destroy_image(image);
            Err(error)
        }
    }
}

/// Everything [`encode`] needs, which is more than an argument list should
/// be.
struct Recording<'a> {
    layout: Layout,
    inputs: Inputs,
    atlas: Atlas,
    raster: Bound<GraphicsPipelineHandle>,
    resolve: Bound<ComputePipelineHandle>,
    moments: BufferHandle,
    /// The image the copy fills. Not the whole [`UploadedTexture`], because a
    /// copy names an image and this function has no business with the view.
    image: ImageHandle,
    /// Layers that image has, which is every row of the volume — the range the
    /// barriers around the copy cover, whether or not this call fills them all.
    image_layers: u32,
    /// The state [`Recording::image`] is already in, which decides what the
    /// barrier before the copy has to order against.
    from: ResourceState,
    /// Which layer of [`Recording::image`] each of the moments buffer's layers
    /// belongs in — the table rows this call captured, in the order it drew
    /// them.
    rows: &'a [u32],
}

/// Records every chunk's cube pass and resolve, copies the moments into the
/// image, submits, and waits.
fn encode(device: &dyn Device, queue: QueueHandle, plan: &Recording<'_>) -> Result<(), HalError> {
    let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
        label: Some("probe visibility capture"),
        queue,
    });

    // The atlas is reused chunk by chunk, so it re-enters `ColorAttachment`
    // from wherever the previous chunk's resolve left it. The first pass
    // discards its contents instead, which is what `Undefined` means.
    let mut atlas_state = ResourceState::Undefined;
    let mut depth_state = ResourceState::Undefined;
    for chunk in 0..plan.layout.chunks {
        let (base, count) = plan.layout.chunk(chunk);
        encoder.pipeline_barrier(&Barriers {
            images: &[
                ImageBarrier::new(
                    plan.atlas.colour,
                    color_range(1),
                    atlas_state,
                    ResourceState::ColorAttachment,
                ),
                ImageBarrier::new(
                    plan.atlas.depth,
                    depth_range(),
                    depth_state,
                    ResourceState::DepthStencilWrite,
                ),
            ],
            ..Default::default()
        });
        atlas_state = ResourceState::ColorAttachment;
        depth_state = ResourceState::DepthStencilWrite;

        draw_cubes(&mut encoder, plan, base, count);

        encoder.pipeline_barrier(&Barriers {
            images: &[ImageBarrier::new(
                plan.atlas.colour,
                color_range(1),
                atlas_state,
                ResourceState::ShaderRead,
            )],
            ..Default::default()
        });
        atlas_state = ResourceState::ShaderRead;

        encoder.begin_compute_pass(&ComputePassDesc {
            label: Some("probe octahedral"),
            timestamp_writes: None,
        });
        encoder.bind_compute_pipeline(plan.resolve.pipeline);
        encoder.bind_group(
            0,
            plan.resolve.group,
            &[chunk * plan.inputs.params_stride],
            plan.resolve.layout,
        );
        let threads = count * EXTENT * EXTENT;
        encoder.dispatch(threads.div_ceil(WORKGROUP), 1, 1);
        encoder.end_compute_pass();
    }

    copy_moments(&mut encoder, plan);

    let commands = encoder.finish()?;
    let submitted = device
        .submit(queue, &SubmitInfo::new(&[commands]))
        .and_then(|()| device.wait_idle());
    device.destroy_command_buffer(commands);
    submitted
}

/// One render pass over the atlas, with a viewport and a draw per tile.
///
/// **A draw per tile rather than one instanced draw over all of them**: a tile
/// is a viewport, and remapping six frusta into one clip space instead would
/// leave each face's triangles clipped against the whole atlas rather than
/// against its own tile, so a wall running off the edge of one face would be
/// drawn across its neighbour.
fn draw_cubes(encoder: &mut Box<dyn CommandEncoder>, plan: &Recording<'_>, base: u32, count: u32) {
    encoder.begin_render_pass(&RenderPassDesc {
        label: Some("probe capture cube"),
        color_attachments: &[ColorAttachment {
            view: plan.atlas.colour_view,
            resolve: None,
            load: LoadOp::Clear,
            store: StoreOp::Store,
            // **The open-space texel.** A pixel no triangle covers keeps
            // `crcbl_shaders::probe_visibility::FAR`, which no surface is
            // further away than, so the probe occludes nothing in that
            // direction — which is what "the capture saw open space" means.
            clear: ClearValue::color([crcbl_shaders::probe_visibility::FAR, 0.0, 0.0, 0.0]),
        }],
        depth_stencil_attachment: Some(DepthStencilAttachment {
            view: plan.atlas.depth_view,
            read_only: false,
            depth_load: LoadOp::Clear,
            // Nothing reads it after the pass: the distance is in the colour
            // target and this only decided which fragment wrote it.
            depth_store: StoreOp::Discard,
            stencil_load: LoadOp::DontCare,
            stencil_store: StoreOp::Discard,
            clear: ClearValue::default(),
        }),
        render_area: Rect2d {
            x: 0,
            y: 0,
            width: plan.layout.atlas_width,
            height: plan.layout.atlas_height,
        },
        timestamp_writes: None,
    });
    encoder.bind_graphics_pipeline(plan.raster.pipeline);
    for tile in 0..count * FACES {
        let rect = tile_rect(tile);
        encoder.set_viewport(&Viewport {
            x: rect.x as f32,
            y: rect.y as f32,
            width: rect.width as f32,
            height: rect.height as f32,
            ..Viewport::from_size(rect.width, rect.height)
        });
        encoder.set_scissor(&rect);
        let offset = (base * FACES + tile) * plan.inputs.face_stride;
        encoder.bind_group(0, plan.raster.group, &[offset], plan.raster.layout);
        encoder.draw(0..plan.inputs.vertices, 0..1);
    }
    encoder.end_render_pass();
}

/// Moves the finished moments out of the buffer the resolve wrote and into the
/// layers of the image the frame binds — one copy per layer, because a copy
/// region's extent is a 2D extent on every backend here.
///
/// **A copy per captured row, into the layer that row names.** A first capture
/// draws every row in order and this is the identity; a recapture draws the rows
/// a scroll exposed and this is what puts each of them back where the table
/// addresses it.
fn copy_moments(encoder: &mut Box<dyn CommandEncoder>, plan: &Recording<'_>) {
    let every_layer = color_range(plan.image_layers);
    encoder.pipeline_barrier(&Barriers {
        buffers: &[BufferBarrier::new(
            plan.moments,
            ResourceState::ShaderWrite,
            ResourceState::TransferSrc,
        )],
        images: &[ImageBarrier::new(
            plan.image,
            every_layer,
            plan.from,
            ResourceState::TransferDst,
        )],
        ..Default::default()
    });
    for (layer, &row) in plan.rows.iter().enumerate() {
        encoder.copy_buffer_to_image(&BufferImageCopy {
            buffer: plan.moments,
            buffer_offset: layer as u64 * plan.layout.layer_pitch,
            buffer_row_length: plan.layout.row_texels(),
            buffer_image_height: EXTENT,
            image: plan.image,
            image_subresource: ImageSubresourceLayers {
                aspect: ImageAspect::COLOR,
                mip: 0,
                base_layer: row,
                layer_count: 1,
            },
            image_offset: Offset3d { x: 0, y: 0, z: 0 },
            image_extent: Extent3d::d2(EXTENT, EXTENT),
        });
    }
    encoder.pipeline_barrier(&Barriers {
        images: &[ImageBarrier::new(
            plan.image,
            every_layer,
            ResourceState::TransferDst,
            ResourceState::ShaderRead,
        )],
        ..Default::default()
    });
}

/// A colour subresource range over every layer of the one level.
const fn color_range(layers: u32) -> ImageSubresourceRange {
    ImageSubresourceRange {
        aspect: ImageAspect::COLOR,
        base_mip: 0,
        mip_count: 1,
        base_layer: 0,
        layer_count: layers,
    }
}

/// The depth aspect of the one level of the one layer.
const fn depth_range() -> ImageSubresourceRange {
    ImageSubresourceRange {
        aspect: ImageAspect::DEPTH,
        base_mip: 0,
        mip_count: 1,
        base_layer: 0,
        layer_count: 1,
    }
}

/// Writes `values` into `bytes` at `at`, little-endian, one word each.
fn write_floats(bytes: &mut [u8], at: usize, values: &[f32]) {
    for (lane, value) in values.iter().enumerate() {
        let slot = at + lane * size_of::<f32>();
        bytes[slot..slot + size_of::<f32>()].copy_from_slice(&value.to_le_bytes());
    }
}

/// [`write_floats`] for a block of `uint`s.
fn write_words(bytes: &mut [u8], at: usize, values: &[u32]) {
    for (lane, value) in values.iter().enumerate() {
        let slot = at + lane * size_of::<u32>();
        bytes[slot..slot + size_of::<u32>()].copy_from_slice(&value.to_le_bytes());
    }
}

/// Creates a buffer and records it for release.
fn make_buffer(
    device: &dyn Device,
    transients: &mut Transients,
    label: &str,
    size: u64,
    usage: BufferUsage,
    memory: MemoryLocation,
) -> Result<BufferHandle, HalError> {
    let handle = device.create_buffer(&BufferDesc {
        label: Some(label),
        size,
        usage,
        memory,
    })?;
    transients.buffers.push(handle);
    Ok(handle)
}

/// The refusal a device whose dynamic-offset alignment does not fit a `u32`
/// earns — `crate::sprite_pass`' wording, for its reason.
fn dynamic_offset_refusal(alignment: u64) -> HalError {
    HalError::InvalidDescriptor(format!(
        "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic offset can express"
    ))
}

/// The entry point `stage` of `shader`, or a refusal naming the drift.
fn entry_point(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&str, HalError> {
    shader.entry_point(stage).ok_or_else(|| {
        HalError::ShaderCompilation(format!(
            "{}.slang exposes no unambiguous {stage:?} entry point; the committed artifact and \
             its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
            shader.name()
        ))
    })
}

// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;

    /// **The pair the resolve rests on**: for every texel of a layer, the face
    /// its direction's major axis picks is a face whose 90° frustum really does
    /// contain that direction, and the tile coordinate it projects to is inside
    /// the tile.
    ///
    /// This is the host mirror of `probe_octahedral.slang`'s whole lookup —
    /// `face_of`, then `mul(faces[…], float4(direction, 0))`, then the NDC to
    /// tile-uv map — written here as the same expressions in the same order. A
    /// face order that disagreed with [`face_matrix`], or a `y` flip the wrong
    /// way round, reads a tile of somewhere else and draws a frame that still
    /// has occlusion in it.
    #[test]
    fn the_six_faces_cover_every_texel_direction() {
        let origin = Vec3::new(1.5, -2.0, 0.75);
        let far = 40.0;
        for y in 0..EXTENT {
            for x in 0..EXTENT {
                let direction = texel_direction(x, y);
                let face = face_of(direction);
                let matrix = face_matrix(origin, face, far);
                let clip = matrix * glam::Vec4::new(direction[0], direction[1], direction[2], 0.0);
                assert!(
                    clip.w > 0.0,
                    "texel ({x}, {y}) projects behind face {face}'s eye"
                );
                let ndc = clip.truncate() / clip.w;
                assert!(
                    ndc.x.abs() <= 1.0 + 1.0e-4 && ndc.y.abs() <= 1.0 + 1.0e-4,
                    "texel ({x}, {y}) lands at {ndc:?} of face {face}, outside its tile"
                );
                // And the point one unit along the direction from the probe
                // projects to the same place, which is what lets the shader
                // pass `w = 0` and never name the probe's position.
                let point = Vec3::from_array(direction) + origin;
                let full = matrix * point.extend(1.0);
                let full_ndc = full.truncate() / full.w;
                assert!(
                    (full_ndc.x - ndc.x).abs() <= 1.0e-4 && (full_ndc.y - ndc.y).abs() <= 1.0e-4,
                    "texel ({x}, {y}) projects to {ndc:?} as a direction and {full_ndc:?} as a \
                     point"
                );
            }
        }
    }

    /// The face a direction straight down an axis picks is that axis's own
    /// face, in the order `crate::shadow` uses — [`face_of`] and
    /// [`face_axis`] agreeing is what makes the uploaded table's `w` name the
    /// tile [`face_matrix`] drew.
    #[test]
    fn each_axis_picks_its_own_face() {
        for face in 0..FACES {
            let axis = face_axis(face);
            assert_eq!(face_of(axis.to_array()), face, "face {face}'s own axis");
        }
    }

    /// Every tile of a chunk lands inside the atlas, and no two tiles overlap.
    #[test]
    fn the_tiles_of_one_chunk_tile_the_atlas() {
        let mut seen = std::collections::HashSet::new();
        for tile in 0..PROBES_PER_CHUNK * FACES {
            let rect = tile_rect(tile);
            assert!(rect.x >= 0 && rect.y >= 0);
            assert!(
                rect.x as u32 + rect.width <= ATLAS_COLUMNS * FACE,
                "tile {tile} runs past the atlas's width"
            );
            assert!(
                rect.y as u32 + rect.height <= ATLAS_ROWS * FACE,
                "tile {tile} runs past the atlas's height"
            );
            assert!(seen.insert((rect.x, rect.y)), "tile {tile} shares a corner");
        }
    }

    /// The row pitch is at least a row, on the alignment, and a whole number of
    /// texels — the three things the copy needs of it, on every alignment a
    /// device reports.
    #[test]
    fn the_row_pitch_holds_a_row_on_every_alignment() {
        let row = u64::from(EXTENT) * TEXEL_BYTES as u64;
        for alignment in [1u64, 4, 8, 16, 64, 256, 512] {
            let pitch = padded_row_pitch(row, TEXEL_BYTES as u64, alignment);
            assert!(pitch >= row, "an alignment of {alignment} lost a texel");
            assert!(pitch.is_multiple_of(alignment), "off {alignment}");
            assert!(
                pitch.is_multiple_of(TEXEL_BYTES as u64),
                "a pitch of {pitch} is not a whole number of texels"
            );
        }
    }

    /// The far plane reaches past every corner of the scene from every probe,
    /// which is what stops a wall being clipped out of a capture.
    #[test]
    fn the_far_plane_reaches_the_whole_scene() {
        let triangles = [[[-5.0, 0.0, -5.0], [5.0, 0.0, -5.0], [0.0, 3.0, 6.0]]];
        let probes = [Vec3::new(-4.0, 1.0, -4.0), Vec3::new(4.0, 2.0, 5.0)];
        let far = scene_far(&triangles, &probes);
        for probe in probes {
            for triangle in &triangles {
                for corner in triangle {
                    let reach = (Vec3::from_array(*corner) - probe).length();
                    assert!(far > reach, "a corner {reach} away is past a far of {far}");
                }
            }
        }
    }

    /// An empty scene still yields a usable far plane rather than a zero one,
    /// which would make every matrix degenerate.
    #[test]
    fn an_empty_scene_still_has_a_far_plane() {
        assert!(scene_far(&[], &[Vec3::ZERO]) >= MIN_FAR);
    }

    /// **One capture covers every level of the clipmap**, and layer `i` stands
    /// where probe row `i` does.
    ///
    /// The layer order is the whole of what makes a row and a visibility map one
    /// probe, and nothing else in the tree can catch it drifting: `mesh.slang`'s
    /// `probe_row` reads a layer index it computed itself, so a capture that
    /// walked its levels in another order draws a room lit through the wrong
    /// walls and no assertion anywhere says which. The positions are checked
    /// against [`ProbeVolume::position`], which is where the clipmap's geometry
    /// is decided.
    #[test]
    fn a_capture_walks_every_level_in_the_order_the_table_is_in() {
        let volume = ProbeVolume {
            origin: [-2.0, 1.0, -3.0],
            inv_spacing: [0.5, 1.0, 0.25],
            counts: [3, 2, 2],
            levels: 3,
            steps: crcbl_shaders::probe::ProbeSteps::default(),
        };
        let positions = probe_positions(&volume);
        assert_eq!(
            positions.len(),
            volume.total() as usize,
            "a capture must have one layer per row of the whole table"
        );
        for level in 0..volume.level_count() {
            for z in 0..volume.counts[2] {
                for y in 0..volume.counts[1] {
                    for x in 0..volume.counts[0] {
                        let row = volume.level_row(level)
                            + (z * volume.counts[1] + y) * volume.counts[0]
                            + x;
                        assert_eq!(
                            positions[row as usize],
                            Vec3::from_array(volume.position(level, [x, y, z])),
                            "row {row} is level {level}'s cell ({x}, {y}, {z})"
                        );
                    }
                }
            }
        }
        // Anti-vacuity: a coarser level really does stand somewhere else, so
        // the equalities above are not comparing one grid against itself three
        // times over.
        assert_ne!(positions[0], positions[volume.per_level() as usize]);
    }

    /// **A volume of more probes than one chunk holds records every chunk**,
    /// which is the only thing in the tree that takes [`encode`]'s loop round
    /// more than once.
    ///
    /// [`PROBES_PER_CHUNK`] tiles is one atlas full, and every scene the engine
    /// ships captures inside one — so the second turn is dead code that no
    /// golden, no e2e run and no other test here can reach. A capture that
    /// stopped after the first chunk would leave every probe past it holding
    /// whatever the moments buffer was created with, and the frames it lit would
    /// be plausible: the layers exist, the image binds, and only the far corner
    /// of a big enough volume is wrong.
    ///
    /// The counts are read off the recorded stream rather than off the layout,
    /// because the layout is what the loop is *supposed* to walk and the stream
    /// is what it walked. One cube pass and one resolve dispatch per chunk, a
    /// draw per tile across the **whole** volume, and a last dispatch smaller
    /// than the first — the partial chunk, which is the case an off-by-one in
    /// the count hands the shader as a full one.
    #[test]
    fn a_capture_of_more_probes_than_one_chunk_records_every_chunk() {
        use crcbl_hal::null::{Command, NullInstance, Recorder};
        use crcbl_hal::{DeviceDesc, Features, Instance, QueueKind};

        let recorder = Recorder::new();
        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        let device = instance
            .create_device(&DeviceDesc {
                label: Some("probe capture chunks"),
                adapter: adapter.id,
                required_features: Features::GPU_DRIVEN,
                optional_features: Features::empty(),
                compatible_surface: None,
            })
            .expect("the null backend always opens");
        let queue = device.queue(QueueKind::Graphics).expect("always present");

        // The demo scene's own geometry under one instance: a capture needs a
        // triangle soup to draw, and this is the cheapest real one rather than
        // a second hand-written cube.
        let mut scene = crate::scene::demo();
        scene.capacities.probes = 1;
        let ids: Vec<u32> = (0..scene.meshes.len() as u32).collect();
        let geometry = Occluders::from_scene(&scene, &ids);
        let placed = [Occluder {
            mesh: ids[0],
            transform: glam::Mat4::IDENTITY,
        }];
        assert!(
            !world_triangles(&geometry, &placed).is_empty(),
            "the fixture must place triangles, or `capture` returns None and every count \
             below is zero"
        );

        // Ten probes past one atlas full, so the last chunk is a partial one.
        let volume = ProbeVolume {
            origin: [-2.0, -1.0, -2.0],
            inv_spacing: [1.0; 3],
            counts: [6, 6, 5],
            levels: 1,
            steps: crcbl_shaders::probe::ProbeSteps::default(),
        };
        let probes = volume.total();
        let layout = Layout::new(device.as_ref(), probes);
        assert!(
            layout.chunks > 1,
            "a fixture of {probes} probes fits in {} chunk(s), so it takes the loop round \
             once and this test would hold with the loop deleted",
            layout.chunks
        );

        let captured = capture(device.as_ref(), queue, &volume, &geometry, &placed)
            .expect("the null backend accepts every descriptor")
            .expect("a volume with probes and a scene with triangles has a map to capture");
        captured.destroy(device.as_ref());

        let commands = recorder.commands();
        let passes = commands
            .iter()
            .filter(|command| {
                matches!(command, Command::BeginRenderPass { label: Some(label), .. }
                    if label == "probe capture cube")
            })
            .count();
        assert_eq!(
            passes as u32, layout.chunks,
            "the capture recorded {passes} cube passes for {} chunks",
            layout.chunks
        );

        let draws = commands
            .iter()
            .filter(|command| matches!(command, Command::Draw { .. }))
            .count();
        assert_eq!(
            draws as u32,
            probes * FACES,
            "a draw per face of every probe, not of the first chunk's"
        );

        let dispatches: Vec<u32> = commands
            .iter()
            .filter_map(|command| match command {
                Command::Dispatch { x, .. } => Some(*x),
                _ => None,
            })
            .collect();
        let expected: Vec<u32> = (0..layout.chunks)
            .map(|chunk| {
                let (_, count) = layout.chunk(chunk);
                (count * EXTENT * EXTENT).div_ceil(WORKGROUP)
            })
            .collect();
        assert_eq!(
            dispatches, expected,
            "one resolve per chunk, each over its own chunk's probes"
        );
        assert!(
            expected.last() < expected.first(),
            "the fixture's last chunk must be a partial one, or nothing here reads the \
             count the loop passes"
        );
    }

    /// **A scrolled level's layers follow its rows rather than its cells**, so
    /// the map in layer `i` is about the probe row `i` addresses.
    ///
    /// The capture and `mesh.slang` agree on a row through
    /// [`ProbeVolume::row`], and a walk that pushed positions in cell order
    /// would put every one of a scrolled level's maps a slab away from the probe
    /// that reads it — a room lit through the wrong wall, and no assertion
    /// anywhere else says which.
    #[test]
    fn a_scrolled_capture_puts_each_row_where_the_volume_addresses_it() {
        let mut volume = ProbeVolume {
            origin: [-2.0, 1.0, -3.0],
            inv_spacing: [0.5, 1.0, 0.25],
            counts: [3, 2, 4],
            levels: 2,
            steps: crcbl_shaders::probe::ProbeSteps::default(),
        };
        volume.steps[0] = [1, -1, 5];
        volume.steps[1] = [-2, 0, 1];
        let positions = probe_positions(&volume);
        assert_eq!(positions.len(), volume.total() as usize);
        for level in 0..volume.level_count() {
            for z in 0..volume.counts[2] {
                for y in 0..volume.counts[1] {
                    for x in 0..volume.counts[0] {
                        let row = volume.row(level, [x, y, z]);
                        assert_eq!(
                            positions[row as usize],
                            Vec3::from_array(volume.position(level, [x, y, z])),
                            "row {row} is not level {level}'s cell ({x}, {y}, {z})"
                        );
                    }
                }
            }
        }
        // Anti-vacuity: the scroll really did permute the rows, so the walk
        // above is not the unscrolled one under another name.
        let still = ProbeVolume {
            steps: crcbl_shaders::probe::ProbeSteps::default(),
            ..volume
        };
        assert_ne!(
            positions,
            probe_positions(&still),
            "the fixture's scroll moved no row, so this holds with the wrap deleted"
        );
    }

    /// **A recapture draws the rows it was given and copies into their layers,
    /// and nothing else** — the whole of what makes a scroll cost a slab rather
    /// than a level.
    ///
    /// Read off the recorded stream rather than off the arguments: the count of
    /// draws is what says only those probes were rasterised, and the set of
    /// destination layers is what says each of their maps landed where the table
    /// addresses it. A recapture that copied layer `i` to layer `i` would pass
    /// every other check here and light the wrong probes.
    ///
    /// **And its barrier names [`ResourceState::ShaderRead`]**, not
    /// `Undefined`: the layers the step did not expose are the ones a scroll
    /// exists to keep, and a barrier discarding the image would throw them away
    /// on every backend allowed to.
    #[test]
    fn a_recapture_writes_only_the_layers_the_step_exposed() {
        use crcbl_hal::null::{Command, NullInstance, Recorder};
        use crcbl_hal::{DeviceDesc, Features, Instance, QueueKind};

        let recorder = Recorder::new();
        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        let device = instance
            .create_device(&DeviceDesc {
                label: Some("probe recapture"),
                adapter: adapter.id,
                required_features: Features::GPU_DRIVEN,
                optional_features: Features::empty(),
                compatible_surface: None,
            })
            .expect("the null backend always opens");
        let queue = device.queue(QueueKind::Graphics).expect("always present");

        let mut scene = crate::scene::demo();
        scene.capacities.probes = 1;
        let ids: Vec<u32> = (0..scene.meshes.len() as u32).collect();
        let geometry = Occluders::from_scene(&scene, &ids);
        let placed = [Occluder {
            mesh: ids[0],
            transform: glam::Mat4::IDENTITY,
        }];

        let mut volume = ProbeVolume {
            origin: [-2.0, -1.0, -2.0],
            inv_spacing: [1.0; 3],
            counts: [4, 3, 2],
            levels: 1,
            steps: crcbl_shaders::probe::ProbeSteps::default(),
        };
        let captured = capture(device.as_ref(), queue, &volume, &geometry, &placed)
            .expect("the null backend accepts every descriptor")
            .expect("a volume with probes and a scene with triangles has a map to capture");

        let mut steps = volume.steps;
        steps[0][0] = 1;
        let rows = volume.exposed(&steps);
        assert_eq!(
            rows.len() as u32,
            volume.counts[1] * volume.counts[2],
            "a step of one along x exposes one slab"
        );
        assert!(
            (rows.len() as u32) < volume.total(),
            "the fixture must keep some rows, or this holds for a recapture of the level"
        );
        volume.steps = steps;

        recorder.clear();
        recapture(
            device.as_ref(),
            queue,
            &volume,
            &geometry,
            &placed,
            &rows,
            captured.image,
        )
        .expect("the null backend accepts every descriptor");

        let commands = recorder.commands();
        let draws = commands
            .iter()
            .filter(|command| matches!(command, Command::Draw { .. }))
            .count();
        assert_eq!(
            draws as u32,
            rows.len() as u32 * FACES,
            "a recapture drew {draws} faces for {} exposed rows",
            rows.len()
        );

        let layers: Vec<u32> = commands
            .iter()
            .filter_map(|command| match command {
                Command::CopyBufferToImage(copy) if copy.image == captured.image => {
                    Some(copy.image_subresource.base_layer)
                }
                _ => None,
            })
            .collect();
        assert_eq!(
            layers, rows,
            "the recapture copied into layers that are not the rows the step exposed"
        );

        let discarded = commands.iter().any(|command| match command {
            Command::Barrier { images, .. } => images.iter().any(|barrier| {
                barrier.image == captured.image && barrier.from == ResourceState::Undefined
            }),
            _ => false,
        });
        assert!(
            !discarded,
            "the recapture discarded the image it was supposed to be writing a slab of"
        );

        captured.destroy(device.as_ref());
        recorder.assert_valid();
    }
}