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
use bevy_math_07::{Quat, Vec3};
use bevy_transform_07::prelude::GlobalTransform;

#[cfg(feature = "bevy-transform-07")] // Repeated to appear in the docs
impl From<GlobalTransform> for crate::Transform {
    #[inline]
    fn from(transform: bevy_transform_07::components::GlobalTransform) -> Self {
        Self::from_scale_angle_translation(
            transform.scale.truncate(),
            angle_2d_from_quat(transform.rotation),
            transform.translation.truncate(),
        )
    }
}

fn angle_2d_from_quat(quat: Quat) -> f32 {
    if quat.is_near_identity() {
        return 0.0;
    }
    let projected = quat.to_scaled_axis().project_onto(Vec3::Z);
    let angle = projected.length();
    if projected.z < 0.0 {
        -angle
    } else {
        angle
    }
}

#[cfg(all(test, feature = "std"))]
mod angle_from_quat {
    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case(Quat::from_axis_angle(Vec3::Z, 1.0), 1.0)]
    #[case(Quat::from_axis_angle(- Vec3::Z, 1.0), - 1.0)]
    #[case(Quat::from_axis_angle(Vec3::Z, - 1.0), - 1.0)]
    #[case(Quat::from_axis_angle(- Vec3::Z, - 1.0), 1.0)]
    fn angle_from_quat(#[case] quat: Quat, #[case] expected: f32) {
        assert!((angle_2d_from_quat(quat) - expected).abs() < f32::EPSILON);
    }
}