Debian Codegraph @

debian/missing-sources/glam-0.24.2/src/f64/dquat.rs

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