Skip to main content

ty_math/
ty_quaternion.rs

1/// A quaternion `(x, y, z, w)` generic over its component type `T`.
2///
3/// See `TyQuaternionF32` and `TyQuaternionF64` for the common instantiations.
4#[derive(Clone, Copy, Debug, PartialEq)]
5pub struct TyQuaternion<T> {
6    /// The `x` component.
7    pub x: T,
8
9    /// The `y` component.
10    pub y: T,
11
12    /// The `z` component.
13    pub z: T,
14
15    /// The `w` (scalar) component.
16    pub w: T,
17}
18
19impl<T> TyQuaternion<T> {
20    /// Creates a new quaternion from `x`, `y`, `z`, and `w` components.
21    pub fn new(x: T, y: T, z: T, w: T) -> Self {
22        Self { x, y, z, w }
23    }
24}
25
26/// Implements the float-only quaternion operations (the identity and its
27/// [`Default`]) for a concrete floating-point component type.
28macro_rules! impl_ty_quaternion_float {
29    ($t:ty) => {
30        impl TyQuaternion<$t> {
31            /// Returns the identity quaternion `(0, 0, 0, 1)`.
32            pub fn identity() -> Self {
33                Self {
34                    x: 0.0,
35                    y: 0.0,
36                    z: 0.0,
37                    w: 1.0,
38                }
39            }
40        }
41
42        impl Default for TyQuaternion<$t> {
43            fn default() -> Self {
44                Self::identity()
45            }
46        }
47    };
48}
49
50impl_ty_quaternion_float!(f32);
51impl_ty_quaternion_float!(f64);