crcbl-render 0.17.2

Crucible renderer: the 3D frame on crcbl-frame — meshes, materials, lights, effects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
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
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
//! GPU draw generation: the cull dispatch, the draw-argument dispatch, and the
//! buffers between them.
//!
//! ```text
//!  begin_frame ──▶ cull params (this frame's frustum)
//!
//!  add_passes ──┬─ compute "clear-counters" ──▶ cull stats, draw args,
//!               │                             counts+mesh args
//!               │                                        │ graph barrier
//!               ├─ compute "cull"      instances ──▶ survivors | · | · | ·
//!               │                                 ──▶ cull stats
//!               │                                        │ graph barrier
//!               └─ compute "draw-args"
//!                    bin      survivors ──▶ · | routes | · | ·
//!                                       ──▶ draw args, counts+mesh args
//!                    starts   counts    ──▶ · | · | · | run starts
//!                    scatter  routes    ──▶ · | · | bucket runs | ·
//!                                       ──▶ draw args
//!                                                        │ graph barrier
//!                        the caller's render pass ◀──────┘  IndirectArgument
//! ```
//!
//! `a | b` is one buffer with regions; the passes below say which is which.
//!
//! Topic 03 §3.3, both halves: "compute pass:
//! frustum cull against instance AABBs → compacted visible instance list →
//! `draw_indexed_indirect` records + count buffer". The first dispatch is
//! `cull.slang` and the second is `draw_gen.slang`, with `clear_counters.slang`
//! ahead of both; **there is not one hand-written barrier here** — the three
//! passes declare what they touch and [`crate::graph`] computes the
//! transitions, including the one into [`ResourceState::IndirectArgument`] that
//! the seam calls the single most important barrier in a GPU-driven frame.
//!
//! # Buckets, and why the CPU still records a draw at all
//!
//! A draw's instances have to be addressable by the vertex stage, and
//! `mesh.slang`'s header measures the only number the four shader targets agree
//! about: `SV_InstanceID`, and only while the draw's first instance is zero. So
//! the arguments cannot be one per visible instance distinguished by a first
//! instance — that reaches the shader as the instance index on two targets and
//! as zero on the other two.
//!
//! What they are instead is §3.3's 2026-07-27 correction: **a fixed bucket
//! table**, one argument structure per bucket, with an instance count the GPU
//! writes and a contiguous run of surviving instance indices the vertex stage
//! walks. The caller records one indirect call per bucket — a number decided
//! when the table is built and independent of what the scene holds, which is the
//! property the whole stage is for.
//!
//! Today a bucket is one resident mesh, because the index range in an argument
//! structure is per draw and instances of two meshes cannot share one. The
//! `(material template, permutation, pass)` bucket the correction describes is
//! the same table with a longer key.
//!
//! # The counters a dispatch zeroes, and why it is a dispatch
//!
//! Both shaders only ever *add*: the cull pass's survivor counter, each bucket's
//! instance count and the y extent of its mesh dispatch are atomics, and an
//! argument buffer left holding last frame's totals would draw last frame's
//! scene twice over. Something has to zero them.
//!
//! The run starts and the routes are **not** among them, and need not be: the
//! draw-argument pass writes every start and every route it later reads in the
//! same frame, before it reads them. Only a counter reads what it adds to.
//!
//! The seam has a fill for exactly this — `CommandEncoder::fill_buffer`, "the
//! idiomatic way to zero an indirect count buffer" — and it is unusable here
//! twice over. A fill is legal only *outside* a pass, and a render-graph frame
//! is passes end to end; and `crcbl-dx12` refuses one outright — a deliberate
//! non-fix argued at its `fill_buffer`, D3D12's fill being
//! `ClearUnorderedAccessViewUint` over a descriptor from a shader-visible heap.
//! The first reason is the one that binds here regardless of what any backend
//! decides: a frame of passes has nowhere to put a fill.
//!
//! So the zero is a dispatch of its own, `clear_counters.slang`, scheduled
//! ahead of the cull pass by [`DrawGen::add_passes`] like any other producer —
//! and the barrier between its write and the cull pass's first atomic is the
//! graph's, computed from what the two declare. Every backend that can run the
//! two passes this zeroes for can run this one, which a fill is not true of.
//!
//! **Every buffer here a shader writes is therefore
//! [`MemoryLocation::DeviceLocal`]**, which is not a tidiness point: D3D12 has
//! no unordered-access view of an upload-heap resource at all — the flag is
//! rejected at creation and the heap pins the resource to `GENERIC_READ` for
//! its lifetime — so the counters being host-visible and bound writable is what
//! took its device down. That rule is about the *binding*, not the frequency:
//! topic 25's hysteresis state is written once a frame by
//! `draw_gen.slang` and is device-local for the same reason the counters are,
//! even though nothing zeroes it per frame. What does zero it is a start-up
//! copy, on [`crate::mesh_pool`]'s and [`crate::texture`]'s terms — see
//! [`DrawGen::group_state`] for why zeroing it twice would be worse than not
//! zeroing it at all. Read-only bindings are untouched by any of this, and the
//! tables beside it stay host-visible.
//!
//! The ones the clearing pass owns carry [`BufferUsage::TRANSFER_DST`] as well
//! as `TRANSFER_SRC`, and for the same reason: a buffer only ever written by a
//! shader is one nothing can poison, and a test that cannot poison a counter
//! cannot tell a zero this pass wrote from the zero the allocation came with.
//! `crcbl-vk`'s `draw_gen` end-to-end fills them with a sentinel before the
//! frame.
//!
//! # The overflow is visible, and it is not silent
//!
//! `cull.slang`'s counter is the *true* survivor count and can exceed the
//! visible list's capacity; `draw_gen.slang` clamps before it indexes anything
//! and generates draws for the prefix that fit. [`DrawGen::visible_capacity`] is
//! what a caller sizes against, and the counter is where a scene that outgrew it
//! says so.
//!
//! # The runs share one region, so a run's start is decided per frame
//!
//! **A bucket's run is not a region of its own.** Every bucket used to reserve a
//! whole [`DrawGenDesc::instance_capacity`] of `u32`, which can never overflow
//! and made the survivors-and-runs buffer `capacity * (1 + buckets)` words — per
//! frame in flight, per generator, and a renderer holds a generator per camera,
//! cascade, shadow light slot and secondary view. In a game scene of 17219
//! instances and 938 buckets that was 61.7 MiB a buffer and about 864 MiB a
//! renderer, and it ran a 2 GiB device out of memory.
//!
//! A survivor lands in exactly one bucket, so the runs between them hold what the
//! survivor list does, and the buffer is now **one capacity of runs** beside the
//! list — plus a capacity of routes and a word per bucket, for the reasons below.
//! [`draw_gen::runs_at`] has the table, and [`draw_gen::runs_words`] is the size;
//! `tests::the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity`
//! works the same scene through both formulas.
//!
//! What that costs is that where a run starts depends on how many survivors the
//! buckets in front of it took, which the GPU learns only once every survivor is
//! counted. So `draw_gen.slang` is three entry points dispatched in turn inside
//! the one `draw-args` pass — route and count each survivor, prefix-sum the
//! counts into starts, scatter each survivor at its bucket's start — and that
//! shader's header argues each. The **routes** are the capacity the buffer grew
//! by: a parallel scatter reads each survivor's bucket while writing the runs,
//! so the two cannot be one region.
//!
//! **And the geometry stages read the start rather than being told it.** The
//! `DrawConstants` block a draw binds is written once at build, and the draw's
//! first instance is the one number the four shader targets disagree about, so
//! neither can carry a per-frame start; the vertex stage's storage bindings are
//! spent. So the starts are a region of the buffer the stages already read, and
//! the block names **the word** a bucket's start is in —
//! [`DrawGen::bucket_start_word`], fixed at build. `mesh.slang`'s header is where
//! that is argued in full.
//!
//! # Buffers here are shared, and the accessors are views rather than allocations
//!
//! **The draw-argument pass binds eight storage buffers**, which is what a
//! WebGPU device guarantees per shader stage — see `shaders/draw_gen.slang`'s
//! header, which is where the merges and their costs are argued. It bound
//! fourteen until 2026-08 and could therefore not be created on a browser at the
//! default limits, nor on SwiftShader, which is every CI runner without a GPU.
//!
//! The consequence for a caller is that several of the accessors below **hand
//! back the same buffer**:
//!
//! * [`DrawGen::visible`] and [`DrawGen::runs`] are one buffer. The survivor
//!   list is at offset zero, and bucket `b`'s run starts at the word this frame
//!   wrote into word [`DrawGen::bucket_start_word`]`(b)` of it — an absolute
//!   word index, so a reader multiplies that by four too.
//! * [`DrawGen::counts`] and [`DrawGen::mesh_args`] are one buffer. The counts
//!   are at offset zero and bucket `b`'s dispatch extents at
//!   [`DrawGen::mesh_args_offset`]`(b)`.
//! * Every host-written table — the bucket table, its per-bucket material
//!   modes, the per-bucket cluster counts, topic 25's three
//!   selection tables and the `(mesh, mode) → bucket` lookup built from the
//!   first two — is one buffer, packed by
//!   [`crcbl_shaders::draw_gen::pack_tables`].
//!
//! So a reader that copies a region back must take its offset from the accessor
//! that names it. Reading at zero because a region used to be its own allocation
//! reads the region in front of it, and the words it finds there are plausible
//! `u32`s.

use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

use crcbl_hal::{
    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
    BufferUsage, ComputePipelineDesc, ComputePipelineHandle, Device, HalError, ImageViewType,
    MemoryLocation, PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, SampleType,
    ShaderEntry, ShaderModuleDesc, ShaderStages, check_portable_storage_buffers,
};
use crcbl_shaders::draw_gen::DrawMode;
use crcbl_shaders::{
    CLEAR_COUNTERS, CULL, DRAW_GEN, Stage, clear_counters, cull as cull_shader, draw_gen,
};
use glam::Mat4;

use crate::cull::{FacePlanes, Frustum};
use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
use crate::pipeline_batch;
use crate::texture::UploadBatch;

// `startsMain` is one workgroup of this size on every device, so it has to fit
// the smallest workgroup any backend promises.
const _: () = assert!(
    draw_gen::STARTS_WORKGROUP_SIZE
        <= crcbl_hal::Limits::minimum().max_compute_invocations_per_workgroup
        && draw_gen::STARTS_WORKGROUP_SIZE
            <= crcbl_hal::Limits::minimum().max_compute_workgroup_size[0]
);

/// How large a [`DrawGen`] is, and what it draws.
#[derive(Clone, Copy, Debug)]
pub struct DrawGenDesc<'a> {
    /// Debug name; every buffer is named after it.
    pub label: Option<&'a str>,
    /// The instance array, one buffer per frame in flight — the ring
    /// [`crate::instance_pool::InstancePool::buffers`] hands out. Its length is
    /// how many frames this keeps state for.
    pub instances: &'a [BufferHandle],
    /// The mesh table both dispatches resolve ranges and bounds out of.
    pub mesh_table: BufferHandle,
    /// Which mesh each bucket draws, as an index into the mesh table, in bucket
    /// order. One entry per indirect call the caller will record.
    pub bucket_meshes: &'a [u32],
    /// Which material **mode** each bucket draws, in the same order — the other
    /// half of a bucket's routing key.
    ///
    /// [`GpuMaterial::mode`](crcbl_shaders::mesh::GpuMaterial::mode) of the rows
    /// the scene holds, and the scatter sends an instance to the bucket matching
    /// its mesh *and* the mode its own record carries. So one mesh drawn by an
    /// opaque material and by a cutout one is two buckets, and the depth prepass
    /// and the shadow atlas bind a pipeline per bucket instead of one per frame.
    ///
    /// The same length as [`bucket_meshes`](Self::bucket_meshes). All zeroes for
    /// a scene whose materials are all opaque, which is every demo in this tree:
    /// one bucket per mesh, and the region costs one word each.
    pub bucket_modes: &'a [u32],
    /// How many clusters each bucket's mesh has, in the same order — the x
    /// extent of that bucket's mesh dispatch, and the only word of the
    /// mesh-dispatch arguments — see [`DrawGen::mesh_args`] — the GPU does not
    /// decide.
    ///
    /// **Zero on every geometry path with no mesh stage**, where nothing reads
    /// those arguments. It is still the same length as
    /// [`bucket_meshes`](Self::bucket_meshes): the pass writes one structure
    /// per bucket whatever the path, exactly as it writes one draw argument
    /// per bucket.
    pub bucket_clusters: &'a [u32],
    /// Where each bucket's mesh's clusters start in the cluster pool, in the
    /// same order — [`TableOffsets::bucket_cluster_bases_at`]'s region, which
    /// this pass packs and never reads.
    ///
    /// **Zero on every geometry path with no mesh stage**, like
    /// [`bucket_clusters`](Self::bucket_clusters), and the same length as
    /// [`bucket_meshes`](Self::bucket_meshes).
    ///
    /// [`TableOffsets::bucket_cluster_bases_at`]: draw_gen::TableOffsets::bucket_cluster_bases_at
    pub bucket_cluster_bases: &'a [u32],
    /// Where each mesh's cluster DAG is, **indexed by mesh id** — so this is
    /// parallel to the mesh table and long enough for every id an instance can
    /// name, not one entry per bucket.
    ///
    /// [`MeshLevels::FLAT`](crcbl_shaders::level_select::MeshLevels::FLAT) with
    /// its `first_level` filled in is what an entry
    /// for a mesh with no hierarchy holds, and it is also what a caller whose
    /// geometry path selects per cluster hands over for every mesh — see
    /// `crcbl_shaders::level_select`, which is where that arrangement is written
    /// down.
    pub mesh_levels: &'a [crcbl_shaders::level_select::MeshLevels],
    /// Every mesh's DAG groups end to end, in the order `mesh_levels` points
    /// into. Empty where nothing has a hierarchy.
    pub level_groups: &'a [crcbl_shaders::level_select::LevelGroup],
    /// Which mesh draws which level: element `first_level + d` of a mesh's run
    /// is the mesh id of its level `d`.
    pub level_meshes: &'a [u32],
    /// Instances the pool this culls can hold.
    ///
    /// Sizes the visible list, its routes, and the one run region every bucket
    /// shares, which is what makes a bucket unable to overflow: at most this
    /// many instances survive, and they are spread across the buckets rather
    /// than duplicated into each — see the module docs.
    ///
    /// It also sizes topic 25's hysteresis state, which is one word
    /// per (instance slot, group) — see [`DrawGen::group_state`].
    pub instance_capacity: u32,
    /// The [`GpuInstance::flags`](crcbl_shaders::mesh::GpuInstance::flags) bit
    /// that removes an instance from this cull, written into every frame's cull
    /// parameters.
    ///
    /// One bit of
    /// [`GpuInstance::HIDDEN_VIEWS_MASK`](crcbl_shaders::mesh::GpuInstance::HIDDEN_VIEWS_MASK)
    /// for a generator that culls for a camera, and
    /// [`GpuInstance::CASTS_NO_SHADOW`](crcbl_shaders::mesh::GpuInstance::CASTS_NO_SHADOW)
    /// for one that culls for no view — a shadow cascade's or a shadowed
    /// light's — so an instance a camera hides still casts its shadow and one
    /// told not to cast does not. Zero rejects nothing on it.
    pub hidden_view: u32,
    /// The most a frame of this generator may ask for, which decides what it
    /// allocates: [`DrawMode::Plain`] is region 0 alone, as every generator was;
    /// [`DrawMode::Occlusion`] adds the two occlusion regions and dispatches the
    /// occlusion pipelines, which its [`DrawGenPipelines`] must carry;
    /// [`DrawMode::Faces`] adds six face regions and six capacities of face
    /// runs.
    ///
    /// A frame may always run [`DrawMode::Plain`] instead — see
    /// [`DrawGen::begin_frame_with`].
    pub mode: DrawMode,
    /// How many (cluster, instance slot) pairs one task workgroup of the mesh
    /// tail decides — [`draw_gen::Params::task_lanes`].
    ///
    /// [`TASK_LANES`](crcbl_shaders::meshlet::TASK_LANES) for a caller drawing
    /// behind `mesh_cluster.slang`'s amplification stage, which then reads
    /// each bucket's mesh-dispatch extents as
    /// [`task_extents`](crcbl_shaders::meshlet::task_extents). **Zero for every
    /// other caller**, including a mesh path with no task stage: its
    /// `meshMain` launches one workgroup per pair from the
    /// `(clusters, instances, 1)` extents zero leaves in place.
    pub task_lanes: u32,
}

/// [`DrawGen::frame_modes`]' word for a frame that dispatches the occlusion
/// entry point for its small-feature test alone and scatters plainly — past
/// every [`DrawMode`] word.
const SMALL_FEATURE_ONLY: u32 = 3;

/// The eye and the budgets a frame's level of detail is selected under — the two
/// numbers [`DrawGen::begin_frame`] takes beside the frustum, as one value for
/// [`DrawGen::begin_frame_with`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Selection {
    /// The eye, in world space — [`draw_gen::Params::camera_position`].
    pub camera_position: [f32; 3],
    /// Pixels per unit and the two budgets — [`draw_gen::Params::lod_params`].
    pub lod_params: [f32; 3],
}

/// What one frame's cull does beyond the frustum — handed to
/// [`DrawGen::begin_frame_with`].
#[derive(Clone, Copy, Debug)]
pub enum FrameCull<'a> {
    /// The frustum and nothing else, into region 0.
    Plain,
    /// A point light's cull: the frustum is the light's box, and each survivor
    /// is tagged with the faces whose side planes it reaches and scattered into
    /// each of those faces' regions. Needs a [`DrawMode::Faces`] generator.
    Faces(&'a FacePlanes),
    /// The camera's two-phase occlusion and small-feature culls. Needs a
    /// [`DrawMode::Occlusion`] generator.
    Occlusion(OcclusionFrame),
}

/// The camera's half of an occlusion frame — see [`FrameCull::Occlusion`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OcclusionFrame {
    /// This frame's world → clip.
    pub view_projection: Mat4,
    /// The previous frame's, which the first phase reprojects through.
    pub previous_view_projection: Mat4,
    /// The depth prepass's extent, which is level 0 of the pyramid.
    pub target: (u32, u32),
    /// Levels of the farthest-depth pyramid, from
    /// [`occlusion_cull::levels_for`](crate::occlusion_cull::levels_for).
    pub pyramid_levels: u32,
    /// Whether the two phases run at all. With this off the frame is
    /// [`DrawMode::Plain`] and only the small-feature test is added.
    pub occlusion: bool,
    /// Whether the pyramid holds the previous frame at this extent, so the first
    /// phase may test against it. Off, every survivor is drawn early.
    pub history: bool,
    /// The small-feature threshold in pixels, or `None` where it is off.
    pub small_feature_pixels: Option<f32>,
}

/// The farthest-depth pyramid a frame's occlusion passes read — see
/// [`DrawGen::add_occlusion_passes`].
#[derive(Clone, Copy, Debug)]
pub struct PyramidInputs<'p> {
    /// Every distinct level image, as the graph knows it, so the two culls can
    /// declare their reads and the reduction passes their writes.
    pub levels: &'p [ImageId],
    /// The group naming those images at the slots `cull.slang` declares in set
    /// 1, built against [`DrawGen::occlusion_layout`].
    pub group: BindGroupHandle,
}

/// What one frame's generated draws live in.
///
/// Returned by [`DrawGen::add_passes`] and consumed by the caller's render
/// pass, which needs both halves: the [`BufferId`]s to declare its reads with,
/// so the graph transitions them, and the handles to name in the indirect call
/// itself.
#[derive(Clone, Copy, Debug)]
pub struct GeneratedDraws {
    /// The indirect arguments, [`draw_gen::DRAW_ARGS_SIZE`] bytes per bucket.
    ///
    /// **A buffer of its own**, unlike the counts and dispatch extents below,
    /// and for the one reason that survives the storage-buffer squeeze the module
    /// docs describe: the mesh path reads these as a shader read in the same pass
    /// that executes those as indirect arguments, and a resource is in one state
    /// at a time.
    pub args: BufferHandle,
    /// The same buffer as the graph knows it. Declare it in
    /// [`ResourceState::IndirectArgument`], or as a shader read on the mesh path.
    pub args_id: BufferId,
    /// The per-bucket draw counts **and** the per-bucket mesh-dispatch
    /// arguments, in that order, in one buffer.
    ///
    /// At [`DrawGen::count_offset`]`(b)` is bucket `b`'s `u32` draw count: `1`
    /// for a bucket with something in it and `0` for one without, which is what
    /// [`GeometryPath::IndirectCount`](crcbl_hal::GeometryPath::IndirectCount)'s
    /// call reads. At [`DrawGen::mesh_args_offset`]`(b)` are its
    /// [`draw_gen::MESH_ARGS_SIZE`] bytes of `(clusters, surviving instances,
    /// 1)` — or, where [`DrawGenDesc::task_lanes`] is non-zero,
    /// [`task_extents`](crcbl_shaders::meshlet::task_extents) of those two —
    /// which is what
    /// [`CommandEncoder::draw_mesh_tasks_indirect`](crcbl_hal::CommandEncoder::draw_mesh_tasks_indirect)
    /// reads on
    /// [`GeometryPath::MeshShader`](crcbl_hal::GeometryPath::MeshShader).
    ///
    /// One buffer because no pass reads both: the two indirect tails execute the
    /// counts and the mesh path executes the extents, so it is in
    /// [`ResourceState::IndirectArgument`] either way and never in two states at
    /// once.
    pub counts: BufferHandle,
    /// The same buffer as the graph knows it. Declare it in
    /// [`ResourceState::IndirectArgument`] — **once**, whichever region the
    /// pass reads.
    pub counts_id: BufferId,
    /// Byte offset in [`counts`](Self::counts) of region 0's first flat task
    /// dispatch: behind every region this generator allocates, one
    /// [`draw_gen::MESH_ARGS_SIZE`] structure per
    /// [flat segment](draw_gen::flat_segment) a region, which is where a flat
    /// call's arguments are — see [`DrawGen::flat_args_offset`]. Per generator
    /// rather than per renderer, because it sits behind however many regions
    /// the generator was built with.
    pub flat_args_offset: u64,
    /// `cull.slang`'s survivor list, each survivor's route, the per-bucket runs
    /// of surviving instance indices the vertex stage reads, and where each run
    /// starts this frame, in that order, in one buffer. Declare it as a shader
    /// read.
    ///
    /// A pass that draws reads only the starts and the runs: bucket `b`'s start
    /// at word [`DrawGen::bucket_start_word`]`(b)` — which is the number
    /// [`DrawConstants::start_at`](crcbl_shaders::mesh::DrawConstants::start_at)
    /// carries — and then the run from the word that start names.
    pub runs_id: BufferId,
    /// Topic 25's hysteresis state, as the graph knows it.
    ///
    /// Here because a caller whose geometry path has an amplification stage
    /// **reads** it: `mesh_cluster.slang` looks up the two groups a cluster
    /// names, so the pass that runs it declares [`ResourceState::ShaderRead`] on
    /// this id and the graph orders that read after the draw-argument pass's
    /// write. A caller on a path with no amplification stage declares nothing,
    /// and the state is then written and read by that pass alone.
    pub group_state_id: BufferId,
    /// The frame's culling statistics, as the graph knows them — the buffer
    /// [`DrawGen::visible_count`] hands out.
    ///
    /// Here because §3.5's amplification stage **writes** it: it counts
    /// surviving clusters into
    /// [`CLUSTER_SURVIVOR_WORD`](crcbl_shaders::cull::CLUSTER_SURVIVOR_WORD),
    /// so the pass that runs it declares
    /// [`ResourceState::ShaderReadWrite`] on this id and the graph orders that
    /// write after the draw-argument pass's read. A caller on a geometry path
    /// with no amplification stage declares nothing and the counter keeps the
    /// zero the clearing pass wrote.
    pub visible_count_id: BufferId,
}

/// The cull and draw-argument dispatches, and everything they need.
#[derive(Debug)]
pub struct DrawGen {
    /// Every host-written table `draw_gen.slang` reads, in one buffer: the
    /// bucket table, the per-bucket cluster counts and topic 25's
    /// three selection tables.
    ///
    /// **Written once**, which is what makes the merge sound rather than merely
    /// convenient: all five are decided when a mesh becomes resident and none is
    /// rewritten per frame, so they change together or not at all.
    /// [`crcbl_shaders::draw_gen::pack_tables`] is what lays them out and
    /// [`table_offsets`](Self::table_offsets) is where each region starts.
    tables: BufferHandle,
    /// Where each region of [`tables`](Self::tables) begins, as the four words
    /// [`draw_gen::Params`] carries into the shader.
    table_offsets: draw_gen::TableOffsets,
    /// The two buffer lengths the clearing dispatch zeroes. Shared by every
    /// frame's group, because both are fixed when the bucket table is built.
    clear_params: BufferHandle,
    /// Topic 25's hysteresis state: one word per (instance slot,
    /// group), holding whether that instance had that group expanded.
    ///
    /// **One buffer, deliberately not a ring**, and `draw_gen.slang`'s own
    /// declaration is where that is argued: a frame reads what the last frame
    /// wrote, an instance the frustum rejected writes nothing at all, and a
    /// per-frame slot would hand such an instance a state that is neither its
    /// own nor monotone — which is a crack rather than a stale level. Frames are
    /// ordered against each other by the graph instead, out of the
    /// `ShaderReadWrite` both the writing and the reading pass declare on it.
    ///
    /// Zeroed at build and never again, which is where the monotonicity
    /// induction starts — by the start-up copy [`DrawGen::new`] records into
    /// its caller's [`UploadBatch`],
    /// because a shader writes this and a buffer a shader writes cannot be
    /// host-visible. A second zero anywhere would erase the history rather than
    /// establish it, so there is deliberately no per-frame clear of it.
    group_state: BufferHandle,
    /// How many groups one instance's run of [`group_state`](Self::group_state)
    /// holds — every resident mesh's group count summed, and at least one so the
    /// buffer is never zero-length.
    group_stride: u32,

    // One per frame in flight, indexed by the caller's frame slot.
    /// The block naming the bucket count, the two capacities and this frame's
    /// selection camera.
    ///
    /// **Ringed since the uniform cut arrived**, where it used to be one shared
    /// buffer: the camera and the pixel budget change every frame, and a frame
    /// still in flight is a frame still reading them.
    gen_params: Vec<BufferHandle>,
    cull_params: Vec<BufferHandle>,
    visible_count: Vec<BufferHandle>,
    /// `cull.slang`'s survivor list, its routes, the per-bucket runs and their
    /// starts — see the module docs, and [`DrawGen::bucket_start_word`] for where
    /// a bucket's start is.
    runs: Vec<BufferHandle>,
    args: Vec<BufferHandle>,
    /// The per-bucket draw counts, then the per-bucket mesh-dispatch extents.
    counts: Vec<BufferHandle>,
    clear_groups: Vec<BindGroupHandle>,
    cull_groups: Vec<BindGroupHandle>,
    gen_groups: Vec<BindGroupHandle>,

    /// The layouts and pipelines every generator of a renderer shares — this
    /// one's reference to them, released by [`destroy`](Self::destroy).
    pipelines: Arc<DrawGenPipelines>,

    bucket_count: u32,
    capacity: u32,
    /// Words in each frame's [`runs`](Self::runs) buffer —
    /// [`draw_gen::runs_words`], checked once at build.
    runs_words: u32,
    hidden_view: u32,
    /// [`DrawGenDesc::task_lanes`], written into every frame's block.
    task_lanes: u32,
    /// What [`DrawGenDesc::mode`] built this for.
    mode: DrawMode,
    /// `[frame]`: the mode [`DrawGen::begin_frame_with`] last wrote, as its
    /// word, so the passes a frame records cannot disagree with the block its
    /// dispatches read.
    frame_modes: Vec<AtomicU32>,
}

/// The two occlusion phases' cull pipelines and the late draw-argument ones.
#[derive(Debug)]
struct OcclusionPipelines {
    /// Set 1 of the cull layout: the farthest-depth pyramid's levels.
    pyramid_layout: BindGroupLayoutHandle,
    /// The cull's set 0 and the pyramid's set 1.
    cull_pipeline_layout: PipelineLayoutHandle,
    early: ComputePipelineHandle,
    late: ComputePipelineHandle,
    late_scatter: ComputePipelineHandle,
    late_finish: ComputePipelineHandle,
}

/// The layouts and compute pipelines a [`DrawGen`] dispatches, built once and
/// shared by every generator a renderer makes.
///
/// **None of it depends on a [`DrawGenDesc`]**: the bind-group layouts and
/// their pipeline layouts are fixed by the shaders' declarations, and every
/// pipeline is one fixed entry point and workgroup size of `clear_counters`,
/// `cull` or `draw_gen`. What differs between a camera's generator and a shadow
/// cascade's — buffers, bind groups, bucket tables, the mode — is the
/// generator's own. So one set serves them all, and building it once instead
/// of once per generator is the saving: measured cold on radv in 2026-10, a
/// set was about 13 ms of driver compile.
///
/// **Shared by reference count.** [`DrawGen::new`] keeps an [`Arc`] of it and
/// [`DrawGen::destroy`] gives that back through [`release`](Self::release),
/// which destroys the set only when it was the last reference — so it cannot be
/// destroyed while a generator still dispatches it, nor twice.
///
/// **Dropping an [`Arc`] of it is not releasing it.** The handles are the
/// device's, not Rust's: a holder whose `Arc` is dropped without
/// [`release`](Self::release) leaks every layout and pipeline in the set if it
/// was the last holder, exactly as a [`DrawGen`] dropped without `destroy`
/// leaks its buffers.
#[derive(Debug)]
pub struct DrawGenPipelines {
    clear_layout: BindGroupLayoutHandle,
    clear_pipeline_layout: PipelineLayoutHandle,
    clear_pipeline: ComputePipelineHandle,
    cull_layout: BindGroupLayoutHandle,
    cull_pipeline_layout: PipelineLayoutHandle,
    cull_pipeline: ComputePipelineHandle,
    gen_layout: BindGroupLayoutHandle,
    gen_pipeline_layout: PipelineLayoutHandle,
    /// `draw_gen.slang`'s entry points, in the order the `draw-args` pass
    /// dispatches them: route and count, prefix-sum the counts into starts,
    /// scatter. One layout serves them all.
    bin_pipeline: ComputePipelineHandle,
    starts_pipeline: ComputePipelineHandle,
    scatter_pipeline: ComputePipelineHandle,
    /// The occlusion entry points, where the set was built with them.
    occlusion: Option<OcclusionPipelines>,
}

impl DrawGenPipelines {
    /// Builds every layout and pipeline a generator dispatches — with the
    /// occlusion phases' too where `occlusion` is set, which a
    /// [`DrawMode::Occlusion`] generator needs.
    ///
    /// The pipelines compile side by side where the device allows it, with
    /// `service` called between rounds of them — see
    /// [`ForwardRenderer::with_scene_serviced`](crate::ForwardRenderer::with_scene_serviced).
    ///
    /// # Errors
    ///
    /// [`HalError`] from any seam call. A failure part-way through releases
    /// everything already created.
    pub fn new(
        device: &dyn Device,
        occlusion: bool,
        service: &mut dyn FnMut(),
    ) -> Result<Arc<Self>, HalError> {
        let mut rollback = Rollback::default();
        match Self::build(device, occlusion, service, &mut rollback) {
            Ok(built) => {
                rollback.disarm();
                Ok(Arc::new(built))
            }
            Err(error) => {
                rollback.run(device);
                Err(error)
            }
        }
    }

    /// Gives back one reference, destroying the set if it was the last.
    ///
    /// Every holder — each [`DrawGen`] through its [`destroy`](DrawGen::destroy),
    /// and whoever built the set — calls this once, in any order, and the set
    /// is destroyed exactly once, after its last user. The device must be idle
    /// by then, as for any other `destroy`.
    ///
    /// **Every holder must call it**: an `Arc` that is dropped instead takes
    /// its count down without destroying anything, so if that was the last
    /// reference the set's layouts and pipelines leak.
    pub fn release(pipelines: Arc<Self>, device: &dyn Device) {
        if let Some(pipelines) = Arc::into_inner(pipelines) {
            pipelines.destroy(device);
        }
    }

    /// Whether this set carries the occlusion phases' pipelines.
    #[must_use]
    pub const fn has_occlusion(&self) -> bool {
        self.occlusion.is_some()
    }

    fn build(
        device: &dyn Device,
        occlusion: bool,
        service: &mut dyn FnMut(),
        rollback: &mut Rollback,
    ) -> Result<Self, HalError> {
        // --- the clearing pass ---
        let clear_entries = [
            uniform(0),
            storage(1, false, UINT_STRIDE),
            storage(2, false, UINT_STRIDE),
            // The draw counts and the mesh-dispatch extents, one buffer.
            storage(3, false, UINT_STRIDE),
        ];
        let clear_desc = BindGroupLayoutDesc {
            label: Some("clear counters"),
            entries: &clear_entries,
        };
        check_portable_storage_buffers(clear_desc.label, &[&clear_desc])?;
        let clear_layout = device.create_bind_group_layout(&clear_desc)?;
        rollback.bind_group_layouts.push(clear_layout);
        let clear_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("clear counters"),
            bind_group_layouts: &[clear_layout],
            push_constants: None,
        })?;
        rollback.pipeline_layouts.push(clear_pipeline_layout);

        // --- the cull pass ---
        //
        // Binding order is `cull.slang`'s declaration order, which is a rule
        // rather than a convention: Slang's Metal target hands each resource the
        // next index in its own table, so a layout that renumbered them would
        // bind the frustum where the instance array goes. See
        // `crcbl_shaders`' declaration-order lint.
        let cull_entries = [
            uniform(0),
            // `StructuredBuffer` in the shader, so read-only here: the cull
            // pass decides what is visible and never edits an instance or a
            // mesh entry.
            storage(1, true, crcbl_shaders::mesh::INSTANCE_STRIDE as u32),
            storage(2, true, crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32),
            storage(3, false, UINT_STRIDE),
            storage(4, false, UINT_STRIDE),
        ];
        let cull_desc = BindGroupLayoutDesc {
            label: Some("cull"),
            entries: &cull_entries,
        };
        check_portable_storage_buffers(cull_desc.label, &[&cull_desc])?;
        let cull_layout = device.create_bind_group_layout(&cull_desc)?;
        rollback.bind_group_layouts.push(cull_layout);
        let cull_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("cull"),
            bind_group_layouts: &[cull_layout],
            push_constants: None,
        })?;
        rollback.pipeline_layouts.push(cull_pipeline_layout);

        // --- the draw-argument pass ---
        //
        // **Eight storage bindings, which is every one a WebGPU device
        // guarantees.** There is no headroom here: a ninth is a pass that cannot
        // be created in a browser at the default limits or on SwiftShader, which
        // is what a CI runner without a GPU has. `check_portable_storage_buffers`
        // below is what turns a ninth into a failure here rather than into a
        // pipeline-layout refusal on somebody else's device.
        let gen_entries = [
            uniform(0),
            // The instance array and the mesh table, read only.
            storage(1, true, crcbl_shaders::mesh::INSTANCE_STRIDE as u32),
            storage(2, true, crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32),
            // The culling statistics, read only: this pass clamps against the
            // survivor count and adds to nothing.
            storage(3, true, UINT_STRIDE),
            // Every host-written table in one buffer, read only: the bucket
            // table, the per-bucket cluster counts and topic 25's
            // three selection tables were all decided when a mesh became
            // resident.
            storage(4, true, UINT_STRIDE),
            // The survivor list, its routes, the per-bucket runs and their
            // starts. Writable, and read through the same descriptor — binding
            // one buffer read-only *and* writable in one group is a usage
            // conflict on WebGPU.
            storage(5, false, UINT_STRIDE),
            // The indirect arguments.
            storage(6, false, UINT_STRIDE),
            // The draw counts and the mesh-dispatch extents.
            storage(7, false, UINT_STRIDE),
            // The hysteresis state, read *and* written: this pass is the
            // only writer, and it reads the previous frame's answer out of
            // the same element it then overwrites.
            storage(8, false, UINT_STRIDE),
        ];
        let gen_desc = BindGroupLayoutDesc {
            label: Some("draw args"),
            entries: &gen_entries,
        };
        check_portable_storage_buffers(gen_desc.label, &[&gen_desc])?;
        let gen_layout = device.create_bind_group_layout(&gen_desc)?;
        rollback.bind_group_layouts.push(gen_layout);
        let gen_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("draw args"),
            bind_group_layouts: &[gen_layout],
            push_constants: None,
        })?;
        rollback.pipeline_layouts.push(gen_pipeline_layout);

        // --- the passes' pipelines, as one batch ---
        //
        // Every layout they need exists by now, so they compile side by side
        // where the device allows it — see [`pipeline_batch`]. Each result
        // is the rollback's before any error is propagated, so a refusal of one
        // releases the others.
        //
        // `cull` is named rather than resolved: `cull.slang` has an entry point
        // per occlusion phase beside this one. `bin`, `starts` and `scatter`
        // are three entry points of one module over one layout, which is why
        // they are `compute_pipeline_entry` too: the route, the prefix sum and
        // the scatter share the bucket table's accessors and shaders here have
        // no `#include`.
        let draw_args = |label, entry_point, workgroup_size| {
            compute_pipeline_entry(
                device,
                label,
                &DRAW_GEN,
                entry_point,
                gen_pipeline_layout,
                workgroup_size,
            )
        };
        let results = pipeline_batch::create(
            device,
            service,
            [
                &|| {
                    compute_pipeline(
                        device,
                        "clear counters",
                        &CLEAR_COUNTERS,
                        clear_pipeline_layout,
                        clear_counters::WORKGROUP_SIZE,
                    )
                },
                &|| {
                    compute_pipeline_entry(
                        device,
                        "cull",
                        &CULL,
                        "computeMain",
                        cull_pipeline_layout,
                        cull_shader::WORKGROUP_SIZE,
                    )
                },
                &|| draw_args("draw args bin", "binMain", draw_gen::WORKGROUP_SIZE),
                // One workgroup for the whole prefix sum, dispatched once by
                // `record_passes`: its invocations split the table into chunks
                // and scan the chunk totals in workgroup memory.
                &|| {
                    draw_args(
                        "draw args starts",
                        "startsMain",
                        draw_gen::STARTS_WORKGROUP_SIZE,
                    )
                },
                &|| draw_args("draw args scatter", "scatterMain", draw_gen::WORKGROUP_SIZE),
            ],
        );
        rollback.pipelines.extend(results.iter().flatten().copied());
        let [
            clear_pipeline,
            cull_pipeline,
            bin_pipeline,
            starts_pipeline,
            scatter_pipeline,
        ] = results;
        let clear_pipeline = clear_pipeline?;
        let cull_pipeline = cull_pipeline?;
        let bin_pipeline = bin_pipeline?;
        let starts_pipeline = starts_pipeline?;
        let scatter_pipeline = scatter_pipeline?;

        // --- the occlusion phases, where they were asked for ---
        let occlusion = if occlusion {
            Some(Self::build_occlusion(
                device,
                rollback,
                cull_layout,
                gen_pipeline_layout,
                service,
            )?)
        } else {
            None
        };

        Ok(Self {
            clear_layout,
            clear_pipeline_layout,
            clear_pipeline,
            cull_layout,
            cull_pipeline_layout,
            cull_pipeline,
            gen_layout,
            gen_pipeline_layout,
            bin_pipeline,
            starts_pipeline,
            scatter_pipeline,
            occlusion,
        })
    }

    /// The pipelines only an occlusion generator uses: `cull.slang`'s two phases
    /// over the cull's set 0 and the pyramid's set 1, and `draw_gen.slang`'s late
    /// scatter and finish over the draw-argument layout.
    fn build_occlusion(
        device: &dyn Device,
        rollback: &mut Rollback,
        cull_layout: BindGroupLayoutHandle,
        gen_pipeline_layout: PipelineLayoutHandle,
        service: &mut dyn FnMut(),
    ) -> Result<OcclusionPipelines, HalError> {
        // One depth texture per level, in `cull.slang`'s declaration order —
        // which is the order Slang's Metal target hands out texture indices in.
        let entries: Vec<BindGroupLayoutEntry> = (0..cull_shader::OCCLUSION_MAX_LEVELS)
            .map(|binding| BindGroupLayoutEntry {
                binding,
                visibility: ShaderStages::COMPUTE,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // `Depth`, on `crate::hiz`'s terms: `DepthTexture2D` in the
                    // shader, read with `Load` and never through a sampler.
                    sample_type: SampleType::Depth,
                },
                count: 1,
                flags: BindingFlags::empty(),
            })
            .collect();
        let pyramid_desc = BindGroupLayoutDesc {
            label: Some("occlusion pyramid"),
            entries: &entries,
        };
        check_portable_storage_buffers(pyramid_desc.label, &[&pyramid_desc])?;
        let pyramid_layout = device.create_bind_group_layout(&pyramid_desc)?;
        rollback.bind_group_layouts.push(pyramid_layout);
        let cull_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("occlusion cull"),
            bind_group_layouts: &[cull_layout, pyramid_layout],
            push_constants: None,
        })?;
        rollback.pipeline_layouts.push(cull_pipeline_layout);
        // One batch, on the terms `build` gives for its own.
        let entry = |label, shader, entry_point, layout, workgroup_size| {
            compute_pipeline_entry(device, label, shader, entry_point, layout, workgroup_size)
        };
        let cull = cull_shader::WORKGROUP_SIZE;
        let results = pipeline_batch::create(
            device,
            service,
            [
                &|| {
                    entry(
                        "occlusion early cull",
                        &CULL,
                        "occlusionMain",
                        cull_pipeline_layout,
                        cull,
                    )
                },
                &|| {
                    entry(
                        "occlusion late cull",
                        &CULL,
                        "lateMain",
                        cull_pipeline_layout,
                        cull,
                    )
                },
                &|| {
                    entry(
                        "draw args late scatter",
                        &DRAW_GEN,
                        "lateScatterMain",
                        gen_pipeline_layout,
                        draw_gen::WORKGROUP_SIZE,
                    )
                },
                // One workgroup, on `startsMain`'s terms: its invocations split
                // the buckets into chunks and scan the two closed regions' task
                // chunks in workgroup memory.
                &|| {
                    entry(
                        "draw args late finish",
                        &DRAW_GEN,
                        "lateFinishMain",
                        gen_pipeline_layout,
                        draw_gen::STARTS_WORKGROUP_SIZE,
                    )
                },
            ],
        );
        rollback.pipelines.extend(results.iter().flatten().copied());
        let [early, late, late_scatter, late_finish] = results;
        let (early, late, late_scatter, late_finish) = (early?, late?, late_scatter?, late_finish?);
        Ok(OcclusionPipelines {
            pyramid_layout,
            cull_pipeline_layout,
            early,
            late,
            late_scatter,
            late_finish,
        })
    }

    /// Releases everything, in dependency order. Only [`release`](Self::release)
    /// calls it, for the last reference.
    fn destroy(self, device: &dyn Device) {
        if let Some(occlusion) = self.occlusion {
            for pipeline in [
                occlusion.early,
                occlusion.late,
                occlusion.late_scatter,
                occlusion.late_finish,
            ] {
                device.destroy_compute_pipeline(pipeline);
            }
            device.destroy_pipeline_layout(occlusion.cull_pipeline_layout);
            device.destroy_bind_group_layout(occlusion.pyramid_layout);
        }
        device.destroy_compute_pipeline(self.scatter_pipeline);
        device.destroy_compute_pipeline(self.starts_pipeline);
        device.destroy_compute_pipeline(self.bin_pipeline);
        device.destroy_pipeline_layout(self.gen_pipeline_layout);
        device.destroy_compute_pipeline(self.cull_pipeline);
        device.destroy_pipeline_layout(self.cull_pipeline_layout);
        device.destroy_compute_pipeline(self.clear_pipeline);
        device.destroy_pipeline_layout(self.clear_pipeline_layout);
        device.destroy_bind_group_layout(self.gen_layout);
        device.destroy_bind_group_layout(self.cull_layout);
        device.destroy_bind_group_layout(self.clear_layout);
    }
}

impl DrawGen {
    /// Builds every bind group per frame and every buffer between the passes,
    /// against `pipelines` — the layouts and pipelines it dispatches, which it
    /// keeps a reference to and does not build. One [`DrawGenPipelines`] serves
    /// every generator a renderer makes.
    ///
    /// `uploads` carries the one start-up copy this makes: the one that zeroes
    /// the hysteresis state, described on [`group_state`](Self::group_state).
    /// It is recorded, not submitted, so **no frame may run these passes until
    /// the caller has submitted that batch** — waiting, with
    /// [`UploadBatch::submit`], or, with [`UploadBatch::submit_deferred`], to
    /// the queue the frames go to. A renderer building several of these
    /// submits all of their copies in one submission.
    ///
    /// # Errors
    ///
    /// [`HalError`] from any seam call. A failure part-way through releases
    /// everything already created, so a caller that gives up leaves nothing
    /// behind — and [abandons](UploadBatch::abandon) `uploads`, which by then
    /// may hold a copy into a buffer that release destroyed.
    ///
    /// # Panics
    ///
    /// If `instances` is empty or `bucket_meshes` is: a ring with no buffers has
    /// nothing to bind, and a table with no buckets generates no draws at all.
    /// Also if `desc` asks for [`DrawMode::Occlusion`] and `pipelines` was built
    /// without the occlusion phases.
    pub fn new(
        device: &dyn Device,
        uploads: &mut UploadBatch<'_>,
        pipelines: &Arc<DrawGenPipelines>,
        desc: &DrawGenDesc<'_>,
    ) -> Result<Self, HalError> {
        assert!(
            desc.mode != DrawMode::Occlusion || pipelines.has_occlusion(),
            "an occlusion generator dispatches the occlusion phases, and these pipelines were \
             built without them"
        );
        assert!(
            !desc.instances.is_empty(),
            "draw generation needs at least one instance buffer to cull"
        );
        assert!(
            !desc.bucket_meshes.is_empty(),
            "draw generation with no buckets would generate no draws"
        );
        assert_eq!(
            desc.bucket_modes.len(),
            desc.bucket_meshes.len(),
            "one material mode per bucket: a shorter table would key a bucket on a mode that \
             belongs to another bucket, or to nothing, and the instances meant for it would \
             scatter nowhere and never be drawn"
        );
        assert_eq!(
            desc.bucket_clusters.len(),
            desc.bucket_meshes.len(),
            "one cluster count per bucket: a shorter table would leave a bucket's mesh dispatch \
             reading a cluster count that belongs to another bucket, or to nothing"
        );
        assert_eq!(
            desc.bucket_cluster_bases.len(),
            desc.bucket_meshes.len(),
            "one cluster base per bucket: a shorter table would leave a range of buckets drawn \
             in one call reading a cluster base that belongs to another bucket, or to nothing"
        );
        let mut rollback = Rollback::default();
        match Self::build(device, uploads, pipelines, desc, &mut rollback) {
            Ok(built) => Ok(built),
            Err(error) => {
                uploads.abandon();
                rollback.run(device);
                Err(error)
            }
        }
    }

    fn build(
        device: &dyn Device,
        uploads: &mut UploadBatch<'_>,
        pipelines: &Arc<DrawGenPipelines>,
        desc: &DrawGenDesc<'_>,
        rollback: &mut Rollback,
    ) -> Result<Self, HalError> {
        let stem = desc.label.unwrap_or("draw generation");
        let bucket_count = u32::try_from(desc.bucket_meshes.len())
            .map_err(|_| HalError::InvalidDescriptor("more buckets than a u32".to_string()))?;
        let capacity = desc.instance_capacity;
        // **The survivor list carries tags above the index**, so a capacity
        // reaching them would be instance indices read back as faces or as an
        // occlusion verdict.
        if capacity > cull_shader::ENTRY_INDEX_MASK + 1 {
            return Err(HalError::InvalidDescriptor(format!(
                "{capacity} instances do not fit the {} a survivor entry indexes below its tags",
                cull_shader::ENTRY_INDEX_MASK + 1
            )));
        }
        let draw_regions = desc.mode.regions();
        // Checked here, once, because the shader indexes the whole buffer with a
        // `uint` and every accessor below does the same arithmetic unchecked.
        let runs_words = draw_gen::runs_words(capacity, bucket_count, desc.mode == DrawMode::Faces)
            .ok_or_else(|| {
                HalError::InvalidDescriptor(format!(
                    "{capacity} instances and {bucket_count} buckets lay out more survivor and run \
                 words than a u32 addresses"
                ))
            })?;

        let mut buffer = |label: &str, size: u64, usage, memory| -> Result<_, HalError> {
            let handle = device.create_buffer(&BufferDesc {
                label: Some(&format!("{stem} {label}")),
                size,
                usage,
                memory,
            })?;
            rollback.buffers.push(handle);
            Ok(handle)
        };

        // **Every host-written table in one buffer**, because the draw-argument
        // pass has eight storage bindings to spend and a WebGPU device
        // guarantees no more — see the module docs. They are packed together
        // rather than any other set because they are the ones written at build
        // and never per frame: the bucket table, its material modes, its cluster
        // counts, and topic 25's three selection tables all follow
        // residency and nothing else.
        //
        // `pack_tables` is what pads an empty selection region out to one zeroed
        // record, which is the ordinary case for a renderer whose meshes have no
        // hierarchy — a mesh's `first_level` names element zero of the level
        // region whether it has a DAG or not.
        let packed = draw_gen::pack_tables(
            desc.bucket_meshes,
            desc.bucket_modes,
            desc.bucket_clusters,
            desc.bucket_cluster_bases,
            desc.mesh_levels,
            desc.level_groups,
            desc.level_meshes,
        )
        .ok_or_else(|| {
            HalError::InvalidDescriptor("more table words than a u32 addresses".to_string())
        })?;
        let tables = buffer(
            "tables",
            packed.bytes.len() as u64,
            BufferUsage::STORAGE,
            MemoryLocation::HostUpload,
        )?;
        device.write_buffer(tables, 0, &packed.bytes)?;
        let table_offsets = packed.offsets;

        // Topic 25's hysteresis state. **Zeroed here and by
        // nothing else ever again**: `draw_gen.slang` reads an element before it
        // writes it, so what the buffer holds on the very first frame is a real
        // input, and freshly allocated device memory holds whatever it holds. A
        // state that is not monotone up a DAG is a cut with a hole in it, so
        // this is the one write that keeps every later frame's induction
        // standing.
        //
        // Device-local like every other buffer a shader writes here, for the
        // reason the module docs give: D3D12 has no unordered-access view of an
        // upload-heap resource. So the zero arrives by a **start-up staging
        // copy** rather than a `write_buffer` — and not by the clearing
        // dispatch, which runs inside every frame. Running it twice would erase
        // exactly the history this buffer exists to carry, and once is what a
        // copy submitted before the first frame is. It joins the caller's
        // batch, whose `submit` is that before; `UploadBatch::fill` is where
        // the copy and its barriers are.
        //
        // At least one word per instance even when nothing resident has a
        // hierarchy, because a zero-length buffer is not a descriptor any
        // backend binds and both shaders index it unconditionally.
        let group_stride = u32::try_from(desc.level_groups.len())
            .map_err(|_| HalError::InvalidDescriptor("more groups than a u32".to_string()))?
            .max(1);
        let group_state_bytes = u64::from(capacity) * u64::from(group_stride) * 4;
        let group_state = buffer(
            "lod group state",
            group_state_bytes,
            BufferUsage::STORAGE | BufferUsage::TRANSFER_DST,
            MemoryLocation::DeviceLocal,
        )?;
        uploads.fill(
            &format!("{stem} lod group state"),
            group_state,
            &vec![
                0u8;
                usize::try_from(group_state_bytes).map_err(|_| HalError::InvalidDescriptor(
                    format!(
                        "the lod group state is {group_state_bytes} bytes, which does not \
                             fit this host's address space"
                    )
                ))?
            ],
            ResourceState::ShaderReadWrite,
        )?;

        let clear_params = buffer(
            "clear params",
            clear_counters::PARAMS_SIZE as u64,
            BufferUsage::UNIFORM,
            MemoryLocation::HostUpload,
        )?;
        // The argument buffer's length in words, from the crate that owns the
        // argument layout — so the clearing shader never re-declares it. Every
        // region's structures, end to end.
        let args_words = draw_regions * bucket_count * draw_gen::DRAW_ARGS_WORDS as u32;
        // The counts-and-extents buffer's: every region's counts and extents,
        // then every region's flat task dispatches.
        let counts_words = draw_gen::flat_args_word(bucket_count, draw_regions, draw_regions, 0, 0);
        device.write_buffer(
            clear_params,
            0,
            &clear_counters::Params {
                args_words,
                counts_words: bucket_count,
                stats_words: cull_shader::STATS_WORDS,
                // Everything behind region 0's counts: its extents, then every
                // further region's counts and extents, which alternate, and
                // the flat task dispatches behind them all.
                mesh_args_words: counts_words - bucket_count,
            }
            .to_bytes(),
        )?;

        let frames = desc.instances.len();
        let mut gen_params = Vec::with_capacity(frames);
        let mut cull_params = Vec::with_capacity(frames);
        let mut visible_count = Vec::with_capacity(frames);
        let mut runs = Vec::with_capacity(frames);
        let mut args = Vec::with_capacity(frames);
        let mut counts = Vec::with_capacity(frames);
        for frame in 0..frames {
            // The static half is written here and the camera half in
            // `begin_frame`, so a frame that never called it still names the
            // right bucket count rather than reading a zeroed block.
            let params = buffer(
                &format!("params {frame}"),
                draw_gen::PARAMS_SIZE as u64,
                BufferUsage::UNIFORM,
                MemoryLocation::HostUpload,
            )?;
            device.write_buffer(
                params,
                0,
                &draw_gen::Params {
                    bucket_count,
                    visible_capacity: capacity,
                    group_stride,
                    bucket_modes_at: table_offsets.bucket_modes_at,
                    bucket_clusters_at: table_offsets.bucket_clusters_at,
                    mesh_levels_at: table_offsets.mesh_levels_at,
                    level_groups_at: table_offsets.level_groups_at,
                    level_meshes_at: table_offsets.level_meshes_at,
                    bucket_lookup_at: table_offsets.bucket_lookup_at,
                    task_lanes: desc.task_lanes,
                    flat_segments_at: table_offsets.flat_segments_at,
                    ..draw_gen::Params::default()
                }
                .to_bytes(),
            )?;
            gen_params.push(params);
            cull_params.push(buffer(
                &format!("cull params {frame}"),
                cull_shader::PARAMS_SIZE as u64,
                BufferUsage::UNIFORM,
                MemoryLocation::HostUpload,
            )?);
            // `TRANSFER_SRC` on all four, and it is not there for tidiness:
            // everything these passes produce is written by a shader and read by
            // another, so a copy out is the *only* way anything can check that
            // what they produced is what a CPU would have recorded. `crcbl-vk`'s
            // `draw_gen` end-to-end does exactly that, and topic 03 §3.6's
            // culling-stats ring — the one readback the frame loop is allowed —
            // is the counter below.
            //
            // `TRANSFER_DST` on the three the clearing dispatch owns, so a test
            // can poison them — see the module docs. They are device-local like
            // everything else here: nothing writes them from the host any more.
            //
            // **Two words, not one**, and they belong to different passes: the
            // cull dispatch counts surviving instances into the first and
            // `mesh_cluster.slang`'s amplification stage counts surviving
            // clusters into the second. One buffer keeps §3.6's ring at one
            // readback — see [`crcbl_shaders::cull::STATS_WORDS`].
            visible_count.push(buffer(
                &format!("cull stats {frame}"),
                u64::from(cull_shader::STATS_WORDS) * 4,
                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
                MemoryLocation::DeviceLocal,
            )?);
            // The survivor list, its routes, the per-bucket runs and their
            // starts, in that order, in one buffer — see the module docs.
            // `cull.slang` writes the first `capacity` words and
            // `draw_gen.slang` the rest; nothing reads a word of one region
            // through another, and the shader is bound the whole buffer once
            // because a read-only view of part of it beside a writable view of
            // the rest is a usage conflict on WebGPU.
            //
            // **One capacity of runs however many buckets there are**: a word
            // per bucket is all the bucket count still costs here.
            runs.push(buffer(
                &format!("visible and bucket runs {frame}"),
                u64::from(runs_words) * 4,
                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
                MemoryLocation::DeviceLocal,
            )?);
            args.push(buffer(
                &format!("draw args {frame}"),
                u64::from(draw_regions) * u64::from(bucket_count) * draw_gen::DRAW_ARGS_SIZE as u64,
                BufferUsage::STORAGE
                    | BufferUsage::INDIRECT
                    | BufferUsage::TRANSFER_SRC
                    | BufferUsage::TRANSFER_DST,
                MemoryLocation::DeviceLocal,
            )?);
            // The per-bucket draw counts, then the mesh path's dispatch extents
            // — one buffer, on the argument buffer's terms exactly: written by
            // the same pass, zeroed by the same one, and read by a driver rather
            // than by a shader, so `INDIRECT`, and `TRANSFER_SRC` so a test can
            // read back what the GPU decided.
            //
            // Merged because no pass reads both, so the buffer is never in two
            // resource states at once — see [`GeneratedDraws::counts`], and the
            // module docs on why a binding had to go.
            counts.push(buffer(
                &format!("draw counts and mesh dispatch args {frame}"),
                u64::from(counts_words) * 4,
                BufferUsage::STORAGE
                    | BufferUsage::INDIRECT
                    | BufferUsage::TRANSFER_SRC
                    | BufferUsage::TRANSFER_DST,
                MemoryLocation::DeviceLocal,
            )?);
        }

        let mut clear_groups = Vec::with_capacity(frames);
        let mut cull_groups = Vec::with_capacity(frames);
        let mut gen_groups = Vec::with_capacity(frames);
        for frame in 0..frames {
            let group = device.create_bind_group(&BindGroupDesc {
                label: Some("clear counters"),
                layout: pipelines.clear_layout,
                entries: &[
                    bound(0, clear_params),
                    bound(1, visible_count[frame]),
                    bound(2, args[frame]),
                    bound(3, counts[frame]),
                ],
                variable_count: None,
            })?;
            rollback.bind_groups.push(group);
            clear_groups.push(group);

            // **This frame's slot of every ring, not a shared buffer.** Binding
            // one buffer here for every group would undo the ring and put a
            // frame's writes where the previous frame is still reading.
            let group = device.create_bind_group(&BindGroupDesc {
                label: Some("cull"),
                layout: pipelines.cull_layout,
                entries: &[
                    bound(0, cull_params[frame]),
                    bound(1, desc.instances[frame]),
                    bound(2, desc.mesh_table),
                    // The survivor list is the front of the buffer whose later
                    // regions hold the routes, the runs and their starts; this
                    // pass writes only the front and `CullParams::capacity` is
                    // what bounds it there.
                    bound(3, runs[frame]),
                    bound(4, visible_count[frame]),
                ],
                variable_count: None,
            })?;
            rollback.bind_groups.push(group);
            cull_groups.push(group);

            let group = device.create_bind_group(&BindGroupDesc {
                label: Some("draw args"),
                layout: pipelines.gen_layout,
                entries: &[
                    bound(0, gen_params[frame]),
                    bound(1, desc.instances[frame]),
                    bound(2, desc.mesh_table),
                    bound(3, visible_count[frame]),
                    bound(4, tables),
                    bound(5, runs[frame]),
                    bound(6, args[frame]),
                    bound(7, counts[frame]),
                    bound(8, group_state),
                ],
                variable_count: None,
            })?;
            rollback.bind_groups.push(group);
            gen_groups.push(group);
        }

        rollback.disarm();
        Ok(Self {
            tables,
            table_offsets,
            clear_params,
            group_state,
            group_stride,
            gen_params,
            cull_params,
            visible_count,
            runs,
            args,
            counts,
            clear_groups,
            cull_groups,
            gen_groups,
            pipelines: Arc::clone(pipelines),
            bucket_count,
            capacity,
            runs_words,
            hidden_view: desc.hidden_view,
            task_lanes: desc.task_lanes,
            mode: desc.mode,
            frame_modes: (0..frames).map(|_| AtomicU32::new(0)).collect(),
        })
    }

    /// Buckets in the table, which is how many indirect calls a caller records.
    #[must_use]
    pub const fn bucket_count(&self) -> u32 {
        self.bucket_count
    }

    /// Instances the visible list holds, and so how many every bucket's run
    /// holds between them — see [`DrawGenDesc::instance_capacity`].
    #[must_use]
    pub const fn visible_capacity(&self) -> u32 {
        self.capacity
    }

    /// Which word of [`DrawGen::runs`] holds where bucket `bucket`'s run starts
    /// this frame, as the number `mesh.slang`'s `DrawConstants::start_at`
    /// carries.
    ///
    /// **The word, not the start.** The start is a per-frame number the
    /// draw-argument pass writes into this word — an absolute word index into
    /// the same buffer, never below [`runs_at`](Self::runs_at) — and the word is
    /// fixed at build, which is what lets a constant block written once name it.
    /// Past the survivors, their routes and the runs; see the module docs. A
    /// reader copying either back multiplies by four.
    ///
    /// The same for every generator a renderer builds from one bucket table and
    /// one capacity, which is what lets one set of constant blocks serve the
    /// camera, every shadow cull and every secondary view.
    #[must_use]
    pub const fn bucket_start_word(&self, bucket: u32) -> u32 {
        draw_gen::run_start_word(self.capacity, self.bucket_count, 0, bucket)
    }

    /// Which word holds where bucket `bucket`'s run of draw region `region`
    /// starts this frame — [`bucket_start_word`](Self::bucket_start_word) for a
    /// region past 0, on its terms exactly.
    ///
    /// [`draw_gen::DRAW_REGIONS`] regions of start words are laid out in every
    /// generator whatever it allocates, so this is the same for every generator
    /// one renderer builds.
    #[must_use]
    pub const fn region_start_word(&self, region: u32, bucket: u32) -> u32 {
        draw_gen::run_start_word(self.capacity, self.bucket_count, region, bucket)
    }

    /// Which word of [`DrawGen::runs`] holds where bucket `bucket`'s task
    /// chunks start in draw region `region` this frame —
    /// [`draw_gen::chunk_start_word`], the number
    /// [`ClusterDrawConstants::chunk_starts_at`](crcbl_shaders::meshlet::ClusterDrawConstants::chunk_starts_at)
    /// carries. `bucket` may be [`bucket_count`](Self::bucket_count), the
    /// region's end.
    ///
    /// The same for every generator one renderer builds, for
    /// [`region_start_word`](Self::region_start_word)'s reason.
    #[must_use]
    pub const fn chunk_start_word(&self, region: u32, bucket: u32) -> u32 {
        draw_gen::chunk_start_word(self.capacity, self.bucket_count, region, bucket)
    }

    /// Byte offset in [`DrawGen::counts`] of flat segment `segment`'s task
    /// dispatch in draw region `region` — what a flat call's
    /// [`DrawIndirect::offset`](crcbl_hal::DrawIndirect::offset) carries.
    /// Behind every region this generator allocates, so it differs between
    /// generators of one renderer; [`GeneratedDraws::flat_args_offset`] is
    /// region 0's first, handed to the pass that draws them.
    #[must_use]
    pub const fn flat_args_offset(&self, region: u32, segment: u32) -> u64 {
        draw_gen::flat_args_word(self.bucket_count, self.mode.regions(), region, segment, 0) as u64
            * 4
    }

    /// Which word of [`DrawGen::runs`] holds bucket `bucket`'s mesh, as the
    /// number `mesh.slang`'s `DrawConstants::mesh_at` carries — filled every
    /// frame by the draw-argument pass from the bucket table.
    ///
    /// The same for every generator one renderer builds, for
    /// [`region_start_word`](Self::region_start_word)'s reason.
    #[must_use]
    pub const fn bucket_mesh_word(&self, bucket: u32) -> u32 {
        draw_gen::bucket_mesh_word(self.capacity, self.bucket_count, bucket)
    }

    /// How far region `region`'s argument structures sit behind region 0's, in
    /// bytes — what a draw of that region adds to
    /// [`args_offset`](Self::args_offset).
    #[must_use]
    pub const fn args_region_offset(&self, region: u32) -> u64 {
        region as u64 * self.bucket_count as u64 * draw_gen::DRAW_ARGS_SIZE as u64
    }

    /// How far region `region`'s draw counts and dispatch extents sit behind
    /// region 0's, in bytes — what a draw of that region adds to
    /// [`count_offset`](Self::count_offset) and
    /// [`mesh_args_offset`](Self::mesh_args_offset). A region is one count and
    /// one extent structure per bucket, so its counts and its extents move
    /// together.
    #[must_use]
    pub const fn counts_region_offset(&self, region: u32) -> u64 {
        region as u64 * self.bucket_count as u64 * (4 + draw_gen::MESH_ARGS_SIZE as u64)
    }

    /// What [`DrawGenDesc::mode`] built this generator for.
    #[must_use]
    pub const fn mode(&self) -> DrawMode {
        self.mode
    }

    /// Set 1 of the occlusion cull's layout — the farthest-depth pyramid's
    /// levels — which [`PyramidInputs::group`] is built against. `None` on a
    /// generator not built for [`DrawMode::Occlusion`].
    #[must_use]
    pub fn occlusion_layout(&self) -> Option<BindGroupLayoutHandle> {
        self.occlusion().map(|pipelines| pipelines.pyramid_layout)
    }

    /// The shared occlusion pipelines, on a generator built for
    /// [`DrawMode::Occlusion`] — `None` on any other, whatever the shared set
    /// carries, so a plain generator never dispatches them.
    fn occlusion(&self) -> Option<&OcclusionPipelines> {
        if self.mode == DrawMode::Occlusion {
            self.pipelines.occlusion.as_ref()
        } else {
            None
        }
    }

    /// The mode `frame`'s dispatches were parametrised for by the last
    /// [`begin_frame_with`](Self::begin_frame_with) on that slot.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn frame_mode(&self, frame: usize) -> DrawMode {
        match self.frame_modes[frame].load(Ordering::Relaxed) {
            SMALL_FEATURE_ONLY => DrawMode::Plain,
            word if word == DrawMode::Occlusion.word() => DrawMode::Occlusion,
            word if word == DrawMode::Faces.word() => DrawMode::Faces,
            _ => DrawMode::Plain,
        }
    }

    /// Whether `frame` dispatches `cull.slang`'s occlusion entry point — the two
    /// phases, or the small-feature test alone — and so must be recorded with
    /// [`add_occlusion_passes`](Self::add_occlusion_passes).
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn uses_occlusion_entry(&self, frame: usize) -> bool {
        let word = self.frame_modes[frame].load(Ordering::Relaxed);
        word == DrawMode::Occlusion.word() || word == SMALL_FEATURE_ONLY
    }

    /// The first word of the run region in [`DrawGen::runs`] — where bucket
    /// zero's run starts in every frame, and the floor of every other start.
    #[must_use]
    pub const fn runs_at(&self) -> u32 {
        draw_gen::runs_at(self.capacity)
    }

    /// Bytes of each frame's [`DrawGen::runs`] buffer: the survivors, their
    /// routes, one capacity of runs and a start word per bucket.
    #[must_use]
    pub const fn runs_size(&self) -> u64 {
        self.runs_words as u64 * 4
    }

    /// Byte offset of bucket `bucket`'s argument structure.
    #[must_use]
    pub const fn args_offset(&self, bucket: u32) -> u64 {
        bucket as u64 * draw_gen::DRAW_ARGS_SIZE as u64
    }

    /// Byte offset of bucket `bucket`'s draw count, which is at the front of the
    /// buffer [`DrawGen::counts`] hands back.
    #[must_use]
    pub const fn count_offset(&self, bucket: u32) -> u64 {
        bucket as u64 * 4
    }

    /// Byte offset of bucket `bucket`'s mesh-dispatch argument structure — what
    /// [`DrawIndirect::offset`](crcbl_hal::DrawIndirect::offset) carries in the
    /// call that reads it.
    ///
    /// **Past the one draw count per bucket** that shares the buffer, so this is
    /// never zero — see the module docs.
    #[must_use]
    pub const fn mesh_args_offset(&self, bucket: u32) -> u64 {
        self.bucket_count as u64 * 4 + bucket as u64 * draw_gen::MESH_ARGS_SIZE as u64
    }

    /// The buffer of per-bucket instance runs for `frame`, which the drawing
    /// pass's bind group names.
    ///
    /// The same buffer [`DrawGen::visible`] hands back: bucket `bucket`'s run
    /// starts at the word this frame wrote into word
    /// [`bucket_start_word`](Self::bucket_start_word)`(bucket)`, past the
    /// survivor list and its routes.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn runs(&self, frame: usize) -> BufferHandle {
        self.runs[frame]
    }

    /// `frame`'s cull parameters — the frustum [`DrawGen::begin_frame`] wrote.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn cull_params(&self, frame: usize) -> BufferHandle {
        self.cull_params[frame]
    }

    /// `frame`'s compacted visible list — `cull.slang`'s survivors, as indices
    /// into the instance array, in no particular order, in the **first
    /// [`visible_capacity`](Self::visible_capacity) words** of the buffer.
    ///
    /// The same buffer [`DrawGen::runs`] hands back; the routes, the per-bucket
    /// runs and their starts follow the survivors in it. See the module docs.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn visible(&self, frame: usize) -> BufferHandle {
        self.runs[frame]
    }

    /// `frame`'s culling statistics: surviving instances in
    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
    /// and surviving clusters in
    /// [`CLUSTER_SURVIVOR_WORD`](crcbl_shaders::cull::CLUSTER_SURVIVOR_WORD).
    ///
    /// **Topic 03 §3.6's culling-stats readback is this buffer, on a delayed
    /// ring — the one readback the frame loop is allowed.** Both counters live
    /// here rather than in a buffer each so that stays one copy per frame.
    ///
    /// The instance count is the **true** one, which can exceed
    /// [`DrawGen::visible_capacity`] — so it is also where a scene that outgrew
    /// the list says so. The cluster count is what §3.5's amplification stage
    /// kept, and is zero on every path that has no amplification stage: the two
    /// indirect tails, and a device with `Features::MESH_SHADER` and no
    /// `Features::TASK_SHADER`.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn visible_count(&self, frame: usize) -> BufferHandle {
        self.visible_count[frame]
    }

    /// `frame`'s indirect arguments, [`draw_gen::DRAW_ARGS_SIZE`] bytes per
    /// bucket. The same buffer [`GeneratedDraws::args`] names.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn args(&self, frame: usize) -> BufferHandle {
        self.args[frame]
    }

    /// `frame`'s per-bucket draw counts, in the **first
    /// [`bucket_count`](Self::bucket_count) words** of the buffer
    /// [`GeneratedDraws::counts`] names.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn counts(&self, frame: usize) -> BufferHandle {
        self.counts[frame]
    }

    /// Every host-written table the draw-argument pass reads, in one buffer —
    /// the bucket table, the per-bucket cluster counts and
    /// topic 25's three selection tables.
    ///
    /// Shared by every frame, because all five are decided when a mesh becomes
    /// resident. Exposed for the reason the per-frame buffers are: the cluster
    /// counts are the only CPU-side half of an extent that is otherwise the
    /// GPU's, so a test with no GPU can still check the pass copied each
    /// bucket's own — [`table_offsets`](Self::table_offsets) is where each
    /// region starts.
    #[must_use]
    pub fn tables(&self) -> BufferHandle {
        self.tables
    }

    /// Where each region of [`tables`](Self::tables) begins, in words.
    #[must_use]
    pub const fn table_offsets(&self) -> draw_gen::TableOffsets {
        self.table_offsets
    }

    /// `frame`'s per-bucket mesh-dispatch arguments, at
    /// [`mesh_args_offset`](Self::mesh_args_offset)`(bucket)` in the buffer
    /// [`GeneratedDraws::counts`] names — the thing a test reads back to see that
    /// the extent the mesh path dispatched is the count culling produced rather
    /// than the instance pool's size.
    ///
    /// The same buffer [`DrawGen::counts`] hands back. **Not at offset zero**:
    /// the draw counts are in front of it.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    #[must_use]
    pub fn mesh_args(&self, frame: usize) -> BufferHandle {
        self.counts[frame]
    }

    /// Topic 25's hysteresis state, for a caller binding it into a
    /// mesh pipeline that reads it.
    ///
    /// One buffer for every frame in flight, unlike everything else here that a
    /// caller binds — see [`DrawGen::group_state`](Self::group_state)'s field
    /// docs, which is where that is argued.
    #[must_use]
    pub fn group_state(&self) -> BufferHandle {
        self.group_state
    }

    /// The stride between two instances in that buffer, which is what
    /// [`ClusterDrawConstants::group_stride`] has to carry for the amplification
    /// stage to index it the same way this pass does.
    ///
    /// [`ClusterDrawConstants::group_stride`]: crcbl_shaders::meshlet::ClusterDrawConstants::group_stride
    #[must_use]
    pub const fn group_stride(&self) -> u32 {
        self.group_stride
    }

    /// Writes `frame`'s cull parameters — this frame's frustum, how much of the
    /// instance array to test, and the camera topic 25's uniform
    /// cut selects a level from.
    ///
    /// The three counters both dispatches add to are **not** zeroed here: that
    /// is the clearing pass [`DrawGen::add_passes`] schedules, and the module
    /// docs say why it has to be a dispatch inside the frame rather than a host
    /// write before it.
    ///
    /// Call once per frame, before [`DrawGen::add_passes`], against the frame
    /// slot the instance pool rotated to — the buffer written here is the one
    /// that slot's bind groups name.
    ///
    /// `instance_count` is how many elements of the instance array the cull
    /// dispatch tests, which is
    /// [`InstancePool::slot_count`](crate::instance_pool::InstancePool::slot_count)
    /// and **not** its live count: an array with a hole in it still has live
    /// instances above the hole.
    ///
    /// # Errors
    ///
    /// [`HalError`] if the write failed.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    /// `camera_position` and `lod_params` are the two the drawing pass writes
    /// into [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) — passed in
    /// rather than re-derived here for the reason the frustum is: a pass that
    /// selects detail against one camera while another draws is a difference
    /// nothing in a frame can see.
    ///
    /// **Which is why the one caller allowed to break that is a deliberate
    /// setting rather than an accident of what was in scope.**
    /// [`ForwardRenderer::set_frozen_selection_eye`] hands this a pinned eye
    /// while the frame block keeps the live camera, so the cut a reviewer is
    /// looking at is the one chosen for somewhere they are no longer standing —
    /// which is the only vantage point a cut can be judged from.
    ///
    /// [`ForwardRenderer::set_frozen_selection_eye`]: crate::ForwardRenderer::set_frozen_selection_eye
    pub fn begin_frame(
        &self,
        device: &dyn Device,
        frame: usize,
        frustum: &Frustum,
        instance_count: u32,
        camera_position: [f32; 3],
        lod_params: [f32; 3],
    ) -> Result<(), HalError> {
        self.begin_frame_with(
            device,
            frame,
            frustum,
            instance_count,
            Selection {
                camera_position,
                lod_params,
            },
            &FrameCull::Plain,
        )
    }

    /// [`begin_frame`](Self::begin_frame), with what the cull does beyond the
    /// frustum this frame.
    ///
    /// The mode written here is what [`add_passes`](Self::add_passes) and
    /// [`add_occlusion_passes`](Self::add_occlusion_passes) check against, so a
    /// frame whose passes disagree with the block its dispatches read is a panic
    /// rather than a frame that scatters into regions nothing draws.
    ///
    /// # Errors
    ///
    /// [`HalError`] if a write failed.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with, or `cull` asks for a mode
    /// this generator was not built for.
    pub fn begin_frame_with(
        &self,
        device: &dyn Device,
        frame: usize,
        frustum: &Frustum,
        instance_count: u32,
        selection: Selection,
        cull: &FrameCull<'_>,
    ) -> Result<(), HalError> {
        let Selection {
            camera_position,
            lod_params,
        } = selection;
        let mut params = cull_shader::Params {
            planes: frustum.planes.map(|plane| plane.to_array()),
            instance_count,
            capacity: self.capacity,
            hidden_view: self.hidden_view,
            ..cull_shader::Params::default()
        };
        let mode = match cull {
            FrameCull::Plain => DrawMode::Plain,
            FrameCull::Faces(faces) => {
                assert_eq!(
                    self.mode,
                    DrawMode::Faces,
                    "a point light's face culls need a generator built with its face regions"
                );
                params.features = cull_shader::Features::FACES;
                for (face, planes) in faces.iter().enumerate() {
                    for (plane, value) in planes.iter().enumerate() {
                        params.face_planes[face * cull_shader::FACE_PLANES + plane] =
                            value.to_array();
                    }
                }
                DrawMode::Faces
            }
            FrameCull::Occlusion(occlusion) => {
                assert_eq!(
                    self.mode,
                    DrawMode::Occlusion,
                    "the occlusion culls need a generator built with the occlusion regions"
                );
                let mut features = cull_shader::Features::NONE;
                if occlusion.occlusion && occlusion.history {
                    features = features.union(cull_shader::Features::OCCLUSION_HISTORY);
                }
                if occlusion.small_feature_pixels.is_some() {
                    features = features.union(cull_shader::Features::SMALL_FEATURE);
                }
                params.features = features;
                params.view_proj = occlusion.view_projection.to_cols_array();
                params.previous_view_proj = occlusion.previous_view_projection.to_cols_array();
                params.target_extent = [occlusion.target.0, occlusion.target.1];
                params.pyramid_levels = occlusion
                    .pyramid_levels
                    .min(cull_shader::OCCLUSION_MAX_LEVELS);
                params.small_feature_pixels = occlusion.small_feature_pixels.unwrap_or(0.0);
                if occlusion.occlusion {
                    DrawMode::Occlusion
                } else {
                    DrawMode::Plain
                }
            }
        };
        device.write_buffer(
            self.gen_params[frame],
            0,
            &draw_gen::Params {
                bucket_count: self.bucket_count,
                visible_capacity: self.capacity,
                group_stride: self.group_stride,
                bucket_modes_at: self.table_offsets.bucket_modes_at,
                bucket_clusters_at: self.table_offsets.bucket_clusters_at,
                mesh_levels_at: self.table_offsets.mesh_levels_at,
                level_groups_at: self.table_offsets.level_groups_at,
                level_meshes_at: self.table_offsets.level_meshes_at,
                camera_position,
                lod_params,
                mode,
                draw_regions: self.mode.regions(),
                face_runs_at: draw_gen::face_runs_at(self.capacity, self.bucket_count),
                bucket_lookup_at: self.table_offsets.bucket_lookup_at,
                task_lanes: self.task_lanes,
                flat_segments_at: self.table_offsets.flat_segments_at,
            }
            .to_bytes(),
        )?;
        device.write_buffer(self.cull_params[frame], 0, &params.to_bytes())?;
        // A frame whose occlusion culls are off but whose small-feature test is
        // on still dispatches the occlusion entry point — it is where that test
        // lives — and scatters plainly.
        let cull_word = match cull {
            FrameCull::Occlusion(occlusion)
                if !occlusion.occlusion && occlusion.small_feature_pixels.is_some() =>
            {
                SMALL_FEATURE_ONLY
            }
            _ => mode.word(),
        };
        self.frame_modes[frame].store(cull_word, Ordering::Relaxed);
        Ok(())
    }

    /// The maximum number of passes [`add_passes`](Self::add_passes) adds to a
    /// frame: the clear, the cull, and the route, prefix-sum and scatter passes.
    ///
    /// A ceiling rather than an exact count: a frame that tests no instance
    /// omits the cull and scatter passes and adds only the clear, route and
    /// prefix-sum ones. This upper bound is what a caller sizing
    /// [`PassTimers`](crate::timing::PassTimers) adds up — see
    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES).
    pub const MAX_PASSES: u32 = 5;

    /// How many dispatches [`add_passes`](Self::add_passes) records for a frame
    /// that tests at least one instance: the clear, the cull, and the
    /// draw-argument pass's route, prefix sum and scatter.
    ///
    /// One per pass of [`MAX_PASSES`](Self::MAX_PASSES), which is the same
    /// number: a frame that tests no instance records neither the cull's nor
    /// the scatter's, since a dispatch of no workgroups is one Metal rejects.
    pub const DISPATCHES: u32 = 5;

    /// Passes [`add_late_passes`](Self::add_late_passes) adds at most: the
    /// second occlusion phase, the late scatter and the finish.
    pub const LATE_PASSES: u32 = 3;

    /// Adds the cull and draw-argument passes to `graph` and returns what the
    /// caller's render pass draws from.
    ///
    /// The barriers between the three — including the transition into
    /// [`ResourceState::IndirectArgument`] — are the graph's, computed from the
    /// accesses declared here and the ones the caller declares on the
    /// [`GeneratedDraws`] ids.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub fn add_passes(
        &self,
        graph: &mut RenderGraph<'_>,
        frame: usize,
        instance_count: u32,
    ) -> GeneratedDraws {
        let word = self.frame_modes[frame].load(Ordering::Relaxed);
        assert!(
            word != DrawMode::Occlusion.word() && word != SMALL_FEATURE_ONLY,
            "frame {frame} was begun with the occlusion culls, whose passes are \
             `add_occlusion_passes`"
        );
        self.record_passes(graph, frame, instance_count, None)
    }

    /// [`add_passes`](Self::add_passes) for a frame
    /// [`begin_frame_with`](Self::begin_frame_with) began with
    /// [`FrameCull::Occlusion`]: the cull is the first occlusion phase against
    /// `pyramid`, which it reads before this frame's reduction passes write it.
    ///
    /// The draws it returns are the **early** ones — region
    /// [`draw_gen::EARLY_REGION`] — until [`add_late_passes`](Self::add_late_passes)
    /// has closed the frame; a frame whose occlusion is off and whose
    /// small-feature test is on draws region 0 from here directly.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with, or was not begun with
    /// [`FrameCull::Occlusion`].
    pub fn add_occlusion_passes(
        &self,
        graph: &mut RenderGraph<'_>,
        frame: usize,
        instance_count: u32,
        pyramid: &PyramidInputs<'_>,
    ) -> GeneratedDraws {
        let word = self.frame_modes[frame].load(Ordering::Relaxed);
        assert!(
            word == DrawMode::Occlusion.word() || word == SMALL_FEATURE_ONLY,
            "frame {frame} was not begun with the occlusion culls"
        );
        let occlusion = self
            .occlusion()
            .unwrap_or_else(|| unreachable!("begin_frame_with checked the generator's mode"));
        self.record_passes(
            graph,
            frame,
            instance_count,
            Some((occlusion.early, occlusion.cull_pipeline_layout, pyramid)),
        )
    }

    /// The second occlusion phase and the late draw arguments, after this
    /// frame's farthest-depth pyramid has been reduced from the early prepass.
    ///
    /// Three passes: `cull.slang`'s `lateMain` tests every survivor the first
    /// phase marked against `pyramid`, `draw_gen.slang`'s late scatter appends
    /// the ones it rescued behind each bucket's early run, and its finish writes
    /// region [`draw_gen::LATE_REGION`]'s counts and region 0's — the early and
    /// late draws together, which is what the forward pass draws. A frame that
    /// tests no instance records the finish alone, because region 0 still needs
    /// its zeroes written.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with, or was not begun with
    /// occlusion on.
    pub fn add_late_passes(
        &self,
        graph: &mut RenderGraph<'_>,
        frame: usize,
        instance_count: u32,
        draws: &GeneratedDraws,
        pyramid: &PyramidInputs<'_>,
    ) {
        assert_eq!(
            self.frame_modes[frame].load(Ordering::Relaxed),
            DrawMode::Occlusion.word(),
            "frame {frame} was not begun with the occlusion culls on"
        );
        let occlusion = self
            .occlusion()
            .unwrap_or_else(|| unreachable!("begin_frame_with checked the generator's mode"));
        let groups = instance_count.div_ceil(cull_shader::WORKGROUP_SIZE);
        if groups != 0 {
            let cull_group = self.cull_groups[frame];
            let pyramid_group = pyramid.group;
            let layout = occlusion.cull_pipeline_layout;
            let pipeline = occlusion.late;
            let mut pass = graph
                .add_compute_pass("occlusion-late")
                .use_buffer(draws.runs_id, ResourceState::ShaderReadWrite)
                .use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite);
            for &level in pyramid.levels {
                pass = pass.read_image(level);
            }
            pass.execute(move |ctx| {
                let encoder = ctx.encoder();
                encoder.bind_compute_pipeline(pipeline);
                encoder.bind_group(0, cull_group, &[], layout);
                encoder.bind_group(1, pyramid_group, &[], layout);
                encoder.dispatch(groups, 1, 1);
            });
        }
        let gen_layout = self.pipelines.gen_pipeline_layout;
        let gen_group = self.gen_groups[frame];
        for (label, pipeline, groups) in [
            (
                "draw-late-scatter",
                occlusion.late_scatter,
                instance_count.div_ceil(draw_gen::WORKGROUP_SIZE),
            ),
            ("draw-late-finish", occlusion.late_finish, 1),
        ] {
            if groups == 0 {
                continue;
            }
            graph
                .add_compute_pass(label)
                .read_buffer(draws.visible_count_id)
                .use_buffer(draws.runs_id, ResourceState::ShaderReadWrite)
                .use_buffer(draws.args_id, ResourceState::ShaderReadWrite)
                .use_buffer(draws.counts_id, ResourceState::ShaderReadWrite)
                .use_buffer(draws.group_state_id, ResourceState::ShaderReadWrite)
                .execute(move |ctx| {
                    let encoder = ctx.encoder();
                    encoder.bind_compute_pipeline(pipeline);
                    encoder.bind_group(0, gen_group, &[], gen_layout);
                    encoder.dispatch(groups, 1, 1);
                });
        }
    }

    /// The clear, the cull and the three draw-argument passes, with the cull
    /// either `cull.slang`'s frustum entry point or `occlusion`'s first phase
    /// over the pyramid it names.
    fn record_passes(
        &self,
        graph: &mut RenderGraph<'_>,
        frame: usize,
        instance_count: u32,
        occlusion: Option<(
            ComputePipelineHandle,
            PipelineLayoutHandle,
            &PyramidInputs<'_>,
        )>,
    ) -> GeneratedDraws {
        // Each buffer arrives in the state the *previous* frame that used this
        // slot left it in, which is the state declared as final below. Vacuous
        // on the first frame, when nothing has been written and there is nothing
        // to order against, and the real prior use on every later one.
        let import = |graph: &mut RenderGraph<'_>, label: &str, buffer, state| {
            graph.import_buffer(
                label,
                ImportedBuffer {
                    buffer,
                    initial: state,
                    final_state: state,
                },
            )
        };
        let visible_count = import(
            graph,
            "cull-count",
            self.visible_count[frame],
            ResourceState::ShaderRead,
        );
        // The survivor list and the per-bucket runs are one buffer, so they are
        // one id: importing it twice would give the graph two independent
        // histories of one resource and a barrier computed from half of it.
        let runs = import(
            graph,
            "visible-and-bucket-runs",
            self.runs[frame],
            ResourceState::ShaderRead,
        );
        let args = import(
            graph,
            "draw-args",
            self.args[frame],
            ResourceState::IndirectArgument,
        );
        // The draw counts and the mesh-dispatch extents, likewise.
        let counts = import(
            graph,
            "draw-counts-and-mesh-dispatch-args",
            self.counts[frame],
            ResourceState::IndirectArgument,
        );
        // **Not indexed by `frame`**, and that is the point: this one buffer is
        // what carries a decision from the previous frame into this one. It
        // arrives in `ShaderReadWrite` because that is what the last frame left
        // it in — and on the very first frame because that is what
        // the start-up fill left it in, which is why that copy ends with a
        // barrier rather than in `TransferDst`. `ResourceState::needs_barrier`
        // answers `true` for any
        // transition touching a write — so the first barrier of this frame
        // carries a source scope covering that frame's writes and the mesh
        // stage's reads of them, whether or not that frame is still in flight.
        let group_state = import(
            graph,
            "lod-group-state",
            self.group_state,
            ResourceState::ShaderReadWrite,
        );

        // The zero every atomic below counts up from, and the first thing in the
        // frame that touches any of the three. Its barrier into the cull pass is
        // the graph's, out of the `ShaderReadWrite` declared on both sides.
        let clear_pipeline = self.pipelines.clear_pipeline;
        let clear_layout = self.pipelines.clear_pipeline_layout;
        let clear_group = self.clear_groups[frame];
        // The longest of the three buffers: the arguments, one structure per
        // bucket per region, or for a small table the counts and extents with
        // the flat task dispatches behind them. `new` refuses a table with no
        // buckets, so this is never the empty dispatch Metal rejects.
        let regions = self.mode.regions();
        let clear_groups = (regions * self.bucket_count * draw_gen::DRAW_ARGS_WORDS as u32)
            .max(draw_gen::flat_args_word(
                self.bucket_count,
                regions,
                regions,
                0,
                0,
            ))
            .div_ceil(clear_counters::WORKGROUP_SIZE);
        graph
            .add_compute_pass("clear-counters")
            .use_buffer(visible_count, ResourceState::ShaderReadWrite)
            .use_buffer(args, ResourceState::ShaderReadWrite)
            // Both regions of it: the counts and the mesh-dispatch extents are
            // one buffer and therefore one declaration.
            .use_buffer(counts, ResourceState::ShaderReadWrite)
            .execute(move |ctx| {
                let encoder = ctx.encoder();
                encoder.bind_compute_pipeline(clear_pipeline);
                encoder.bind_group(0, clear_group, &[], clear_layout);
                encoder.dispatch(clear_groups, 1, 1);
            });

        let (cull_pipeline, cull_layout, pyramid_group) = match occlusion {
            Some((pipeline, layout, pyramid)) => (pipeline, layout, Some(pyramid.group)),
            None => (
                self.pipelines.cull_pipeline,
                self.pipelines.cull_pipeline_layout,
                None,
            ),
        };
        let cull_group = self.cull_groups[frame];
        let cull_groups = instance_count.div_ceil(cull_shader::WORKGROUP_SIZE);
        // Omit an empty pass, not just its dispatch: Metal still creates an
        // encoder for a graph pass, and strict validation rejects ending one
        // without work. The clear and argument-generation passes remain needed
        // to erase the preceding frame's counts and populate zero draws.
        if cull_groups != 0 {
            let mut pass = graph
                .add_compute_pass("cull")
                // `ShaderReadWrite` rather than a write-only state for both: a
                // storage-buffer descriptor permits reads whatever the shader does
                // with it, and the counter is genuinely read-modify-written.
                .use_buffer(runs, ResourceState::ShaderReadWrite)
                .use_buffer(visible_count, ResourceState::ShaderReadWrite);
            // The previous frame's pyramid, read before this frame's reduction
            // writes over it: the declaration is what orders the two.
            for &level in occlusion.map_or(&[][..], |(_, _, pyramid)| pyramid.levels) {
                pass = pass.read_image(level);
            }
            pass.execute(move |ctx| {
                let encoder = ctx.encoder();
                encoder.bind_compute_pipeline(cull_pipeline);
                encoder.bind_group(0, cull_group, &[], cull_layout);
                if let Some(group) = pyramid_group {
                    encoder.bind_group(1, group, &[], cull_layout);
                }
                encoder.dispatch(cull_groups, 1, 1);
            });
        }

        let gen_layout = self.pipelines.gen_pipeline_layout;
        let gen_group = self.gen_groups[frame];
        // One `binMain` invocation owns bucket `i` *and* routes visible instance
        // `i`, so its dispatch covers the larger of the two — and is never empty,
        // because the static half of every bucket's arguments has to be written
        // even for a frame that culled everything.
        let bin_groups = instance_count
            .max(self.bucket_count)
            .div_ceil(draw_gen::WORKGROUP_SIZE);
        // `scatterMain` only scatters, and the survivors are at most the tested
        // instances.
        let scatter_groups = instance_count.div_ceil(draw_gen::WORKGROUP_SIZE);
        // **Three passes, not three dispatches in one**, and the difference is
        // the whole of whether this works on every device. Each stage reads what
        // the one before it wrote — `startsMain` the routes and counts
        // `binMain` finished, `scatterMain` the starts — and a dependency a pass
        // does not declare is one the device is not told about: `crcbl-vk`
        // records explicit pipeline barriers, and a driver may run commands with
        // no barrier between them in any order it likes. Recorded as one pass,
        // an NVIDIA GeForce MX550 (615.71.09) ran the prefix sum and the scatter
        // against buffers the routing dispatch had not written yet, so every
        // bucket's start collapsed onto the run region's first word — while
        // lavapipe, which runs commands in order, passed every check. As three
        // passes over the same declarations the graph puts a barrier on each
        // buffer between them, as it does between the cull and this.
        //
        // Every pass declares all four written buffers, because every pass binds
        // the one group that names them.
        let passes = [
            ("draw-args", self.pipelines.bin_pipeline, bin_groups),
            ("draw-starts", self.pipelines.starts_pipeline, 1),
            (
                "draw-scatter",
                self.pipelines.scatter_pipeline,
                scatter_groups,
            ),
        ];
        for (label, pipeline, groups) in passes {
            // No instances tested is no survivors to scatter: omit that pass
            // for the same reason as the cull's.
            if groups == 0 {
                continue;
            }
            graph
                .add_compute_pass(label)
                .read_buffer(visible_count)
                // Read for the survivor list and written for the routes, the runs
                // and their starts, which share it — one declaration, and
                // `ShaderReadWrite` is what it really is.
                .use_buffer(runs, ResourceState::ShaderReadWrite)
                .use_buffer(args, ResourceState::ShaderReadWrite)
                .use_buffer(counts, ResourceState::ShaderReadWrite)
                .use_buffer(group_state, ResourceState::ShaderReadWrite)
                .execute(move |ctx| {
                    let encoder = ctx.encoder();
                    encoder.bind_compute_pipeline(pipeline);
                    encoder.bind_group(0, gen_group, &[], gen_layout);
                    encoder.dispatch(groups, 1, 1);
                });
        }

        GeneratedDraws {
            args: self.args[frame],
            args_id: args,
            counts: self.counts[frame],
            counts_id: counts,
            flat_args_offset: self.flat_args_offset(0, 0),
            runs_id: runs,
            group_state_id: group_state,
            visible_count_id: visible_count,
        }
    }

    /// Releases everything it owns, in dependency order, and gives back its
    /// reference to the shared [`DrawGenPipelines`] — which this destroys only
    /// if it was the last. The device must be idle.
    pub fn destroy(self, device: &dyn Device) {
        for group in self
            .gen_groups
            .into_iter()
            .chain(self.cull_groups)
            .chain(self.clear_groups)
        {
            device.destroy_bind_group(group);
        }
        DrawGenPipelines::release(self.pipelines, device);
        for buffer in [self.tables, self.clear_params, self.group_state]
            .into_iter()
            .chain(self.gen_params)
            .chain(self.cull_params)
            .chain(self.visible_count)
            .chain(self.runs)
            .chain(self.args)
            .chain(self.counts)
        {
            device.destroy_buffer(buffer);
        }
    }
}

/// A uniform-buffer layout entry for the compute stage.
///
/// Shared with [`crate::light_grid`], which builds a compute pass on exactly
/// these terms: one uniform block of parameters and a handful of storage
/// buffers, in the shader's declaration order.
pub(crate) const fn uniform(binding: u32) -> BindGroupLayoutEntry {
    BindGroupLayoutEntry {
        binding,
        visibility: ShaderStages::COMPUTE,
        kind: BindingKind::UniformBuffer { dynamic: false },
        count: 1,
        flags: BindingFlags::empty(),
    }
}

/// A `uint` element's stride — the element of every counter, index and bitmask
/// buffer these compute passes declare.
pub(crate) const UINT_STRIDE: u32 = size_of::<u32>() as u32;

/// A storage-buffer layout entry for the compute stage. `read_only` is the
/// shader's own `StructuredBuffer` versus `RWStructuredBuffer`, so it is the
/// truth rather than a hint, and `stride` is the byte size of that buffer's
/// element type — `crcbl-vk` and `crcbl-dx12` both refuse a pipeline whose
/// shader disagrees.
pub(crate) const fn storage(binding: u32, read_only: bool, stride: u32) -> BindGroupLayoutEntry {
    BindGroupLayoutEntry {
        binding,
        visibility: ShaderStages::COMPUTE,
        kind: BindingKind::StorageBuffer {
            read_only,
            dynamic: false,
            stride,
        },
        count: 1,
        flags: BindingFlags::empty(),
    }
}

/// A whole-buffer bind group entry.
pub(crate) const fn bound(binding: u32, buffer: BufferHandle) -> BindGroupEntry {
    BindGroupEntry {
        binding,
        array_index: 0,
        resource: BindingResource::whole_buffer(buffer),
    }
}

/// Creates a compute pipeline from `shader`'s single compute entry point,
/// destroying the module whether or not the pipeline was created.
pub(crate) fn compute_pipeline(
    device: &dyn Device,
    label: &str,
    shader: &crcbl_shaders::Shader,
    layout: PipelineLayoutHandle,
    workgroup_size: u32,
) -> Result<ComputePipelineHandle, HalError> {
    // Resolved before the module exists, for `crate::forward`'s reason: a
    // manifest that disagreed with the artifact would otherwise fail inside the
    // descriptor literal, with the module already created and nothing holding
    // it.
    let entry_point = shader.entry_point(Stage::Compute).ok_or_else(|| {
        HalError::ShaderCompilation(format!(
            "{}.slang exposes no unambiguous compute entry point; the committed SPIR-V and its \
             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
            shader.name()
        ))
    })?;
    compute_pipeline_entry(device, label, shader, entry_point, layout, workgroup_size)
}

/// [`compute_pipeline`] for a module with **more than one** compute entry
/// point, which is a thing Slang compiles and [`Shader::entry_point`] refuses
/// to guess between.
///
/// `crate::volumetric` is the caller that needs it: its scatter and integrate
/// kernels are two entry points of one module because they share the froxel
/// arithmetic and there is no `#include` to share it any other way.
///
/// The name is not checked against the module here — a wrong one fails at
/// pipeline creation, which is where every backend reports it.
///
/// [`Shader::entry_point`]: crcbl_shaders::Shader::entry_point
pub(crate) fn compute_pipeline_entry(
    device: &dyn Device,
    label: &str,
    shader: &crcbl_shaders::Shader,
    entry_point: &str,
    layout: PipelineLayoutHandle,
    workgroup_size: u32,
) -> Result<ComputePipelineHandle, HalError> {
    compute_pipeline_entry_with_workgroup(
        device,
        label,
        shader,
        entry_point,
        layout,
        [workgroup_size, 1, 1],
    )
}

/// [`compute_pipeline_entry`] with the complete three-dimensional workgroup
/// shape for kernels whose lanes form a tile rather than a row.
pub(crate) fn compute_pipeline_entry_with_workgroup(
    device: &dyn Device,
    label: &str,
    shader: &crcbl_shaders::Shader,
    entry_point: &str,
    layout: PipelineLayoutHandle,
    workgroup_size: [u32; 3],
) -> Result<ComputePipelineHandle, HalError> {
    let module = device.create_shader_module(&ShaderModuleDesc {
        label: Some(shader.name()),
        spirv: shader.spirv(),
        wgsl: shader.wgsl(),
        msl: shader.msl(),
        // One DXIL container per entry point, all of them, exactly as the
        // two-stage graphics modules pass theirs — the backend picks the one
        // `entry_point` names below.
        dxil: &shader.dxil_containers(),
    })?;
    let pipeline = device.create_compute_pipeline(&ComputePipelineDesc {
        label: Some(label),
        layout,
        compute: ShaderEntry {
            module,
            entry_point,
        },
        // The shader's own shape rather than literals: a dispatch sized against
        // a different one tests part of the array and reads as a cull.
        workgroup_size,
    });
    device.destroy_shader_module(module);
    pipeline
}

/// What a partly-built [`DrawGen`] or [`DrawGenPipelines`] has to give back.
///
/// Each `build` creates its objects with `?` between them and the seam's
/// `destroy_*` is explicit, so a failure half way through would otherwise leak
/// everything created before it. A generator's holds buffers and bind groups;
/// the shared set's holds layouts and pipelines.
#[derive(Debug, Default)]
struct Rollback {
    buffers: Vec<BufferHandle>,
    bind_groups: Vec<BindGroupHandle>,
    bind_group_layouts: Vec<BindGroupLayoutHandle>,
    pipeline_layouts: Vec<PipelineLayoutHandle>,
    pipelines: Vec<ComputePipelineHandle>,
}

impl Rollback {
    /// Forgets everything, once the objects have an owner that will destroy
    /// them.
    fn disarm(&mut self) {
        *self = Self::default();
    }

    /// Releases everything: pipelines before their layouts, bind groups before
    /// theirs, and buffers last — the order [`DrawGen::destroy`] and
    /// [`DrawGenPipelines`]' own release follow between them.
    fn run(self, device: &dyn Device) {
        for handle in self.pipelines {
            device.destroy_compute_pipeline(handle);
        }
        for handle in self.pipeline_layouts {
            device.destroy_pipeline_layout(handle);
        }
        for handle in self.bind_groups {
            device.destroy_bind_group(handle);
        }
        for handle in self.bind_group_layouts {
            device.destroy_bind_group_layout(handle);
        }
        for handle in self.buffers {
            device.destroy_buffer(handle);
        }
    }
}

// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;
    use crcbl_hal::null::{NullInstance, Recorder};
    use crcbl_hal::{DeviceDesc, Instance, QueueHandle, QueueKind};
    use crcbl_shaders::level_select::MeshLevels;

    fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
        let recorder = Recorder::new();
        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        let device = instance
            .create_device(&DeviceDesc::for_adapter(adapter.id))
            .expect("the null backend always opens");
        let queue = device.queue(QueueKind::Graphics).expect("always present");
        (recorder, device, queue)
    }

    /// A generator over `buckets` buckets of `capacity` instances, every bucket
    /// drawing its own flat mesh — the smallest table that is still a table of
    /// that length.
    fn generator(device: &dyn Device, queue: QueueHandle, capacity: u32, buckets: u32) -> DrawGen {
        generator_in(device, queue, capacity, buckets, DrawMode::Plain)
    }

    /// [`generator`], built for `mode`.
    fn generator_in(
        device: &dyn Device,
        queue: QueueHandle,
        capacity: u32,
        buckets: u32,
        mode: DrawMode,
    ) -> DrawGen {
        let storage = |label: &str, size: u64| {
            device
                .create_buffer(&BufferDesc {
                    label: Some(label),
                    size,
                    usage: BufferUsage::STORAGE,
                    memory: MemoryLocation::HostUpload,
                })
                .expect("a storage buffer")
        };
        let instances = [storage("instances", 4)];
        let mesh_table = storage("mesh table", 4);
        let bucket_meshes: Vec<u32> = (0..buckets).collect();
        let zeroes = vec![0u32; bucket_meshes.len()];
        let mesh_levels: Vec<MeshLevels> = bucket_meshes
            .iter()
            .map(|mesh| MeshLevels {
                first_level: *mesh,
                ..MeshLevels::FLAT
            })
            .collect();
        let mut uploads = UploadBatch::new(device, queue, "draw gen test");
        let pipelines = DrawGenPipelines::new(device, mode == DrawMode::Occlusion, &mut || {})
            .expect("the null backend builds the pipelines");
        let draws = DrawGen::new(
            device,
            &mut uploads,
            &pipelines,
            &DrawGenDesc {
                label: Some("draw gen test"),
                instances: &instances,
                mesh_table,
                bucket_meshes: &bucket_meshes,
                bucket_modes: &zeroes,
                bucket_clusters: &zeroes,
                bucket_cluster_bases: &zeroes,
                mesh_levels: &mesh_levels,
                level_groups: &[],
                level_meshes: &bucket_meshes,
                instance_capacity: capacity,
                hidden_view: 0,
                mode,
                task_lanes: 0,
            },
        )
        .expect("the null backend builds a generator");
        uploads.submit().expect("the hysteresis state fills");
        // The generator holds the only reference now, so its own `destroy`
        // releases the set.
        DrawGenPipelines::release(pipelines, device);
        draws
    }

    /// **The runs buffer costs two words per bucket per draw region — its run
    /// start and its task chunks' start — and one for the bucket's mesh, not a
    /// capacity per bucket.**
    ///
    /// Two generators of one capacity and very different bucket counts, and the
    /// size the device was actually asked for — read off the allocation rather
    /// than off [`DrawGen::runs_size`], which a build that sized the buffer some
    /// other way would still answer correctly. When each bucket reserved its own
    /// run this difference was `capacity` words a bucket, so the second
    /// generator's buffer was sixty-four times the first's.
    #[test]
    fn the_runs_buffer_grows_by_a_word_per_bucket() {
        const CAPACITY: u32 = 1000;
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let few = generator(device, queue, CAPACITY, 1);
        let many = generator(device, queue, CAPACITY, 64);
        let size = |draws: &DrawGen| {
            recorder
                .buffer_size(draws.runs(0))
                .expect("the runs buffer is live")
        };

        let regions = u64::from(draw_gen::DRAW_REGIONS);
        assert_eq!(
            size(&many) - size(&few),
            u64::from(many.bucket_count() - few.bucket_count()) * (2 * regions + 1) * 4,
            "sixty-three more buckets cost sixty-three more words of run start and of chunk \
             start a region, and of mesh, and nothing else"
        );
        assert_eq!(
            size(&few),
            (3 * u64::from(CAPACITY) + regions + 1 + 2 * regions) * 4,
            "one bucket's generator holds the survivors, their routes, one capacity of runs, \
             one start per region, its mesh, and its chunk start and the region's end per region"
        );
        for draws in [&few, &many] {
            assert_eq!(
                draws.runs_size(),
                size(draws),
                "and the accessor a reader sizes a copy by is the size that was allocated"
            );
        }

        few.destroy(device);
        many.destroy(device);
        recorder.assert_valid();
    }

    /// **Every start word is past the runs and inside the buffer**, and bucket
    /// zero's run opens the run region.
    ///
    /// The words a constant block names are fixed at build and read by the
    /// geometry stages every frame, so two buckets sharing one would draw one
    /// bucket's run twice, and a word past the end is a read of nothing. The
    /// last region's chunk end, behind every start, mesh and chunk start, is
    /// the buffer's last.
    #[test]
    fn every_bucket_start_is_a_word_of_its_own_behind_the_runs() {
        const CAPACITY: u32 = 100;
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let draws = generator(device, queue, CAPACITY, 5);

        assert_eq!(
            draws.runs_at(),
            2 * CAPACITY,
            "past the survivors and their routes"
        );
        let starts: Vec<u32> = (0..draws.bucket_count())
            .map(|bucket| draws.bucket_start_word(bucket))
            .collect();
        assert_eq!(
            starts,
            (0..5)
                .map(|bucket| 3 * CAPACITY + bucket)
                .collect::<Vec<_>>(),
            "one word per bucket, in bucket order, behind one capacity of runs"
        );
        assert_eq!(
            draws.region_start_word(1, 0),
            starts[starts.len() - 1] + 1,
            "region 1's starts directly behind region 0's"
        );
        assert_eq!(
            draws.bucket_mesh_word(0),
            draws.region_start_word(draw_gen::DRAW_REGIONS - 1, draws.bucket_count() - 1) + 1,
            "the buckets' meshes directly behind the last region's starts"
        );
        assert_eq!(
            draws.chunk_start_word(0, 0),
            draws.bucket_mesh_word(draws.bucket_count() - 1) + 1,
            "the chunk starts directly behind the last bucket's mesh"
        );
        assert_eq!(
            draws.chunk_start_word(1, 0),
            draws.chunk_start_word(0, draws.bucket_count()) + 1,
            "each region's chunk starts, its end word included, directly behind the one before"
        );
        assert_eq!(
            u64::from(draws.chunk_start_word(draw_gen::DRAW_REGIONS - 1, draws.bucket_count()) + 1)
                * 4,
            draws.runs_size(),
            "and the last region's chunk end is the buffer's last word"
        );

        draws.destroy(device);
        recorder.assert_valid();
    }

    /// **The scene that ran a 2 GiB device out of memory**, through the layout
    /// each bucket used to reserve and through the one it has now.
    ///
    /// 17219 instances and 938 buckets are the measured `ew` scene
    /// `docs/backlog.md`'s performance review records; the numbers here are its
    /// byte sizes, asserted rather than written into a comment, so the module
    /// docs' claim moves with the formula.
    #[test]
    fn the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity() {
        const CAPACITY: u32 = 17219;
        const BUCKETS: u32 = 938;
        let per_bucket_runs = u64::from(CAPACITY) * (1 + u64::from(BUCKETS)) * 4;
        let shared_runs = u64::from(
            draw_gen::runs_words(CAPACITY, BUCKETS, false).expect("the scene's layout addresses"),
        ) * 4;
        assert_eq!(
            per_bucket_runs, 64_674_564,
            "61.7 MiB a buffer, as measured"
        );
        assert_eq!(
            shared_runs, 262_936,
            "256.8 KiB a buffer, with a run start and a chunk start per bucket for every draw \
             region, a chunk end per region, and a mesh word per bucket"
        );
    }

    /// **What the draw regions cost one frame in flight**, per generator and per
    /// renderer, in the measured scene of
    /// [`the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity`] —
    /// read off the allocations the device was asked for, so the figures a
    /// report quotes are these assertions' and not arithmetic beside them.
    ///
    /// A renderer holds a camera generator built for [`DrawMode::Occlusion`],
    /// [`crate::shadow::CASCADES`] built for [`DrawMode::Plain`] and
    /// [`crate::shadow::LIGHT_SLOTS`] built for [`DrawMode::Faces`] — the point
    /// light's face culls, whose face runs are most of the cost.
    #[test]
    fn the_regions_cost_what_their_layout_says_in_the_measured_scene() {
        const CAPACITY: u32 = 17219;
        const BUCKETS: u32 = 938;
        let (recorder, device, queue) = open();
        let device = device.as_ref();
        let size = |buffer| recorder.buffer_size(buffer).expect("live");
        let per_frame = |mode| {
            let draws = generator_in(device, queue, CAPACITY, BUCKETS, mode);
            let bytes = size(draws.runs(0)) + size(draws.args(0)) + size(draws.counts(0));
            draws.destroy(device);
            bytes
        };
        let [plain, occlusion, faces] =
            [DrawMode::Plain, DrawMode::Occlusion, DrawMode::Faces].map(per_frame);
        assert_eq!(
            plain, 296_776,
            "runs, one region of arguments and one of counts, and its flat dispatches"
        );
        assert_eq!(
            occlusion, 364_456,
            "three regions of arguments, counts and flat dispatches"
        );
        assert_eq!(
            faces, 913_076,
            "seven regions and six capacities of face runs"
        );
        // What a generator cost before there were regions: the runs with one
        // start per bucket, one argument structure and one count region.
        let before = (3 * u64::from(CAPACITY) + u64::from(BUCKETS)) * 4
            + u64::from(BUCKETS) * (draw_gen::DRAW_ARGS_SIZE as u64 + 16);
        assert_eq!(before, 244_148);
        let cascades = crate::shadow::CASCADES as u64;
        let slots = crate::shadow::LIGHT_SLOTS as u64;
        let renderer_before = before * (1 + cascades + slots);
        let renderer_after = occlusion + plain * cascades + faces * slots;
        assert_eq!(renderer_before, 1_709_036);
        assert_eq!(
            renderer_after, 4_610_312,
            "4.40 MiB a frame in flight, against 1.63 MiB before"
        );
        recorder.assert_valid();
    }
}