1#![no_std]
2#![deny(missing_docs)]
3use num_traits::{One, real::Real};
13
14pub use vector_space::*;
15
16pub trait DotProduct<T = Self>: VectorSpace {
18 type Output;
20
21 fn dot(&self, other: &T) -> <Self as DotProduct<T>>::Output;
23}
24
25impl DotProduct for f32 {
26 type Output = Self;
27 fn dot(&self, other: &Self) -> Self {
28 *self * *other
29 }
30}
31impl DotProduct for f64 {
32 type Output = Self;
33 fn dot(&self, other: &Self) -> Self {
34 *self * *other
35 }
36}
37
38pub trait InnerSpace: DotProduct<Output = <Self as VectorSpace>::Scalar> {
40 #[inline]
45 fn magnitude2(&self) -> Self::Scalar {
46 self.dot(self)
47 }
48
49 #[inline]
51 fn magnitude(&self) -> Self::Scalar {
52 self.magnitude2().sqrt()
53 }
54
55 #[inline]
57 fn normalize(self) -> Self {
58 let mag = self.magnitude();
59 self / mag
60 }
61
62 #[inline]
64 fn angle(&self, other: &Self) -> Self::Scalar {
65 (self.dot(other) / (self.magnitude() * other.magnitude())).acos()
66 }
67
68 #[inline]
70 fn with_magnitude(self, magnitude: Self::Scalar) -> Self {
71 let mag = self.magnitude();
72 self * (magnitude / mag)
73 }
74
75 #[inline]
77 fn with_direction(self, dir: Self) -> Self {
78 dir * self.magnitude()
79 }
80
81 #[inline]
83 fn query_axis(&self, dir: Self) -> Self::Scalar {
84 self.dot(&dir.normalize())
85 }
86
87 #[inline]
89 fn normalized_project(self, dir: Self) -> Self {
90 let scalar = self.dot(&dir);
91 dir * scalar
92 }
93
94 #[inline]
96 fn project(self, dir: Self) -> Self {
97 self.normalized_project(dir.normalize())
98 }
99
100 #[inline]
102 fn normalized_reject(self, dir: Self) -> Self {
103 let scalar = self.dot(&dir);
104 let proj = dir * scalar;
105 self - proj
106 }
107
108 #[inline]
110 fn reject(self, dir: Self) -> Self {
111 self.normalized_reject(dir.normalize())
112 }
113
114 #[inline]
116 fn normalized_reflect(self, dir: Self) -> Self {
117 let scalar = self.dot(&dir);
118 let proj = dir * scalar;
119 proj * (Self::Scalar::one() + Self::Scalar::one()) - self
120 }
121
122 #[inline]
124 fn reflect(self, dir: Self) -> Self {
125 self.normalized_reflect(dir.normalize())
126 }
127}
128
129impl<T: DotProduct<Output = Self::Scalar>> InnerSpace for T {}
130
131pub fn distance<T: AffineSpace>(a: T, b: T) -> <T::Diff as VectorSpace>::Scalar
133where
134 T::Diff: InnerSpace,
135{
136 (b - a).magnitude()
137}
138
139pub fn distance2<T: AffineSpace>(a: T, b: T) -> <T::Diff as VectorSpace>::Scalar
141where
142 T::Diff: InnerSpace,
143{
144 (b - a).magnitude2()
145}