Skip to main content

crcbl_water/
body.rs

1//! A body of water and the medium inside it, and what makes one well formed.
2
3/// What light meets inside a body of water, per colour channel.
4///
5/// The parameter set `docs/plan/55-water.md`'s second decision gives every body
6/// kind: an **absorption** coefficient, the fraction of light turned into heat
7/// per metre, and a **scattering** coefficient, the fraction sent in a new
8/// direction per metre. Both are in **1/m**, one value per linear-RGB channel,
9/// and their sum is the extinction — how fast light travelling through the body
10/// is lost to either. Clear water absorbs red fastest and blue slowest, which is
11/// why a deep pool reads blue-green; a muddy pond scatters more.
12///
13/// **There is no phase asymmetry here yet**, though that decision lists one. The
14/// renderer's rung 1 scatters the ambient and the sun's light isotropically, so
15/// an anisotropy field would be a number no reader looks at; the rung whose
16/// shading has a direction to weigh adds it.
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct Medium {
19    /// Absorption per metre, per linear-RGB channel.
20    pub absorption: [f32; 3],
21    /// Scattering per metre, per linear-RGB channel.
22    pub scattering: [f32; 3],
23}
24
25/// One body of water: a closed outline on the XZ plane, the height its surface
26/// sits at, and what it is made of.
27///
28/// The outline is a **simple polygon** — convex or not, wound either way, with
29/// no edge touching or crossing another — and it is closed implicitly: the last
30/// point joins the first. [`crate::surface_mesh`] refuses one that is not,
31/// rather than drawing a surface with a hole or a fold in it.
32#[derive(Clone, Debug, PartialEq)]
33pub struct WaterBody {
34    /// The surface's boundary, as `[x, z]` points in metres.
35    pub outline: Vec<[f32; 2]>,
36    /// The surface's height, in metres.
37    pub level: f32,
38    /// What the water is made of.
39    pub medium: Medium,
40}
41
42/// Why a [`WaterBody`] cannot be meshed.
43#[derive(Clone, Debug, PartialEq, thiserror::Error)]
44pub enum BodyError {
45    /// The outline has fewer than three points, so it encloses nothing.
46    #[error("an outline needs at least three points, and this one has {count}")]
47    TooFewPoints {
48        /// How many it has.
49        count: usize,
50    },
51    /// An outline point has a coordinate that is not a finite number.
52    #[error("outline point {index} is {point:?}, which is not a finite position")]
53    NonFinitePoint {
54        /// Which point.
55        index: usize,
56        /// The point as given.
57        point: [f32; 2],
58    },
59    /// Two consecutive outline points are the same point, so the edge between
60    /// them has no direction.
61    #[error("outline points {index} and the one after it are both {point:?}")]
62    RepeatedPoint {
63        /// The first of the two.
64        index: usize,
65        /// The point both are.
66        point: [f32; 2],
67    },
68    /// The level is not a finite number.
69    #[error("the water level {level} is not a finite height")]
70    NonFiniteLevel {
71        /// The level as given.
72        level: f32,
73    },
74    /// A medium coefficient is negative or not finite. A negative absorption
75    /// would add light with depth rather than remove it.
76    #[error("the medium's {which} is {values:?}; each channel must be finite and at least zero")]
77    InvalidMedium {
78        /// `"absorption"` or `"scattering"`.
79        which: &'static str,
80        /// The three channels as given.
81        values: [f32; 3],
82    },
83    /// The outline's points all lie on one line, so it encloses no area.
84    #[error("the outline encloses no area")]
85    NoArea,
86    /// Two edges of the outline touch or cross, so it is not a simple polygon.
87    #[error("outline edges {first} and {second} touch or cross")]
88    SelfIntersecting {
89        /// The edge starting at this point index.
90        first: usize,
91        /// The edge starting at this point index.
92        second: usize,
93    },
94    /// The grid spacing is not a finite, positive length.
95    #[error("a grid spacing of {spacing} is not a finite positive length")]
96    InvalidSpacing {
97        /// The spacing as given.
98        spacing: f32,
99    },
100    /// The surface meshes to more vertices than a `u32` index can address.
101    #[error("the surface meshes to more vertices than a u32 index addresses")]
102    TooManyVertices,
103    /// The outline's bounds hold more grid cells than [`crate::MAX_GRID_CELLS`].
104    #[error("the outline's bounds hold {cells} grid cells at this spacing, past the {max} allowed")]
105    TooManyCells {
106        /// How many cells the bounds hold, saturating.
107        cells: u64,
108        /// [`crate::MAX_GRID_CELLS`].
109        max: u64,
110    },
111}
112
113impl Medium {
114    /// Refuses a coefficient that is negative or not finite.
115    pub(crate) fn validate(&self) -> Result<(), BodyError> {
116        for (which, values) in [
117            ("absorption", self.absorption),
118            ("scattering", self.scattering),
119        ] {
120            // Written so a `NaN` fails: every comparison against one is false.
121            if !values
122                .iter()
123                .all(|value| value.is_finite() && *value >= 0.0)
124            {
125                return Err(BodyError::InvalidMedium { which, values });
126            }
127        }
128        Ok(())
129    }
130}
131
132/// `(b - a) × (c - a)` on the XZ plane, in `f64`: positive when `a`, `b`, `c`
133/// turn counter-clockwise with `x` across and `z` up the page.
134///
135/// `f64` because the sign is what every decision in this crate reads, and a
136/// nearly collinear corner is decided with more than twice the precision the
137/// `f32` coordinates carry. It is **not** an exact predicate — Shewchuk's
138/// adaptive arithmetic would be — and nothing here relies on one: a corner
139/// misjudged by rounding is one whose triangle has no area to lose.
140pub(crate) fn orient(a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> f64 {
141    let (ax, az) = (f64::from(a[0]), f64::from(a[1]));
142    (f64::from(b[0]) - ax) * (f64::from(c[1]) - az)
143        - (f64::from(b[1]) - az) * (f64::from(c[0]) - ax)
144}
145
146impl WaterBody {
147    /// Refuses a body [`crate::surface_mesh`] could not mesh faithfully: too few
148    /// points, a non-finite coordinate or level, a repeated point, an invalid
149    /// medium, no area, or an outline that touches or crosses itself.
150    ///
151    /// The self-intersection test compares every pair of edges, which is
152    /// quadratic in the outline's length — a pool's outline is tens of points,
153    /// and a body is validated when it is set rather than every frame.
154    pub(crate) fn validate(&self) -> Result<(), BodyError> {
155        let outline = &self.outline;
156        if outline.len() < 3 {
157            return Err(BodyError::TooFewPoints {
158                count: outline.len(),
159            });
160        }
161        if let Some((index, point)) = outline
162            .iter()
163            .enumerate()
164            .find(|(_, point)| !(point[0].is_finite() && point[1].is_finite()))
165        {
166            return Err(BodyError::NonFinitePoint {
167                index,
168                point: *point,
169            });
170        }
171        if !self.level.is_finite() {
172            return Err(BodyError::NonFiniteLevel { level: self.level });
173        }
174        self.medium.validate()?;
175        let count = outline.len();
176        for index in 0..count {
177            if outline[index] == outline[(index + 1) % count] {
178                return Err(BodyError::RepeatedPoint {
179                    index,
180                    point: outline[index],
181                });
182            }
183        }
184        if signed_area(outline) == 0.0 {
185            return Err(BodyError::NoArea);
186        }
187        for first in 0..count {
188            for second in first + 1..count {
189                if edges_meet(outline, first, second) {
190                    return Err(BodyError::SelfIntersecting { first, second });
191                }
192            }
193        }
194        Ok(())
195    }
196}
197
198/// Twice the outline's signed area, positive when it winds counter-clockwise in
199/// [`orient`]'s sense — the shoelace sum, in `f64`.
200pub(crate) fn signed_area(outline: &[[f32; 2]]) -> f64 {
201    let origin = outline[0];
202    (1..outline.len() - 1)
203        .map(|index| orient(origin, outline[index], outline[index + 1]))
204        .sum()
205}
206
207/// Whether edges `first` and `second` of `outline` — each from a point to the
208/// next — share any point they should not.
209///
210/// Two edges that follow one another share their joint and nothing else is
211/// allowed: the far end of either lying on the other is a fold back along
212/// itself. Any other pair may share nothing at all, touching included.
213fn edges_meet(outline: &[[f32; 2]], first: usize, second: usize) -> bool {
214    let count = outline.len();
215    let (a, b) = (outline[first], outline[(first + 1) % count]);
216    let (c, d) = (outline[second], outline[(second + 1) % count]);
217    if (first + 1) % count == second {
218        // `b == c` is the joint: the edges fold if `d` lies on `ab` or `a` on
219        // `cd`, which for two segments from one point means they are collinear
220        // and pointing the same way.
221        return on_segment(a, b, d) || on_segment(c, d, a);
222    }
223    if (second + 1) % count == first {
224        return on_segment(c, d, b) || on_segment(a, b, c);
225    }
226    segments_meet(a, b, c, d)
227}
228
229/// Whether `p` lies on the closed segment `ab`.
230fn on_segment(a: [f32; 2], b: [f32; 2], p: [f32; 2]) -> bool {
231    orient(a, b, p) == 0.0 && within(a[0], b[0], p[0]) && within(a[1], b[1], p[1])
232}
233
234/// Whether `value` lies between `a` and `b`, inclusive, in either order.
235fn within(a: f32, b: f32, value: f32) -> bool {
236    a.min(b) <= value && value <= a.max(b)
237}
238
239/// Whether the closed segments `ab` and `cd` share a point — the textbook
240/// orientation test, with the collinear cases decided by [`on_segment`].
241fn segments_meet(a: [f32; 2], b: [f32; 2], c: [f32; 2], d: [f32; 2]) -> bool {
242    let abc = orient(a, b, c);
243    let abd = orient(a, b, d);
244    let cda = orient(c, d, a);
245    let cdb = orient(c, d, b);
246    if ((abc > 0.0 && abd < 0.0) || (abc < 0.0 && abd > 0.0))
247        && ((cda > 0.0 && cdb < 0.0) || (cda < 0.0 && cdb > 0.0))
248    {
249        return true;
250    }
251    on_segment(a, b, c) || on_segment(a, b, d) || on_segment(c, d, a) || on_segment(c, d, b)
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    const CLEAR: Medium = Medium {
259        absorption: [0.4, 0.1, 0.05],
260        scattering: [0.01, 0.01, 0.01],
261    };
262
263    fn body(outline: &[[f32; 2]]) -> WaterBody {
264        WaterBody {
265            outline: outline.to_vec(),
266            level: 0.0,
267            medium: CLEAR,
268        }
269    }
270
271    #[test]
272    fn a_square_is_well_formed_either_way_round() {
273        let square = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]];
274        assert_eq!(body(&square).validate(), Ok(()));
275        let mut reversed = square;
276        reversed.reverse();
277        assert_eq!(body(&reversed).validate(), Ok(()));
278        assert_eq!(signed_area(&square), 8.0);
279        assert_eq!(signed_area(&reversed), -8.0);
280    }
281
282    #[test]
283    fn a_concave_outline_is_well_formed() {
284        let ell = [
285            [0.0, 0.0],
286            [3.0, 0.0],
287            [3.0, 1.0],
288            [1.0, 1.0],
289            [1.0, 3.0],
290            [0.0, 3.0],
291        ];
292        assert_eq!(body(&ell).validate(), Ok(()));
293    }
294
295    #[test]
296    fn too_few_points_are_refused() {
297        assert_eq!(
298            body(&[[0.0, 0.0], [1.0, 0.0]]).validate(),
299            Err(BodyError::TooFewPoints { count: 2 })
300        );
301    }
302
303    #[test]
304    fn a_non_finite_point_or_level_is_refused() {
305        let outline = [[0.0, 0.0], [f32::NAN, 0.0], [0.0, 1.0]];
306        assert!(matches!(
307            body(&outline).validate(),
308            Err(BodyError::NonFinitePoint { index: 1, .. })
309        ));
310        let mut level = body(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]);
311        level.level = f32::INFINITY;
312        assert!(matches!(
313            level.validate(),
314            Err(BodyError::NonFiniteLevel { .. })
315        ));
316    }
317
318    #[test]
319    fn a_repeated_point_is_refused() {
320        let outline = [[0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
321        assert_eq!(
322            body(&outline).validate(),
323            Err(BodyError::RepeatedPoint {
324                index: 1,
325                point: [1.0, 0.0]
326            })
327        );
328        // And the closing edge, from the last point back to the first.
329        let closing = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]];
330        assert!(matches!(
331            body(&closing).validate(),
332            Err(BodyError::RepeatedPoint { index: 3, .. })
333        ));
334    }
335
336    #[test]
337    fn a_collinear_outline_has_no_area() {
338        let line = [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]];
339        assert_eq!(body(&line).validate(), Err(BodyError::NoArea));
340    }
341
342    #[test]
343    fn a_bow_tie_crosses_itself() {
344        // Lopsided, so its two lobes do not cancel to no area at all — that
345        // outline would be refused as `NoArea` before its edges were compared.
346        let bow_tie = [[0.0, 0.0], [2.0, 2.0], [2.0, 0.0], [0.0, 1.0]];
347        assert_eq!(
348            body(&bow_tie).validate(),
349            Err(BodyError::SelfIntersecting {
350                first: 0,
351                second: 2
352            })
353        );
354    }
355
356    #[test]
357    fn an_edge_touching_a_corner_is_refused() {
358        // Point 4 sits on edge 0's span: the outline pinches there.
359        let pinched = [
360            [0.0, 0.0],
361            [4.0, 0.0],
362            [4.0, 2.0],
363            [3.0, 2.0],
364            [2.0, 0.0],
365            [0.0, 2.0],
366        ];
367        assert!(matches!(
368            body(&pinched).validate(),
369            Err(BodyError::SelfIntersecting { .. })
370        ));
371    }
372
373    #[test]
374    fn a_fold_back_along_an_edge_is_refused() {
375        // Point 2 walks back along edge 0 toward where it started.
376        let spike = [[0.0, 0.0], [2.0, 0.0], [1.0, 0.0], [1.0, 1.0]];
377        assert!(matches!(
378            body(&spike).validate(),
379            Err(BodyError::SelfIntersecting { .. })
380        ));
381    }
382
383    #[test]
384    fn a_negative_or_non_finite_coefficient_is_refused() {
385        let mut negative = body(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]);
386        negative.medium.absorption[1] = -0.1;
387        assert!(matches!(
388            negative.validate(),
389            Err(BodyError::InvalidMedium {
390                which: "absorption",
391                ..
392            })
393        ));
394        let mut not_a_number = body(&[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]);
395        not_a_number.medium.scattering[2] = f32::NAN;
396        assert!(matches!(
397            not_a_number.validate(),
398            Err(BodyError::InvalidMedium {
399                which: "scattering",
400                ..
401            })
402        ));
403    }
404}