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 let ratio = self.dot(&dir) / dir.magnitude2();
98 dir * ratio
99 }
100
101 #[inline]
103 fn normalized_reject(self, dir: Self) -> Self {
104 let scalar = self.dot(&dir);
105 let proj = dir * scalar;
106 self - proj
107 }
108
109 #[inline]
111 fn reject(self, dir: Self) -> Self {
112 let ratio = self.dot(&dir) / dir.magnitude2();
113 self - dir * ratio
114 }
115
116 #[inline]
118 fn normalized_reflect(self, dir: Self) -> Self {
119 let scalar = self.dot(&dir);
120 let proj = dir * scalar;
121 proj * (Self::Scalar::one() + Self::Scalar::one()) - self
122 }
123
124 #[inline]
126 fn reflect(self, dir: Self) -> Self {
127 let ratio = self.dot(&dir) / dir.magnitude2();
128 dir * ratio * (Self::Scalar::one() + Self::Scalar::one()) - self
129 }
130}
131
132impl<T: DotProduct<Output = Self::Scalar>> InnerSpace for T {}
133
134pub fn distance<T: AffineSpace>(a: T, b: T) -> <T::Diff as VectorSpace>::Scalar
136where
137 T::Diff: InnerSpace,
138{
139 (b - a).magnitude()
140}
141
142pub fn distance2<T: AffineSpace>(a: T, b: T) -> <T::Diff as VectorSpace>::Scalar
144where
145 T::Diff: InnerSpace,
146{
147 (b - a).magnitude2()
148}
149
150pub fn direction<T: AffineSpace>(a: T, b: T) -> T::Diff
152where
153 T::Diff: InnerSpace,
154{
155 (b - a).normalize()
156}