1use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
2
3use super::scalar::{Float, approx, degrees, radians, valid_tolerance};
4use super::vector::Vec3;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum RotationOrder {
9 Xyz,
10 Xzy,
11 Yxz,
12 Yzx,
13 Zxy,
14 Zyx,
15}
16
17#[repr(C)]
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct Quat<T: Float = f32> {
21 pub x: T,
22 pub y: T,
23 pub z: T,
24 pub w: T,
25}
26
27pub type DQuat = Quat<f64>;
28
29impl<T: Float> Default for Quat<T> {
30 fn default() -> Self {
31 Self::identity()
32 }
33}
34
35impl<T: Float> Quat<T> {
36 pub fn identity() -> Self {
37 Self {
38 x: T::ZERO,
39 y: T::ZERO,
40 z: T::ZERO,
41 w: T::ONE,
42 }
43 }
44
45 pub fn try_from_axis_angle(axis: Vec3<T>, angle_radians: T) -> Option<Self> {
47 if !angle_radians.is_finite() {
48 return None;
49 }
50 let axis = axis.try_normalized()?;
51 let half_angle = angle_radians * T::HALF;
52 let sine = half_angle.sin();
53 let result = Self {
54 x: axis.x * sine,
55 y: axis.y * sine,
56 z: axis.z * sine,
57 w: half_angle.cos(),
58 };
59 result.is_finite().then_some(result)
60 }
61
62 pub fn is_finite(self) -> bool {
63 self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite()
64 }
65
66 pub fn norm_squared(self) -> T {
67 (self.x * self.x + self.y * self.y) + (self.z * self.z + self.w * self.w)
68 }
69
70 pub fn norm(self) -> T {
71 let squared = self.norm_squared();
72 if squared.is_finite() && squared > T::ZERO {
73 return squared.sqrt();
74 }
75 if !self.is_finite() {
76 return squared.sqrt();
77 }
78 let magnitude = self
79 .x
80 .abs()
81 .max(self.y.abs())
82 .max(self.z.abs())
83 .max(self.w.abs());
84 if magnitude == T::ZERO {
85 return T::ZERO;
86 }
87 let scaled = self / magnitude;
88 magnitude * scaled.norm_squared().sqrt()
89 }
90
91 pub fn try_normalized(self) -> Option<Self> {
93 let squared = self.norm_squared();
94 if squared.is_finite() && squared > T::ZERO {
95 return Some(self / squared.sqrt());
96 }
97 if !self.is_finite() {
98 return None;
99 }
100 let magnitude = self
101 .x
102 .abs()
103 .max(self.y.abs())
104 .max(self.z.abs())
105 .max(self.w.abs());
106 if magnitude <= T::ZERO {
107 return None;
108 }
109 let scaled = self / magnitude;
110 let norm = scaled.norm();
111 if !norm.is_finite() || norm <= T::ZERO {
112 return None;
113 }
114 let result = scaled / norm;
115 result.is_finite().then_some(result)
116 }
117
118 pub fn conjugate(self) -> Self {
119 Self {
120 x: -self.x,
121 y: -self.y,
122 z: -self.z,
123 w: self.w,
124 }
125 }
126
127 pub fn dot(self, other: Self) -> T {
128 self.x * other.x + self.y * other.y + self.z * other.z + self.w * other.w
129 }
130
131 pub fn try_inverse(self, tolerance: T) -> Option<Self> {
132 if !valid_tolerance(tolerance) || !self.is_finite() {
133 return None;
134 }
135 let magnitude = self
136 .x
137 .abs()
138 .max(self.y.abs())
139 .max(self.z.abs())
140 .max(self.w.abs());
141 if magnitude <= tolerance {
142 return None;
143 }
144 let scaled = self / magnitude;
145 let norm_squared = scaled.norm_squared();
146 if !norm_squared.is_finite() || norm_squared <= T::ZERO {
147 return None;
148 }
149 let result = (scaled.conjugate() / norm_squared) / magnitude;
150 result.is_finite().then_some(result)
151 }
152
153 #[inline]
154 pub fn try_rotate(self, vector: Vec3<T>) -> Option<Vec3<T>> {
155 let squared = self.norm_squared();
156 let unit_tolerance = T::EPSILON * T::from_f64(8.0);
157 let unit = if squared.is_finite() && (squared - T::ONE).abs() <= unit_tolerance {
158 self
159 } else {
160 self.try_normalized()?
161 };
162 let imaginary = Vec3 {
163 x: unit.x,
164 y: unit.y,
165 z: unit.z,
166 };
167 let twice_cross = imaginary.cross(vector) * T::TWO;
168 Some(vector + twice_cross * unit.w + imaginary.cross(twice_cross))
169 }
170
171 pub fn try_inverse_rotate(self, vector: Vec3<T>) -> Option<Vec3<T>> {
172 self.conjugate().try_rotate(vector)
173 }
174
175 pub fn try_from_euler_radians(angles: Vec3<T>, order: RotationOrder) -> Option<Self> {
177 if !angles.is_finite() {
178 return None;
179 }
180 let x = Self::try_from_axis_angle(
181 Vec3 {
182 x: T::ONE,
183 y: T::ZERO,
184 z: T::ZERO,
185 },
186 angles.x,
187 )?;
188 let y = Self::try_from_axis_angle(
189 Vec3 {
190 x: T::ZERO,
191 y: T::ONE,
192 z: T::ZERO,
193 },
194 angles.y,
195 )?;
196 let z = Self::try_from_axis_angle(
197 Vec3 {
198 x: T::ZERO,
199 y: T::ZERO,
200 z: T::ONE,
201 },
202 angles.z,
203 )?;
204 Some(match order {
205 RotationOrder::Xyz => z * (y * x),
206 RotationOrder::Xzy => y * (z * x),
207 RotationOrder::Yxz => z * (x * y),
208 RotationOrder::Yzx => x * (z * y),
209 RotationOrder::Zxy => y * (x * z),
210 RotationOrder::Zyx => x * (y * z),
211 })
212 }
213
214 pub fn try_from_euler_degrees(angles: Vec3<T>, order: RotationOrder) -> Option<Self> {
215 Self::try_from_euler_radians(
216 Vec3 {
217 x: radians(angles.x),
218 y: radians(angles.y),
219 z: radians(angles.z),
220 },
221 order,
222 )
223 }
224
225 pub fn try_to_euler_radians(self, order: RotationOrder) -> Option<Vec3<T>> {
226 let q = self.try_normalized()?;
227 let xx = q.x * q.x;
228 let yy = q.y * q.y;
229 let zz = q.z * q.z;
230 let xy = q.x * q.y;
231 let xz = q.x * q.z;
232 let yz = q.y * q.z;
233 let xw = q.x * q.w;
234 let yw = q.y * q.w;
235 let zw = q.z * q.w;
236 let m11 = T::ONE - T::TWO * (yy + zz);
237 let m12 = T::TWO * (xy - zw);
238 let m13 = T::TWO * (xz + yw);
239 let m21 = T::TWO * (xy + zw);
240 let m22 = T::ONE - T::TWO * (xx + zz);
241 let m23 = T::TWO * (yz - xw);
242 let m31 = T::TWO * (xz - yw);
243 let m32 = T::TWO * (yz + xw);
244 let m33 = T::ONE - T::TWO * (xx + yy);
245 let lock = T::ONE - T::EPSILON * T::from_f64(64.0);
246 let mut result = Vec3::default();
247 match order {
248 RotationOrder::Zyx => {
249 result.y = m13.max(-T::ONE).min(T::ONE).asin();
250 if m13.abs() < lock {
251 result.x = (-m23).atan2(m33);
252 result.z = (-m12).atan2(m11);
253 } else {
254 result.x = m32.atan2(m22);
255 }
256 }
257 RotationOrder::Zxy => {
258 result.x = -m23.max(-T::ONE).min(T::ONE).asin();
259 if m23.abs() < lock {
260 result.y = m13.atan2(m33);
261 result.z = m21.atan2(m22);
262 } else {
263 result.y = (-m31).atan2(m11);
264 }
265 }
266 RotationOrder::Yxz => {
267 result.x = m32.max(-T::ONE).min(T::ONE).asin();
268 if m32.abs() < lock {
269 result.y = (-m31).atan2(m33);
270 result.z = (-m12).atan2(m22);
271 } else {
272 result.z = m21.atan2(m11);
273 }
274 }
275 RotationOrder::Xyz => {
276 result.y = -m31.max(-T::ONE).min(T::ONE).asin();
277 if m31.abs() < lock {
278 result.x = m32.atan2(m33);
279 result.z = m21.atan2(m11);
280 } else {
281 result.z = (-m12).atan2(m22);
282 }
283 }
284 RotationOrder::Xzy => {
285 result.z = m21.max(-T::ONE).min(T::ONE).asin();
286 if m21.abs() < lock {
287 result.x = (-m23).atan2(m22);
288 result.y = (-m31).atan2(m11);
289 } else {
290 result.y = m13.atan2(m33);
291 }
292 }
293 RotationOrder::Yzx => {
294 result.z = -m12.max(-T::ONE).min(T::ONE).asin();
295 if m12.abs() < lock {
296 result.x = m32.atan2(m22);
297 result.y = m13.atan2(m11);
298 } else {
299 result.x = (-m23).atan2(m33);
300 }
301 }
302 }
303 Some(result)
304 }
305
306 pub fn try_to_euler_degrees(self, order: RotationOrder) -> Option<Vec3<T>> {
307 let value = self.try_to_euler_radians(order)?;
308 Some(Vec3 {
309 x: degrees(value.x),
310 y: degrees(value.y),
311 z: degrees(value.z),
312 })
313 }
314
315 pub fn try_nlerp(self, other: Self, amount: T) -> Option<Self> {
316 let a = self.try_normalized()?;
317 let mut b = other.try_normalized()?;
318 if a.dot(b) < T::ZERO {
319 b = -b;
320 }
321 (a + (b - a) * amount).try_normalized()
322 }
323
324 pub fn try_slerp(self, other: Self, amount: T) -> Option<Self> {
325 let a = self.try_normalized()?;
326 let mut b = other.try_normalized()?;
327 let mut cosine = a.dot(b);
328 if cosine < T::ZERO {
329 b = -b;
330 cosine = -cosine;
331 }
332 cosine = cosine.max(-T::ONE).min(T::ONE);
333 if cosine > T::ONE - T::TOLERANCE {
334 return a.try_nlerp(b, amount);
335 }
336 let angle = cosine.acos();
337 let sine = angle.sin();
338 let weight_a = ((T::ONE - amount) * angle).sin() / sine;
339 let weight_b = (amount * angle).sin() / sine;
340 (a * weight_a + b * weight_b).try_normalized()
341 }
342
343 pub fn angle(self) -> Option<T> {
344 let q = self.try_normalized()?;
345 Some(T::TWO * q.w.abs().max(-T::ONE).min(T::ONE).acos())
346 }
347
348 pub fn axis(self) -> Option<Vec3<T>> {
349 let mut q = self.try_normalized()?;
350 if q.w < T::ZERO {
351 q = -q;
352 }
353 let sine_half = (T::ONE - q.w * q.w).max(T::ZERO).sqrt();
354 if sine_half <= T::TOLERANCE {
355 return Some(Vec3 {
356 x: T::ONE,
357 y: T::ZERO,
358 z: T::ZERO,
359 });
360 }
361 Some(Vec3 {
362 x: q.x / sine_half,
363 y: q.y / sine_half,
364 z: q.z / sine_half,
365 })
366 }
367
368 pub fn approximately_equal(self, other: Self, absolute: T, relative: T) -> bool {
369 approx(self.x, other.x, absolute, relative)
370 && approx(self.y, other.y, absolute, relative)
371 && approx(self.z, other.z, absolute, relative)
372 && approx(self.w, other.w, absolute, relative)
373 }
374}
375
376impl<T: Float> Add for Quat<T> {
377 type Output = Self;
378
379 fn add(self, other: Self) -> Self {
380 Self {
381 x: self.x + other.x,
382 y: self.y + other.y,
383 z: self.z + other.z,
384 w: self.w + other.w,
385 }
386 }
387}
388
389impl<T: Float> Sub for Quat<T> {
390 type Output = Self;
391
392 fn sub(self, other: Self) -> Self {
393 Self {
394 x: self.x - other.x,
395 y: self.y - other.y,
396 z: self.z - other.z,
397 w: self.w - other.w,
398 }
399 }
400}
401
402impl<T: Float> Mul<T> for Quat<T> {
403 type Output = Self;
404
405 fn mul(self, scalar: T) -> Self {
406 Self {
407 x: self.x * scalar,
408 y: self.y * scalar,
409 z: self.z * scalar,
410 w: self.w * scalar,
411 }
412 }
413}
414
415impl<T: Float> Mul for Quat<T> {
416 type Output = Self;
417
418 fn mul(self, other: Self) -> Self {
419 Self {
420 x: self.w * other.x + self.x * other.w + self.y * other.z - self.z * other.y,
421 y: self.w * other.y - self.x * other.z + self.y * other.w + self.z * other.x,
422 z: self.w * other.z + self.x * other.y - self.y * other.x + self.z * other.w,
423 w: self.w * other.w - self.x * other.x - self.y * other.y - self.z * other.z,
424 }
425 }
426}
427
428impl<T: Float> Div<T> for Quat<T> {
429 type Output = Self;
430
431 fn div(self, scalar: T) -> Self {
432 Self {
433 x: self.x / scalar,
434 y: self.y / scalar,
435 z: self.z / scalar,
436 w: self.w / scalar,
437 }
438 }
439}
440
441impl<T: Float> Neg for Quat<T> {
442 type Output = Self;
443
444 fn neg(self) -> Self {
445 Self {
446 x: -self.x,
447 y: -self.y,
448 z: -self.z,
449 w: -self.w,
450 }
451 }
452}
453
454impl<T: Float> AddAssign for Quat<T> {
455 fn add_assign(&mut self, other: Self) {
456 *self = *self + other;
457 }
458}
459
460impl<T: Float> SubAssign for Quat<T> {
461 fn sub_assign(&mut self, other: Self) {
462 *self = *self - other;
463 }
464}
465
466impl<T: Float> MulAssign<T> for Quat<T> {
467 fn mul_assign(&mut self, scalar: T) {
468 *self = *self * scalar;
469 }
470}
471
472impl<T: Float> MulAssign for Quat<T> {
473 fn mul_assign(&mut self, other: Self) {
474 *self = *self * other;
475 }
476}
477
478impl<T: Float> DivAssign<T> for Quat<T> {
479 fn div_assign(&mut self, scalar: T) {
480 *self = *self / scalar;
481 }
482}
483
484impl Mul<Quat<f32>> for f32 {
485 type Output = Quat<f32>;
486
487 fn mul(self, quaternion: Quat<f32>) -> Self::Output {
488 quaternion * self
489 }
490}
491
492impl Mul<Quat<f64>> for f64 {
493 type Output = Quat<f64>;
494
495 fn mul(self, quaternion: Quat<f64>) -> Self::Output {
496 quaternion * self
497 }
498}