reda_geometry/shape/
polyline.rs

1use num_traits::NumCast;
2
3use crate::traits::{Cast, MapPoint, TryBoundingBox};
4
5use super::{CoordType, Edge, Point, Rect};
6use std::cmp::PartialEq;
7use std::slice::Iter;
8
9#[derive(Clone, Debug, Hash, Eq, PartialEq)]
10pub struct Polyline<T> {
11    pub points: Vec<Point<T>>,
12    pub normalized: bool,
13}
14
15#[macro_export]
16macro_rules! polyline {
17    ($($x:expr),*) => {  };
18}
19
20impl<T> Polyline<T> {
21    pub fn from_points(points: impl Into<Vec<Point<T>>>) -> Self {
22        Self {
23            points: points.into(),
24            normalized: false,
25        }
26    }
27
28    pub fn empty() -> Self {
29        Self {
30            points: Vec::new(),
31            normalized: false,
32        }
33    }
34
35    pub fn len(&self) -> usize {
36        self.points.len()
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.points.is_empty()
41    }
42
43    pub fn iter(&self) -> Iter<Point<T>> {
44        self.points.iter()
45    }
46
47    pub fn points(&self) -> &[Point<T>] {
48        &self.points
49    }
50
51    /// Get index of previous vertex.
52    pub fn prev_index(&self, i: usize) -> usize {
53        match i {
54            0 => self.points.len() - 1,
55            x => x - 1,
56        }
57    }
58
59    /// Get index of next vertex.
60    pub fn next_index(&self, i: usize) -> usize {
61        match i {
62            _ if i == self.points.len() - 1 => 0,
63            x => x + 1,
64        }
65    }
66}
67
68impl<T: PartialOrd> Polyline<T> {
69    pub fn new(points: Vec<Point<T>>) -> Self {
70        Self::from_points(points).normalized()
71    }
72
73    /// Rotate the vertices to get the lexicographically smallest polygon.
74    /// Does not change the orientation.
75    pub fn normalize(&mut self) {
76        if !self.normalized {
77            let rotated = 
78                |rot: usize| self.points.iter()
79                    .cycle()
80                    .skip(rot)
81                    .take(self.points.len());
82            
83            let best_rot = (0..self.points.len()).skip(1).fold(0, |best_rot, rot| {
84                if rotated(rot).lt(rotated(best_rot)) {
85                    rot
86                } else {
87                    best_rot
88                }
89            });
90            self.points.rotate_left(best_rot);
91        }
92        self.normalized = true;
93    }
94
95    pub fn normalized(mut self) -> Self {
96        self.normalize();
97        self
98    }
99}
100
101impl<T: Copy> Polyline<T> {
102    pub fn iter_cycle(&self) -> impl Iterator<Item = &Point<T>> {
103        self.points.iter().cycle().take(self.points.len() + 1)
104    }
105
106    pub fn edges_iter(&self) -> impl Iterator<Item = Edge<T>> + '_ {
107        self.iter()
108            .zip(self.iter_cycle().skip(1))
109            .map(|(a, b)| Edge::new(a, b))
110    }
111
112    pub fn edges(&self) -> Vec<Edge<T>> {
113        self.edges_iter().collect()
114    }
115
116    pub fn from_rect(rect: &Rect<T>) -> Self {
117        Self {
118            points: vec![
119                rect.lower_left(),
120                rect.lower_right(),
121                rect.upper_right(),
122                rect.upper_left(),
123            ],
124            normalized: true,
125        }
126    }
127}
128
129impl<T, P> FromIterator<P> for Polyline<T> 
130where 
131    T: Copy,
132    P: Into<Point<T>>
133{
134    fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Self {
135        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
136        assert!(
137            points.len() >= 2,
138            "A polygon needs to have at least two points."
139        );
140        Self::from_points(points)
141    }
142}
143
144impl<'a, T> IntoIterator for &'a Polyline<T> {
145    type Item = &'a Point<T>;
146    type IntoIter = std::slice::Iter<'a, Point<T>>;
147
148    fn into_iter(self) -> Self::IntoIter {
149        self.points.iter()
150    }
151}
152
153impl<I, T, P> From<I> for Polyline<T> 
154where 
155    T: Copy + PartialOrd,
156    I: IntoIterator<Item = P>,
157    Point<T>: From<P>,
158{
159    fn from(iter: I) -> Self {
160        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
161        Polyline::from_points(points)
162    }
163}
164
165impl<T: Copy> MapPoint<T> for Polyline<T> {
166    fn transform<F>(&self, transformate: F) -> Self
167    where 
168        F: Fn(Point<T>) -> Point<T> 
169    {
170        let points: Vec<_> = self.points.iter().map(|&p| transformate(p)).collect();
171        Self::from_points(points)    
172    }
173}
174
175impl<T: Copy + PartialOrd> TryBoundingBox<T> for Polyline<T> {
176    fn try_bounding_box(&self) -> Option<Rect<T>> {
177        if !self.is_empty() {
178            let mut x_min = self.points[0].x;
179            let mut x_max = x_min;
180            let mut y_min = self.points[0].y;
181            let mut y_max = y_min;
182
183            for p in self.iter().skip(1) {
184                if p.x < x_min {
185                    x_min = p.x;
186                }
187                if p.x > x_max {
188                    x_max = p.x;
189                }
190                if p.y < y_min {
191                    y_min = p.y;
192                }
193                if p.y > y_max {
194                    y_max = p.y;
195                }
196            }
197
198            Some(Rect::new((x_min, y_min), (x_max, y_max)))
199        } else {
200            None
201        }
202    }
203}
204
205impl<T: CoordType + NumCast, Dst: CoordType + NumCast> Cast<T, Dst> for Polyline<T> {
206    type Output = Polyline<Dst>;
207
208    fn try_cast(&self) -> Option<Self::Output> {
209        let new_points: Option<Vec<_>> = self.points.iter().map(|p| p.try_cast()).collect();
210        new_points.map(|p| Polyline::new(p))
211    }
212}