1#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct Medium {
19 pub absorption: [f32; 3],
21 pub scattering: [f32; 3],
23}
24
25#[derive(Clone, Debug, PartialEq)]
33pub struct WaterBody {
34 pub outline: Vec<[f32; 2]>,
36 pub level: f32,
38 pub medium: Medium,
40}
41
42#[derive(Clone, Debug, PartialEq, thiserror::Error)]
44pub enum BodyError {
45 #[error("an outline needs at least three points, and this one has {count}")]
47 TooFewPoints {
48 count: usize,
50 },
51 #[error("outline point {index} is {point:?}, which is not a finite position")]
53 NonFinitePoint {
54 index: usize,
56 point: [f32; 2],
58 },
59 #[error("outline points {index} and the one after it are both {point:?}")]
62 RepeatedPoint {
63 index: usize,
65 point: [f32; 2],
67 },
68 #[error("the water level {level} is not a finite height")]
70 NonFiniteLevel {
71 level: f32,
73 },
74 #[error("the medium's {which} is {values:?}; each channel must be finite and at least zero")]
77 InvalidMedium {
78 which: &'static str,
80 values: [f32; 3],
82 },
83 #[error("the outline encloses no area")]
85 NoArea,
86 #[error("outline edges {first} and {second} touch or cross")]
88 SelfIntersecting {
89 first: usize,
91 second: usize,
93 },
94 #[error("a grid spacing of {spacing} is not a finite positive length")]
96 InvalidSpacing {
97 spacing: f32,
99 },
100 #[error("the surface meshes to more vertices than a u32 index addresses")]
102 TooManyVertices,
103 #[error("the outline's bounds hold {cells} grid cells at this spacing, past the {max} allowed")]
105 TooManyCells {
106 cells: u64,
108 max: u64,
110 },
111}
112
113impl Medium {
114 pub(crate) fn validate(&self) -> Result<(), BodyError> {
116 for (which, values) in [
117 ("absorption", self.absorption),
118 ("scattering", self.scattering),
119 ] {
120 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
132pub(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 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
198pub(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
207fn 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 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
229fn 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
234fn within(a: f32, b: f32, value: f32) -> bool {
236 a.min(b) <= value && value <= a.max(b)
237}
238
239fn 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 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 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 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 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}