Skip to main content

crcbl_render/grass/
field.rs

1//! What a patch of grass *is*, as data — `docs/plan/57-grass.md`'s decision 2:
2//! "A field is a description: bounds, a ground heightfield (texture plus CPU
3//! copy), a density map and a type map, and a table of blade types."
4//!
5//! ```text
6//!  origin ─┬─────────── tiles[0] · tile_size ───────────┐
7//!          │ tile 0 │ tile 1 │ tile 2 │ tile 3 │  …     │   +X
8//!          ├────────┼────────┼────────┼────────┤        │
9//!          │ tile 4 │ tile 5 │ …                        │
10//!          ⋮                                            ⋮   +Z
11//! ```
12//!
13//! Every tile is [`CELLS_PER_TILE`] cells on a side and every cell may carry one
14//! blade, so a tile's slot holds [`SLOT_CAPACITY`] instances and no more — which
15//! is what lets the generation pass append without a bound check.
16//!
17//! # Two maps, one texel each
18//!
19//! The plan names a density map and a type map. They are **one** map here, two
20//! channels of it: a cell reads one texel and gets both numbers, where two maps
21//! would be two fetches of two textures whose extents would then have to be
22//! argued about. [`CoverMap`] is that map, and `cover` is what this crate calls
23//! it so neither half's name claims the whole.
24//!
25//! # No texture is named by a field
26//!
27//! The card every blade is drawn with is the engine's, authored in arithmetic by
28//! [`super::card`], and a shell's strand is arithmetic in the shader. A field
29//! that named an image would need an asset seam, a page and a cook of its own;
30//! `docs/backlog.md` carries the authored page.
31//!
32//! # A look and a style are a blade row's, the shell stack is the field's
33//!
34//! Decision 3's three looks are one blade description drawn three ways, so
35//! [`BladeType::look`] is a field of the row and switching it changes nothing
36//! else — not which cells carry a blade, not their size, not the wind they lean
37//! in. Decision 4's levers are [`BladeType::style`] for the same reason: "each
38//! is a field of the blade type, so any of the three looks can be stylised".
39//!
40//! [`Shells`] is the field's rather than a row's, because every shell row of a
41//! field stands in one stack: its count is what the shells' overdraw is
42//! proportional to, and a stack cannot be sixteen layers under one row and
43//! thirty-two under the next. [`BladeLod`] is the field's for the same reason:
44//! where the mesh blades change level is a distance from one camera, and two
45//! rows switching at two distances would pop at both.
46//!
47//! [`BladeType::clumping`] is a row's and is **placement**, not look: decision
48//! 2's clumps move a blade's facing and height, and they move them for every
49//! look alike, so a row's clumping survives a look switch unchanged.
50
51use crcbl_shaders::grass::{
52    BLADE_STRIDE, DEFAULT_SHELLS, GrassBlade, INSTANCE_STRIDE, LOOK_BLADES, LOOK_CARDS,
53    LOOK_SHELLS, MAX_SHELLS, NORMAL_GROUND, NORMAL_UP,
54};
55
56/// Cells along one side of a tile's placement grid.
57///
58/// **The generation dispatch's lane count and the slot's capacity are the same
59/// number**, which is what makes the append unbounded-check-free: one lane per
60/// cell and one instance per surviving lane means the count cannot pass the
61/// capacity. [`SLOT_CAPACITY`] is the square of this, and
62/// `the_slot_holds_one_instance_per_cell` is where the two are held together.
63pub const CELLS_PER_TILE: u32 = 64;
64
65/// Instances one tile's slot holds.
66pub const SLOT_CAPACITY: u32 = CELLS_PER_TILE * CELLS_PER_TILE;
67
68/// The most tiles a field may hold.
69///
70/// A ceiling rather than a budget: the instance buffer is
71/// [`GrassField::instance_bytes`], which at this cap stays under WebGPU's
72/// 128 MiB default maximum storage binding size — decision 1's limit on a ring,
73/// and `the_widest_field_fits_a_browsers_storage_binding` is where it is held.
74pub const MAX_TILES: u32 = 64;
75
76/// The most blade rows a field's table may hold.
77///
78/// The cover map's green channel indexes it and that channel holds 256 values,
79/// so this is a choice about how many looks one field mixes rather than a limit
80/// the encoding forces.
81pub const MAX_BLADES: u32 = 16;
82
83/// Why a field could not be built.
84///
85/// One variant per way of being wrong rather than one string, on
86/// `crcbl_wind::WindError`'s terms: a caller can tell a map that has not been
87/// filled in from one that is the wrong shape, and the message names the numbers
88/// it refused.
89#[derive(Debug, thiserror::Error, PartialEq)]
90pub enum GrassError {
91    /// A field with no tiles along one of its axes, or more than [`MAX_TILES`]
92    /// of them.
93    #[error("a {x}x{z} field of tiles is not one this crate will lay out")]
94    Tiles {
95        /// Tiles along `+X`.
96        x: u32,
97        /// Tiles along `+Z`.
98        z: u32,
99    },
100    /// A tile side, a reach or a texel scale that is not a positive finite
101    /// number of metres.
102    #[error("a grass field's {what} of {metres} m is not a distance")]
103    Metres {
104        /// Which number was refused.
105        what: &'static str,
106        /// What was offered, as its bits printed — a `NaN` reaches here too.
107        metres: f32,
108    },
109    /// A map with a zero dimension.
110    #[error("a {width}x{height} grass {what} map has no texels")]
111    EmptyMap {
112        /// Which map was refused.
113        what: &'static str,
114        /// Texels along `+X`.
115        width: u32,
116        /// Texels along `+Z`.
117        height: u32,
118    },
119    /// A map whose contents are not one entry per texel of the grid it was
120    /// handed with.
121    #[error("a {width}x{height} grass {what} map holds {expected} texels, and {found} arrived")]
122    MapSize {
123        /// Which map was refused.
124        what: &'static str,
125        /// Texels along `+X`.
126        width: u32,
127        /// Texels along `+Z`.
128        height: u32,
129        /// Entries the grid needs.
130        expected: usize,
131        /// Entries that arrived.
132        found: usize,
133    },
134    /// A height that is not a finite number of metres.
135    #[error("the grass ground field holds {height} at texel {at}, which is not a height")]
136    Height {
137        /// What was offered.
138        height: f32,
139        /// Where it was.
140        at: usize,
141    },
142    /// No blade rows, or more than [`MAX_BLADES`] of them.
143    #[error("a blade table of {rows} row(s) is not one this crate will hold")]
144    Blades {
145        /// Rows that arrived.
146        rows: usize,
147    },
148    /// A blade row whose size, spread or lever is not a number a blade can be
149    /// drawn with.
150    #[error("blade row {row}'s {what} of {value} is not one a blade is drawn with")]
151    Blade {
152        /// Which row was refused.
153        row: usize,
154        /// Which field of it.
155        what: &'static str,
156        /// What was offered.
157        value: f32,
158    },
159    /// A shell stack of no layers, or of more than [`MAX_SHELLS`].
160    #[error("a stack of {count} shells is not one a field holds; 1 to {MAX_SHELLS} are")]
161    Shells {
162        /// Layers that were asked for.
163        count: u32,
164    },
165    /// A level-of-detail switch that is not a positive distance, or a band
166    /// before it that is negative or longer than the distance.
167    #[error(
168        "a blade level switch at {distance} m over a band of {band} m is not one a field draws"
169    )]
170    BladeLod {
171        /// The switch distance that was offered.
172        distance: f32,
173        /// The band that was offered.
174        band: f32,
175    },
176}
177
178/// The ground a field stands on: one height per texel, and the CPU copy of it.
179///
180/// **There is no terrain system**, which decision 2 says outright — "a field
181/// takes them from a heightfield the caller supplies until one exists". This is
182/// that heightfield.
183///
184/// Read with `Load` and blended by hand in both copies, never sampled: a
185/// hardware bilinear filter has eight bits of sub-texel precision by
186/// specification, and the CPU copy of this placement has all of them.
187#[derive(Clone, Debug, PartialEq)]
188pub struct Heightfield {
189    /// Texels along `+X` and along `+Z`.
190    pub texels: [u32; 2],
191    /// Metres of world between neighbouring texels.
192    pub metres_per_texel: f32,
193    /// The world XZ that texel `(0, 0)` stands at.
194    pub origin: [f32; 2],
195    /// One height in metres per texel, row-major along `+X` then `+Z`.
196    pub heights: Vec<f32>,
197}
198
199/// The density and blade-row map — decision 2's density map and type map, as
200/// two channels of one texel.
201#[derive(Clone, Debug, PartialEq)]
202pub struct CoverMap {
203    /// Texels along `+X` and along `+Z`.
204    pub texels: [u32; 2],
205    /// Metres of world between neighbouring texels.
206    pub metres_per_texel: f32,
207    /// The world XZ that texel `(0, 0)` stands at.
208    pub origin: [f32; 2],
209    /// `[density, row]` per texel, row-major. A density of zero is bare ground
210    /// and 255 is every cell; the row indexes [`GrassField::blades`] and is
211    /// clamped to it.
212    pub cover: Vec<[u8; 2]>,
213}
214
215/// Which geometry a blade row is drawn with — decision 3's looks.
216#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
217pub enum BladeLook {
218    /// Two crossed cards per blade, cut out against the cooked coverage chain:
219    /// the photoreal look, and the cheapest.
220    #[default]
221    Cards,
222    /// Acerola's shell texturing: the field's [`Shells`] stacked over the
223    /// ground, each cutting out a cone about every blade's root, with fins
224    /// where the stack is seen at a grazing angle.
225    Shells,
226    /// Ghost of Tsushima's mesh blades: a cubic Bézier per blade built from its
227    /// vertex index, fifteen vertices near the camera and seven past the
228    /// field's [`BladeLod`] — the realistic look.
229    Blades,
230}
231
232/// Which normal a blade row shades by — decision 4's last lever.
233#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
234pub enum BladeNormal {
235    /// The ground's under the blade's root, so a field shades as the surface it
236    /// grows on.
237    #[default]
238    Ground,
239    /// Straight up whatever the ground does, so a hillside shades as one flat
240    /// colour — the stylised half of the lever.
241    Up,
242}
243
244/// Decision 4's shading levers: "a base-to-tip gradient along the blade, an
245/// ambient-occlusion colour at the root, an additive tip colour (Acerola),
246/// clump-coloured patches (Ghost of Tsushima), and normals taken from the ground
247/// or straight up".
248///
249/// The gradient is [`BladeType::root_color`] and [`BladeType::tip_color`], which
250/// every row has always carried; the rest are here. **[`BladeStyle::PLAIN`]
251/// pulls none of them**, and a row carrying it draws exactly the picture it drew
252/// before they existed — `grass.slang`'s `grass_style` returns its colour
253/// unchanged for it, not merely close to it.
254#[derive(Clone, Copy, Debug, PartialEq)]
255pub struct BladeStyle {
256    /// The colour a blade darkens toward at its root.
257    pub root_occlusion: [f32; 3],
258    /// The fraction of a blade's height the occlusion colour reaches up it, in
259    /// `0..=1`. Zero is no occlusion at all.
260    pub occlusion_reach: f32,
261    /// The colour added toward a blade's tip. Black adds nothing.
262    pub tip_glow: [f32; 3],
263    /// The fraction of a blade's height the tip colour starts at, in `0..1`; it
264    /// rises linearly from there to all of itself at the tip.
265    pub glow_start: f32,
266    /// The colour a patch of blades leans toward.
267    pub patch_color: [f32; 3],
268    /// The most of [`BladeStyle::patch_color`] a patch takes, in `0..=1`; each
269    /// patch takes its own hashed share of it. Zero is no patches.
270    ///
271    /// **A patch is a clump** — decision 2's Voronoi cells, which every blade
272    /// belongs to whatever its row's [`BladeType::clumping`] — so the colour
273    /// follows the same structure the facing and the height do.
274    pub patch_share: f32,
275    /// The normal the row shades by.
276    pub normal: BladeNormal,
277}
278
279impl BladeStyle {
280    /// No lever pulled: no occlusion, no glow, no patches, the ground's normal.
281    pub const PLAIN: Self = Self {
282        root_occlusion: [0.0; 3],
283        occlusion_reach: 0.0,
284        tip_glow: [0.0; 3],
285        glow_start: 0.0,
286        patch_color: [0.0; 3],
287        patch_share: 0.0,
288        normal: BladeNormal::Ground,
289    };
290}
291
292impl Default for BladeStyle {
293    fn default() -> Self {
294        Self::PLAIN
295    }
296}
297
298/// A mesh blade's shape — decision 3's "tilt and facing set the tip, bend sets
299/// the midpoint … normals tilt outward so a flat blade reads as rounded".
300///
301/// Read by [`BladeLook::Blades`] alone; a card or a shell row carries it
302/// unread, so switching a row's look keeps its shape for the day it switches
303/// back.
304#[derive(Clone, Copy, Debug, PartialEq)]
305pub struct BladeShape {
306    /// How far the tip leans out along the blade's face, as the sine of the
307    /// lean, in `0..1`. The blade keeps its height as its length.
308    pub tilt: f32,
309    /// How far the middle of the blade bows back from the straight line between
310    /// its root and its tip, as a fraction of its height, in `0..=1`.
311    pub bow: f32,
312    /// How far the normal tilts out toward each edge, in `0..=1`, so a flat
313    /// strip shades as a rounded blade.
314    pub rounding: f32,
315}
316
317impl BladeShape {
318    /// A straight, flat, upright blade.
319    pub const STRAIGHT: Self = Self {
320        tilt: 0.0,
321        bow: 0.0,
322        rounding: 0.0,
323    };
324}
325
326impl Default for BladeShape {
327    fn default() -> Self {
328        Self::STRAIGHT
329    }
330}
331
332/// How much a row's blades take from their clump — decision 2's "clumps …
333/// driving height, a shared facing and colour".
334///
335/// **Placement, for every look**: a card, a shell and a mesh blade of one row
336/// and one cell stand the same way at the same height. The colour half is
337/// [`BladeStyle::patch_share`], which is a lever. [`Clumping::NONE`] leaves every
338/// facing and height the bits it was before clumps existed.
339#[derive(Clone, Copy, Debug, PartialEq)]
340pub struct Clumping {
341    /// The share of a blade's own facing its clump's shared facing replaces, in
342    /// `0..=1`.
343    pub facing: f32,
344    /// The fraction of a blade's height its clump may take away, in `0..1` —
345    /// one hashed share per clump, on top of the blade's own
346    /// [`BladeType::height_spread`].
347    pub height: f32,
348}
349
350impl Clumping {
351    /// No clumping: every blade faces and stands by its own hash alone.
352    pub const NONE: Self = Self {
353        facing: 0.0,
354        height: 0.0,
355    };
356}
357
358impl Default for Clumping {
359    fn default() -> Self {
360        Self::NONE
361    }
362}
363
364/// Where a field's mesh blades change level of detail — decision 3's "the low
365/// LOD's tile is twice the size with the same blade count, the high LOD drops
366/// three blades in four first, and the high LOD morphs toward the low LOD's
367/// shape near the switch".
368///
369/// A blade whose root is nearer the camera than [`BladeLod::distance`] is drawn
370/// with fifteen vertices; past it, only the one blade of every two-by-two block
371/// of cells the far level keeps is drawn, with seven. Over the
372/// [`BladeLod::band`] before the switch the near level narrows the other three
373/// away and then morphs onto the far shape, so a blade crossing the switch does
374/// not move a pixel. A band of zero is a hard switch, and pops.
375#[derive(Clone, Copy, Debug, PartialEq)]
376pub struct BladeLod {
377    /// The switch, in metres from the camera.
378    pub distance: f32,
379    /// The band before it, in metres, `0..=distance`.
380    pub band: f32,
381}
382
383impl Default for BladeLod {
384    /// A switch at twelve metres over a band of four — a starting value rather
385    /// than a measurement, and a field's own choice to make.
386    fn default() -> Self {
387        Self {
388            distance: 12.0,
389            band: 4.0,
390        }
391    }
392}
393
394/// A field's shell stack: how many layers, and whether fins stand where the
395/// stack is seen edge-on.
396///
397/// **The overdraw of a shell look is proportional to [`Shells::count`]**, which
398/// is decision 3's price and the reason it is a parameter: every layer is a
399/// sheet over the whole field, and a fragment of each is shaded wherever the
400/// sheet is on screen.
401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
402pub struct Shells {
403    /// Layers in the stack, `1..=MAX_SHELLS`.
404    pub count: u32,
405    /// Whether fins stand at silhouettes. Off, a stack seen at a grazing angle
406    /// shows the gaps between its layers — which is what a test of the fins
407    /// compares against.
408    pub fins: bool,
409}
410
411impl Default for Shells {
412    fn default() -> Self {
413        Self {
414            count: DEFAULT_SHELLS,
415            fins: true,
416        }
417    }
418}
419
420/// One row of the blade table — decision 3's "one blade description", drawn as
421/// its [`BladeType::look`] says.
422#[derive(Clone, Copy, Debug, PartialEq)]
423pub struct BladeType {
424    /// The colour at the blade's root. Decision 4's root-occlusion lever: a
425    /// darker root is what makes a field read as having depth.
426    pub root_color: [f32; 3],
427    /// The colour at its tip.
428    pub tip_color: [f32; 3],
429    /// The tallest a blade of this row stands, in metres.
430    pub height: f32,
431    /// The widest half a card of this row is, in metres.
432    pub half_width: f32,
433    /// The fraction of [`BladeType::height`] a blade may lose to its own hash,
434    /// in `0..1`.
435    pub height_spread: f32,
436    /// The same for [`BladeType::half_width`].
437    ///
438    /// A shell strand's root is this half-width too, bounded by half a
439    /// placement cell — see `grass.slang`'s `grass_strand_reach`.
440    pub width_spread: f32,
441    /// The geometry the row is drawn with.
442    pub look: BladeLook,
443    /// Decision 4's levers.
444    pub style: BladeStyle,
445    /// A mesh blade's shape, read only where [`BladeType::look`] is
446    /// [`BladeLook::Blades`].
447    pub shape: BladeShape,
448    /// Decision 2's clumping, for every look.
449    pub clumping: Clumping,
450}
451
452impl BladeType {
453    /// The row as the shader reads it.
454    #[must_use]
455    pub fn row(&self) -> GrassBlade {
456        let with = |[r, g, b]: [f32; 3], a: f32| [r, g, b, a];
457        let style = self.style;
458        GrassBlade {
459            root_color: with(self.root_color, 0.0),
460            tip_color: with(self.tip_color, 0.0),
461            size: [
462                self.height,
463                self.half_width,
464                self.height_spread,
465                self.width_spread,
466            ],
467            occlusion: with(style.root_occlusion, style.occlusion_reach),
468            glow: with(style.tip_glow, style.glow_start),
469            patch: with(style.patch_color, style.patch_share),
470            shape: [self.shape.tilt, self.shape.bow, self.shape.rounding, 0.0],
471            clump: [self.clumping.facing, self.clumping.height, 0.0, 0.0],
472            flags: [
473                match self.look {
474                    BladeLook::Cards => LOOK_CARDS,
475                    BladeLook::Shells => LOOK_SHELLS,
476                    BladeLook::Blades => LOOK_BLADES,
477                },
478                match style.normal {
479                    BladeNormal::Ground => NORMAL_GROUND,
480                    BladeNormal::Up => NORMAL_UP,
481                },
482                0,
483                0,
484            ],
485        }
486    }
487
488    /// The first of this row's numbers a shader could not draw with, as the
489    /// name and value [`GrassError::Blade`] reports.
490    fn refusal(&self) -> Option<(&'static str, f32)> {
491        let style = self.style;
492        let unit = |value: f32| value.is_finite() && (0.0..=1.0).contains(&value);
493        let below_one = |value: f32| value.is_finite() && (0.0..1.0).contains(&value);
494        let colour = |value: f32| value.is_finite() && value >= 0.0;
495        let checks = [
496            (
497                "height",
498                self.height,
499                self.height.is_finite() && self.height > 0.0,
500            ),
501            (
502                "half-width",
503                self.half_width,
504                self.half_width.is_finite() && self.half_width > 0.0,
505            ),
506            (
507                "height spread",
508                self.height_spread,
509                below_one(self.height_spread),
510            ),
511            (
512                "width spread",
513                self.width_spread,
514                below_one(self.width_spread),
515            ),
516            (
517                "occlusion reach",
518                style.occlusion_reach,
519                unit(style.occlusion_reach),
520            ),
521            ("glow start", style.glow_start, below_one(style.glow_start)),
522            ("patch share", style.patch_share, unit(style.patch_share)),
523            ("tilt", self.shape.tilt, below_one(self.shape.tilt)),
524            ("bow", self.shape.bow, unit(self.shape.bow)),
525            ("rounding", self.shape.rounding, unit(self.shape.rounding)),
526            (
527                "clump facing",
528                self.clumping.facing,
529                unit(self.clumping.facing),
530            ),
531            (
532                "clump height",
533                self.clumping.height,
534                below_one(self.clumping.height),
535            ),
536        ];
537        let colours = [
538            ("root occlusion colour", style.root_occlusion),
539            ("tip glow", style.tip_glow),
540            ("patch colour", style.patch_color),
541        ]
542        .into_iter()
543        .flat_map(|(what, rgb)| rgb.map(|value| (what, value, colour(value))));
544        checks
545            .into_iter()
546            .chain(colours)
547            .find(|(_, _, ok)| !ok)
548            .map(|(what, value, _)| (what, value))
549    }
550}
551
552/// A patch of grass, as data.
553///
554/// Built through [`GrassField::new`], which is the only way: every number below
555/// is read by a shader that cannot check it, and a field that reached the device
556/// with a zero texel scale would divide by it there.
557#[derive(Clone, Debug, PartialEq)]
558pub struct GrassField {
559    tiles: [u32; 2],
560    tile_size: f32,
561    origin: [f32; 2],
562    reach: f32,
563    ground: Heightfield,
564    cover: CoverMap,
565    blades: Vec<BladeType>,
566    shells: Shells,
567    blade_lod: BladeLod,
568}
569
570impl GrassField {
571    /// A field of `tiles` tiles of `tile_size` metres, with its minimum corner
572    /// at `origin` on the XZ plane.
573    ///
574    /// `reach` is how far from the camera a blade is still generated — decision
575    /// 7's distance cull, which is the only cull this rung spends.
576    ///
577    /// # Errors
578    ///
579    /// A [`GrassError`] naming the first number refused. Nothing is built from a
580    /// field that failed, so a caller may hand the same description back after
581    /// fixing it.
582    pub fn new(
583        tiles: [u32; 2],
584        tile_size: f32,
585        origin: [f32; 2],
586        reach: f32,
587        ground: Heightfield,
588        cover: CoverMap,
589        blades: Vec<BladeType>,
590    ) -> Result<Self, GrassError> {
591        let [x, z] = tiles;
592        if x == 0 || z == 0 || x.saturating_mul(z) > MAX_TILES {
593            return Err(GrassError::Tiles { x, z });
594        }
595        for (what, metres) in [("tile side", tile_size), ("reach", reach)] {
596            if !(metres.is_finite() && metres > 0.0) {
597                return Err(GrassError::Metres { what, metres });
598            }
599        }
600        for value in origin {
601            if !value.is_finite() {
602                return Err(GrassError::Metres {
603                    what: "origin",
604                    metres: value,
605                });
606            }
607        }
608        ground.check("ground")?;
609        cover.check()?;
610        if blades.is_empty() || blades.len() > MAX_BLADES as usize {
611            return Err(GrassError::Blades { rows: blades.len() });
612        }
613        for (row, blade) in blades.iter().enumerate() {
614            if let Some((what, value)) = blade.refusal() {
615                return Err(GrassError::Blade { row, what, value });
616            }
617        }
618        Ok(Self {
619            tiles,
620            tile_size,
621            origin,
622            reach,
623            ground,
624            cover,
625            blades,
626            shells: Shells::default(),
627            blade_lod: BladeLod::default(),
628        })
629    }
630
631    /// This field with its shell stack replaced.
632    ///
633    /// # Errors
634    ///
635    /// [`GrassError::Shells`] for a stack of no layers or of more than
636    /// [`MAX_SHELLS`], and then the field is not built.
637    pub fn with_shells(mut self, shells: Shells) -> Result<Self, GrassError> {
638        if !(1..=MAX_SHELLS).contains(&shells.count) {
639            return Err(GrassError::Shells {
640                count: shells.count,
641            });
642        }
643        self.shells = shells;
644        Ok(self)
645    }
646
647    /// This field with its mesh blades' level switch replaced.
648    ///
649    /// # Errors
650    ///
651    /// [`GrassError::BladeLod`] for a switch that is not a positive finite
652    /// distance, or a band that is negative, not finite or longer than the
653    /// distance — and then the field is not built.
654    pub fn with_blade_lod(mut self, lod: BladeLod) -> Result<Self, GrassError> {
655        let BladeLod { distance, band } = lod;
656        if !(distance.is_finite()
657            && distance > 0.0
658            && band.is_finite()
659            && (0.0..=distance).contains(&band))
660        {
661            return Err(GrassError::BladeLod { distance, band });
662        }
663        self.blade_lod = lod;
664        Ok(self)
665    }
666
667    /// Where the field's mesh blades change level of detail. Read by the draw
668    /// only where a row's look is [`BladeLook::Blades`].
669    #[must_use]
670    pub const fn blade_lod(&self) -> BladeLod {
671        self.blade_lod
672    }
673
674    /// Whether any row of the blade table is drawn as mesh blades — which is
675    /// whether a frame records the two blade draws at all.
676    #[must_use]
677    pub fn draws_blades(&self) -> bool {
678        self.blades
679            .iter()
680            .any(|blade| blade.look == BladeLook::Blades)
681    }
682
683    /// The field's shell stack. Read by the draw only where a row's look is
684    /// [`BladeLook::Shells`].
685    #[must_use]
686    pub const fn shells(&self) -> Shells {
687        self.shells
688    }
689
690    /// Whether any row of the blade table is drawn as shells — which is whether
691    /// a frame records the shell and fin draws at all.
692    #[must_use]
693    pub fn draws_shells(&self) -> bool {
694        self.blades
695            .iter()
696            .any(|blade| blade.look == BladeLook::Shells)
697    }
698
699    /// How tall the shell stack stands, in metres: the tallest shell row's
700    /// height, which no blade of any row exceeds. Zero where no row is shells.
701    #[must_use]
702    pub fn shell_stack(&self) -> f32 {
703        self.blades
704            .iter()
705            .filter(|blade| blade.look == BladeLook::Shells)
706            .fold(0.0, |tallest, blade| tallest.max(blade.height))
707    }
708
709    /// Tiles along `+X` and along `+Z`.
710    #[must_use]
711    pub const fn tiles(&self) -> [u32; 2] {
712        self.tiles
713    }
714
715    /// How many tiles there are, which is how many slots and how many draws.
716    #[must_use]
717    pub const fn slots(&self) -> u32 {
718        self.tiles[0] * self.tiles[1]
719    }
720
721    /// One tile's side, in metres.
722    #[must_use]
723    pub const fn tile_size(&self) -> f32 {
724        self.tile_size
725    }
726
727    /// The world XZ of the field's minimum corner.
728    #[must_use]
729    pub const fn origin(&self) -> [f32; 2] {
730        self.origin
731    }
732
733    /// How far from the camera a blade is still generated, in metres.
734    #[must_use]
735    pub const fn reach(&self) -> f32 {
736        self.reach
737    }
738
739    /// The ground the field stands on.
740    #[must_use]
741    pub const fn ground(&self) -> &Heightfield {
742        &self.ground
743    }
744
745    /// The density and blade-row map.
746    #[must_use]
747    pub const fn cover(&self) -> &CoverMap {
748        &self.cover
749    }
750
751    /// The blade table the cover map's rows index.
752    #[must_use]
753    pub fn blades(&self) -> &[BladeType] {
754        &self.blades
755    }
756
757    /// The world XZ of tile `slot`'s minimum corner.
758    ///
759    /// # Panics
760    ///
761    /// If `slot` is not one of this field's — the caller holds the field and
762    /// [`GrassField::slots`] says how many there are.
763    #[must_use]
764    pub fn tile_origin(&self, slot: u32) -> [f32; 2] {
765        assert!(
766            slot < self.slots(),
767            "slot {slot} is not one of this field's"
768        );
769        let [x, z] = [slot % self.tiles[0], slot / self.tiles[0]];
770        [
771            self.origin[0] + x as f32 * self.tile_size,
772            self.origin[1] + z as f32 * self.tile_size,
773        ]
774    }
775
776    /// Bytes the cells buffer needs for this field: one row per cell of every
777    /// tile.
778    #[must_use]
779    pub fn cell_bytes(&self) -> u64 {
780        u64::from(self.slots()) * u64::from(SLOT_CAPACITY) * INSTANCE_STRIDE as u64
781    }
782
783    /// Bytes the instance buffer needs for this field: two regions of
784    /// [`GrassField::cell_bytes`] each — the cards and the far mesh blades in
785    /// the first, the near mesh blades in the second.
786    #[must_use]
787    pub fn instance_bytes(&self) -> u64 {
788        2 * self.cell_bytes()
789    }
790
791    /// Bytes the blade table needs.
792    #[must_use]
793    pub fn blade_bytes(&self) -> u64 {
794        self.blades.len() as u64 * BLADE_STRIDE as u64
795    }
796}
797
798impl Heightfield {
799    /// The height at `(x, z)`, blended bilinearly from the four texels around
800    /// it, and the ground's unit normal there.
801    ///
802    /// **`grass_ground_under` in `grass_gen.slang` is the same arithmetic in the
803    /// same order**, which is what lets a blade's root be compared between the
804    /// two copies. It is not bit-identical: a shader compiler may contract each
805    /// multiply-add here into an FMA and Rust never does, so the two agree to
806    /// the last place of an `f32` rather than to the bit.
807    #[must_use]
808    pub fn under(&self, x: f32, z: f32) -> (f32, [f32; 3]) {
809        let inverse = 1.0 / self.metres_per_texel;
810        let at = [
811            (x - self.origin[0]) * inverse,
812            (z - self.origin[1]) * inverse,
813        ];
814        let base = [at[0].floor(), at[1].floor()];
815        let blend = [at[0] - base[0], at[1] - base[1]];
816        #[expect(
817            clippy::cast_possible_truncation,
818            reason = "`floor` has already made these integral, so the cast is exact"
819        )]
820        let texel = [base[0] as i32, base[1] as i32];
821        let corner = |dx: i32, dz: i32| self.texel(texel[0] + dx, texel[1] + dz);
822        let (h00, h10, h01, h11) = (corner(0, 0), corner(1, 0), corner(0, 1), corner(1, 1));
823        let lower = h00 + blend[0] * (h10 - h00);
824        let upper = h01 + blend[0] * (h11 - h01);
825        let height = lower + blend[1] * (upper - lower);
826        let rise_x = 0.5 * ((h10 - h00) + (h11 - h01));
827        let rise_z = 0.5 * ((h01 - h00) + (h11 - h10));
828        let normal = normalise([-rise_x, self.metres_per_texel, -rise_z]);
829        (height, normal)
830    }
831
832    /// One texel, clamped to the field's edge.
833    fn texel(&self, x: i32, z: i32) -> f32 {
834        let [width, height] = self.texels;
835        #[expect(
836            clippy::cast_possible_wrap,
837            reason = "`check` refuses a map larger than an `i32` holds"
838        )]
839        let last = [width as i32 - 1, height as i32 - 1];
840        let clamped = [x.clamp(0, last[0]), z.clamp(0, last[1])];
841        #[expect(
842            clippy::cast_sign_loss,
843            reason = "clamped into `0..=last`, which is non-negative"
844        )]
845        let at = clamped[1] as usize * width as usize + clamped[0] as usize;
846        self.heights[at]
847    }
848
849    /// The bytes of the `R32Float` image this is uploaded as.
850    #[must_use]
851    pub fn to_bytes(&self) -> Vec<u8> {
852        self.heights
853            .iter()
854            .flat_map(|height| height.to_le_bytes())
855            .collect()
856    }
857
858    fn check(&self, what: &'static str) -> Result<(), GrassError> {
859        let [width, height] = self.texels;
860        check_grid(what, self.texels, self.metres_per_texel, self.origin)?;
861        let expected = width as usize * height as usize;
862        if self.heights.len() != expected {
863            return Err(GrassError::MapSize {
864                what,
865                width,
866                height,
867                expected,
868                found: self.heights.len(),
869            });
870        }
871        for (at, value) in self.heights.iter().enumerate() {
872            if !value.is_finite() {
873                return Err(GrassError::Height { height: *value, at });
874            }
875        }
876        Ok(())
877    }
878}
879
880impl CoverMap {
881    /// The texel under `(x, z)` — nearest, never blended, which is what makes
882    /// the density test that reads it an integer comparison.
883    ///
884    /// `grass_cover_under` in `grass_gen.slang` is the same three lines.
885    #[must_use]
886    pub fn under(&self, x: f32, z: f32) -> [u8; 2] {
887        let inverse = 1.0 / self.metres_per_texel;
888        let at = [
889            (x - self.origin[0]) * inverse,
890            (z - self.origin[1]) * inverse,
891        ];
892        let [width, height] = self.texels;
893        #[expect(
894            clippy::cast_possible_truncation,
895            clippy::cast_possible_wrap,
896            reason = "`floor` has made these integral and `check` bounds the extents"
897        )]
898        let texel = [
899            ((at[0] + 0.5).floor() as i32).clamp(0, width as i32 - 1),
900            ((at[1] + 0.5).floor() as i32).clamp(0, height as i32 - 1),
901        ];
902        #[expect(
903            clippy::cast_sign_loss,
904            reason = "clamped into `0..=last`, which is non-negative"
905        )]
906        let at = texel[1] as usize * width as usize + texel[0] as usize;
907        self.cover[at]
908    }
909
910    /// The bytes of the `Rgba8Unorm` image this is uploaded as: density in red,
911    /// the blade row in green, and zeroes in the two channels no shader reads.
912    #[must_use]
913    pub fn to_bytes(&self) -> Vec<u8> {
914        self.cover
915            .iter()
916            .flat_map(|[density, row]| [*density, *row, 0, 0])
917            .collect()
918    }
919
920    fn check(&self) -> Result<(), GrassError> {
921        let [width, height] = self.texels;
922        check_grid("cover", self.texels, self.metres_per_texel, self.origin)?;
923        let expected = width as usize * height as usize;
924        if self.cover.len() != expected {
925            return Err(GrassError::MapSize {
926                what: "cover",
927                width,
928                height,
929                expected,
930                found: self.cover.len(),
931            });
932        }
933        Ok(())
934    }
935}
936
937/// The extent, scale and origin checks both maps share.
938fn check_grid(
939    what: &'static str,
940    texels: [u32; 2],
941    metres_per_texel: f32,
942    origin: [f32; 2],
943) -> Result<(), GrassError> {
944    let [width, height] = texels;
945    if width == 0 || height == 0 || width > i32::MAX as u32 || height > i32::MAX as u32 {
946        return Err(GrassError::EmptyMap {
947            what,
948            width,
949            height,
950        });
951    }
952    if !(metres_per_texel.is_finite() && metres_per_texel > 0.0) {
953        return Err(GrassError::Metres {
954            what: "texel scale",
955            metres: metres_per_texel,
956        });
957    }
958    for value in origin {
959        if !value.is_finite() {
960            return Err(GrassError::Metres {
961                what: "map origin",
962                metres: value,
963            });
964        }
965    }
966    Ok(())
967}
968
969/// `vector` scaled to unit length, or `+Y` where it has no length to scale.
970///
971/// The shader's `normalize` with the degenerate case written out: a ground
972/// field that is flat everywhere has a rise of zero on both axes and a texel
973/// scale that `check_grid` has already refused to let be zero, so the fallback
974/// is unreachable from a checked field — and it is here rather than absent
975/// because the alternative is a `NaN` in a normal that shades every blade of a
976/// tile black.
977fn normalise(vector: [f32; 3]) -> [f32; 3] {
978    let length_squared = vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2];
979    if length_squared > 0.0 {
980        let scale = 1.0 / length_squared.sqrt();
981        [vector[0] * scale, vector[1] * scale, vector[2] * scale]
982    } else {
983        [0.0, 1.0, 0.0]
984    }
985}
986
987#[cfg(test)]
988pub(crate) mod tests {
989    use super::*;
990
991    /// A flat ground field of `texels` square at one metre a texel.
992    pub(crate) fn flat_ground(texels: u32, height: f32) -> Heightfield {
993        Heightfield {
994            texels: [texels, texels],
995            metres_per_texel: 1.0,
996            origin: [0.0, 0.0],
997            heights: vec![height; (texels * texels) as usize],
998        }
999    }
1000
1001    /// A cover map of `texels` square at one metre a texel, every texel at
1002    /// `density` on row zero.
1003    pub(crate) fn flat_cover(texels: u32, density: u8) -> CoverMap {
1004        CoverMap {
1005            texels: [texels, texels],
1006            metres_per_texel: 1.0,
1007            origin: [0.0, 0.0],
1008            cover: vec![[density, 0]; (texels * texels) as usize],
1009        }
1010    }
1011
1012    pub(crate) fn one_blade() -> Vec<BladeType> {
1013        vec![BladeType {
1014            root_color: [0.05, 0.12, 0.03],
1015            tip_color: [0.35, 0.55, 0.15],
1016            height: 0.4,
1017            half_width: 0.03,
1018            height_spread: 0.4,
1019            width_spread: 0.3,
1020            look: BladeLook::Cards,
1021            style: BladeStyle::PLAIN,
1022            shape: BladeShape::STRAIGHT,
1023            clumping: Clumping::NONE,
1024        }]
1025    }
1026
1027    pub(super) fn field() -> GrassField {
1028        GrassField::new(
1029            [2, 2],
1030            8.0,
1031            [0.0, 0.0],
1032            100.0,
1033            flat_ground(32, 0.0),
1034            flat_cover(32, 255),
1035            one_blade(),
1036        )
1037        .expect("a real field")
1038    }
1039
1040    /// **A slot holds exactly one instance per cell**, which is what lets the
1041    /// generation pass append with no bound on the atomic's result.
1042    #[test]
1043    fn the_slot_holds_one_instance_per_cell() {
1044        assert_eq!(SLOT_CAPACITY, CELLS_PER_TILE * CELLS_PER_TILE);
1045    }
1046
1047    /// **The whole instance buffer fits a browser's guaranteed binding size**,
1048    /// which decision 1 names: "its 128 MiB default storage binding size means
1049    /// one instance buffer per ring rather than one for the field".
1050    #[test]
1051    fn the_widest_field_fits_a_browsers_storage_binding() {
1052        const WEBGPU_MAX_STORAGE_BINDING: u64 = 128 * 1024 * 1024;
1053        let widest = GrassField::new(
1054            [MAX_TILES, 1],
1055            8.0,
1056            [0.0, 0.0],
1057            100.0,
1058            flat_ground(8, 0.0),
1059            flat_cover(8, 8),
1060            one_blade(),
1061        )
1062        .expect("the widest field is a field")
1063        .instance_bytes();
1064        eprintln!("grass: the widest field's instances are {widest} byte(s)");
1065        assert!(
1066            widest <= WEBGPU_MAX_STORAGE_BINDING,
1067            "{MAX_TILES} tiles of {SLOT_CAPACITY} instances is {widest} bytes, past the \
1068             {WEBGPU_MAX_STORAGE_BINDING} a browser guarantees"
1069        );
1070    }
1071
1072    /// Every number a shader divides by or indexes with is refused here, and
1073    /// each refusal names what it refused.
1074    #[test]
1075    fn a_field_refuses_every_number_a_shader_could_not_survive() {
1076        let build = |tiles, tile_size, reach, ground, cover, blades| {
1077            GrassField::new(tiles, tile_size, [0.0, 0.0], reach, ground, cover, blades)
1078        };
1079        assert_eq!(
1080            build(
1081                [0, 2],
1082                8.0,
1083                10.0,
1084                flat_ground(8, 0.0),
1085                flat_cover(8, 8),
1086                one_blade()
1087            ),
1088            Err(GrassError::Tiles { x: 0, z: 2 })
1089        );
1090        assert_eq!(
1091            build(
1092                [MAX_TILES, 2],
1093                8.0,
1094                10.0,
1095                flat_ground(8, 0.0),
1096                flat_cover(8, 8),
1097                one_blade()
1098            ),
1099            Err(GrassError::Tiles { x: MAX_TILES, z: 2 })
1100        );
1101        assert!(matches!(
1102            build(
1103                [1, 1],
1104                0.0,
1105                10.0,
1106                flat_ground(8, 0.0),
1107                flat_cover(8, 8),
1108                one_blade()
1109            ),
1110            Err(GrassError::Metres {
1111                what: "tile side",
1112                ..
1113            })
1114        ));
1115        assert!(matches!(
1116            build(
1117                [1, 1],
1118                8.0,
1119                f32::NAN,
1120                flat_ground(8, 0.0),
1121                flat_cover(8, 8),
1122                one_blade()
1123            ),
1124            Err(GrassError::Metres { what: "reach", .. })
1125        ));
1126        let mut short = flat_ground(8, 0.0);
1127        short.heights.pop();
1128        assert!(matches!(
1129            build([1, 1], 8.0, 10.0, short, flat_cover(8, 8), one_blade()),
1130            Err(GrassError::MapSize { what: "ground", .. })
1131        ));
1132        let mut nan = flat_ground(8, 0.0);
1133        nan.heights[3] = f32::INFINITY;
1134        assert!(matches!(
1135            build([1, 1], 8.0, 10.0, nan, flat_cover(8, 8), one_blade()),
1136            Err(GrassError::Height { at: 3, .. })
1137        ));
1138        let mut scaleless = flat_cover(8, 8);
1139        scaleless.metres_per_texel = 0.0;
1140        assert!(matches!(
1141            build(
1142                [1, 1],
1143                8.0,
1144                10.0,
1145                flat_ground(8, 0.0),
1146                scaleless,
1147                one_blade()
1148            ),
1149            Err(GrassError::Metres {
1150                what: "texel scale",
1151                ..
1152            })
1153        ));
1154        assert_eq!(
1155            build(
1156                [1, 1],
1157                8.0,
1158                10.0,
1159                flat_ground(8, 0.0),
1160                flat_cover(8, 8),
1161                Vec::new()
1162            ),
1163            Err(GrassError::Blades { rows: 0 })
1164        );
1165        let mut flat_blade = one_blade();
1166        flat_blade[0].height = 0.0;
1167        assert!(matches!(
1168            build(
1169                [1, 1],
1170                8.0,
1171                10.0,
1172                flat_ground(8, 0.0),
1173                flat_cover(8, 8),
1174                flat_blade
1175            ),
1176            Err(GrassError::Blade {
1177                row: 0,
1178                what: "height",
1179                ..
1180            })
1181        ));
1182    }
1183
1184    /// **Tiles are laid out along `+X` then `+Z`**, from the field's own corner,
1185    /// and every slot's origin is one tile side from its neighbour's.
1186    #[test]
1187    fn the_tiles_tile_the_field() {
1188        let field = GrassField::new(
1189            [3, 2],
1190            4.0,
1191            [-6.0, 10.0],
1192            50.0,
1193            flat_ground(32, 0.0),
1194            flat_cover(32, 128),
1195            one_blade(),
1196        )
1197        .expect("a real field");
1198        assert_eq!(field.slots(), 6);
1199        assert_eq!(field.tile_origin(0), [-6.0, 10.0]);
1200        assert_eq!(field.tile_origin(2), [2.0, 10.0]);
1201        assert_eq!(field.tile_origin(3), [-6.0, 14.0]);
1202        assert_eq!(field.tile_origin(5), [2.0, 14.0]);
1203    }
1204
1205    /// **A slope reads back as its slope**, and a flat field's normal is `+Y`.
1206    ///
1207    /// The heights rise by one metre per texel along `+X`, so the ground leans
1208    /// at 45° about `+Z` and the normal's `x` and `y` are equal and opposite in
1209    /// sign to the rise.
1210    #[test]
1211    fn the_ground_answers_its_own_height_and_slope() {
1212        let flat = flat_ground(8, 2.5);
1213        let (height, normal) = flat.under(3.25, 4.75);
1214        assert_eq!(height, 2.5);
1215        assert_eq!(normal, [0.0, 1.0, 0.0]);
1216
1217        let ramp = Heightfield {
1218            texels: [8, 8],
1219            metres_per_texel: 1.0,
1220            origin: [0.0, 0.0],
1221            heights: (0..64).map(|at| (at % 8) as f32).collect(),
1222        };
1223        let (height, normal) = ramp.under(3.5, 2.0);
1224        assert!(
1225            (height - 3.5).abs() < 1e-6,
1226            "the ramp read {height} at x=3.5"
1227        );
1228        let root_half = core::f32::consts::FRAC_1_SQRT_2;
1229        assert!((normal[0] + root_half).abs() < 1e-6, "{normal:?}");
1230        assert!((normal[1] - root_half).abs() < 1e-6, "{normal:?}");
1231        assert!(normal[2].abs() < 1e-6, "{normal:?}");
1232    }
1233
1234    /// **The cover map is nearest**, so a position anywhere inside a texel's
1235    /// square reads that texel and nothing of its neighbours.
1236    #[test]
1237    fn the_cover_map_reads_one_texel() {
1238        let mut cover = flat_cover(4, 0);
1239        cover.cover[2 + 4] = [200, 1];
1240        for (x, z) in [(2.0, 1.0), (1.51, 0.51), (2.49, 1.49)] {
1241            assert_eq!(cover.under(x, z), [200, 1], "at ({x}, {z})");
1242        }
1243        assert_eq!(cover.under(1.49, 1.0), [0, 0]);
1244        assert_eq!(cover.under(2.0, 1.51), [0, 0]);
1245        // And the edges clamp rather than wrapping or indexing out.
1246        assert_eq!(cover.under(-100.0, -100.0), [0, 0]);
1247        assert_eq!(cover.under(100.0, 100.0), [0, 0]);
1248    }
1249
1250    /// The two uploads are the byte layouts the seam takes: four bytes a texel
1251    /// for the heights and four for the cover.
1252    #[test]
1253    fn the_maps_upload_as_the_formats_they_are_bound_as() {
1254        let ground = flat_ground(2, 1.5);
1255        let bytes = ground.to_bytes();
1256        assert_eq!(bytes.len(), 4 * 4);
1257        assert_eq!(f32::from_le_bytes(bytes[4..8].try_into().expect("4")), 1.5);
1258        let cover = flat_cover(2, 77);
1259        let bytes = cover.to_bytes();
1260        assert_eq!(bytes.len(), 4 * 4);
1261        assert_eq!(&bytes[0..4], &[77, 0, 0, 0]);
1262    }
1263
1264    /// The blade row reaches the shader's layout with its colours split and its
1265    /// four sizes in the order the shader reads them.
1266    #[test]
1267    fn a_blade_row_is_the_shaders_row() {
1268        let row = one_blade()[0].row();
1269        assert_eq!(row.root_color, [0.05, 0.12, 0.03, 0.0]);
1270        assert_eq!(row.tip_color, [0.35, 0.55, 0.15, 0.0]);
1271        assert_eq!(row.size, [0.4, 0.03, 0.4, 0.3]);
1272        // A plain card row pulls no lever: every reach, start and share is the
1273        // zero the shader returns its colour unchanged for.
1274        assert_eq!(row.occlusion, [0.0; 4]);
1275        assert_eq!(row.glow, [0.0; 4]);
1276        assert_eq!(row.patch, [0.0; 4]);
1277        assert_eq!(row.flags, [LOOK_CARDS, NORMAL_GROUND, 0, 0]);
1278
1279        let styled = BladeType {
1280            look: BladeLook::Shells,
1281            style: BladeStyle {
1282                root_occlusion: [0.1, 0.2, 0.3],
1283                occlusion_reach: 0.4,
1284                tip_glow: [0.5, 0.6, 0.7],
1285                glow_start: 0.8,
1286                patch_color: [0.9, 1.0, 1.1],
1287                patch_share: 0.25,
1288                normal: BladeNormal::Up,
1289            },
1290            ..one_blade()[0]
1291        }
1292        .row();
1293        assert_eq!(styled.occlusion, [0.1, 0.2, 0.3, 0.4]);
1294        assert_eq!(styled.glow, [0.5, 0.6, 0.7, 0.8]);
1295        assert_eq!(styled.patch, [0.9, 1.0, 1.1, 0.25]);
1296        assert_eq!(styled.flags, [LOOK_SHELLS, NORMAL_UP, 0, 0]);
1297        // A plain row's shape and clumping are all zero, which is what the
1298        // shaders read as a straight blade and no clump.
1299        assert_eq!(row.shape, [0.0; 4]);
1300        assert_eq!(row.clump, [0.0; 4]);
1301
1302        let blade = BladeType {
1303            look: BladeLook::Blades,
1304            shape: BladeShape {
1305                tilt: 0.25,
1306                bow: 0.5,
1307                rounding: 0.75,
1308            },
1309            clumping: Clumping {
1310                facing: 0.125,
1311                height: 0.375,
1312            },
1313            ..one_blade()[0]
1314        }
1315        .row();
1316        assert_eq!(blade.shape, [0.25, 0.5, 0.75, 0.0]);
1317        assert_eq!(blade.clump, [0.125, 0.375, 0.0, 0.0]);
1318        assert_eq!(blade.flags, [LOOK_BLADES, NORMAL_GROUND, 0, 0]);
1319    }
1320
1321    /// **Every lever a shader divides by or blends with is refused out of
1322    /// range**, and the shell stack's count is held to the block it fills.
1323    #[test]
1324    fn a_field_refuses_levers_and_stacks_a_shader_could_not_draw() {
1325        let with_style = |style: BladeStyle| {
1326            GrassField::new(
1327                [1, 1],
1328                8.0,
1329                [0.0, 0.0],
1330                10.0,
1331                flat_ground(8, 0.0),
1332                flat_cover(8, 8),
1333                vec![BladeType {
1334                    style,
1335                    ..one_blade()[0]
1336                }],
1337            )
1338        };
1339        for (style, what) in [
1340            (
1341                BladeStyle {
1342                    occlusion_reach: 1.5,
1343                    ..BladeStyle::PLAIN
1344                },
1345                "occlusion reach",
1346            ),
1347            (
1348                BladeStyle {
1349                    glow_start: 1.0,
1350                    ..BladeStyle::PLAIN
1351                },
1352                "glow start",
1353            ),
1354            (
1355                BladeStyle {
1356                    patch_share: -0.1,
1357                    ..BladeStyle::PLAIN
1358                },
1359                "patch share",
1360            ),
1361            (
1362                BladeStyle {
1363                    tip_glow: [0.0, f32::NAN, 0.0],
1364                    ..BladeStyle::PLAIN
1365                },
1366                "tip glow",
1367            ),
1368        ] {
1369            assert!(
1370                matches!(with_style(style), Err(GrassError::Blade { row: 0, what: refused, .. }) if refused == what),
1371                "{what} was not refused"
1372            );
1373        }
1374        let field = with_style(BladeStyle::PLAIN).expect("a plain row is a real row");
1375        assert_eq!(field.shells(), Shells::default());
1376        for count in [0, MAX_SHELLS + 1] {
1377            assert_eq!(
1378                field.clone().with_shells(Shells { count, fins: true }),
1379                Err(GrassError::Shells { count })
1380            );
1381        }
1382        let stacked = field
1383            .clone()
1384            .with_shells(Shells {
1385                count: MAX_SHELLS,
1386                fins: false,
1387            })
1388            .expect("the widest stack is one the block holds");
1389        assert_eq!(stacked.shells().count, MAX_SHELLS);
1390
1391        let with_shape = |shape: BladeShape, clumping: Clumping| {
1392            GrassField::new(
1393                [1, 1],
1394                8.0,
1395                [0.0, 0.0],
1396                10.0,
1397                flat_ground(8, 0.0),
1398                flat_cover(8, 8),
1399                vec![BladeType {
1400                    shape,
1401                    clumping,
1402                    ..one_blade()[0]
1403                }],
1404            )
1405        };
1406        for (shape, clumping, what) in [
1407            (
1408                BladeShape {
1409                    tilt: 1.0,
1410                    ..BladeShape::STRAIGHT
1411                },
1412                Clumping::NONE,
1413                "tilt",
1414            ),
1415            (
1416                BladeShape {
1417                    bow: f32::INFINITY,
1418                    ..BladeShape::STRAIGHT
1419                },
1420                Clumping::NONE,
1421                "bow",
1422            ),
1423            (
1424                BladeShape {
1425                    rounding: -0.5,
1426                    ..BladeShape::STRAIGHT
1427                },
1428                Clumping::NONE,
1429                "rounding",
1430            ),
1431            (
1432                BladeShape::STRAIGHT,
1433                Clumping {
1434                    facing: 1.25,
1435                    ..Clumping::NONE
1436                },
1437                "clump facing",
1438            ),
1439            (
1440                BladeShape::STRAIGHT,
1441                Clumping {
1442                    height: 1.0,
1443                    ..Clumping::NONE
1444                },
1445                "clump height",
1446            ),
1447        ] {
1448            assert!(
1449                matches!(with_shape(shape, clumping), Err(GrassError::Blade { row: 0, what: refused, .. }) if refused == what),
1450                "{what} was not refused"
1451            );
1452        }
1453
1454        assert_eq!(field.blade_lod(), BladeLod::default());
1455        for (distance, band) in [
1456            (0.0, 0.0),
1457            (f32::NAN, 1.0),
1458            (10.0, -1.0),
1459            (10.0, 10.5),
1460            (10.0, f32::INFINITY),
1461        ] {
1462            assert!(
1463                matches!(
1464                    field.clone().with_blade_lod(BladeLod { distance, band }),
1465                    Err(GrassError::BladeLod { .. })
1466                ),
1467                "a switch at {distance} m over {band} m was not refused"
1468            );
1469        }
1470        let hard = field
1471            .with_blade_lod(BladeLod {
1472                distance: 6.0,
1473                band: 0.0,
1474            })
1475            .expect("a hard switch is a switch");
1476        assert_eq!(hard.blade_lod().band, 0.0);
1477    }
1478
1479    /// **The shell stack is the tallest shell row**, and a field with none has
1480    /// none — so a card field records no shell draw.
1481    #[test]
1482    fn the_stack_stands_as_tall_as_the_tallest_shell_row() {
1483        let mut rows = one_blade();
1484        rows.push(BladeType {
1485            height: 0.9,
1486            look: BladeLook::Cards,
1487            ..rows[0]
1488        });
1489        let cards = GrassField::new(
1490            [1, 1],
1491            8.0,
1492            [0.0, 0.0],
1493            10.0,
1494            flat_ground(8, 0.0),
1495            flat_cover(8, 8),
1496            rows.clone(),
1497        )
1498        .expect("a real field");
1499        assert!(!cards.draws_shells());
1500        assert_eq!(cards.shell_stack(), 0.0);
1501
1502        rows[0].look = BladeLook::Shells;
1503        let mixed = GrassField::new(
1504            [1, 1],
1505            8.0,
1506            [0.0, 0.0],
1507            10.0,
1508            flat_ground(8, 0.0),
1509            flat_cover(8, 8),
1510            rows,
1511        )
1512        .expect("a real field");
1513        assert!(mixed.draws_shells());
1514        assert!(!mixed.draws_blades());
1515        // The taller row is a card row, so the stack is the shell row's height.
1516        assert_eq!(mixed.shell_stack(), 0.4);
1517    }
1518
1519    /// The buffer sizes are what the shaders index, so a field that fits its
1520    /// slots fits its buffer.
1521    #[test]
1522    fn the_buffers_are_the_size_the_shaders_index() {
1523        let field = field();
1524        assert_eq!(
1525            field.cell_bytes(),
1526            u64::from(field.slots()) * u64::from(SLOT_CAPACITY) * INSTANCE_STRIDE as u64
1527        );
1528        assert_eq!(field.instance_bytes(), 2 * field.cell_bytes());
1529        assert_eq!(field.blade_bytes(), BLADE_STRIDE as u64);
1530    }
1531}