reda_geometry/shape/
polygon.rs

1use itertools::Itertools;
2use num_traits::NumCast;
3
4use crate::traits::{Cast, MapPoint, TryBoundingBox};
5
6use super::{DType, Edge, Point, Polyline, Rect};
7
8#[derive(Clone, Hash, Debug, Eq, PartialEq)]
9#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10pub struct Polygon<T> {
11    pub exterior: Polyline<T>,
12    pub interiors: Vec<Polyline<T>>, 
13}
14
15impl<T> Polygon<T> {
16    pub fn new<E, I>(exterior: E, holes: Vec<I>) -> Self 
17    where 
18        E: Into<Polyline<T>>,
19        I: Into<Polyline<T>>,
20    {
21        Self {
22            exterior: exterior.into(),
23            interiors: holes.into_iter().map(|i| i.into()).collect()
24        }
25    }
26
27    pub fn new_exterior(exterior: impl Into<Vec<Point<T>>>) -> Self {
28        Self {
29            exterior: Polyline::from_points(exterior),
30            interiors: Vec::new(),
31        }
32    }
33
34    pub fn empty() -> Self {
35        Self {
36            exterior: Polyline::empty(),
37            interiors: Vec::new(),
38        }
39    }
40
41    pub fn len(&self) -> usize {
42        self.exterior.len()
43    }
44
45    pub fn is_empty(&self) -> bool {
46        self.exterior.is_empty()
47    }
48}   
49
50impl<T: Copy> Polygon<T> {
51    pub fn exterior_edges(&self) -> Vec<Edge<T>> {
52        self.exterior.edges()
53    }
54
55    pub fn exterior_edges_iter(&self) -> impl Iterator<Item = Edge<T>> + '_ {
56        self.exterior.edges_iter()
57    }
58
59    pub fn all_edges(&self) -> Vec<Edge<T>> {
60        self.all_edges_iter().collect()
61    }
62
63    pub fn all_edges_iter(&self) -> impl Iterator<Item = Edge<T>> + '_ {
64        self.exterior.edges_iter().chain(
65            self.interiors
66                .iter()
67                .flat_map(|interior| interior.edges_iter())
68        )
69    }
70}
71
72impl<T: PartialOrd> Polygon<T> {
73    pub fn new_normalized<E, I>(exterior: E, holes: Vec<I>) -> Self 
74    where 
75        E: Into<Polyline<T>>,
76        I: Into<Polyline<T>>,
77    {
78        Self::new(exterior, holes).normalized()
79    }
80    
81    pub fn new_exterior_normalized(exterior: impl Into<Vec<Point<T>>>) -> Self {
82        Self::new_exterior(exterior).normalized()
83    }
84
85    /// Reorder vertices and holes to get the lexicographically smallest representation of this polygon.
86    /// Does not change the orientations.
87    pub fn normalize(&mut self) {
88        self.exterior.normalize();
89        self.interiors.iter_mut().for_each(|p| p.normalize());
90        self.interiors.sort_by(|a, b| {
91            a.points()
92                .partial_cmp(b.points())
93                .unwrap_or(std::cmp::Ordering::Less)
94        })
95    }
96
97    /// Reorder vertices and holes to get the lexicographically smallest representation of this polygon.
98    /// Does not change the orientations.
99    pub fn normalized(mut self) -> Self {
100        self.normalize();
101        self
102    }
103}
104
105impl<'a, T, P> From<&'a [P]> for Polygon<T>
106where
107    T: DType,
108    Point<T>: From<&'a P>,
109{
110    fn from(vec: &'a [P]) -> Self {
111        Self {
112            exterior: vec.into(),
113            interiors: Vec::new(),
114        }
115    }
116}
117
118impl<T, P> From<Vec<P>> for Polygon<T>
119where
120    T: Copy + PartialOrd,
121    Point<T>: From<P>,
122{
123    fn from(vec: Vec<P>) -> Self {
124        Self {
125            exterior: vec.into(),
126            interiors: Vec::new(),
127        }
128    }
129}
130
131impl<T> From<Polyline<T>> for Polygon<T> {
132    fn from(polyline: Polyline<T>) -> Self {
133        Self {
134            exterior: polyline,
135            interiors: Vec::new(),
136        }
137    }
138}
139
140impl<T> From<&Polyline<T>> for Polygon<T> 
141where 
142    T: Clone
143{
144    fn from(polyline: &Polyline<T>) -> Self {
145        Self {
146            exterior: polyline.clone(),
147            interiors: Vec::new(),
148        }
149    }
150}
151
152impl<T> From<Rect<T>> for Polygon<T>
153where
154    T: Copy,
155{
156    fn from(rect: Rect<T>) -> Self {
157        Self::from(&rect)
158    }
159}
160
161impl<T> From<&Rect<T>> for Polygon<T>
162where
163    T: Copy,
164{
165    fn from(rect: &Rect<T>) -> Self {
166        Polyline::from_rect(rect).into()
167    }
168}
169
170impl<T: Copy> MapPoint<T> for Polygon<T> {
171    fn transform<F>(&self, transformate: F) -> Self
172    where 
173        F: Fn(Point<T>) -> Point<T> 
174    {
175        Self {
176            exterior: self.exterior.transform(&transformate),
177            interiors: self.interiors.iter().map(|p| p.transform(&transformate)).collect(),
178        }    
179    }
180}
181
182impl<T: Copy + PartialOrd> TryBoundingBox<T> for Polygon<T> {
183    fn try_bounding_box(&self) -> Option<Rect<T>> {
184        self.exterior.try_bounding_box()  
185    }
186}
187
188impl<T: DType + NumCast, Dst: DType + NumCast> Cast<T, Dst>
189    for Polygon<T>
190{
191    type Output = Polygon<Dst>;
192
193    fn try_cast(&self) -> Option<Self::Output> {
194        if let Some(new_hull) = self.exterior.try_cast() {
195            let new_holes: Vec<_> = self
196                .interiors
197                .iter()
198                .map(|hole| hole.try_cast())
199                .while_some()
200                .collect();
201            if new_holes.len() == self.interiors.len() {
202                Some(Polygon::new(new_hull, new_holes))
203            } else {
204                None
205            }
206        } else {
207            None
208        }
209    }
210}