ferravex_math/quaternion.rs
1use crate::{Vec3, Vec4, vec3};
2use std::ops::{Add, Div, Mul, MulAssign, Neg, Sub};
3
4/// Intrinsic Euler rotations: `XYZ(a,b,c)` composes `Rx(a) * Ry(b) * Rz(c)`.
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum EulerRot {
7 XYZ,
8 XZY,
9 YXZ,
10 YZX,
11 ZXY,
12 ZYX,
13}
14
15/// Quaternion stored as vector part `(x,y,z)` followed by scalar part `w`.
16#[repr(C)]
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct Quat {
19 pub x: f32,
20 pub y: f32,
21 pub z: f32,
22 pub w: f32,
23}
24
25/// Checked factorization of a rotation into `swing * twist` (twist acts first).
26///
27/// Both factors are normalized. `twist` rotates about the requested local axis;
28/// `swing` carries that axis to its final direction. Reconstruction agrees with
29/// the normalized input orientation, up to floating-point rounding and sign.
30///
31/// ```
32/// use ferravex_math::{Quat, SwingTwist, Vec3};
33/// let parts: SwingTwist = Quat::from_rotation_y(0.4).try_swing_twist(Vec3::Y).unwrap();
34/// assert!(!parts.is_singular);
35/// assert!(parts.swing.try_angle_between(Quat::IDENTITY).unwrap() < 1.0e-6);
36/// assert!((parts.twist_angle - 0.4).abs() < 1.0e-6);
37/// ```
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub struct SwingTwist {
40 /// Swing factor; applied after [`Self::twist`].
41 pub swing: Quat,
42 /// Twist factor about the normalized authored axis.
43 pub twist: Quat,
44 /// Signed shortest twist in radians, in `[-pi, pi]`.
45 pub twist_angle: f32,
46 /// True for an exact half-turn swing with underdetermined twist.
47 ///
48 /// In that case `twist` is identity, `twist_angle` is zero and `swing`
49 /// retains the entire input rotation. This is a convention, not a measured
50 /// zero twist. Near-singular rotations are not snapped to this convention.
51 pub is_singular: bool,
52}
53
54impl Default for Quat {
55 fn default() -> Self {
56 Self::IDENTITY
57 }
58}
59impl Quat {
60 pub const IDENTITY: Self = Self::from_xyzw(0.0, 0.0, 0.0, 1.0);
61 pub const NAN: Self = Self::from_xyzw(f32::NAN, f32::NAN, f32::NAN, f32::NAN);
62 pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
63 Self { x, y, z, w }
64 }
65 pub const fn from_array(v: [f32; 4]) -> Self {
66 Self::from_xyzw(v[0], v[1], v[2], v[3])
67 }
68 pub const fn to_array(self) -> [f32; 4] {
69 [self.x, self.y, self.z, self.w]
70 }
71 pub const fn from_vec4(v: Vec4) -> Self {
72 Self::from_xyzw(v.x, v.y, v.z, v.w)
73 }
74 pub const fn to_vec4(self) -> Vec4 {
75 Vec4::new(self.x, self.y, self.z, self.w)
76 }
77 pub const fn xyz(self) -> Vec3 {
78 vec3(self.x, self.y, self.z)
79 }
80 /// Finite nonzero axes are normalized. A zero axis returns NaNs.
81 pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
82 let unit = axis.normalize();
83 let (s, c) = (angle * 0.5).sin_cos();
84 Self::from_xyzw(unit.x * s, unit.y * s, unit.z * s, c)
85 }
86 pub fn from_rotation_x(angle: f32) -> Self {
87 let (s, c) = (angle * 0.5).sin_cos();
88 Self::from_xyzw(s, 0.0, 0.0, c)
89 }
90 pub fn from_rotation_y(angle: f32) -> Self {
91 let (s, c) = (angle * 0.5).sin_cos();
92 Self::from_xyzw(0.0, s, 0.0, c)
93 }
94 pub fn from_rotation_z(angle: f32) -> Self {
95 let (s, c) = (angle * 0.5).sin_cos();
96 Self::from_xyzw(0.0, 0.0, s, c)
97 }
98 pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
99 use EulerRot::*;
100 match order {
101 XYZ => Self::from_rotation_x(a) * Self::from_rotation_y(b) * Self::from_rotation_z(c),
102 XZY => Self::from_rotation_x(a) * Self::from_rotation_z(b) * Self::from_rotation_y(c),
103 YXZ => Self::from_rotation_y(a) * Self::from_rotation_x(b) * Self::from_rotation_z(c),
104 YZX => Self::from_rotation_y(a) * Self::from_rotation_z(b) * Self::from_rotation_x(c),
105 ZXY => Self::from_rotation_z(a) * Self::from_rotation_x(b) * Self::from_rotation_y(c),
106 ZYX => Self::from_rotation_z(a) * Self::from_rotation_y(b) * Self::from_rotation_x(c),
107 }
108 }
109 pub fn from_scaled_axis(axis: Vec3) -> Self {
110 if axis == Vec3::ZERO {
111 Self::IDENTITY
112 } else {
113 Self::from_axis_angle(axis, axis.length())
114 }
115 }
116 /// Shortest rotation between two finite nonzero directions.
117 pub fn from_rotation_arc(from: Vec3, to: Vec3) -> Self {
118 let a = from.normalize();
119 let b = to.normalize();
120 let cosine = a.dot(b).clamp(-1.0, 1.0);
121 if cosine > 1.0 - 1.0e-6 {
122 return Self::IDENTITY;
123 }
124 if cosine < -1.0 + 1.0e-6 {
125 return Self::from_axis_angle(a.any_orthonormal_vector(), std::f32::consts::PI);
126 }
127 let cross = a.cross(b);
128 Self::from_xyzw(cross.x, cross.y, cross.z, 1.0 + cosine).normalize()
129 }
130 pub fn to_axis_angle(self) -> (Vec3, f32) {
131 let q = self.normalize();
132 let sine = q.xyz().length();
133 if sine < 1.0e-7 {
134 (Vec3::X, 0.0)
135 } else {
136 (q.xyz() / sine, 2.0 * sine.atan2(q.w))
137 }
138 }
139 pub fn to_scaled_axis(self) -> Vec3 {
140 let (axis, angle) = self.to_axis_angle();
141 axis * angle
142 }
143
144 /// Decomposes into `swing * twist` about a local-space `twist_axis`.
145 ///
146 /// Finite nonzero quaternions and axes are normalized internally, including
147 /// very large and subnormal inputs. Zero or non-finite inputs return `None`.
148 /// Projection and angle calculations use `f64` intermediates; results are
149 /// rounded to `f32`. The operation uses no heap storage or retained state.
150 ///
151 /// The twist angle is the signed shortest angle in `[-pi, pi]`. Antipodal
152 /// inputs give the same factors and angle: choose positive `w`, or at exact
153 /// `w == 0`, choose the sign making the first nonzero component in `(x,y,z)`
154 /// positive. This also resolves exact twist half-turn ties. Reversing the
155 /// axis negates the angle (including those ties), retaining the factors.
156 /// This tie rule is local to this API; existing interpolation is unchanged.
157 ///
158 /// A singular half-turn swing has both scalar part and vector projection
159 /// onto the axis exactly zero in the wider calculation. It returns
160 /// [`SwingTwist::is_singular`] with identity twist, rather than rejecting a
161 /// valid rotation. No epsilon cutoff is applied: near this singularity the
162 /// twist is inherently sensitive to small changes. Trigonometric creation
163 /// of a nominal half turn may leave a small nonzero scalar component.
164 ///
165 /// ```
166 /// use ferravex_math::{Quat, Vec3};
167 /// let rotation = Quat::from_rotation_x(0.7) * Quat::from_rotation_z(-0.4);
168 /// let parts = rotation.try_swing_twist(Vec3::Z * 5.0).unwrap();
169 /// let reconstructed = parts.swing * parts.twist;
170 /// assert!(rotation.try_angle_between(reconstructed).unwrap() < 1.0e-6);
171 /// assert!((parts.twist_angle + 0.4).abs() < 1.0e-6);
172 /// let half_swing = Quat::from_xyzw(1.0, 0.0, 0.0, 0.0);
173 /// assert!(half_swing.try_swing_twist(Vec3::Z).unwrap().is_singular);
174 /// assert_eq!(rotation.try_swing_twist(Vec3::ZERO), None);
175 /// ```
176 pub fn try_swing_twist(self, twist_axis: Vec3) -> Option<SwingTwist> {
177 let mut q = self.try_normalized_components()?;
178 let axis = twist_axis.to_array().map(f64::from);
179 let axis_length = axis.iter().map(|v| v * v).sum::<f64>().sqrt();
180 if axis_length == 0.0 || !axis_length.is_finite() {
181 return None;
182 }
183 let axis = axis.map(|v| v / axis_length);
184 if [q[3], q[0], q[1], q[2]].into_iter().find(|v| *v != 0.0)? < 0.0 {
185 q = q.map(|v| -v);
186 }
187 let rotation = Self::from_array(q.map(|v| v as f32));
188 let projection = axis.iter().zip(q).map(|(a, v)| a * v).sum::<f64>();
189 let length = projection.hypot(q[3]);
190 if length == 0.0 {
191 return Some(SwingTwist {
192 swing: rotation,
193 twist: Self::IDENTITY,
194 twist_angle: 0.0,
195 is_singular: true,
196 });
197 }
198 let twist = Self::from_xyzw(
199 (axis[0] * projection / length) as f32,
200 (axis[1] * projection / length) as f32,
201 (axis[2] * projection / length) as f32,
202 (q[3] / length) as f32,
203 );
204 Some(SwingTwist {
205 swing: (rotation * twist.conjugate()).normalize(),
206 twist,
207 twist_angle: (2.0 * projection.atan2(q[3])) as f32,
208 is_singular: false,
209 })
210 }
211
212 /// Clamps the signed shortest twist about a local axis, preserving swing.
213 ///
214 /// Bounds are inclusive radians and must be finite with
215 /// `-f32::consts::PI <= min_angle <= max_angle <= f32::consts::PI`.
216 /// They describe an ordinary interval, not a wrapped interval across pi.
217 /// Invalid bounds, axes or rotations return `None`, even for a full range.
218 /// Uses the sign/tie/singularity conventions of [`Self::try_swing_twist`].
219 /// A singular decomposition uses its conventional zero twist; if zero lies
220 /// outside the limits, the nearest bound is applied to that swing. Inspect
221 /// the decomposition first if authoring requires a different policy.
222 ///
223 /// Returns a normalized rotation. If the rounded twist angle already lies
224 /// within the bounds, returns normalized `self` without recomposition,
225 /// preserving its sign. Otherwise returns `swing * limited_twist`, whose
226 /// sign need not match `self`. The rotated axis direction is preserved up
227 /// to floating-point rounding. Rounding can put the recovered angle outside
228 /// a bound; its error can be large arbitrarily close to a singular swing,
229 /// especially when components underflow. Exact idempotence is not guaranteed.
230 /// There is no iterative solver or state.
231 ///
232 /// This headless pose recipe aims a local Z axis, then limits authored roll
233 /// without changing the aim direction. A caller can compose the result with
234 /// its existing parent/bind-pose transform; no game behavior is selected.
235 ///
236 /// ```
237 /// use ferravex_math::{Quat, Vec3};
238 /// let aim = Quat::from_rotation_arc(Vec3::Z, Vec3::new(0.4, 0.2, 1.0));
239 /// let authored_pose = aim * Quat::from_rotation_z(1.2);
240 /// let limited_pose = authored_pose.try_clamp_twist(Vec3::Z, -0.3, 0.3).unwrap();
241 /// assert!((limited_pose * Vec3::Z).abs_diff_eq(authored_pose * Vec3::Z, 1.0e-6));
242 /// let parts = limited_pose.try_swing_twist(Vec3::Z).unwrap();
243 /// assert!((parts.twist_angle - 0.3).abs() < 1.0e-6);
244 /// assert!(parts.swing.try_angle_between(aim).unwrap() < 1.0e-6);
245 /// assert_eq!(authored_pose.try_clamp_twist(Vec3::Z, 0.3, -0.3), None);
246 /// ```
247 pub fn try_clamp_twist(self, twist_axis: Vec3, min_angle: f32, max_angle: f32) -> Option<Self> {
248 let pi = std::f32::consts::PI;
249 if !min_angle.is_finite()
250 || !max_angle.is_finite()
251 || min_angle < -pi
252 || max_angle > pi
253 || min_angle > max_angle
254 {
255 return None;
256 }
257 let parts = self.try_swing_twist(twist_axis)?;
258 let angle = parts.twist_angle.clamp(min_angle, max_angle);
259 if angle == parts.twist_angle {
260 return self.try_normalize();
261 }
262 // Apply only the twist correction. Algebraically this is swing times
263 // the limited twist, but avoids rounding swing again on small repeated
264 // boundary corrections. Right multiplication keeps the local axis fixed.
265 (self.try_normalize()? * Self::from_axis_angle(twist_axis, angle - parts.twist_angle))
266 .try_normalize()
267 }
268 pub fn dot(self, rhs: Self) -> f32 {
269 self.to_vec4().dot(rhs.to_vec4())
270 }
271 pub fn length_squared(self) -> f32 {
272 self.dot(self)
273 }
274 pub fn length(self) -> f32 {
275 self.to_vec4().length()
276 }
277 pub fn is_finite(self) -> bool {
278 self.to_vec4().is_finite()
279 }
280 pub fn is_nan(self) -> bool {
281 self.to_vec4().is_nan()
282 }
283 pub fn is_normalized(self) -> bool {
284 self.to_vec4().is_normalized()
285 }
286 pub fn try_normalize(self) -> Option<Self> {
287 self.to_vec4().try_normalize().map(Self::from_vec4)
288 }
289 pub fn normalize(self) -> Self {
290 self.try_normalize().unwrap_or(Self::NAN)
291 }
292 pub const fn conjugate(self) -> Self {
293 Self::from_xyzw(-self.x, -self.y, -self.z, self.w)
294 }
295 /// Algebraic inverse, also correct for finite non-unit quaternions.
296 pub fn try_inverse(self) -> Option<Self> {
297 let a = self.to_array();
298 let norm = a.iter().map(|x| f64::from(*x).powi(2)).sum::<f64>();
299 if norm == 0.0 || !norm.is_finite() {
300 return None;
301 }
302 let result = Self::from_array(
303 self.conjugate()
304 .to_array()
305 .map(|x| (f64::from(x) / norm) as f32),
306 );
307 result.is_finite().then_some(result)
308 }
309 pub fn inverse(self) -> Self {
310 self.try_inverse().unwrap_or(Self::NAN)
311 }
312 /// Applies a unit quaternion rotation. Non-unit quaternions must be normalized first.
313 pub fn mul_vec3(self, v: Vec3) -> Vec3 {
314 let t = 2.0 * self.xyz().cross(v);
315 v + self.w * t + self.xyz().cross(t)
316 }
317 pub fn mul_quat(self, rhs: Self) -> Self {
318 self * rhs
319 }
320 pub fn lerp(self, rhs: Self, t: f32) -> Self {
321 let rhs = if self.dot(rhs) < 0.0 { -rhs } else { rhs };
322 (self * (1.0 - t) + rhs * t).normalize()
323 }
324 /// Spherical interpolation follows the shortest rotation and normalizes endpoints.
325 pub fn slerp(self, rhs: Self, t: f32) -> Self {
326 let a = self.normalize();
327 let mut b = rhs.normalize();
328 let mut cosine = a.dot(b);
329 if cosine < 0.0 {
330 b = -b;
331 cosine = -cosine;
332 }
333 if cosine > 0.9995 {
334 return a.lerp(b, t);
335 }
336 let angle = cosine.clamp(-1.0, 1.0).acos();
337 let divisor = angle.sin();
338 (a * ((1.0 - t) * angle).sin() / divisor + b * (t * angle).sin() / divisor).normalize()
339 }
340 pub fn angle_between(self, rhs: Self) -> f32 {
341 2.0 * self
342 .normalize()
343 .dot(rhs.normalize())
344 .abs()
345 .clamp(0.0, 1.0)
346 .acos()
347 }
348 /// Returns the shortest angular distance in **radians**, in `[0, pi]`.
349 ///
350 /// Both inputs are normalized internally. Returns `None` if either input
351 /// is zero or has a non-finite component; finite non-unit inputs, including
352 /// subnormal and very large inputs, are accepted. Antipodal quaternions
353 /// (`q` and `-q`) represent the same orientation and have zero distance.
354 ///
355 /// Unlike [`Self::angle_between`], this uses wider intermediates and chord
356 /// lengths instead of `acos(dot)`, retaining small angular differences near
357 /// identical orientations without a fixed small-angle cutoff. The returned
358 /// distance is still subject to `f32` rounding.
359 ///
360 /// ```
361 /// use ferravex_math::Quat;
362 /// use std::f32::consts::FRAC_PI_2;
363 ///
364 /// let target = Quat::from_rotation_y(FRAC_PI_2);
365 /// let distance = Quat::IDENTITY.try_angle_between(target).unwrap();
366 /// assert!((distance - FRAC_PI_2).abs() < 1.0e-6);
367 /// assert_eq!(target.try_angle_between(-target), Some(0.0));
368 /// assert_eq!(Quat::NAN.try_angle_between(target), None);
369 /// ```
370 pub fn try_angle_between(self, rhs: Self) -> Option<f32> {
371 let (_, _, half_angle) = self.try_shortest_arc(rhs)?;
372 Some((2.0 * half_angle) as f32)
373 }
374
375 /// Rotates toward `rhs` along the shortest arc by at most `max_angle`
376 /// **radians**, without overshooting (subject to floating-point rounding).
377 ///
378 /// Returns a normalized quaternion. Returns `None` if either endpoint is
379 /// zero or non-finite, or if `max_angle` is negative or non-finite. Both
380 /// endpoints are validated even for a zero step. Finite non-unit endpoints
381 /// are accepted, as in [`Self::try_angle_between`].
382 ///
383 /// A zero step returns normalized `self`. Identical and antipodal (`q`,
384 /// `-q`) orientations also return normalized `self`. Otherwise, `rhs` is
385 /// sign-adjusted to the hemisphere of `self`; a sufficient step returns
386 /// that normalized target. At an exact half turn (zero endpoint dot
387 /// product), both directions are equally short and the supplied signs
388 /// select the arc. Near-identical orientations use spherical interpolation
389 /// with no fixed small-angle cutoff or premature snap.
390 ///
391 /// `max_angle` is a per-call angular budget, not an angular speed. For
392 /// fixed-tick motion, multiply radians per second by the tick duration:
393 ///
394 /// ```
395 /// use ferravex_math::Quat;
396 ///
397 /// let target = Quat::from_rotation_y(1.0);
398 /// let radians_per_second = 2.0;
399 /// let tick_seconds = 1.0 / 60.0;
400 /// let step = radians_per_second * tick_seconds;
401 /// let next = Quat::IDENTITY.try_rotate_towards(target, step).unwrap();
402 /// let moved = Quat::IDENTITY.try_angle_between(next).unwrap();
403 /// assert!((moved - step).abs() < 1.0e-6);
404 /// assert!(next.is_normalized());
405 /// assert_eq!(next.try_rotate_towards(target, -step), None);
406 /// ```
407 pub fn try_rotate_towards(self, rhs: Self, max_angle: f32) -> Option<Self> {
408 if !max_angle.is_finite() || max_angle < 0.0 {
409 return None;
410 }
411 let (a, b, half_angle) = self.try_shortest_arc(rhs)?;
412 if max_angle == 0.0 || half_angle == 0.0 {
413 return Some(Self::from_array(a.map(|v| v as f32)));
414 }
415 let step = f64::from(max_angle) * 0.5;
416 if step >= half_angle {
417 return Some(Self::from_array(b.map(|v| v as f32)));
418 }
419 let divisor = half_angle.sin();
420 let from_weight = (half_angle - step).sin() / divisor;
421 let to_weight = step.sin() / divisor;
422 Self::from_array(std::array::from_fn(|i| {
423 (a[i] * from_weight + b[i] * to_weight) as f32
424 }))
425 .try_normalize()
426 }
427
428 // Keep normalized components in f64 through distance and interpolation:
429 // rounding them to f32 first can erase a small, representable rotation.
430 fn try_shortest_arc(self, rhs: Self) -> Option<([f64; 4], [f64; 4], f64)> {
431 let a = self.try_normalized_components()?;
432 let mut b = rhs.try_normalized_components()?;
433 if a.iter().zip(b).map(|(a, b)| a * b).sum::<f64>() < 0.0 {
434 b = b.map(|v| -v);
435 }
436 let difference = a
437 .iter()
438 .zip(b)
439 .map(|(a, b)| (a - b).powi(2))
440 .sum::<f64>()
441 .sqrt();
442 let sum = a
443 .iter()
444 .zip(b)
445 .map(|(a, b)| (a + b).powi(2))
446 .sum::<f64>()
447 .sqrt();
448 // Unit quaternion chord ratio is tan(physical rotation angle / 4).
449 let half_angle = (2.0 * difference.atan2(sum)).min(std::f64::consts::FRAC_PI_2);
450 Some((a, b, half_angle))
451 }
452
453 fn try_normalized_components(self) -> Option<[f64; 4]> {
454 let values = self.to_array().map(f64::from);
455 let length = values.iter().map(|v| v * v).sum::<f64>().sqrt();
456 if length > 0.0 && length.is_finite() {
457 Some(values.map(|v| v / length))
458 } else {
459 None
460 }
461 }
462
463 pub fn abs_diff_eq(self, rhs: Self, tolerance: f32) -> bool {
464 self.to_vec4().abs_diff_eq(rhs.to_vec4(), tolerance)
465 }
466 pub fn rotate_towards(self, rhs: Self, max_angle: f32) -> Self {
467 assert!(max_angle.is_finite() && max_angle >= 0.0);
468 let angle = self.angle_between(rhs);
469 if angle <= max_angle {
470 rhs.normalize()
471 } else {
472 self.slerp(rhs, max_angle / angle)
473 }
474 }
475}
476impl From<[f32; 4]> for Quat {
477 fn from(v: [f32; 4]) -> Self {
478 Self::from_array(v)
479 }
480}
481impl From<Quat> for [f32; 4] {
482 fn from(v: Quat) -> Self {
483 v.to_array()
484 }
485}
486impl From<Quat> for Vec4 {
487 fn from(v: Quat) -> Self {
488 v.to_vec4()
489 }
490}
491impl Neg for Quat {
492 type Output = Self;
493 fn neg(self) -> Self {
494 Self::from_vec4(-self.to_vec4())
495 }
496}
497impl Add for Quat {
498 type Output = Self;
499 fn add(self, rhs: Self) -> Self {
500 Self::from_vec4(self.to_vec4() + rhs.to_vec4())
501 }
502}
503impl Sub for Quat {
504 type Output = Self;
505 fn sub(self, rhs: Self) -> Self {
506 Self::from_vec4(self.to_vec4() - rhs.to_vec4())
507 }
508}
509impl Mul<f32> for Quat {
510 type Output = Self;
511 fn mul(self, rhs: f32) -> Self {
512 Self::from_vec4(self.to_vec4() * rhs)
513 }
514}
515impl Mul<Quat> for f32 {
516 type Output = Quat;
517 fn mul(self, rhs: Quat) -> Quat {
518 rhs * self
519 }
520}
521impl Div<f32> for Quat {
522 type Output = Self;
523 fn div(self, rhs: f32) -> Self {
524 Self::from_vec4(self.to_vec4() / rhs)
525 }
526}
527impl Mul for Quat {
528 type Output = Self;
529 fn mul(self, rhs: Self) -> Self {
530 let vector = self.w * rhs.xyz() + rhs.w * self.xyz() + self.xyz().cross(rhs.xyz());
531 Self::from_xyzw(
532 vector.x,
533 vector.y,
534 vector.z,
535 self.w * rhs.w - self.xyz().dot(rhs.xyz()),
536 )
537 }
538}
539impl Mul<Vec3> for Quat {
540 type Output = Vec3;
541 fn mul(self, rhs: Vec3) -> Vec3 {
542 self.mul_vec3(rhs)
543 }
544}
545impl MulAssign for Quat {
546 fn mul_assign(&mut self, rhs: Self) {
547 *self = *self * rhs;
548 }
549}