Debian Codegraph @

debian/missing-sources/glam-0.24.2/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 f32::math,
7 DQuat, Mat3, Mat3A, Mat4, Vec2, Vec3, Vec3A, Vec4,
8 };
9
10 use core::simd::*;
11
12 #[cfg(not(target_arch = "spirv"))]
13 use core::fmt;
14 use core::iter::{Product, Sum};
15 use core::ops::{Add, Deref, DerefMut, Div, Mul, MulAssign, Neg, Sub};
16
17 /// Creates a quaternion from `x`, `y`, `z` and `w` values.
18 ///
19 /// This should generally not be called manually unless you know what you are doing. Use
20 /// one of the other constructors instead such as `identity` or `from_axis_angle`.
21 #[inline]
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) f32x4);
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 pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
62 Self(f32x4::from_array([x, y, z, w]))
63 }
64
65 /// Creates a rotation quaternion from an array.
66 ///
67 /// # Preconditions
68 ///
69 /// This function does not check if the input is normalized, it is up to the user to
70 /// provide normalized input or to normalized the resulting quaternion.
71 #[inline]
72 pub const fn from_array(a: [f32; 4]) -> Self {
73 Self(f32x4::from_array(a))
74 }
75
76 /// Creates a new rotation quaternion from a 4D vector.
77 ///
78 /// # Preconditions
79 ///
80 /// This function does not check if the input is normalized, it is up to the user to
81 /// provide normalized input or to normalized the resulting quaternion.
82 #[inline]
83 pub fn from_vec4(v: Vec4) -> Self {
84 Self(v.0)
85 }
86
87 /// Creates a rotation quaternion from a slice.
88 ///
89 /// # Preconditions
90 ///
91 /// This function does not check if the input is normalized, it is up to the user to
92 /// provide normalized input or to normalized the resulting quaternion.
93 ///
94 /// # Panics
95 ///
96 /// Panics if `slice` length is less than 4.
97 #[inline]
98 pub fn from_slice(slice: &[f32]) -> Self {
99 Self::from_xyzw(slice[0], slice[1], slice[2], slice[3])
100 }
101
102 /// Writes the quaternion to an unaligned slice.
103 ///
104 /// # Panics
105 ///
106 /// Panics if `slice` length is less than 4.
107 #[inline]
108 pub fn write_to_slice(self, slice: &mut [f32]) {
109 slice[0] = self.x;
110 slice[1] = self.y;
111 slice[2] = self.z;
112 slice[3] = self.w;
113 }
114
115 /// Create a quaternion for a normalized rotation `axis` and `angle` (in radians).
116 ///
117 /// The axis must be a unit vector.
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) = math::sin_cos(angle * 0.5);
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) = math::sin_cos(angle * 0.5);
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) = math::sin_cos(angle * 0.5);
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) = math::sin_cos(angle * 0.5);
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 / math::sqrt(four_xsq);
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 / math::sqrt(four_ysq);
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 / math::sqrt(four_zsq);
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 / math::sqrt(four_wsq);
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 inputs must be unit vectors.
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 inputs must be unit vectors.
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 inputs must be unit vectors.
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 / math::sqrt(z * z + w * w);
340 Self::from_xyzw(0.0, 0.0, z * len_rcp, w * len_rcp)
341 }
342 }
343
344 /// Returns the rotation axis (normalized) 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 let v = Vec3::new(self.x, self.y, self.z);
349 let length = v.length();
350 if length >= EPSILON {
351 let angle = 2.0 * math::atan2(length, self.w);
352 let axis = v / length;
353 (axis, angle)
354 } else {
355 (Vec3::X, 0.0)
356 }
357 }
358
359 /// Returns the rotation axis scaled by the rotation in radians.
360 #[inline]
361 pub fn to_scaled_axis(self) -> Vec3 {
362 let (axis, angle) = self.to_axis_angle();
363 axis * angle
364 }
365
366 /// Returns the rotation angles for the given euler rotation sequence.
367 #[inline]
368 pub fn to_euler(self, euler: EulerRot) -> (f32, f32, f32) {
369 euler.convert_quat(self)
370 }
371
372 /// `[x, y, z, w]`
373 #[inline]
374 pub fn to_array(&self) -> [f32; 4] {
375 [self.x, self.y, self.z, self.w]
376 }
377
378 /// Returns the vector part of the quaternion.
379 #[inline]
380 pub fn xyz(self) -> Vec3 {
381 Vec3::new(self.x, self.y, self.z)
382 }
383
384 /// Returns the quaternion conjugate of `self`. For a unit quaternion the
385 /// conjugate is also the inverse.
386 #[must_use]
387 #[inline]
388 pub fn conjugate(self) -> Self {
389 const SIGN: f32x4 = f32x4::from_array([-1.0, -1.0, -1.0, 1.0]);
390 Self(self.0.mul(SIGN))
391 }
392
393 /// Returns the inverse of a normalized quaternion.
394 ///
395 /// Typically quaternion inverse returns the conjugate of a normalized quaternion.
396 /// Because `self` is assumed to already be unit length this method *does not* normalize
397 /// before returning the conjugate.
398 ///
399 /// # Panics
400 ///
401 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
402 #[must_use]
403 #[inline]
404 pub fn inverse(self) -> Self {
405 glam_assert!(self.is_normalized());
406 self.conjugate()
407 }
408
409 /// Computes the dot product of `self` and `rhs`. The dot product is
410 /// equal to the cosine of the angle between two quaternion rotations.
411 #[inline]
412 pub fn dot(self, rhs: Self) -> f32 {
413 Vec4::from(self).dot(Vec4::from(rhs))
414 }
415
416 /// Computes the length of `self`.
417 #[doc(alias = "magnitude")]
418 #[inline]
419 pub fn length(self) -> f32 {
420 Vec4::from(self).length()
421 }
422
423 /// Computes the squared length of `self`.
424 ///
425 /// This is generally faster than `length()` as it avoids a square
426 /// root operation.
427 #[doc(alias = "magnitude2")]
428 #[inline]
429 pub fn length_squared(self) -> f32 {
430 Vec4::from(self).length_squared()
431 }
432
433 /// Computes `1.0 / length()`.
434 ///
435 /// For valid results, `self` must _not_ be of length zero.
436 #[inline]
437 pub fn length_recip(self) -> f32 {
438 Vec4::from(self).length_recip()
439 }
440
441 /// Returns `self` normalized to length 1.0.
442 ///
443 /// For valid results, `self` must _not_ be of length zero.
444 ///
445 /// Panics
446 ///
447 /// Will panic if `self` is zero length when `glam_assert` is enabled.
448 #[must_use]
449 #[inline]
450 pub fn normalize(self) -> Self {
451 Self::from_vec4(Vec4::from(self).normalize())
452 }
453
454 /// Returns `true` if, and only if, all elements are finite.
455 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
456 #[inline]
457 pub fn is_finite(self) -> bool {
458 Vec4::from(self).is_finite()
459 }
460
461 #[inline]
462 pub fn is_nan(self) -> bool {
463 Vec4::from(self).is_nan()
464 }
465
466 /// Returns whether `self` of length `1.0` or not.
467 ///
468 /// Uses a precision threshold of `1e-6`.
469 #[inline]
470 pub fn is_normalized(self) -> bool {
471 Vec4::from(self).is_normalized()
472 }
473
474 #[inline]
475 pub fn is_near_identity(self) -> bool {
476 // Based on https://github.com/nfrechette/rtm `rtm::quat_near_identity`
477 let threshold_angle = 0.002_847_144_6;
478 // Because of floating point precision, we cannot represent very small rotations.
479 // The closest f32 to 1.0 that is not 1.0 itself yields:
480 // 0.99999994.acos() * 2.0 = 0.000690533954 rad
481 //
482 // An error threshold of 1.e-6 is used by default.
483 // (1.0 - 1.e-6).acos() * 2.0 = 0.00284714461 rad
484 // (1.0 - 1.e-7).acos() * 2.0 = 0.00097656250 rad
485 //
486 // We don't really care about the angle value itself, only if it's close to 0.
487 // This will happen whenever quat.w is close to 1.0.
488 // If the quat.w is close to -1.0, the angle will be near 2*PI which is close to
489 // a negative 0 rotation. By forcing quat.w to be positive, we'll end up with
490 // the shortest path.
491 let positive_w_angle = math::acos_approx(math::abs(self.w)) * 2.0;
492 positive_w_angle < threshold_angle
493 }
494
495 /// Returns the angle (in radians) for the minimal rotation
496 /// for transforming this quaternion into another.
497 ///
498 /// Both quaternions must be normalized.
499 ///
500 /// # Panics
501 ///
502 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
503 #[inline]
504 pub fn angle_between(self, rhs: Self) -> f32 {
505 glam_assert!(self.is_normalized() && rhs.is_normalized());
506 math::acos_approx(math::abs(self.dot(rhs))) * 2.0
507 }
508
509 /// Returns true if the absolute difference of all elements between `self` and `rhs`
510 /// is less than or equal to `max_abs_diff`.
511 ///
512 /// This can be used to compare if two quaternions contain similar elements. It works
513 /// best when comparing with a known value. The `max_abs_diff` that should be used used
514 /// depends on the values being compared against.
515 ///
516 /// For more see
517 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
518 #[inline]
519 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
520 Vec4::from(self).abs_diff_eq(Vec4::from(rhs), max_abs_diff)
521 }
522
523 /// Performs a linear interpolation between `self` and `rhs` based on
524 /// the value `s`.
525 ///
526 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
527 /// is `1.0`, the result will be equal to `rhs`.
528 ///
529 /// # Panics
530 ///
531 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
532 #[inline]
533 #[doc(alias = "mix")]
534 pub fn lerp(self, end: Self, s: f32) -> Self {
535 glam_assert!(self.is_normalized());
536 glam_assert!(end.is_normalized());
537
538 const NEG_ZERO: f32x4 = f32x4::from_array([-0.0; 4]);
539 let start = self.0;
540 let end = end.0;
541 let dot = dot4_into_f32x4(start, end);
542 // Calculate the bias, if the dot product is positive or zero, there is no bias
543 // but if it is negative, we want to flip the 'end' rotation XYZW components
544 let bias = f32x4_bitand(dot, NEG_ZERO);
545 let interpolated = start + ((f32x4_bitxor(end, bias) - start) * f32x4::splat(s));
546 Quat(interpolated).normalize()
547 }
548
549 /// Performs a spherical linear interpolation between `self` and `end`
550 /// based on the value `s`.
551 ///
552 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
553 /// is `1.0`, the result will be equal to `end`.
554 ///
555 /// # Panics
556 ///
557 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
558 #[inline]
559 pub fn slerp(self, mut end: Self, s: f32) -> Self {
560 // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
561 glam_assert!(self.is_normalized());
562 glam_assert!(end.is_normalized());
563
564 const DOT_THRESHOLD: f32 = 0.9995;
565
566 // Note that a rotation can be represented by two quaternions: `q` and
567 // `-q`. The slerp path between `q` and `end` will be different from the
568 // path between `-q` and `end`. One path will take the long way around and
569 // one will take the short way. In order to correct for this, the `dot`
570 // product between `self` and `end` should be positive. If the `dot`
571 // product is negative, slerp between `self` and `-end`.
572 let mut dot = self.dot(end);
573 if dot < 0.0 {
574 end = -end;
575 dot = -dot;
576 }
577
578 if dot > DOT_THRESHOLD {
579 // assumes lerp returns a normalized quaternion
580 self.lerp(end, s)
581 } else {
582 let theta = math::acos_approx(dot);
583
584 let x = math::sin(theta * (1.0 - s));
585 let y = math::sin(theta * s);
586 let z = math::sin(theta);
587 let w = 0.0;
588 let tmp = f32x4::from_array([x, y, z, w]);
589
590 let scale1 = simd_swizzle!(tmp, [0, 0, 0, 0]);
591 let scale2 = simd_swizzle!(tmp, [1, 1, 1, 1]);
592 let theta_sin = simd_swizzle!(tmp, [2, 2, 2, 2]);
593
594 Self(self.0.mul(scale1).add(end.0.mul(scale2)).div(theta_sin))
595 }
596 }
597
598 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
599 ///
600 /// # Panics
601 ///
602 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
603 #[inline]
604 pub fn mul_vec3(self, rhs: Vec3) -> Vec3 {
605 glam_assert!(self.is_normalized());
606
607 self.mul_vec3a(rhs.into()).into()
608 }
609
610 /// Multiplies two quaternions. If they each represent a rotation, the result will
611 /// represent the combined rotation.
612 ///
613 /// Note that due to floating point rounding the result may not be perfectly normalized.
614 ///
615 /// # Panics
616 ///
617 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
618 #[inline]
619 pub fn mul_quat(self, rhs: Self) -> Self {
620 glam_assert!(self.is_normalized());
621 glam_assert!(rhs.is_normalized());
622
623 let lhs = self.0;
624 let rhs = rhs.0;
625
626 const CONTROL_WZYX: f32x4 = f32x4::from_array([1.0, -1.0, 1.0, -1.0]);
627 const CONTROL_ZWXY: f32x4 = f32x4::from_array([1.0, 1.0, -1.0, -1.0]);
628 const CONTROL_YXWZ: f32x4 = f32x4::from_array([-1.0, 1.0, 1.0, -1.0]);
629
630 let r_xxxx = simd_swizzle!(lhs, [0, 0, 0, 0]);
631 let r_yyyy = simd_swizzle!(lhs, [1, 1, 1, 1]);
632 let r_zzzz = simd_swizzle!(lhs, [2, 2, 2, 2]);
633 let r_wwww = simd_swizzle!(lhs, [3, 3, 3, 3]);
634
635 let lxrw_lyrw_lzrw_lwrw = r_wwww * rhs;
636 let l_wzyx = simd_swizzle!(rhs, [3, 2, 1, 0]);
637
638 let lwrx_lzrx_lyrx_lxrx = r_xxxx * l_wzyx;
639 let l_zwxy = simd_swizzle!(l_wzyx, [1, 0, 3, 2]);
640
641 let lwrx_nlzrx_lyrx_nlxrx = lwrx_lzrx_lyrx_lxrx * CONTROL_WZYX;
642
643 let lzry_lwry_lxry_lyry = r_yyyy * l_zwxy;
644 let l_yxwz = simd_swizzle!(l_zwxy, [3, 2, 1, 0]);
645
646 let lzry_lwry_nlxry_nlyry = lzry_lwry_lxry_lyry * CONTROL_ZWXY;
647
648 let lyrz_lxrz_lwrz_lzrz = r_zzzz * l_yxwz;
649 let result0 = lxrw_lyrw_lzrw_lwrw + lwrx_nlzrx_lyrx_nlxrx;
650
651 let nlyrz_lxrz_lwrz_wlzrz = lyrz_lxrz_lwrz_lzrz * CONTROL_YXWZ;
652 let result1 = lzry_lwry_nlxry_nlyry + nlyrz_lxrz_lwrz_wlzrz;
653 Self(result0 + result1)
654 }
655
656 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
657 #[inline]
658 pub fn from_affine3(a: &crate::Affine3A) -> Self {
659 #[allow(clippy::useless_conversion)]
660 Self::from_rotation_axes(
661 a.matrix3.x_axis.into(),
662 a.matrix3.y_axis.into(),
663 a.matrix3.z_axis.into(),
664 )
665 }
666
667 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
668 #[inline]
669 pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
670 const TWO: f32x4 = f32x4::from_array([2.0; 4]);
671 let w = simd_swizzle!(self.0, [3, 3, 3, 3]);
672 let b = self.0;
673 let b2 = dot3_into_f32x4(b, b);
674 Vec3A(
675 rhs.0
676 .mul(w.mul(w).sub(b2))
677 .add(b.mul(dot3_into_f32x4(rhs.0, b).mul(TWO)))
678 .add(Vec3A(b).cross(rhs).0.mul(w.mul(TWO))),
679 )
680 }
681
682 #[inline]
683 pub fn as_f64(self) -> DQuat {
684 DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
685 }
686 }
687
688 #[cfg(not(target_arch = "spirv"))]
689 impl fmt::Debug for Quat {
690 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
691 fmt.debug_tuple(stringify!(Quat))
692 .field(&self.x)
693 .field(&self.y)
694 .field(&self.z)
695 .field(&self.w)
696 .finish()
697 }
698 }
699
700 #[cfg(not(target_arch = "spirv"))]
701 impl fmt::Display for Quat {
702 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
703 write!(fmt, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
704 }
705 }
706
707 impl Add<Quat> for Quat {
708 type Output = Self;
709 /// Adds two quaternions.
710 ///
711 /// The sum is not guaranteed to be normalized.
712 ///
713 /// Note that addition is not the same as combining the rotations represented by the
714 /// two quaternions! That corresponds to multiplication.
715 #[inline]
716 fn add(self, rhs: Self) -> Self {
717 Self::from_vec4(Vec4::from(self) + Vec4::from(rhs))
718 }
719 }
720
721 impl Sub<Quat> for Quat {
722 type Output = Self;
723 /// Subtracts the `rhs` quaternion from `self`.
724 ///
725 /// The difference is not guaranteed to be normalized.
726 #[inline]
727 fn sub(self, rhs: Self) -> Self {
728 Self::from_vec4(Vec4::from(self) - Vec4::from(rhs))
729 }
730 }
731
732 impl Mul<f32> for Quat {
733 type Output = Self;
734 /// Multiplies a quaternion by a scalar value.
735 ///
736 /// The product is not guaranteed to be normalized.
737 #[inline]
738 fn mul(self, rhs: f32) -> Self {
739 Self::from_vec4(Vec4::from(self) * rhs)
740 }
741 }
742
743 impl Div<f32> for Quat {
744 type Output = Self;
745 /// Divides a quaternion by a scalar value.
746 /// The quotient is not guaranteed to be normalized.
747 #[inline]
748 fn div(self, rhs: f32) -> Self {
749 Self::from_vec4(Vec4::from(self) / rhs)
750 }
751 }
752
753 impl Mul<Quat> for Quat {
754 type Output = Self;
755 /// Multiplies two quaternions. If they each represent a rotation, the result will
756 /// represent the combined rotation.
757 ///
758 /// Note that due to floating point rounding the result may not be perfectly
759 /// normalized.
760 ///
761 /// # Panics
762 ///
763 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
764 #[inline]
765 fn mul(self, rhs: Self) -> Self {
766 self.mul_quat(rhs)
767 }
768 }
769
770 impl MulAssign<Quat> for Quat {
771 /// Multiplies two quaternions. If they each represent a rotation, the result will
772 /// represent the combined rotation.
773 ///
774 /// Note that due to floating point rounding the result may not be perfectly
775 /// normalized.
776 ///
777 /// # Panics
778 ///
779 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
780 #[inline]
781 fn mul_assign(&mut self, rhs: Self) {
782 *self = self.mul_quat(rhs);
783 }
784 }
785
786 impl Mul<Vec3> for Quat {
787 type Output = Vec3;
788 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
789 ///
790 /// # Panics
791 ///
792 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
793 #[inline]
794 fn mul(self, rhs: Vec3) -> Self::Output {
795 self.mul_vec3(rhs)
796 }
797 }
798
799 impl Neg for Quat {
800 type Output = Self;
801 #[inline]
802 fn neg(self) -> Self {
803 self * -1.0
804 }
805 }
806
807 impl Default for Quat {
808 #[inline]
809 fn default() -> Self {
810 Self::IDENTITY
811 }
812 }
813
814 impl PartialEq for Quat {
815 #[inline]
816 fn eq(&self, rhs: &Self) -> bool {
817 Vec4::from(*self).eq(&Vec4::from(*rhs))
818 }
819 }
820
821 #[cfg(not(target_arch = "spirv"))]
822 impl AsRef<[f32; 4]> for Quat {
823 #[inline]
824 fn as_ref(&self) -> &[f32; 4] {
825 unsafe { &*(self as *const Self as *const [f32; 4]) }
826 }
827 }
828
829 impl Sum<Self> for Quat {
830 fn sum<I>(iter: I) -> Self
831 where
832 I: Iterator<Item = Self>,
833 {
834 iter.fold(Self::ZERO, Self::add)
835 }
836 }
837
838 impl<'a> Sum<&'a Self> for Quat {
839 fn sum<I>(iter: I) -> Self
840 where
841 I: Iterator<Item = &'a Self>,
842 {
843 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
844 }
845 }
846
847 impl Product for Quat {
848 fn product<I>(iter: I) -> Self
849 where
850 I: Iterator<Item = Self>,
851 {
852 iter.fold(Self::IDENTITY, Self::mul)
853 }
854 }
855
856 impl<'a> Product<&'a Self> for Quat {
857 fn product<I>(iter: I) -> Self
858 where
859 I: Iterator<Item = &'a Self>,
860 {
861 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
862 }
863 }
864
865 impl Mul<Vec3A> for Quat {
866 type Output = Vec3A;
867 #[inline]
868 fn mul(self, rhs: Vec3A) -> Self::Output {
869 self.mul_vec3a(rhs)
870 }
871 }
872
873 impl From<Quat> for Vec4 {
874 #[inline]
875 fn from(q: Quat) -> Self {
876 Self(q.0)
877 }
878 }
879
880 impl From<Quat> for (f32, f32, f32, f32) {
881 #[inline]
882 fn from(q: Quat) -> Self {
883 Vec4::from(q).into()
884 }
885 }
886
887 impl From<Quat> for [f32; 4] {
888 #[inline]
889 fn from(q: Quat) -> Self {
890 Vec4::from(q).into()
891 }
892 }
893
894 impl From<Quat> for f32x4 {
895 #[inline]
896 fn from(q: Quat) -> Self {
897 q.0
898 }
899 }
900
901 impl Deref for Quat {
902 type Target = crate::deref::Vec4<f32>;
903 #[inline]
904 fn deref(&self) -> &Self::Target {
905 unsafe { &*(self as *const Self).cast() }
906 }
907 }
908
909 impl DerefMut for Quat {
910 #[inline]
911 fn deref_mut(&mut self) -> &mut Self::Target {
912 unsafe { &mut *(self as *mut Self).cast() }
913 }
914 }