fey_math/
radians.rs

1use crate::{Cardinal, Degrees, Float, Octal, Rotations, impl_angle};
2use serde::{Deserialize, Serialize};
3
4pub type RadiansF = Radians<f32>;
5
6/// An angle represented in radians.
7#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
8#[serde(transparent)]
9#[repr(transparent)]
10pub struct Radians<T>(pub T);
11
12impl_angle!(Radians, from_radians, to_radians);
13
14/// Create a [`Radians`].
15#[inline]
16pub const fn rads<T>(value: T) -> Radians<T> {
17    Radians(value)
18}
19
20impl<T: Float> Radians<T> {
21    /// Convert from radians.
22    #[inline]
23    pub fn from_radians(value: Radians<T>) -> Self {
24        value
25    }
26
27    /// Convert from degrees.
28    #[inline]
29    pub fn from_degrees(value: Degrees<T>) -> Self {
30        Self(T::to_radians(value.0))
31    }
32
33    /// Convert from rotations.
34    #[inline]
35    pub fn from_rotations(value: Rotations<T>) -> Self {
36        Self(value.0 * T::TAU)
37    }
38
39    /// Convert from a cardinal direction.
40    #[inline]
41    pub fn from_cardinal(value: Cardinal) -> Self {
42        Self(match value {
43            Cardinal::East => T::ZERO,
44            Cardinal::South => T::PI_OVER_2,
45            Cardinal::West => T::PI,
46            Cardinal::North => -T::PI_OVER_2,
47        })
48    }
49
50    /// Convert from an octal direction.
51    #[inline]
52    pub fn from_octal(value: Octal) -> Self {
53        Self(match value {
54            Octal::East => T::ZERO,
55            Octal::SouthEast => T::PI_OVER_4,
56            Octal::South => T::PI_OVER_2,
57            Octal::SouthWest => T::PI_OVER_2 + T::PI_OVER_4,
58            Octal::West => T::PI,
59            Octal::NorthWest => -T::PI_OVER_4,
60            Octal::North => -T::PI_OVER_4,
61            Octal::NorthEast => -(T::PI_OVER_2 + T::PI_OVER_4),
62        })
63    }
64
65    /// Wraps the angle into the range `(-PI, PI]`.
66    #[inline]
67    pub fn wrap(self) -> Self {
68        let angle = self.0;
69        Self(if angle > -T::PI && angle <= T::PI {
70            angle
71        } else {
72            let angle = angle % T::TAU;
73            if angle <= -T::PI {
74                angle + T::TAU
75            } else if angle > T::PI {
76                angle - T::TAU
77            } else {
78                angle
79            }
80        })
81    }
82}