Skip to main content

jagua_rs/geometry/primitives/
simple_polygon.rs

1use itertools::Itertools;
2use ordered_float::{NotNan, OrderedFloat};
3
4use crate::geometry::Transformation;
5use crate::geometry::convex_hull::convex_hull_from_points;
6use crate::geometry::fail_fast::{SPSurrogate, SPSurrogateConfig, compute_pole};
7use crate::geometry::geo_enums::GeoPosition;
8use crate::geometry::geo_traits::{
9    CollidesWith, DistanceTo, SeparationDistance, Transformable, TransformableFrom,
10};
11use crate::geometry::primitives::Circle;
12use crate::geometry::primitives::Edge;
13use crate::geometry::primitives::GeometryError;
14use crate::geometry::primitives::Point;
15use crate::geometry::primitives::Rect;
16use crate::geometry::short_edges::remove_short_edges;
17use crate::util::FPA;
18use crate::util::assertions;
19use anyhow::{Result, bail};
20use log::debug;
21
22/// A Simple Polygon is a polygon that does not intersect itself and contains no holes.
23/// It is a closed shape with a finite number of vertices and edges.
24/// [read more](https://en.wikipedia.org/wiki/Simple_polygon)
25#[derive(Clone, Debug)]
26pub struct SPolygon {
27    /// Vertices in counterclockwise order, including after reflection.
28    pub(crate) vertices: Vec<Point>,
29    /// Bounding box
30    pub(crate) bbox: Rect,
31    /// Area of its interior
32    pub(crate) area: f32,
33    /// Maximum distance between any two points in the polygon
34    pub(crate) diameter: f32,
35    /// [Pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility) represented as a circle
36    pub(crate) poi: Circle,
37    /// Optional surrogate representation of the polygon (subset of the original)
38    pub(crate) surrogate: Option<SPSurrogate>,
39}
40
41impl SPolygon {
42    /// Minimum length of an edge, as a fraction of the polygon's diameter.
43    ///
44    /// Shorter edges are removed on construction, see [`SPolygon::new`].
45    /// The margin is large compared to the `f32` rounding error of the coordinates of a centered polygon
46    /// (about `6e-8` times the diameter), so centering or rotating it cannot collapse an edge into a single point (issue #133).
47    ///
48    /// [`Transformable::transform`] and [`TransformableFrom::transform_from`] do not uphold this minimum:
49    /// translated far from the origin, where the `f32` spacing exceeds it, a short edge can still collapse.
50    /// Collision detection does not rely on the minimum; rebuild the polygon with [`SPolygon::new`] where it is needed.
51    pub const MIN_EDGE_LENGTH_RATIO: f32 = 1e-5;
52
53    /// Create a new simple polygon from a set of points, expensive operations are performed here! Use [`Self::clone()`] or [`Self::transform()`] to avoid recomputation.
54    ///
55    /// Every vertex that lies closer than [`SPolygon::MIN_EDGE_LENGTH_RATIO`] times the diameter
56    /// to the previous kept vertex is removed, so no edge is shorter than that.
57    /// Returns an error if the remaining vertices do not form a valid simple polygon.
58    pub fn new(mut points: Vec<Point>) -> Result<Self> {
59        if points.len() < 3 {
60            bail!(GeometryError::TooFewPoints(points.len()));
61        }
62        let removal = remove_short_edges(&mut points);
63        if !removal.removed.is_empty() {
64            debug!("[SP] {removal}");
65        }
66        if points.len() < 3 {
67            bail!(GeometryError::TooFewPoints(points.len()));
68        }
69        if points.iter().unique().count() != points.len() {
70            let [i, j] = (0..points.len())
71                .array_combinations()
72                .find(|&[i, j]| points[i] == points[j])
73                .expect("a duplicate point exists");
74            bail!(GeometryError::DuplicatePoints(i, j));
75        }
76        if let Some((e1_idx, e2_idx)) = SPolygon::find_self_intersection(&points) {
77            bail!(GeometryError::IntersectingEdges(e1_idx, e2_idx));
78        }
79
80        let area = match SPolygon::calculate_area(&points) {
81            0.0 => bail!(GeometryError::NoArea),
82            area if area < 0.0 => {
83                //edges should always be ordered counterclockwise (positive area)
84                points.reverse();
85                -area
86            }
87            area => area,
88        };
89
90        let diameter = SPolygon::calculate_diameter(points.clone());
91        let bbox = SPolygon::generate_bounding_box(&points);
92        let poi = SPolygon::calculate_poi(&points, diameter)?;
93
94        Ok(SPolygon {
95            vertices: points,
96            bbox,
97            area,
98            diameter,
99            poi,
100            surrogate: None,
101        })
102    }
103
104    pub fn generate_surrogate(&mut self, config: SPSurrogateConfig) -> Result<()> {
105        //regenerate the surrogate if it is not present or if the config has changed
106        match &self.surrogate {
107            Some(surrogate) if surrogate.config == config => {}
108            _ => self.surrogate = Some(SPSurrogate::new(self, config)?),
109        }
110        Ok(())
111    }
112
113    #[must_use]
114    pub fn vertex(&self, i: usize) -> Point {
115        self.vertices[i]
116    }
117
118    #[must_use]
119    pub fn edge(&self, i: usize) -> Edge {
120        assert!(i < self.n_vertices(), "index out of bounds");
121        let j = if i == self.n_vertices() - 1 { 0 } else { i + 1 };
122        Edge {
123            start: self.vertices[i],
124            end: self.vertices[j],
125        }
126    }
127
128    pub fn edge_iter(&self) -> impl Iterator<Item = Edge> + '_ {
129        (0..self.n_vertices()).map(move |i| self.edge(i))
130    }
131
132    #[must_use]
133    pub fn n_vertices(&self) -> usize {
134        self.vertices.len()
135    }
136
137    #[must_use]
138    pub fn surrogate(&self) -> &SPSurrogate {
139        self.surrogate.as_ref().expect("surrogate not generated")
140    }
141
142    #[must_use]
143    pub(crate) fn calculate_diameter(points: Vec<Point>) -> f32 {
144        //The two points furthest apart must be part of the convex hull
145        let ch = convex_hull_from_points(points);
146
147        //go through all pairs of points and find the pair with the largest distance
148        let sq_diam = ch
149            .iter()
150            .array_combinations::<2>()
151            .map(|[p1, p2]| p1.sq_distance_to(p2))
152            .max_by_key(|sq_d| NotNan::new(*sq_d).unwrap())
153            .unwrap_or(0.0); // fewer than two distinct points
154
155        sq_diam.sqrt()
156    }
157
158    #[must_use]
159    pub fn generate_bounding_box(points: &[Point]) -> Rect {
160        let (mut x_min, mut y_min) = (f32::MAX, f32::MAX);
161        let (mut x_max, mut y_max) = (f32::MIN, f32::MIN);
162
163        for point in points {
164            x_min = x_min.min(point.0);
165            y_min = y_min.min(point.1);
166            x_max = x_max.max(point.0);
167            y_max = y_max.max(point.1);
168        }
169        Rect::try_new(x_min, y_min, x_max, y_max).unwrap()
170    }
171
172    //https://en.wikipedia.org/wiki/Shoelace_formula
173    //counterclockwise = positive area, clockwise = negative area
174    #[must_use]
175    pub fn calculate_area(points: &[Point]) -> f32 {
176        let mut sigma: f32 = 0.0;
177        for i in 0..points.len() {
178            //next point
179            let j = (i + 1) % points.len();
180
181            let (x_i, y_i) = points[i].into();
182            let (x_j, y_j) = points[j].into();
183
184            sigma += (y_i + y_j) * (x_i - x_j);
185        }
186
187        0.5 * sigma
188    }
189
190    fn calculate_poi(points: &[Point], diameter: f32) -> Result<Circle> {
191        //need to make a dummy simple polygon, because the pole generation algorithm
192        //relies on many of the methods provided by the simple polygon struct
193        let dummy_sp = {
194            let bbox = SPolygon::generate_bounding_box(points);
195            let area = SPolygon::calculate_area(points);
196            let dummy_poi = Circle::try_new(Point(f32::MAX, f32::MAX), f32::MAX).unwrap();
197
198            SPolygon {
199                vertices: points.to_vec(),
200                bbox,
201                area,
202                diameter,
203                poi: dummy_poi,
204                surrogate: None,
205            }
206        };
207
208        compute_pole(&dummy_sp, &[])
209    }
210
211    #[must_use]
212    pub fn centroid(&self) -> Point {
213        //based on: https://en.wikipedia.org/wiki/Centroid#Of_a_polygon
214
215        //relative to the first vertex: far from the origin, the cross products of absolute coordinates cancel out
216        let Point(o_x, o_y) = self.vertex(0);
217        let area = self.area;
218        let mut c_x = 0.0;
219        let mut c_y = 0.0;
220
221        for i in 0..self.n_vertices() {
222            let j = if i == self.n_vertices() - 1 { 0 } else { i + 1 };
223            let (x_i, y_i) = (self.vertex(i).0 - o_x, self.vertex(i).1 - o_y);
224            let (x_j, y_j) = (self.vertex(j).0 - o_x, self.vertex(j).1 - o_y);
225            c_x += (x_i + x_j) * (x_i * y_j - x_j * y_i);
226            c_y += (y_i + y_j) * (x_i * y_j - x_j * y_i);
227        }
228
229        c_x /= 6.0 * area;
230        c_y /= 6.0 * area;
231
232        (o_x + c_x, o_y + c_y).into()
233    }
234
235    fn find_self_intersection(points: &[Point]) -> Option<(usize, usize)> {
236        let edge = |i| Edge {
237            start: points[i],
238            end: points[(i + 1) % points.len()],
239        };
240        let are_neighboring_edges = |i, j| i + 1 == j || (i == 0 && j == points.len() - 1);
241
242        (0..points.len()).combinations(2).find_map(|pair| {
243            let (i, j) = (pair[0], pair[1]);
244            (!are_neighboring_edges(i, j) && edge(i).collides_with(&edge(j))).then_some((i, j))
245        })
246    }
247
248    /// Vertices in counterclockwise order, including after reflection.
249    #[must_use]
250    pub fn vertices(&self) -> &[Point] {
251        &self.vertices
252    }
253
254    /// Bounding box
255    #[must_use]
256    pub fn bbox(&self) -> Rect {
257        self.bbox
258    }
259
260    /// Area of its interior
261    #[must_use]
262    pub fn area(&self) -> f32 {
263        self.area
264    }
265
266    /// Maximum distance between any two points in the polygon
267    #[must_use]
268    pub fn diameter(&self) -> f32 {
269        self.diameter
270    }
271
272    /// [Pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility) represented as a circle
273    #[must_use]
274    pub fn poi(&self) -> Circle {
275        self.poi
276    }
277}
278
279impl Transformable for SPolygon {
280    fn transform(&mut self, t: &Transformation) -> &mut Self {
281        let reflected = t.is_reflected();
282        //destructuring pattern to ensure that the code is updated when the struct changes
283        let SPolygon {
284            vertices: points,
285            bbox,
286            area: _,
287            diameter: _,
288            poi,
289            surrogate,
290        } = self;
291
292        //transform all points of the simple poly
293        for p in points.iter_mut() {
294            p.transform(t);
295        }
296        if reflected {
297            points.reverse();
298        }
299
300        poi.transform(t);
301
302        //transform the surrogate
303        if let Some(surrogate) = surrogate.as_mut() {
304            surrogate.transform(t);
305            if reflected {
306                surrogate.reverse_vertex_order(points.len());
307            }
308        }
309
310        //regenerate bounding box
311        *bbox = SPolygon::generate_bounding_box(points);
312
313        self
314    }
315}
316
317impl TransformableFrom for SPolygon {
318    fn transform_from(&mut self, reference: &Self, t: &Transformation) -> &mut Self {
319        let reflected = t.is_reflected();
320        assert_eq!(self.vertices.len(), reference.vertices.len());
321        //destructuring pattern to ensure that the code is updated when the struct changes
322        let SPolygon {
323            vertices: points,
324            bbox,
325            area: _,
326            diameter: _,
327            poi,
328            surrogate,
329        } = self;
330
331        if reflected {
332            for (p, ref_p) in points.iter_mut().zip(reference.vertices.iter().rev()) {
333                p.transform_from(ref_p, t);
334            }
335        } else {
336            for (p, ref_p) in points.iter_mut().zip(&reference.vertices) {
337                p.transform_from(ref_p, t);
338            }
339        }
340
341        poi.transform_from(&reference.poi, t);
342
343        //transform the surrogate
344        if let Some(surrogate) = surrogate.as_mut() {
345            let ref_surrogate = reference.surrogate();
346            surrogate.transform_from(ref_surrogate, t);
347            // The destination was cloned from `reference`, so its hull indices only
348            // need remapping when the vertex storage orientation changes.
349            if surrogate.hull_reversed() != (ref_surrogate.hull_reversed() ^ reflected) {
350                surrogate.reverse_vertex_order(points.len());
351            }
352            debug_assert!(assertions::hull_indices_match_reference(
353                surrogate,
354                ref_surrogate,
355                reflected,
356                points.len()
357            ));
358        }
359        //regenerate bounding box
360        *bbox = SPolygon::generate_bounding_box(points);
361
362        self
363    }
364}
365
366impl CollidesWith<Point> for SPolygon {
367    fn collides_with(&self, point: &Point) -> bool {
368        //based on the ray casting algorithm: https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm
369        if self.bbox.collides_with(point) {
370            //horizontal ray shot to the right.
371            //Starting from the point to another point that is certainly outside the shape
372            let point_outside = Point(self.bbox.x_max + self.bbox.width(), point.1);
373            let ray = Edge {
374                start: *point,
375                end: point_outside,
376            };
377
378            let n_intersections = self
379                .edge_iter()
380                .filter(|edge| ray_crosses(edge, point, &ray))
381                .count();
382            n_intersections % 2 == 1
383        } else {
384            false
385        }
386    }
387}
388
389/// Whether `edge` counts as a crossing of `ray`, shot horizontally to the right from `point`,
390/// in the ray casting test of [`SPolygon::collides_with`].
391#[inline(always)]
392pub(crate) fn ray_crosses(edge: &Edge, point: &Point, ray: &Edge) -> bool {
393    //Check if the ray does not go through (or almost through) a vertex
394    //This can result in funky behaviour, which could incorrect results
395    //Therefore we handle this case
396    let (s_x, s_y) = (FPA(edge.start.0), FPA(edge.start.1));
397    let (e_x, e_y) = (FPA(edge.end.0), FPA(edge.end.1));
398    let (p_x, p_y) = (FPA(point.0), FPA(point.1));
399
400    if (s_y == p_y && s_x > p_x) || (e_y == p_y && e_x > p_x) {
401        //in this case, the ray passes through (or dangerously close to) a vertex
402        //We handle this case by only counting an intersection if the edge is below the ray
403        s_y < p_y || e_y < p_y
404    } else {
405        ray.collides_with(edge)
406    }
407}
408
409impl DistanceTo<Point> for SPolygon {
410    fn distance_to(&self, point: &Point) -> f32 {
411        self.sq_distance_to(point).sqrt()
412    }
413    fn sq_distance_to(&self, point: &Point) -> f32 {
414        if self.collides_with(point) {
415            0.0
416        } else {
417            self.edge_iter()
418                .map(|edge| edge.sq_distance_to(point))
419                .min_by(|a, b| a.partial_cmp(b).unwrap())
420                .unwrap()
421        }
422    }
423}
424
425impl SeparationDistance<Point> for SPolygon {
426    fn separation_distance(&self, point: &Point) -> (GeoPosition, f32) {
427        let (position, sq_distance) = self.sq_separation_distance(point);
428        (position, sq_distance.sqrt())
429    }
430
431    fn sq_separation_distance(&self, point: &Point) -> (GeoPosition, f32) {
432        let distance_to_closest_edge = self
433            .edge_iter()
434            .map(|edge| edge.sq_distance_to(point))
435            .min_by_key(|sq_d| OrderedFloat(*sq_d))
436            .unwrap();
437
438        if self.collides_with(point) {
439            (GeoPosition::Interior, distance_to_closest_edge)
440        } else {
441            (GeoPosition::Exterior, distance_to_closest_edge)
442        }
443    }
444}
445
446impl TryFrom<&Rect> for SPolygon {
447    type Error = anyhow::Error;
448
449    /// Fails if the rectangle is so thin that [`SPolygon::new`] removes its short sides,
450    /// see [`SPolygon::MIN_EDGE_LENGTH_RATIO`].
451    fn try_from(r: &Rect) -> Result<Self> {
452        SPolygon::new(vec![
453            (r.x_min, r.y_min).into(),
454            (r.x_max, r.y_min).into(),
455            (r.x_max, r.y_max).into(),
456            (r.x_min, r.y_max).into(),
457        ])
458    }
459}
460
461impl TryFrom<Rect> for SPolygon {
462    type Error = anyhow::Error;
463
464    /// See [`SPolygon::try_from(&Rect)`](#impl-TryFrom%3C%26Rect%3E-for-SPolygon).
465    fn try_from(r: Rect) -> Result<Self> {
466        SPolygon::try_from(&r)
467    }
468}