crcbl-render 0.8.0

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

pub mod card;
pub mod field;
pub mod placement;
pub mod shell;

use crcbl_hal::{
    BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
    BufferUsage, ClearValue, ColorTargetState, CompareOp, ComputePipelineHandle, DepthBias,
    DepthStencilState, Device, DrawIndirect, FilterMode, Format, GraphicsPipelineDesc,
    GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
    MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PrimitiveTopology, ResourceState,
    SampleType, SamplerAddressMode, SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc,
    ShaderStages, StoreOp, check_portable_storage_buffers,
};
use crcbl_shaders::grass::{
    BLADE_FAR_DRAW, BLADE_NEAR_DRAW, BLADE_STRIDE, CARD_DRAW, DRAW_ARGS_SIZE, FIELD_BLOCK_SIZE,
    FIN_DRAW, GEN_PARAMS_SIZE, GenParams, INSTANCE_STRIDE, PARAMS_SIZE, Params, SHELL_DRAW,
    SLOT_ARGS_SIZE, TILE_SIZE, Tile, WORKGROUP_SIZE,
};
use crcbl_shaders::wind::{PARAMS_SIZE as WIND_PARAMS_SIZE, WindParams};
use crcbl_shaders::{GRASS, GRASS_GEN, Stage};

use crate::draw_gen::compute_pipeline_entry;
use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
use crate::ssao::cached_group;
use crate::texture::{UploadedTexture, upload_texture, upload_texture_mip_layers};

pub use field::{
    BladeLod, BladeLook, BladeNormal, BladeShape, BladeStyle, BladeType, CELLS_PER_TILE, Clumping,
    CoverMap, GrassError, GrassField, Heightfield, MAX_BLADES, MAX_TILES, SLOT_CAPACITY, Shells,
};

/// One authored wind layer, as the texels `crcbl_wind` encodes them into.
///
/// **Here rather than in a module of its own**, because grass is the field's
/// only GPU consumer at this rung: `docs/plan/56-wind.md`'s decision 6 gives the
/// GPU copy one bind group, and that bind group is bindings 0 to 3 of
/// `grass_gen.slang`. The moment a second consumer wants it — trees at T1,
/// water at a later rung — it becomes a holder of its own, and `docs/backlog.md`
/// carries that.
///
/// The bytes are the same RGBA8 a `crcbl_wind::DirectionLayer` or
/// `crcbl_wind::IntensityLayer` was built from, so a caller hands one
/// description to both copies rather than encoding it twice.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindLayer {
    /// Texels along `+X` and along `+Z`.
    pub texels: [u32; 2],
    /// `texels[0] · texels[1] · 4` bytes of RGBA8.
    pub rgba8: Vec<u8>,
}

/// The two layers `grass_gen.slang` samples the wind through.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindLayers {
    /// The coarse direction layer: a deflection per texel in red and green.
    pub direction: WindLayer,
    /// The fine intensity layer: a speed multiplier per texel in red.
    pub intensity: WindLayer,
}

/// The direction layer a renderer binds until a caller sets one: a single texel
/// of "no deflection".
///
/// `(255, 128)` decodes to `(1, 0)` through the layer's `2x − 1`, which is the
/// complex identity — see `crcbl_wind::WindField::direction_at`. The prevailing
/// wind passes through it unturned.
const CALM_DIRECTION: [u8; 4] = [255, 128, 0, 255];

/// The intensity layer a renderer binds until a caller sets one: a single texel
/// of calm.
///
/// **Zero, so a field with no wind set is still.** It is the same off position
/// the plan's own check names — "at zero wind intensity no blade, card, shell or
/// tree moves between two ticks" — reached by the placeholder rather than by a
/// branch.
const CALM_INTENSITY: [u8; 4] = [0, 0, 0, 255];

/// Why a wind layer could not be uploaded.
#[derive(Debug, thiserror::Error)]
pub enum WindLayerError {
    /// A layer with a zero dimension.
    #[error("a {width}x{height} wind layer has no texels")]
    Empty {
        /// Texels along `+X`.
        width: u32,
        /// Texels along `+Z`.
        height: u32,
    },
    /// A layer whose bytes are not four per texel of the grid it came with.
    #[error("a {width}x{height} wind layer is {expected} bytes of RGBA8, and {found} arrived")]
    Size {
        /// Texels along `+X`.
        width: u32,
        /// Texels along `+Z`.
        height: u32,
        /// Bytes the grid needs.
        expected: usize,
        /// Bytes that arrived.
        found: usize,
    },
    /// The seam refused the upload.
    #[error("a wind layer could not be uploaded: {0}")]
    Hal(#[from] HalError),
}

impl WindLayer {
    fn check(&self) -> Result<(), WindLayerError> {
        let [width, height] = self.texels;
        if width == 0 || height == 0 {
            return Err(WindLayerError::Empty { width, height });
        }
        let expected = width as usize * height as usize * 4;
        if self.rgba8.len() != expected {
            return Err(WindLayerError::Size {
                width,
                height,
                expected,
                found: self.rgba8.len(),
            });
        }
        Ok(())
    }
}

/// The two buffers `docs/plan/57-grass.md`'s generation pass writes, and how
/// many slots they hold.
///
/// What `crcbl`'s `render_e2e` copies back to check the placement blade by blade
/// against [`placement::blades_of_tile`], and to read each slot's instance
/// count — the rung's "compared as instance data read back" and "a denser tile
/// draws more instances". Both are device-local with `TRANSFER_SRC`, which is
/// what makes that copy possible at all.
///
/// Slot `s` owns `[s · SLOT_CAPACITY, (s + 1) · SLOT_CAPACITY)` rows of
/// [`cells`](GrassBuffers::cells) and two regions of
/// [`instances`](GrassBuffers::instances): the same rows, holding its cards from
/// the start and its far mesh blades from the end, and the rows `slots ·
/// SLOT_CAPACITY` past them, holding its near mesh blades from the start. Every
/// row is `crcbl_shaders::grass::INSTANCE_STRIDE` bytes. It owns
/// `crcbl_shaders::grass::DRAWS_PER_SLOT` draws of [`args`](GrassBuffers::args)
/// from `s · SLOT_ARGS_SIZE` bytes — each draw vertex count, **instance count**,
/// first vertex, first instance, in `CARD_DRAW`, `SHELL_DRAW`, `FIN_DRAW`,
/// `BLADE_NEAR_DRAW`, `BLADE_FAR_DRAW` order.
#[derive(Clone, Copy, Debug)]
pub struct GrassBuffers {
    /// Every slot's card and mesh blade instances, in the order the appends
    /// landed, in the regions this type's documentation lays out.
    pub instances: crcbl_hal::BufferHandle,
    /// Every cell's blade at the cell's own index, whatever its look, and zero
    /// where the cell carries none.
    pub cells: crcbl_hal::BufferHandle,
    /// Every slot's draws' arguments.
    pub args: crcbl_hal::BufferHandle,
    /// Slots, which is tiles.
    pub slots: u32,
}

/// What one frame's grass draws: every handle its three passes bind, and the
/// static half of its generation block.
#[derive(Clone, Copy, Debug)]
pub(crate) struct GrassFrame {
    pub(crate) instances: BufferHandle,
    pub(crate) cells: BufferHandle,
    pub(crate) args: BufferHandle,
    pub(crate) blades: BufferHandle,
    pub(crate) tiles: BufferHandle,
    pub(crate) field_block: BufferHandle,
    pub(crate) ground: ImageViewHandle,
    pub(crate) cover: ImageViewHandle,
    pub(crate) card: ImageViewHandle,
    pub(crate) wind_direction: ImageViewHandle,
    pub(crate) wind_intensity: ImageViewHandle,
    /// Tiles, which is dispatches and draws alike.
    pub(crate) slots: u32,
    /// Whether any row is drawn as shells, which is whether the pass records
    /// the shell and fin draws.
    pub(crate) shells: bool,
    /// Whether the field stands fins, where it draws shells at all.
    pub(crate) fins: bool,
    /// Whether any row is drawn as mesh blades, which is whether the pass
    /// records the two blade draws.
    pub(crate) mesh_blades: bool,
    /// Everything of [`GenParams`] but the camera, which is the view's.
    pub(crate) generation: GenParams,
}

impl GrassFrame {
    /// Draws the `grass` pass records per tile slot: the cards always, the
    /// shells and fins where the field draws them, and both levels of mesh
    /// blades where it draws those.
    pub(crate) const fn draws_per_slot(&self) -> u32 {
        1 + self.shells as u32 + (self.shells && self.fins) as u32 + 2 * self.mesh_blades as u32
    }

    /// How many rows the field's blade table holds.
    pub(crate) const fn rows(&self) -> u32 {
        self.generation.limits[1]
    }

    /// The generation block for a camera at `camera`.
    pub(crate) fn gen_params(&self, camera: glam::Vec3) -> GenParams {
        let mut params = self.generation;
        params.camera = [camera.x, camera.y, camera.z, self.generation.camera[3]];
        params
    }
}

/// The field a renderer draws, its device resources, and the ones a replaced
/// field left behind.
#[derive(Debug)]
pub(crate) struct GrassScene {
    field: Option<GrassField>,
    live: Option<Resident>,
    wind: Wind,
    /// What a replaced field or layer left, and the frame count it was replaced
    /// at.
    ///
    /// **Not destroyed where it was replaced**: a frame already submitted is
    /// still reading those handles, and a caller replacing a field mid-flight is
    /// the ordinary case rather than a mistake. [`GrassScene::begin_frame`]
    /// releases what is older than the ring.
    retired: Vec<(u64, Retired)>,
    /// Frames begun, which is what a retirement is aged against.
    frames: u64,
    /// How many frames a retirement waits, which is the ring's depth.
    depth: u64,
}

/// A field's device resources.
#[derive(Debug)]
struct Resident {
    instances: BufferHandle,
    cells: BufferHandle,
    args: BufferHandle,
    blades: BufferHandle,
    tiles: BufferHandle,
    field_block: BufferHandle,
    ground: UploadedTexture,
    cover: UploadedTexture,
    card: UploadedTexture,
    slots: u32,
    shells: bool,
    fins: bool,
    mesh_blades: bool,
    generation: GenParams,
}

/// The two wind layers, and whether a caller set them.
#[derive(Debug)]
struct Wind {
    direction: UploadedTexture,
    intensity: UploadedTexture,
}

/// Anything waiting for the ring to come round before it is released.
#[derive(Debug)]
enum Retired {
    Field(Box<Resident>),
    Wind(Box<Wind>),
}

impl GrassScene {
    /// No field, and the calm placeholder layers.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the two one-texel uploads.
    pub(crate) fn new(
        device: &dyn Device,
        queue: crcbl_hal::QueueHandle,
        frames: usize,
    ) -> Result<Self, HalError> {
        Ok(Self {
            field: None,
            live: None,
            wind: Wind::calm(device, queue)?,
            retired: Vec::new(),
            frames: 0,
            depth: frames as u64,
        })
    }

    /// The field as it was last set.
    pub(crate) fn field(&self) -> Option<&GrassField> {
        self.field.as_ref()
    }

    /// Replaces the field, uploading everything a dispatch and a draw read.
    ///
    /// **All or nothing**: the new resources are built before the old ones are
    /// let go, so a field that fails leaves the previous one drawing.
    ///
    /// # Errors
    ///
    /// [`SetError::Field`] for a description the field itself refuses, and
    /// [`SetError::Hal`] for a seam call that failed.
    pub(crate) fn set(
        &mut self,
        device: &dyn Device,
        queue: crcbl_hal::QueueHandle,
        field: Option<&GrassField>,
    ) -> Result<(), SetError> {
        let resident = match field {
            Some(field) => Some(Resident::upload(device, queue, field)?),
            None => None,
        };
        if let Some(old) = self.live.take() {
            self.retired
                .push((self.frames, Retired::Field(Box::new(old))));
        }
        self.live = resident;
        self.field = field.cloned();
        Ok(())
    }

    /// Replaces the two wind layers; [`None`] restores the calm placeholder.
    ///
    /// # Errors
    ///
    /// [`WindLayerError`] for a layer that is not four bytes a texel, or a seam
    /// call that failed.
    pub(crate) fn set_wind_layers(
        &mut self,
        device: &dyn Device,
        queue: crcbl_hal::QueueHandle,
        layers: Option<&WindLayers>,
    ) -> Result<(), WindLayerError> {
        let wind = match layers {
            Some(layers) => Wind::upload(device, queue, layers)?,
            None => Wind::calm(device, queue)?,
        };
        let old = core::mem::replace(&mut self.wind, wind);
        self.retired
            .push((self.frames, Retired::Wind(Box::new(old))));
        Ok(())
    }

    /// Ages the retirement list and releases whatever the ring has passed.
    pub(crate) fn begin_frame(&mut self, device: &dyn Device) {
        self.frames += 1;
        let depth = self.depth;
        let now = self.frames;
        let mut kept = Vec::new();
        for (at, retired) in self.retired.drain(..) {
            if now.saturating_sub(at) > depth {
                match retired {
                    Retired::Field(resident) => resident.destroy(device),
                    Retired::Wind(wind) => wind.destroy(device),
                }
            } else {
                kept.push((at, retired));
            }
        }
        self.retired = kept;
    }

    /// The two buffers a dispatch writes, or [`None`] for a renderer with no
    /// field.
    pub(crate) fn buffers(&self) -> Option<GrassBuffers> {
        let live = self.live.as_ref()?;
        Some(GrassBuffers {
            instances: live.instances,
            cells: live.cells,
            args: live.args,
            slots: live.slots,
        })
    }

    /// What a frame draws, or [`None`] for a renderer with no field.
    pub(crate) fn frame(&self) -> Option<GrassFrame> {
        let live = self.live.as_ref()?;
        Some(GrassFrame {
            instances: live.instances,
            cells: live.cells,
            args: live.args,
            blades: live.blades,
            tiles: live.tiles,
            field_block: live.field_block,
            ground: live.ground.view,
            cover: live.cover.view,
            card: live.card.view,
            wind_direction: self.wind.direction.view,
            wind_intensity: self.wind.intensity.view,
            slots: live.slots,
            shells: live.shells,
            fins: live.fins,
            mesh_blades: live.mesh_blades,
            generation: live.generation,
        })
    }

    /// Releases everything, retirements included. The device must be idle.
    pub(crate) fn destroy(self, device: &dyn Device) {
        for (_, retired) in self.retired {
            match retired {
                Retired::Field(resident) => resident.destroy(device),
                Retired::Wind(wind) => wind.destroy(device),
            }
        }
        if let Some(live) = self.live {
            live.destroy(device);
        }
        self.wind.destroy(device);
    }
}

/// Why a field could not be made resident: its own description, or the seam.
#[derive(Debug, thiserror::Error)]
pub enum SetError {
    /// The description itself.
    #[error(transparent)]
    Field(#[from] GrassError),
    /// A buffer, an image or a copy the seam refused.
    #[error("a grass field could not be uploaded: {0}")]
    Hal(#[from] HalError),
}

impl Resident {
    /// Uploads everything `field` needs, releasing anything already created if a
    /// later step fails.
    fn upload(
        device: &dyn Device,
        queue: crcbl_hal::QueueHandle,
        field: &GrassField,
    ) -> Result<Self, SetError> {
        let ground = field.ground();
        let cover = field.cover();
        let ground_image = upload_texture(
            device,
            queue,
            "grass ground",
            Format::R32Float,
            ground.texels[0],
            ground.texels[1],
            &ground.to_bytes(),
        )?;
        let cover_image = match upload_texture(
            device,
            queue,
            "grass cover",
            Format::Rgba8Unorm,
            cover.texels[0],
            cover.texels[1],
            &cover.to_bytes(),
        ) {
            Ok(image) => image,
            Err(error) => {
                ground_image.destroy(device);
                return Err(error.into());
            }
        };
        let chain = card::coverage_chain(&card::blade_mask(card::CARD_EXTENT), card::CARD_EXTENT);
        let levels: Vec<&[u8]> = chain.iter().map(Vec::as_slice).collect();
        let card_image = match upload_texture_mip_layers(
            device,
            queue,
            "grass card",
            Format::R8Unorm,
            card::CARD_EXTENT,
            card::CARD_EXTENT,
            &[&levels],
        ) {
            Ok(image) => image,
            Err(error) => {
                cover_image.destroy(device);
                ground_image.destroy(device);
                return Err(error.into());
            }
        };

        let slots = field.slots();
        let descs = [
            (
                "grass instances",
                field.instance_bytes(),
                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
                MemoryLocation::DeviceLocal,
            ),
            (
                "grass draw args",
                u64::from(slots) * SLOT_ARGS_SIZE as u64,
                BufferUsage::STORAGE | BufferUsage::INDIRECT | BufferUsage::TRANSFER_SRC,
                MemoryLocation::DeviceLocal,
            ),
            (
                "grass blades",
                field.blade_bytes(),
                BufferUsage::STORAGE,
                MemoryLocation::HostUpload,
            ),
            (
                "grass tiles",
                u64::from(slots) * u64::from(TILE_STRIDE),
                BufferUsage::UNIFORM,
                MemoryLocation::HostUpload,
            ),
            // **One row per cell, whatever the looks**: a cell is written here
            // for a card row as for a shell or a blade row — see this module's
            // header for what that buys.
            (
                "grass cells",
                field.cell_bytes(),
                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
                MemoryLocation::DeviceLocal,
            ),
            (
                "grass field",
                FIELD_BLOCK_SIZE as u64,
                BufferUsage::UNIFORM,
                MemoryLocation::HostUpload,
            ),
        ];
        let mut created: Vec<BufferHandle> = Vec::with_capacity(descs.len());
        for (label, size, usage, memory) in descs {
            match device.create_buffer(&BufferDesc {
                label: Some(label),
                size,
                usage,
                memory,
            }) {
                Ok(buffer) => created.push(buffer),
                Err(error) => {
                    for buffer in created {
                        device.destroy_buffer(buffer);
                    }
                    card_image.destroy(device);
                    cover_image.destroy(device);
                    ground_image.destroy(device);
                    return Err(error.into());
                }
            }
        }
        let resident = Self {
            instances: created[0],
            args: created[1],
            blades: created[2],
            tiles: created[3],
            cells: created[4],
            field_block: created[5],
            ground: ground_image,
            cover: cover_image,
            card: card_image,
            slots,
            shells: field.draws_shells(),
            fins: field.shells().fins,
            mesh_blades: field.draws_blades(),
            generation: gen_params_of(field),
        };
        if let Err(error) = resident.write_static(device, field) {
            resident.destroy(device);
            return Err(error.into());
        }
        Ok(resident)
    }

    /// The three blocks a field fixes for its whole life: the blade table, one
    /// row per tile and the field block.
    ///
    /// **Written once here rather than per frame**, and that is what makes a
    /// field replacement safe without a ring: nothing rewrites a buffer a
    /// submitted frame is reading, because a new field is new buffers and the
    /// old ones are retired whole.
    fn write_static(&self, device: &dyn Device, field: &GrassField) -> Result<(), HalError> {
        let blades: Vec<u8> = field
            .blades()
            .iter()
            .flat_map(|blade| blade.row().to_bytes())
            .collect();
        device.write_buffer(self.blades, 0, &blades)?;

        let mut tiles = vec![0u8; self.slots as usize * TILE_STRIDE as usize];
        for slot in 0..self.slots {
            let [x, z] = field.tile_origin(slot);
            let block = Tile {
                tile: [x, z, field.tile_size(), 0.0],
                slot: [slot, slot % field.tiles()[0], slot / field.tiles()[0], 0],
            };
            let at = slot as usize * TILE_STRIDE as usize;
            tiles[at..at + TILE_SIZE].copy_from_slice(&block.to_bytes());
        }
        device.write_buffer(self.tiles, 0, &tiles)?;
        device.write_buffer(
            self.field_block,
            0,
            &shell::field_block_of(field).to_bytes(),
        )
    }

    fn destroy(&self, device: &dyn Device) {
        for buffer in [
            self.instances,
            self.cells,
            self.args,
            self.blades,
            self.tiles,
            self.field_block,
        ] {
            device.destroy_buffer(buffer);
        }
        self.card.destroy(device);
        self.cover.destroy(device);
        self.ground.destroy(device);
    }
}

impl Wind {
    fn calm(device: &dyn Device, queue: crcbl_hal::QueueHandle) -> Result<Self, HalError> {
        let one = |label, texel: [u8; 4]| {
            upload_texture(device, queue, label, Format::Rgba8Unorm, 1, 1, &texel)
        };
        let direction = one("wind direction", CALM_DIRECTION)?;
        match one("wind intensity", CALM_INTENSITY) {
            Ok(intensity) => Ok(Self {
                direction,
                intensity,
            }),
            Err(error) => {
                direction.destroy(device);
                Err(error)
            }
        }
    }

    fn upload(
        device: &dyn Device,
        queue: crcbl_hal::QueueHandle,
        layers: &WindLayers,
    ) -> Result<Self, WindLayerError> {
        layers.direction.check()?;
        layers.intensity.check()?;
        let one = |label, layer: &WindLayer| {
            upload_texture(
                device,
                queue,
                label,
                Format::Rgba8Unorm,
                layer.texels[0],
                layer.texels[1],
                &layer.rgba8,
            )
        };
        let direction = one("wind direction", &layers.direction)?;
        match one("wind intensity", &layers.intensity) {
            Ok(intensity) => Ok(Self {
                direction,
                intensity,
            }),
            Err(error) => {
                direction.destroy(device);
                Err(error.into())
            }
        }
    }

    fn destroy(&self, device: &dyn Device) {
        self.intensity.destroy(device);
        self.direction.destroy(device);
    }
}

/// Bytes between two tile blocks in the ring.
///
/// A dynamic uniform offset must be a multiple of
/// [`Limits::min_uniform_buffer_offset_alignment`](crcbl_hal::Limits::min_uniform_buffer_offset_alignment),
/// which every backend in this tree and WebGPU's own guarantee put at 256, so
/// the block's own [`TILE_SIZE`] bytes are padded up to it. Spelled here rather
/// than read off the device because the buffer is written once, before any view
/// exists, and a stride that varied by adapter would make a field's bytes a
/// property of the machine that uploaded them.
const TILE_STRIDE: u32 = 256;

/// The static half of a field's generation block — everything but the camera,
/// which is the view's.
fn gen_params_of(field: &GrassField) -> GenParams {
    let ground = field.ground();
    let cover = field.cover();
    GenParams {
        camera: [0.0, 0.0, 0.0, field.reach()],
        ground: [
            ground.origin[0],
            ground.origin[1],
            ground.metres_per_texel,
            1.0 / ground.metres_per_texel,
        ],
        cover: [
            cover.origin[0],
            cover.origin[1],
            cover.metres_per_texel,
            1.0 / cover.metres_per_texel,
        ],
        maps: [
            ground.texels[0],
            ground.texels[1],
            cover.texels[0],
            cover.texels[1],
        ],
        limits: [
            SLOT_CAPACITY,
            field.blades().len() as u32,
            CELLS_PER_TILE,
            field.slots(),
        ],
        looks: [field.shells().count, u32::from(field.shells().fins), 0, 0],
        lod: [field.blade_lod().distance, 0.0, 0.0, 0.0],
    }
}

/// The bindings of `grass_gen.slang`, in its declaration order.
mod gen_binding {
    pub(super) const WIND: u32 = 0;
    pub(super) const WIND_DIRECTION: u32 = 1;
    pub(super) const WIND_INTENSITY: u32 = 2;
    pub(super) const WIND_SAMPLER: u32 = 3;
    pub(super) const PARAMS: u32 = 4;
    pub(super) const TILE: u32 = 5;
    pub(super) const BLADES: u32 = 6;
    pub(super) const GROUND: u32 = 7;
    pub(super) const COVER: u32 = 8;
    pub(super) const INSTANCES: u32 = 9;
    pub(super) const ARGS: u32 = 10;
    pub(super) const CELLS: u32 = 11;
}

/// The bindings of `grass.slang`, in its declaration order.
mod binding {
    pub(super) const FRAME: u32 = 0;
    pub(super) const PARAMS: u32 = 1;
    pub(super) const TILE: u32 = 2;
    pub(super) const INSTANCES: u32 = 3;
    pub(super) const BLADES: u32 = 4;
    pub(super) const CARD: u32 = 5;
    pub(super) const CARD_SAMPLER: u32 = 6;
    pub(super) const SHADOW_ATLAS: u32 = 7;
    pub(super) const SHADOW_SAMPLER: u32 = 8;
    pub(super) const LIGHTS: u32 = 9;
    pub(super) const CLUSTER_LIGHTS: u32 = 10;
    pub(super) const FIELD: u32 = 11;
    pub(super) const CELLS: u32 = 12;
    pub(super) const GROUND: u32 = 13;
    pub(super) const WIND: u32 = 14;
    pub(super) const WIND_DIRECTION: u32 = 15;
    pub(super) const WIND_INTENSITY: u32 = 16;
    pub(super) const WIND_SAMPLER: u32 = 17;
}

/// The graph transients the grass pass reads and writes.
#[derive(Clone, Copy, Debug)]
pub(crate) struct GrassImages {
    /// The HDR frame the opaque pass left: drawn into, in place.
    pub(crate) color: ImageId,
    /// The scene depth: tested and written.
    pub(crate) depth: ImageId,
    /// The shadow atlas the frame's shadow pass drew.
    pub(crate) shadow_atlas: ImageId,
}

/// Everything else the three passes read, as handles other passes own.
#[derive(Clone, Copy, Debug)]
pub(crate) struct GrassInputs {
    /// This view's `FrameUniforms` slot — the forward pass's block.
    pub(crate) frame_block: BufferHandle,
    /// This frame's light rows and froxel lists, as the forward pass binds them.
    pub(crate) lights: BufferHandle,
    pub(crate) cluster_lights: BufferHandle,
    /// The froxel grid as the graph knows it, so the read is declared against
    /// the pass that wrote it.
    pub(crate) light_grid: BufferId,
    /// What the scene's field holds this frame.
    pub(crate) field: GrassFrame,
}

/// What the two generation dispatches bind, and the cache each keeps.
///
/// `Copy`, so both `execute` bodies take one of their own — the resources are
/// handles and the closures are the only readers.
#[derive(Clone, Copy)]
struct GenGroup {
    layout: BindGroupLayoutHandle,
    field: GrassFrame,
    gen_params: BufferHandle,
    wind_params: BufferHandle,
    wind_sampler: SamplerHandle,
}

impl GenGroup {
    /// The group, built or taken from `cached`.
    fn build(
        self,
        device: &dyn Device,
        named: &mut Option<Vec<BufferHandle>>,
        cached: &mut Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
    ) -> Option<BindGroupHandle> {
        let field = self.field;
        // A replaced field is new buffers, and a group naming the old ones is
        // stale whatever its views say.
        let now = vec![
            field.instances,
            field.cells,
            field.args,
            field.blades,
            field.tiles,
        ];
        if named.as_ref() != Some(&now) {
            if let Some((_, stale)) = cached.take() {
                device.destroy_bind_group(stale);
            }
            *named = Some(now);
        }
        let buffer = |binding, buffer| BindGroupEntry {
            binding,
            array_index: 0,
            resource: BindingResource::whole_buffer(buffer),
        };
        let view = |binding, view| BindGroupEntry {
            binding,
            array_index: 0,
            resource: BindingResource::ImageView(view),
        };
        let entries = [
            buffer(gen_binding::WIND, self.wind_params),
            view(gen_binding::WIND_DIRECTION, field.wind_direction),
            view(gen_binding::WIND_INTENSITY, field.wind_intensity),
            BindGroupEntry {
                binding: gen_binding::WIND_SAMPLER,
                array_index: 0,
                resource: BindingResource::Sampler(self.wind_sampler),
            },
            buffer(gen_binding::PARAMS, self.gen_params),
            // **The bound range is one block, not the buffer**: a dynamic
            // offset is added to it, so a whole-buffer binding would let the
            // last tile's offset run past the end.
            BindGroupEntry {
                binding: gen_binding::TILE,
                array_index: 0,
                resource: BindingResource::Buffer {
                    buffer: field.tiles,
                    offset: 0,
                    size: TILE_SIZE as u64,
                },
            },
            buffer(gen_binding::BLADES, field.blades),
            view(gen_binding::GROUND, field.ground),
            view(gen_binding::COVER, field.cover),
            buffer(gen_binding::INSTANCES, field.instances),
            buffer(gen_binding::ARGS, field.args),
            buffer(gen_binding::CELLS, field.cells),
        ];
        cached_group(
            cached,
            device,
            &[
                (gen_binding::WIND_DIRECTION, field.wind_direction),
                (gen_binding::WIND_INTENSITY, field.wind_intensity),
                (gen_binding::GROUND, field.ground),
                (gen_binding::COVER, field.cover),
            ],
            "grass generate",
            self.layout,
            &entries,
        )
    }
}

/// A group, cached against the views it names and the buffers a replaced field
/// moves.
type RasterCache = (
    Option<Vec<BufferHandle>>,
    Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
);

/// Everything one camera's grass passes own.
#[derive(Debug)]
pub(crate) struct Grass {
    gen_layout: BindGroupLayoutHandle,
    gen_pipeline_layout: PipelineLayoutHandle,
    clear_pipeline: ComputePipelineHandle,
    generate_pipeline: ComputePipelineHandle,
    raster_layout: BindGroupLayoutHandle,
    raster_pipeline_layout: PipelineLayoutHandle,
    /// The cards, then the shells and the fins, then the near and far mesh
    /// blades — one pipeline each over one layout.
    raster_pipeline: GraphicsPipelineHandle,
    shell_pipeline: GraphicsPipelineHandle,
    fin_pipeline: GraphicsPipelineHandle,
    blade_near_pipeline: GraphicsPipelineHandle,
    blade_far_pipeline: GraphicsPipelineHandle,
    /// `[frame]`: `grass_gen.slang`'s own block.
    gen_params: Vec<BufferHandle>,
    /// `[frame]`: the wind's block, `crcbl_shaders::wind::WindParams`.
    wind_params: Vec<BufferHandle>,
    /// `[frame]`: `grass.slang`'s own block. A ring rather than one buffer
    /// beside the field, because its screen scale is **this view's** and a
    /// second view of the same field draws at another extent.
    raster_params: Vec<BufferHandle>,
    /// `[frame]`: the clearing dispatch's group — see [`Grass::add_passes`] for
    /// why there are two of one set.
    clear_groups: Vec<RasterCache>,
    /// `[frame]`: the generation dispatch's group.
    gen_groups: Vec<RasterCache>,
    /// `[frame]`: the raster group — see [`RasterCache`].
    raster_groups: Vec<RasterCache>,
    card_sampler: SamplerHandle,
    wind_sampler: SamplerHandle,
    shadow_sampler: SamplerHandle,
}

impl Grass {
    /// Passes [`Grass::add_passes`] adds to a frame that has a field.
    pub(crate) const PASSES: u32 = 3;

    /// Builds the seven pipelines — two dispatches and a card, a shell, a fin
    /// and two mesh blade draws — the two samplers and the three uniform rings.
    ///
    /// `service` runs before each pipeline: on a cold driver cache these seven
    /// are the longest run of compilations in a renderer's build — see
    /// [`ForwardRenderer::with_scene_serviced`](crate::forward::ForwardRenderer::with_scene_serviced).
    ///
    /// # Errors
    ///
    /// [`HalError`] from any seam call. **Nothing is released on the failing
    /// path**, for the reason every other builder in this crate gives: the
    /// caller holds a rollback, and this is stored in it whole.
    pub(crate) fn new(
        device: &dyn Device,
        frames: usize,
        shadow_sampler: SamplerHandle,
        service: &mut dyn FnMut(),
    ) -> Result<Self, HalError> {
        let compute = ShaderStages::COMPUTE;
        let gen_entries = [
            uniform(gen_binding::WIND, compute, false),
            sampled(gen_binding::WIND_DIRECTION, compute, SampleType::Float),
            sampled(gen_binding::WIND_INTENSITY, compute, SampleType::Float),
            sampler(gen_binding::WIND_SAMPLER, compute),
            uniform(gen_binding::PARAMS, compute, false),
            uniform(gen_binding::TILE, compute, true),
            storage(gen_binding::BLADES, compute, true, BLADE_STRIDE as u32),
            // `UnfilterableFloat`, which is what a WebGPU device reports for
            // `R32Float`: the field is read with `Load` and never sampled, so
            // there is no filter to want here — see `crate::grass::field`.
            BindGroupLayoutEntry {
                binding: gen_binding::GROUND,
                visibility: compute,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    sample_type: SampleType::UnfilterableFloat,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            sampled(gen_binding::COVER, compute, SampleType::Float),
            storage(
                gen_binding::INSTANCES,
                compute,
                false,
                INSTANCE_STRIDE as u32,
            ),
            storage(gen_binding::ARGS, compute, false, 4),
            storage(gen_binding::CELLS, compute, false, INSTANCE_STRIDE as u32),
        ];
        let gen_desc = BindGroupLayoutDesc {
            label: Some("grass generate"),
            entries: &gen_entries,
        };
        check_portable_storage_buffers(Some("grass generate"), &[&gen_desc])?;
        let gen_layout = device.create_bind_group_layout(&gen_desc)?;
        let gen_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("grass generate"),
            bind_group_layouts: &[gen_layout],
            push_constants: None,
        })?;
        service();
        let clear_pipeline = compute_pipeline_entry(
            device,
            "grass clear",
            &GRASS_GEN,
            "clearMain",
            gen_pipeline_layout,
            WORKGROUP_SIZE,
        )?;
        service();
        let generate_pipeline = compute_pipeline_entry(
            device,
            "grass generate",
            &GRASS_GEN,
            "generateMain",
            gen_pipeline_layout,
            WORKGROUP_SIZE,
        )?;

        // **Every binding is visible to both stages**, on `crate::water`'s
        // terms: Slang's Metal backend materialises every global into every
        // entry point, and Metal's draw validation refuses a fragment function
        // missing a vertex-only buffer. The four storage buffers this puts in
        // the vertex stage stay inside the browser's limit, which
        // `check_portable_storage_buffers` below holds it to.
        let both = ShaderStages::VERTEX.union(ShaderStages::FRAGMENT);
        let raster_entries = [
            uniform(binding::FRAME, both, false),
            uniform(binding::PARAMS, both, false),
            uniform(binding::TILE, both, true),
            storage(binding::INSTANCES, both, true, INSTANCE_STRIDE as u32),
            storage(binding::BLADES, both, true, BLADE_STRIDE as u32),
            BindGroupLayoutEntry {
                binding: binding::CARD,
                visibility: both,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2Array,
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            sampler(binding::CARD_SAMPLER, both),
            sampled(binding::SHADOW_ATLAS, both, SampleType::Depth),
            BindGroupLayoutEntry {
                binding: binding::SHADOW_SAMPLER,
                visibility: both,
                kind: BindingKind::Sampler { comparison: true },
                count: 1,
                flags: BindingFlags::empty(),
            },
            storage(
                binding::LIGHTS,
                both,
                true,
                crcbl_shaders::light::LIGHT_STRIDE as u32,
            ),
            storage(binding::CLUSTER_LIGHTS, both, true, 4),
            uniform(binding::FIELD, both, false),
            storage(binding::CELLS, both, true, INSTANCE_STRIDE as u32),
            // `UnfilterableFloat` and read with `Load`, on the generation
            // layout's terms for the same image.
            BindGroupLayoutEntry {
                binding: binding::GROUND,
                visibility: both,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    sample_type: SampleType::UnfilterableFloat,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            uniform(binding::WIND, both, false),
            sampled(binding::WIND_DIRECTION, both, SampleType::Float),
            sampled(binding::WIND_INTENSITY, both, SampleType::Float),
            sampler(binding::WIND_SAMPLER, both),
        ];
        let raster_desc = BindGroupLayoutDesc {
            label: Some("grass"),
            entries: &raster_entries,
        };
        check_portable_storage_buffers(Some("grass"), &[&raster_desc])?;
        let raster_layout = device.create_bind_group_layout(&raster_desc)?;
        let raster_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("grass"),
            bind_group_layouts: &[raster_layout],
            push_constants: None,
        })?;
        let list = PrimitiveTopology::TriangleList;
        service();
        let raster_pipeline = build_raster(
            device,
            raster_pipeline_layout,
            ("vertexMain", "fragmentMain"),
            list,
        )?;
        service();
        let shell_pipeline = build_raster(
            device,
            raster_pipeline_layout,
            ("shellVertexMain", "shellFragmentMain"),
            list,
        )?;
        service();
        let fin_pipeline = build_raster(
            device,
            raster_pipeline_layout,
            ("finVertexMain", "shellFragmentMain"),
            list,
        )?;
        // **Strips**: a blade is a pair of vertices at each height and one at
        // the tip, which is decision 3's fifteen and seven only as a strip.
        let strip = PrimitiveTopology::TriangleStrip;
        service();
        let blade_near_pipeline = build_raster(
            device,
            raster_pipeline_layout,
            ("bladeNearVertexMain", "bladeFragmentMain"),
            strip,
        )?;
        service();
        let blade_far_pipeline = build_raster(
            device,
            raster_pipeline_layout,
            ("bladeFarVertexMain", "bladeFragmentMain"),
            strip,
        )?;

        let card_sampler = device.create_sampler(&SamplerDesc {
            label: Some("grass card"),
            // **Linear within a level, and the level is the shader's.**
            // `grass.slang`'s `grassCardLevel` picks a whole level per instance
            // and reads it with `SampleLevel`, so the mip filter below never
            // blends two of them — it is `Linear` because a level between two
            // whole ones would be read exactly if the shader ever asked for
            // one, and `Nearest` would then silently round it a second time.
            min_filter: FilterMode::Linear,
            mag_filter: FilterMode::Linear,
            mip_filter: FilterMode::Linear,
            address_mode: [SamplerAddressMode::ClampToEdge; 3],
            ..SamplerDesc::default()
        })?;
        let wind_sampler = match device.create_sampler(&SamplerDesc {
            label: Some("wind layers"),
            min_filter: FilterMode::Linear,
            mag_filter: FilterMode::Linear,
            // The layers have no chain; `wind.slang` reads level zero.
            mip_filter: FilterMode::Nearest,
            // `repeat` on every axis — the addressing `crcbl_wind`'s wrapped
            // texel indices are the statement of.
            address_mode: [SamplerAddressMode::Repeat; 3],
            ..SamplerDesc::default()
        }) {
            Ok(sampler) => sampler,
            Err(error) => {
                device.destroy_sampler(card_sampler);
                return Err(error);
            }
        };

        let mut gen_params = Vec::with_capacity(frames);
        let mut wind_params = Vec::with_capacity(frames);
        let mut raster_params = Vec::with_capacity(frames);
        for _ in 0..frames {
            raster_params.push(device.create_buffer(&BufferDesc {
                label: Some("grass params"),
                size: PARAMS_SIZE as u64,
                usage: BufferUsage::UNIFORM,
                memory: MemoryLocation::HostUpload,
            })?);
            gen_params.push(device.create_buffer(&BufferDesc {
                label: Some("grass generate params"),
                size: GEN_PARAMS_SIZE as u64,
                usage: BufferUsage::UNIFORM,
                memory: MemoryLocation::HostUpload,
            })?);
            wind_params.push(device.create_buffer(&BufferDesc {
                label: Some("grass wind params"),
                size: WIND_PARAMS_SIZE as u64,
                usage: BufferUsage::UNIFORM,
                memory: MemoryLocation::HostUpload,
            })?);
        }

        Ok(Self {
            gen_layout,
            gen_pipeline_layout,
            clear_pipeline,
            generate_pipeline,
            raster_layout,
            raster_pipeline_layout,
            raster_pipeline,
            shell_pipeline,
            fin_pipeline,
            blade_near_pipeline,
            blade_far_pipeline,
            gen_params,
            wind_params,
            raster_params,
            clear_groups: (0..frames).map(|_| (None, None)).collect(),
            gen_groups: (0..frames).map(|_| (None, None)).collect(),
            raster_groups: (0..frames).map(|_| (None, None)).collect(),
            card_sampler,
            wind_sampler,
            shadow_sampler,
        })
    }

    /// Writes `frame`'s three blocks.
    ///
    /// Written whether or not the frame has a field, on every other per-frame
    /// block in this crate's terms: a block written only on the frames that draw
    /// one is stale on the frame a caller first sets a field.
    ///
    /// # Errors
    ///
    /// [`HalError`] from a mapped write.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn begin_frame(
        &self,
        device: &dyn Device,
        frame: usize,
        generation: GenParams,
        wind: WindParams,
        raster: Params,
    ) -> Result<(), HalError> {
        device.write_buffer(self.gen_params[frame], 0, &generation.to_bytes())?;
        device.write_buffer(self.raster_params[frame], 0, &raster.to_bytes())?;
        device.write_buffer(self.wind_params[frame], 0, &wind.to_bytes())
    }

    /// Adds `grass-clear`, `grass-generate` and `grass`, in that order.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn add_passes<'a>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        frame: usize,
        images: GrassImages,
        inputs: GrassInputs,
    ) {
        let GrassImages {
            color,
            depth,
            shadow_atlas,
        } = images;
        let GrassInputs {
            frame_block,
            lights,
            cluster_lights,
            light_grid,
            field,
        } = inputs;

        let mut imported = |label: &str, buffer| {
            graph.import_buffer(
                label,
                ImportedBuffer {
                    buffer,
                    initial: ResourceState::ShaderReadWrite,
                    final_state: ResourceState::ShaderReadWrite,
                },
            )
        };
        let instances_id = imported("grass-instances", field.instances);
        let args_id = imported("grass-draw-args", field.args);

        let slots = field.slots;
        let gen_layout = self.gen_layout;
        let gen_pipeline_layout = self.gen_pipeline_layout;
        let clear_pipeline = self.clear_pipeline;
        let generate_pipeline = self.generate_pipeline;
        let gen_params = self.gen_params[frame];
        let wind_params = self.wind_params[frame];
        let wind_sampler = self.wind_sampler;
        let group_of = GenGroup {
            layout: gen_layout,
            field,
            gen_params,
            wind_params,
            wind_sampler,
        };
        // **One cache per pass, and they build the same descriptor set.** The
        // two dispatches bind one layout over one set of resources and differ in
        // a pipeline and a dynamic offset; they hold a cache each because two
        // `execute` bodies cannot share one mutable borrow, and the price of
        // that is one descriptor set per frame slot.
        let (clear_named, clear_cached) = &mut self.clear_groups[frame];
        graph
            .add_compute_pass("grass-clear")
            .use_buffer(args_id, ResourceState::ShaderReadWrite)
            .execute(move |ctx| {
                let device = ctx.device();
                let Some(group) = group_of.build(device, clear_named, clear_cached) else {
                    return;
                };
                let encoder = ctx.encoder();
                encoder.bind_compute_pipeline(clear_pipeline);
                encoder.bind_group(0, group, &[0], gen_pipeline_layout);
                encoder.dispatch(slots.div_ceil(WORKGROUP_SIZE), 1, 1);
            });

        let (gen_named, gen_cached) = &mut self.gen_groups[frame];
        graph
            .add_compute_pass("grass-generate")
            .use_buffer(args_id, ResourceState::ShaderReadWrite)
            .use_buffer(instances_id, ResourceState::ShaderReadWrite)
            .execute(move |ctx| {
                let device = ctx.device();
                let Some(group) = group_of.build(device, gen_named, gen_cached) else {
                    return;
                };
                let encoder = ctx.encoder();
                encoder.bind_compute_pipeline(generate_pipeline);
                // One dispatch per tile — decision 1's cost, and the dynamic
                // offset is what tells the shader which tile it is.
                for slot in 0..slots {
                    encoder.bind_group(0, group, &[slot * TILE_STRIDE], gen_pipeline_layout);
                    encoder.dispatch(
                        (CELLS_PER_TILE * CELLS_PER_TILE).div_ceil(WORKGROUP_SIZE),
                        1,
                        1,
                    );
                }
            });

        let raster_pipeline = self.raster_pipeline;
        let shell_pipeline = self.shell_pipeline;
        let fin_pipeline = self.fin_pipeline;
        let blade_near_pipeline = self.blade_near_pipeline;
        let blade_far_pipeline = self.blade_far_pipeline;
        let raster_pipeline_layout = self.raster_pipeline_layout;
        let raster_layout = self.raster_layout;
        let card_sampler = self.card_sampler;
        let shadow_sampler = self.shadow_sampler;
        let raster_params = self.raster_params[frame];
        let (raster_named, raster_cached) = &mut self.raster_groups[frame];
        graph
            .add_render_pass("grass")
            // **Loaded**, like the water surface's attachment: the cards cover
            // some pixels and every other one has to stay what the frame drew.
            .color(color, LoadOp::Load, StoreOp::Store, ClearValue::default())
            // Loaded and stored **with writes on**: a card is opaque where its
            // cutout keeps it, so it stands in the depth buffer for the
            // background, the pyramid and the march that follow.
            .depth(depth, LoadOp::Load, StoreOp::Store, ClearValue::default())
            .read_image(shadow_atlas)
            .read_buffer(instances_id)
            .read_buffer(light_grid)
            .use_buffer(args_id, ResourceState::IndirectArgument)
            .execute(move |ctx| {
                let atlas_view = ctx.image_view(shadow_atlas);
                let device = ctx.device();
                let now = vec![
                    field.instances,
                    field.cells,
                    field.blades,
                    field.tiles,
                    field.field_block,
                    lights,
                ];
                if raster_named.as_ref() != Some(&now) {
                    if let Some((_, stale)) = raster_cached.take() {
                        device.destroy_bind_group(stale);
                    }
                    *raster_named = Some(now);
                }
                let buffer = |binding, buffer| BindGroupEntry {
                    binding,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(buffer),
                };
                let entries = [
                    buffer(binding::FRAME, frame_block),
                    buffer(binding::PARAMS, raster_params),
                    BindGroupEntry {
                        binding: binding::TILE,
                        array_index: 0,
                        resource: BindingResource::Buffer {
                            buffer: field.tiles,
                            offset: 0,
                            size: TILE_SIZE as u64,
                        },
                    },
                    buffer(binding::INSTANCES, field.instances),
                    buffer(binding::BLADES, field.blades),
                    BindGroupEntry {
                        binding: binding::CARD,
                        array_index: 0,
                        resource: BindingResource::ImageView(field.card),
                    },
                    BindGroupEntry {
                        binding: binding::CARD_SAMPLER,
                        array_index: 0,
                        resource: BindingResource::Sampler(card_sampler),
                    },
                    BindGroupEntry {
                        binding: binding::SHADOW_ATLAS,
                        array_index: 0,
                        resource: BindingResource::ImageView(atlas_view),
                    },
                    BindGroupEntry {
                        binding: binding::SHADOW_SAMPLER,
                        array_index: 0,
                        resource: BindingResource::Sampler(shadow_sampler),
                    },
                    buffer(binding::LIGHTS, lights),
                    buffer(binding::CLUSTER_LIGHTS, cluster_lights),
                    buffer(binding::FIELD, field.field_block),
                    buffer(binding::CELLS, field.cells),
                    BindGroupEntry {
                        binding: binding::GROUND,
                        array_index: 0,
                        resource: BindingResource::ImageView(field.ground),
                    },
                    buffer(binding::WIND, wind_params),
                    BindGroupEntry {
                        binding: binding::WIND_DIRECTION,
                        array_index: 0,
                        resource: BindingResource::ImageView(field.wind_direction),
                    },
                    BindGroupEntry {
                        binding: binding::WIND_INTENSITY,
                        array_index: 0,
                        resource: BindingResource::ImageView(field.wind_intensity),
                    },
                    BindGroupEntry {
                        binding: binding::WIND_SAMPLER,
                        array_index: 0,
                        resource: BindingResource::Sampler(wind_sampler),
                    },
                ];
                let Some(group) = cached_group(
                    raster_cached,
                    device,
                    &[
                        (binding::CARD, field.card),
                        (binding::SHADOW_ATLAS, atlas_view),
                        (binding::GROUND, field.ground),
                        (binding::WIND_DIRECTION, field.wind_direction),
                        (binding::WIND_INTENSITY, field.wind_intensity),
                    ],
                    "grass",
                    raster_layout,
                    &entries,
                ) else {
                    return;
                };
                let encoder = ctx.encoder();
                // One draw per slot and look, each reading the instance count its
                // own dispatch left — decision 1's fixed indirect slots, and an
                // empty one draws nothing because its count is the zero the
                // clear left. The shells, the fins and the blades are recorded
                // only for a field that draws them, so a card field's stream is
                // rung G1's.
                let looks = [
                    Some((raster_pipeline, CARD_DRAW)),
                    field.shells.then_some((shell_pipeline, SHELL_DRAW)),
                    (field.shells && field.fins).then_some((fin_pipeline, FIN_DRAW)),
                    field
                        .mesh_blades
                        .then_some((blade_near_pipeline, BLADE_NEAR_DRAW)),
                    field
                        .mesh_blades
                        .then_some((blade_far_pipeline, BLADE_FAR_DRAW)),
                ];
                for (pipeline, draw) in looks.into_iter().flatten() {
                    encoder.bind_graphics_pipeline(pipeline);
                    for slot in 0..slots {
                        encoder.bind_group(0, group, &[slot * TILE_STRIDE], raster_pipeline_layout);
                        encoder.draw_indirect(&DrawIndirect {
                            args: field.args,
                            offset: u64::from(slot) * SLOT_ARGS_SIZE as u64
                                + u64::from(draw) * DRAW_ARGS_SIZE as u64,
                            draw_count: 1,
                            stride: DRAW_ARGS_SIZE as u32,
                        });
                    }
                }
            });
    }

    /// Releases everything, in dependency order. The device must be idle.
    pub(crate) fn destroy(self, device: &dyn Device) {
        for (_, group) in self
            .clear_groups
            .into_iter()
            .filter_map(|(_, cached)| cached)
            .chain(self.gen_groups.into_iter().filter_map(|(_, cached)| cached))
            .chain(
                self.raster_groups
                    .into_iter()
                    .filter_map(|(_, cached)| cached),
            )
        {
            device.destroy_bind_group(group);
        }
        device.destroy_graphics_pipeline(self.blade_far_pipeline);
        device.destroy_graphics_pipeline(self.blade_near_pipeline);
        device.destroy_graphics_pipeline(self.fin_pipeline);
        device.destroy_graphics_pipeline(self.shell_pipeline);
        device.destroy_graphics_pipeline(self.raster_pipeline);
        device.destroy_pipeline_layout(self.raster_pipeline_layout);
        device.destroy_bind_group_layout(self.raster_layout);
        device.destroy_compute_pipeline(self.generate_pipeline);
        device.destroy_compute_pipeline(self.clear_pipeline);
        device.destroy_pipeline_layout(self.gen_pipeline_layout);
        device.destroy_bind_group_layout(self.gen_layout);
        device.destroy_sampler(self.wind_sampler);
        device.destroy_sampler(self.card_sampler);
        for buffer in self
            .gen_params
            .into_iter()
            .chain(self.wind_params)
            .chain(self.raster_params)
        {
            device.destroy_buffer(buffer);
        }
    }
}

/// One of the grass pass's pipelines — cards, shells, fins or a level of mesh
/// blades, by the vertex and fragment entry points named and assembled as
/// `topology`: no vertex stream, depth-tested and written under reversed-Z, one
/// opaque `Rgba16Float` target.
fn build_raster(
    device: &dyn Device,
    layout: PipelineLayoutHandle,
    (vertex, fragment): (&'static str, &'static str),
    topology: PrimitiveTopology,
) -> Result<GraphicsPipelineHandle, HalError> {
    // Resolved before the module exists, on `crate::water`'s terms, and by name:
    // `grass.slang` has more than one entry point per stage.
    let vertex = crate::forward::named_entry(&GRASS, vertex, Stage::Vertex)?;
    let fragment = crate::forward::named_entry(&GRASS, fragment, Stage::Fragment)?;
    let module = device.create_shader_module(&ShaderModuleDesc {
        label: Some(GRASS.source()),
        spirv: GRASS.spirv(),
        wgsl: GRASS.wgsl(),
        msl: GRASS.msl(),
        dxil: &GRASS.dxil_containers(),
    })?;
    let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
        label: Some(vertex),
        layout,
        vertex: ShaderEntry {
            module,
            entry_point: vertex,
        },
        fragment: Some(ShaderEntry {
            module,
            entry_point: fragment,
        }),
        // **Nothing is culled**, and it is `crcbl_hal::CullMode`'s default
        // rather than a choice spelled here: a card is a flat quad seen from
        // both sides, and half a crossed pair faces away from any camera. A
        // shell is seen from below where the ground dips, and a fin and a mesh
        // blade from either side, so none of them has a back face either.
        primitive: crcbl_hal::PrimitiveState {
            topology,
            ..crcbl_hal::PrimitiveState::default()
        },
        depth_stencil: Some(DepthStencilState {
            format: crate::forward::SCENE_DEPTH_FORMAT,
            depth_write: true,
            depth_compare: CompareOp::Greater,
            stencil: None,
            bias: DepthBias::default(),
        }),
        multisample: MultisampleState::default(),
        color_targets: &[ColorTargetState::opaque(Format::Rgba16Float)],
    });
    device.destroy_shader_module(module);
    pipeline
}

/// A uniform-buffer layout entry.
const fn uniform(binding: u32, visibility: ShaderStages, dynamic: bool) -> BindGroupLayoutEntry {
    BindGroupLayoutEntry {
        binding,
        visibility,
        kind: BindingKind::UniformBuffer { dynamic },
        count: 1,
        flags: BindingFlags::empty(),
    }
}

/// A storage-buffer layout entry of `stride` bytes a row.
const fn storage(
    binding: u32,
    visibility: ShaderStages,
    read_only: bool,
    stride: u32,
) -> BindGroupLayoutEntry {
    BindGroupLayoutEntry {
        binding,
        visibility,
        kind: BindingKind::StorageBuffer {
            read_only,
            dynamic: false,
            stride,
        },
        count: 1,
        flags: BindingFlags::empty(),
    }
}

/// A 2D sampled-image layout entry.
const fn sampled(
    binding: u32,
    visibility: ShaderStages,
    sample_type: SampleType,
) -> BindGroupLayoutEntry {
    BindGroupLayoutEntry {
        binding,
        visibility,
        kind: BindingKind::SampledImage {
            view_type: ImageViewType::D2,
            sample_type,
        },
        count: 1,
        flags: BindingFlags::empty(),
    }
}

/// A filtering-sampler layout entry.
const fn sampler(binding: u32, visibility: ShaderStages) -> BindGroupLayoutEntry {
    BindGroupLayoutEntry {
        binding,
        visibility,
        kind: BindingKind::Sampler { comparison: false },
        count: 1,
        flags: BindingFlags::empty(),
    }
}

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