Skip to main content

sciart_core/
grid.rs

1//! Dense 2-D fields for automata, lattices and PDEs (SPEC-001 CORE-R33..R36, CORE-R43,
2//! CORE-R48, CORE-R52, CORE-R53, CORE-R68, CORE-R69).
3//!
4//! One contiguous row-major `Vec<T>`: rows are cache-line friendly for the
5//! `for y { for x { .. } }` sweeps every grid scene does, and the same layout as
6//! [`Canvas`](crate::Canvas), so a grid maps onto the screen cell for cell.
7//!
8//! Coordinates are `i32` like the rest of the drawing API, so callers can probe
9//! `x - 1` at the edge without casts; anything off-grid is reported as `None` /
10//! `false`, never a panic (GEN-R4). Index arithmetic is done in `usize` after the
11//! bounds check, because a `u16 × u16` area does not fit in `i32`.
12//!
13//! No `Index<(i32, i32)>` impl on purpose: `grid[(x - 1, y)]` reads naturally but
14//! panics on the edge, which is exactly the GEN-R4 failure mode. [`Grid::get`]
15//! plus `unwrap_or` is barely longer and cannot crash a scene.
16
17use std::iter::FusedIterator;
18
19use crate::Size;
20
21/// A dense `width × height` field of `T`, stored row-major (CORE-R33).
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Grid<T> {
24    // `u16` like `Size`, but kept separately because a grid may be 0×0 while a
25    // `Size` is always at least 1×1 (CORE-R1).
26    width: u16,
27    height: u16,
28    cells: Vec<T>,
29}
30
31/// The 0×0 grid (CORE-R33). Does not allocate, so it is the natural initial value
32/// for a scene field or a [`Grid::step`] scratch buffer before the first resize.
33impl<T> Default for Grid<T> {
34    fn default() -> Self {
35        Self {
36            width: 0,
37            height: 0,
38            cells: Vec::new(),
39        }
40    }
41}
42
43impl<T: Clone> Grid<T> {
44    /// A `size` grid with every cell set to `fill` (CORE-R33).
45    pub fn new(size: Size, fill: T) -> Self {
46        Self {
47            width: size.width(),
48            height: size.height(),
49            cells: vec![fill; size.area()],
50        }
51    }
52
53    /// Set every cell to `v` (CORE-R33).
54    pub fn fill(&mut self, v: T) {
55        self.cells.fill(v);
56    }
57
58    /// Change the dimensions, keeping every cell whose `(x, y)` exists in both the
59    /// old and the new size; new cells become `fill` (CORE-R34).
60    ///
61    /// Works in place: surviving cells are moved to their new row-major slot by
62    /// `swap`, which needs neither `Copy` nor extra clones. The buffer only grows
63    /// (never shrinks), so a shrink-then-grow on terminal resize does not allocate.
64    pub fn resize(&mut self, size: Size, fill: T) {
65        let (ow, oh) = (usize::from(self.width), usize::from(self.height));
66        let (nw, nh) = (usize::from(size.width()), usize::from(size.height()));
67        if (ow, oh) == (nw, nh) {
68            return;
69        }
70        let (mw, mh) = (ow.min(nw), oh.min(nh));
71        let new_len = nw * nh;
72
73        // Make room first so every destination index is valid during the moves.
74        if new_len > self.cells.len() {
75            self.cells.resize(new_len, fill.clone());
76        }
77
78        // Move each kept cell from `y*ow + x` to `y*nw + x`. The iteration order
79        // guarantees a source slot is never clobbered before it is read: when rows
80        // get narrower every destination is <= its source, so walk forwards; when
81        // they get wider every destination is >= its source, so walk backwards.
82        // The value swapped *into* a source slot is garbage that is later either
83        // overwritten by `fill` below or truncated away.
84        let mut shift = |y: usize, x: usize| self.cells.swap(y * ow + x, y * nw + x);
85        if nw <= ow {
86            (0..mh).for_each(|y| (0..mw).for_each(|x| shift(y, x)));
87        } else {
88            (0..mh)
89                .rev()
90                .for_each(|y| (0..mw).rev().for_each(|x| shift(y, x)));
91        }
92
93        self.cells.truncate(new_len);
94        // Everything outside the kept `mw × mh` rectangle is new.
95        if mw < nw {
96            for y in 0..mh {
97                self.cells[y * nw + mw..(y + 1) * nw].fill(fill.clone());
98            }
99        }
100        self.cells[mh * nw..].fill(fill);
101        self.width = size.width();
102        self.height = size.height();
103    }
104
105    /// Change the dimensions to `size` with every cell `fill`, discarding the contents
106    /// but reusing the buffer: the cheap reshape for a buffer about to be overwritten.
107    fn reshape(&mut self, size: Size, fill: T) {
108        self.cells.clear();
109        self.cells.resize(size.area(), fill);
110        self.width = size.width();
111        self.height = size.height();
112    }
113}
114
115impl<T> Grid<T> {
116    /// The grid's dimensions (CORE-R33).
117    ///
118    /// A `Size` cannot be 0×0 (CORE-R1), so for the empty [`Grid::default`] this
119    /// reports 1×1; use [`width`](Self::width)/[`height`](Self::height) or
120    /// [`is_empty`](Self::is_empty) when the grid may be empty.
121    #[inline]
122    pub fn size(&self) -> Size {
123        Size::new(self.width, self.height)
124    }
125
126    /// Number of columns; `0` only for the empty grid (CORE-R33).
127    #[inline]
128    pub fn width(&self) -> u16 {
129        self.width
130    }
131
132    /// Number of rows; `0` only for the empty grid (CORE-R33).
133    #[inline]
134    pub fn height(&self) -> u16 {
135        self.height
136    }
137
138    /// Number of cells, `width * height`.
139    #[inline]
140    pub fn len(&self) -> usize {
141        self.cells.len()
142    }
143
144    #[inline]
145    pub fn is_empty(&self) -> bool {
146        self.cells.is_empty()
147    }
148
149    /// Whether the grid is exactly `size` (never true for the empty grid).
150    #[inline]
151    fn size_is(&self, size: Size) -> bool {
152        (self.width, self.height) == (size.width(), size.height())
153    }
154
155    /// Row-major buffer index of `(x, y)`, or `None` off-grid.
156    ///
157    /// The bounds check happens in `i32` (so negative and huge values are simply
158    /// out of range) and only the validated values are widened to `usize` for the
159    /// multiply, which cannot overflow: `(65535 - 1) * 65535 + 65534 < usize::MAX`.
160    #[inline]
161    fn index(&self, x: i32, y: i32) -> Option<usize> {
162        let in_x = (0..i32::from(self.width)).contains(&x);
163        let in_y = (0..i32::from(self.height)).contains(&y);
164        (in_x && in_y).then(|| y as usize * usize::from(self.width) + x as usize)
165    }
166
167    /// The cell at `(x, y)`, or `None` off-grid; never panics (CORE-R33).
168    #[inline]
169    pub fn get(&self, x: i32, y: i32) -> Option<&T> {
170        self.index(x, y).map(|i| &self.cells[i])
171    }
172
173    /// Mutable access to the cell at `(x, y)`, or `None` off-grid (CORE-R33).
174    #[inline]
175    pub fn get_mut(&mut self, x: i32, y: i32) -> Option<&mut T> {
176        self.index(x, y).map(|i| &mut self.cells[i])
177    }
178
179    /// Store `v` at `(x, y)`; returns `false` (dropping `v`) off-grid (CORE-R33).
180    #[inline]
181    pub fn set(&mut self, x: i32, y: i32, v: T) -> bool {
182        match self.get_mut(x, y) {
183            Some(cell) => {
184                *cell = v;
185                true
186            }
187            None => false,
188        }
189    }
190
191    /// Every cell with its coordinates, in row-major order (CORE-R33).
192    pub fn iter(&self) -> Iter<'_, T> {
193        Iter {
194            cells: self.cells.iter(),
195            width: i32::from(self.width),
196            x: 0,
197            y: 0,
198        }
199    }
200
201    /// The row-major buffer: cell `(x, y)` is at `y * width + x` (CORE-R33).
202    #[inline]
203    pub fn as_slice(&self) -> &[T] {
204        &self.cells
205    }
206
207    /// Mutable row-major buffer, for bulk per-cell updates that need no coordinates.
208    #[inline]
209    pub fn as_mut_slice(&mut self) -> &mut [T] {
210        &mut self.cells
211    }
212
213    /// In-grid neighbour coordinates of `(x, y)`, excluding `(x, y)` itself
214    /// (CORE-R35). Yields nothing if `(x, y)` is off-grid.
215    ///
216    /// Order follows the offset table (row-major around the cell). With
217    /// [`Edges::Wrap`] on a grid narrower or shorter than 3, several offsets can
218    /// land on the same cell or on the cell itself; those are yielded once / skipped.
219    /// Allocation-free: a fixed offset table and an 8-slot inline "seen" list.
220    pub fn neighbors(&self, x: i32, y: i32, hood: Hood, edges: Edges) -> Neighbors {
221        let offsets: &'static [(i32, i32)] = match hood {
222            Hood::VonNeumann => &VON_NEUMANN,
223            Hood::Moore => &MOORE,
224        };
225        let (w, h) = (i32::from(self.width), i32::from(self.height));
226        Neighbors {
227            x,
228            y,
229            w,
230            h,
231            edges,
232            // An off-grid centre has no neighbourhood; starting exhausted also
233            // keeps the arithmetic below within `-1..=w` (no overflow possible).
234            offsets: if self.index(x, y).is_some() {
235                offsets
236            } else {
237                &[]
238            },
239            // Only small wrapped grids can alias; skip the de-dup work otherwise.
240            dedup: edges == Edges::Wrap && (w < 3 || h < 3),
241            seen: [(0, 0); 8],
242            n_seen: 0,
243        }
244    }
245
246    /// One synchronous update: every cell of the next generation is
247    /// `rule(&old, x, y)`, computed from the old grid only, then the buffers are
248    /// swapped (CORE-R36). Afterwards `scratch` holds the previous generation.
249    ///
250    /// `scratch` is rebuilt to this grid's size by clear-and-push, which keeps its
251    /// capacity, so after the first call the two buffers just ping-pong with no
252    /// allocation. This also means `T` needs no `Clone`/`Default` for the scratch.
253    pub fn step(&mut self, scratch: &mut Grid<T>, mut rule: impl FnMut(&Grid<T>, i32, i32) -> T) {
254        scratch.cells.clear();
255        scratch.cells.reserve_exact(self.cells.len());
256        for y in 0..i32::from(self.height) {
257            for x in 0..i32::from(self.width) {
258                scratch.cells.push(rule(self, x, y));
259            }
260        }
261        scratch.width = self.width;
262        scratch.height = self.height;
263        std::mem::swap(self, scratch);
264    }
265}
266
267/// Coordinate `d` on an axis of `dn` cells mapped onto an axis of `sn` cells with cell
268/// centres aligned, `(d + ½) / dn = (s + ½) / sn` (CORE-R43, CORE-R68): the convention of
269/// every resampler here and of [`SampleMap`]. `d` may be fractional (an agent's position,
270/// a pixel centre). Exact for equal sizes.
271#[inline]
272pub fn centre_of(d: f64, dn: usize, sn: usize) -> f64 {
273    (d + 0.5) * sn as f64 / dn as f64 - 0.5
274}
275
276/// Carry a continuous field onto a new lattice (ADR-0012, CORE-R68): `scratch` is
277/// reshaped to `size` (its old contents are discarded, its buffer reused), filled by
278/// [`resample_bilinear`] from `field`, and swapped in, so afterwards `field` has `size`
279/// and `scratch` holds the old field. No-op if `field` is empty or already `size`.
280pub fn regrid_bilinear(field: &mut Grid<f32>, size: Size, scratch: &mut Grid<f32>) {
281    if field.is_empty() || field.size_is(size) {
282        return;
283    }
284    scratch.reshape(size, 0.0);
285    resample_bilinear(field, scratch);
286    std::mem::swap(field, scratch);
287}
288
289/// [`regrid_bilinear`] for discrete states: nearest-neighbour via [`resample_nearest`]
290/// (CORE-R68), so only values present in `field` appear.
291pub fn regrid_nearest<T: Clone>(field: &mut Grid<T>, size: Size, scratch: &mut Grid<T>) {
292    if field.is_empty() || field.size_is(size) {
293        return;
294    }
295    // Any value will do as the placeholder: every cell is overwritten by the resample.
296    let fill = field.cells[0].clone();
297    scratch.reshape(size, fill);
298    resample_nearest(field, scratch);
299    std::mem::swap(field, scratch);
300}
301
302/// Fill `dst` (keeping its size) by bilinear sampling of `src`, cell-centre aligned and
303/// clamped at the edges (CORE-R43). No-op if either grid is empty; never allocates.
304///
305/// For moving a continuous field (concentration, ρ, u) onto a new simulation lattice
306/// after a resize (ADR-0012). Interpolation uses `a + (b − a)·f`, so a constant field
307/// comes through bit-exact, and equal sizes are the identity.
308pub fn resample_bilinear(src: &Grid<f32>, dst: &mut Grid<f32>) {
309    if src.is_empty() || dst.is_empty() {
310        return;
311    }
312    let (sw, sh) = (usize::from(src.width), usize::from(src.height));
313    let (dw, dh) = (usize::from(dst.width), usize::from(dst.height));
314    for (y, row) in dst.cells.chunks_exact_mut(dw).enumerate() {
315        let (y0, y1, fy) = bilinear_taps(y, dh, sh);
316        let (r0, r1) = (&src.cells[y0 * sw..][..sw], &src.cells[y1 * sw..][..sw]);
317        for (x, out) in row.iter_mut().enumerate() {
318            let (x0, x1, fx) = bilinear_taps(x, dw, sw);
319            *out = bilerp(r0[x0], r0[x1], r1[x0], r1[x1], fx, fy);
320        }
321    }
322}
323
324/// Neighbouring source indices and weight along one axis for destination index `d` of
325/// `dn` sampling a source of `sn ≥ 1` (CORE-R43): cell-centre aligned, edge-clamped.
326#[inline]
327fn bilinear_taps(d: usize, dn: usize, sn: usize) -> (usize, usize, f32) {
328    let s = centre_of(d as f64, dn, sn).clamp(0.0, (sn - 1) as f64);
329    let i0 = s as usize; // s ≥ 0, so truncation is floor
330    let i1 = (i0 + 1).min(sn - 1);
331    (i0, i1, (s - i0 as f64) as f32)
332}
333
334/// `a + (b − a)·f`, returning `a` itself at `f = 0` so constants survive bit-exactly.
335#[inline(always)]
336fn lerp32(a: f32, b: f32, f: f32) -> f32 {
337    if f == 0.0 { a } else { a + (b - a) * f }
338}
339
340/// Bilinear blend of a 2×2 neighbourhood: along x on both rows, then along y. The one
341/// formula shared by [`resample_bilinear`] and [`SampleMap::sample`] (CORE-R52).
342#[inline(always)]
343fn bilerp(top0: f32, top1: f32, bottom0: f32, bottom1: f32, fx: f32, fy: f32) -> f32 {
344    lerp32(lerp32(top0, top1, fx), lerp32(bottom0, bottom1, fx), fy)
345}
346
347/// Nearest source index for destination index `d`: `floor((d + ½)·sn/dn)` in integers,
348/// exact and the identity for equal sizes (CORE-R43).
349#[inline]
350fn nearest_tap(d: usize, dn: usize, sn: usize) -> usize {
351    ((2 * d + 1) * sn / (2 * dn)).min(sn - 1)
352}
353
354/// One axis of a [`SampleMap`]: the bilinear pair and weight, and the nearest index.
355/// `u16` indices suffice because grid axes are `u16`.
356#[derive(Debug, Clone, Copy, PartialEq)]
357struct Tap {
358    i0: u16,
359    i1: u16,
360    near: u16,
361    f: f32,
362}
363
364impl Tap {
365    fn new(d: usize, dn: usize, sn: usize) -> Self {
366        let (i0, i1, f) = bilinear_taps(d, dn, sn);
367        // Every index is < sn ≤ u16::MAX, so the narrowing is lossless.
368        Self {
369            i0: i0 as u16,
370            i1: i1 as u16,
371            near: nearest_tap(d, dn, sn) as u16,
372            f,
373        }
374    }
375}
376
377/// Precomputed per-axis sampling tables from a simulation lattice onto a display region
378/// (CORE-R52, ADR-0012): the per-cell work of [`resample_bilinear`] /
379/// [`resample_nearest`] without the float divisions, and without a destination grid,
380/// so a scene can sample its capped lattice straight into `Pixels` or `Dots`.
381///
382/// Built in `resize` with [`rebuild`](Self::rebuild); the tables allocate only when
383/// they grow. The [`Default`] map is empty: `sample` gives 0 and `nearest` `(0, 0)`.
384#[derive(Debug, Clone, Default)]
385pub struct SampleMap {
386    src: (u16, u16),
387    xs: Vec<Tap>,
388    ys: Vec<Tap>,
389    /// Catmull-Rom taps per axis (CORE-R102).
390    cxs: Vec<Cubic>,
391    cys: Vec<Cubic>,
392    magnification: f32,
393}
394
395/// One axis of a [`SampleMap`]'s cubic mode: four edge-clamped source indices around
396/// the sample point and their Catmull-Rom weights (CORE-R102).
397#[derive(Debug, Clone, Copy, PartialEq)]
398struct Cubic {
399    i: [u16; 4],
400    w: [f32; 4],
401}
402
403impl Cubic {
404    fn new(d: usize, dn: usize, sn: usize) -> Self {
405        // The bilinear pair is taps 1 and 2; the outer two are one further out, clamped.
406        let s = centre_of(d as f64, dn, sn).clamp(0.0, (sn.max(1) - 1) as f64);
407        let i1 = s as usize; // s ≥ 0, so truncation is floor
408        let last = sn.max(1) - 1;
409        let t = s - i1 as f64;
410        let (t2, t3) = (t * t, t * t * t);
411        let w = [
412            0.5 * (-t3 + 2.0 * t2 - t),
413            0.5 * (3.0 * t3 - 5.0 * t2 + 2.0),
414            0.5 * (-3.0 * t3 + 4.0 * t2 + t),
415            0.5 * (t3 - t2),
416        ];
417        // Every index is < sn ≤ u16::MAX, so the narrowing is lossless.
418        Self {
419            i: [
420                i1.saturating_sub(1) as u16,
421                i1 as u16,
422                (i1 + 1).min(last) as u16,
423                (i1 + 2).min(last) as u16,
424            ],
425            w: w.map(|w| w as f32),
426        }
427    }
428}
429
430/// One destination row of a [`SampleMap`]'s cubic mode over one source grid
431/// (CORE-R102), from [`SampleMap::row_cubic`].
432#[derive(Debug, Clone, Copy)]
433pub struct CubicRow<'a> {
434    xs: &'a [Cubic],
435    rows: [&'a [f32]; 4],
436    wy: [f32; 4],
437}
438
439impl CubicRow<'_> {
440    /// Catmull-Rom value at destination column `x` (clamped onto the region): 16
441    /// multiply-adds, clamped to the four central source values' range.
442    #[inline(always)]
443    pub fn at(&self, x: i32) -> f32 {
444        let Some(last) = self.xs.len().checked_sub(1) else {
445            return 0.0;
446        };
447        if self.rows[0].is_empty() {
448            return 0.0;
449        }
450        let tx = self.xs[usize::try_from(x).map_or(0, |i| i.min(last))];
451        let [a, b, c, d] = tx.i.map(usize::from);
452        let across = |r: &[f32]| tx.w[0] * r[a] + tx.w[1] * r[b] + tx.w[2] * r[c] + tx.w[3] * r[d];
453        let v = self.wy[0] * across(self.rows[0])
454            + self.wy[1] * across(self.rows[1])
455            + self.wy[2] * across(self.rows[2])
456            + self.wy[3] * across(self.rows[3]);
457        let (r1, r2) = (self.rows[1], self.rows[2]);
458        let lo = r1[b].min(r1[c]).min(r2[b]).min(r2[c]);
459        let hi = r1[b].max(r1[c]).max(r2[b]).max(r2[c]);
460        // `max` then `min` also maps a NaN sum onto the range's low end.
461        v.max(lo).min(hi)
462    }
463}
464
465impl SampleMap {
466    /// Tables for sampling a `src` grid at every cell of a `dst` region, with the
467    /// cell-centre, edge-clamp convention of [`resample_bilinear`] (CORE-R52).
468    pub fn rebuild(&mut self, src: Size, dst: Size) {
469        let (sw, sh) = (usize::from(src.width()), usize::from(src.height()));
470        let (dw, dh) = (usize::from(dst.width()), usize::from(dst.height()));
471        self.src = (src.width(), src.height());
472        self.xs.clear();
473        self.xs.extend((0..dw).map(|x| Tap::new(x, dw, sw)));
474        self.ys.clear();
475        self.ys.extend((0..dh).map(|y| Tap::new(y, dh, sh)));
476        self.cxs.clear();
477        self.cxs.extend((0..dw).map(|x| Cubic::new(x, dw, sw)));
478        self.cys.clear();
479        self.cys.extend((0..dh).map(|y| Cubic::new(y, dh, sh)));
480        let ratio = |d: usize, s: usize| if s == 0 { 0.0 } else { d as f32 / s as f32 };
481        self.magnification = if dw == 0 || dh == 0 {
482            0.0
483        } else {
484            ratio(dw, sw).max(ratio(dh, sh))
485        };
486    }
487
488    /// How many destination cells span one source cell, along the more magnified axis
489    /// (0 for the empty map). GEN-R17: bilinear up to 2, [`sample_cubic`](Self::sample_cubic)
490    /// above it.
491    #[inline]
492    pub fn magnification(&self) -> f32 {
493        self.magnification
494    }
495
496    /// Separable Catmull-Rom value of `src` at destination cell `(x, y)` (clamped onto
497    /// the region), CORE-R102: 4 × 4 taps with weights from the `rebuild` tables (no
498    /// transcendental maths), clamped to the range of the four central source values so
499    /// it never overshoots into a new colour. Exact at source centres for equal sizes;
500    /// a wrong-size source or the empty map gives 0, as [`sample`](Self::sample).
501    #[inline]
502    pub fn sample_cubic(&self, src: &Grid<f32>, x: i32, y: i32) -> f32 {
503        self.row_cubic(src, y).at(x)
504    }
505
506    /// Row `y` (clamped) of [`sample_cubic`](Self::sample_cubic) with its four source
507    /// rows and weights looked up once (CORE-R102, as [`row`](Self::row)).
508    #[inline(always)]
509    pub fn row_cubic<'a>(&'a self, src: &'a Grid<f32>, y: i32) -> CubicRow<'a> {
510        let mut out = CubicRow {
511            xs: &[],
512            rows: [&[]; 4],
513            wy: [0.0; 4],
514        };
515        if (src.width, src.height) != self.src {
516            return out;
517        }
518        let Some(last) = self.cys.len().checked_sub(1) else {
519            return out;
520        };
521        let ty = self.cys[usize::try_from(y).map_or(0, |i| i.min(last))];
522        let w = usize::from(src.width);
523        for (row, &i) in out.rows.iter_mut().zip(&ty.i) {
524            *row = &src.cells[usize::from(i) * w..][..w];
525        }
526        out.xs = &self.cxs;
527        out.wy = ty.w;
528        out
529    }
530
531    /// Taps for destination `(x, y)`, clamped onto the table.
532    #[inline(always)]
533    fn taps(&self, x: i32, y: i32) -> Option<(Tap, Tap)> {
534        let pick = |t: &[Tap], i: i32| {
535            let last = t.len().checked_sub(1)?;
536            // Negative ⇒ 0, beyond ⇒ last: `usize::try_from` fails only for negatives.
537            Some(t[usize::try_from(i).map_or(0, |i| i.min(last))])
538        };
539        Some((pick(&self.xs, x)?, pick(&self.ys, y)?))
540    }
541
542    /// Bilinear value of `src` at destination cell `(x, y)` (clamped onto the region),
543    /// bit-identical to [`resample_bilinear`]'s output for that cell (CORE-R52).
544    ///
545    /// `src` must have the size passed to [`rebuild`](Self::rebuild); any other size
546    /// (a caller bug) and the empty map give 0.
547    #[inline(always)]
548    pub fn sample(&self, src: &Grid<f32>, x: i32, y: i32) -> f32 {
549        if (src.width, src.height) != self.src {
550            return 0.0;
551        }
552        let Some((tx, ty)) = self.taps(x, y) else {
553            return 0.0;
554        };
555        let w = usize::from(src.width);
556        let row = |i: u16| &src.cells[usize::from(i) * w..][..w];
557        let (r0, r1) = (row(ty.i0), row(ty.i1));
558        let (x0, x1) = (usize::from(tx.i0), usize::from(tx.i1));
559        bilerp(r0[x0], r0[x1], r1[x0], r1[x1], tx.f, ty.f)
560    }
561
562    /// Row `y` of the destination region (clamped onto it) as a [`MapRow`]: its two
563    /// source rows and weight looked up once, so sampling a whole row costs one x-tap
564    /// per cell (CORE-R104). `row(src, y).at(x)` is bit-identical to
565    /// [`sample(src, x, y)`](Self::sample), including 0 for the empty map or a source of
566    /// another size.
567    #[inline(always)]
568    pub fn row<'a>(&'a self, src: &'a Grid<f32>, y: i32) -> MapRow<'a> {
569        let empty = MapRow {
570            xs: &[],
571            r0: &[],
572            r1: &[],
573            fy: 0.0,
574        };
575        if (src.width, src.height) != self.src {
576            return empty;
577        }
578        let Some(last) = self.ys.len().checked_sub(1) else {
579            return empty;
580        };
581        let ty = self.ys[usize::try_from(y).map_or(0, |i| i.min(last))];
582        let w = usize::from(src.width);
583        let row = |i: u16| &src.cells[usize::from(i) * w..][..w];
584        MapRow {
585            xs: &self.xs,
586            r0: row(ty.i0),
587            r1: row(ty.i1),
588            fy: ty.f,
589        }
590    }
591
592    /// The source cell nearest to destination cell `(x, y)` (clamped onto the region),
593    /// the one [`resample_nearest`] copies; `(0, 0)` for the empty map (CORE-R52).
594    #[inline(always)]
595    pub fn nearest(&self, x: i32, y: i32) -> (i32, i32) {
596        self.taps(x, y)
597            .map_or((0, 0), |(tx, ty)| (i32::from(tx.near), i32::from(ty.near)))
598    }
599}
600
601/// One destination row of a [`SampleMap`] over one source grid (CORE-R104), from
602/// [`SampleMap::row`]: hoist it out of the x loop (or rebuild it when `y` changes inside
603/// a [`Pixels::shade`](crate::raster::Pixels::shade) closure).
604#[derive(Debug, Clone, Copy)]
605pub struct MapRow<'a> {
606    xs: &'a [Tap],
607    r0: &'a [f32],
608    r1: &'a [f32],
609    fy: f32,
610}
611
612impl MapRow<'_> {
613    /// Bilinear value at destination column `x` (clamped onto the region), bit-identical
614    /// to [`SampleMap::sample`] for this row.
615    #[inline(always)]
616    pub fn at(&self, x: i32) -> f32 {
617        let Some(last) = self.xs.len().checked_sub(1) else {
618            return 0.0;
619        };
620        if self.r0.is_empty() {
621            return 0.0;
622        }
623        let tx = self.xs[usize::try_from(x).map_or(0, |i| i.min(last))];
624        let (x0, x1) = (usize::from(tx.i0), usize::from(tx.i1));
625        bilerp(
626            self.r0[x0],
627            self.r0[x1],
628            self.r1[x0],
629            self.r1[x1],
630            tx.f,
631            self.fy,
632        )
633    }
634}
635
636/// The isotropic 9-point Laplacian of `src` into `dst` at unit spacing (CORE-R53):
637/// `(4·(N + S + E + W) + (NE + NW + SE + SW) − 20·c) / 6`.
638///
639/// `Edges::Wrap` is periodic; `Edges::Clip` is zero-flux (Neumann): a ghost cell beyond
640/// a wall repeats the edge cell next to it, so nothing flows through the wall. `dst` is
641/// reshaped to `src` (reusing its buffer when large enough).
642///
643/// Its error is isotropic to leading order, so reaction–diffusion spots stay round
644/// instead of going square on the lattice. Mirror pairs are added first (`W + E`,
645/// `N + S`, `NW + NE`, `SW + SE`), and float addition is commutative, so a mirrored
646/// field gives a bitwise mirrored result and symmetric patterns stay symmetric forever.
647pub fn laplacian9(src: &Grid<f32>, dst: &mut Grid<f32>, edges: Edges) {
648    let (w, h) = (usize::from(src.width), usize::from(src.height));
649    dst.cells.clear();
650    dst.cells.resize(w * h, 0.0);
651    dst.width = src.width;
652    dst.height = src.height;
653    if w == 0 || h == 0 {
654        return;
655    }
656    // Previous/next index along an axis of length n under the edge rule.
657    let around = |i: usize, n: usize| match edges {
658        Edges::Wrap => ((i + n - 1) % n, (i + 1) % n),
659        Edges::Clip => (i.saturating_sub(1), (i + 1).min(n - 1)),
660    };
661    let row = |y: usize| &src.cells[y * w..][..w];
662    for (y, out) in dst.cells.chunks_exact_mut(w).enumerate() {
663        let (yn, ys) = around(y, h);
664        let (north, mid, south) = (row(yn), row(y), row(ys));
665        for (x, o) in out.iter_mut().enumerate() {
666            let (xw, xe) = around(x, w);
667            let orth = (mid[xw] + mid[xe]) + (north[x] + south[x]);
668            let diag = (north[xw] + north[xe]) + (south[xw] + south[xe]);
669            *o = (4.0 * orth + diag - 20.0 * mid[x]) / 6.0;
670        }
671    }
672}
673
674/// Fill `dst` (keeping its size) by nearest-neighbour sampling of `src`, cell-centre
675/// aligned (CORE-R43), so only values present in `src` appear. For discrete states such
676/// as Ising spins. No-op if either grid is empty; never allocates.
677pub fn resample_nearest<T: Clone>(src: &Grid<T>, dst: &mut Grid<T>) {
678    if src.is_empty() || dst.is_empty() {
679        return;
680    }
681    let (sw, sh) = (usize::from(src.width), usize::from(src.height));
682    let (dw, dh) = (usize::from(dst.width), usize::from(dst.height));
683    for (y, row) in dst.cells.chunks_exact_mut(dw).enumerate() {
684        let src_row = &src.cells[nearest_tap(y, dh, sh) * sw..][..sw];
685        for (x, out) in row.iter_mut().enumerate() {
686            out.clone_from(&src_row[nearest_tap(x, dw, sw)]);
687        }
688    }
689}
690
691/// A capped simulation lattice for a display region measured in square units
692/// (ADR-0012, CORE-R48).
693///
694/// The display aspect `w / h` is snapped to the nearest power of `bucket` (e.g. 1.25;
695/// `bucket ≤ 1` or NaN keeps the exact aspect), and the result is the largest lattice of
696/// that aspect with `w·h ≤ max_nodes`, clamped per axis to the display (so small
697/// displays simulate at display size) and at least 1×1 (`max_nodes = 0` ⇒ 1×1).
698///
699/// Because the uncapped shape depends only on the bucket and `max_nodes`, any display at
700/// least that large in both axes, within one bucket, maps to the same lattice: resizing
701/// there never touches simulation state.
702pub fn lattice_for(display: Size, max_nodes: usize, bucket: f64) -> Size {
703    if max_nodes == 0 {
704        return Size::new(1, 1);
705    }
706    let (dw, dh) = (display.width(), display.height());
707    let aspect = f64::from(dw) / f64::from(dh);
708    let snapped = if bucket > 1.0 {
709        let step = bucket.ln();
710        ((aspect.ln() / step).round() * step).exp()
711    } else {
712        aspect
713    };
714    // Degenerate buckets (∞, 1 + ε) can produce 0, ∞ or NaN here: fall back to exact.
715    let aspect = if snapped.is_finite() && snapped > 0.0 {
716        snapped
717    } else {
718        aspect
719    };
720    let full = lattice_for_aspect(aspect, max_nodes);
721    Size::new(full.width().min(dw), full.height().min(dh))
722}
723
724/// The largest lattice of aspect `w / h ≈ aspect` with `w·h ≤ max_nodes`, at least 1×1
725/// and at most `u16::MAX` per axis (CORE-R69): the uncapped shape behind [`lattice_for`],
726/// for a scene that picks its own aspect (say, a fixed-bucket channel) rather than a
727/// display's. Never panics: a zero, negative or NaN `aspect` gives 1 column, and `max_nodes
728/// = 0` gives 1×1.
729pub fn lattice_for_aspect(aspect: f64, max_nodes: usize) -> Size {
730    if max_nodes == 0 {
731        return Size::new(1, 1);
732    }
733    // h·(aspect·h) = max_nodes. Flooring both axes (and the w ≤ max/h guard for float
734    // round-off and the 1-wide/1-tall extremes) keeps w·h ≤ max_nodes; the float → usize
735    // casts saturate (NaN ⇒ 0), so the clamps also absorb degenerate aspects.
736    let h_ideal = (max_nodes as f64 / aspect).sqrt();
737    let h = (h_ideal as usize).clamp(1, max_nodes);
738    let w = ((h_ideal * aspect) as usize).clamp(1, max_nodes / h);
739    let axis = |n: usize| u16::try_from(n).unwrap_or(u16::MAX);
740    Size::new(axis(w), axis(h))
741}
742
743/// Which cells count as neighbours (CORE-R35).
744#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
745pub enum Hood {
746    /// The 4 orthogonal cells.
747    VonNeumann,
748    /// The 8 orthogonal and diagonal cells.
749    Moore,
750}
751
752/// What happens at the border (CORE-R35).
753#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
754pub enum Edges {
755    /// Off-grid neighbours are dropped.
756    Clip,
757    /// The grid is a torus: coordinates wrap around both axes.
758    Wrap,
759}
760
761// Row-major around the centre, so iteration order is stable and predictable.
762const VON_NEUMANN: [(i32, i32); 4] = [(0, -1), (-1, 0), (1, 0), (0, 1)];
763const MOORE: [(i32, i32); 8] = [
764    (-1, -1),
765    (0, -1),
766    (1, -1),
767    (-1, 0),
768    (1, 0),
769    (-1, 1),
770    (0, 1),
771    (1, 1),
772];
773
774/// Row-major iterator over `((x, y), &cell)`, from [`Grid::iter`] (CORE-R33).
775///
776/// Tracks `x`/`y` incrementally instead of dividing the flat index each step.
777#[derive(Debug, Clone)]
778pub struct Iter<'a, T> {
779    cells: std::slice::Iter<'a, T>,
780    width: i32,
781    x: i32,
782    y: i32,
783}
784
785impl<'a, T> Iterator for Iter<'a, T> {
786    type Item = ((i32, i32), &'a T);
787
788    #[inline]
789    fn next(&mut self) -> Option<Self::Item> {
790        let cell = self.cells.next()?;
791        let pos = (self.x, self.y);
792        self.x += 1;
793        if self.x == self.width {
794            self.x = 0;
795            self.y += 1;
796        }
797        Some((pos, cell))
798    }
799
800    #[inline]
801    fn size_hint(&self) -> (usize, Option<usize>) {
802        self.cells.size_hint()
803    }
804}
805
806impl<T> ExactSizeIterator for Iter<'_, T> {}
807impl<T> FusedIterator for Iter<'_, T> {}
808
809/// Neighbour coordinates of one cell, from [`Grid::neighbors`] (CORE-R35).
810///
811/// Holds no borrow of the grid, so a caller can iterate neighbours while mutating
812/// the grid (e.g. to scatter into them).
813#[derive(Debug, Clone)]
814pub struct Neighbors {
815    x: i32,
816    y: i32,
817    w: i32,
818    h: i32,
819    edges: Edges,
820    offsets: &'static [(i32, i32)],
821    dedup: bool,
822    seen: [(i32, i32); 8],
823    n_seen: usize,
824}
825
826impl Iterator for Neighbors {
827    type Item = (i32, i32);
828
829    fn next(&mut self) -> Option<(i32, i32)> {
830        while let Some((&(dx, dy), rest)) = self.offsets.split_first() {
831            self.offsets = rest;
832            // The centre is in-grid (checked at construction), so these are in
833            // `-1..=w` / `-1..=h` and cannot overflow.
834            let (mut nx, mut ny) = (self.x + dx, self.y + dy);
835            match self.edges {
836                Edges::Clip => {
837                    if !(0..self.w).contains(&nx) || !(0..self.h).contains(&ny) {
838                        continue;
839                    }
840                }
841                Edges::Wrap => {
842                    nx = nx.rem_euclid(self.w);
843                    ny = ny.rem_euclid(self.h);
844                }
845            }
846            if self.dedup {
847                let p = (nx, ny);
848                if p == (self.x, self.y) || self.seen[..self.n_seen].contains(&p) {
849                    continue;
850                }
851                self.seen[self.n_seen] = p;
852                self.n_seen += 1;
853            }
854            return Some((nx, ny));
855        }
856        None
857    }
858
859    #[inline]
860    fn size_hint(&self) -> (usize, Option<usize>) {
861        (0, Some(self.offsets.len()))
862    }
863}
864
865impl FusedIterator for Neighbors {}