Debian Codegraph @

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