Debian Codegraph @

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

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