Skip to main content

rapier2d/utils/
dot_product.rs

1//! SimdDot and SimdLength traits for generalized dot product and length.
2
3#[cfg(feature = "simd-is-enabled")]
4use crate::math::SimdReal;
5use crate::math::{Real, Vector};
6use crate::utils::SimdRealCopy;
7use na::{SimdRealField, Vector1, Vector2, Vector3};
8
9/// Trait for computing generalized dot products.
10pub trait DotProduct<Rhs>: Sized + Copy {
11    /// The result type of the dot product.
12    type Result: SimdRealField;
13    /// Computes the generalized dot product of `self` with `rhs`.
14    fn gdot(&self, rhs: Rhs) -> Self::Result;
15}
16
17/// Trait for computing generalized lengths.
18pub trait SimdLength: DotProduct<Self> {
19    /// Computes the SIMD length of this value.
20    fn simd_length(&self) -> Self::Result {
21        use crate::na::SimdComplexField;
22        self.gdot(*self).simd_sqrt()
23    }
24}
25
26impl<T: DotProduct<T>> SimdLength for T {}
27
28impl<N: SimdRealCopy> DotProduct<Vector3<N>> for Vector3<N> {
29    type Result = N;
30
31    fn gdot(&self, rhs: Vector3<N>) -> Self::Result {
32        self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
33    }
34}
35
36impl<N: SimdRealCopy> DotProduct<Vector2<N>> for Vector2<N> {
37    type Result = N;
38
39    fn gdot(&self, rhs: Vector2<N>) -> Self::Result {
40        self.x * rhs.x + self.y * rhs.y
41    }
42}
43
44impl<N: SimdRealCopy> DotProduct<Vector1<N>> for N {
45    type Result = N;
46
47    fn gdot(&self, rhs: Vector1<N>) -> Self::Result {
48        *self * rhs.x
49    }
50}
51
52impl DotProduct<Real> for Real {
53    type Result = Real;
54
55    fn gdot(&self, rhs: Real) -> Self::Result {
56        *self * rhs
57    }
58}
59
60#[cfg(feature = "simd-is-enabled")]
61impl DotProduct<SimdReal> for SimdReal {
62    type Result = SimdReal;
63
64    fn gdot(&self, rhs: SimdReal) -> Self::Result {
65        *self * rhs
66    }
67}
68
69impl<N: SimdRealCopy> DotProduct<N> for Vector1<N> {
70    type Result = N;
71
72    fn gdot(&self, rhs: N) -> Self::Result {
73        self.x * rhs
74    }
75}
76
77// Glam implementations for concrete Vector type
78impl DotProduct<Vector> for Vector {
79    type Result = Real;
80
81    fn gdot(&self, rhs: Vector) -> Self::Result {
82        self.dot(rhs)
83    }
84}