reda_geometry/shape/
rect.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//! Data structures and functions for dealing with rectangles which consist of
7//! vertical and horizontal edges.
8use num_traits::{NumCast, One, Zero};
9use std::ops::{Add, Div, Sub};
10use crate::base::{cmp, Vec2};
11use crate::shape::Point;
12use crate::traits::{BoundingBox, Cast, MapPoint, ToPolygon, TryBoundingBox};
13
14use super::Polygon;
15
16/// A rectangle which is oriented along the x an y axis and
17/// represented by its lower left and upper right corner.
18#[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
19pub struct Rect<T> {
20    pub lower_left: Point<T>,
21    pub upper_right: Point<T>,
22}
23
24impl<T: PartialOrd + Copy> Rect<T> {
25    /// Construct the bounding box of the two points. Order does not matter.
26    ///
27    /// # Examples
28    ///
29    /// ```
30    /// use reda_geometry::prelude::*;
31    ///
32    /// // Create a rectangle based on two corner points.
33    /// let rect1 = Rect::new(Point::new(0, 0), Point::new(1, 2));
34    /// // Any type that implements `Into<Point<T>>` can be used for the corner points.
35    /// let rect2 = Rect::new((1, 2), (0, 0));
36    /// // Ordering of the corner points does not matter.
37    /// assert_eq!(rect1, rect2);
38    /// // Even though `(0, 0)` was passed as second argument it is recognized as lower left corner.
39    /// assert_eq!(rect2.lower_left(), Point::new(0, 0));
40    /// ```
41    pub fn new(c1: impl Into<Point<T>>, c2: impl Into<Point<T>>) -> Self {
42        let p1 = c1.into();
43        let p2 = c2.into();
44
45        let (x1, x2) = if p1.x < p2.x {
46            (p1.x, p2.x)
47        } else {
48            (p2.x, p1.x)
49        };
50
51        let (y1, y2) = if p1.y < p2.y {
52            (p1.y, p2.y)
53        } else {
54            (p2.y, p1.y)
55        };
56
57        Rect {
58            lower_left: Point::new(x1, y1),
59            upper_right: Point::new(x2, y2),
60        }
61    }
62}
63
64impl<T: Copy> Rect<T> {
65    /// Get the lower left corner.
66    #[inline]
67    pub fn lower_left(&self) -> Point<T> {
68        self.lower_left
69    }
70
71    /// Get the upper left corner.
72    #[inline]
73    pub fn upper_left(&self) -> Point<T> {
74        Point::new(self.lower_left.x, self.upper_right.y)
75    }
76
77    /// Get the upper right corner.
78    #[inline]
79    pub fn upper_right(&self) -> Point<T> {
80        self.upper_right
81    }
82
83    /// Get the lower right corner.
84    #[inline]
85    pub fn lower_right(&self) -> Point<T> {
86        Point::new(self.upper_right.x, self.lower_left.y)
87    }
88}
89
90impl<T: PartialOrd + Copy> Rect<T> {
91    /// Check if rectangle contains the point.
92    /// Inclusive boundaries.
93    ///
94    /// # Example
95    /// ```
96    /// use reda_geometry::prelude::*;
97    /// let rect = Rect::new((0, 0), (10, 20));
98    /// // Contains point somewhere in the center.
99    /// assert!(rect.contains_point(Point::new(5, 5)));
100    /// // Also contains point on the boundaries.
101    /// assert!(rect.contains_point(Point::new(0, 0)));
102    /// // Does not contain point outside of the rectangle.
103    /// assert!(!rect.contains_point(Point::new(10, 21)));
104    /// ```
105    pub fn contains_point(&self, p: Point<T>) -> bool {
106        self.lower_left.x <= p.x
107            && p.x <= self.upper_right.x
108            && self.lower_left.y <= p.y
109            && p.y <= self.upper_right.y
110    }
111
112    /// Check if rectangle contains the point.
113    /// Exclusive boundaries.
114    ///
115    /// # Example
116    /// ```
117    /// use reda_geometry::prelude::*;
118    /// let rect = Rect::new((0, 0), (10, 20));
119    /// // Contains point somewhere in the center.
120    /// assert!(rect.contains_point_exclusive(Point::new(5, 5)));
121    /// // Does not contain points on boundaries.
122    /// assert!(!rect.contains_point_exclusive(Point::new(0, 0)));
123    /// // Does not contain point outside of the rectangle.
124    /// assert!(!rect.contains_point_exclusive(Point::new(10, 21)));
125    /// ```
126    pub fn contains_point_exclusive(&self, p: Point<T>) -> bool {
127        self.lower_left.x < p.x
128            && p.x < self.upper_right.x
129            && self.lower_left.y < p.y
130            && p.y < self.upper_right.y
131    }
132
133    /// Check if rectangle contains other rectangle.
134    /// Inclusive boundaries.
135    ///
136    /// # Example
137    ///
138    /// ```
139    /// use reda_geometry::prelude::*;
140    ///
141    /// let outer = Rect::new((0, 0), (2, 2));
142    /// let inner = Rect::new((0, 0), (1, 1));
143    /// assert!(outer.contains_rectangle(&inner));
144    /// assert!(!inner.contains_rectangle(&outer));
145    /// ```
146    pub fn contains_rectangle(&self, other: &Self) -> bool {
147        self.contains_point(other.lower_left) && self.contains_point(other.upper_right)
148    }
149
150    /// Check if rectangle contains other rectangle.
151    /// Exclusive boundaries.
152    ///
153    /// # Example
154    ///
155    /// ```
156    /// use reda_geometry::prelude::*;
157    ///
158    /// let outer = Rect::new((0, 0), (3, 3));
159    /// let inner = Rect::new((1, 1), (2, 2));
160    /// assert!(outer.contains_rectangle_exclusive(&inner));
161    /// assert!(!inner.contains_rectangle_exclusive(&outer));
162    ///
163    /// let not_inner = Rect::new((0, 0), (1, 1)); // This shares the boundary with `outer`.
164    /// assert!(!outer.contains_rectangle_exclusive(&not_inner));
165    /// ```
166    pub fn contains_rectangle_exclusive(&self, other: &Self) -> bool {
167        self.contains_point_exclusive(other.lower_left)
168            && self.contains_point_exclusive(other.upper_right)
169    }
170
171    /// Test if the both rectangles touch each other, i.e. if they either share a boundary or are overlapping.
172    pub fn touches(&self, other: &Self) -> bool {
173        !(self.lower_left.x > other.upper_right.x
174            || self.lower_left.y > other.upper_right.y
175            || self.upper_right.x < other.lower_left.x
176            || self.upper_right.y < other.lower_left.y)
177    }
178
179    /// Compute the boolean intersection of two rectangles.
180    /// This function excludes the boundaries, hence a zero-area intersection is considered `None`.
181    /// See `intersection_inclusive_bounds()` zero-area intersections should be returned as `Some(rectangle)`.
182    ///
183    /// # Example
184    ///
185    /// ```
186    /// use reda_geometry::prelude::*;
187    ///
188    /// // Create two overlapping rectangles.
189    /// let a = Rect::new((0, 0), (2, 2));
190    /// let b = Rect::new((1, 1), (3, 3));
191    ///
192    /// // Compute the intersection.
193    /// assert_eq!(a.intersection(&b), Some(Rect::new((1, 1), (2, 2))));
194    ///
195    /// // Create a non-overlapping rectangle.
196    /// let c = Rect::new((100, 100), (200, 200));
197    /// // The intersection with a non-overlapping rectangle is `None`.
198    /// assert_eq!(a.intersection(&c), None);
199    /// ```
200    pub fn intersection(&self, other: &Self) -> Option<Self> {
201        let llx = cmp::max(self.lower_left.x, other.lower_left.x);
202        let lly = cmp::max(self.lower_left.y, other.lower_left.y);
203
204        let urx = cmp::min(self.upper_right.x, other.upper_right.x);
205        let ury = cmp::min(self.upper_right.y, other.upper_right.y);
206
207        if llx < urx && lly < ury {
208            Some(Rect::new((llx, lly), (urx, ury)))
209        } else {
210            None
211        }
212    }
213
214    /// Compute the boolean intersection of two rectangles and include the boundaries.
215    /// This allows to get zero-area intersection results for example if the two
216    /// rectangles touch on a boundary or one of the rectangle is already zero-area.
217    ///
218    /// # Example
219    ///
220    /// ```
221    /// use reda_geometry::prelude::*;
222    ///
223    /// // Create two rectangles which intersect in a single point.
224    /// let a = Rect::new((0, 0), (2, 2));
225    /// let b = Rect::new((2, 2), (3, 3));
226    ///
227    /// // Compute the intersection.
228    /// assert_eq!(a.intersection_inclusive_bounds(&b), Some(Rect::new((2, 2), (2, 2))));
229    ///
230    /// ```
231    pub fn intersection_inclusive_bounds(&self, other: &Self) -> Option<Self> {
232        let llx = cmp::max(self.lower_left.x, other.lower_left.x);
233        let lly = cmp::max(self.lower_left.y, other.lower_left.y);
234
235        let urx = cmp::min(self.upper_right.x, other.upper_right.x);
236        let ury = cmp::min(self.upper_right.y, other.upper_right.y);
237
238        if llx <= urx && lly <= ury {
239            Some(Rect::new((llx, lly), (urx, ury)))
240        } else {
241            None
242        }
243    }
244
245    /// Create the smallest `Rect` that contains the original `Rect` and the `point`.
246    ///
247    /// # Example
248    ///
249    /// ```
250    /// use reda_geometry::prelude::*;
251    ///
252    /// let r1 = Rect::new((0,0), (1,2));
253    ///
254    /// let r2 = r1.add_point(Point::new(10, 11));
255    ///
256    /// assert_eq!(r2, Rect::new((0,0), (10,11)));
257    ///
258    /// ```
259    pub fn add_point(&self, point: Point<T>) -> Self {
260        Rect::new(
261            Point::new(
262                cmp::min(self.lower_left.x, point.x),
263                cmp::min(self.lower_left.y, point.y),
264            ),
265            Point::new(
266                cmp::max(self.upper_right.x, point.x),
267                cmp::max(self.upper_right.y, point.y),
268            ),
269        )
270    }
271
272    /// Get the smallest `Rect` that contains both rectangles `self` and `rect`.
273    ///
274    /// # Example
275    ///
276    /// ```
277    /// use reda_geometry::prelude::*;
278    ///
279    /// let r1 = Rect::new((0,0), (1,2));
280    /// let r2 = Rect::new((4,5), (6,7));
281    ///
282    /// let r3 = r1.add_rect(&r2);
283    ///
284    /// assert_eq!(r3, Rect::new((0,0), (6,7)));
285    ///
286    /// ```
287    pub fn add_rect(&self, rect: &Self) -> Self {
288        self.add_point(rect.lower_left).add_point(rect.upper_right)
289    }
290}
291
292impl<T: Sub<Output = T> + Copy + Ord + Zero> Rect<T> {
293    /// Compute the shortest from the rectangle to the point `p`.
294    /// The distance is zero if the point is inside the rectangle.
295    ///
296    /// # Example
297    ///
298    /// ```
299    /// use reda_geometry::prelude::*;
300    ///
301    /// let r = Rect::new((0,0), (10, 10));
302    ///
303    /// assert_eq!(r.distance_to_point((5, 15).into()), Vec2::new(0, 5));
304    ///
305    /// // Distance to point inside the rectangle is zero.
306    /// assert_eq!(r.distance_to_point((5, 5).into()), Vec2::new(0, 0));
307    ///
308    /// ```
309    pub fn distance_to_point(&self, p: Point<T>) -> Vec2<T> {
310        
311        let ll = self.lower_left();
312        let ul = self.upper_right();
313
314        // Compute x component of distance.
315        let dx_neg = (p.x - ll.x).min(Zero::zero());
316        let dx_pos = (p.x - ul.x).max(Zero::zero());
317        let dx = dx_neg + dx_pos;
318
319        // Compute y component of distance.
320        let dy_neg = (p.y - ll.y).min(Zero::zero());
321        let dy_pos = (p.y - ul.y).max(Zero::zero());
322        let dy = dy_neg + dy_pos;
323
324        Vec2::new(dx, dy)
325    }
326}
327
328impl<T: Copy + Sub<Output = T>> Rect<T> {
329    /// Compute the width of the rectangle.
330    #[inline]
331    pub fn width(&self) -> T {
332        self.upper_right.x - self.lower_left.x
333    }
334
335    /// Compute the height of the rectangle.
336    #[inline]
337    pub fn height(&self) -> T {
338        self.upper_right.y - self.lower_left.y
339    }
340}
341
342impl<T: Copy + Add<Output = T> + Div<Output = T> + One> Rect<T> {
343    /// Get the center point of the rectangle.
344    /// When using integer coordinates the resulting
345    /// coordinates will be truncated to the next integers.
346    pub fn center(&self) -> Point<T> {
347        let two = T::one() + T::one();
348        (self.lower_left() + self.upper_right()) / two
349    }
350}
351
352impl<T: Copy + Add<Output = T> + Sub<Output = T> + PartialOrd> Rect<T> {
353    /// Create an enlarged copy of this rectangle.
354    /// The vertical boundaries will be shifted towards the outside by `add_x`.
355    /// The horizontal boundaries will be shifted towards the outside by `add_y`.
356    pub fn sized(&self, add_x: T, add_y: T) -> Self {
357        Rect::new(
358            (self.lower_left.x - add_x, self.lower_left.y - add_y),
359            (self.upper_right.x + add_x, self.upper_right.y + add_y),
360        )
361    }
362
363    /// Create an enlarged copy of this rectangle.
364    pub fn sized_isotropic(&self, add: T) -> Self {
365        self.sized(add, add)
366    }
367}
368
369/// Iterate over all points of the rectangle.
370/// Starts with the lower left corner and iterates counter clock-wise.
371impl<'a, T> IntoIterator for &'a Rect<T>
372where
373    T: Copy,
374{
375    type Item = Point<T>;
376    type IntoIter = std::array::IntoIter<Self::Item, 4>;
377
378    fn into_iter(self) -> Self::IntoIter {
379        [
380            self.lower_left(),
381            self.lower_right(),
382            self.upper_right(),
383            self.upper_left(),
384        ]
385        .into_iter()
386    }
387}
388
389/// Iterate over all points of the rectangle.
390/// Starts with the lower left corner and iterates counter clock-wise.
391impl<T> IntoIterator for Rect<T>
392where
393    T: Copy,
394{
395    type Item = Point<T>;
396    type IntoIter = std::array::IntoIter<Self::Item, 4>;
397
398    fn into_iter(self) -> Self::IntoIter {
399        (&self).into_iter()
400    }
401}
402
403impl<T: Copy> MapPoint<T> for Rect<T> {
404    fn transform<F>(&self, transformate: F) -> Self
405        where 
406            F: Fn(Point<T>) -> Point<T> 
407    {
408        Self {
409            lower_left: transformate(self.lower_left),
410            upper_right: transformate(self.upper_right)
411        }    
412    }
413}
414
415impl<T: Copy> BoundingBox<T> for Rect<T> {
416    fn bounding_box(&self) -> Rect<T> {
417        *self
418    }
419}
420
421impl<T: Copy> TryBoundingBox<T> for Rect<T> {
422    fn try_bounding_box(&self) -> Option<Rect<T>> {
423        Some(self.bounding_box())
424    }
425}
426
427impl<Src: Copy + NumCast, Dst: Copy + NumCast + PartialOrd> Cast<Src, Dst> for Rect<Src> {
428    type Output = Rect<Dst>;
429
430    fn try_cast(&self) -> Option<Self::Output> {
431        match (self.lower_left.try_cast(), self.upper_right.try_cast()) {
432            (Some(ll), Some(ur)) => Some(Rect::new(ll, ur)),
433            _ => None,
434        }
435    }
436}
437
438impl<T: Copy> ToPolygon<T> for Rect<T> {
439    fn to_polygon(&self) -> Polygon<T> {
440        Polygon::from(self)
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    #[test]
449    fn test_distance_to_point() {
450        let rect = Rect::new((10, 10), (20, 20));
451    
452        assert_eq!(rect.distance_to_point((15, 15).into()).norm1(), 0);
453        assert_eq!(rect.distance_to_point((10, 10).into()).norm1(), 0);
454        assert_eq!(rect.distance_to_point((10, 20).into()).norm1(), 0);
455    
456        assert_eq!(rect.distance_to_point((0, 0).into()).norm1(), 20);
457        assert_eq!(rect.distance_to_point((0, 5).into()).norm1(), 15);
458        assert_eq!(rect.distance_to_point((0, 10).into()).norm1(), 10);
459        assert_eq!(rect.distance_to_point((0, 15).into()).norm1(), 10);
460        assert_eq!(rect.distance_to_point((0, 20).into()).norm1(), 10);
461        assert_eq!(rect.distance_to_point((0, 25).into()).norm1(), 15);
462    }
463
464    #[test]
465    fn test_rect_intersection() {
466        let a = Rect::new((0, 0), (2, 4));
467        let b = Rect::new((1, 2), (3, 5));
468        assert_eq!(a.intersection(&b), Some(Rect::new((1, 2), (2, 4))));
469
470        let a = Rect::new((0, 0), (2, 2));
471        let b = Rect::new((1, 1), (3, 3));
472        assert_eq!(a.intersection(&b), Some(Rect::new((1, 1), (2, 2))));
473
474        let a = Rect::new((0, 0), (1, 1));
475        let b = Rect::new((2, 2), (3, 3));
476        assert_eq!(a.intersection(&b), None);
477
478        let a = Rect::new((0, 0), (2, 2));
479        let b = Rect::new((1, 2), (5, 5));
480        assert_eq!(a.intersection(&b), None);
481    }
482}