Skip to main content

reda_geometry/
traits.rs

1use std::ops::{Add, Mul, Sub};
2use num_traits::{Num, NumCast, Zero};
3use crate::{base::{Angle, Vec2}, shape::{Point, Polygon, Rect}};
4
5pub trait CoordType: Num + Copy + PartialOrd + Sized {}
6impl<T: Num + Copy + PartialOrd> CoordType for T {}
7
8pub trait BoundingBox<T> {
9    fn bounding_box(&self) -> Rect<T>;
10}
11
12pub trait TryBoundingBox<T> {
13    fn try_bounding_box(&self) -> Option<Rect<T>>;
14}
15
16/// Translate the geometrical object
17pub trait Translate<T> {
18    fn translate(&self, v: Vec2<T>) -> Self;
19}
20
21/// Scale the geometrical shape. Scaling center is the origin `(0, 0)`.
22pub trait Scale<T> {
23    fn scale(&self, factor: T) -> Self;
24}
25
26/// Rotate by a integer multiple of 90 degrees.
27pub trait Rotate<T> {
28    fn rotate(&self, a: Angle) -> Self;
29}
30
31/// Mirror at the x or y axis.
32pub trait Mirror<T> {
33    fn mirror_x(&self) -> Self;
34    fn mirror_y(&self) -> Self;
35}
36
37/// Transform the geometrical object by transforming each point of it.
38pub trait MapPoint<T> {
39    fn transform<F>(&self, transformate: F) -> Self
40    where 
41        F: Fn(Point<T>) -> Point<T>;
42}
43
44impl<S, T> Scale<T> for S 
45where 
46    T: Copy + Mul<Output = T>,
47    S: MapPoint<T>,
48{
49    fn scale(&self, factor: T) -> Self {
50        self.transform(|p| p * factor)
51    }
52}
53
54impl<S, T> Translate<T> for S
55where
56    T: Copy + Add<Output = T>,
57    S: MapPoint<T>,
58{
59    fn translate(&self, v: Vec2<T>) -> S {
60        self.transform(|p: Point<T>| p + v)
61    }
62}
63
64impl<S, T> Rotate<T> for S
65where
66    T: Copy + Zero + Sub<Output = T>,
67    S: MapPoint<T>,
68{
69    fn rotate(&self, a: Angle) -> S {
70        self.transform(|p: Point<T>| match a {
71            Angle::R0 => p,
72            Angle::R90 => Point::new(T::zero() - p.y, p.x),
73            Angle::R180 => Point::zero() - p.vec2(),
74            Angle::R270 => Point::new(p.y, T::zero() - p.x),
75        })
76    }
77}
78
79impl<S, T> Mirror<T> for S 
80where 
81    T: Copy + Zero + Sub<Output = T>,
82    S: MapPoint<T>
83{
84    fn mirror_x(&self) -> Self {
85        self.transform(|p| Point::new(p.x, T::zero() - p.y))
86    }
87
88    fn mirror_y(&self) -> Self {
89        self.transform(|p| Point::new(T::zero() - p.x, p.y))
90    }
91}
92
93pub trait Cast<Src, Dst>
94where 
95    Src: NumCast,
96    Dst: NumCast,
97{
98    type Output;
99
100    fn try_cast(&self) -> Option<Self::Output>;
101    fn cast(&self) -> Self::Output {
102        self.try_cast().unwrap()
103    }
104}
105
106pub trait ToPolygon<T> {
107    fn to_polygon(&self) -> Polygon<T>;
108}