Skip to main content

paiagram_core/units/
distance.rs

1use bevy::prelude::Reflect;
2use derive_more::{Add, AddAssign, Sub, SubAssign};
3
4/// The length or distance represented in meters
5#[derive(Reflect, Debug, Clone, Copy, Add, AddAssign, Sub, SubAssign)]
6pub struct Distance(pub i32);
7
8impl Distance {
9    pub const ZERO: Self = Distance(0);
10    #[inline]
11    pub fn from_km(km: f32) -> Self {
12        Distance((km * 1000.0).round() as i32)
13    }
14    #[inline]
15    pub fn from_m(m: i32) -> Self {
16        Distance(m)
17    }
18}
19
20impl std::iter::Sum for Distance {
21    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
22        let mut s = Distance::ZERO;
23        for i in iter {
24            s += i
25        }
26        s
27    }
28}
29
30impl std::fmt::Display for Distance {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        if self.0 <= 1000 {
33            write!(f, "{}m", self.0)
34        } else {
35            write!(f, "{}.{:03}km", self.0 / 1000, self.0 % 1000)
36        }
37    }
38}
39
40impl std::ops::Mul<i32> for Distance {
41    type Output = Self;
42    fn mul(self, rhs: i32) -> Self::Output {
43        Self(self.0 * rhs)
44    }
45}
46
47impl std::ops::MulAssign<i32> for Distance {
48    fn mul_assign(&mut self, rhs: i32) {
49        self.0 *= rhs;
50    }
51}
52
53impl std::ops::Mul<f32> for Distance {
54    type Output = Self;
55    fn mul(self, rhs: f32) -> Self::Output {
56        Self((self.0 as f32 * rhs).round() as i32)
57    }
58}
59
60impl std::ops::MulAssign<f32> for Distance {
61    fn mul_assign(&mut self, rhs: f32) {
62        self.0 = (self.0 as f32 * rhs).round() as i32;
63    }
64}
65
66impl std::ops::Div<i32> for Distance {
67    type Output = Self;
68    fn div(self, rhs: i32) -> Self::Output {
69        Self(self.0 / rhs)
70    }
71}
72
73impl std::ops::DivAssign<i32> for Distance {
74    fn div_assign(&mut self, rhs: i32) {
75        self.0 /= rhs
76    }
77}
78
79impl std::ops::Div<f32> for Distance {
80    type Output = Self;
81    fn div(self, rhs: f32) -> Self::Output {
82        Self((self.0 as f32 / rhs).round() as i32)
83    }
84}
85
86impl std::ops::DivAssign<f32> for Distance {
87    fn div_assign(&mut self, rhs: f32) {
88        self.0 = (self.0 as f32 / rhs).round() as i32;
89    }
90}