glam_det 2.0.0

A simple and fast 3D math library for games and graphics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// Copyright (C) 2020-2025 glam-det authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Generated from quat.rs.tera template. Edit the template, not the generated file.

use crate::f32::ffi::{Mat4, Quat, UnitVec3A, UnitVec4, Vec3A, Vec4};
use crate::{
    euler::EulerRot::{self, *},
    FloatEx, Mat3, UnitDQuat, UnitVec2, UnitVec3, Vec3,
};

use crate::nums::*;

use auto_ops_det::{impl_op_ex, impl_op_ex_commutative};
#[cfg(not(target_arch = "spirv"))]
use core::fmt;
use core::iter::Product;
use core::ops::{self, Deref, Neg};

union VecUnionCast {
    v: Quat,
    uv: UnitQuat,
}

impl Quat {
    #[inline]
    pub fn as_unit_quat_unchecked(self) -> UnitQuat {
        unsafe { VecUnionCast { v: self }.uv }
    }
}

impl UnitQuat {
    #[inline]
    pub fn as_quat(self) -> Quat {
        unsafe { VecUnionCast { uv: self }.v }
    }
}

// Copyright (C) 2020-2025 glam-det authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
union UnionCastFfi {
    simd: crate::f32::simd_alias::UnitQuat,
    ffi: UnitQuat,
}

impl From<crate::f32::simd_alias::UnitQuat> for UnitQuat {
    #[inline]
    fn from(simd: crate::f32::simd_alias::UnitQuat) -> Self {
        unsafe { UnionCastFfi { simd }.ffi }
    }
}

impl From<UnitQuat> for crate::f32::simd_alias::UnitQuat {
    #[inline]
    fn from(ffi: UnitQuat) -> Self {
        unsafe { UnionCastFfi { ffi }.simd }
    }
}

impl From<super::C128> for crate::f32::simd_alias::UnitQuat {
    #[inline]
    fn from(t: super::C128) -> Self {
        UnitQuat(t).into()
    }
}

/// A quaternion representing an orientation.
///
/// This quaternion is intended to be of unit length but may denormalize due to
/// floating point "error creep" which can occur when successive quaternion
/// operations are applied.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct UnitQuat(pub(crate) super::C128);

impl UnitQuat {
    /// The identity unit quaternion. Corresponds to no rotation.
    pub const IDENTITY: Self = Self::from_xyzw_unchecked(0.0_f32, 0.0_f32, 0.0_f32, 1.0_f32);

    /// Creates a new rotation quaternion.
    #[inline]
    pub const fn from_xyzw_unchecked(x: f32, y: f32, z: f32, w: f32) -> Self {
        Self(super::C128(x, y, z, w))
    }

    /// Creates a rotation quaternion from an array.
    #[inline]
    pub const fn from_array_unchecked(a: [f32; 4]) -> Self {
        Self::from_xyzw_unchecked(a[0], a[1], a[2], a[3])
    }

    /// Creates a new rotation quaternion from a 4D unit vector.
    #[inline]
    pub fn from_unit_vec4(v: UnitVec4) -> Self {
        let q: Self = crate::f32::simd_alias::UnitQuat::from_unit_vec4(v.into()).into();
        glam_assert!(q.is_normalized(), "{:?} is not normalized.", q);
        q
    }

    /// Creates a rotation quaternion from a slice.
    ///
    /// # Panics
    ///
    /// Panics if `slice` length is less than 4.
    #[inline]
    pub fn from_slice_unchecked(slice: &[f32]) -> Self {
        crate::f32::simd_alias::UnitQuat::from_slice_unchecked(slice).into()
    }

    /// Writes the quaternion to an unaligned slice.
    ///
    /// # Panics
    ///
    /// Panics if `slice` length is less than 4.
    #[inline]
    pub fn write_to_slice(self, slice: &mut [f32]) {
        crate::f32::simd_alias::UnitQuat::write_to_slice(self.into(), slice)
    }

    /// Create a unit quaternion for a unit-length `axis` and `angle` (in radians).
    #[inline]
    pub fn from_axis_angle(axis: UnitVec3, angle: f32) -> Self {
        #[cfg_attr(
            not(any(
                all(debug_assertions, feature = "debug-glam-assert"),
                feature = "glam-assert"
            )),
            allow(clippy::let_and_return)
        )]
        let q = Quat::from_axis_angle(axis, angle).as_unit_quat_unchecked();
        glam_assert!(q.is_normalized(), "{:?} is not normalized.", q);
        q
    }

    /// Create a unit quaternion that rotates `v.length()` radians around `v.normalize()`.
    ///
    /// `from_scaled_axis(Vec3::ZERO)` results in the identity quaternion.
    #[inline]
    pub fn from_scaled_axis(v: Vec3) -> Self {
        #[cfg_attr(
            not(any(
                all(debug_assertions, feature = "debug-glam-assert"),
                feature = "glam-assert"
            )),
            allow(clippy::let_and_return)
        )]
        let q = Quat::from_scaled_axis(v).as_unit_quat_unchecked();
        glam_assert!(q.is_normalized(), "{:?} is not normalized.", q);
        q
    }

    /// Creates a unit quaternion from the `angle` (in radians) around the x axis.
    #[inline]
    pub fn from_rotation_x(angle: f32) -> Self {
        glam_assert!(angle.is_finite(), "angle {:?} is not finite.", angle);
        let (s, c) = (angle * 0.5_f32).sin_cosf();
        Self::from_xyzw_unchecked(s, 0.0_f32, 0.0_f32, c)
    }

    /// Creates a unit quaternion from the `angle` (in radians) around the y axis.
    #[inline]
    pub fn from_rotation_y(angle: f32) -> Self {
        glam_assert!(angle.is_finite(), "angle {:?} is not finite.", angle);
        let (s, c) = (angle * 0.5_f32).sin_cosf();
        Self::from_xyzw_unchecked(0.0_f32, s, 0.0_f32, c)
    }

    /// Creates a unit quaternion from the `angle` (in radians) around the z axis.
    #[inline]
    pub fn from_rotation_z(angle: f32) -> Self {
        glam_assert!(angle.is_finite(), "angle {:?} is not finite.", angle);
        let (s, c) = (angle * 0.5_f32).sin_cosf();
        Self::from_xyzw_unchecked(0.0_f32, 0.0_f32, s, c)
    }

    #[inline]
    /// Creates a unit quaternion from the given Euler rotation sequence and the angles (in radians).
    pub fn from_euler(euler: EulerRot, a: f32, b: f32, c: f32) -> Self {
        let (sa, ca) = (a * 0.5_f32).sin_cosf();
        let (sb, cb) = (b * 0.5_f32).sin_cosf();
        let (sc, cc) = (c * 0.5_f32).sin_cosf();
        match euler {
            ZYX => Self::from_xyzw_unchecked(
                ca * cb * sc - cc * sa * sb,
                ca * cc * sb + cb * sa * sc,
                cb * cc * sa - ca * sb * sc,
                ca * cb * cc + sa * sb * sc,
            ),
            ZXY => Self::from_xyzw_unchecked(
                ca * cc * sb - cb * sa * sc,
                cc * sa * sb + ca * cb * sc,
                cb * cc * sa + ca * sb * sc,
                ca * cb * cc - sa * sb * sc,
            ),
            YXZ => Self::from_xyzw_unchecked(
                ca * cc * sb + cb * sa * sc,
                cb * cc * sa - ca * sb * sc,
                ca * cb * sc - cc * sa * sb,
                ca * cb * cc + sa * sb * sc,
            ),
            YZX => Self::from_xyzw_unchecked(
                cc * sa * sb + ca * cb * sc,
                cb * cc * sa + ca * sb * sc,
                ca * cc * sb - cb * sa * sc,
                ca * cb * cc - sa * sb * sc,
            ),
            XYZ => Self::from_xyzw_unchecked(
                cb * cc * sa + ca * sb * sc,
                ca * cc * sb - cb * sa * sc,
                cc * sa * sb + ca * cb * sc,
                ca * cb * cc - sa * sb * sc,
            ),
            XZY => Self::from_xyzw_unchecked(
                cb * cc * sa - ca * sb * sc,
                ca * cb * sc - cc * sa * sb,
                ca * cc * sb + cb * sa * sc,
                ca * cb * cc + sa * sb * sc,
            ),
            ZYZ => Self::from_xyzw_unchecked(
                ca * sb * sc - cc * sa * sb,
                ca * cc * sb + sa * sb * sc,
                cb * cc * sa + ca * cb * sc,
                ca * cb * cc - cb * sa * sc,
            ),
            ZXZ => Self::from_xyzw_unchecked(
                ca * cc * sb + sa * sb * sc,
                cc * sa * sb - ca * sb * sc,
                cb * cc * sa + ca * cb * sc,
                ca * cb * cc - cb * sa * sc,
            ),
            YXY => Self::from_xyzw_unchecked(
                ca * cc * sb + sa * sb * sc,
                cb * cc * sa + ca * cb * sc,
                ca * sb * sc - cc * sa * sb,
                ca * cb * cc - cb * sa * sc,
            ),
            YZY => Self::from_xyzw_unchecked(
                cc * sa * sb - ca * sb * sc,
                cb * cc * sa + ca * cb * sc,
                ca * cc * sb + sa * sb * sc,
                ca * cb * cc - cb * sa * sc,
            ),
            XYX => Self::from_xyzw_unchecked(
                cb * cc * sa + ca * cb * sc,
                ca * cc * sb + sa * sb * sc,
                cc * sa * sb - ca * sb * sc,
                ca * cb * cc - cb * sa * sc,
            ),
            XZX => Self::from_xyzw_unchecked(
                cb * cc * sa + ca * cb * sc,
                ca * sb * sc - cc * sa * sb,
                ca * cc * sb + sa * sb * sc,
                ca * cb * cc - cb * sa * sc,
            ),
        }
        .renormalize()
    }

    #[inline]
    /// Creates a unit quaternion from the given the angles (in radians).
    /// Default euler rotation sequence is `Z -> Y -> X` as roll (z-axis) -> yaw (y-axis) -> pitch (x-axis).
    /// First apply the z-axis rotation.
    pub fn from_euler_default(a: f32, b: f32, c: f32) -> Self {
        Self::from_euler(EulerRot::default(), a, b, c)
    }

    /// From the columns of a 3x3 rotation matrix.
    #[inline]
    pub(crate) fn from_rotation_axes(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Self {
        #[cfg_attr(
            not(any(
                all(debug_assertions, feature = "debug-glam-assert"),
                feature = "glam-assert"
            )),
            allow(clippy::let_and_return)
        )]
        let q = Quat::from_rotation_axes(x_axis, y_axis, z_axis).as_unit_quat_unchecked();
        glam_assert!(q.is_normalized(), "{:?} is not normalized.", q);
        q
    }

    /// Creates a unit quaternion from a 3x3 rotation matrix.
    #[inline]
    pub fn from_mat3(mat: &Mat3) -> Self {
        Self::from_rotation_axes(mat.x_axis, mat.y_axis, mat.z_axis)
    }

    /// Creates a unit quaternion from a 3x3 rotation matrix inside a homogeneous 4x4 matrix.
    #[inline]
    pub fn from_mat4(mat: &Mat4) -> Self {
        Self::from_rotation_axes(
            mat.x_axis.truncate(),
            mat.y_axis.truncate(),
            mat.z_axis.truncate(),
        )
    }

    /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
    #[inline]
    pub fn from_affine3(a: &crate::Affine3A) -> Self {
        #[allow(clippy::useless_conversion)]
        Self::from_rotation_axes(
            a.matrix3.x_axis.into(),
            a.matrix3.y_axis.into(),
            a.matrix3.z_axis.into(),
        )
    }

    /// Gets the minimal rotation for transforming `from` to `to`.  The rotation is in the
    /// plane spanned by the two vectors.  Will rotate at most 180 degrees.
    #[inline]
    pub fn from_rotation_arc(from: UnitVec3, to: UnitVec3) -> Self {
        #[cfg_attr(
            not(any(
                all(debug_assertions, feature = "debug-glam-assert"),
                feature = "glam-assert"
            )),
            allow(clippy::let_and_return)
        )]
        let q = Quat::from_rotation_arc(from, to).as_unit_quat_unchecked();
        glam_assert!(q.is_normalized(), "{:?} is not normalized.", q);
        q
    }

    /// Gets the minimal rotation for transforming `from` to either `to` or `-to`.  This means
    /// that the resulting quaternion will rotate `from` so that it is colinear with `to`.
    ///
    /// The rotation is in the plane spanned by the two vectors.  Will rotate at most 90
    /// degrees.
    #[inline]
    pub fn from_rotation_arc_colinear(from: UnitVec3, to: UnitVec3) -> Self {
        #[cfg_attr(
            not(any(
                all(debug_assertions, feature = "debug-glam-assert"),
                feature = "glam-assert"
            )),
            allow(clippy::let_and_return)
        )]
        let q = Quat::from_rotation_arc_colinear(from, to).as_unit_quat_unchecked();
        glam_assert!(q.is_normalized(), "{:?} is not normalized.", q);
        q
    }

    /// Gets the minimal rotation for transforming `from` to `to`.  The resulting rotation is
    /// around the z axis. Will rotate at most 180 degrees.
    #[inline]
    pub fn from_rotation_arc_2d(from: UnitVec2, to: UnitVec2) -> Self {
        #[cfg_attr(
            not(any(
                all(debug_assertions, feature = "debug-glam-assert"),
                feature = "glam-assert"
            )),
            allow(clippy::let_and_return)
        )]
        let q = Quat::from_rotation_arc_2d(from, to).as_unit_quat_unchecked();
        glam_assert!(q.is_normalized(), "{:?} is not normalized.", q);
        q
    }

    /// Returns the rotation axis and angle (in radians) of `self`.
    #[inline]
    pub fn to_axis_angle(self) -> (UnitVec3, f32) {
        const EPSILON: f64 = 1.0e-8;
        const EPSILON_SQUARED: f64 = EPSILON * EPSILON;

        let w = self.w;
        let v3 = self.xyz();
        let sin_theta_abs = v3.length();

        let angle_valid = sin_theta_abs > EPSILON_SQUARED as f32;

        let axis0 = v3 * sin_theta_abs.recip();
        let axis1 = Vec3::X;

        let a = if angle_valid { axis0 } else { axis1 };
        let angle = if angle_valid {
            (sin_theta_abs * w.signumf()).atan2f(w.absf()) * 2.0_f32
        } else {
            0.0_f32
        };

        (a.as_unit_vec3_unchecked(), angle)
    }

    /// Returns the rotation axis scaled by the rotation in radians.
    #[inline]
    pub fn to_scaled_axis(self) -> Vec3 {
        let (axis, angle) = self.to_axis_angle();
        axis * angle
    }

    /// Returns the rotation angles for the given euler rotation sequence.
    #[inline]
    pub fn to_euler(self, euler: EulerRot) -> (f32, f32, f32) {
        const PI: f32 = core::f32::consts::PI;
        #[allow(non_snake_case)]
        let TWO_PI: f32 = PI + PI;
        #[allow(clippy::excessive_precision)]
        const SQRT_2: f32 = 1.41421356237309504880168872420969808;

        let not_proper = euler.not_proper();
        let (i, j, k) = euler.map_sequence();
        let levi_civita_sig = euler.levi_civita_sig();
        let q = [self.w, self.x, self.y, self.z];

        let (a, b, c, d) = if not_proper {
            (
                (q[0] - q[j]) / SQRT_2,
                (q[k] * levi_civita_sig + q[i]) / SQRT_2,
                (q[0] + q[j]) / SQRT_2,
                (q[k] * levi_civita_sig - q[i]) / SQRT_2,
            )
        } else {
            (q[0], q[i], q[j], q[k] * levi_civita_sig)
        };

        let cos_theta_2 = 2.0_f32 * (a * a + b * b) - 1.0_f32;
        let theta_positive = b.atan2f(a);
        let theta_negative = -d.atan2f(c);

        let mut theta_1: f32;
        let mut theta_2: f32;
        let mut theta_3: f32;

        if cos_theta_2 + f32::EPSILON >= 1.0 {
            theta_1 = 0.0;
            theta_2 = 0.0;
            theta_3 = 2.0 * theta_positive;
        } else if cos_theta_2 - f32::EPSILON <= -1.0 {
            theta_1 = 0.0;
            theta_2 = PI;
            theta_3 = -2.0 * theta_negative;
        } else {
            theta_1 = theta_positive + theta_negative;
            theta_2 = cos_theta_2.acosf();
            theta_3 = theta_positive - theta_negative;
        };

        if not_proper {
            theta_3 *= levi_civita_sig;
            theta_2 -= PI / 2.0_f32;
        }

        theta_1 %= TWO_PI;
        theta_3 %= TWO_PI;

        if theta_1.absf() >= PI {
            theta_1 -= theta_1.signumf() * TWO_PI;
        }
        if theta_3.absf() >= PI {
            theta_3 -= theta_3.signumf() * TWO_PI;
        }

        (theta_3, theta_2, theta_1)
    }

    #[inline]
    /// Returns the rotation angles for the given euler rotation sequence.
    /// Default euler rotation sequence is `Z -> Y -> X` as roll (z-axis) -> yaw (y-axis) -> pitch (x-axis).
    /// First apply the z-axis rotation.
    pub fn to_euler_default(self) -> (f32, f32, f32) {
        self.to_euler(EulerRot::default())
    }

    /// `[x, y, z, w]`
    #[inline]
    pub fn to_array(&self) -> [f32; 4] {
        [self.x, self.y, self.z, self.w]
    }

    /// Returns the vector part of the quaternion.
    #[inline]
    pub fn xyz(self) -> Vec3 {
        Vec3::new(self.x, self.y, self.z)
    }

    /// Returns the quaternion conjugate of `self`. For a unit quaternion the
    /// conjugate is also the inverse.
    #[must_use]
    #[inline]
    pub fn conjugate(self) -> Self {
        crate::f32::simd_alias::UnitQuat::conjugate(self.into()).into()
    }

    /// Returns the inverse of a unit quaternion.
    #[must_use]
    #[inline]
    pub fn inverse(self) -> Self {
        self.conjugate()
    }

    /// Computes the dot product of `self` and `rhs`.
    /// The dot product is equal to the cosine of the angle between two unit quaternion.
    #[inline]
    pub fn dot(self, rhs: Self) -> f32 {
        Vec4::from(self).dot(Vec4::from(rhs))
    }

    /// Returns whether `self` of length `1.0` or not.
    ///
    /// Uses a precision threshold of `1e-6`.
    #[inline]
    pub fn is_normalized(self) -> bool {
        Vec4::from(self).is_normalized()
    }

    /// Returns `self` normalized to length 1.0.
    /// Unit quaternion may denormalize due to loating point "error creep" which
    /// can occur when successive quaternion operations are applied.
    ///
    /// For valid results, `self` must _not_ be of length zero or infinite.
    ///
    /// Panics
    ///
    /// Will panic if `self` is zero or infinite length when `glam_assert` is enabled.
    #[must_use]
    #[inline]
    pub fn renormalize(self) -> Self {
        Self::from_unit_vec4(Vec4::from(self).normalize_to_unit())
    }

    #[inline]
    pub fn is_near_identity(self) -> bool {
        // Based on https://github.com/nfrechette/rtm `rtm::quat_near_identity`

        let threshold_angle = 0.002_847_144_6;

        // Because of floating point precision, we cannot represent very small rotations.
        // The closest f32 to 1.0 that is not 1.0 itself yields:
        // 0.99999994.acosf() * 2.0  = 0.000690533954 rad
        //
        // An error threshold of 1.e-6 is used by default.
        // (1.0 - 1.e-6).acosf() * 2.0 = 0.00284714461 rad
        // (1.0 - 1.e-7).acosf() * 2.0 = 0.00097656250 rad
        //
        // We don't really care about the angle value itself, only if it's close to 0.
        // This will happen whenever quat.w is close to 1.0.
        // If the quat.w is close to -1.0, the angle will be near 2*PI which is close to
        // a negative 0 rotation. By forcing quat.w to be positive, we'll end up with
        // the shortest path.
        let positive_w_angle = self.w.absf().acos_approx() * 2.0_f32;

        positive_w_angle < threshold_angle
    }

    /// Returns the angle (in radians) for the minimal rotation
    /// for transforming this quaternion into another.
    #[inline]
    pub fn angle_between(self, rhs: Self) -> f32 {
        self.dot(rhs).absf().acos_approx() * 2.0_f32
    }

    /// Returns true if the absolute difference of all elements between `self` and `rhs`
    /// is less than or equal to `max_abs_diff`.
    ///
    /// This can be used to compare if two quaternions contain similar elements. It works
    /// best when comparing with a known value. The `max_abs_diff` that should be used used
    /// depends on the values being compared against.
    ///
    /// For more see
    /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
    #[inline]
    pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
        Vec4::from(self).abs_diff_eq(Vec4::from(rhs), max_abs_diff)
    }

    /// Performs a linear interpolation between `self` and `rhs` based on
    /// the value `s`.
    ///
    /// When `s` is `0.0`, the result will be equal to `self`.  When `s`
    /// is `1.0`, the result will be equal to `rhs`.
    #[inline]
    #[doc(alias = "mix")]
    pub fn lerp(self, end: Self, s: f32) -> Self {
        crate::f32::simd_alias::UnitQuat::lerp(self.into(), end.into(), s).into()
    }

    /// Performs a spherical linear interpolation between `self` and `end`
    /// based on the value `s`.
    ///
    /// When `s` is `0.0`, the result will be equal to `self`.  When `s`
    /// is `1.0`, the result will be equal to `end`.
    #[inline]
    pub fn slerp(self, mut end: Self, s: f32) -> Self {
        // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/

        const DOT_THRESHOLD: f32 = 0.9995;

        // Note that a rotation can be represented by two quaternions: `q` and
        // `-q`. The slerp path between `q` and `end` will be different from the
        // path between `-q` and `end`. One path will take the long way around and
        // one will take the short way. In order to correct for this, the `dot`
        // product between `self` and `end` should be positive. If the `dot`
        // product is negative, slerp between `self` and `-end`.
        let mut dot = self.dot(end);

        if dot < 0.0 {
            end = -end;
            dot = -dot;
        }

        if dot > DOT_THRESHOLD {
            self.lerp(end, s)
        } else {
            crate::f32::simd_alias::UnitQuat::slerp(self.into(), end.into(), s).into()
        }
    }

    /// Multiplies a unit quaternion and a 3D vector, returning the rotated vector.
    #[inline]
    pub fn mul_vec3(self, rhs: Vec3) -> Vec3 {
        self.mul_vec3a(rhs.into()).into()
    }

    /// Multiplies two unit quaternions. If they each represent a rotation, the result will
    /// represent the combined rotation.
    ///
    /// Note that due to floating point rounding the result may not be perfectly normalized.
    #[inline]
    pub fn mul_unit_quat(self, rhs: Self) -> Self {
        crate::f32::simd_alias::UnitQuat::mul_unit_quat(self.into(), rhs.into()).into()
    }

    /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
    #[inline]
    pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
        crate::f32::simd_alias::UnitQuat::mul_vec3a(self.into(), rhs.into()).into()
    }

    #[inline]
    pub fn as_f64(self) -> UnitDQuat {
        UnitDQuat::from_xyzw_unchecked(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
    }
}

#[cfg(not(target_arch = "spirv"))]
impl fmt::Debug for UnitQuat {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_tuple(stringify!(UnitQuat))
            .field(&self.x)
            .field(&self.y)
            .field(&self.z)
            .field(&self.w)
            .finish()
    }
}

#[cfg(not(target_arch = "spirv"))]
impl fmt::Display for UnitQuat {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
    }
}

impl_op_ex!(+ |a: &UnitQuat, b: &UnitQuat| -> Quat{
    Quat::from_vec4(Vec4::from(a) + Vec4::from(b))
});

impl_op_ex!(-|a: &UnitQuat, b: &UnitQuat| -> Quat {
    Quat::from_vec4(Vec4::from(a) - Vec4::from(b))
});

impl_op_ex_commutative!(*|a: &UnitQuat, b: &f32| -> Quat { Quat::from_vec4(Vec4::from(a) * b) });

impl_op_ex!(/ |a: &UnitQuat, b: &f32| -> Quat{
    Quat::from_vec4(Vec4::from(a) / b)
});

impl_op_ex!(*|a: &UnitQuat, b: &UnitQuat| -> UnitQuat { a.mul_unit_quat(*b) });

impl_op_ex!(*= |a: &mut UnitQuat, b: &UnitQuat| {
    *a = a.mul_unit_quat(*b)
});

impl_op_ex!(*|a: &UnitQuat, b: &Quat| -> Quat { a.as_quat().mul_quat(*b) });

impl_op_ex!(*|a: &Quat, b: &UnitQuat| -> Quat { a.mul_quat(b.as_quat()) });

impl_op_ex!(*= |a: &mut Quat, b: &UnitQuat| {
    *a = a.mul_quat(b.as_quat())
});

impl_op_ex!(*|a: &UnitQuat, b: &Vec3| -> Vec3 { a.mul_vec3(*b) });

impl_op_ex!(*|a: &UnitQuat, b: &UnitVec3| -> UnitVec3 {
    a.mul_vec3(b.as_vec3()).as_unit_vec3_unchecked()
});

impl_op_ex!(*|a: &UnitQuat, b: &Vec3A| -> Vec3A { a.mul_vec3a(*b) });

impl_op_ex!(*|a: &UnitQuat, b: &UnitVec3A| -> UnitVec3A {
    (a * b.as_vec3a()).as_unit_vec3a_unchecked()
});

impl Neg for UnitQuat {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self {
        (self * -1.0_f32).as_unit_quat_unchecked()
    }
}

impl Default for UnitQuat {
    #[inline]
    fn default() -> Self {
        Self::IDENTITY
    }
}

impl PartialEq for UnitQuat {
    #[inline]
    fn eq(&self, rhs: &Self) -> bool {
        Vec4::from(*self).eq(&Vec4::from(*rhs))
    }
}

#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f32; 4]> for UnitQuat {
    #[inline]
    fn as_ref(&self) -> &[f32; 4] {
        unsafe { &*(self as *const Self as *const [f32; 4]) }
    }
}

impl<'a> Product<&'a Self> for UnitQuat {
    fn product<I>(iter: I) -> Self
    where
        I: Iterator<Item = &'a Self>,
    {
        iter.fold(Self::IDENTITY, |a, &b| a * b)
    }
}

impl From<UnitQuat> for Vec4 {
    #[inline]
    fn from(q: UnitQuat) -> Self {
        crate::f32::simd_alias::Vec4::from(crate::f32::simd_alias::UnitQuat::from(q)).into()
    }
}

impl From<UnitQuat> for UnitVec4 {
    #[inline]
    fn from(q: UnitQuat) -> Self {
        Vec4::from(q).as_unit_vec4_unchecked()
    }
}

impl From<UnitQuat> for (f32, f32, f32, f32) {
    #[inline]
    fn from(q: UnitQuat) -> Self {
        Self::from(crate::f32::simd_alias::UnitQuat::from(q))
    }
}

impl From<UnitQuat> for [f32; 4] {
    #[inline]
    fn from(q: UnitQuat) -> Self {
        Self::from(crate::f32::simd_alias::UnitQuat::from(q))
    }
}

impl From<&UnitQuat> for Vec4 {
    #[inline]
    fn from(q: &UnitQuat) -> Self {
        crate::f32::simd_alias::Vec4::from(crate::f32::simd_alias::UnitQuat::from(*q)).into()
    }
}

impl From<&UnitQuat> for UnitVec4 {
    #[inline]
    fn from(q: &UnitQuat) -> Self {
        Vec4::from(q).as_unit_vec4_unchecked()
    }
}

impl From<&UnitQuat> for (f32, f32, f32, f32) {
    #[inline]
    fn from(q: &UnitQuat) -> Self {
        Self::from(crate::f32::simd_alias::UnitQuat::from(*q))
    }
}

impl From<&UnitQuat> for [f32; 4] {
    #[inline]
    fn from(q: &UnitQuat) -> Self {
        Self::from(crate::f32::simd_alias::UnitQuat::from(*q))
    }
}

impl Deref for UnitQuat {
    type Target = crate::deref::Vec4<f32>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        unsafe { &*(self as *const Self).cast() }
    }
}