Struct Quat

Source
#[repr(C)]
pub struct Quat { pub x: f32, pub y: f32, pub z: f32, pub w: f32, }
Expand description

Quaternion stored as vector part (x,y,z) followed by scalar part w.

Fields§

§x: f32§y: f32§z: f32§w: f32

Implementations§

Source§

impl Quat

Source

pub const IDENTITY: Quat

Source

pub const NAN: Quat

Source

pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Quat

Source

pub const fn from_array(v: [f32; 4]) -> Quat

Source

pub const fn to_array(self) -> [f32; 4]

Source

pub const fn from_vec4(v: Vec4) -> Quat

Source

pub const fn to_vec4(self) -> Vec4

Source

pub const fn xyz(self) -> Vec3

Source

pub fn from_axis_angle(axis: Vec3, angle: f32) -> Quat

Finite nonzero axes are normalized. A zero axis returns NaNs.

Source

pub fn from_rotation_x(angle: f32) -> Quat

Source

pub fn from_rotation_y(angle: f32) -> Quat

Source

pub fn from_rotation_z(angle: f32) -> Quat

Source

pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Quat

Source

pub fn from_scaled_axis(axis: Vec3) -> Quat

Source

pub fn from_rotation_arc(from: Vec3, to: Vec3) -> Quat

Shortest rotation between two finite nonzero directions.

Source

pub fn to_axis_angle(self) -> (Vec3, f32)

Source

pub fn to_scaled_axis(self) -> Vec3

Source

pub fn try_swing_twist(self, twist_axis: Vec3) -> Option<SwingTwist>

Decomposes into swing * twist about a local-space twist_axis.

Finite nonzero quaternions and axes are normalized internally, including very large and subnormal inputs. Zero or non-finite inputs return None. Projection and angle calculations use f64 intermediates; results are rounded to f32. The operation uses no heap storage or retained state.

The twist angle is the signed shortest angle in [-pi, pi]. Antipodal inputs give the same factors and angle: choose positive w, or at exact w == 0, choose the sign making the first nonzero component in (x,y,z) positive. This also resolves exact twist half-turn ties. Reversing the axis negates the angle (including those ties), retaining the factors. This tie rule is local to this API; existing interpolation is unchanged.

A singular half-turn swing has both scalar part and vector projection onto the axis exactly zero in the wider calculation. It returns SwingTwist::is_singular with identity twist, rather than rejecting a valid rotation. No epsilon cutoff is applied: near this singularity the twist is inherently sensitive to small changes. Trigonometric creation of a nominal half turn may leave a small nonzero scalar component.

use ferravex_math::{Quat, Vec3};
let rotation = Quat::from_rotation_x(0.7) * Quat::from_rotation_z(-0.4);
let parts = rotation.try_swing_twist(Vec3::Z * 5.0).unwrap();
let reconstructed = parts.swing * parts.twist;
assert!(rotation.try_angle_between(reconstructed).unwrap() < 1.0e-6);
assert!((parts.twist_angle + 0.4).abs() < 1.0e-6);
let half_swing = Quat::from_xyzw(1.0, 0.0, 0.0, 0.0);
assert!(half_swing.try_swing_twist(Vec3::Z).unwrap().is_singular);
assert_eq!(rotation.try_swing_twist(Vec3::ZERO), None);
Source

pub fn try_clamp_twist( self, twist_axis: Vec3, min_angle: f32, max_angle: f32, ) -> Option<Quat>

Clamps the signed shortest twist about a local axis, preserving swing.

Bounds are inclusive radians and must be finite with -f32::consts::PI <= min_angle <= max_angle <= f32::consts::PI. They describe an ordinary interval, not a wrapped interval across pi. Invalid bounds, axes or rotations return None, even for a full range. Uses the sign/tie/singularity conventions of Self::try_swing_twist. A singular decomposition uses its conventional zero twist; if zero lies outside the limits, the nearest bound is applied to that swing. Inspect the decomposition first if authoring requires a different policy.

Returns a normalized rotation. If the rounded twist angle already lies within the bounds, returns normalized self without recomposition, preserving its sign. Otherwise returns swing * limited_twist, whose sign need not match self. The rotated axis direction is preserved up to floating-point rounding. Rounding can put the recovered angle outside a bound; its error can be large arbitrarily close to a singular swing, especially when components underflow. Exact idempotence is not guaranteed. There is no iterative solver or state.

This headless pose recipe aims a local Z axis, then limits authored roll without changing the aim direction. A caller can compose the result with its existing parent/bind-pose transform; no game behavior is selected.

use ferravex_math::{Quat, Vec3};
let aim = Quat::from_rotation_arc(Vec3::Z, Vec3::new(0.4, 0.2, 1.0));
let authored_pose = aim * Quat::from_rotation_z(1.2);
let limited_pose = authored_pose.try_clamp_twist(Vec3::Z, -0.3, 0.3).unwrap();
assert!((limited_pose * Vec3::Z).abs_diff_eq(authored_pose * Vec3::Z, 1.0e-6));
let parts = limited_pose.try_swing_twist(Vec3::Z).unwrap();
assert!((parts.twist_angle - 0.3).abs() < 1.0e-6);
assert!(parts.swing.try_angle_between(aim).unwrap() < 1.0e-6);
assert_eq!(authored_pose.try_clamp_twist(Vec3::Z, 0.3, -0.3), None);
Source

pub fn dot(self, rhs: Quat) -> f32

Source

pub fn length_squared(self) -> f32

Source

pub fn length(self) -> f32

Source

pub fn is_finite(self) -> bool

Source

pub fn is_nan(self) -> bool

Source

pub fn is_normalized(self) -> bool

Source

pub fn try_normalize(self) -> Option<Quat>

Source

pub fn normalize(self) -> Quat

Source

pub const fn conjugate(self) -> Quat

Source

pub fn try_inverse(self) -> Option<Quat>

Algebraic inverse, also correct for finite non-unit quaternions.

Source

pub fn inverse(self) -> Quat

Source

pub fn mul_vec3(self, v: Vec3) -> Vec3

Applies a unit quaternion rotation. Non-unit quaternions must be normalized first.

Source

pub fn mul_quat(self, rhs: Quat) -> Quat

Source

pub fn lerp(self, rhs: Quat, t: f32) -> Quat

Source

pub fn slerp(self, rhs: Quat, t: f32) -> Quat

Spherical interpolation follows the shortest rotation and normalizes endpoints.

Source

pub fn angle_between(self, rhs: Quat) -> f32

Source

pub fn try_angle_between(self, rhs: Quat) -> Option<f32>

Returns the shortest angular distance in radians, in [0, pi].

Both inputs are normalized internally. Returns None if either input is zero or has a non-finite component; finite non-unit inputs, including subnormal and very large inputs, are accepted. Antipodal quaternions (q and -q) represent the same orientation and have zero distance.

Unlike Self::angle_between, this uses wider intermediates and chord lengths instead of acos(dot), retaining small angular differences near identical orientations without a fixed small-angle cutoff. The returned distance is still subject to f32 rounding.

use ferravex_math::Quat;
use std::f32::consts::FRAC_PI_2;

let target = Quat::from_rotation_y(FRAC_PI_2);
let distance = Quat::IDENTITY.try_angle_between(target).unwrap();
assert!((distance - FRAC_PI_2).abs() < 1.0e-6);
assert_eq!(target.try_angle_between(-target), Some(0.0));
assert_eq!(Quat::NAN.try_angle_between(target), None);
Source

pub fn try_rotate_towards(self, rhs: Quat, max_angle: f32) -> Option<Quat>

Rotates toward rhs along the shortest arc by at most max_angle radians, without overshooting (subject to floating-point rounding).

Returns a normalized quaternion. Returns None if either endpoint is zero or non-finite, or if max_angle is negative or non-finite. Both endpoints are validated even for a zero step. Finite non-unit endpoints are accepted, as in Self::try_angle_between.

A zero step returns normalized self. Identical and antipodal (q, -q) orientations also return normalized self. Otherwise, rhs is sign-adjusted to the hemisphere of self; a sufficient step returns that normalized target. At an exact half turn (zero endpoint dot product), both directions are equally short and the supplied signs select the arc. Near-identical orientations use spherical interpolation with no fixed small-angle cutoff or premature snap.

max_angle is a per-call angular budget, not an angular speed. For fixed-tick motion, multiply radians per second by the tick duration:

use ferravex_math::Quat;

let target = Quat::from_rotation_y(1.0);
let radians_per_second = 2.0;
let tick_seconds = 1.0 / 60.0;
let step = radians_per_second * tick_seconds;
let next = Quat::IDENTITY.try_rotate_towards(target, step).unwrap();
let moved = Quat::IDENTITY.try_angle_between(next).unwrap();
assert!((moved - step).abs() < 1.0e-6);
assert!(next.is_normalized());
assert_eq!(next.try_rotate_towards(target, -step), None);
Source

pub fn abs_diff_eq(self, rhs: Quat, tolerance: f32) -> bool

Source

pub fn rotate_towards(self, rhs: Quat, max_angle: f32) -> Quat

Trait Implementations§

Source§

impl Add for Quat

Source§

type Output = Quat

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Quat) -> Quat

Performs the + operation. Read more
Source§

impl Clone for Quat

Source§

fn clone(&self) -> Quat

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Quat

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Quat

Source§

fn default() -> Quat

Returns the “default value” for a type. Read more
Source§

impl Div<f32> for Quat

Source§

type Output = Quat

The resulting type after applying the / operator.
Source§

fn div(self, rhs: f32) -> Quat

Performs the / operation. Read more
Source§

impl From<[f32; 4]> for Quat

Source§

fn from(v: [f32; 4]) -> Quat

Converts to this type from the input type.
Source§

impl From<Quat> for Vec4

Source§

fn from(v: Quat) -> Vec4

Converts to this type from the input type.
Source§

impl Mul<Vec3> for Quat

Source§

type Output = Vec3

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Vec3) -> Vec3

Performs the * operation. Read more
Source§

impl Mul<f32> for Quat

Source§

type Output = Quat

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: f32) -> Quat

Performs the * operation. Read more
Source§

impl Mul for Quat

Source§

type Output = Quat

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Quat) -> Quat

Performs the * operation. Read more
Source§

impl MulAssign for Quat

Source§

fn mul_assign(&mut self, rhs: Quat)

Performs the *= operation. Read more
Source§

impl Neg for Quat

Source§

type Output = Quat

The resulting type after applying the - operator.
Source§

fn neg(self) -> Quat

Performs the unary - operation. Read more
Source§

impl PartialEq for Quat

Source§

fn eq(&self, other: &Quat) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Sub for Quat

Source§

type Output = Quat

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Quat) -> Quat

Performs the - operation. Read more
Source§

impl Copy for Quat

Source§

impl StructuralPartialEq for Quat

Auto Trait Implementations§

§

impl Freeze for Quat

§

impl RefUnwindSafe for Quat

§

impl Send for Quat

§

impl Sync for Quat

§

impl Unpin for Quat

§

impl UnwindSafe for Quat

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.