Skip to main content

lib_jsl_geometry/dim_2/
unit_vector2d.rs

1//! Concrete two-dimensional unit vector type.
2
3use crate::common::{
4    CanNormalize, CoordinatePrimitive, DotProduct, GeometricPrimitive, GeometricPrimitive2D,
5    GeometryMeasure, HasDimension, HasNorm, IsUnitVector, Normalize,
6};
7use crate::coordinate_systems::{CoordinateSystem2D, ToCartesian, ToPolar};
8use crate::two_d::coordinate_conversions;
9use crate::two_d::FreeVector2D;
10use std::fmt::{self, Display, Formatter};
11use std::hash::{Hash, Hasher};
12use std::ops::{Index, IndexMut};
13
14/// Concrete 2D unit-vector implementation whose stored coordinates may be Cartesian or polar.
15#[derive(Debug, Clone, Copy, PartialEq)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct UnitVector2D {
18    coords: [GeometryMeasure; 2],
19    coordinate_system: CoordinateSystem2D,
20}
21
22impl Eq for UnitVector2D {}
23
24impl Hash for UnitVector2D {
25    fn hash<H: Hasher>(&self, state: &mut H) {
26        for value in self.coords {
27            value.to_bits().hash(state);
28        }
29        self.coordinate_system.hash(state);
30    }
31}
32
33impl UnitVector2D {
34    /// Creates and normalizes a vector from Cartesian coordinates.
35    pub fn new(x: GeometryMeasure, y: GeometryMeasure) -> Self {
36        Self::new_in_system(x, y, CoordinateSystem2D::Cartesian)
37    }
38
39    /// Creates and normalizes a vector from raw coordinates in the supplied system.
40    pub fn new_in_system(
41        first: GeometryMeasure,
42        second: GeometryMeasure,
43        coordinate_system: CoordinateSystem2D,
44    ) -> Self {
45        let cartesian = coordinate_conversions::to_cartesian([first, second], coordinate_system);
46        Self::from_cartesian_components(cartesian, coordinate_system)
47    }
48
49    pub(crate) fn from_cartesian_components(
50        coords: [GeometryMeasure; 2],
51        coordinate_system: CoordinateSystem2D,
52    ) -> Self {
53        let norm = (coords[0] * coords[0] + coords[1] * coords[1]).sqrt();
54        let normalized = if norm == 0.0 {
55            [1.0, 0.0]
56        } else {
57            [coords[0] / norm, coords[1] / norm]
58        };
59        Self {
60            coords: coordinate_conversions::from_cartesian(normalized, coordinate_system),
61            coordinate_system,
62        }
63    }
64
65    /// Creates a unit vector by normalizing a free geometry vector.
66    pub fn from_vector(vector: FreeVector2D) -> Self {
67        Self::from_cartesian_components(vector.cartesian_components(), vector.coordinate_system())
68    }
69
70    /// Returns this unit vector as a free geometry vector with the same components.
71    pub fn as_vector(self) -> FreeVector2D {
72        FreeVector2D::from_cartesian_components(self.cartesian_components(), self.coordinate_system)
73    }
74
75    /// Returns the raw stored coordinates in the current coordinate system.
76    pub fn raw_components(&self) -> [GeometryMeasure; 2] {
77        self.coords
78    }
79
80    /// Returns the Cartesian `[x, y]` representation of this vector.
81    pub fn cartesian_components(&self) -> [GeometryMeasure; 2] {
82        coordinate_conversions::to_cartesian(self.coords, self.coordinate_system)
83    }
84
85    /// Returns the current coordinate system.
86    pub fn coordinate_system(&self) -> CoordinateSystem2D {
87        self.coordinate_system
88    }
89
90    /// Converts the stored coordinates to `coordinate_system` if needed.
91    pub fn set_coordinate_system(&mut self, coordinate_system: CoordinateSystem2D) {
92        if self.coordinate_system != coordinate_system {
93            let cartesian = self.cartesian_components();
94            self.coords = coordinate_conversions::from_cartesian(cartesian, coordinate_system);
95            self.coordinate_system = coordinate_system;
96        }
97    }
98
99    /// Returns a copy represented in the requested coordinate system.
100    pub fn converted_to(&self, coordinate_system: CoordinateSystem2D) -> Self {
101        let mut converted = *self;
102        converted.set_coordinate_system(coordinate_system);
103        converted
104    }
105
106    /// Returns the Cartesian x-component.
107    pub fn x(&self) -> GeometryMeasure {
108        self.cartesian_components()[0]
109    }
110
111    /// Returns the Cartesian y-component.
112    pub fn y(&self) -> GeometryMeasure {
113        self.cartesian_components()[1]
114    }
115}
116
117impl Display for UnitVector2D {
118    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
119        write!(
120            f,
121            "UnitVector2D({:?}, {}, {})",
122            self.coordinate_system, self.coords[0], self.coords[1]
123        )
124    }
125}
126
127impl GeometricPrimitive for UnitVector2D {}
128impl GeometricPrimitive2D for UnitVector2D {}
129impl CoordinatePrimitive for UnitVector2D {}
130impl IsUnitVector for UnitVector2D {}
131impl HasDimension for UnitVector2D {
132    const DIM: usize = 2;
133}
134
135impl AsRef<GeometryMeasure> for UnitVector2D {
136    fn as_ref(&self) -> &GeometryMeasure {
137        &self.coords[0]
138    }
139}
140
141impl AsMut<GeometryMeasure> for UnitVector2D {
142    fn as_mut(&mut self) -> &mut GeometryMeasure {
143        &mut self.coords[0]
144    }
145}
146
147impl Index<usize> for UnitVector2D {
148    type Output = GeometryMeasure;
149
150    fn index(&self, index: usize) -> &Self::Output {
151        &self.coords[index]
152    }
153}
154
155impl IndexMut<usize> for UnitVector2D {
156    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
157        &mut self.coords[index]
158    }
159}
160
161impl DotProduct for UnitVector2D {
162    type Output = GeometryMeasure;
163
164    fn dot(&self, rhs: &Self) -> <Self as DotProduct>::Output {
165        let lhs = self.cartesian_components();
166        let rhs = rhs.cartesian_components();
167        lhs[0] * rhs[0] + lhs[1] * rhs[1]
168    }
169}
170
171impl HasNorm for UnitVector2D {
172    fn norm(&self) -> GeometryMeasure {
173        1.0
174    }
175}
176
177impl Normalize for UnitVector2D {
178    fn normalized(&self) -> Self {
179        *self
180    }
181}
182
183impl CanNormalize for UnitVector2D {
184    fn normalize(&mut self) {
185        *self = Self::from_cartesian_components(self.cartesian_components(), self.coordinate_system);
186    }
187}
188
189impl ToCartesian for UnitVector2D {
190    type Cartesian = UnitVector2D;
191
192    fn to_cartesian(&self) -> Self::Cartesian {
193        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem2D::Cartesian)
194    }
195}
196
197impl ToPolar for UnitVector2D {
198    type Polar = UnitVector2D;
199
200    fn to_polar(&self) -> Self::Polar {
201        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem2D::Polar)
202    }
203}