Skip to main content

astrelis_geometry/chart/
rect.rs

1//! Rectangular bounds utility for chart rendering.
2
3use glam::Vec2;
4
5/// Rectangular bounds for chart rendering.
6#[derive(Debug, Clone, Copy, PartialEq)]
7pub struct Rect {
8    /// X position (left)
9    pub x: f32,
10    /// Y position (top)
11    pub y: f32,
12    /// Width
13    pub width: f32,
14    /// Height
15    pub height: f32,
16}
17
18impl Rect {
19    /// Create a new rect.
20    pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
21        Self {
22            x,
23            y,
24            width,
25            height,
26        }
27    }
28
29    /// Create from position and size.
30    pub fn from_pos_size(pos: Vec2, size: Vec2) -> Self {
31        Self {
32            x: pos.x,
33            y: pos.y,
34            width: size.x,
35            height: size.y,
36        }
37    }
38
39    /// Get the position as a Vec2.
40    pub fn position(&self) -> Vec2 {
41        Vec2::new(self.x, self.y)
42    }
43
44    /// Get the size as a Vec2.
45    pub fn size(&self) -> Vec2 {
46        Vec2::new(self.width, self.height)
47    }
48
49    /// Get the center point.
50    pub fn center(&self) -> Vec2 {
51        Vec2::new(self.x + self.width * 0.5, self.y + self.height * 0.5)
52    }
53
54    /// Inset the rect by a padding amount.
55    pub fn inset(&self, padding: f32) -> Self {
56        Self {
57            x: self.x + padding,
58            y: self.y + padding,
59            width: (self.width - padding * 2.0).max(0.0),
60            height: (self.height - padding * 2.0).max(0.0),
61        }
62    }
63
64    /// Check if a point is inside the rect.
65    pub fn contains(&self, point: Vec2) -> bool {
66        point.x >= self.x
67            && point.x <= self.x + self.width
68            && point.y >= self.y
69            && point.y <= self.y + self.height
70    }
71
72    /// Get the right edge.
73    pub fn right(&self) -> f32 {
74        self.x + self.width
75    }
76
77    /// Get the bottom edge.
78    pub fn bottom(&self) -> f32 {
79        self.y + self.height
80    }
81}