Skip to main content

sim_engine/
math.rs

1use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
2
3/// A 2D vector used for world-space and screen-space coordinates.
4///
5/// The type is intentionally unitless. Callers should document whether a value
6/// is in simulation world units, logical screen pixels, physical surface pixels,
7/// or another coordinate space.
8#[derive(Debug, Clone, Copy, PartialEq, Default)]
9pub struct Vec2 {
10    pub(crate) x: f32,
11    pub(crate) y: f32,
12}
13
14impl Vec2 {
15    /// Vector with both components set to `0.0`.
16    pub const ZERO: Self = Self::new(0.0, 0.0);
17    /// Vector with both components set to `1.0`.
18    pub const ONE: Self = Self::new(1.0, 1.0);
19    /// Positive unit vector on the x axis.
20    pub const X: Self = Self::new(1.0, 0.0);
21    /// Positive unit vector on the y axis.
22    pub const Y: Self = Self::new(0.0, 1.0);
23
24    /// Builds a vector from explicit components.
25    pub const fn new(x: f32, y: f32) -> Self {
26        Self { x, y }
27    }
28
29    /// Returns the horizontal component.
30    pub const fn x(self) -> f32 {
31        self.x
32    }
33
34    /// Returns the vertical component.
35    pub const fn y(self) -> f32 {
36        self.y
37    }
38
39    /// Builds a vector with both components set to the same value.
40    pub fn splat(value: f32) -> Self {
41        Self::new(value, value)
42    }
43
44    /// Returns the squared vector length.
45    ///
46    /// Use this instead of [`Vec2::length`] when only relative distance matters.
47    pub fn length_squared(self) -> f32 {
48        self.x * self.x + self.y * self.y
49    }
50
51    /// Returns the Euclidean vector length.
52    pub fn length(self) -> f32 {
53        self.x.hypot(self.y)
54    }
55
56    /// Returns the dot product between two vectors.
57    pub fn dot(self, other: Self) -> f32 {
58        self.x * other.x + self.y * other.y
59    }
60
61    /// Returns a unit-length vector with the same direction.
62    ///
63    /// Zero-length and near-zero vectors return [`Vec2::ZERO`] instead of NaN.
64    pub fn normalized(self) -> Self {
65        if !self.is_finite() {
66            Self::ZERO
67        } else {
68            let maximum_component = self.x.abs().max(self.y.abs());
69            if maximum_component <= f32::EPSILON {
70                return Self::ZERO;
71            }
72            let scaled = self / maximum_component;
73            let length = scaled.length();
74            if length <= f32::EPSILON {
75                Self::ZERO
76            } else {
77                scaled / length
78            }
79        }
80    }
81
82    /// Returns a perpendicular vector rotated 90 degrees counter-clockwise.
83    pub fn perp(self) -> Self {
84        Self::new(-self.y, self.x)
85    }
86
87    /// Linearly interpolates toward `end`.
88    ///
89    /// `amount` is not clamped so callers can intentionally extrapolate.
90    pub fn lerp(self, end: Self, amount: f32) -> Self {
91        if !self.is_finite() || !end.is_finite() || !amount.is_finite() {
92            return self;
93        }
94        Self::new(
95            stable_lerp_component(self.x, end.x, amount),
96            stable_lerp_component(self.y, end.y, amount),
97        )
98    }
99
100    /// Returns true when both components are finite values.
101    pub fn is_finite(self) -> bool {
102        self.x.is_finite() && self.y.is_finite()
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::{Rect, Vec2};
109
110    #[test]
111    fn normalization_preserves_large_finite_direction() {
112        let normalized = Vec2::new(3.0e38, 3.0e38).normalized();
113
114        assert!(normalized.is_finite());
115        assert!((normalized.length() - 1.0).abs() < 0.0001);
116        assert!(normalized.x > 0.0 && normalized.y > 0.0);
117    }
118
119    #[test]
120    fn interpolation_and_rect_center_stay_finite_at_extremes() {
121        let midpoint = Vec2::splat(f32::MAX).lerp(Vec2::splat(-f32::MAX), 0.5);
122        assert_eq!(midpoint, Vec2::ZERO);
123
124        let rect = Rect::new(Vec2::splat(f32::MAX), Vec2::splat(f32::MAX));
125        assert_eq!(rect.center(), Vec2::splat(f32::MAX));
126    }
127}
128
129impl Add for Vec2 {
130    type Output = Self;
131
132    fn add(self, rhs: Self) -> Self::Output {
133        Self::new(self.x + rhs.x, self.y + rhs.y)
134    }
135}
136
137impl AddAssign for Vec2 {
138    fn add_assign(&mut self, rhs: Self) {
139        *self = *self + rhs;
140    }
141}
142
143impl Sub for Vec2 {
144    type Output = Self;
145
146    fn sub(self, rhs: Self) -> Self::Output {
147        Self::new(self.x - rhs.x, self.y - rhs.y)
148    }
149}
150
151impl SubAssign for Vec2 {
152    fn sub_assign(&mut self, rhs: Self) {
153        *self = *self - rhs;
154    }
155}
156
157impl Mul<f32> for Vec2 {
158    type Output = Self;
159
160    fn mul(self, rhs: f32) -> Self::Output {
161        Self::new(self.x * rhs, self.y * rhs)
162    }
163}
164
165impl MulAssign<f32> for Vec2 {
166    fn mul_assign(&mut self, rhs: f32) {
167        *self = *self * rhs;
168    }
169}
170
171impl Div<f32> for Vec2 {
172    type Output = Self;
173
174    fn div(self, rhs: f32) -> Self::Output {
175        Self::new(self.x / rhs, self.y / rhs)
176    }
177}
178
179impl DivAssign<f32> for Vec2 {
180    fn div_assign(&mut self, rhs: f32) {
181        *self = *self / rhs;
182    }
183}
184
185impl Neg for Vec2 {
186    type Output = Self;
187
188    fn neg(self) -> Self::Output {
189        Self::new(-self.x, -self.y)
190    }
191}
192
193/// Axis-aligned rectangle represented by minimum and maximum corners.
194///
195/// The rectangle may be constructed with inverted coordinates. Call
196/// [`Rect::normalized`] before using width or height when input ordering is not
197/// trusted.
198#[derive(Debug, Clone, Copy, PartialEq)]
199pub struct Rect {
200    pub(crate) min: Vec2,
201    pub(crate) max: Vec2,
202}
203
204impl Rect {
205    /// Builds a rectangle from two corners in the caller's coordinate space.
206    pub fn new(min: Vec2, max: Vec2) -> Self {
207        Self { min, max }
208    }
209
210    /// Returns the first stored corner, which is the minimum after normalization.
211    pub const fn min(self) -> Vec2 {
212        self.min
213    }
214
215    /// Returns the second stored corner, which is the maximum after normalization.
216    pub const fn max(self) -> Vec2 {
217        self.max
218    }
219
220    /// Builds a rectangle from its center and size.
221    ///
222    /// Negative size components are allowed and can be normalized later.
223    pub fn from_center_size(center: Vec2, size: Vec2) -> Self {
224        let half = size * 0.5;
225        Self::new(center - half, center + half)
226    }
227
228    /// Builds a rectangle from its minimum corner and size.
229    ///
230    /// Negative size components are allowed and can be normalized later.
231    pub fn from_min_size(min: Vec2, size: Vec2) -> Self {
232        Self::new(min, min + size)
233    }
234
235    /// Returns `max.x - min.x` in the rectangle's coordinate space.
236    pub fn width(self) -> f32 {
237        self.max.x - self.min.x
238    }
239
240    /// Returns `max.y - min.y` in the rectangle's coordinate space.
241    pub fn height(self) -> f32 {
242        self.max.y - self.min.y
243    }
244
245    /// Returns width and height as a vector in the rectangle's coordinate space.
246    pub fn size(self) -> Vec2 {
247        Vec2::new(self.width(), self.height())
248    }
249
250    /// Returns the midpoint between `min` and `max`.
251    pub fn center(self) -> Vec2 {
252        Vec2::new(
253            stable_midpoint(self.min.x, self.max.x),
254            stable_midpoint(self.min.y, self.max.y),
255        )
256    }
257
258    /// Expands all edges outward by `amount`.
259    ///
260    /// Negative values shrink the rectangle.
261    pub fn expand(self, amount: f32) -> Self {
262        Self::new(
263            self.min - Vec2::splat(amount),
264            self.max + Vec2::splat(amount),
265        )
266    }
267
268    /// Returns a rectangle whose `min` components are not greater than `max`.
269    pub fn normalized(self) -> Self {
270        Self::new(
271            Vec2::new(self.min.x.min(self.max.x), self.min.y.min(self.max.y)),
272            Vec2::new(self.min.x.max(self.max.x), self.min.y.max(self.max.y)),
273        )
274    }
275}
276
277fn stable_lerp_component(start: f32, end: f32, amount: f32) -> f32 {
278    let value = f64::from(start) + (f64::from(end) - f64::from(start)) * f64::from(amount);
279    value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
280}
281
282fn stable_midpoint(first: f32, second: f32) -> f32 {
283    ((f64::from(first) + f64::from(second)) * 0.5) as f32
284}