Debian Codegraph @

debian/missing-sources/glam/src/f32/wasm32/quat.rs

raw
1 // Generated from quat.rs.tera template. Edit the template, not the generated file.
2
3 use crate::{
4 euler::{EulerRot, FromEuler, ToEuler},
5 f32::math,
6 wasm32::*,
7 DQuat, Mat3, Mat3A, Mat4, Vec2, Vec3, Vec3A, Vec4,
8 };
9
10 use core::arch::wasm32::*;
11
12 use core::fmt;
13 use core::iter::{Product, Sum};
14 use core::ops::{
15 Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign,
16 };
17
18 #[cfg(feature = "zerocopy")]
19 use zerocopy_derive::*;
20
21 /// Creates a quaternion from `x`, `y`, `z` and `w` values.
22 ///
23 /// This should generally not be called manually unless you know what you are doing. Use
24 /// one of the other constructors instead such as `identity` or `from_axis_angle`.
25 #[inline]
26 #[must_use]
27 pub const fn quat(x: f32, y: f32, z: f32, w: f32) -> Quat {
28 Quat::from_xyzw(x, y, z, w)
29 }
30
31 /// A quaternion representing an orientation.
32 ///
33 /// This quaternion is intended to be of unit length but may denormalize due to
34 /// floating point "error creep" which can occur when successive quaternion
35 /// operations are applied.
36 ///
37 /// SIMD vector types are used for storage on supported platforms.
38 ///
39 /// This type is 16 byte aligned.
40 #[derive(Clone, Copy)]
41 #[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
42 #[cfg_attr(
43 feature = "zerocopy",
44 derive(FromBytes, Immutable, IntoBytes, KnownLayout)
45 )]
46 #[repr(transparent)]
47 pub struct Quat(pub(crate) v128);
48
49 impl Quat {
50 /// All zeros.
51 const ZERO: Self = Self::from_array([0.0; 4]);
52
53 /// The identity quaternion. Corresponds to no rotation.
54 pub const IDENTITY: Self = Self::from_xyzw(0.0, 0.0, 0.0, 1.0);
55
56 /// All NANs.
57 pub const NAN: Self = Self::from_array([f32::NAN; 4]);
58
59 /// Creates a new rotation quaternion.
60 ///
61 /// This should generally not be called manually unless you know what you are doing.
62 /// Use one of the other constructors instead such as `identity` or `from_axis_angle`.
63 ///
64 /// `from_xyzw` is mostly used by unit tests and `serde` deserialization.
65 ///
66 /// # Preconditions
67 ///
68 /// This function does not check if the input is normalized, it is up to the user to
69 /// provide normalized input or to normalized the resulting quaternion.
70 #[inline(always)]
71 #[must_use]
72 pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
73 Self(f32x4(x, y, z, w))
74 }
75
76 /// Creates a rotation quaternion from an array.
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 #[must_use]
84 pub const fn from_array(a: [f32; 4]) -> Self {
85 Self::from_xyzw(a[0], a[1], a[2], a[3])
86 }
87
88 /// Creates a new rotation quaternion from a 4D vector.
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 #[inline]
95 #[must_use]
96 pub const fn from_vec4(v: Vec4) -> Self {
97 Self(v.0)
98 }
99
100 /// Creates a rotation quaternion from a slice.
101 ///
102 /// # Preconditions
103 ///
104 /// This function does not check if the input is normalized, it is up to the user to
105 /// provide normalized input or to normalized the resulting quaternion.
106 ///
107 /// # Panics
108 ///
109 /// Panics if `slice` length is less than 4.
110 #[inline]
111 #[must_use]
112 pub fn from_slice(slice: &[f32]) -> Self {
113 Self::from_xyzw(slice[0], slice[1], slice[2], slice[3])
114 }
115
116 /// Writes the quaternion to an unaligned slice.
117 ///
118 /// # Panics
119 ///
120 /// Panics if `slice` length is less than 4.
121 #[inline]
122 pub fn write_to_slice(self, slice: &mut [f32]) {
123 slice[0] = self.x;
124 slice[1] = self.y;
125 slice[2] = self.z;
126 slice[3] = self.w;
127 }
128
129 /// Create a quaternion for a normalized rotation `axis` and `angle` (in radians).
130 ///
131 /// The axis must be a unit vector.
132 ///
133 /// # Panics
134 ///
135 /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
136 #[inline]
137 #[must_use]
138 pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
139 glam_assert!(axis.is_normalized());
140 let (s, c) = math::sin_cos(angle * 0.5);
141 let v = axis * s;
142 Self::from_xyzw(v.x, v.y, v.z, c)
143 }
144
145 /// Create a quaternion that rotates `v.length()` radians around `v.normalize()`.
146 ///
147 /// `from_scaled_axis(Vec3::ZERO)` results in the identity quaternion.
148 #[inline]
149 #[must_use]
150 pub fn from_scaled_axis(v: Vec3) -> Self {
151 let length = v.length();
152 if length == 0.0 {
153 Self::IDENTITY
154 } else {
155 Self::from_axis_angle(v / length, length)
156 }
157 }
158
159 /// Creates a quaternion from the `angle` (in radians) around the x axis.
160 #[inline]
161 #[must_use]
162 pub fn from_rotation_x(angle: f32) -> Self {
163 let (s, c) = math::sin_cos(angle * 0.5);
164 Self::from_xyzw(s, 0.0, 0.0, c)
165 }
166
167 /// Creates a quaternion from the `angle` (in radians) around the y axis.
168 #[inline]
169 #[must_use]
170 pub fn from_rotation_y(angle: f32) -> Self {
171 let (s, c) = math::sin_cos(angle * 0.5);
172 Self::from_xyzw(0.0, s, 0.0, c)
173 }
174
175 /// Creates a quaternion from the `angle` (in radians) around the z axis.
176 #[inline]
177 #[must_use]
178 pub fn from_rotation_z(angle: f32) -> Self {
179 let (s, c) = math::sin_cos(angle * 0.5);
180 Self::from_xyzw(0.0, 0.0, s, c)
181 }
182
183 /// Creates a quaternion from the given Euler rotation sequence and the angles (in radians).
184 #[inline]
185 #[must_use]
186 pub fn from_euler(euler: EulerRot, a: f32, b: f32, c: f32) -> Self {
187 Self::from_euler_angles(euler, a, b, c)
188 }
189
190 /// From the columns of a 3x3 rotation matrix.
191 ///
192 /// Note if the input axes contain scales, shears, or other non-rotation transformations then
193 /// the output of this function is ill-defined.
194 ///
195 /// # Panics
196 ///
197 /// Will panic if any axis is not normalized when `glam_assert` is enabled.
198 #[inline]
199 #[must_use]
200 pub(crate) fn from_rotation_axes(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Self {
201 glam_assert!(x_axis.is_normalized() && y_axis.is_normalized() && z_axis.is_normalized());
202 // Based on https://github.com/microsoft/DirectXMath `XMQuaternionRotationMatrix`
203 let (m00, m01, m02) = x_axis.into();
204 let (m10, m11, m12) = y_axis.into();
205 let (m20, m21, m22) = z_axis.into();
206 if m22 <= 0.0 {
207 // x^2 + y^2 >= z^2 + w^2
208 let dif10 = m11 - m00;
209 let omm22 = 1.0 - m22;
210 if dif10 <= 0.0 {
211 // x^2 >= y^2
212 let four_xsq = omm22 - dif10;
213 let inv4x = 0.5 / math::sqrt(four_xsq);
214 Self::from_xyzw(
215 four_xsq * inv4x,
216 (m01 + m10) * inv4x,
217 (m02 + m20) * inv4x,
218 (m12 - m21) * inv4x,
219 )
220 } else {
221 // y^2 >= x^2
222 let four_ysq = omm22 + dif10;
223 let inv4y = 0.5 / math::sqrt(four_ysq);
224 Self::from_xyzw(
225 (m01 + m10) * inv4y,
226 four_ysq * inv4y,
227 (m12 + m21) * inv4y,
228 (m20 - m02) * inv4y,
229 )
230 }
231 } else {
232 // z^2 + w^2 >= x^2 + y^2
233 let sum10 = m11 + m00;
234 let opm22 = 1.0 + m22;
235 if sum10 <= 0.0 {
236 // z^2 >= w^2
237 let four_zsq = opm22 - sum10;
238 let inv4z = 0.5 / math::sqrt(four_zsq);
239 Self::from_xyzw(
240 (m02 + m20) * inv4z,
241 (m12 + m21) * inv4z,
242 four_zsq * inv4z,
243 (m01 - m10) * inv4z,
244 )
245 } else {
246 // w^2 >= z^2
247 let four_wsq = opm22 + sum10;
248 let inv4w = 0.5 / math::sqrt(four_wsq);
249 Self::from_xyzw(
250 (m12 - m21) * inv4w,
251 (m20 - m02) * inv4w,
252 (m01 - m10) * inv4w,
253 four_wsq * inv4w,
254 )
255 }
256 }
257 }
258
259 /// Creates a quaternion from a 3x3 rotation matrix.
260 ///
261 /// Note if the input matrix contain scales, shears, or other non-rotation transformations then
262 /// the resulting quaternion will be ill-defined.
263 ///
264 /// # Panics
265 ///
266 /// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
267 #[inline]
268 #[must_use]
269 pub fn from_mat3(mat: &Mat3) -> Self {
270 Self::from_rotation_axes(mat.x_axis, mat.y_axis, mat.z_axis)
271 }
272
273 /// Creates a quaternion from a 3x3 SIMD aligned rotation matrix.
274 ///
275 /// Note if the input matrix contain scales, shears, or other non-rotation transformations then
276 /// the resulting quaternion will be ill-defined.
277 ///
278 /// # Panics
279 ///
280 /// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
281 #[inline]
282 #[must_use]
283 pub fn from_mat3a(mat: &Mat3A) -> Self {
284 Self::from_rotation_axes(mat.x_axis.into(), mat.y_axis.into(), mat.z_axis.into())
285 }
286
287 /// Creates a quaternion from the upper 3x3 rotation matrix inside a homogeneous 4x4 matrix.
288 ///
289 /// Note if the upper 3x3 matrix contain scales, shears, or other non-rotation transformations
290 /// then the resulting quaternion will be ill-defined.
291 ///
292 /// # Panics
293 ///
294 /// Will panic if any column of the upper 3x3 rotation matrix is not normalized when
295 /// `glam_assert` is enabled.
296 #[inline]
297 #[must_use]
298 pub fn from_mat4(mat: &Mat4) -> Self {
299 Self::from_rotation_axes(
300 mat.x_axis.truncate(),
301 mat.y_axis.truncate(),
302 mat.z_axis.truncate(),
303 )
304 }
305
306 /// Gets the minimal rotation for transforming `from` to `to`. The rotation is in the
307 /// plane spanned by the two vectors. Will rotate at most 180 degrees.
308 ///
309 /// The inputs must be unit vectors.
310 ///
311 /// `from_rotation_arc(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 #[must_use]
320 pub fn from_rotation_arc(from: Vec3, to: Vec3) -> Self {
321 glam_assert!(from.is_normalized());
322 glam_assert!(to.is_normalized());
323
324 const ONE_MINUS_EPS: f32 = 1.0 - 2.0 * f32::EPSILON;
325 let dot = from.dot(to);
326 if dot > ONE_MINUS_EPS {
327 // 0° singularity: from ≈ to
328 Self::IDENTITY
329 } else if dot < -ONE_MINUS_EPS {
330 // 180° singularity: from ≈ -to
331 use core::f32::consts::PI; // half a turn = 𝛕/2 = 180°
332 Self::from_axis_angle(from.any_orthonormal_vector(), PI)
333 } else {
334 let c = from.cross(to);
335 Self::from_xyzw(c.x, c.y, c.z, 1.0 + dot).normalize()
336 }
337 }
338
339 /// Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means
340 /// that the resulting quaternion will rotate `from` so that it is colinear with `to`.
341 ///
342 /// The rotation is in the plane spanned by the two vectors. Will rotate at most 90
343 /// degrees.
344 ///
345 /// The inputs must be unit vectors.
346 ///
347 /// `to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`.
348 ///
349 /// # Panics
350 ///
351 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
352 #[inline]
353 #[must_use]
354 pub fn from_rotation_arc_colinear(from: Vec3, to: Vec3) -> Self {
355 if from.dot(to) < 0.0 {
356 Self::from_rotation_arc(from, -to)
357 } else {
358 Self::from_rotation_arc(from, to)
359 }
360 }
361
362 /// Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is
363 /// around the z axis. Will rotate at most 180 degrees.
364 ///
365 /// The inputs must be unit vectors.
366 ///
367 /// `from_rotation_arc_2d(from, to) * from ≈ to`.
368 ///
369 /// For near-singular cases (from≈to and from≈-to) the current implementation
370 /// is only accurate to about 0.001 (for `f32`).
371 ///
372 /// # Panics
373 ///
374 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
375 #[must_use]
376 pub fn from_rotation_arc_2d(from: Vec2, to: Vec2) -> Self {
377 glam_assert!(from.is_normalized());
378 glam_assert!(to.is_normalized());
379
380 const ONE_MINUS_EPSILON: f32 = 1.0 - 2.0 * f32::EPSILON;
381 let dot = from.dot(to);
382 if dot > ONE_MINUS_EPSILON {
383 // 0° singularity: from ≈ to
384 Self::IDENTITY
385 } else if dot < -ONE_MINUS_EPSILON {
386 // 180° singularity: from ≈ -to
387 const COS_FRAC_PI_2: f32 = 0.0;
388 const SIN_FRAC_PI_2: f32 = 1.0;
389 // rotation around z by PI radians
390 Self::from_xyzw(0.0, 0.0, SIN_FRAC_PI_2, COS_FRAC_PI_2)
391 } else {
392 // vector3 cross where z=0
393 let z = from.x * to.y - to.x * from.y;
394 let w = 1.0 + dot;
395 // calculate length with x=0 and y=0 to normalize
396 let len_rcp = 1.0 / math::sqrt(z * z + w * w);
397 Self::from_xyzw(0.0, 0.0, z * len_rcp, w * len_rcp)
398 }
399 }
400
401 /// Creates a quaterion rotation from a facing direction and an up direction.
402 ///
403 /// For a left-handed view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
404 ///
405 /// # Panics
406 ///
407 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
408 #[inline]
409 #[must_use]
410 pub fn look_to_lh(dir: Vec3, up: Vec3) -> Self {
411 Self::look_to_rh(-dir, up)
412 }
413
414 /// Creates a quaterion rotation from facing direction and an up direction.
415 ///
416 /// For a right-handed view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
417 ///
418 /// # Panics
419 ///
420 /// Will panic if `dir` and `up` are not normalized when `glam_assert` is enabled.
421 #[inline]
422 #[must_use]
423 pub fn look_to_rh(dir: Vec3, up: Vec3) -> Self {
424 glam_assert!(dir.is_normalized());
425 glam_assert!(up.is_normalized());
426 let f = dir;
427 let s = f.cross(up).normalize();
428 let u = s.cross(f);
429
430 Self::from_rotation_axes(
431 Vec3::new(s.x, u.x, -f.x),
432 Vec3::new(s.y, u.y, -f.y),
433 Vec3::new(s.z, u.z, -f.z),
434 )
435 }
436
437 /// Creates a left-handed view matrix using a camera position, a focal point, and an up
438 /// direction.
439 ///
440 /// For a left-handed view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
441 ///
442 /// # Panics
443 ///
444 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
445 #[inline]
446 #[must_use]
447 pub fn look_at_lh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
448 Self::look_to_lh(center.sub(eye).normalize(), up)
449 }
450
451 /// Creates a right-handed view matrix using a camera position, an up direction, and a focal
452 /// point.
453 ///
454 /// For a right-handed view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
455 ///
456 /// # Panics
457 ///
458 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
459 #[inline]
460 #[must_use]
461 pub fn look_at_rh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
462 Self::look_to_rh(center.sub(eye).normalize(), up)
463 }
464
465 /// Returns the rotation axis (normalized) and angle (in radians) of `self`.
466 #[inline]
467 #[must_use]
468 pub fn to_axis_angle(self) -> (Vec3, f32) {
469 const EPSILON: f32 = 1.0e-8;
470 let v = Vec3::new(self.x, self.y, self.z);
471 let length = v.length();
472 if length >= EPSILON {
473 let angle = 2.0 * math::atan2(length, self.w);
474 let axis = v / length;
475 (axis, angle)
476 } else {
477 (Vec3::X, 0.0)
478 }
479 }
480
481 /// Returns the rotation axis scaled by the rotation in radians.
482 #[inline]
483 #[must_use]
484 pub fn to_scaled_axis(self) -> Vec3 {
485 let (axis, angle) = self.to_axis_angle();
486 axis * angle
487 }
488
489 /// Returns the rotation angles for the given euler rotation sequence.
490 #[inline]
491 #[must_use]
492 pub fn to_euler(self, order: EulerRot) -> (f32, f32, f32) {
493 self.to_euler_angles(order)
494 }
495
496 /// `[x, y, z, w]`
497 #[inline]
498 #[must_use]
499 pub fn to_array(&self) -> [f32; 4] {
500 [self.x, self.y, self.z, self.w]
501 }
502
503 /// Returns the vector part of the quaternion.
504 #[inline]
505 #[must_use]
506 pub fn xyz(self) -> Vec3 {
507 Vec3::new(self.x, self.y, self.z)
508 }
509
510 /// Returns the quaternion conjugate of `self`. For a unit quaternion the
511 /// conjugate is also the inverse.
512 #[inline]
513 #[must_use]
514 pub fn conjugate(self) -> Self {
515 const SIGN: v128 = v128_from_f32x4([-1.0, -1.0, -1.0, 1.0]);
516 Self(f32x4_mul(self.0, SIGN))
517 }
518
519 /// Returns the inverse of a normalized quaternion.
520 ///
521 /// Typically quaternion inverse returns the conjugate of a normalized quaternion.
522 /// Because `self` is assumed to already be unit length this method *does not* normalize
523 /// before returning the conjugate.
524 ///
525 /// # Panics
526 ///
527 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
528 #[inline]
529 #[must_use]
530 pub fn inverse(self) -> Self {
531 glam_assert!(self.is_normalized());
532 self.conjugate()
533 }
534
535 /// Computes the dot product of `self` and `rhs`. The dot product is
536 /// equal to the cosine of the angle between two quaternion rotations.
537 #[inline]
538 #[must_use]
539 pub fn dot(self, rhs: Self) -> f32 {
540 Vec4::from(self).dot(Vec4::from(rhs))
541 }
542
543 /// Computes the length of `self`.
544 #[doc(alias = "magnitude")]
545 #[inline]
546 #[must_use]
547 pub fn length(self) -> f32 {
548 Vec4::from(self).length()
549 }
550
551 /// Computes the squared length of `self`.
552 ///
553 /// This is generally faster than `length()` as it avoids a square
554 /// root operation.
555 #[doc(alias = "magnitude2")]
556 #[inline]
557 #[must_use]
558 pub fn length_squared(self) -> f32 {
559 Vec4::from(self).length_squared()
560 }
561
562 /// Computes `1.0 / length()`.
563 ///
564 /// For valid results, `self` must _not_ be of length zero.
565 #[inline]
566 #[must_use]
567 pub fn length_recip(self) -> f32 {
568 Vec4::from(self).length_recip()
569 }
570
571 /// Returns `self` normalized to length 1.0.
572 ///
573 /// For valid results, `self` must _not_ be of length zero.
574 ///
575 /// Panics
576 ///
577 /// Will panic if `self` is zero length when `glam_assert` is enabled.
578 #[inline]
579 #[must_use]
580 pub fn normalize(self) -> Self {
581 Self::from_vec4(Vec4::from(self).normalize())
582 }
583
584 /// Returns `true` if, and only if, all elements are finite.
585 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
586 #[inline]
587 #[must_use]
588 pub fn is_finite(self) -> bool {
589 Vec4::from(self).is_finite()
590 }
591
592 /// Returns `true` if any elements are `NAN`.
593 #[inline]
594 #[must_use]
595 pub fn is_nan(self) -> bool {
596 Vec4::from(self).is_nan()
597 }
598
599 /// Returns whether `self` of length `1.0` or not.
600 ///
601 /// Uses a precision threshold of `1e-6`.
602 #[inline]
603 #[must_use]
604 pub fn is_normalized(self) -> bool {
605 Vec4::from(self).is_normalized()
606 }
607
608 #[inline]
609 #[must_use]
610 pub fn is_near_identity(self) -> bool {
611 // Based on https://github.com/nfrechette/rtm `rtm::quat_near_identity`
612 // Because of floating point precision, we cannot represent very small rotations.
613 // The closest f32 to 1.0 that is not 1.0 itself yields:
614 // 0.99999994.acos() * 2.0 = 0.000690533954 rad
615 //
616 // An error threshold of 1.e-6 is used by default.
617 // (1.0 - 1.e-6).acos() * 2.0 = 0.00284714461 rad
618 // (1.0 - 1.e-7).acos() * 2.0 = 0.00097656250 rad
619 //
620 // We don't really care about the angle value itself, only if it's close to 0.
621 // This will happen whenever quat.w is close to 1.0.
622 // If the quat.w is close to -1.0, the angle will be near 2*PI which is close to
623 // a negative 0 rotation. By forcing quat.w to be positive, we'll end up with
624 // the shortest path.
625 //
626 // For f64 we're using a threshhold of
627 // (1.0 - 1e-14).acos() * 2.0
628 const THRESHOLD_ANGLE: f32 = 0.002_847_144_6;
629 let positive_w_angle = math::acos_approx(math::abs(self.w)) * 2.0;
630 positive_w_angle < THRESHOLD_ANGLE
631 }
632
633 /// Returns the angle (in radians) for the minimal rotation
634 /// for transforming this quaternion into another.
635 ///
636 /// Both quaternions must be normalized.
637 ///
638 /// # Panics
639 ///
640 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
641 #[inline]
642 #[must_use]
643 pub fn angle_between(self, rhs: Self) -> f32 {
644 glam_assert!(self.is_normalized() && rhs.is_normalized());
645 math::acos_approx(math::abs(self.dot(rhs))) * 2.0
646 }
647
648 /// Rotates towards `rhs` up to `max_angle` (in radians).
649 ///
650 /// When `max_angle` is `0.0`, the result will be equal to `self`. When `max_angle` is equal to
651 /// `self.angle_between(rhs)`, the result will be equal to `rhs`. If `max_angle` is negative,
652 /// rotates towards the exact opposite of `rhs`. Will not go past the target.
653 ///
654 /// Both quaternions must be normalized.
655 ///
656 /// # Panics
657 ///
658 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
659 #[inline]
660 #[must_use]
661 pub fn rotate_towards(&self, rhs: Self, max_angle: f32) -> Self {
662 glam_assert!(self.is_normalized() && rhs.is_normalized());
663 let angle = self.angle_between(rhs);
664 if angle <= 1e-4 {
665 return rhs;
666 }
667 let s = (max_angle / angle).clamp(-1.0, 1.0);
668 self.slerp(rhs, s)
669 }
670
671 /// Returns true if the absolute difference of all elements between `self` and `rhs`
672 /// is less than or equal to `max_abs_diff`.
673 ///
674 /// This can be used to compare if two quaternions contain similar elements. It works
675 /// best when comparing with a known value. The `max_abs_diff` that should be used used
676 /// depends on the values being compared against.
677 ///
678 /// For more see
679 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
680 #[inline]
681 #[must_use]
682 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
683 Vec4::from(self).abs_diff_eq(Vec4::from(rhs), max_abs_diff)
684 }
685
686 #[inline(always)]
687 #[must_use]
688 fn lerp_impl(self, end: Self, s: f32) -> Self {
689 (self * (1.0 - s) + end * s).normalize()
690 }
691
692 /// Performs a linear interpolation between `self` and `rhs` based on
693 /// the value `s`.
694 ///
695 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
696 /// is `1.0`, the result will be equal to `rhs`.
697 ///
698 /// # Panics
699 ///
700 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
701 #[doc(alias = "mix")]
702 #[inline]
703 #[must_use]
704 pub fn lerp(self, end: Self, s: f32) -> Self {
705 glam_assert!(self.is_normalized());
706 glam_assert!(end.is_normalized());
707
708 const NEG_ZERO: v128 = v128_from_f32x4([-0.0; 4]);
709 let dot = dot4_into_v128(self.0, end.0);
710 // Calculate the bias, if the dot product is positive or zero, there is no bias
711 // but if it is negative, we want to flip the 'end' rotation XYZW components
712 let bias = v128_and(dot, NEG_ZERO);
713 self.lerp_impl(Self(v128_xor(end.0, bias)), s)
714 }
715
716 /// Performs a spherical linear interpolation between `self` and `end`
717 /// based on the value `s`.
718 ///
719 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
720 /// is `1.0`, the result will be equal to `end`.
721 ///
722 /// # Panics
723 ///
724 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
725 #[inline]
726 #[must_use]
727 pub fn slerp(self, mut end: Self, s: f32) -> Self {
728 // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
729 glam_assert!(self.is_normalized());
730 glam_assert!(end.is_normalized());
731
732 // Note that a rotation can be represented by two quaternions: `q` and
733 // `-q`. The slerp path between `q` and `end` will be different from the
734 // path between `-q` and `end`. One path will take the long way around and
735 // one will take the short way. In order to correct for this, the `dot`
736 // product between `self` and `end` should be positive. If the `dot`
737 // product is negative, slerp between `self` and `-end`.
738 let mut dot = self.dot(end);
739 if dot < 0.0 {
740 end = -end;
741 dot = -dot;
742 }
743
744 const DOT_THRESHOLD: f32 = 1.0 - f32::EPSILON;
745 if dot > DOT_THRESHOLD {
746 // if above threshold perform linear interpolation to avoid divide by zero
747 self.lerp_impl(end, s)
748 } else {
749 let theta = math::acos_approx(dot);
750
751 let scale1 = math::sin(theta * (1.0 - s));
752 let scale2 = math::sin(theta * s);
753 let theta_sin = math::sin(theta);
754 ((self * scale1) + (end * scale2)) * (1.0 / theta_sin)
755 }
756 }
757
758 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
759 ///
760 /// # Panics
761 ///
762 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
763 #[inline]
764 #[must_use]
765 pub fn mul_vec3(self, rhs: Vec3) -> Vec3 {
766 glam_assert!(self.is_normalized());
767
768 self.mul_vec3a(rhs.into()).into()
769 }
770
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 normalized.
775 ///
776 /// # Panics
777 ///
778 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
779 #[inline]
780 #[must_use]
781 pub fn mul_quat(self, rhs: Self) -> Self {
782 let lhs = self.0;
783 let rhs = rhs.0;
784
785 const CONTROL_WZYX: v128 = v128_from_f32x4([1.0, -1.0, 1.0, -1.0]);
786 const CONTROL_ZWXY: v128 = v128_from_f32x4([1.0, 1.0, -1.0, -1.0]);
787 const CONTROL_YXWZ: v128 = v128_from_f32x4([-1.0, 1.0, 1.0, -1.0]);
788
789 let r_xxxx = i32x4_shuffle::<0, 0, 4, 4>(lhs, lhs);
790 let r_yyyy = i32x4_shuffle::<1, 1, 5, 5>(lhs, lhs);
791 let r_zzzz = i32x4_shuffle::<2, 2, 6, 6>(lhs, lhs);
792 let r_wwww = i32x4_shuffle::<3, 3, 7, 7>(lhs, lhs);
793
794 let lxrw_lyrw_lzrw_lwrw = f32x4_mul(r_wwww, rhs);
795 let l_wzyx = i32x4_shuffle::<3, 2, 5, 4>(rhs, rhs);
796
797 let lwrx_lzrx_lyrx_lxrx = f32x4_mul(r_xxxx, l_wzyx);
798 let l_zwxy = i32x4_shuffle::<1, 0, 7, 6>(l_wzyx, l_wzyx);
799
800 let lwrx_nlzrx_lyrx_nlxrx = f32x4_mul(lwrx_lzrx_lyrx_lxrx, CONTROL_WZYX);
801
802 let lzry_lwry_lxry_lyry = f32x4_mul(r_yyyy, l_zwxy);
803 let l_yxwz = i32x4_shuffle::<3, 2, 5, 4>(l_zwxy, l_zwxy);
804
805 let lzry_lwry_nlxry_nlyry = f32x4_mul(lzry_lwry_lxry_lyry, CONTROL_ZWXY);
806
807 let lyrz_lxrz_lwrz_lzrz = f32x4_mul(r_zzzz, l_yxwz);
808 let result0 = f32x4_add(lxrw_lyrw_lzrw_lwrw, lwrx_nlzrx_lyrx_nlxrx);
809
810 let nlyrz_lxrz_lwrz_wlzrz = f32x4_mul(lyrz_lxrz_lwrz_lzrz, CONTROL_YXWZ);
811 let result1 = f32x4_add(lzry_lwry_nlxry_nlyry, nlyrz_lxrz_lwrz_wlzrz);
812
813 Self(f32x4_add(result0, result1))
814 }
815
816 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
817 ///
818 /// Note if the input affine matrix contain scales, shears, or other non-rotation
819 /// transformations then the resulting quaternion will be ill-defined.
820 ///
821 /// # Panics
822 ///
823 /// Will panic if any input affine matrix column is not normalized when `glam_assert` is
824 /// enabled.
825 #[inline]
826 #[must_use]
827 pub fn from_affine3(a: &crate::Affine3A) -> Self {
828 #[allow(clippy::useless_conversion)]
829 Self::from_rotation_axes(
830 a.matrix3.x_axis.into(),
831 a.matrix3.y_axis.into(),
832 a.matrix3.z_axis.into(),
833 )
834 }
835
836 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
837 #[inline]
838 #[must_use]
839 pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
840 const TWO: v128 = v128_from_f32x4([2.0; 4]);
841 let w = i32x4_shuffle::<3, 3, 7, 7>(self.0, self.0);
842 let b = self.0;
843 let b2 = dot3_into_v128(b, b);
844 Vec3A(f32x4_add(
845 f32x4_add(
846 f32x4_mul(rhs.0, f32x4_sub(f32x4_mul(w, w), b2)),
847 f32x4_mul(b, f32x4_mul(dot3_into_v128(rhs.0, b), TWO)),
848 ),
849 f32x4_mul(Vec3A(b).cross(rhs).into(), f32x4_mul(w, TWO)),
850 ))
851 }
852
853 #[inline]
854 #[must_use]
855 pub fn as_dquat(self) -> DQuat {
856 DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
857 }
858 }
859
860 impl fmt::Debug for Quat {
861 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
862 fmt.debug_tuple(stringify!(Quat))
863 .field(&self.x)
864 .field(&self.y)
865 .field(&self.z)
866 .field(&self.w)
867 .finish()
868 }
869 }
870
871 impl fmt::Display for Quat {
872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
873 if let Some(p) = f.precision() {
874 write!(
875 f,
876 "[{:.*}, {:.*}, {:.*}, {:.*}]",
877 p, self.x, p, self.y, p, self.z, p, self.w
878 )
879 } else {
880 write!(f, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
881 }
882 }
883 }
884
885 impl Add for Quat {
886 type Output = Self;
887 /// Adds two quaternions.
888 ///
889 /// The sum is not guaranteed to be normalized.
890 ///
891 /// Note that addition is not the same as combining the rotations represented by the
892 /// two quaternions! That corresponds to multiplication.
893 #[inline]
894 fn add(self, rhs: Self) -> Self {
895 Self::from_vec4(Vec4::from(self) + Vec4::from(rhs))
896 }
897 }
898
899 impl Add<&Self> for Quat {
900 type Output = Self;
901 #[inline]
902 fn add(self, rhs: &Self) -> Self {
903 self.add(*rhs)
904 }
905 }
906
907 impl Add<&Quat> for &Quat {
908 type Output = Quat;
909 #[inline]
910 fn add(self, rhs: &Quat) -> Quat {
911 (*self).add(*rhs)
912 }
913 }
914
915 impl Add<Quat> for &Quat {
916 type Output = Quat;
917 #[inline]
918 fn add(self, rhs: Quat) -> Quat {
919 (*self).add(rhs)
920 }
921 }
922
923 impl AddAssign for Quat {
924 #[inline]
925 fn add_assign(&mut self, rhs: Self) {
926 *self = self.add(rhs);
927 }
928 }
929
930 impl AddAssign<&Self> for Quat {
931 #[inline]
932 fn add_assign(&mut self, rhs: &Self) {
933 self.add_assign(*rhs);
934 }
935 }
936
937 impl Sub for Quat {
938 type Output = Self;
939 /// Subtracts the `rhs` quaternion from `self`.
940 ///
941 /// The difference is not guaranteed to be normalized.
942 #[inline]
943 fn sub(self, rhs: Self) -> Self {
944 Self::from_vec4(Vec4::from(self) - Vec4::from(rhs))
945 }
946 }
947
948 impl Sub<&Self> for Quat {
949 type Output = Self;
950 #[inline]
951 fn sub(self, rhs: &Self) -> Self {
952 self.sub(*rhs)
953 }
954 }
955
956 impl Sub<&Quat> for &Quat {
957 type Output = Quat;
958 #[inline]
959 fn sub(self, rhs: &Quat) -> Quat {
960 (*self).sub(*rhs)
961 }
962 }
963
964 impl Sub<Quat> for &Quat {
965 type Output = Quat;
966 #[inline]
967 fn sub(self, rhs: Quat) -> Quat {
968 (*self).sub(rhs)
969 }
970 }
971
972 impl SubAssign for Quat {
973 #[inline]
974 fn sub_assign(&mut self, rhs: Self) {
975 *self = self.sub(rhs);
976 }
977 }
978
979 impl SubAssign<&Self> for Quat {
980 #[inline]
981 fn sub_assign(&mut self, rhs: &Self) {
982 self.sub_assign(*rhs);
983 }
984 }
985
986 impl Mul<f32> for Quat {
987 type Output = Self;
988 /// Multiplies a quaternion by a scalar value.
989 ///
990 /// The product is not guaranteed to be normalized.
991 #[inline]
992 fn mul(self, rhs: f32) -> Self {
993 Self::from_vec4(Vec4::from(self) * rhs)
994 }
995 }
996
997 impl Mul<&f32> for Quat {
998 type Output = Self;
999 #[inline]
1000 fn mul(self, rhs: &f32) -> Self {
1001 self.mul(*rhs)
1002 }
1003 }
1004
1005 impl Mul<&f32> for &Quat {
1006 type Output = Quat;
1007 #[inline]
1008 fn mul(self, rhs: &f32) -> Quat {
1009 (*self).mul(*rhs)
1010 }
1011 }
1012
1013 impl Mul<f32> for &Quat {
1014 type Output = Quat;
1015 #[inline]
1016 fn mul(self, rhs: f32) -> Quat {
1017 (*self).mul(rhs)
1018 }
1019 }
1020
1021 impl MulAssign<f32> for Quat {
1022 #[inline]
1023 fn mul_assign(&mut self, rhs: f32) {
1024 *self = self.mul(rhs);
1025 }
1026 }
1027
1028 impl MulAssign<&f32> for Quat {
1029 #[inline]
1030 fn mul_assign(&mut self, rhs: &f32) {
1031 self.mul_assign(*rhs);
1032 }
1033 }
1034
1035 impl Div<f32> for Quat {
1036 type Output = Self;
1037 /// Divides a quaternion by a scalar value.
1038 /// The quotient is not guaranteed to be normalized.
1039 #[inline]
1040 fn div(self, rhs: f32) -> Self {
1041 Self::from_vec4(Vec4::from(self) / rhs)
1042 }
1043 }
1044
1045 impl Div<&f32> for Quat {
1046 type Output = Self;
1047 #[inline]
1048 fn div(self, rhs: &f32) -> Self {
1049 self.div(*rhs)
1050 }
1051 }
1052
1053 impl Div<&f32> for &Quat {
1054 type Output = Quat;
1055 #[inline]
1056 fn div(self, rhs: &f32) -> Quat {
1057 (*self).div(*rhs)
1058 }
1059 }
1060
1061 impl Div<f32> for &Quat {
1062 type Output = Quat;
1063 #[inline]
1064 fn div(self, rhs: f32) -> Quat {
1065 (*self).div(rhs)
1066 }
1067 }
1068
1069 impl DivAssign<f32> for Quat {
1070 #[inline]
1071 fn div_assign(&mut self, rhs: f32) {
1072 *self = self.div(rhs);
1073 }
1074 }
1075
1076 impl DivAssign<&f32> for Quat {
1077 #[inline]
1078 fn div_assign(&mut self, rhs: &f32) {
1079 self.div_assign(*rhs);
1080 }
1081 }
1082
1083 impl Mul for Quat {
1084 type Output = Self;
1085 /// Multiplies two quaternions. If they each represent a rotation, the result will
1086 /// represent the combined rotation.
1087 ///
1088 /// Note that due to floating point rounding the result may not be perfectly
1089 /// normalized.
1090 ///
1091 /// # Panics
1092 ///
1093 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
1094 #[inline]
1095 fn mul(self, rhs: Self) -> Self {
1096 self.mul_quat(rhs)
1097 }
1098 }
1099
1100 impl Mul<&Self> for Quat {
1101 type Output = Self;
1102 #[inline]
1103 fn mul(self, rhs: &Self) -> Self {
1104 self.mul(*rhs)
1105 }
1106 }
1107
1108 impl Mul<&Quat> for &Quat {
1109 type Output = Quat;
1110 #[inline]
1111 fn mul(self, rhs: &Quat) -> Quat {
1112 (*self).mul(*rhs)
1113 }
1114 }
1115
1116 impl Mul<Quat> for &Quat {
1117 type Output = Quat;
1118 #[inline]
1119 fn mul(self, rhs: Quat) -> Quat {
1120 (*self).mul(rhs)
1121 }
1122 }
1123
1124 impl MulAssign for Quat {
1125 #[inline]
1126 fn mul_assign(&mut self, rhs: Self) {
1127 *self = self.mul(rhs);
1128 }
1129 }
1130
1131 impl MulAssign<&Self> for Quat {
1132 #[inline]
1133 fn mul_assign(&mut self, rhs: &Self) {
1134 self.mul_assign(*rhs);
1135 }
1136 }
1137
1138 impl Mul<Vec3> for Quat {
1139 type Output = Vec3;
1140 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
1141 ///
1142 /// # Panics
1143 ///
1144 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
1145 #[inline]
1146 fn mul(self, rhs: Vec3) -> Self::Output {
1147 self.mul_vec3(rhs)
1148 }
1149 }
1150
1151 impl Mul<&Vec3> for Quat {
1152 type Output = Vec3;
1153 #[inline]
1154 fn mul(self, rhs: &Vec3) -> Vec3 {
1155 self.mul(*rhs)
1156 }
1157 }
1158
1159 impl Mul<&Vec3> for &Quat {
1160 type Output = Vec3;
1161 #[inline]
1162 fn mul(self, rhs: &Vec3) -> Vec3 {
1163 (*self).mul(*rhs)
1164 }
1165 }
1166
1167 impl Mul<Vec3> for &Quat {
1168 type Output = Vec3;
1169 #[inline]
1170 fn mul(self, rhs: Vec3) -> Vec3 {
1171 (*self).mul(rhs)
1172 }
1173 }
1174
1175 impl Mul<Vec3A> for Quat {
1176 type Output = Vec3A;
1177 #[inline]
1178 fn mul(self, rhs: Vec3A) -> Self::Output {
1179 self.mul_vec3a(rhs)
1180 }
1181 }
1182
1183 impl Mul<&Vec3A> for Quat {
1184 type Output = Vec3A;
1185 #[inline]
1186 fn mul(self, rhs: &Vec3A) -> Vec3A {
1187 self.mul(*rhs)
1188 }
1189 }
1190
1191 impl Mul<&Vec3A> for &Quat {
1192 type Output = Vec3A;
1193 #[inline]
1194 fn mul(self, rhs: &Vec3A) -> Vec3A {
1195 (*self).mul(*rhs)
1196 }
1197 }
1198
1199 impl Mul<Vec3A> for &Quat {
1200 type Output = Vec3A;
1201 #[inline]
1202 fn mul(self, rhs: Vec3A) -> Vec3A {
1203 (*self).mul(rhs)
1204 }
1205 }
1206
1207 impl Neg for Quat {
1208 type Output = Self;
1209 #[inline]
1210 fn neg(self) -> Self {
1211 self * -1.0
1212 }
1213 }
1214
1215 impl Neg for &Quat {
1216 type Output = Quat;
1217 #[inline]
1218 fn neg(self) -> Quat {
1219 (*self).neg()
1220 }
1221 }
1222
1223 impl Default for Quat {
1224 #[inline]
1225 fn default() -> Self {
1226 Self::IDENTITY
1227 }
1228 }
1229
1230 impl PartialEq for Quat {
1231 #[inline]
1232 fn eq(&self, rhs: &Self) -> bool {
1233 Vec4::from(*self).eq(&Vec4::from(*rhs))
1234 }
1235 }
1236
1237 impl AsRef<[f32; 4]> for Quat {
1238 #[inline]
1239 fn as_ref(&self) -> &[f32; 4] {
1240 unsafe { &*(self as *const Self as *const [f32; 4]) }
1241 }
1242 }
1243
1244 impl Sum<Self> for Quat {
1245 fn sum<I>(iter: I) -> Self
1246 where
1247 I: Iterator<Item = Self>,
1248 {
1249 iter.fold(Self::ZERO, Self::add)
1250 }
1251 }
1252
1253 impl<'a> Sum<&'a Self> for Quat {
1254 fn sum<I>(iter: I) -> Self
1255 where
1256 I: Iterator<Item = &'a Self>,
1257 {
1258 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1259 }
1260 }
1261
1262 impl Product for Quat {
1263 fn product<I>(iter: I) -> Self
1264 where
1265 I: Iterator<Item = Self>,
1266 {
1267 iter.fold(Self::IDENTITY, Self::mul)
1268 }
1269 }
1270
1271 impl<'a> Product<&'a Self> for Quat {
1272 fn product<I>(iter: I) -> Self
1273 where
1274 I: Iterator<Item = &'a Self>,
1275 {
1276 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
1277 }
1278 }
1279
1280 impl From<Quat> for Vec4 {
1281 #[inline]
1282 fn from(q: Quat) -> Self {
1283 Self(q.0)
1284 }
1285 }
1286
1287 impl From<Quat> for (f32, f32, f32, f32) {
1288 #[inline]
1289 fn from(q: Quat) -> Self {
1290 Vec4::from(q).into()
1291 }
1292 }
1293
1294 impl From<Quat> for [f32; 4] {
1295 #[inline]
1296 fn from(q: Quat) -> Self {
1297 Vec4::from(q).into()
1298 }
1299 }
1300
1301 impl From<Quat> for v128 {
1302 #[inline]
1303 fn from(q: Quat) -> Self {
1304 q.0
1305 }
1306 }
1307
1308 impl Deref for Quat {
1309 type Target = crate::deref::Vec4<f32>;
1310 #[inline]
1311 fn deref(&self) -> &Self::Target {
1312 unsafe { &*(self as *const Self).cast() }
1313 }
1314 }
1315
1316 impl DerefMut for Quat {
1317 #[inline]
1318 fn deref_mut(&mut self) -> &mut Self::Target {
1319 unsafe { &mut *(self as *mut Self).cast() }
1320 }
1321 }