Debian Codegraph @

debian/missing-sources/glam-0.24.2/src/f32/sse2/quat.rs

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