Skip to main content

model/layout/
rect.rs

1#[derive(Debug, Clone, Copy, PartialEq)]
2#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
3pub struct Rect {
4    pub x: u32,
5    pub y: u32,
6    pub width: u32,
7    pub height: u32,
8}
9
10impl Rect {
11    pub fn scissor(&self) -> (u32, u32, u32, u32) {
12        (self.x, self.y, self.width, self.height)
13    }
14
15    pub fn viewport(&self) -> (f32, f32, f32, f32) {
16        (
17            self.x as f32,
18            self.y as f32,
19            self.width as f32,
20            self.height as f32,
21        )
22    }
23}
24
25/// Float-precision pixel rect — element bounds, selection boxes, and other
26/// sub-pixel screen geometry. `Rect` (u32) stays the type for buffer/texture
27/// areas; this one is for visual geometry derived from f32 layout math.
28#[derive(Debug, Clone, Copy, PartialEq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30pub struct RectF {
31    pub x: f32,
32    pub y: f32,
33    pub width: f32,
34    pub height: f32,
35}
36
37impl RectF {
38    pub fn from_rect(r: &Rect) -> Self {
39        Self {
40            x: r.x as f32,
41            y: r.y as f32,
42            width: r.width as f32,
43            height: r.height as f32,
44        }
45    }
46
47    pub fn contains(&self, px: f32, py: f32) -> bool {
48        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
49    }
50
51    /// Grow by `pad` on every side (negative shrinks; width/height floor at 0).
52    pub fn expanded(&self, pad: f32) -> Self {
53        Self {
54            x: self.x - pad,
55            y: self.y - pad,
56            width: (self.width + pad * 2.0).max(0.0),
57            height: (self.height + pad * 2.0).max(0.0),
58        }
59    }
60
61    pub fn translated(&self, dx: f32, dy: f32) -> Self {
62        Self {
63            x: self.x + dx,
64            y: self.y + dy,
65            ..*self
66        }
67    }
68}
69
70#[derive(Debug, Clone, PartialEq)]
71#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
72pub struct ChartArea(pub Rect);
73
74#[derive(Debug, Clone, PartialEq)]
75#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
76pub struct DataArea(pub Rect);
77
78impl std::ops::Deref for ChartArea {
79    type Target = Rect;
80    fn deref(&self) -> &Rect {
81        &self.0
82    }
83}
84impl std::ops::DerefMut for ChartArea {
85    fn deref_mut(&mut self) -> &mut Rect {
86        &mut self.0
87    }
88}
89impl std::ops::Deref for DataArea {
90    type Target = Rect;
91    fn deref(&self) -> &Rect {
92        &self.0
93    }
94}
95impl std::ops::DerefMut for DataArea {
96    fn deref_mut(&mut self) -> &mut Rect {
97        &mut self.0
98    }
99}