Debian Codegraph @

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

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