reda_geometry/shape/
path.rs

1// Copyright (c) 2018-2020 Thomas Kramer.
2// SPDX-FileCopyrightText: 2018-2022 Thomas Kramer
3//
4// SPDX-License-Identifier: AGPL-3.0-or-later
5
6//! A point string is a finite sequence of points.
7
8use crate::base::Vec2;
9use crate::shape::Edge;
10use crate::shape::Point;
11use crate::traits::Cast;
12pub use crate::traits::CoordType;
13use crate::traits::MapPoint;
14use crate::traits::Rotate;
15use crate::traits::TryBoundingBox;
16use crate::transform::Transform;
17use std::iter::FromIterator;
18use std::slice::Iter;
19
20use num_traits::Num;
21use num_traits::{Float, NumCast};
22use std::ops::Sub;
23
24use super::Angle;
25use super::Rect;
26
27/// `Path` is essentially a chain of line segments but with a possibly a non-zero width.
28/// It can be thought of the shape resulting by a stroke of a thick pen along the line segments.
29#[derive(Clone, PartialEq, Eq, Hash, Debug)]
30pub struct Path<T> {
31    /// The vertices of the path which define the sequence of line segments.
32    pub points: PointList<T>,
33    /// Width of the path.
34    pub width: T,
35    /// Type of the path endings.
36    pub path_type: PathEndType<T>,
37}
38
39/// Encoding for the type of the beginning and end of the path.
40#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
41pub enum PathEndType<T> {
42    Flat,
43    Extended(T, T),
44    Round,
45}
46
47#[derive(Clone, Debug, PartialEq, Eq, Hash)]
48pub struct PointList<T> {
49    /// The points defining this point string.
50    pub points: Vec<Point<T>>,
51}
52
53impl<T> PointList<T> {
54    /// Get the number of vertices.
55    pub fn len(&self) -> usize {
56        self.points.len()
57    }
58
59    /// Check if string has zero length.
60    pub fn is_empty(&self) -> bool {
61        self.points.is_empty()
62    }
63}
64
65impl<T: Copy> PointList<T> {
66    /// Create new point string by taking vertices from a type that implements `Into<PointList<T>>`.
67    pub fn new<I>(i: I) -> Self
68    where
69        I: Into<Self>,
70    {
71        i.into()
72    }
73
74    /// Shortcut for `self.points.iter()`.
75    pub fn iter(&self) -> Iter<Point<T>> {
76        self.points.iter()
77    }
78
79    /// Get the sequence of edges of the point string starting from the first point to the last.
80    /// # Examples
81    ///
82    /// ```
83    /// use reda_geometry::shape::PointList;
84    /// use reda_geometry::shape::Edge;
85    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
86    ///
87    /// let point_string = PointList::new(coords);
88    ///
89    /// let edges: Vec<_> = point_string.edges().collect();
90    ///
91    /// assert_eq!(edges, vec![Edge::new((0, 0), (1, 0)), Edge::new((1, 0), (2, 0))]);
92    /// ```
93    pub fn edges(&self) -> impl Iterator<Item = Edge<T>> + '_ {
94        self.iter()
95            .zip(self.iter().skip(1))
96            .map(|(a, b)| Edge::new(a, b))
97    }
98
99    /// Same as `edges` but in reverse order.
100    /// Get the sequence of edges of the point string starting from the last point to the first.
101    /// # Examples
102    ///
103    /// ```
104    /// use reda_geometry::shape::PointList;
105    /// use reda_geometry::shape::Edge;
106    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
107    ///
108    /// let point_string = PointList::new(coords);
109    ///
110    /// let edges: Vec<_> = point_string.edges_reversed().collect();
111    ///
112    /// assert_eq!(edges, vec![Edge::new((2, 0), (1, 0)), Edge::new((1, 0), (0, 0))]);
113    /// ```
114    pub fn edges_reversed(&self) -> impl Iterator<Item = Edge<T>> + '_ {
115        self.iter()
116            .rev()
117            .zip(self.iter().rev().skip(1))
118            .map(|(a, b)| Edge::new(a, b))
119    }
120}
121
122impl<T: Copy + Sub<Output = T> + NumCast> PointList<T> {
123    /// Compute geometrical length of the path defined by the point string.
124    /// # Examples
125    ///
126    /// ```
127    /// use reda_geometry::shape::PointList;
128    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
129    ///
130    /// let point_string = PointList::new(coords);
131    ///
132    /// assert_eq!(point_string.path_length::<f64>(), 2.0);
133    /// ```
134    pub fn path_length<F: Float>(&self) -> F {
135        self.iter()
136            .zip(self.iter().skip(1))
137            .map(|(a, b)| a.distance(b))
138            .fold(F::zero(), |a, b| a + b)
139    }
140}
141
142/// Create a point string from something that can be turned into an iterator of values convertible to [`Point`]s.
143impl<I, T, P> From<I> for PointList<T>
144where
145    T: Copy,
146    I: IntoIterator<Item = P>,
147    Point<T>: From<P>,
148{
149    fn from(iter: I) -> Self {
150        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
151
152        PointList { points }
153    }
154}
155
156/// Create a point string from a iterator of values convertible to [`Point`]s.
157impl<T, P> FromIterator<P> for PointList<T>
158where
159    T: Copy,
160    P: Into<Point<T>>,
161{
162    fn from_iter<I>(iter: I) -> Self
163    where
164        I: IntoIterator<Item = P>,
165    {
166        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
167
168        PointList { points }
169    }
170}
171
172impl<T: Copy + PartialOrd + Num> TryBoundingBox<T> for Path<T>
173where
174    T: Copy + PartialOrd,
175{
176    fn try_bounding_box(&self) -> Option<Rect<T>> {
177        let bbox = self.points.try_bounding_box();
178        let _1 = T::one();
179        let _2 = _1 + _1;
180        bbox.map(|bbox| {
181            // Enlarge it by width/2 in all directions to make sure the path is fully contained
182            // in the bounding box.
183            let (p1, p2) = (bbox.lower_left(), bbox.upper_right());
184            let w_half = (self.width + _1) / _2;
185            let width = Vec2::new(w_half, w_half);
186            Rect::new(p1 - width, p2 + width)
187        })
188    }
189}
190
191impl<T> TryBoundingBox<T> for PointList<T>
192where
193    T: Copy + PartialOrd,
194{
195    fn try_bounding_box(&self) -> Option<Rect<T>> {
196        if self.points.is_empty() {
197            None
198        } else {
199            let mut x_min = self.points[0].x;
200            let mut x_max = x_min;
201            let mut y_min = self.points[0].y;
202            let mut y_max = y_min;
203
204            for p in self.iter().skip(1) {
205                let (x, y) = p.into();
206                if x < x_min {
207                    x_min = x;
208                }
209                if x > x_max {
210                    x_max = x;
211                }
212                if y < y_min {
213                    y_min = y;
214                }
215                if y > y_max {
216                    y_max = y;
217                }
218            }
219
220            Some(Rect::new((x_min, y_min), (x_max, y_max)))
221        }
222    }
223}
224
225impl<T> MapPoint<T> for PointList<T>
226where
227    T: Copy,
228{
229    fn transform<F: Fn(Point<T>) -> Point<T>>(&self, tf: F) -> Self {
230        let points = self.points.iter().map(|&p| tf(p)).collect();
231        PointList { points }
232    }
233}
234
235impl<T: CoordType> Path<T> {
236    pub fn rotate(&self, angle: Angle) -> Self {
237        Path {
238            points: self.points.rotate(angle),
239            width: self.width,
240            path_type: self.path_type,
241        }
242    }
243
244    pub fn transform(&self, tf: &Transform<T>) -> Self {
245        Self {
246            points: self.points.transform(|p| tf.transform_point(p)),
247            width: tf.transform_distance(self.width),
248            path_type: self.path_type,
249        }
250    }
251}
252
253impl<T: Copy + NumCast, Dst: CoordType + NumCast> Cast<T, Dst> for PointList<T> {
254    type Output = PointList<Dst>;
255
256    fn try_cast(&self) -> Option<Self::Output> {
257        let new_points: Option<Vec<_>> = self.points.iter().map(|p| p.try_cast()).collect();
258        new_points.map(|p| PointList::new(p))
259    }
260}
261
262impl<T: CoordType + NumCast, Dst: CoordType + NumCast> Cast<T, Dst> for Path<T> {
263    type Output = Path<Dst>;
264
265    fn try_cast(&self) -> Option<Self::Output> {
266        let new_width = Dst::from(self.width);
267        let new_points = self.points.try_cast();
268        let new_path_type = match self.path_type {
269            PathEndType::Extended(begin_ext, end_ext) => {
270                let new_begin_ext = Dst::from(begin_ext);
271                let new_end_ext = Dst::from(end_ext);
272                match (new_begin_ext, new_end_ext) {
273                    (Some(b), Some(e)) => Some(PathEndType::Extended(b, e)),
274                    _ => None,
275                }
276            }
277            PathEndType::Flat => Some(PathEndType::Flat),
278            PathEndType::Round => Some(PathEndType::Round),
279        };
280
281        match (new_width, new_points, new_path_type) {
282            (Some(width), Some(points), Some(path_type)) => Some(Path {
283                points,
284                width,
285                path_type,
286            }),
287            _ => {
288                // Failed to cast some values.
289                None
290            }
291        }
292    }
293}