Skip to main content

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> Path<T> {
54    pub fn new(points: impl Into<PointList<T>>, width: T, path_type: PathEndType<T>) -> Self {
55        Self { points: points.into(), width, path_type }
56    }
57
58    pub fn flat(points: impl Into<PointList<T>>, width: T) -> Self {
59        Self::new(points, width, PathEndType::Flat)
60    }
61
62    pub fn round(points: impl Into<PointList<T>>, width: T) -> Self {
63        Self::new(points, width, PathEndType::Round)
64    }
65}
66
67impl<T> PointList<T> {
68    /// Get the number of vertices.
69    pub fn len(&self) -> usize {
70        self.points.len()
71    }
72
73    /// Check if string has zero length.
74    pub fn is_empty(&self) -> bool {
75        self.points.is_empty()
76    }
77}
78
79impl<T: Copy> PointList<T> {
80    /// Create new point string by taking vertices from a type that implements `Into<PointList<T>>`.
81    pub fn new<I>(i: I) -> Self
82    where
83        I: Into<Self>,
84    {
85        i.into()
86    }
87
88    /// Shortcut for `self.points.iter()`.
89    pub fn iter(&self) -> Iter<Point<T>> {
90        self.points.iter()
91    }
92
93    /// Get the sequence of edges of the point string starting from the first point to the last.
94    /// # Examples
95    ///
96    /// ```
97    /// use reda_geometry::shape::PointList;
98    /// use reda_geometry::shape::Edge;
99    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
100    ///
101    /// let point_string = PointList::new(coords);
102    ///
103    /// let edges: Vec<_> = point_string.edges().collect();
104    ///
105    /// assert_eq!(edges, vec![Edge::new((0, 0), (1, 0)), Edge::new((1, 0), (2, 0))]);
106    /// ```
107    pub fn edges(&self) -> impl Iterator<Item = Edge<T>> + '_ {
108        self.iter()
109            .zip(self.iter().skip(1))
110            .map(|(a, b)| Edge::new(a, b))
111    }
112
113    /// Same as `edges` but in reverse order.
114    /// Get the sequence of edges of the point string starting from the last point to the first.
115    /// # Examples
116    ///
117    /// ```
118    /// use reda_geometry::shape::PointList;
119    /// use reda_geometry::shape::Edge;
120    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
121    ///
122    /// let point_string = PointList::new(coords);
123    ///
124    /// let edges: Vec<_> = point_string.edges_reversed().collect();
125    ///
126    /// assert_eq!(edges, vec![Edge::new((2, 0), (1, 0)), Edge::new((1, 0), (0, 0))]);
127    /// ```
128    pub fn edges_reversed(&self) -> impl Iterator<Item = Edge<T>> + '_ {
129        self.iter()
130            .rev()
131            .zip(self.iter().rev().skip(1))
132            .map(|(a, b)| Edge::new(a, b))
133    }
134}
135
136impl<T: Copy + Sub<Output = T> + NumCast> PointList<T> {
137    /// Compute geometrical length of the path defined by the point string.
138    /// # Examples
139    ///
140    /// ```
141    /// use reda_geometry::shape::PointList;
142    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
143    ///
144    /// let point_string = PointList::new(coords);
145    ///
146    /// assert_eq!(point_string.path_length::<f64>(), 2.0);
147    /// ```
148    pub fn path_length<F: Float>(&self) -> F {
149        self.iter()
150            .zip(self.iter().skip(1))
151            .map(|(a, b)| a.distance(b))
152            .fold(F::zero(), |a, b| a + b)
153    }
154}
155
156/// Create a point string from something that can be turned into an iterator of values convertible to [`Point`]s.
157impl<I, T, P> From<I> for PointList<T>
158where
159    T: Copy,
160    I: IntoIterator<Item = P>,
161    Point<T>: From<P>,
162{
163    fn from(iter: I) -> Self {
164        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
165
166        PointList { points }
167    }
168}
169
170/// Create a point string from a iterator of values convertible to [`Point`]s.
171impl<T, P> FromIterator<P> for PointList<T>
172where
173    T: Copy,
174    P: Into<Point<T>>,
175{
176    fn from_iter<I>(iter: I) -> Self
177    where
178        I: IntoIterator<Item = P>,
179    {
180        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
181
182        PointList { points }
183    }
184}
185
186impl<T: Copy + PartialOrd + Num> TryBoundingBox<T> for Path<T>
187where
188    T: Copy + PartialOrd,
189{
190    fn try_bounding_box(&self) -> Option<Rect<T>> {
191        let bbox = self.points.try_bounding_box();
192        let _1 = T::one();
193        let _2 = _1 + _1;
194        bbox.map(|bbox| {
195            // Enlarge it by width/2 in all directions to make sure the path is fully contained
196            // in the bounding box.
197            let (p1, p2) = (bbox.lower_left(), bbox.upper_right());
198            let w_half = (self.width + _1) / _2;
199            let width = Vec2::new(w_half, w_half);
200            Rect::new(p1 - width, p2 + width)
201        })
202    }
203}
204
205impl<T> TryBoundingBox<T> for PointList<T>
206where
207    T: Copy + PartialOrd,
208{
209    fn try_bounding_box(&self) -> Option<Rect<T>> {
210        if self.points.is_empty() {
211            None
212        } else {
213            let mut x_min = self.points[0].x;
214            let mut x_max = x_min;
215            let mut y_min = self.points[0].y;
216            let mut y_max = y_min;
217
218            for p in self.iter().skip(1) {
219                let (x, y) = p.into();
220                if x < x_min {
221                    x_min = x;
222                }
223                if x > x_max {
224                    x_max = x;
225                }
226                if y < y_min {
227                    y_min = y;
228                }
229                if y > y_max {
230                    y_max = y;
231                }
232            }
233
234            Some(Rect::new((x_min, y_min), (x_max, y_max)))
235        }
236    }
237}
238
239impl<T> MapPoint<T> for PointList<T>
240where
241    T: Copy,
242{
243    fn transform<F: Fn(Point<T>) -> Point<T>>(&self, tf: F) -> Self {
244        let points = self.points.iter().map(|&p| tf(p)).collect();
245        PointList { points }
246    }
247}
248
249impl<T: CoordType> Path<T> {
250    pub fn rotate(&self, angle: Angle) -> Self {
251        Path {
252            points: self.points.rotate(angle),
253            width: self.width,
254            path_type: self.path_type,
255        }
256    }
257
258    pub fn transform(&self, tf: &Transform<T>) -> Self {
259        Self {
260            points: self.points.transform(|p| tf.transform_point(p)),
261            width: tf.transform_distance(self.width),
262            path_type: self.path_type,
263        }
264    }
265}
266
267impl<T: Copy + NumCast, Dst: CoordType + NumCast> Cast<T, Dst> for PointList<T> {
268    type Output = PointList<Dst>;
269
270    fn try_cast(&self) -> Option<Self::Output> {
271        let new_points: Option<Vec<_>> = self.points.iter().map(|p| p.try_cast()).collect();
272        new_points.map(|p| PointList::new(p))
273    }
274}
275
276impl<T: CoordType + NumCast, Dst: CoordType + NumCast> Cast<T, Dst> for Path<T> {
277    type Output = Path<Dst>;
278
279    fn try_cast(&self) -> Option<Self::Output> {
280        let new_width = Dst::from(self.width);
281        let new_points = self.points.try_cast();
282        let new_path_type = match self.path_type {
283            PathEndType::Extended(begin_ext, end_ext) => {
284                let new_begin_ext = Dst::from(begin_ext);
285                let new_end_ext = Dst::from(end_ext);
286                match (new_begin_ext, new_end_ext) {
287                    (Some(b), Some(e)) => Some(PathEndType::Extended(b, e)),
288                    _ => None,
289                }
290            }
291            PathEndType::Flat => Some(PathEndType::Flat),
292            PathEndType::Round => Some(PathEndType::Round),
293        };
294
295        match (new_width, new_points, new_path_type) {
296            (Some(width), Some(points), Some(path_type)) => Some(Path {
297                points,
298                width,
299                path_type,
300            }),
301            _ => {
302                // Failed to cast some values.
303                None
304            }
305        }
306    }
307}