| 1 | use crate::core::{ |
| 2 | storage::{XYZ, XYZW}, |
| 3 | traits::{quaternion::Quaternion, scalar::*, vector::*}, |
| 4 | }; |
| 5 | |
| 6 | impl<T: FloatEx> Quaternion<T> for XYZW<T> { |
| 7 | // fallback |
| 8 | type SIMDVector3 = XYZ<T>; |
| 9 | |
| 10 | #[inline(always)] |
| 11 | fn conjugate(self) -> Self { |
| 12 | Self::new(-self.x, -self.y, -self.z, self.w) |
| 13 | } |
| 14 | |
| 15 | #[inline] |
| 16 | fn lerp(self, end: Self, s: T) -> Self { |
| 17 | glam_assert!(FloatVector4::is_normalized(self)); |
| 18 | glam_assert!(FloatVector4::is_normalized(end)); |
| 19 | |
| 20 | let start = self; |
| 21 | let end = end; |
| 22 | let dot = start.dot(end); |
| 23 | let bias = if dot >= T::ZERO { T::ONE } else { T::NEG_ONE }; |
| 24 | let interpolated = start.add(end.mul_scalar(bias).sub(start).mul_scalar(s)); |
| 25 | interpolated.normalize() |
| 26 | } |
| 27 | |
| 28 | #[inline] |
| 29 | fn slerp(self, end: Self, s: T) -> Self { |
| 30 | // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/ |
| 31 | |
| 32 | glam_assert!(FloatVector4::is_normalized(self)); |
| 33 | glam_assert!(FloatVector4::is_normalized(end)); |
| 34 | |
| 35 | let dot = self.dot(end); |
| 36 | |
| 37 | if dot > T::from_f32(0.9995) { |
| 38 | // assumes lerp returns a normalized quaternion |
| 39 | self.lerp(end, s) |
| 40 | } else { |
| 41 | // assumes scalar_acos clamps the input to [-1.0, 1.0] |
| 42 | let theta = dot.acos_approx(); |
| 43 | let scale1 = (theta * (T::ONE - s)).sin(); |
| 44 | let scale2 = (theta * s).sin(); |
| 45 | let theta_sin = theta.sin(); |
| 46 | |
| 47 | self.mul_scalar(scale1) |
| 48 | .add(end.mul_scalar(scale2)) |
| 49 | .mul_scalar(theta_sin.recip()) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[inline] |
| 54 | fn mul_vector3(self, other: XYZ<T>) -> XYZ<T> { |
| 55 | glam_assert!(FloatVector4::is_normalized(self)); |
| 56 | let w = self.w; |
| 57 | let b = XYZ { |
| 58 | x: self.x, |
| 59 | y: self.y, |
| 60 | z: self.z, |
| 61 | }; |
| 62 | let b2 = b.dot(b); |
| 63 | other |
| 64 | .mul_scalar(w * w - b2) |
| 65 | .add(b.mul_scalar(other.dot(b) * T::TWO)) |
| 66 | .add(b.cross(other).mul_scalar(w * T::TWO)) |
| 67 | } |
| 68 | |
| 69 | #[inline] |
| 70 | fn mul_quaternion(self, other: Self) -> Self { |
| 71 | glam_assert!(FloatVector4::is_normalized(self)); |
| 72 | glam_assert!(FloatVector4::is_normalized(other)); |
| 73 | let (x0, y0, z0, w0) = self.into_tuple(); |
| 74 | let (x1, y1, z1, w1) = other.into_tuple(); |
| 75 | Self::new( |
| 76 | w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, |
| 77 | w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1, |
| 78 | w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1, |
| 79 | w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1, |
| 80 | ) |
| 81 | } |
| 82 | |
| 83 | #[inline(always)] |
| 84 | fn mul_float4_as_vector3(self, other: XYZ<T>) -> XYZ<T> { |
| 85 | self.mul_vector3(other) |
| 86 | } |
| 87 | } |