Skip to main content

rayengine_core/
ui.rs

1//! Small anchored UI primitives shared by both dimensions.
2
3use crate::collision::Aabb2;
4use glam::Vec2;
5
6mod interaction;
7pub use interaction::{
8    UiActions, UiButton, UiCapture, UiId, UiInput, UiRegion, UiResponse, UiState,
9};
10
11/// A sized UI rectangle with normalized anchor and pivot coordinates.
12#[derive(Clone, Copy, Debug)]
13pub struct UiRect {
14    /// Point on the viewport: `(0,0)` is top left, `(1,1)` bottom right.
15    pub anchor: Vec2,
16    /// Point on this rectangle that sits at the anchor.
17    pub pivot: Vec2,
18    /// Offset from the anchor in UI units.
19    pub offset: Vec2,
20    /// Rectangle dimensions in UI units.
21    pub size: Vec2,
22}
23
24impl UiRect {
25    /// Top-left anchored rectangle.
26    pub fn top_left(offset: Vec2, size: Vec2) -> Self {
27        Self {
28            anchor: Vec2::ZERO,
29            pivot: Vec2::ZERO,
30            offset,
31            size,
32        }
33    }
34
35    /// Bottom-right anchored rectangle with matching pivot.
36    pub fn bottom_right(offset: Vec2, size: Vec2) -> Self {
37        Self {
38            anchor: Vec2::ONE,
39            pivot: Vec2::ONE,
40            offset,
41            size,
42        }
43    }
44
45    /// Resolves the rectangle against the viewport's logical size.
46    pub fn resolve(&self, logical_size: Vec2) -> Aabb2 {
47        let min = logical_size * self.anchor + self.offset - self.size * self.pivot;
48        Aabb2 {
49            min,
50            max: min + self.size,
51        }
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn anchored_ui_preserves_margin_as_view_expands() {
61        let rect = UiRect::bottom_right(Vec2::splat(-16.0), Vec2::new(200.0, 40.0));
62        for size in [Vec2::new(960.0, 540.0), Vec2::new(1400.0, 540.0)] {
63            assert_eq!(rect.resolve(size).max, size - Vec2::splat(16.0));
64        }
65    }
66}