Skip to main content

fae/
types.rs

1//! Types used throughout the crate.
2
3/// Represents a rectangle.
4///
5/// # Usage
6/// ```
7/// # use fae::Rect;
8/// // Rects can be defined via the struct
9/// let rect = Rect { x: 1.0, y: 1.0, width: 5.0, height: 5.0 };
10/// // And via a tuple as well (x, y, width, height):
11/// let rect_ = (1.0, 1.0, 5.0, 5.0).into();
12/// assert_eq!(rect, rect_);
13/// ```
14///
15/// Tip: Many functions in `fae` take `Into<Rect>` as a parameter, in
16/// which case it is often cleaner to pass in a tuple, like `rect_`
17/// above, but without the `.into()`.
18// Note: Only axis-aligned rectangles are allowed (rotation is
19// specified via another parameter) because this is much more
20// optimizable, and I don't intend to support
21// non-axis-aligned-rectangles.
22#[derive(Clone, Copy, Debug, PartialEq)]
23pub struct Rect {
24    /// The x-coordinate of the top-left corner of this rectangle.
25    pub x: f32,
26    /// The y-coordinate of the top-left corner of this rectangle.
27    pub y: f32,
28    /// The width of this rectangle.
29    pub width: f32,
30    /// The height of this rectangle.
31    pub height: f32,
32}
33
34impl Rect {
35    pub(crate) fn into_corners(self) -> (f32, f32, f32, f32) {
36        (self.x, self.y, self.x + self.width, self.y + self.height)
37    }
38}
39
40impl From<(f32, f32, f32, f32)> for Rect {
41    fn from(from: (f32, f32, f32, f32)) -> Self {
42        Rect {
43            x: from.0,
44            y: from.1,
45            width: from.2,
46            height: from.3,
47        }
48    }
49}
50
51impl From<(i32, i32, i32, i32)> for Rect {
52    fn from(from: (i32, i32, i32, i32)) -> Self {
53        Rect {
54            x: from.0 as f32,
55            y: from.1 as f32,
56            width: from.2 as f32,
57            height: from.3 as f32,
58        }
59    }
60}
61
62impl From<RectPx> for Rect {
63    fn from(from: RectPx) -> Self {
64        Rect {
65            x: from.x as f32,
66            y: from.y as f32,
67            width: from.width as f32,
68            height: from.height as f32,
69        }
70    }
71}
72
73/// Like Rect, but i32-based. Internal use only, at least currently.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
75pub(crate) struct RectPx {
76    /// The x-coordinate of the top-left corner of this rectangle.
77    pub x: i32,
78    /// The y-coordinate of the top-left corner of this rectangle.
79    pub y: i32,
80    /// The width of this rectangle.
81    pub width: i32,
82    /// The height of this rectangle.
83    pub height: i32,
84}
85
86impl From<(i32, i32, i32, i32)> for RectPx {
87    fn from(from: (i32, i32, i32, i32)) -> Self {
88        RectPx {
89            x: from.0,
90            y: from.1,
91            width: from.2,
92            height: from.3,
93        }
94    }
95}
96
97impl From<RectPx> for (i32, i32, i32, i32) {
98    fn from(from: RectPx) -> Self {
99        (from.x, from.y, from.width, from.height)
100    }
101}