Debian Codegraph @

debian/missing-sources/glam-0.29.3/src/f32/wasm32/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 wasm32::*,
7 DQuat, Mat3, Mat3A, Mat4, Vec2, Vec3, Vec3A, Vec4,
8 };
9
10 use core::arch::wasm32::*;
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) v128);
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(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::from_xyzw(a[0], a[1], a[2], a[3])
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: v128 = v128_from_f32x4([-1.0, -1.0, -1.0, 1.0]);
442 Self(f32x4_mul(self.0, 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: v128 = v128_from_f32x4([-0.0; 4]);
632 let dot = dot4_into_v128(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 = v128_and(dot, NEG_ZERO);
636 self.lerp_impl(Self(v128_xor(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: v128 = v128_from_f32x4([1.0, -1.0, 1.0, -1.0]);
709 const CONTROL_ZWXY: v128 = v128_from_f32x4([1.0, 1.0, -1.0, -1.0]);
710 const CONTROL_YXWZ: v128 = v128_from_f32x4([-1.0, 1.0, 1.0, -1.0]);
711
712 let r_xxxx = i32x4_shuffle::<0, 0, 4, 4>(lhs, lhs);
713 let r_yyyy = i32x4_shuffle::<1, 1, 5, 5>(lhs, lhs);
714 let r_zzzz = i32x4_shuffle::<2, 2, 6, 6>(lhs, lhs);
715 let r_wwww = i32x4_shuffle::<3, 3, 7, 7>(lhs, lhs);
716
717 let lxrw_lyrw_lzrw_lwrw = f32x4_mul(r_wwww, rhs);
718 let l_wzyx = i32x4_shuffle::<3, 2, 5, 4>(rhs, rhs);
719
720 let lwrx_lzrx_lyrx_lxrx = f32x4_mul(r_xxxx, l_wzyx);
721 let l_zwxy = i32x4_shuffle::<1, 0, 7, 6>(l_wzyx, l_wzyx);
722
723 let lwrx_nlzrx_lyrx_nlxrx = f32x4_mul(lwrx_lzrx_lyrx_lxrx, CONTROL_WZYX);
724
725 let lzry_lwry_lxry_lyry = f32x4_mul(r_yyyy, l_zwxy);
726 let l_yxwz = i32x4_shuffle::<3, 2, 5, 4>(l_zwxy, l_zwxy);
727
728 let lzry_lwry_nlxry_nlyry = f32x4_mul(lzry_lwry_lxry_lyry, CONTROL_ZWXY);
729
730 let lyrz_lxrz_lwrz_lzrz = f32x4_mul(r_zzzz, l_yxwz);
731 let result0 = f32x4_add(lxrw_lyrw_lzrw_lwrw, lwrx_nlzrx_lyrx_nlxrx);
732
733 let nlyrz_lxrz_lwrz_wlzrz = f32x4_mul(lyrz_lxrz_lwrz_lzrz, CONTROL_YXWZ);
734 let result1 = f32x4_add(lzry_lwry_nlxry_nlyry, nlyrz_lxrz_lwrz_wlzrz);
735
736 Self(f32x4_add(result0, result1))
737 }
738
739 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
740 ///
741 /// Note if the input affine matrix contain scales, shears, or other non-rotation
742 /// transformations then the resulting quaternion will be ill-defined.
743 ///
744 /// # Panics
745 ///
746 /// Will panic if any input affine matrix column is not normalized when `glam_assert` is
747 /// enabled.
748 #[inline]
749 #[must_use]
750 pub fn from_affine3(a: &crate::Affine3A) -> Self {
751 #[allow(clippy::useless_conversion)]
752 Self::from_rotation_axes(
753 a.matrix3.x_axis.into(),
754 a.matrix3.y_axis.into(),
755 a.matrix3.z_axis.into(),
756 )
757 }
758
759 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
760 #[inline]
761 #[must_use]
762 pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
763 const TWO: v128 = v128_from_f32x4([2.0; 4]);
764 let w = i32x4_shuffle::<3, 3, 7, 7>(self.0, self.0);
765 let b = self.0;
766 let b2 = dot3_into_v128(b, b);
767 Vec3A(f32x4_add(
768 f32x4_add(
769 f32x4_mul(rhs.0, f32x4_sub(f32x4_mul(w, w), b2)),
770 f32x4_mul(b, f32x4_mul(dot3_into_v128(rhs.0, b), TWO)),
771 ),
772 f32x4_mul(Vec3A(b).cross(rhs).into(), f32x4_mul(w, TWO)),
773 ))
774 }
775
776 #[inline]
777 #[must_use]
778 pub fn as_dquat(self) -> DQuat {
779 DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
780 }
781 }
782
783 impl fmt::Debug for Quat {
784 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
785 fmt.debug_tuple(stringify!(Quat))
786 .field(&self.x)
787 .field(&self.y)
788 .field(&self.z)
789 .field(&self.w)
790 .finish()
791 }
792 }
793
794 impl fmt::Display for Quat {
795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796 if let Some(p) = f.precision() {
797 write!(
798 f,
799 "[{:.*}, {:.*}, {:.*}, {:.*}]",
800 p, self.x, p, self.y, p, self.z, p, self.w
801 )
802 } else {
803 write!(f, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
804 }
805 }
806 }
807
808 impl Add<Quat> for Quat {
809 type Output = Self;
810 /// Adds two quaternions.
811 ///
812 /// The sum is not guaranteed to be normalized.
813 ///
814 /// Note that addition is not the same as combining the rotations represented by the
815 /// two quaternions! That corresponds to multiplication.
816 #[inline]
817 fn add(self, rhs: Self) -> Self {
818 Self::from_vec4(Vec4::from(self) + Vec4::from(rhs))
819 }
820 }
821
822 impl Sub<Quat> for Quat {
823 type Output = Self;
824 /// Subtracts the `rhs` quaternion from `self`.
825 ///
826 /// The difference is not guaranteed to be normalized.
827 #[inline]
828 fn sub(self, rhs: Self) -> Self {
829 Self::from_vec4(Vec4::from(self) - Vec4::from(rhs))
830 }
831 }
832
833 impl Mul<f32> for Quat {
834 type Output = Self;
835 /// Multiplies a quaternion by a scalar value.
836 ///
837 /// The product is not guaranteed to be normalized.
838 #[inline]
839 fn mul(self, rhs: f32) -> Self {
840 Self::from_vec4(Vec4::from(self) * rhs)
841 }
842 }
843
844 impl Div<f32> for Quat {
845 type Output = Self;
846 /// Divides a quaternion by a scalar value.
847 /// The quotient is not guaranteed to be normalized.
848 #[inline]
849 fn div(self, rhs: f32) -> Self {
850 Self::from_vec4(Vec4::from(self) / rhs)
851 }
852 }
853
854 impl Mul<Quat> for Quat {
855 type Output = Self;
856 /// Multiplies two quaternions. If they each represent a rotation, the result will
857 /// represent the combined rotation.
858 ///
859 /// Note that due to floating point rounding the result may not be perfectly
860 /// normalized.
861 ///
862 /// # Panics
863 ///
864 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
865 #[inline]
866 fn mul(self, rhs: Self) -> Self {
867 self.mul_quat(rhs)
868 }
869 }
870
871 impl MulAssign<Quat> for Quat {
872 /// Multiplies two quaternions. If they each represent a rotation, the result will
873 /// represent the combined rotation.
874 ///
875 /// Note that due to floating point rounding the result may not be perfectly
876 /// normalized.
877 ///
878 /// # Panics
879 ///
880 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
881 #[inline]
882 fn mul_assign(&mut self, rhs: Self) {
883 *self = self.mul_quat(rhs);
884 }
885 }
886
887 impl Mul<Vec3> for Quat {
888 type Output = Vec3;
889 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
890 ///
891 /// # Panics
892 ///
893 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
894 #[inline]
895 fn mul(self, rhs: Vec3) -> Self::Output {
896 self.mul_vec3(rhs)
897 }
898 }
899
900 impl Neg for Quat {
901 type Output = Self;
902 #[inline]
903 fn neg(self) -> Self {
904 self * -1.0
905 }
906 }
907
908 impl Default for Quat {
909 #[inline]
910 fn default() -> Self {
911 Self::IDENTITY
912 }
913 }
914
915 impl PartialEq for Quat {
916 #[inline]
917 fn eq(&self, rhs: &Self) -> bool {
918 Vec4::from(*self).eq(&Vec4::from(*rhs))
919 }
920 }
921
922 #[cfg(not(target_arch = "spirv"))]
923 impl AsRef<[f32; 4]> for Quat {
924 #[inline]
925 fn as_ref(&self) -> &[f32; 4] {
926 unsafe { &*(self as *const Self as *const [f32; 4]) }
927 }
928 }
929
930 impl Sum<Self> for Quat {
931 fn sum<I>(iter: I) -> Self
932 where
933 I: Iterator<Item = Self>,
934 {
935 iter.fold(Self::ZERO, Self::add)
936 }
937 }
938
939 impl<'a> Sum<&'a Self> for Quat {
940 fn sum<I>(iter: I) -> Self
941 where
942 I: Iterator<Item = &'a Self>,
943 {
944 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
945 }
946 }
947
948 impl Product for Quat {
949 fn product<I>(iter: I) -> Self
950 where
951 I: Iterator<Item = Self>,
952 {
953 iter.fold(Self::IDENTITY, Self::mul)
954 }
955 }
956
957 impl<'a> Product<&'a Self> for Quat {
958 fn product<I>(iter: I) -> Self
959 where
960 I: Iterator<Item = &'a Self>,
961 {
962 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
963 }
964 }
965
966 impl Mul<Vec3A> for Quat {
967 type Output = Vec3A;
968 #[inline]
969 fn mul(self, rhs: Vec3A) -> Self::Output {
970 self.mul_vec3a(rhs)
971 }
972 }
973
974 impl From<Quat> for Vec4 {
975 #[inline]
976 fn from(q: Quat) -> Self {
977 Self(q.0)
978 }
979 }
980
981 impl From<Quat> for (f32, f32, f32, f32) {
982 #[inline]
983 fn from(q: Quat) -> Self {
984 Vec4::from(q).into()
985 }
986 }
987
988 impl From<Quat> for [f32; 4] {
989 #[inline]
990 fn from(q: Quat) -> Self {
991 Vec4::from(q).into()
992 }
993 }
994
995 impl From<Quat> for v128 {
996 #[inline]
997 fn from(q: Quat) -> Self {
998 q.0
999 }
1000 }
1001
1002 impl Deref for Quat {
1003 type Target = crate::deref::Vec4<f32>;
1004 #[inline]
1005 fn deref(&self) -> &Self::Target {
1006 unsafe { &*(self as *const Self).cast() }
1007 }
1008 }
1009
1010 impl DerefMut for Quat {
1011 #[inline]
1012 fn deref_mut(&mut self) -> &mut Self::Target {
1013 unsafe { &mut *(self as *mut Self).cast() }
1014 }
1015 }