ori_graphics/
rect.rs

1use glam::Vec2;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq)]
4pub struct Rect {
5    pub min: Vec2,
6    pub max: Vec2,
7}
8
9impl Rect {
10    pub const ZERO: Self = Self::new(Vec2::ZERO, Vec2::ZERO);
11
12    pub const fn new(min: Vec2, max: Vec2) -> Self {
13        Self { min, max }
14    }
15
16    pub fn min_size(min: Vec2, size: Vec2) -> Self {
17        Self {
18            min,
19            max: min + size,
20        }
21    }
22
23    pub fn center_size(center: Vec2, size: Vec2) -> Self {
24        let half_size = size / 2.0;
25        Self {
26            min: center - half_size,
27            max: center + half_size,
28        }
29    }
30
31    pub fn round(self) -> Self {
32        Self {
33            min: self.min.round(),
34            max: self.max.round(),
35        }
36    }
37
38    pub fn ceil(self) -> Self {
39        Self {
40            min: self.min.floor(),
41            max: self.max.ceil(),
42        }
43    }
44
45    pub fn floor(self) -> Self {
46        Self {
47            min: self.min.ceil(),
48            max: self.max.floor(),
49        }
50    }
51
52    pub fn size(self) -> Vec2 {
53        self.max - self.min
54    }
55
56    pub fn width(self) -> f32 {
57        self.max.x - self.min.x
58    }
59
60    pub fn height(self) -> f32 {
61        self.max.y - self.min.y
62    }
63
64    pub fn center(self) -> Vec2 {
65        (self.min + self.max) / 2.0
66    }
67
68    pub fn contains(self, point: Vec2) -> bool {
69        let inside_x = point.x >= self.min.x && point.x <= self.max.x;
70        let inside_y = point.y >= self.min.y && point.y <= self.max.y;
71        inside_x && inside_y
72    }
73
74    pub fn union(self, other: Self) -> Self {
75        Self {
76            min: self.min.min(other.min),
77            max: self.max.max(other.max),
78        }
79    }
80
81    pub fn left(self) -> f32 {
82        self.min.x
83    }
84
85    pub fn right(self) -> f32 {
86        self.max.x
87    }
88
89    pub fn top(self) -> f32 {
90        self.min.y
91    }
92
93    pub fn bottom(self) -> f32 {
94        self.max.y
95    }
96
97    pub fn top_left(self) -> Vec2 {
98        self.min
99    }
100
101    pub fn top_right(self) -> Vec2 {
102        Vec2::new(self.max.x, self.min.y)
103    }
104
105    pub fn bottom_left(self) -> Vec2 {
106        Vec2::new(self.min.x, self.max.y)
107    }
108
109    pub fn bottom_right(self) -> Vec2 {
110        self.max
111    }
112
113    pub fn translate(self, offset: impl Into<Vec2>) -> Self {
114        let offset = offset.into();
115
116        Self {
117            min: self.min + offset,
118            max: self.max + offset,
119        }
120    }
121
122    pub fn pad(self, padding: impl Into<Vec2>) -> Self {
123        let padding = padding.into();
124
125        Self {
126            min: self.min - padding,
127            max: self.max + padding,
128        }
129    }
130}