sgl-3d 0.9.2

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
//! The volumetric fog in real frames: a medium without density leaves the
//! frame as no fog does; a point light's scattering along a froxel column
//! matches a numerical single-scattering integral along its view ray; a
//! shadowed light, local or directional, scatters nothing in the medium its
//! occluder hides from it; the filter blurs each slice by Godot's Gaussian
//! while the history stays unfiltered; a light's fog energy scales its
//! light in the medium and nowhere else; fog volumes add their medium to
//! every froxel they reach; the sky takes its sky affect of the fog; and a
//! light's shadow opacity blends its shadow toward unshadowed on surfaces
//! and in the medium alike; and the frame's medium begins `Fog::start` from
//! the eye while fog volumes nearer still fog.
use super::froxels;
use crate::renderer::test_frame::TestRenderer;
use crate::settings::{self, FogQuality, Settings};
use crate::shading::gbuffer;
use crate::{
    Backdrop, Camera, DirectionalLight, DirectionalShadow, Fog, FrameInput, HemisphereLight,
    InstanceState, Light, LightShape, Mobility, Scene, test_support,
};
use glam::{Mat4, Quat, Vec2, Vec3};

const SIZE: [u32; 2] = [160, 90];
const QUALITY: FogQuality = FogQuality::High;

fn projection() -> Mat4 {
    crate::perspective(1., SIZE[0] as f32 / SIZE[1] as f32, 0.1)
}

fn settings(atmosphere: bool) -> Settings {
    Settings {
        antialiasing: settings::Antialiasing::Off,
        bloom: settings::Bloom::Off,
        atmosphere,
        fog_quality: QUALITY,
        ..Settings::default()
    }
}

/// A camera at the origin looking down -Z over a black backdrop, its
/// atmosphere on so that the settings decide whether the fog runs.
fn input(fog: Fog) -> FrameInput {
    let mut input = FrameInput::new(Camera {
        view: Mat4::IDENTITY,
        projection: projection(),
        eye: Vec3::ZERO,
    });
    input.backdrop = Backdrop::Color([0.; 3]);
    input.atmosphere = true;
    input.fog = fog;
    input
}

/// `frames` frames of `scene` seen as `input`, the first a camera cut.
fn render(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    scene: &mut Scene,
    input: &FrameInput,
    settings: &Settings,
    frames: usize,
) -> TestRenderer {
    let mut renderer = TestRenderer::for_test(device, queue, SIZE, settings);
    let output = crate::view::targets::target(device, "fog frames", SIZE, gbuffer::COLOR);
    for frame in 0..frames {
        let mut input = *input;
        input.camera_cut = frame == 0;
        let mut encoder = device.create_command_encoder(&Default::default());
        renderer.render(
            device,
            queue,
            &mut encoder,
            scene,
            &input,
            settings,
            &output,
            None,
        );
        queue.submit([encoder.finish()]);
        renderer.finish_frame(scene);
    }
    renderer
}

// Defect: reprojecting a volume written with a different Fog::length reads
// density from another world position, as Godot's lookup through the
// current length does. The frame after the change reprojects its
// predecessor (V-3), so the independent oracle is a fixed box at 4..6 m:
// its interior keeps its authored density and empty space stays empty when
// only the covered range grows or shrinks. Shader validation cannot detect
// a valid lookup into the wrong historical grid.
#[test]
fn changing_fog_range_keeps_a_stationary_volume_in_place() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    for filter in [false, true] {
        for (before, after) in [(10., 20.), (20., 10.)] {
            let mut scene = Scene::new(&device, &queue);
            scene
                .update_fog_volumes(
                    &device,
                    &queue,
                    &[crate::FogVolume {
                        center: Vec3::new(0., 0., -5.),
                        size: Vec3::new(20., 20., 2.),
                        density: 0.1,
                        edge_fade: 0.,
                        ..Default::default()
                    }],
                )
                .unwrap();
            let mut choice = settings(true);
            choice.fog_filter = filter;
            let mut frame = input(Fog {
                length: before,
                ..Default::default()
            });
            let mut renderer = render(&device, &queue, &mut scene, &frame, &choice, 2);
            let output =
                crate::view::targets::target(&device, "fog range change", SIZE, gbuffer::COLOR);
            frame.fog.length = after;
            let mut encoder = device.create_command_encoder(&Default::default());
            renderer.render(
                &device,
                &queue,
                &mut encoder,
                &mut scene,
                &frame,
                &choice,
                &output,
                None,
            );
            queue.submit([encoder.finish()]);
            renderer.finish_frame(&mut scene);
            let view = renderer.fog_volumes()[0];
            let extent = view.texture().size();
            let density = texels(&read(&device, &queue, view));
            let size = [extent.width, extent.height, extent.depth_or_array_layers];
            let mut interior = 0;
            let mut empty = 0;
            for z in 0..size[2] {
                let depth = -froxel_center(&frame, size, [size[0] / 2, size[1] / 2, z]).z;
                let index = (z * size[0] * size[1] + size[1] / 2 * size[0] + size[0] / 2) as usize;
                let actual = density[index][3];
                if (4.5..5.5).contains(&depth) {
                    interior += 1;
                    assert!(
                        (actual - 0.1).abs() < 1e-4,
                        "{before}->{after}, filter {filter}, depth {depth}: box density {actual}"
                    );
                } else if (2.0..3.0).contains(&depth) || (9.0..11.0).contains(&depth) {
                    empty += 1;
                    assert!(
                        actual < 1e-4,
                        "{before}->{after}, filter {filter}, depth {depth}: density {actual} outside the box"
                    );
                }
            }
            assert!(
                interior > 0 && empty > 0,
                "fixture must sample the box and empty space"
            );
        }
    }
}

// Defect (O-7): a Fog::length that differs at all from the last frame's
// drops the froxels' history and jitter, so a game that computes its length
// each frame with rounding noise never accumulates: every froxel shows its
// centre's single sample. The oracle is equivalence: a length one f32 step
// apart on alternate frames moves no froxel by more than a millionth of its
// depth, so its volume must converge as the unchanged length's does. A box
// whose near face at 5 m crosses a slice, faded over Godot's 0.1 m, makes the
// froxels there differ between their centre's sample and the mean of their
// jittered ones. The bound is the half-float store: each frame's froxel is
// stored to within a step (HALF_STEP relative) and keeps 0.9 of the last,
// so two runs whose inputs agree differ by at most the steps a 0.9 history
// sums, 10 steps of the largest density.
#[test]
fn a_length_with_rounding_noise_accumulates_as_an_unchanged_one() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    const HALF_STEP: f32 = 1. / 1024.;
    const DENSITY: f32 = 0.1;
    const LENGTH: f32 = 20.;
    let settings = settings(true);
    // The froxels' extinction after 48 frames, three jitter cycles, with the
    // length on odd frames `odd`.
    let run = |odd: f32| {
        let mut scene = Scene::new(&device, &queue);
        scene
            .update_fog_volumes(
                &device,
                &queue,
                &[crate::FogVolume {
                    center: Vec3::new(0., 0., -6.),
                    size: Vec3::new(40., 40., 2.),
                    density: DENSITY,
                    edge_fade: 0.,
                    ..Default::default()
                }],
            )
            .unwrap();
        let mut frame = input(Fog {
            length: LENGTH,
            ..Default::default()
        });
        let mut renderer = TestRenderer::for_test(&device, &queue, SIZE, &settings);
        let output =
            crate::view::targets::target(&device, "fog length noise", SIZE, gbuffer::COLOR);
        for index in 0..48 {
            frame.camera_cut = index == 0;
            frame.fog.length = if index % 2 == 1 { odd } else { LENGTH };
            let mut encoder = device.create_command_encoder(&Default::default());
            renderer.render(
                &device,
                &queue,
                &mut encoder,
                &mut scene,
                &frame,
                &settings,
                &output,
                None,
            );
            queue.submit([encoder.finish()]);
            renderer.finish_frame(&mut scene);
        }
        let view = renderer.fog_volumes()[0];
        texels(&read(&device, &queue, view))
            .into_iter()
            .map(|texel| texel[3])
            .collect::<Vec<_>>()
    };
    let steady = run(LENGTH);
    let noisy = run(LENGTH.next_up());
    let partial = steady
        .iter()
        .filter(|&&d| d > 0.05 * DENSITY && d < 0.95 * DENSITY)
        .count();
    assert!(
        partial > 0,
        "the box's face must leave froxels partly inside it"
    );
    let bound = 10. * HALF_STEP * DENSITY;
    let (worst, at) = steady
        .iter()
        .zip(&noisy)
        .map(|(a, b)| (a - b).abs())
        .enumerate()
        .fold(
            (0f32, 0),
            |(worst, at), (i, d)| {
                if d > worst { (d, i) } else { (worst, at) }
            },
        );
    assert!(
        worst <= bound,
        "a length alternating by one f32 step left froxel {at} at {} where the unchanged length's is {} ({worst} apart, bound {bound}; {partial} froxels partly in the box)",
        noisy[at],
        steady[at]
    );
}

fn texels(bytes: &[u8]) -> Vec<[f32; 4]> {
    bytes
        .chunks_exact(8)
        .map(|texel| std::array::from_fn(|channel| test_support::half(&texel[channel * 2..])))
        .collect()
}

fn read(device: &wgpu::Device, queue: &wgpu::Queue, view: &wgpu::TextureView) -> Vec<u8> {
    test_support::read(device, queue, view.texture(), 8)
}

/// A static occluder: `test_support::cube` scaled by `scale` about `center`.
fn add_box(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    scene: &mut Scene,
    center: Vec3,
    scale: Vec3,
) {
    let ids = scene
        .add_asset(device, queue, test_support::cube())
        .unwrap();
    scene
        .add_instance(
            device,
            queue,
            InstanceState {
                model: ids.model,
                pose: Mat4::from_translation(center) * Mat4::from_scale(scale),
                visible: true,
                capture_visible: true,
            },
            Mobility::Static,
        )
        .unwrap();
}

/// The world position of froxel `index` of a volume of `size` seen by
/// `input`'s camera at the origin, without jitter: the centre of its
/// column at the centre of its slice.
fn froxel_center(input: &FrameInput, size: [u32; 3], index: [u32; 3]) -> Vec3 {
    let (ndc, depth) = froxel_ray(input, size, [index[0], index[1]], index[2]);
    view_ray(input, ndc) * depth
}

/// Column `column`'s frame position and slice `slice`'s view depth, from
/// the frame's geometry: columns split the frame evenly, and slices split
/// the fog's length as the volume's detail spread spaces them.
fn froxel_ray(input: &FrameInput, size: [u32; 3], column: [u32; 2], slice: u32) -> (Vec2, f32) {
    let u = (column[0] as f32 + 0.5) / size[0] as f32;
    let v = (column[1] as f32 + 0.5) / size[1] as f32;
    let unit = (slice as f32 + 0.5) / size[2] as f32;
    let depth = input.fog.length * unit.powf(crate::shading::fog::DETAIL_SPREAD);
    (Vec2::new(u * 2. - 1., 1. - v * 2.), depth)
}

/// The view-space point a metre deep under frame position `ndc`, which the
/// camera's projection maps there.
fn view_ray(input: &FrameInput, ndc: Vec2) -> Vec3 {
    let p = input.camera.projection;
    Vec3::new(
        (ndc.x + p.z_axis.x) / p.x_axis.x,
        (ndc.y + p.z_axis.y) / p.y_axis.y,
        -1.,
    )
}

// Defect: the volume's split leaves its froxels far from square, or a side
// past the device's 3D texture limit as the frame narrows (at 60×1900 High
// asked for 2090 froxels tall, past WebGPU's default 2048), so creating the
// volume fails. The oracle is the documented sizing: a frame and its
// transpose take transposed volumes, each froxel covers as many pixels
// across as down up to truncating its counts, and no side leaves
// 1..=limit.
#[test]
fn froxels_stay_square_and_within_the_texture_limit_however_thin_the_frame() {
    const LIMIT: u32 = 2048;
    for quality in [FogQuality::Low, FogQuality::High] {
        for render in [[60, 1900], [1900, 60], [40, 1300], [1920, 1080], [7, 7]] {
            let [x, y, _] = froxels(quality, render, LIMIT);
            let [across, down, _] = froxels(quality, [render[1], render[0]], LIMIT);
            assert_eq!([x, y], [down, across], "{quality:?} {render:?} transposed");
            let aspect = (render[0] as f32 / x as f32) / (render[1] as f32 / y as f32);
            let truncation = (x + 1) as f32 / x as f32 * (y + 1) as f32 / y as f32;
            assert!(
                aspect.max(aspect.recip()) <= truncation,
                "{quality:?} {render:?}: {x}×{y} froxels, aspect {aspect}"
            );
        }
        for render in [[1, 1 << 20], [1 << 20, 1]] {
            let [x, y, _] = froxels(quality, render, LIMIT);
            assert!(
                (1..=LIMIT).contains(&x) && (1..=LIMIT).contains(&y),
                "{quality:?} {render:?}: {x}×{y} froxels"
            );
        }
    }
}

// Defect: the fog adds light or dims where the medium has no density, or
// the composition is not color * transmittance + scattering, so the frame
// with an empty medium, skipped or run, differs from the frame with no fog.
// The run's integrated volume must be exactly clear, and a denser medium
// must change the frame.
#[test]
fn an_empty_medium_leaves_the_frame_as_no_fog_does() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    add_box(
        &device,
        &queue,
        &mut scene,
        Vec3::new(0., -0.5, -6.),
        Vec3::new(3., 1., 3.),
    );
    // All of the hemisphere fill's ambient light, so the ambient's
    // scattering is among what an empty medium must not add.
    let mut frame = input(Fog {
        density: 0.,
        length: 30.,
        anisotropy: 0.5,
        ambient: 1.,
        ..Fog::default()
    });
    frame.directional_lights[0] = Some(DirectionalLight {
        direction: Vec3::new(0.3, -1., -0.4),
        color: [1., 0.9, 0.8],
        illuminance: 4.,
        shadow: Some(DirectionalShadow {
            distance: 30.,
            cascades: 2,
        }),
        ..Default::default()
    });
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.4, 0.5, 0.7],
        ground_color: [0.1, 0.1, 0.1],
        intensity: 1.,
    };
    frame.backdrop = Backdrop::Color([0.2, 0.3, 0.45]);
    let composite = |renderer: &TestRenderer| read(&device, &queue, &renderer.targets().composite);
    let unfogged = composite(&render(
        &device,
        &queue,
        &mut scene,
        &frame,
        &settings(false),
        1,
    ));
    // Without a medium the fog has nothing to do.
    let skipped = composite(&render(
        &device,
        &queue,
        &mut scene,
        &frame,
        &settings(true),
        1,
    ));
    assert!(skipped == unfogged, "no medium changed the frame");
    // An empty fog volume runs the fog over a medium without density; the
    // second frame reprojects the first's volume.
    scene
        .update_fog_volumes(
            &device,
            &queue,
            &[crate::FogVolume {
                center: Vec3::new(0., 0., -6.),
                rotation: glam::Quat::IDENTITY,
                size: Vec3::splat(4.),
                density: 0.,
                albedo: [1.; 3],
                edge_fade: 0.,
            }],
        )
        .unwrap();
    let empty = render(&device, &queue, &mut scene, &frame, &settings(true), 2);
    let integrated = texels(&read(&device, &queue, empty.fog_volumes()[2]));
    assert!(
        integrated.iter().all(|texel| *texel == [0., 0., 0., 1.]),
        "an empty medium scattered or dimmed"
    );
    assert!(
        composite(&empty) == unfogged,
        "an empty medium changed the frame"
    );
    frame.fog.density = 0.05;
    let dense = composite(&render(
        &device,
        &queue,
        &mut scene,
        &frame,
        &settings(true),
        1,
    ));
    assert!(dense != unfogged, "a dense medium left the frame unfogged");
}

/// Henyey-Greenstein's phase function.
fn henyey_greenstein(cos_theta: f32, g: f32) -> f32 {
    (1. - g * g) / (4. * std::f32::consts::PI * (1. + g * g - 2. * g * cos_theta).powf(1.5))
}

// Defect: the injection's units, phase, light attenuation or albedo, or the
// integration's step or extinction, are wrong. The
// reference integrates single scattering along each column's view ray from
// the camera to a slice's centre by brute force: a homogeneous medium's
// transmittance exp(-sigma t) (Beer-Lambert) times what it scatters from a
// point light of known intensity, inverse-square falloff and range window
// (the light's documented attenuation), weighted by the phase function.
#[test]
fn point_light_scattering_matches_a_single_scattering_integral() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    let light_position = Vec3::new(1.2, 1.2, -4.5);
    let intensity = 40.;
    let range = 25.;
    scene
        .add_light(
            &device,
            &queue,
            Light {
                position: light_position,
                shape: LightShape::Point {
                    radius: LightShape::DEFAULT_RADIUS,
                },
                color: [1.; 3],
                intensity,
                range,
                baked: false,
                specular: 1.,
                casts_shadow: false,
                ..Default::default()
            },
        )
        .unwrap();
    let fog = Fog {
        density: 0.06,
        albedo: [1., 0.5, 0.25],
        anisotropy: 0.4,
        length: 10.,
        ..Fog::default()
    };
    let frame = input(fog);
    let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    let integrated = texels(&read(&device, &queue, renderer.fog_volumes()[2]));
    let mut checked = 0;
    for column in [
        [size[0] / 2, size[1] / 2],
        [size[0] * 3 / 4, size[1] / 2],
        [size[0] / 3, size[1] / 3],
        [size[0] * 2 / 3, size[1] * 2 / 3],
    ] {
        let along = view_ray(&frame, froxel_ray(&frame, size, column, 0).0);
        let direction = along.normalize();
        // Close passes concentrate the light into a few slices, where the
        // froxels' resolution, not the method, limits agreement.
        let closest = (light_position - direction * light_position.dot(direction)).length();
        assert!(
            closest > 1.,
            "column {column:?} passes {closest} m from the light"
        );
        for slice in [size[2] / 4, size[2] / 2, size[2] * 3 / 4, size[2] - 1] {
            let distance = froxel_ray(&frame, size, column, slice).1 * along.length();
            let steps = 20_000;
            let step = distance / steps as f32;
            let mut reference = [0f32; 3];
            for index in 0..steps {
                let t = (index as f32 + 0.5) * step;
                let point = direction * t;
                let to_light = light_position - point;
                let square = to_light.length_squared();
                let window = (1. - (square / (range * range)).powi(2))
                    .clamp(0., 1.)
                    .powi(2);
                let irradiance = intensity * window / square.max(1e-4);
                let phase = henyey_greenstein(direction.dot(to_light.normalize()), fog.anisotropy);
                let attenuated = irradiance * phase * (-fog.density * t).exp() * step;
                for (sum, albedo) in reference.iter_mut().zip(fog.albedo) {
                    *sum += fog.density * albedo * attenuated;
                }
            }
            let texel = integrated[((slice * size[1] + column[1]) * size[0] + column[0]) as usize];
            for channel in 0..3 {
                let error = (texel[channel] - reference[channel]).abs();
                assert!(
                    error <= 0.03 * reference[channel] + 1e-4,
                    "column {column:?} slice {slice} channel {channel}: {} against the integral's {}",
                    texel[channel],
                    reference[channel]
                );
            }
            let transmittance = (-fog.density * distance).exp();
            assert!(
                (texel[3] - transmittance).abs() <= 2e-3,
                "column {column:?} slice {slice}: transmittance {} against Beer-Lambert's {transmittance}",
                texel[3]
            );
            checked += usize::from(reference[0] > 1e-3);
        }
    }
    assert!(
        checked >= 8,
        "too few samples carry measurable light: {checked}"
    );
}

// Defect: one jittered sample per froxel of a point light's inverse square
// spikes to thousands of times the froxel's light whenever it lands
// centimetres from the light, and the reprojected history holds each spike
// for frames, so the fog about a still light pulses with the 16-frame jitter
// cycle (and a moving light leaves puffs behind it). A still scene's fog
// must hold still: once the history has settled, the froxel holding the
// light changes by at most a quarter over a whole jitter cycle, on the
// view's axis and at the frame's corners, where the frustum shears a froxel
// half a metre across. The bound follows from the froxel's geometry, not from a
// measurement: with the light at the centre of the froxel's bounding box in
// view space, every jittered sample lies within half the box's diagonal b of
// it, so with b² added to the inverse square's denominator, as the medium
// takes it, each sample's 1/(d² + b²) lies between 1/(1.25 b²) and 1/b², a
// quarter apart at most, and so does any history mix of them. Unbiased, 1/d²
// ranges a thousandfold between the samples.
#[test]
fn a_still_point_light_holds_its_froxel_steady_over_the_jitter_cycle() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.,
        // Slices metres deep a few metres out, as a long fog's are.
        length: 100.,
        ..Fog::default()
    };
    let frame = input(fog);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    // A froxel's corner at unit coordinates `unit` of the volume, in view
    // space (the camera's view is the identity), from the frame's geometry.
    let corner = |unit: Vec3| {
        let ndc = Vec2::new(unit.x * 2. - 1., 1. - unit.y * 2.);
        view_ray(&frame, ndc) * fog.length * unit.z.powf(crate::shading::fog::DETAIL_SPREAD)
    };
    // Froxels about 4 m out, their slices 0.6 m deep and their columns about
    // 5 cm across: on the view's axis, and at the frame's top-left and
    // bottom-right corners.
    for column in [
        [size[0] / 2, size[1] / 2],
        [1, 1],
        [size[0] - 2, size[1] - 2],
    ] {
        let index = [column[0], column[1], 12];
        let (mut low, mut high) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
        for offset in 0..8u32 {
            let unit = Vec3::new(
                (index[0] + (offset & 1)) as f32 / size[0] as f32,
                (index[1] + (offset >> 1 & 1)) as f32 / size[1] as f32,
                (index[2] + (offset >> 2)) as f32 / size[2] as f32,
            );
            let p = corner(unit);
            low = low.min(p);
            high = high.max(p);
        }
        let mut scene = Scene::new(&device, &queue);
        scene
            .add_light(
                &device,
                &queue,
                Light {
                    position: (low + high) * 0.5,
                    shape: LightShape::Point {
                        radius: LightShape::DEFAULT_RADIUS,
                    },
                    color: [1.; 3],
                    intensity: 10.,
                    range: 25.,
                    baked: false,
                    specular: 1.,
                    casts_shadow: false,
                    ..Default::default()
                },
            )
            .unwrap();
        let settings = settings(true);
        let mut renderer = TestRenderer::for_test(&device, &queue, SIZE, &settings);
        let output = crate::view::targets::target(&device, "fog frames", SIZE, gbuffer::COLOR);
        let at = ((index[2] * size[1] + index[1]) * size[0] + index[0]) as usize;
        let mut light = Vec::new();
        // Three jitter cycles: two for the history to settle, the third read.
        for frame_index in 0..48 {
            let mut input = frame;
            input.camera_cut = frame_index == 0;
            let mut encoder = device.create_command_encoder(&Default::default());
            renderer.render(
                &device,
                &queue,
                &mut encoder,
                &mut scene,
                &input,
                &settings,
                &output,
                None,
            );
            queue.submit([encoder.finish()]);
            renderer.finish_frame(&mut scene);
            if frame_index >= 32 {
                light.push(texels(&read(&device, &queue, renderer.fog_volumes()[0]))[at][0]);
            }
        }
        let (least, most) = light
            .iter()
            .fold((f32::MAX, 0f32), |(least, most), &value| {
                (least.min(value), most.max(value))
            });
        assert!(
            least > 1e-3,
            "froxel {index:?}, holding the light, is unlit: {light:?}"
        );
        assert!(
            most <= 1.25 * least,
            "froxel {index:?}, holding a still light, ranged {least} to {most} over a jitter cycle: {light:?}"
        );
    }
}

// Defect: the medium's bias of a light's inverse square depends on where
// the froxel lies on screen, as one oblique corner-to-corner vector of a
// froxel the frustum shears does: such a measure differs between a froxel
// and its mirror image across the view's axis, so a light near the camera
// would hold different fog on either side of the screen. The camera's
// projection is symmetric, so a light and its mirror image each lit in the
// froxel holding it must hold the same light there, at every corner of the
// frame, within the half-float volume's rounding.
#[test]
fn a_light_holds_the_same_fog_on_either_side_of_the_screen() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.,
        length: 100.,
        ..Fog::default()
    };
    let frame = input(fog);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    // The light a centimetre toward the camera from the centre of froxel
    // `index`, alone (a light exactly at a sample has no direction and
    // lights nothing there); the froxel's light on the first frame, which
    // samples froxel centres.
    let held = |index: [u32; 3]| {
        let mut scene = Scene::new(&device, &queue);
        scene
            .add_light(
                &device,
                &queue,
                Light {
                    position: {
                        let center = froxel_center(&frame, size, index);
                        center - center.normalize() * 0.01
                    },
                    shape: LightShape::Point {
                        radius: LightShape::DEFAULT_RADIUS,
                    },
                    color: [1.; 3],
                    intensity: 10.,
                    range: 25.,
                    baked: false,
                    specular: 1.,
                    casts_shadow: false,
                    ..Default::default()
                },
            )
            .unwrap();
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let at = ((index[2] * size[1] + index[1]) * size[0] + index[0]) as usize;
        texels(&read(&device, &queue, renderer.fog_volumes()[0]))[at][0]
    };
    for (column, slice) in [([1, 1], 12), ([size[0] - 2, 1], 12), ([3, 5], 20)] {
        let index = [column[0], column[1], slice];
        let mirror = [size[0] - 1 - column[0], size[1] - 1 - column[1], slice];
        let (light, mirrored) = (held(index), held(mirror));
        assert!(
            light > 1e-3,
            "froxel {index:?}, holding the light, is unlit"
        );
        assert!(
            (light - mirrored).abs() <= 4e-3 * light,
            "froxel {index:?} holds {light} of a light at its centre, its mirror image {mirror:?} {mirrored}"
        );
    }
}

// Defect: the medium's bias of a light's inverse square reaches froxels far
// smaller than their distance to the light, dimming a distant light's fog.
// There the bias is the froxel's squared diagonal over thousands of square
// metres, under a thousandth, so each froxel's first-frame light (its centre,
// unjittered) must equal the light's physical falloff at that centre
// (the light's documented attenuation and the phase function), within the
// half-float volume's rounding.
#[test]
fn froxels_far_smaller_than_their_distance_to_a_light_keep_its_falloff() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.,
        // Slices a few centimetres deep near the camera.
        length: 10.,
        ..Fog::default()
    };
    let frame = input(fog);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    // Far ahead of and beside the near froxels below: 4 m and more away from
    // froxels at most about 3 cm across.
    let light_position = Vec3::new(1.5, 0.5, -5.5);
    let intensity = 40.;
    let range = 25.;
    let mut scene = Scene::new(&device, &queue);
    scene
        .add_light(
            &device,
            &queue,
            Light {
                position: light_position,
                shape: LightShape::Point {
                    radius: LightShape::DEFAULT_RADIUS,
                },
                color: [1.; 3],
                intensity,
                range,
                baked: false,
                specular: 1.,
                casts_shadow: false,
                ..Default::default()
            },
        )
        .unwrap();
    let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
    let written = texels(&read(&device, &queue, renderer.fog_volumes()[0]));
    let mut checked = 0;
    for slice in [8, 12, 16] {
        for column in [
            [size[0] / 2, size[1] / 2],
            [size[0] / 4, size[1] / 3],
            [size[0] * 3 / 4, size[1] * 2 / 3],
        ] {
            let index = [column[0], column[1], slice];
            let center = froxel_center(&frame, size, index);
            let square = (light_position - center).length_squared();
            let window = (1. - (square / (range * range)).powi(2))
                .clamp(0., 1.)
                .powi(2);
            let expected =
                fog.density * intensity * window / square * henyey_greenstein(0., fog.anisotropy);
            let texel = written[((slice * size[1] + column[1]) * size[0] + column[0]) as usize][0];
            assert!(
                (texel - expected).abs() <= 2e-3 * expected,
                "froxel {index:?}, {} m from the light: {texel} against its falloff's {expected}",
                square.sqrt()
            );
            checked += 1;
        }
    }
    assert_eq!(checked, 9);
}

/// Godot's filter weights (b130438 `volumetric_fog_process.glsl`
/// MODE_FILTER `gauss`), from three froxels before to three after.
const GODOT_GAUSS: [f32; 7] = [
    0.071303, 0.131514, 0.189879, 0.214607, 0.189879, 0.131514, 0.071303,
];

/// `volume` of `size` blurred along `axis` (0 x, 1 y) by Godot's weights,
/// its coordinates clamped to the volume as Godot clamps them.
fn godot_gaussian(volume: &[[f32; 4]], size: [u32; 3], axis: usize) -> Vec<[f32; 4]> {
    let index = |at: [u32; 3]| ((at[2] * size[1] + at[1]) * size[0] + at[0]) as usize;
    let mut blurred = vec![[0.; 4]; volume.len()];
    for z in 0..size[2] {
        for y in 0..size[1] {
            for x in 0..size[0] {
                let at = [x, y, z];
                let sum = &mut blurred[index(at)];
                for (tap, weight) in GODOT_GAUSS.iter().enumerate() {
                    let mut from = at;
                    from[axis] =
                        (at[axis] as i32 + tap as i32 - 3).clamp(0, size[axis] as i32 - 1) as u32;
                    for (channel, value) in volume[index(from)].iter().enumerate() {
                        sum[channel] += weight * value;
                    }
                }
            }
        }
    }
    blurred
}

// Defect: the filter takes other weights, axes or edges than Godot's, the
// integration reads the unfiltered froxels, or the filter reaches the history
// the next frame reprojects, which Godot copies before it filters, or it
// leaves a channel out. Over two frames of a point light in a medium whose
// density falls with height, so its light and its extinction both vary
// across the frame, the froxels the frame wrote are the same with the filter
// as without, the froxels it integrates are Godot's Gaussian of them along x
// and then y within half-float rounding, and the integrated volume differs
// from the unfiltered one.
#[test]
fn the_filter_blurs_each_slice_by_godots_gaussian_and_leaves_the_history_unfiltered() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    scene
        .add_light(
            &device,
            &queue,
            Light {
                position: Vec3::new(0.5, 0.3, -3.),
                shape: LightShape::Point {
                    radius: LightShape::DEFAULT_RADIUS,
                },
                color: [1.; 3],
                intensity: 40.,
                range: 25.,
                baked: false,
                specular: 1.,
                casts_shadow: false,
                ..Default::default()
            },
        )
        .unwrap();
    let frame = input(Fog {
        density: 0.06,
        height: -1.,
        height_falloff: 3.,
        length: 10.,
        ..Fog::default()
    });
    let mut volumes = |fog_filter: bool| {
        let settings = Settings {
            fog_filter,
            ..settings(true)
        };
        let renderer = render(&device, &queue, &mut scene, &frame, &settings, 2);
        renderer
            .fog_volumes()
            .map(|view| texels(&read(&device, &queue, view)))
    };
    let [written, filtered, integrated] = volumes(true);
    let [unfiltered_written, _, unfiltered_integrated] = volumes(false);
    assert!(
        written == unfiltered_written,
        "the filter changed the froxels the next frame reprojects"
    );
    assert!(
        integrated != unfiltered_integrated,
        "the integration ignored the filter"
    );
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    let expected = godot_gaussian(&godot_gaussian(&written, size, 0), size, 1);
    // Two half-float roundings of non-negative sums, one per pass.
    let tolerance = |expected: f32| 2e-3 * expected + 1e-6;
    // Froxels the filter moved by far more than that, in the light (red) and
    // the extinction, where a wrong kernel would show.
    let mut spread = [0; 2];
    for (index, ((filtered, expected), written)) in
        filtered.iter().zip(&expected).zip(&written).enumerate()
    {
        for channel in 0..4 {
            assert!(
                (filtered[channel] - expected[channel]).abs() <= tolerance(expected[channel]),
                "froxel {index} channel {channel}: {} against Godot's Gaussian {}",
                filtered[channel],
                expected[channel]
            );
        }
        for (moved, channel) in spread.iter_mut().zip([0, 3]) {
            *moved += usize::from(
                (expected[channel] - written[channel]).abs() > 10. * tolerance(expected[channel]),
            );
        }
    }
    assert!(
        spread.iter().all(|moved| *moved > 10_000),
        "the filter moved only {spread:?} froxels' light and extinction"
    );
}

// Defect: the injection ignores a light's shadow, or samples it where the
// medium is not, so light leaks into the medium beneath an opaque slab.
// The occluder's geometry decides: froxels well below the slab, within the
// light's reach, see none of a local light and, through Godot's fog tap,
// at most exp(-10 x the metres they lie behind the slab's top) of the
// directional light; froxels above it see it.
#[test]
fn shadowed_lights_scatter_almost_nothing_behind_their_occluder() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.1,
        anisotropy: 0.,
        length: 20.,
        ..Fog::default()
    };
    // The slab spans y 1.4..1.6 and x and z ±20 about (0, -10).
    let slab = |device: &wgpu::Device, queue: &wgpu::Queue| {
        let mut scene = Scene::new(device, queue);
        add_box(
            device,
            queue,
            &mut scene,
            Vec3::new(0., 1.5, -10.),
            Vec3::new(40., 0.2, 40.),
        );
        scene
    };
    let spot = Vec3::new(0., 4., -10.);
    // Where each light reaches the medium.
    let reached = |local: bool, point: Vec3| {
        if local {
            // Within the spot's inner cone and range.
            let below = spot.y - point.y;
            let across = Vec3::new(point.x - spot.x, 0., point.z - spot.z).length();
            below > 0.5 && across < below * 0.6f32.tan() && (spot - point).length() < 12.
        } else {
            // Beneath the slab, away from its edges along the light.
            point.x.abs() < 15. && point.z < -2. && point.z > -25.
        }
    };
    for (label, local) in [("local atlas", true), ("directional cascades", false)] {
        let mut scene = slab(&device, &queue);
        let mut frame = input(fog);
        if local {
            scene
                .add_light(
                    &device,
                    &queue,
                    Light {
                        position: spot,
                        shape: LightShape::Spot {
                            direction: Vec3::NEG_Y,
                            inner_angle: 0.6,
                            outer_angle: 0.9,
                            radius: LightShape::DEFAULT_RADIUS,
                        },
                        color: [1.; 3],
                        intensity: 100.,
                        range: 15.,
                        baked: false,
                        specular: 1.,
                        casts_shadow: true,
                        ..Default::default()
                    },
                )
                .unwrap();
        } else {
            frame.directional_lights[0] = Some(DirectionalLight {
                direction: Vec3::new(0.2, -1., 0.1),
                color: [1.; 3],
                illuminance: 5.,
                shadow: Some(DirectionalShadow {
                    distance: 40.,
                    cascades: 2,
                }),
                ..Default::default()
            });
        }
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
        let froxels = texels(&read(&device, &queue, renderer.fog_volumes()[0]));
        let (mut below, mut above) = (Vec::new(), Vec::new());
        for z in 0..size[2] {
            for y in 0..size[1] {
                for x in 0..size[0] {
                    let point = froxel_center(&frame, size, [x, y, z]);
                    if !reached(local, point) || point.z > -1. {
                        continue;
                    }
                    let light = froxels[((z * size[1] + y) * size[0] + x) as usize][0];
                    if point.y < 0.4 {
                        below.push(light);
                    } else if point.y > 2.6 {
                        above.push(light);
                    }
                }
            }
        }
        assert!(
            below.len() > 100 && above.len() > 10,
            "{label}: {} froxels below and {} above",
            below.len(),
            above.len()
        );
        let darkest_above = above.iter().copied().fold(f32::MAX, f32::min);
        let brightest_below = below.iter().copied().fold(0., f32::max);
        assert!(darkest_above > 0., "{label}: lit medium scattered nothing");
        // Froxels below y 0.4 lie at least 1.2 m behind the slab's top.
        let most_below = if local {
            0.
        } else {
            darkest_above * (-10f32 * 1.2).exp()
        };
        assert!(
            brightest_below <= most_below,
            "{label}: {brightest_below} scattered beneath the occluder, against {darkest_above} above it"
        );
    }
}

// Defect: a light's fog energy does not scale what it scatters in the
// medium, a light at 0 still scatters there, or the energy reaches its
// surface lighting. The reference is the same light's in-scatter at fog
// energy 1, measured froxel by froxel: at 2 each froxel holds twice it, at
// 0 none, and without fog the frame is the same, and lit, at 0 as at 1.
#[test]
fn fog_energy_scales_a_light_in_the_medium_alone() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.3,
        length: 20.,
        ..Fog::default()
    };
    for (label, local) in [("scene light", true), ("directional light", false)] {
        // Each froxel's in-scatter, and the frame without fog, with the light
        // at `fog_energy` over a floor beneath it.
        let observe = |fog_energy: f32| {
            let mut scene = Scene::new(&device, &queue);
            add_box(
                &device,
                &queue,
                &mut scene,
                Vec3::new(0., -2., -10.),
                Vec3::new(20., 1., 20.),
            );
            let mut frame = input(fog);
            if local {
                scene
                    .add_light(
                        &device,
                        &queue,
                        Light {
                            position: Vec3::new(0., 3., -8.),
                            shape: LightShape::Spot {
                                direction: Vec3::NEG_Y,
                                inner_angle: 0.5,
                                outer_angle: 0.8,
                                radius: LightShape::DEFAULT_RADIUS,
                            },
                            intensity: 60.,
                            range: 12.,
                            casts_shadow: true,
                            fog_energy,
                            ..Light::default()
                        },
                    )
                    .unwrap();
            } else {
                frame.directional_lights[0] = Some(DirectionalLight {
                    direction: Vec3::new(0.2, -1., 0.1),
                    illuminance: 3.,
                    shadow: Some(DirectionalShadow {
                        distance: 30.,
                        cascades: 2,
                    }),
                    fog_energy,
                    ..DirectionalLight::default()
                });
            }
            let fogged = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
            let in_scatter: Vec<[f32; 3]> = texels(&read(&device, &queue, fogged.fog_volumes()[0]))
                .into_iter()
                .map(|froxel| [froxel[0], froxel[1], froxel[2]])
                .collect();
            let unfogged = render(&device, &queue, &mut scene, &frame, &settings(false), 1);
            let surfaces = read(&device, &queue, &unfogged.targets().composite);
            (in_scatter, surfaces)
        };
        let (single, surfaces) = observe(1.);
        let lit = single
            .iter()
            .filter(|froxel| froxel.iter().any(|&channel| channel > 1e-3))
            .count();
        assert!(lit > 100, "{label}: {lit} froxels carry measurable light");
        let (double, _) = observe(2.);
        for (index, (twice, once)) in double.iter().zip(&single).enumerate() {
            for channel in 0..3 {
                let expected = 2. * once[channel];
                assert!(
                    (twice[channel] - expected).abs() <= 1e-3 * expected + 1e-6,
                    "{label}: froxel {index} channel {channel} holds {} at fog energy 2, twice {} is {expected}",
                    twice[channel],
                    once[channel]
                );
            }
        }
        let (none, surfaces_at_zero) = observe(0.);
        assert!(
            none.iter().flatten().all(|&channel| channel == 0.),
            "{label}: the medium scattered light at fog energy 0"
        );
        assert!(
            texels(&surfaces)
                .iter()
                .any(|texel| texel[..3].iter().any(|&channel| channel > 0.)),
            "{label}: the light lit no surface"
        );
        assert!(
            surfaces_at_zero == surfaces,
            "{label}: fog energy 0 changed the surfaces' light"
        );
    }
}

// Defect: a fog volume's box is placed, turned or sized wrongly, or its
// density does not add to the medium's; or its froxel bounds leave out
// froxels it reaches, at its faces or where it crosses the frame's edge,
// the camera's plane or the volume's far end, or holds the camera; or a
// froxel reads another volume's record for bounds that skip culled
// volumes; or the bounds misplace the camera (its position, turn or
// off-centre projection). The boxes' definitions decide: a froxel holds the
// frame's medium plus each box's density where its centre lies, and
// scatters an isotropic, unshadowed directional light by the albedos those
// densities weight, Godot's scattering.
#[test]
fn fog_volumes_add_their_medium_to_every_froxel_they_reach() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    // A camera away from the origin, turned, with an off-centre projection;
    // each box is placed relative to it.
    let turn = Quat::from_rotation_y(0.7);
    let world_from_camera = Mat4::from_rotation_translation(turn, Vec3::new(12., 1.5, -40.));
    let volume = |center: Vec3, rotation: Quat, size: Vec3, density: f32, albedo: [f32; 3]| {
        crate::FogVolume {
            center: world_from_camera.transform_point3(center),
            rotation: turn * rotation,
            size,
            density,
            albedo,
            edge_fade: 0.,
        }
    };
    let volumes = [
        // Behind the camera, beside the frame and beyond the volume: none
        // reaches a froxel.
        volume(
            Vec3::new(0., 0., 6.),
            Quat::IDENTITY,
            Vec3::splat(3.),
            0.5,
            [1., 0., 0.],
        ),
        volume(
            Vec3::new(-30., 0., -8.),
            Quat::IDENTITY,
            Vec3::splat(2.),
            0.5,
            [0., 1., 0.],
        ),
        volume(
            Vec3::new(0., 0., -30.),
            Quat::IDENTITY,
            Vec3::splat(4.),
            0.5,
            [0., 0., 1.],
        ),
        // Beside the camera, from behind it to in front of it.
        volume(
            Vec3::new(1.5, -1., 0.),
            Quat::IDENTITY,
            Vec3::new(1., 1., 12.),
            0.3,
            [0.2, 0.9, 0.5],
        ),
        // A tunnel holding the camera.
        volume(
            Vec3::new(0., 0., -4.),
            Quat::from_rotation_y(0.1),
            Vec3::new(6., 4., 20.),
            0.05,
            [0.5, 0.5, 1.],
        ),
        // Across the frame's left edge.
        volume(
            Vec3::new(-7.5, 0.5, -8.),
            Quat::from_rotation_y(0.4),
            Vec3::new(3., 2., 3.),
            0.2,
            [0.9, 0.3, 0.6],
        ),
        // Across the volume's far end.
        volume(
            Vec3::new(1., 1., -19.5),
            Quat::IDENTITY,
            Vec3::new(2., 2., 3.),
            0.15,
            [0.4, 0.8, 0.2],
        ),
        // Two overlapping boxes.
        volume(
            Vec3::new(0.5, 0., -9.),
            Quat::from_rotation_y(0.6) * Quat::from_rotation_x(0.3),
            Vec3::new(4., 3., 5.),
            0.2,
            [1., 0.5, 0.25],
        ),
        volume(
            Vec3::new(1.8, 0.6, -10.5),
            Quat::IDENTITY,
            Vec3::splat(3.),
            0.1,
            [0.2, 0.9, 0.6],
        ),
    ];
    let mut scene = Scene::new(&device, &queue);
    scene.update_fog_volumes(&device, &queue, &volumes).unwrap();
    let fog = Fog {
        density: 0.01,
        albedo: [1., 0.7, 0.4],
        anisotropy: 0.,
        ambient: 0.,
        length: 20.,
        ..Fog::default()
    };
    let mut frame = input(fog);
    let mut projection = projection();
    projection.z_axis.x = 0.1;
    projection.z_axis.y = -0.05;
    frame.camera = Camera {
        view: world_from_camera.inverse(),
        projection,
        eye: world_from_camera.w_axis.truncate(),
    };
    // An isotropic phase scatters 1 / (4 PI) of the illuminance toward the
    // camera, so each froxel scatters its albedo-weighted density.
    frame.directional_lights[0] = Some(DirectionalLight {
        direction: Vec3::new(0.3, -1., -0.4),
        color: [1.; 3],
        illuminance: 4. * std::f32::consts::PI,
        shadow: None,
        ..Default::default()
    });
    let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    let froxels = texels(&read(&device, &queue, renderer.fog_volumes()[0]));
    let local_from_world = volumes
        .map(|volume| Mat4::from_rotation_translation(volume.rotation, volume.center).inverse());
    let world_from_view = frame.camera.view.inverse();
    let mut reached = [0; 9];
    for z in 0..size[2] {
        for y in 0..size[1] {
            for x in 0..size[0] {
                let point =
                    world_from_view.transform_point3(froxel_center(&frame, size, [x, y, z]));
                let mut density = fog.density;
                let mut scattering = Vec3::from(fog.albedo) * fog.density;
                for (index, volume) in volumes.iter().enumerate() {
                    let local = local_from_world[index].transform_point3(point);
                    let added = volume.density * box_density(local, volume.size * 0.5);
                    density += added;
                    scattering += Vec3::from(volume.albedo) * added;
                    reached[index] += usize::from(added > 0.);
                }
                let froxel = froxels[((z * size[1] + y) * size[0] + x) as usize];
                assert!(
                    (froxel[3] - density).abs() <= 1e-3 * density + 1e-4,
                    "{point}: extinction {} against the boxes' {density}",
                    froxel[3]
                );
                for channel in 0..3 {
                    assert!(
                        (froxel[channel] - scattering[channel]).abs()
                            <= 2e-3 * scattering[channel] + 1e-4,
                        "{point} channel {channel}: scattering {} against the boxes' {}",
                        froxel[channel],
                        scattering[channel]
                    );
                }
            }
        }
    }
    assert!(
        reached[3..].iter().all(|&count| count > 50),
        "froxels inside each box: {reached:?}"
    );
}

/// The share of a box fog volume's density at `local` in the box of
/// `half_size` without edge fade: Godot's box `FogVolume`
/// (`volumetric_fog.glsl`), whose density fades in over the 0.1 m inside its
/// faces by its signed distance.
fn box_density(local: Vec3, half_size: Vec3) -> f32 {
    let q = local.abs() - half_size;
    let distance = q.max(Vec3::ZERO).length() + q.max_element().min(0.);
    let t = ((distance + 0.1) / 0.1).clamp(0., 1.);
    1. - t * t * (3. - 2. * t)
}

// Defect: a blended surface fogs itself at the wrong distance (a fragment's
// position w is one over its view depth). With no light in the medium, an
// unlit blended quad at a known depth keeps exactly the share of its colour
// that Beer-Lambert's law passes along its view ray.
#[test]
fn a_blended_surface_is_fogged_at_its_depth() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let depth = 30.;
    let mut quad = test_support::cube();
    quad.meshes[0] = crate::asset::CpuMesh {
        vertices: [(-1., -1.), (1., -1.), (1., 1.), (-1., 1.)]
            .map(|(x, y)| crate::asset::Vertex {
                tangent: [0.; 4],
                lightmap_bounds: [0., 0., 1., 1.],
                lightmap_uv: [0.; 2],
                position: [x * 4., y * 4., -depth],
                normal: [0., 0., 1.],
                uv: [(x + 1.) / 2., (1. - y) / 2.],
                color: [1.; 4],
            })
            .to_vec(),
        indices: vec![0, 1, 2, 0, 2, 3],
        material: 0,
        deformation: Default::default(),
    };
    quad.materials[0].unlit = true;
    quad.materials[0].base = [1., 0.6, 0.3, 1.];
    quad.materials[0].alpha = crate::AlphaMode::Blend {
        receives_screen_space_reflections: false,
        keeps_specular: false,
    };
    let mut scene = Scene::new(&device, &queue);
    test_support::add_static(&device, &queue, &mut scene, quad);
    let fog = Fog {
        density: 0.02,
        length: 60.,
        ..Fog::default()
    };
    let frame = input(fog);
    let centre = |atmosphere: bool| {
        let renderer = render(
            &device,
            &queue,
            &mut scene,
            &frame,
            &settings(atmosphere),
            1,
        );
        let composite = texels(&read(&device, &queue, &renderer.targets().composite));
        composite[(SIZE[1] / 2 * SIZE[0] + SIZE[0] / 2) as usize]
    };
    let [clear, fogged] = [false, true].map(centre);
    let (ndc, _) = froxel_ray(&frame, [SIZE[0], SIZE[1], 1], [SIZE[0] / 2, SIZE[1] / 2], 0);
    let transmittance = (-fog.density * depth * view_ray(&frame, ndc).length()).exp();
    for channel in 0..3 {
        let share = fogged[channel] / clear[channel];
        assert!(
            (share - transmittance).abs() < 5e-3,
            "channel {channel}: {} of the quad's colour against Beer-Lambert's {transmittance}",
            share
        );
    }
}

// Defect: a coverage-blended surface adds the fog's in-scatter whole rather
// than over its covered share, as Filament ef1a133's fade mode does
// (shaders/src/surface_main.fs 83-84 scales it in the transparent mode
// alone), or its colour is not scaled by its alpha. Porter and Duff's over
// of the fogged surface is the oracle: at alpha 0.5 the frame is half the
// surface fogged as at alpha 1 and half the frame behind it without the
// surface, alpha (c T + I) + (1 - alpha) behind, in a medium that scatters
// the hemisphere fill, so that I and the fogged sky behind are not zero.
#[test]
fn a_blended_surface_covers_its_fog_by_its_alpha() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let depth = 30.;
    let mut quad = test_support::cube();
    quad.meshes[0] = crate::asset::CpuMesh {
        vertices: [(-1., -1.), (1., -1.), (1., 1.), (-1., 1.)]
            .map(|(x, y)| crate::asset::Vertex {
                tangent: [0.; 4],
                lightmap_bounds: [0., 0., 1., 1.],
                lightmap_uv: [0.; 2],
                position: [x * 4., y * 4., -depth],
                normal: [0., 0., 1.],
                uv: [(x + 1.) / 2., (1. - y) / 2.],
                color: [1.; 4],
            })
            .to_vec(),
        indices: vec![0, 1, 2, 0, 2, 3],
        material: 0,
        deformation: Default::default(),
    };
    quad.materials[0].unlit = true;
    quad.materials[0].base = [1., 0.6, 0.3, 1.];
    quad.materials[0].alpha = crate::AlphaMode::Blend {
        receives_screen_space_reflections: false,
        keeps_specular: false,
    };
    let mut scene = Scene::new(&device, &queue);
    let (ids, instance) = test_support::add_static(&device, &queue, &mut scene, quad);
    let fog = Fog {
        density: 0.02,
        length: 60.,
        ambient: 1.,
        ..Fog::default()
    };
    let mut frame = input(fog);
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.4, 0.5, 0.7],
        ground_color: [0.4, 0.5, 0.7],
        intensity: 1.,
    };
    let mut centre = |alpha: Option<f32>| {
        let mut values = scene.material(ids.materials[0]).unwrap();
        values.base[3] = alpha.unwrap_or(1.);
        scene
            .set_material(&queue, ids.materials[0], values)
            .unwrap();
        let mut state = *scene.instance(instance).unwrap();
        state.visible = alpha.is_some();
        scene.set_instance(&queue, instance, state).unwrap();
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let composite = texels(&read(&device, &queue, &renderer.targets().composite));
        composite[(SIZE[1] / 2 * SIZE[0] + SIZE[0] / 2) as usize]
    };
    let [whole, half, behind] = [Some(1.), Some(0.5), None].map(&mut centre);
    let (ndc, _) = froxel_ray(&frame, [SIZE[0], SIZE[1], 1], [SIZE[0] / 2, SIZE[1] / 2], 0);
    let transmittance = (-fog.density * depth * view_ray(&frame, ndc).length()).exp();
    for channel in 0..3 {
        let in_scatter = whole[channel] - [1., 0.6, 0.3][channel] * transmittance;
        assert!(
            in_scatter > 0.02 && behind[channel] > 0.02,
            "channel {channel}: too little in-scatter ({in_scatter}) or fogged sky ({}) to tell \
             a share of it",
            behind[channel]
        );
        let expected = 0.5 * whole[channel] + 0.5 * behind[channel];
        assert!(
            (half[channel] - expected).abs() <= 5e-3 * expected + 1e-3,
            "channel {channel}: {} at alpha 0.5, against Porter and Duff's over {expected} \
             of {} at alpha 1 and {} behind",
            half[channel],
            whole[channel],
            behind[channel]
        );
    }
}

// Defect: additive glow adds the fog's in-scatter on top of a background
// that already holds it (D-44), so a black glow brightens the fog and N
// layers add it N times, or its own light is not dimmed by the medium in
// front of it. An unshadowed light at a known depth reaches the camera
// through Beer-Lambert's transmittance alone: in a medium that scatters the
// hemisphere fill, a glow of colour c at alpha 1 raises the frame by c T,
// and a black one leaves it unchanged.
#[test]
fn glow_adds_its_light_through_the_fog_and_none_of_its_in_scatter() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let depth = 30.;
    let fog = Fog {
        density: 0.02,
        length: 60.,
        ambient: 1.,
        ..Fog::default()
    };
    let mut frame = input(fog);
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.4, 0.5, 0.7],
        ground_color: [0.4, 0.5, 0.7],
        intensity: 1.,
    };
    let mut scene = Scene::new(&device, &queue);
    let mut centre = |color: Option<[f32; 3]>| {
        let vertices = match color {
            Some([r, g, b]) => [
                [-200., -200., -depth],
                [600., -200., -depth],
                [-200., 600., -depth],
            ]
            .map(|position| crate::effects::Glow {
                position,
                color: [r, g, b, 1.],
                kind: crate::effects::GlowKind::Uniform,
                soft_distance: 0.,
            })
            .to_vec(),
            None => Vec::new(),
        };
        scene.update_effects(&device, &queue, &vertices).unwrap();
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let composite = texels(&read(&device, &queue, &renderer.targets().composite));
        composite[(SIZE[1] / 2 * SIZE[0] + SIZE[0] / 2) as usize]
    };
    let behind = centre(None);
    let (ndc, _) = froxel_ray(&frame, [SIZE[0], SIZE[1], 1], [SIZE[0] / 2, SIZE[1] / 2], 0);
    let transmittance = (-fog.density * depth * view_ray(&frame, ndc).length()).exp();
    for color in [[0.; 3], [1., 0.6, 0.3]] {
        let glowing = centre(Some(color));
        for channel in 0..3 {
            assert!(
                behind[channel] > 0.02,
                "channel {channel}: too little fog ({}) to tell its in-scatter",
                behind[channel]
            );
            let added = glowing[channel] - behind[channel];
            let expected = color[channel] * transmittance;
            assert!(
                (added - expected).abs() <= 5e-3 * expected + 1e-3,
                "glow {color:?} channel {channel}: added {added} over {} behind, against its \
                 light through Beer-Lambert's {transmittance}, {expected}",
                behind[channel]
            );
        }
    }
}

// Defect: the sky ignores `Fog::sky_affect`, it reaches the surfaces too, or
// it scales one part of the fog (its scattering or its transmittance) alone.
// Godot's sky affect (b130438 sky.glsl) mixes the sky with the fogged sky:
// at 0 the sky stays as without fog while surfaces fog as at 1, and at 0.5
// each sky texel lies halfway between those two frames.
#[test]
fn the_sky_takes_its_sky_affect_of_the_fog() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    add_box(
        &device,
        &queue,
        &mut scene,
        Vec3::new(0., -1., -6.),
        Vec3::new(4., 1., 3.),
    );
    // The medium scatters the hemisphere fill, so the sky's fog both dims it
    // and adds light.
    let mut frame = input(Fog {
        density: 0.05,
        length: 30.,
        ambient: 1.,
        ..Fog::default()
    });
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.4, 0.5, 0.7],
        ground_color: [0.1, 0.1, 0.1],
        intensity: 1.,
    };
    frame.backdrop = Backdrop::Color([0.2, 0.3, 0.45]);
    let mut composite = |frame: &FrameInput, atmosphere: bool| {
        let renderer = render(&device, &queue, &mut scene, frame, &settings(atmosphere), 1);
        texels(&read(&device, &queue, &renderer.targets().composite))
    };
    let clear = composite(&frame, false);
    let whole = composite(&frame, true);
    frame.fog.sky_affect = 0.;
    let none = composite(&frame, true);
    frame.fog.sky_affect = 0.5;
    let half = composite(&frame, true);
    // The frame's top row looks up into the sky, whose backdrop is one colour.
    let sky_colour = clear[0];
    let sky: Vec<_> = (0..clear.len())
        .filter(|&texel| clear[texel] == sky_colour)
        .collect();
    assert!(
        sky.len() < clear.len(),
        "the frame holds no surface: {sky_colour:?}"
    );
    assert!(whole[0] != clear[0], "the whole fog left the sky clear");
    for texel in 0..clear.len() {
        if sky.contains(&texel) {
            assert_eq!(
                none[texel], clear[texel],
                "texel {texel}: no sky affect fogged the sky"
            );
            for channel in 0..3 {
                let midway = (clear[texel][channel] + whole[texel][channel]) / 2.;
                assert!(
                    (half[texel][channel] - midway).abs() < 2e-3,
                    "texel {texel} channel {channel}: half the sky affect gave {} against {midway}",
                    half[texel][channel]
                );
            }
        } else {
            assert_eq!(
                none[texel], whole[texel],
                "texel {texel}: the sky affect fogged a surface"
            );
        }
    }
}

// Defect: a light's shadow opacity does not lighten its shadow, lightens it
// on surfaces or in the medium alone, or scales the light rather than its
// shadow. Godot's shadow_opacity blends the shadow toward unshadowed,
// mix(1, shadow, opacity), and lighting is linear in it: at 0.5 each
// surface texel and froxel lies halfway between the light without a shadow
// and with its whole shadow, and at 0 it is as without one.
#[test]
fn shadow_opacity_blends_a_lights_shadow_on_surfaces_and_in_the_medium() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.3,
        length: 20.,
        ..Fog::default()
    };
    for (label, local) in [("scene light", true), ("directional light", false)] {
        // Each froxel's in-scatter and the frame without fog, of a floor and
        // a slab above it shadowing part of it and of the medium, lit by the
        // light with a shadow at `opacity`, or without one.
        let observe = |opacity: Option<f32>| {
            let mut scene = Scene::new(&device, &queue);
            add_box(
                &device,
                &queue,
                &mut scene,
                Vec3::new(0., -2., -10.),
                Vec3::new(20., 1., 20.),
            );
            add_box(
                &device,
                &queue,
                &mut scene,
                Vec3::new(0., 1., -8.),
                Vec3::new(3., 0.2, 3.),
            );
            let mut frame = input(fog);
            if local {
                scene
                    .add_light(
                        &device,
                        &queue,
                        Light {
                            position: Vec3::new(0., 3., -8.),
                            shape: LightShape::Spot {
                                direction: Vec3::NEG_Y,
                                inner_angle: 0.6,
                                outer_angle: 0.9,
                                radius: LightShape::DEFAULT_RADIUS,
                            },
                            intensity: 60.,
                            range: 12.,
                            casts_shadow: opacity.is_some(),
                            shadow_opacity: opacity.unwrap_or(1.),
                            ..Light::default()
                        },
                    )
                    .unwrap();
            } else {
                frame.directional_lights[0] = Some(DirectionalLight {
                    direction: Vec3::new(0.2, -1., 0.1),
                    illuminance: 3.,
                    shadow: opacity.map(|_| DirectionalShadow {
                        distance: 30.,
                        cascades: 2,
                    }),
                    shadow_opacity: opacity.unwrap_or(1.),
                    ..DirectionalLight::default()
                });
            }
            let fogged = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
            let medium: Vec<f32> = texels(&read(&device, &queue, fogged.fog_volumes()[0]))
                .into_iter()
                .flat_map(|froxel| [froxel[0], froxel[1], froxel[2]])
                .collect();
            let unfogged = render(&device, &queue, &mut scene, &frame, &settings(false), 1);
            let surfaces: Vec<f32> = texels(&read(&device, &queue, &unfogged.targets().composite))
                .into_iter()
                .flat_map(|texel| [texel[0], texel[1], texel[2]])
                .collect();
            [medium, surfaces]
        };
        let unshadowed = observe(None);
        let shadowed = observe(Some(1.));
        let half = observe(Some(0.5));
        let clear = observe(Some(0.));
        for (part, receiver) in ["medium", "surfaces"].into_iter().enumerate() {
            let (unshadowed, shadowed, half) = (&unshadowed[part], &shadowed[part], &half[part]);
            let darkened = unshadowed
                .iter()
                .zip(shadowed)
                .filter(|(lit, dark)| *lit - *dark > 1e-2 * *lit + 1e-4)
                .count();
            assert!(
                darkened > 100,
                "{label}: the slab shadowed {darkened} values of the {receiver}"
            );
            for (index, ((lit, dark), blended)) in
                unshadowed.iter().zip(shadowed).zip(half).enumerate()
            {
                let expected = (lit + dark) / 2.;
                assert!(
                    (blended - expected).abs() <= 2e-3 * lit.abs() + 1e-4,
                    "{label}: {receiver} value {index} is {blended} at shadow opacity 0.5, halfway from {dark} to {lit} is {expected}"
                );
            }
            assert!(
                clear[part] == *unshadowed,
                "{label}: shadow opacity 0 drew a shadow on the {receiver}"
            );
        }
    }
}

// Defect: the filter overwrites the previous frame's volume but leaves its
// old camera label. A submitted frame retried without finish_frame must
// reject that volume. Black albedo scatters no light: any nonzero RGB in
// the retry's froxels is illumination retained from the overwritten volume.
#[test]
fn a_submitted_filtered_frame_is_not_reprojected_as_previous_on_retry() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let settings = Settings {
        fog_filter: true,
        ..settings(true)
    };
    let mut scene = Scene::new(&device, &queue);
    let mut frame = input(Fog {
        density: 0.05,
        length: 10.,
        albedo: [0.; 3],
        ambient: 1.,
        ..Default::default()
    });
    frame.hemisphere_light = HemisphereLight {
        sky_color: [1.; 3],
        ground_color: [1.; 3],
        intensity: 1.,
    };
    let mut renderer = TestRenderer::for_test(&device, &queue, SIZE, &settings);
    let output = crate::view::targets::target(&device, "fog retry", SIZE, gbuffer::COLOR);
    for step in 0..3 {
        frame.fog.albedo = if step == 1 { [1.; 3] } else { [0.; 3] };
        let mut encoder = device.create_command_encoder(&Default::default());
        renderer.render(
            &device,
            &queue,
            &mut encoder,
            &mut scene,
            &frame,
            &settings,
            &output,
            None,
        );
        queue.submit([encoder.finish()]);
        if step != 1 {
            renderer.finish_frame(&mut scene);
        }
        let froxels = texels(&read(&device, &queue, renderer.fog_volumes()[1]));
        let light = froxels
            .iter()
            .flat_map(|texel| &texel[..3])
            .copied()
            .fold(0f32, f32::max);
        if step == 1 {
            assert!(
                light > 0.,
                "the submitted volume must hold light to expose stale reprojection"
            );
        } else {
            assert_eq!(
                light, 0.,
                "step {step}: black albedo cannot scatter prior illumination"
            );
        }
    }
}

/// An unlit opaque square facing +Z centred on `centre`, `2 half` metres
/// across, of `colour`.
fn unlit_square(centre: Vec3, half: f32, colour: [f32; 4]) -> crate::asset::Asset {
    let mut square = test_support::cube();
    square.meshes[0] = crate::asset::CpuMesh {
        vertices: [(-1., -1.), (1., -1.), (1., 1.), (-1., 1.)]
            .map(|(x, y)| crate::asset::Vertex {
                tangent: [0.; 4],
                lightmap_bounds: [0., 0., 1., 1.],
                lightmap_uv: [0.; 2],
                position: (centre + Vec3::new(x, y, 0.) * half).to_array(),
                normal: [0., 0., 1.],
                uv: [(x + 1.) / 2., (1. - y) / 2.],
                color: [1.; 4],
            })
            .to_vec(),
        indices: vec![0, 1, 2, 0, 2, 3],
        material: 0,
        deformation: Default::default(),
    };
    square.materials[0].unlit = true;
    square.materials[0].base = colour;
    square
}

// Defects: the air composed in front of the fog (the fog's light dimmed by
// the air) or beside it (neither dimming the other), or the sky taking the
// air a second time from the volume (the sky-view table already holds it).
// The three frames share one layout, so a slice read at the wrong depth
// would cancel here; aerial_slices_past_the_fogs_length_hold_the_air_to_their_depth
// checks that against a closed form. The oracle is the architecture's composition, fog over
// air (Wicked Engine 4323a33 aerialPerspectiveCS.hlsl 82-83): each pixel
// shows the fog's light plus the fog's transmittance over the air's light
// and the air's transmittance over the surface, with the fog alone and the
// air alone measured in frames of their own: the fog alone with aerial
// perspective at 0, the air alone through a medium of the same length too
// thin to dim anything (1e-6 per metre; at 0 the fog would not run), so
// the three volumes share their slices. Unlit squares of 0 and
// then 1 at 40 m (inside the fog's 60 m) and at 200 m (beyond it) give each
// part's light (the square of 0) and transmittance (the difference); a
// strength of 50 makes their air 2 km and 10 km deep. The sun lights the
// air alone (fog energy 0). And the sky shows what it shows with aerial
// perspective at 0.
#[test]
fn the_fog_lies_over_the_air_and_the_sky_takes_the_fog_alone() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.02,
        length: 60.,
        ..Fog::default()
    };
    let mut base = input(fog);
    base.backdrop = Backdrop::Color([0.5; 3]);
    base.directional_lights[0] = Some(DirectionalLight {
        direction: -Vec3::new(0., 0.6, 0.8),
        illuminance: 1000.,
        fog_energy: 0.,
        ..DirectionalLight::default()
    });
    let depths = [40., 200.];
    let projection = projection();
    // Each square's pixel: the left at 40 m, the right at 200 m.
    let columns = [-0.3f32, 0.3].map(|ndc_offset| {
        let ndc = projection.x_axis.x * ndc_offset;
        ((ndc + 1.) / 2. * SIZE[0] as f32) as u32
    });
    let at = |column: u32| (SIZE[1] / 2 * SIZE[0] + column) as usize;
    // The squares' and the sky's texels of a frame with `aerial` strength
    // and the fog's `density`, the squares of `colour`.
    let frame = |aerial: f32, density: f32, colour: f32| {
        let mut scene = Scene::new(&device, &queue);
        for (depth, side) in depths.into_iter().zip([-0.3, 0.3]) {
            test_support::add_static(
                &device,
                &queue,
                &mut scene,
                unlit_square(
                    Vec3::new(side * depth, 0., -depth),
                    0.08 * depth,
                    [colour, colour, colour, 1.],
                ),
            );
        }
        let mut frame = base;
        frame.fog.density = density;
        frame.environment = crate::FrameEnvironment::Sky(crate::Sky {
            aerial_perspective: aerial,
            ..crate::Sky::default()
        });
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let composite = texels(&read(&device, &queue, &renderer.targets().composite));
        (columns.map(|column| composite[at(column)]), composite[0])
    };
    // Each square's light and transmittance, and the sky's texel.
    let parts = |aerial: f32, density: f32| {
        let (black, sky) = frame(aerial, density, 0.);
        let (white, _) = frame(aerial, density, 1.);
        let squares: [([f32; 3], [f32; 3]); 2] = std::array::from_fn(|square| {
            (
                std::array::from_fn(|c| black[square][c]),
                std::array::from_fn(|c| white[square][c] - black[square][c]),
            )
        });
        (squares, sky)
    };
    let (fog_alone, fog_sky) = parts(0., fog.density);
    let (air_alone, _) = parts(50., 1e-6);
    let (both, both_sky) = parts(50., fog.density);
    for (square, depth) in depths.into_iter().enumerate() {
        let ((fog_light, fog_through), (air_light, air_through)) =
            (fog_alone[square], air_alone[square]);
        let (light, through) = both[square];
        for c in 0..3 {
            assert!(
                fog_through[c] < 0.9 && air_through[c] < 0.99 && air_light[c] > 0.,
                "{depth} m channel {c}: the fog passes {}, the air {} and adds {}",
                fog_through[c],
                air_through[c],
                air_light[c]
            );
            let expected_light = fog_light[c] + fog_through[c] * air_light[c];
            let expected_through = fog_through[c] * air_through[c];
            assert!(
                (light[c] / expected_light - 1.).abs() < 0.01
                    && (through[c] / expected_through - 1.).abs() < 0.01,
                "{depth} m channel {c}: light {} and transmittance {}, the fog over the air {expected_light} and {expected_through}",
                light[c],
                through[c]
            );
        }
    }
    assert!(fog_sky[0] < 0.5, "the fog dims the sky: {fog_sky:?}");
    for c in 0..3 {
        assert!(
            (both_sky[c] - fog_sky[c]).abs() <= fog_sky[c] / 1024.,
            "channel {c}: the sky shows {} with the air, {} without",
            both_sky[c],
            fog_sky[c]
        );
    }
}

// Defect: aerial perspective coming into effect (a sky's strength rising
// from 0) starts the fog's froxel history over, though only the integrated
// volume's depth changes, so the fog pops. The oracle is equivalence: the
// froxels never depend on aerial perspective, which joins at the
// integration, so the froxels of each frame after the strength rises from
// 0 equal, texel for texel, those of the same frames of a run with it at 1
// throughout. A restarted history differs wherever a point light's falloff
// makes the jittered samples differ.
#[test]
fn aerial_perspective_coming_into_effect_keeps_the_froxels_history() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.,
        length: 30.,
        ..Fog::default()
    };
    let mut scene = Scene::new(&device, &queue);
    scene
        .add_light(
            &device,
            &queue,
            Light {
                position: Vec3::new(0.5, 0.3, -6.),
                shape: LightShape::Point {
                    radius: LightShape::DEFAULT_RADIUS,
                },
                intensity: 20.,
                range: 15.,
                casts_shadow: false,
                ..Default::default()
            },
        )
        .unwrap();
    let settings = settings(true);
    let output = crate::view::targets::target(&device, "fog frames", SIZE, gbuffer::COLOR);
    // The froxels of frames 4 and 5 under a sky whose strength is `early`
    // for frames 0 to 3 and 1 after.
    let mut froxels_after = |early: f32| {
        let mut renderer = TestRenderer::for_test(&device, &queue, SIZE, &settings);
        let mut written = Vec::new();
        for frame_index in 0..6 {
            let mut frame = input(fog);
            frame.camera_cut = frame_index == 0;
            frame.environment = crate::FrameEnvironment::Sky(crate::Sky {
                aerial_perspective: if frame_index < 4 { early } else { 1. },
                ..crate::Sky::default()
            });
            let mut encoder = device.create_command_encoder(&Default::default());
            renderer.render(
                &device,
                &queue,
                &mut encoder,
                &mut scene,
                &frame,
                &settings,
                &output,
                None,
            );
            queue.submit([encoder.finish()]);
            renderer.finish_frame(&mut scene);
            if frame_index >= 4 {
                written.push(texels(&read(&device, &queue, renderer.fog_volumes()[0])));
            }
        }
        written
    };
    let (rising, throughout) = (froxels_after(0.), froxels_after(1.));
    for (frame, (rising, throughout)) in rising.iter().zip(&throughout).enumerate() {
        assert!(
            throughout.iter().any(|texel| texel[0] > 1e-3),
            "the light lights no froxel"
        );
        let differing = rising
            .iter()
            .zip(throughout)
            .filter(|(a, b)| a != b)
            .count();
        assert_eq!(
            differing,
            0,
            "frame {}: {differing} froxels differ from a run with aerial perspective throughout",
            frame + 4
        );
    }
}

// Defect: the aerial slices past a fog's length written at other depths
// than the frame reads them at (fog_layout_aerial_depth and
// fog_volume_slice disagreeing once the length is not 0, as without its
// `length +`). The oracle is analytic: with no light the air
// and a medium too thin to dim anything (1e-6 per metre) add no light, so
// an unlit white square 1,000 m out, past the fog's 400 m, shows the air's
// transmittance alone, which at strength 10 is the closed form of 10 km of
// ground-level air (Rayleigh's scattering and Mie's extinction at sea
// level; ozone's tent is empty below 10 km), averaged over the channels as
// the volume stores it, within 1 %.
#[test]
fn aerial_slices_past_the_fogs_length_hold_the_air_to_their_depth() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let depth = 1000.;
    let strength = 10.;
    let mut scene = Scene::new(&device, &queue);
    test_support::add_static(
        &device,
        &queue,
        &mut scene,
        unlit_square(Vec3::new(0., 0., -depth), 0.1 * depth, [1.; 4]),
    );
    let mut frame = input(Fog {
        density: 1e-6,
        length: 400.,
        ..Fog::default()
    });
    frame.environment = crate::FrameEnvironment::Sky(crate::Sky {
        aerial_perspective: strength,
        ..crate::Sky::default()
    });
    let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
    let composite = texels(&read(&device, &queue, &renderer.targets().composite));
    let column = [SIZE[0] / 2, SIZE[1] / 2];
    let shown = composite[(column[1] * SIZE[0] + column[0]) as usize];
    let (ndc, _) = froxel_ray(&frame, [SIZE[0], SIZE[1], 1], column, 0);
    let metres = f64::from(depth * view_ray(&frame, ndc).length() * strength);
    let extinction = [
        5.802e-6 + 4.440e-6,
        13.558e-6 + 4.440e-6,
        33.1e-6 + 4.440e-6,
    ];
    let expected = extinction
        .iter()
        .map(|sigma: &f64| (-sigma * metres).exp())
        .sum::<f64>()
        / 3.;
    for (channel, &through) in shown[..3].iter().enumerate() {
        let through = f64::from(through);
        assert!(
            (through / expected - 1.).abs() < 0.01,
            "channel {channel}: the square shows {through}, the closed form of {metres} m of air {expected}"
        );
    }
}

/// Unlit white squares facing the camera at the origin, each centred on the
/// ray through pixel `column` of the frame `metres` from the eye, and the
/// pixel's index: what each pixel shows of white through the fog.
fn squares_at(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    scene: &mut Scene,
    frame: &FrameInput,
    placed: &[([u32; 2], f32)],
) -> Vec<usize> {
    placed
        .iter()
        .map(|&(column, metres)| {
            let (ndc, _) = froxel_ray(frame, [SIZE[0], SIZE[1], 1], column, 0);
            let ray = view_ray(frame, ndc).normalize();
            test_support::add_static(
                device,
                queue,
                scene,
                unlit_square(ray * metres, 0.03 * metres, [1.; 4]),
            );
            (column[1] * SIZE[0] + column[0]) as usize
        })
        .collect()
}

// Defects: the start measured as view depth rather than distance from the
// eye (a surface at the frame's edge then fogs from farther out than one at
// its centre the same distance away), in other units, or applied as a ramp
// (which fogs a surface just nearer than the start, or thins the fog just
// beyond it). The oracle is the closed form: with no light in the medium an
// unlit white square shows the transmittance, nearer than the start exactly
// as with the medium absent, and exp(-density (d - start)) at distance d
// beyond it, at the frame's centre, edge and corners alike, within the
// integration's slice tolerance: each froxel's density covers the step that
// ends at its slice's centre (Godot's integration) while its jittered
// sample spans half a slice either side, so any edge in the medium, this
// start's too, takes effect up to a slice nearer. The tolerance is the
// density over one slice's length along the ray at the start (2.8 % at
// most here), plus 0.002, the error with the start at 0.
#[test]
fn the_frames_medium_begins_its_start_distance_from_the_eye() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.02,
        length: 60.,
        start: 20.,
        ..Fog::default()
    };
    let frame = input(fog);
    let mut scene = Scene::new(&device, &queue);
    let row = SIZE[1] / 2;
    // The centre and the left edge 40 m away, a square 25 m away high in
    // the frame and one 50 m away low and right, and one nearer the eye
    // than the start, 15 m away.
    let beyond = [
        ([SIZE[0] / 2, row], 40.),
        ([8, row], 40.),
        ([SIZE[0] / 2, 20], 25.),
        ([150, 70], 50.),
    ];
    let near = ([120, row], 15.);
    let placed: Vec<_> = beyond.iter().copied().chain([near]).collect();
    let pixels = squares_at(&device, &queue, &mut scene, &frame, &placed);
    let mut composite = |atmosphere: bool| {
        let renderer = render(
            &device,
            &queue,
            &mut scene,
            &frame,
            &settings(atmosphere),
            1,
        );
        texels(&read(&device, &queue, &renderer.targets().composite))
    };
    let (fogged, clear) = (composite(true), composite(false));
    let near_pixel = pixels[beyond.len()];
    assert_eq!(
        fogged[near_pixel], clear[near_pixel],
        "the square nearer than the start is fogged"
    );
    let slices = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d)[2] as f32;
    for (&(column, metres), &pixel) in beyond.iter().zip(&pixels) {
        let (ndc, _) = froxel_ray(&frame, [SIZE[0], SIZE[1], 1], column, 0);
        let ray = view_ray(&frame, ndc).length();
        // The slice holding the start along this ray, and its length along
        // the ray (depth = length × unit^spread).
        let spread = crate::shading::fog::DETAIL_SPREAD;
        let unit = (fog.start / ray / fog.length).powf(1. / spread);
        let slice = fog.length * spread * unit.powf(spread - 1.) / slices * ray;
        let tolerance = fog.density * slice + 0.002;
        let expected = -fog.density * (metres - fog.start);
        let shown = fogged[pixel][0].ln();
        assert!(
            (shown - expected).abs() <= tolerance,
            "pixel {column:?}, {metres} m away: optical depth {} against the closed form's {}, within {tolerance}",
            -shown,
            -expected
        );
    }
}

// Defect: the start applied to fog volumes, which are placed content. The
// oracle is the volume's own fog as without a frame medium: a square 12 m
// away behind a box of fog 6 to 10 m away shows, with a frame medium that
// starts at 20 m, exactly what it shows with no frame medium at all.
#[test]
fn a_fog_volume_nearer_than_the_start_still_fogs() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    scene
        .update_fog_volumes(
            &device,
            &queue,
            &[crate::FogVolume {
                center: Vec3::new(0., 0., -8.),
                size: Vec3::new(20., 20., 4.),
                density: 0.1,
                edge_fade: 0.,
                ..Default::default()
            }],
        )
        .unwrap();
    let base = input(Fog {
        length: 60.,
        start: 20.,
        ..Fog::default()
    });
    let pixel = squares_at(
        &device,
        &queue,
        &mut scene,
        &base,
        &[([SIZE[0] / 2, SIZE[1] / 2], 12.)],
    )[0];
    let mut centre = |density: f32| {
        let mut frame = base;
        frame.fog.density = density;
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        texels(&read(&device, &queue, &renderer.targets().composite))[pixel]
    };
    let (with_medium, volume_alone) = (centre(0.02), centre(0.));
    assert!(
        volume_alone[0] < 0.9,
        "the volume fogs nothing: {volume_alone:?}"
    );
    assert_eq!(
        with_medium, volume_alone,
        "the start reached the fog volume"
    );
}

// Defect: a start out of range left as given: NaN, negative or infinite
// starts making the medium vanish or the frame non-finite, or a start
// beyond the volume's reach fogging anything. The oracle is Fog::start's
// documented result over a grey sky, which shows the fog's transmittance:
// NaN, negative and infinite starts render as a start of 0; a start at the
// length still fogs the sky toward the frame's edges, where the volume's
// 60 m of view depth lies up to about 90 m away, every texel finite; and a
// start beyond that renders as no medium.
#[test]
fn out_of_range_starts_render_as_documented() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    let mut base = input(Fog {
        density: 0.02,
        length: 60.,
        ..Fog::default()
    });
    base.backdrop = Backdrop::Color([0.5; 3]);
    squares_at(
        &device,
        &queue,
        &mut scene,
        &base,
        &[([SIZE[0] / 2, SIZE[1] / 2], 30.), ([20, 20], 50.)],
    );
    let mut composite = |start: f32, atmosphere: bool| {
        let mut frame = base;
        frame.fog.start = start;
        let renderer = render(
            &device,
            &queue,
            &mut scene,
            &frame,
            &settings(atmosphere),
            1,
        );
        texels(&read(&device, &queue, &renderer.targets().composite))
    };
    let (from_the_eye, clear) = (composite(0., true), composite(0., false));
    assert_ne!(from_the_eye, clear, "the medium fogs nothing");
    for start in [f32::NAN, -5., f32::INFINITY] {
        assert_eq!(composite(start, true), from_the_eye, "start {start}");
    }
    let at_length = composite(60., true);
    assert!(at_length.iter().flatten().all(|c| c.is_finite()));
    assert_ne!(at_length, clear, "a start at the length fogs nothing");
    for start in [100., 1000.] {
        assert_eq!(composite(start, true), clear, "start {start}");
    }
}

// Defect: the fog dropping the frame's medium at a reach nearer than the
// volume's farthest froxel (the frame's edge rather than its corner, or a
// lens offset taken with its sign), so a start the farthest froxels still
// lie beyond leaves them clear. The oracle is the frame's geometry: through
// a lens shifted down the bottom corners' rays are the longest, and a start
// just inside their distance, 95 % of it, still fogs the sky there.
#[test]
fn a_start_just_inside_the_farthest_corner_still_fogs_it() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    let mut frame = input(Fog {
        density: 0.02,
        length: 60.,
        ..Fog::default()
    });
    frame.backdrop = Backdrop::Color([0.5; 3]);
    frame.camera.projection.z_axis.y = -0.4;
    let corner = view_ray(&frame, Vec2::new(-1., -1.)).length() * frame.fog.length;
    frame.fog.start = 0.95 * corner;
    let bottom_left = ((SIZE[1] - 1) * SIZE[0]) as usize;
    let mut sky = |atmosphere: bool| {
        let renderer = render(
            &device,
            &queue,
            &mut scene,
            &frame,
            &settings(atmosphere),
            1,
        );
        texels(&read(&device, &queue, &renderer.targets().composite))[bottom_left]
    };
    let (fogged, clear) = (sky(true), sky(false));
    assert!(
        fogged[0] < clear[0],
        "a start of {} m, inside the corner's {corner} m, leaves its sky clear: {fogged:?}",
        frame.fog.start
    );
}