Debian Codegraph @

debian/missing-sources/glam-0.29.3/src/f32/coresimd/quat.rs

raw
1 // Generated from quat.rs.tera template. Edit the template, not the generated file.
2
3 use crate::{
4 coresimd::*,
5 euler::{EulerRot, FromEuler, ToEuler},
6 f32::math,
7 DQuat, Mat3, Mat3A, Mat4, Vec2, Vec3, Vec3A, Vec4,
8 };
9
10 use core::simd::*;
11
12 use core::fmt;
13 use core::iter::{Product, Sum};
14 use core::ops::{Add, Deref, DerefMut, Div, Mul, MulAssign, Neg, Sub};
15
16 /// Creates a quaternion from `x`, `y`, `z` and `w` values.
17 ///
18 /// This should generally not be called manually unless you know what you are doing. Use
19 /// one of the other constructors instead such as `identity` or `from_axis_angle`.
20 #[inline]
21 #[must_use]
22 pub const fn quat(x: f32, y: f32, z: f32, w: f32) -> Quat {
23 Quat::from_xyzw(x, y, z, w)
24 }
25
26 /// A quaternion representing an orientation.
27 ///
28 /// This quaternion is intended to be of unit length but may denormalize due to
29 /// floating point "error creep" which can occur when successive quaternion
30 /// operations are applied.
31 ///
32 /// SIMD vector types are used for storage on supported platforms.
33 ///
34 /// This type is 16 byte aligned.
35 #[derive(Clone, Copy)]
36 #[repr(transparent)]
37 pub struct Quat(pub(crate) f32x4);
38
39 impl Quat {
40 /// All zeros.
41 const ZERO: Self = Self::from_array([0.0; 4]);
42
43 /// The identity quaternion. Corresponds to no rotation.
44 pub const IDENTITY: Self = Self::from_xyzw(0.0, 0.0, 0.0, 1.0);
45
46 /// All NANs.
47 pub const NAN: Self = Self::from_array([f32::NAN; 4]);
48
49 /// Creates a new rotation quaternion.
50 ///
51 /// This should generally not be called manually unless you know what you are doing.
52 /// Use one of the other constructors instead such as `identity` or `from_axis_angle`.
53 ///
54 /// `from_xyzw` is mostly used by unit tests and `serde` deserialization.
55 ///
56 /// # Preconditions
57 ///
58 /// This function does not check if the input is normalized, it is up to the user to
59 /// provide normalized input or to normalized the resulting quaternion.
60 #[inline(always)]
61 #[must_use]
62 pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
63 Self(f32x4::from_array([x, y, z, w]))
64 }
65
66 /// Creates a rotation quaternion from an array.
67 ///
68 /// # Preconditions
69 ///
70 /// This function does not check if the input is normalized, it is up to the user to
71 /// provide normalized input or to normalized the resulting quaternion.
72 #[inline]
73 #[must_use]
74 pub const fn from_array(a: [f32; 4]) -> Self {
75 Self(f32x4::from_array(a))
76 }
77
78 /// Creates a new rotation quaternion from a 4D vector.
79 ///
80 /// # Preconditions
81 ///
82 /// This function does not check if the input is normalized, it is up to the user to
83 /// provide normalized input or to normalized the resulting quaternion.
84 #[inline]
85 #[must_use]
86 pub const fn from_vec4(v: Vec4) -> Self {
87 Self(v.0)
88 }
89
90 /// Creates a rotation quaternion from a slice.
91 ///
92 /// # Preconditions
93 ///
94 /// This function does not check if the input is normalized, it is up to the user to
95 /// provide normalized input or to normalized the resulting quaternion.
96 ///
97 /// # Panics
98 ///
99 /// Panics if `slice` length is less than 4.
100 #[inline]
101 #[must_use]
102 pub fn from_slice(slice: &[f32]) -> Self {
103 Self::from_xyzw(slice[0], slice[1], slice[2], slice[3])
104 }
105
106 /// Writes the quaternion to an unaligned slice.
107 ///
108 /// # Panics
109 ///
110 /// Panics if `slice` length is less than 4.
111 #[inline]
112 pub fn write_to_slice(self, slice: &mut [f32]) {
113 slice[0] = self.x;
114 slice[1] = self.y;
115 slice[2] = self.z;
116 slice[3] = self.w;
117 }
118
119 /// Create a quaternion for a normalized rotation `axis` and `angle` (in radians).
120 ///
121 /// The axis must be a unit vector.
122 ///
123 /// # Panics
124 ///
125 /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
126 #[inline]
127 #[must_use]
128 pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
129 glam_assert!(axis.is_normalized());
130 let (s, c) = math::sin_cos(angle * 0.5);
131 let v = axis * s;
132 Self::from_xyzw(v.x, v.y, v.z, c)
133 }
134
135 /// Create a quaternion that rotates `v.length()` radians around `v.normalize()`.
136 ///
137 /// `from_scaled_axis(Vec3::ZERO)` results in the identity quaternion.
138 #[inline]
139 #[must_use]
140 pub fn from_scaled_axis(v: Vec3) -> Self {
141 let length = v.length();
142 if length == 0.0 {
143 Self::IDENTITY
144 } else {
145 Self::from_axis_angle(v / length, length)
146 }
147 }
148
149 /// Creates a quaternion from the `angle` (in radians) around the x axis.
150 #[inline]
151 #[must_use]
152 pub fn from_rotation_x(angle: f32) -> Self {
153 let (s, c) = math::sin_cos(angle * 0.5);
154 Self::from_xyzw(s, 0.0, 0.0, c)
155 }
156
157 /// Creates a quaternion from the `angle` (in radians) around the y axis.
158 #[inline]
159 #[must_use]
160 pub fn from_rotation_y(angle: f32) -> Self {
161 let (s, c) = math::sin_cos(angle * 0.5);
162 Self::from_xyzw(0.0, s, 0.0, c)
163 }
164
165 /// Creates a quaternion from the `angle` (in radians) around the z axis.
166 #[inline]
167 #[must_use]
168 pub fn from_rotation_z(angle: f32) -> Self {
169 let (s, c) = math::sin_cos(angle * 0.5);
170 Self::from_xyzw(0.0, 0.0, s, c)
171 }
172
173 /// Creates a quaternion from the given Euler rotation sequence and the angles (in radians).
174 #[inline]
175 #[must_use]
176 pub fn from_euler(euler: EulerRot, a: f32, b: f32, c: f32) -> Self {
177 Self::from_euler_angles(euler, a, b, c)
178 }
179
180 /// From the columns of a 3x3 rotation matrix.
181 ///
182 /// Note if the input axes contain scales, shears, or other non-rotation transformations then
183 /// the output of this function is ill-defined.
184 ///
185 /// # Panics
186 ///
187 /// Will panic if any axis is not normalized when `glam_assert` is enabled.
188 #[inline]
189 #[must_use]
190 pub(crate) fn from_rotation_axes(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Self {
191 glam_assert!(x_axis.is_normalized() && y_axis.is_normalized() && z_axis.is_normalized());
192 // Based on https://github.com/microsoft/DirectXMath `XMQuaternionRotationMatrix`
193 let (m00, m01, m02) = x_axis.into();
194 let (m10, m11, m12) = y_axis.into();
195 let (m20, m21, m22) = z_axis.into();
196 if m22 <= 0.0 {
197 // x^2 + y^2 >= z^2 + w^2
198 let dif10 = m11 - m00;
199 let omm22 = 1.0 - m22;
200 if dif10 <= 0.0 {
201 // x^2 >= y^2
202 let four_xsq = omm22 - dif10;
203 let inv4x = 0.5 / math::sqrt(four_xsq);
204 Self::from_xyzw(
205 four_xsq * inv4x,
206 (m01 + m10) * inv4x,
207 (m02 + m20) * inv4x,
208 (m12 - m21) * inv4x,
209 )
210 } else {
211 // y^2 >= x^2
212 let four_ysq = omm22 + dif10;
213 let inv4y = 0.5 / math::sqrt(four_ysq);
214 Self::from_xyzw(
215 (m01 + m10) * inv4y,
216 four_ysq * inv4y,
217 (m12 + m21) * inv4y,
218 (m20 - m02) * inv4y,
219 )
220 }
221 } else {
222 // z^2 + w^2 >= x^2 + y^2
223 let sum10 = m11 + m00;
224 let opm22 = 1.0 + m22;
225 if sum10 <= 0.0 {
226 // z^2 >= w^2
227 let four_zsq = opm22 - sum10;
228 let inv4z = 0.5 / math::sqrt(four_zsq);
229 Self::from_xyzw(
230 (m02 + m20) * inv4z,
231 (m12 + m21) * inv4z,
232 four_zsq * inv4z,
233 (m01 - m10) * inv4z,
234 )
235 } else {
236 // w^2 >= z^2
237 let four_wsq = opm22 + sum10;
238 let inv4w = 0.5 / math::sqrt(four_wsq);
239 Self::from_xyzw(
240 (m12 - m21) * inv4w,
241 (m20 - m02) * inv4w,
242 (m01 - m10) * inv4w,
243 four_wsq * inv4w,
244 )
245 }
246 }
247 }
248
249 /// Creates a quaternion from a 3x3 rotation matrix.
250 ///
251 /// Note if the input matrix contain scales, shears, or other non-rotation transformations then
252 /// the resulting quaternion will be ill-defined.
253 ///
254 /// # Panics
255 ///
256 /// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
257 #[inline]
258 #[must_use]
259 pub fn from_mat3(mat: &Mat3) -> Self {
260 Self::from_rotation_axes(mat.x_axis, mat.y_axis, mat.z_axis)
261 }
262
263 /// Creates a quaternion from a 3x3 SIMD aligned rotation matrix.
264 ///
265 /// Note if the input matrix contain scales, shears, or other non-rotation transformations then
266 /// the resulting quaternion will be ill-defined.
267 ///
268 /// # Panics
269 ///
270 /// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
271 #[inline]
272 #[must_use]
273 pub fn from_mat3a(mat: &Mat3A) -> Self {
274 Self::from_rotation_axes(mat.x_axis.into(), mat.y_axis.into(), mat.z_axis.into())
275 }
276
277 /// Creates a quaternion from the upper 3x3 rotation matrix inside a homogeneous 4x4 matrix.
278 ///
279 /// Note if the upper 3x3 matrix contain scales, shears, or other non-rotation transformations
280 /// then the resulting quaternion will be ill-defined.
281 ///
282 /// # Panics
283 ///
284 /// Will panic if any column of the upper 3x3 rotation matrix is not normalized when
285 /// `glam_assert` is enabled.
286 #[inline]
287 #[must_use]
288 pub fn from_mat4(mat: &Mat4) -> Self {
289 Self::from_rotation_axes(
290 mat.x_axis.truncate(),
291 mat.y_axis.truncate(),
292 mat.z_axis.truncate(),
293 )
294 }
295
296 /// Gets the minimal rotation for transforming `from` to `to`. The rotation is in the
297 /// plane spanned by the two vectors. Will rotate at most 180 degrees.
298 ///
299 /// The inputs must be unit vectors.
300 ///
301 /// `from_rotation_arc(from, to) * from ≈ to`.
302 ///
303 /// For near-singular cases (from≈to and from≈-to) the current implementation
304 /// is only accurate to about 0.001 (for `f32`).
305 ///
306 /// # Panics
307 ///
308 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
309 #[must_use]
310 pub fn from_rotation_arc(from: Vec3, to: Vec3) -> Self {
311 glam_assert!(from.is_normalized());
312 glam_assert!(to.is_normalized());
313
314 const ONE_MINUS_EPS: f32 = 1.0 - 2.0 * f32::EPSILON;
315 let dot = from.dot(to);
316 if dot > ONE_MINUS_EPS {
317 // 0° singularity: from ≈ to
318 Self::IDENTITY
319 } else if dot < -ONE_MINUS_EPS {
320 // 180° singularity: from ≈ -to
321 use core::f32::consts::PI; // half a turn = 𝛕/2 = 180°
322 Self::from_axis_angle(from.any_orthonormal_vector(), PI)
323 } else {
324 let c = from.cross(to);
325 Self::from_xyzw(c.x, c.y, c.z, 1.0 + dot).normalize()
326 }
327 }
328
329 /// Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means
330 /// that the resulting quaternion will rotate `from` so that it is colinear with `to`.
331 ///
332 /// The rotation is in the plane spanned by the two vectors. Will rotate at most 90
333 /// degrees.
334 ///
335 /// The inputs must be unit vectors.
336 ///
337 /// `to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`.
338 ///
339 /// # Panics
340 ///
341 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
342 #[inline]
343 #[must_use]
344 pub fn from_rotation_arc_colinear(from: Vec3, to: Vec3) -> Self {
345 if from.dot(to) < 0.0 {
346 Self::from_rotation_arc(from, -to)
347 } else {
348 Self::from_rotation_arc(from, to)
349 }
350 }
351
352 /// Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is
353 /// around the z axis. Will rotate at most 180 degrees.
354 ///
355 /// The inputs must be unit vectors.
356 ///
357 /// `from_rotation_arc_2d(from, to) * from ≈ to`.
358 ///
359 /// For near-singular cases (from≈to and from≈-to) the current implementation
360 /// is only accurate to about 0.001 (for `f32`).
361 ///
362 /// # Panics
363 ///
364 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
365 #[must_use]
366 pub fn from_rotation_arc_2d(from: Vec2, to: Vec2) -> Self {
367 glam_assert!(from.is_normalized());
368 glam_assert!(to.is_normalized());
369
370 const ONE_MINUS_EPSILON: f32 = 1.0 - 2.0 * f32::EPSILON;
371 let dot = from.dot(to);
372 if dot > ONE_MINUS_EPSILON {
373 // 0° singularity: from ≈ to
374 Self::IDENTITY
375 } else if dot < -ONE_MINUS_EPSILON {
376 // 180° singularity: from ≈ -to
377 const COS_FRAC_PI_2: f32 = 0.0;
378 const SIN_FRAC_PI_2: f32 = 1.0;
379 // rotation around z by PI radians
380 Self::from_xyzw(0.0, 0.0, SIN_FRAC_PI_2, COS_FRAC_PI_2)
381 } else {
382 // vector3 cross where z=0
383 let z = from.x * to.y - to.x * from.y;
384 let w = 1.0 + dot;
385 // calculate length with x=0 and y=0 to normalize
386 let len_rcp = 1.0 / math::sqrt(z * z + w * w);
387 Self::from_xyzw(0.0, 0.0, z * len_rcp, w * len_rcp)
388 }
389 }
390
391 /// Returns the rotation axis (normalized) and angle (in radians) of `self`.
392 #[inline]
393 #[must_use]
394 pub fn to_axis_angle(self) -> (Vec3, f32) {
395 const EPSILON: f32 = 1.0e-8;
396 let v = Vec3::new(self.x, self.y, self.z);
397 let length = v.length();
398 if length >= EPSILON {
399 let angle = 2.0 * math::atan2(length, self.w);
400 let axis = v / length;
401 (axis, angle)
402 } else {
403 (Vec3::X, 0.0)
404 }
405 }
406
407 /// Returns the rotation axis scaled by the rotation in radians.
408 #[inline]
409 #[must_use]
410 pub fn to_scaled_axis(self) -> Vec3 {
411 let (axis, angle) = self.to_axis_angle();
412 axis * angle
413 }
414
415 /// Returns the rotation angles for the given euler rotation sequence.
416 #[inline]
417 #[must_use]
418 pub fn to_euler(self, order: EulerRot) -> (f32, f32, f32) {
419 self.to_euler_angles(order)
420 }
421
422 /// `[x, y, z, w]`
423 #[inline]
424 #[must_use]
425 pub fn to_array(&self) -> [f32; 4] {
426 [self.x, self.y, self.z, self.w]
427 }
428
429 /// Returns the vector part of the quaternion.
430 #[inline]
431 #[must_use]
432 pub fn xyz(self) -> Vec3 {
433 Vec3::new(self.x, self.y, self.z)
434 }
435
436 /// Returns the quaternion conjugate of `self`. For a unit quaternion the
437 /// conjugate is also the inverse.
438 #[inline]
439 #[must_use]
440 pub fn conjugate(self) -> Self {
441 const SIGN: f32x4 = f32x4::from_array([-1.0, -1.0, -1.0, 1.0]);
442 Self(self.0.mul(SIGN))
443 }
444
445 /// Returns the inverse of a normalized quaternion.
446 ///
447 /// Typically quaternion inverse returns the conjugate of a normalized quaternion.
448 /// Because `self` is assumed to already be unit length this method *does not* normalize
449 /// before returning the conjugate.
450 ///
451 /// # Panics
452 ///
453 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
454 #[inline]
455 #[must_use]
456 pub fn inverse(self) -> Self {
457 glam_assert!(self.is_normalized());
458 self.conjugate()
459 }
460
461 /// Computes the dot product of `self` and `rhs`. The dot product is
462 /// equal to the cosine of the angle between two quaternion rotations.
463 #[inline]
464 #[must_use]
465 pub fn dot(self, rhs: Self) -> f32 {
466 Vec4::from(self).dot(Vec4::from(rhs))
467 }
468
469 /// Computes the length of `self`.
470 #[doc(alias = "magnitude")]
471 #[inline]
472 #[must_use]
473 pub fn length(self) -> f32 {
474 Vec4::from(self).length()
475 }
476
477 /// Computes the squared length of `self`.
478 ///
479 /// This is generally faster than `length()` as it avoids a square
480 /// root operation.
481 #[doc(alias = "magnitude2")]
482 #[inline]
483 #[must_use]
484 pub fn length_squared(self) -> f32 {
485 Vec4::from(self).length_squared()
486 }
487
488 /// Computes `1.0 / length()`.
489 ///
490 /// For valid results, `self` must _not_ be of length zero.
491 #[inline]
492 #[must_use]
493 pub fn length_recip(self) -> f32 {
494 Vec4::from(self).length_recip()
495 }
496
497 /// Returns `self` normalized to length 1.0.
498 ///
499 /// For valid results, `self` must _not_ be of length zero.
500 ///
501 /// Panics
502 ///
503 /// Will panic if `self` is zero length when `glam_assert` is enabled.
504 #[inline]
505 #[must_use]
506 pub fn normalize(self) -> Self {
507 Self::from_vec4(Vec4::from(self).normalize())
508 }
509
510 /// Returns `true` if, and only if, all elements are finite.
511 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
512 #[inline]
513 #[must_use]
514 pub fn is_finite(self) -> bool {
515 Vec4::from(self).is_finite()
516 }
517
518 /// Returns `true` if any elements are `NAN`.
519 #[inline]
520 #[must_use]
521 pub fn is_nan(self) -> bool {
522 Vec4::from(self).is_nan()
523 }
524
525 /// Returns whether `self` of length `1.0` or not.
526 ///
527 /// Uses a precision threshold of `1e-6`.
528 #[inline]
529 #[must_use]
530 pub fn is_normalized(self) -> bool {
531 Vec4::from(self).is_normalized()
532 }
533
534 #[inline]
535 #[must_use]
536 pub fn is_near_identity(self) -> bool {
537 // Based on https://github.com/nfrechette/rtm `rtm::quat_near_identity`
538 let threshold_angle = 0.002_847_144_6;
539 // Because of floating point precision, we cannot represent very small rotations.
540 // The closest f32 to 1.0 that is not 1.0 itself yields:
541 // 0.99999994.acos() * 2.0 = 0.000690533954 rad
542 //
543 // An error threshold of 1.e-6 is used by default.
544 // (1.0 - 1.e-6).acos() * 2.0 = 0.00284714461 rad
545 // (1.0 - 1.e-7).acos() * 2.0 = 0.00097656250 rad
546 //
547 // We don't really care about the angle value itself, only if it's close to 0.
548 // This will happen whenever quat.w is close to 1.0.
549 // If the quat.w is close to -1.0, the angle will be near 2*PI which is close to
550 // a negative 0 rotation. By forcing quat.w to be positive, we'll end up with
551 // the shortest path.
552 let positive_w_angle = math::acos_approx(math::abs(self.w)) * 2.0;
553 positive_w_angle < threshold_angle
554 }
555
556 /// Returns the angle (in radians) for the minimal rotation
557 /// for transforming this quaternion into another.
558 ///
559 /// Both quaternions must be normalized.
560 ///
561 /// # Panics
562 ///
563 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
564 #[inline]
565 #[must_use]
566 pub fn angle_between(self, rhs: Self) -> f32 {
567 glam_assert!(self.is_normalized() && rhs.is_normalized());
568 math::acos_approx(math::abs(self.dot(rhs))) * 2.0
569 }
570
571 /// Rotates towards `rhs` up to `max_angle` (in radians).
572 ///
573 /// When `max_angle` is `0.0`, the result will be equal to `self`. When `max_angle` is equal to
574 /// `self.angle_between(rhs)`, the result will be equal to `rhs`. If `max_angle` is negative,
575 /// rotates towards the exact opposite of `rhs`. Will not go past the target.
576 ///
577 /// Both quaternions must be normalized.
578 ///
579 /// # Panics
580 ///
581 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
582 #[inline]
583 #[must_use]
584 pub fn rotate_towards(&self, rhs: Self, max_angle: f32) -> Self {
585 glam_assert!(self.is_normalized() && rhs.is_normalized());
586 let angle = self.angle_between(rhs);
587 if angle <= 1e-4 {
588 return *self;
589 }
590 let s = (max_angle / angle).clamp(-1.0, 1.0);
591 self.slerp(rhs, s)
592 }
593
594 /// Returns true if the absolute difference of all elements between `self` and `rhs`
595 /// is less than or equal to `max_abs_diff`.
596 ///
597 /// This can be used to compare if two quaternions contain similar elements. It works
598 /// best when comparing with a known value. The `max_abs_diff` that should be used used
599 /// depends on the values being compared against.
600 ///
601 /// For more see
602 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
603 #[inline]
604 #[must_use]
605 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
606 Vec4::from(self).abs_diff_eq(Vec4::from(rhs), max_abs_diff)
607 }
608
609 #[inline(always)]
610 #[must_use]
611 fn lerp_impl(self, end: Self, s: f32) -> Self {
612 (self * (1.0 - s) + end * s).normalize()
613 }
614
615 /// Performs a linear interpolation between `self` and `rhs` based on
616 /// the value `s`.
617 ///
618 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
619 /// is `1.0`, the result will be equal to `rhs`.
620 ///
621 /// # Panics
622 ///
623 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
624 #[doc(alias = "mix")]
625 #[inline]
626 #[must_use]
627 pub fn lerp(self, end: Self, s: f32) -> Self {
628 glam_assert!(self.is_normalized());
629 glam_assert!(end.is_normalized());
630
631 const NEG_ZERO: f32x4 = f32x4::from_array([-0.0; 4]);
632 let dot = dot4_into_f32x4(self.0, end.0);
633 // Calculate the bias, if the dot product is positive or zero, there is no bias
634 // but if it is negative, we want to flip the 'end' rotation XYZW components
635 let bias = f32x4_bitand(dot, NEG_ZERO);
636 self.lerp_impl(Self(f32x4_bitxor(end.0, bias)), s)
637 }
638
639 /// Performs a spherical linear interpolation between `self` and `end`
640 /// based on the value `s`.
641 ///
642 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
643 /// is `1.0`, the result will be equal to `end`.
644 ///
645 /// # Panics
646 ///
647 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
648 #[inline]
649 #[must_use]
650 pub fn slerp(self, mut end: Self, s: f32) -> Self {
651 // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
652 glam_assert!(self.is_normalized());
653 glam_assert!(end.is_normalized());
654
655 // Note that a rotation can be represented by two quaternions: `q` and
656 // `-q`. The slerp path between `q` and `end` will be different from the
657 // path between `-q` and `end`. One path will take the long way around and
658 // one will take the short way. In order to correct for this, the `dot`
659 // product between `self` and `end` should be positive. If the `dot`
660 // product is negative, slerp between `self` and `-end`.
661 let mut dot = self.dot(end);
662 if dot < 0.0 {
663 end = -end;
664 dot = -dot;
665 }
666
667 const DOT_THRESHOLD: f32 = 1.0 - f32::EPSILON;
668 if dot > DOT_THRESHOLD {
669 // if above threshold perform linear interpolation to avoid divide by zero
670 self.lerp_impl(end, s)
671 } else {
672 let theta = math::acos_approx(dot);
673
674 let scale1 = math::sin(theta * (1.0 - s));
675 let scale2 = math::sin(theta * s);
676 let theta_sin = math::sin(theta);
677 ((self * scale1) + (end * scale2)) * (1.0 / theta_sin)
678 }
679 }
680
681 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
682 ///
683 /// # Panics
684 ///
685 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
686 #[inline]
687 #[must_use]
688 pub fn mul_vec3(self, rhs: Vec3) -> Vec3 {
689 glam_assert!(self.is_normalized());
690
691 self.mul_vec3a(rhs.into()).into()
692 }
693
694 /// Multiplies two quaternions. If they each represent a rotation, the result will
695 /// represent the combined rotation.
696 ///
697 /// Note that due to floating point rounding the result may not be perfectly normalized.
698 ///
699 /// # Panics
700 ///
701 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
702 #[inline]
703 #[must_use]
704 pub fn mul_quat(self, rhs: Self) -> Self {
705 let lhs = self.0;
706 let rhs = rhs.0;
707
708 const CONTROL_WZYX: f32x4 = f32x4::from_array([1.0, -1.0, 1.0, -1.0]);
709 const CONTROL_ZWXY: f32x4 = f32x4::from_array([1.0, 1.0, -1.0, -1.0]);
710 const CONTROL_YXWZ: f32x4 = f32x4::from_array([-1.0, 1.0, 1.0, -1.0]);
711
712 let r_xxxx = simd_swizzle!(lhs, [0, 0, 0, 0]);
713 let r_yyyy = simd_swizzle!(lhs, [1, 1, 1, 1]);
714 let r_zzzz = simd_swizzle!(lhs, [2, 2, 2, 2]);
715 let r_wwww = simd_swizzle!(lhs, [3, 3, 3, 3]);
716
717 let lxrw_lyrw_lzrw_lwrw = r_wwww * rhs;
718 let l_wzyx = simd_swizzle!(rhs, [3, 2, 1, 0]);
719
720 let lwrx_lzrx_lyrx_lxrx = r_xxxx * l_wzyx;
721 let l_zwxy = simd_swizzle!(l_wzyx, [1, 0, 3, 2]);
722
723 let lwrx_nlzrx_lyrx_nlxrx = lwrx_lzrx_lyrx_lxrx * CONTROL_WZYX;
724
725 let lzry_lwry_lxry_lyry = r_yyyy * l_zwxy;
726 let l_yxwz = simd_swizzle!(l_zwxy, [3, 2, 1, 0]);
727
728 let lzry_lwry_nlxry_nlyry = lzry_lwry_lxry_lyry * CONTROL_ZWXY;
729
730 let lyrz_lxrz_lwrz_lzrz = r_zzzz * l_yxwz;
731 let result0 = lxrw_lyrw_lzrw_lwrw + lwrx_nlzrx_lyrx_nlxrx;
732
733 let nlyrz_lxrz_lwrz_wlzrz = lyrz_lxrz_lwrz_lzrz * CONTROL_YXWZ;
734 let result1 = lzry_lwry_nlxry_nlyry + nlyrz_lxrz_lwrz_wlzrz;
735 Self(result0 + result1)
736 }
737
738 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
739 ///
740 /// Note if the input affine matrix contain scales, shears, or other non-rotation
741 /// transformations then the resulting quaternion will be ill-defined.
742 ///
743 /// # Panics
744 ///
745 /// Will panic if any input affine matrix column is not normalized when `glam_assert` is
746 /// enabled.
747 #[inline]
748 #[must_use]
749 pub fn from_affine3(a: &crate::Affine3A) -> Self {
750 #[allow(clippy::useless_conversion)]
751 Self::from_rotation_axes(
752 a.matrix3.x_axis.into(),
753 a.matrix3.y_axis.into(),
754 a.matrix3.z_axis.into(),
755 )
756 }
757
758 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
759 #[inline]
760 #[must_use]
761 pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
762 const TWO: f32x4 = f32x4::from_array([2.0; 4]);
763 let w = simd_swizzle!(self.0, [3, 3, 3, 3]);
764 let b = self.0;
765 let b2 = dot3_into_f32x4(b, b);
766 Vec3A(
767 rhs.0
768 .mul(w.mul(w).sub(b2))
769 .add(b.mul(dot3_into_f32x4(rhs.0, b).mul(TWO)))
770 .add(Vec3A(b).cross(rhs).0.mul(w.mul(TWO))),
771 )
772 }
773
774 #[inline]
775 #[must_use]
776 pub fn as_dquat(self) -> DQuat {
777 DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
778 }
779 }
780
781 impl fmt::Debug for Quat {
782 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
783 fmt.debug_tuple(stringify!(Quat))
784 .field(&self.x)
785 .field(&self.y)
786 .field(&self.z)
787 .field(&self.w)
788 .finish()
789 }
790 }
791
792 impl fmt::Display for Quat {
793 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794 if let Some(p) = f.precision() {
795 write!(
796 f,
797 "[{:.*}, {:.*}, {:.*}, {:.*}]",
798 p, self.x, p, self.y, p, self.z, p, self.w
799 )
800 } else {
801 write!(f, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
802 }
803 }
804 }
805
806 impl Add<Quat> for Quat {
807 type Output = Self;
808 /// Adds two quaternions.
809 ///
810 /// The sum is not guaranteed to be normalized.
811 ///
812 /// Note that addition is not the same as combining the rotations represented by the
813 /// two quaternions! That corresponds to multiplication.
814 #[inline]
815 fn add(self, rhs: Self) -> Self {
816 Self::from_vec4(Vec4::from(self) + Vec4::from(rhs))
817 }
818 }
819
820 impl Sub<Quat> for Quat {
821 type Output = Self;
822 /// Subtracts the `rhs` quaternion from `self`.
823 ///
824 /// The difference is not guaranteed to be normalized.
825 #[inline]
826 fn sub(self, rhs: Self) -> Self {
827 Self::from_vec4(Vec4::from(self) - Vec4::from(rhs))
828 }
829 }
830
831 impl Mul<f32> for Quat {
832 type Output = Self;
833 /// Multiplies a quaternion by a scalar value.
834 ///
835 /// The product is not guaranteed to be normalized.
836 #[inline]
837 fn mul(self, rhs: f32) -> Self {
838 Self::from_vec4(Vec4::from(self) * rhs)
839 }
840 }
841
842 impl Div<f32> for Quat {
843 type Output = Self;
844 /// Divides a quaternion by a scalar value.
845 /// The quotient is not guaranteed to be normalized.
846 #[inline]
847 fn div(self, rhs: f32) -> Self {
848 Self::from_vec4(Vec4::from(self) / rhs)
849 }
850 }
851
852 impl Mul<Quat> for Quat {
853 type Output = Self;
854 /// Multiplies two quaternions. If they each represent a rotation, the result will
855 /// represent the combined rotation.
856 ///
857 /// Note that due to floating point rounding the result may not be perfectly
858 /// normalized.
859 ///
860 /// # Panics
861 ///
862 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
863 #[inline]
864 fn mul(self, rhs: Self) -> Self {
865 self.mul_quat(rhs)
866 }
867 }
868
869 impl MulAssign<Quat> for Quat {
870 /// Multiplies two quaternions. If they each represent a rotation, the result will
871 /// represent the combined rotation.
872 ///
873 /// Note that due to floating point rounding the result may not be perfectly
874 /// normalized.
875 ///
876 /// # Panics
877 ///
878 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
879 #[inline]
880 fn mul_assign(&mut self, rhs: Self) {
881 *self = self.mul_quat(rhs);
882 }
883 }
884
885 impl Mul<Vec3> for Quat {
886 type Output = Vec3;
887 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
888 ///
889 /// # Panics
890 ///
891 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
892 #[inline]
893 fn mul(self, rhs: Vec3) -> Self::Output {
894 self.mul_vec3(rhs)
895 }
896 }
897
898 impl Neg for Quat {
899 type Output = Self;
900 #[inline]
901 fn neg(self) -> Self {
902 self * -1.0
903 }
904 }
905
906 impl Default for Quat {
907 #[inline]
908 fn default() -> Self {
909 Self::IDENTITY
910 }
911 }
912
913 impl PartialEq for Quat {
914 #[inline]
915 fn eq(&self, rhs: &Self) -> bool {
916 Vec4::from(*self).eq(&Vec4::from(*rhs))
917 }
918 }
919
920 #[cfg(not(target_arch = "spirv"))]
921 impl AsRef<[f32; 4]> for Quat {
922 #[inline]
923 fn as_ref(&self) -> &[f32; 4] {
924 unsafe { &*(self as *const Self as *const [f32; 4]) }
925 }
926 }
927
928 impl Sum<Self> for Quat {
929 fn sum<I>(iter: I) -> Self
930 where
931 I: Iterator<Item = Self>,
932 {
933 iter.fold(Self::ZERO, Self::add)
934 }
935 }
936
937 impl<'a> Sum<&'a Self> for Quat {
938 fn sum<I>(iter: I) -> Self
939 where
940 I: Iterator<Item = &'a Self>,
941 {
942 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
943 }
944 }
945
946 impl Product for Quat {
947 fn product<I>(iter: I) -> Self
948 where
949 I: Iterator<Item = Self>,
950 {
951 iter.fold(Self::IDENTITY, Self::mul)
952 }
953 }
954
955 impl<'a> Product<&'a Self> for Quat {
956 fn product<I>(iter: I) -> Self
957 where
958 I: Iterator<Item = &'a Self>,
959 {
960 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
961 }
962 }
963
964 impl Mul<Vec3A> for Quat {
965 type Output = Vec3A;
966 #[inline]
967 fn mul(self, rhs: Vec3A) -> Self::Output {
968 self.mul_vec3a(rhs)
969 }
970 }
971
972 impl From<Quat> for Vec4 {
973 #[inline]
974 fn from(q: Quat) -> Self {
975 Self(q.0)
976 }
977 }
978
979 impl From<Quat> for (f32, f32, f32, f32) {
980 #[inline]
981 fn from(q: Quat) -> Self {
982 Vec4::from(q).into()
983 }
984 }
985
986 impl From<Quat> for [f32; 4] {
987 #[inline]
988 fn from(q: Quat) -> Self {
989 Vec4::from(q).into()
990 }
991 }
992
993 impl From<Quat> for f32x4 {
994 #[inline]
995 fn from(q: Quat) -> Self {
996 q.0
997 }
998 }
999
1000 impl Deref for Quat {
1001 type Target = crate::deref::Vec4<f32>;
1002 #[inline]
1003 fn deref(&self) -> &Self::Target {
1004 unsafe { &*(self as *const Self).cast() }
1005 }
1006 }
1007
1008 impl DerefMut for Quat {
1009 #[inline]
1010 fn deref_mut(&mut self) -> &mut Self::Target {
1011 unsafe { &mut *(self as *mut Self).cast() }
1012 }
1013 }