Skip to main content

lib_jsl_geometry/dim_3/
free_vector3d.rs

1//! Concrete three-dimensional free-vector type for the public geometry API.
2//!
3//! [`FreeVector3D`] represents displacement, scale-factor, and direction-with-magnitude data.
4//! Its stored coordinates may be Cartesian, spherical, or cylindrical, but arithmetic is carried
5//! out in Cartesian space and then converted back to the vector's declared coordinate system.
6
7use crate::common::{
8    CanNormalize, CanScale, CanScaleNonUniform, CoordinatePrimitive, CrossProduct, DotProduct,
9    GeometricPrimitive, GeometricPrimitive3D, GeometryMeasure, HasDimension, HasNorm, Normalize,
10    ScalarOperable, SelfAddition, SelfProductInner,
11};
12use crate::coordinate_systems::{
13    CoordinateSystem3D, ToCartesian, ToCylindrical, ToSpherical,
14};
15use crate::three_d::coordinate_conversions;
16use std::fmt::{self, Display, Formatter};
17use std::hash::{Hash, Hasher};
18use std::ops::{Add, Div, Index, IndexMut, Mul, Sub};
19
20/// Concrete 3D geometry-vector implementation whose stored coordinates may be Cartesian,
21/// spherical, or cylindrical.
22#[derive(Debug, Clone, Copy, PartialEq)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct FreeVector3D {
25    coords: [GeometryMeasure; 3],
26    coordinate_system: CoordinateSystem3D,
27}
28
29impl Eq for FreeVector3D {}
30
31impl Hash for FreeVector3D {
32    fn hash<H: Hasher>(&self, state: &mut H) {
33        for value in self.coords {
34            value.to_bits().hash(state);
35        }
36        self.coordinate_system.hash(state);
37    }
38}
39
40impl FreeVector3D {
41    /// Creates a vector from Cartesian `x`, `y`, and `z` components.
42    pub fn new(x: GeometryMeasure, y: GeometryMeasure, z: GeometryMeasure) -> Self {
43        Self {
44            coords: [x, y, z],
45            coordinate_system: CoordinateSystem3D::Cartesian,
46        }
47    }
48
49    /// Creates a vector from raw coordinates in the specified system.
50    pub fn new_in_system(
51        first: GeometryMeasure,
52        second: GeometryMeasure,
53        third: GeometryMeasure,
54        coordinate_system: CoordinateSystem3D,
55    ) -> Self {
56        Self {
57            coords: [first, second, third],
58            coordinate_system,
59        }
60    }
61
62    pub(crate) fn from_array_in_system(
63        coords: [GeometryMeasure; 3],
64        coordinate_system: CoordinateSystem3D,
65    ) -> Self {
66        Self {
67            coords,
68            coordinate_system,
69        }
70    }
71
72    pub(crate) fn from_cartesian_components(
73        coords: [GeometryMeasure; 3],
74        coordinate_system: CoordinateSystem3D,
75    ) -> Self {
76        Self::from_array_in_system(
77            coordinate_conversions::from_cartesian(coords, coordinate_system),
78            coordinate_system,
79        )
80    }
81
82    /// Returns the raw stored coordinates in the currently declared coordinate system.
83    pub fn raw_components(&self) -> [GeometryMeasure; 3] {
84        self.coords
85    }
86
87    /// Returns the Cartesian `[x, y, z]` representation of this vector.
88    pub fn cartesian_components(&self) -> [GeometryMeasure; 3] {
89        coordinate_conversions::to_cartesian(self.coords, self.coordinate_system)
90    }
91
92    /// Returns the current coordinate system.
93    pub fn coordinate_system(&self) -> CoordinateSystem3D {
94        self.coordinate_system
95    }
96
97    /// Converts the stored coordinates to `coordinate_system` if needed.
98    pub fn set_coordinate_system(&mut self, coordinate_system: CoordinateSystem3D) {
99        if self.coordinate_system != coordinate_system {
100            let cartesian = self.cartesian_components();
101            self.coords = coordinate_conversions::from_cartesian(cartesian, coordinate_system);
102            self.coordinate_system = coordinate_system;
103        }
104    }
105
106    /// Returns a copy represented in the requested coordinate system.
107    pub fn converted_to(&self, coordinate_system: CoordinateSystem3D) -> Self {
108        let mut converted = *self;
109        converted.set_coordinate_system(coordinate_system);
110        converted
111    }
112
113    /// Returns the Cartesian x-component.
114    pub fn x(&self) -> GeometryMeasure {
115        self.cartesian_components()[0]
116    }
117
118    /// Returns the Cartesian y-component.
119    pub fn y(&self) -> GeometryMeasure {
120        self.cartesian_components()[1]
121    }
122
123    /// Returns the Cartesian z-component.
124    pub fn z(&self) -> GeometryMeasure {
125        self.cartesian_components()[2]
126    }
127}
128
129impl Display for FreeVector3D {
130    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
131        write!(
132            f,
133            "FreeVector3D({:?}, {}, {}, {})",
134            self.coordinate_system, self.coords[0], self.coords[1], self.coords[2]
135        )
136    }
137}
138
139impl GeometricPrimitive for FreeVector3D {}
140impl GeometricPrimitive3D for FreeVector3D {}
141impl CoordinatePrimitive for FreeVector3D {}
142impl HasDimension for FreeVector3D {
143    const DIM: usize = 3;
144}
145
146impl AsRef<GeometryMeasure> for FreeVector3D {
147    fn as_ref(&self) -> &GeometryMeasure {
148        &self.coords[0]
149    }
150}
151
152impl AsMut<GeometryMeasure> for FreeVector3D {
153    fn as_mut(&mut self) -> &mut GeometryMeasure {
154        &mut self.coords[0]
155    }
156}
157
158impl Index<usize> for FreeVector3D {
159    type Output = GeometryMeasure;
160
161    fn index(&self, index: usize) -> &Self::Output {
162        &self.coords[index]
163    }
164}
165
166impl IndexMut<usize> for FreeVector3D {
167    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
168        &mut self.coords[index]
169    }
170}
171
172impl Add<GeometryMeasure> for FreeVector3D {
173    type Output = Self;
174
175    fn add(self, rhs: GeometryMeasure) -> Self::Output {
176        let cartesian = self.cartesian_components();
177        Self::from_cartesian_components(
178            [cartesian[0] + rhs, cartesian[1] + rhs, cartesian[2] + rhs],
179            self.coordinate_system,
180        )
181    }
182}
183
184impl Sub<GeometryMeasure> for FreeVector3D {
185    type Output = Self;
186
187    fn sub(self, rhs: GeometryMeasure) -> Self::Output {
188        let cartesian = self.cartesian_components();
189        Self::from_cartesian_components(
190            [cartesian[0] - rhs, cartesian[1] - rhs, cartesian[2] - rhs],
191            self.coordinate_system,
192        )
193    }
194}
195
196impl Mul<GeometryMeasure> for FreeVector3D {
197    type Output = Self;
198
199    fn mul(self, rhs: GeometryMeasure) -> Self::Output {
200        let cartesian = self.cartesian_components();
201        Self::from_cartesian_components(
202            [cartesian[0] * rhs, cartesian[1] * rhs, cartesian[2] * rhs],
203            self.coordinate_system,
204        )
205    }
206}
207
208impl Div<GeometryMeasure> for FreeVector3D {
209    type Output = Self;
210
211    fn div(self, rhs: GeometryMeasure) -> Self::Output {
212        let cartesian = self.cartesian_components();
213        Self::from_cartesian_components(
214            [cartesian[0] / rhs, cartesian[1] / rhs, cartesian[2] / rhs],
215            self.coordinate_system,
216        )
217    }
218}
219
220impl Add for FreeVector3D {
221    type Output = Self;
222
223    fn add(self, rhs: Self) -> Self::Output {
224        let lhs = self.cartesian_components();
225        let rhs = rhs.cartesian_components();
226        Self::from_cartesian_components(
227            [lhs[0] + rhs[0], lhs[1] + rhs[1], lhs[2] + rhs[2]],
228            self.coordinate_system,
229        )
230    }
231}
232
233impl Sub for FreeVector3D {
234    type Output = Self;
235
236    fn sub(self, rhs: Self) -> Self::Output {
237        let lhs = self.cartesian_components();
238        let rhs = rhs.cartesian_components();
239        Self::from_cartesian_components(
240            [lhs[0] - rhs[0], lhs[1] - rhs[1], lhs[2] - rhs[2]],
241            self.coordinate_system,
242        )
243    }
244}
245
246impl Mul<FreeVector3D> for FreeVector3D {
247    type Output = GeometryMeasure;
248
249    fn mul(self, rhs: FreeVector3D) -> Self::Output {
250        let lhs = self.cartesian_components();
251        let rhs = rhs.cartesian_components();
252        lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2]
253    }
254}
255
256impl ScalarOperable for FreeVector3D {}
257impl SelfAddition for FreeVector3D {}
258impl SelfProductInner for FreeVector3D {}
259
260impl CanScale for FreeVector3D {
261    fn scale(&mut self, factor: GeometryMeasure) {
262        *self = *self * factor;
263    }
264}
265
266impl CanScaleNonUniform for FreeVector3D {
267    type ScaleVector = FreeVector3D;
268
269    fn scale_non_uniform(&mut self, factors: &Self::ScaleVector) {
270        let coords = self.cartesian_components();
271        let factor_coords = factors.cartesian_components();
272        *self = Self::from_cartesian_components(
273            [
274                coords[0] * factor_coords[0],
275                coords[1] * factor_coords[1],
276                coords[2] * factor_coords[2],
277            ],
278            self.coordinate_system,
279        );
280    }
281}
282
283impl DotProduct for FreeVector3D {
284    type Output = GeometryMeasure;
285
286    fn dot(&self, rhs: &Self) -> <Self as DotProduct>::Output {
287        let lhs = self.cartesian_components();
288        let rhs = rhs.cartesian_components();
289        lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2]
290    }
291}
292
293impl CrossProduct for FreeVector3D {
294    type Output = FreeVector3D;
295
296    fn cross(&self, rhs: &Self) -> <Self as CrossProduct>::Output {
297        let lhs = self.cartesian_components();
298        let rhs = rhs.cartesian_components();
299        Self::from_cartesian_components(
300            [
301                lhs[1] * rhs[2] - lhs[2] * rhs[1],
302                lhs[2] * rhs[0] - lhs[0] * rhs[2],
303                lhs[0] * rhs[1] - lhs[1] * rhs[0],
304            ],
305            self.coordinate_system,
306        )
307    }
308}
309
310impl HasNorm for FreeVector3D {
311    fn norm(&self) -> GeometryMeasure {
312        let coords = self.cartesian_components();
313        (coords[0] * coords[0] + coords[1] * coords[1] + coords[2] * coords[2]).sqrt()
314    }
315}
316
317impl Normalize for FreeVector3D {
318    fn normalized(&self) -> Self {
319        let norm = self.norm();
320        if norm == 0.0 {
321            Self::new(0.0, 0.0, 0.0)
322        } else {
323            Self::from_cartesian_components(
324                [self.x() / norm, self.y() / norm, self.z() / norm],
325                self.coordinate_system,
326            )
327        }
328    }
329}
330
331impl CanNormalize for FreeVector3D {
332    fn normalize(&mut self) {
333        *self = self.normalized();
334    }
335}
336
337impl ToCartesian for FreeVector3D {
338    type Cartesian = FreeVector3D;
339
340    fn to_cartesian(&self) -> Self::Cartesian {
341        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem3D::Cartesian)
342    }
343}
344
345impl ToSpherical for FreeVector3D {
346    type Spherical = FreeVector3D;
347
348    fn to_spherical(&self) -> Self::Spherical {
349        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem3D::Spherical)
350    }
351}
352
353impl ToCylindrical for FreeVector3D {
354    type Cylindrical = FreeVector3D;
355
356    fn to_cylindrical(&self) -> Self::Cylindrical {
357        Self::from_cartesian_components(self.cartesian_components(), CoordinateSystem3D::Cylindrical)
358    }
359}