Skip to main content

blockworx_geom/
units.rs

1//! [`WorldPx`], the newtype for world-space magnitudes — radii, hit margins,
2//! snap thresholds, the lengths that scale with zoom on screen. Non-negative:
3//! a length below zero clamps to zero.
4
5use crate::bounded::{Bounded, Bounds};
6use crate::pos2::Pos2;
7
8pub struct WorldPxBounds;
9
10impl Bounds for WorldPxBounds {
11    const MIN: f32 = 0.0;
12    const MAX: f32 = f32::INFINITY;
13}
14
15pub type WorldPx = Bounded<WorldPxBounds>;
16
17impl WorldPx {
18    pub const ZERO: Self = Self::new(0.0);
19
20    /// An unbounded length — the "no limit" end of the range, used where a
21    /// length is a cap rather than a magnitude (an unwrapped text run).
22    pub const UNBOUNDED: Self = Self::max_value();
23
24    /// Whether `a` and `b` (world space) are within this length of each other.
25    pub fn within(self, a: Pos2, b: Pos2) -> bool {
26        a.distance(b) < self.get()
27    }
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33    use crate::pos2::pos2;
34
35    #[test]
36    fn within_is_a_strict_distance_check() {
37        let r = WorldPx::new(5.0);
38        assert!(r.within(pos2(0.0, 0.0), pos2(3.0, 0.0)));
39        assert!(!r.within(pos2(0.0, 0.0), pos2(5.0, 0.0)));
40    }
41
42    #[test]
43    fn lengths_cannot_be_negative() {
44        assert_eq!(WorldPx::new(-3.0).get(), 0.0);
45    }
46}