Skip to main content

lib_jsl_geometry/algorithms/
quaternions.rs

1//! Unit quaternions for representing and composing 3D rotations.
2//!
3//! A [`Quaternion`] `w + xi + yj + zk` with unit norm encodes a rotation by an angle θ about a unit
4//! axis `n` as `cos(θ/2) + sin(θ/2) (n_x i + n_y j + n_z k)`. Composition is the Hamilton product,
5//! and `q` and `-q` describe the same rotation. Arithmetic is in `f64`.
6//!
7//! See the book entry [Rotations, Euler angles and quaternions](https://jwkunz.github.io/lib_jsl/book/geometry/rotations.html#quaternions).
8
9use crate::three_d::{CoordinateVector3D, FreeVector3D};
10use std::ops::{Add, Div, Mul, Neg, Sub};
11
12/// A quaternion `w + xi + yj + zk` (scalar part first).
13#[derive(Debug, Clone, Copy, PartialEq)]
14
15pub struct Quaternion {
16    pub w: f64,
17    pub x: f64,
18    pub y: f64,
19    pub z: f64,
20}
21
22impl Quaternion {
23    pub const fn new(w: f64, x: f64, y: f64, z: f64) -> Self {
24        Quaternion { w, x, y, z }
25    }
26
27    /// The multiplicative identity, i.e. no rotation.
28    pub const fn identity() -> Self {
29        Quaternion::new(1.0, 0.0, 0.0, 0.0)
30    }
31
32    /// A pure quaternion (zero scalar part) holding a vector.
33    pub const fn from_vector(v: [f64; 3]) -> Self {
34        Quaternion::new(0.0, v[0], v[1], v[2])
35    }
36
37    /// The vector (imaginary) part.
38    pub const fn vector_part(&self) -> [f64; 3] {
39        [self.x, self.y, self.z]
40    }
41
42    /// Rotation by `angle` radians about `axis` (which need not be normalised; a zero axis gives the
43    /// identity).
44    pub fn from_axis_angle(axis: [f64; 3], angle: f64) -> Self {
45        let n = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
46        if n == 0.0 {
47            return Self::identity();
48        }
49        let (s, c) = (0.5 * angle).sin_cos();
50        Quaternion::new(c, s * axis[0] / n, s * axis[1] / n, s * axis[2] / n)
51    }
52
53    /// The axis and angle in `[0, π]` of a (unit) rotation quaternion; the axis is `[1, 0, 0]` for
54    /// the identity, where it is arbitrary.
55    pub fn to_axis_angle(&self) -> ([f64; 3], f64) {
56        let q = if self.w < 0.0 { -*self } else { *self }.normalized();
57        let s = (q.x * q.x + q.y * q.y + q.z * q.z).sqrt();
58        if s < 1e-15 {
59            return ([1.0, 0.0, 0.0], 0.0);
60        }
61        ([q.x / s, q.y / s, q.z / s], 2.0 * s.atan2(q.w))
62    }
63
64    /// Rotation from intrinsic Z-Y-X (yaw, pitch, roll) Euler angles in radians: first yaw about
65    /// Z, then pitch about the new Y, then roll about the new X.
66    pub fn from_euler(roll: f64, pitch: f64, yaw: f64) -> Self {
67        let (sr, cr) = (0.5 * roll).sin_cos();
68        let (sp, cp) = (0.5 * pitch).sin_cos();
69        let (sy, cy) = (0.5 * yaw).sin_cos();
70        Quaternion::new(
71            cr * cp * cy + sr * sp * sy,
72            sr * cp * cy - cr * sp * sy,
73            cr * sp * cy + sr * cp * sy,
74            cr * cp * sy - sr * sp * cy,
75        )
76    }
77
78    /// `(roll, pitch, yaw)` for the Z-Y-X convention of [`Quaternion::from_euler`]; pitch is in
79    /// `[-π/2, π/2]` (at the ±90° gimbal lock yaw is taken as zero).
80    pub fn to_euler(&self) -> (f64, f64, f64) {
81        let q = self.normalized();
82        let sinp = 2.0 * (q.w * q.y - q.z * q.x);
83        if sinp.abs() >= 1.0 - 1e-12 {
84            let pitch = std::f64::consts::FRAC_PI_2.copysign(sinp);
85            // Here q = ±cos(π/4)(cos(r/2), sin(r/2), ±cos(r/2), ∓sin(r/2)) for the roll r that
86            // goes with zero yaw, whichever the sign of the pitch.
87            let roll = 2.0 * q.x.atan2(q.w);
88            let roll = if roll > std::f64::consts::PI { roll - std::f64::consts::TAU } else if roll <= -std::f64::consts::PI { roll + std::f64::consts::TAU } else { roll };
89            return (roll, pitch, 0.0);
90        }
91        let roll = (2.0 * (q.w * q.x + q.y * q.z)).atan2(1.0 - 2.0 * (q.x * q.x + q.y * q.y));
92        let yaw = (2.0 * (q.w * q.z + q.x * q.y)).atan2(1.0 - 2.0 * (q.y * q.y + q.z * q.z));
93        (roll, sinp.asin(), yaw)
94    }
95
96    /// The 3×3 rotation matrix (row-major) of the normalised quaternion.
97    pub fn to_rotation_matrix(&self) -> [[f64; 3]; 3] {
98        let q = self.normalized();
99        let (w, x, y, z) = (q.w, q.x, q.y, q.z);
100        [
101            [1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - w * z), 2.0 * (x * z + w * y)],
102            [2.0 * (x * y + w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - w * x)],
103            [2.0 * (x * z - w * y), 2.0 * (y * z + w * x), 1.0 - 2.0 * (x * x + y * y)],
104        ]
105    }
106
107    /// The quaternion (with `w >= 0`) of a proper rotation matrix, by Shepperd's method, which is
108    /// numerically stable for every rotation.
109    pub fn from_rotation_matrix(m: &[[f64; 3]; 3]) -> Self {
110        let trace = m[0][0] + m[1][1] + m[2][2];
111        let q = if trace > 0.0 {
112            let s = 2.0 * (trace + 1.0).sqrt();
113            Quaternion::new(0.25 * s, (m[2][1] - m[1][2]) / s, (m[0][2] - m[2][0]) / s, (m[1][0] - m[0][1]) / s)
114        } else if m[0][0] > m[1][1] && m[0][0] > m[2][2] {
115            let s = 2.0 * (1.0 + m[0][0] - m[1][1] - m[2][2]).sqrt();
116            Quaternion::new((m[2][1] - m[1][2]) / s, 0.25 * s, (m[0][1] + m[1][0]) / s, (m[0][2] + m[2][0]) / s)
117        } else if m[1][1] > m[2][2] {
118            let s = 2.0 * (1.0 + m[1][1] - m[0][0] - m[2][2]).sqrt();
119            Quaternion::new((m[0][2] - m[2][0]) / s, (m[0][1] + m[1][0]) / s, 0.25 * s, (m[1][2] + m[2][1]) / s)
120        } else {
121            let s = 2.0 * (1.0 + m[2][2] - m[0][0] - m[1][1]).sqrt();
122            Quaternion::new((m[1][0] - m[0][1]) / s, (m[0][2] + m[2][0]) / s, (m[1][2] + m[2][1]) / s, 0.25 * s)
123        };
124        if q.w < 0.0 { -q } else { q }
125    }
126
127    /// The shortest rotation taking direction `from` onto direction `to` (neither need be unit).
128    /// Returns the identity if either is zero.
129    pub fn from_two_vectors(from: [f64; 3], to: [f64; 3]) -> Self {
130        let (nf, nt) = (norm3(from), norm3(to));
131        if nf == 0.0 || nt == 0.0 {
132            return Self::identity();
133        }
134        let (a, b) = (scale3(from, 1.0 / nf), scale3(to, 1.0 / nt));
135        let d = dot3(a, b);
136        if d < -1.0 + 1e-12 {
137            // Opposite directions: rotate half a turn about any axis perpendicular to `a`.
138            let helper = if a[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] };
139            return Self::from_axis_angle(cross3(a, helper), std::f64::consts::PI);
140        }
141        let c = cross3(a, b);
142        Quaternion::new(1.0 + d, c[0], c[1], c[2]).normalized()
143    }
144
145    pub fn norm_squared(&self) -> f64 {
146        self.w * self.w + self.x * self.x + self.y * self.y + self.z * self.z
147    }
148
149    pub fn norm(&self) -> f64 {
150        self.norm_squared().sqrt()
151    }
152
153    /// Scaled to unit length; the identity if the norm is zero.
154    pub fn normalized(&self) -> Self {
155        let n = self.norm();
156        if n == 0.0 { Self::identity() } else { *self / n }
157    }
158
159    pub fn conjugate(&self) -> Self {
160        Quaternion::new(self.w, -self.x, -self.y, -self.z)
161    }
162
163    /// The multiplicative inverse `q* / |q|²`; `None` for the zero quaternion.
164    pub fn inverse(&self) -> Option<Self> {
165        let n2 = self.norm_squared();
166        (n2 > 0.0).then(|| self.conjugate() / n2)
167    }
168
169    pub fn dot(&self, other: &Self) -> f64 {
170        self.w * other.w + self.x * other.x + self.y * other.y + self.z * other.z
171    }
172
173    /// Rotates `v` by this (normalised) quaternion: `q v q*`.
174    pub fn rotate_vector(&self, v: [f64; 3]) -> [f64; 3] {
175        let q = self.normalized();
176        let u = [q.x, q.y, q.z];
177        // v' = v + 2 w (u × v) + 2 u × (u × v)
178        let t = scale3(cross3(u, v), 2.0);
179        let c = cross3(u, t);
180        [v[0] + q.w * t[0] + c[0], v[1] + q.w * t[1] + c[1], v[2] + q.w * t[2] + c[2]]
181    }
182
183    /// Rotates a [`FreeVector3D`] (computed in `f64`, stored back as `f32`).
184    pub fn rotate_free_vector(&self, v: &FreeVector3D) -> FreeVector3D {
185        let r = self.rotate_vector(v.cartesian_components().map(f64::from));
186        FreeVector3D::new(r[0] as f32, r[1] as f32, r[2] as f32)
187    }
188
189    /// Rotates a point about the origin.
190    pub fn rotate_point(&self, p: &CoordinateVector3D) -> CoordinateVector3D {
191        let r = self.rotate_vector([p.x() as f64, p.y() as f64, p.z() as f64]);
192        CoordinateVector3D::new(r[0] as f32, r[1] as f32, r[2] as f32)
193    }
194
195    /// The quaternion exponential.
196    pub fn exp(&self) -> Self {
197        let v = norm3(self.vector_part());
198        let e = self.w.exp();
199        if v < 1e-300 {
200            return Quaternion::new(e, 0.0, 0.0, 0.0);
201        }
202        let s = e * v.sin() / v;
203        Quaternion::new(e * v.cos(), s * self.x, s * self.y, s * self.z)
204    }
205
206    /// The principal logarithm (zero quaternion has no logarithm: returns `-∞` scalar).
207    pub fn ln(&self) -> Self {
208        let n = self.norm();
209        let v = norm3(self.vector_part());
210        if v < 1e-300 {
211            return Quaternion::new(n.ln(), 0.0, 0.0, 0.0);
212        }
213        let k = (self.w / n).acos() / v;
214        Quaternion::new(n.ln(), k * self.x, k * self.y, k * self.z)
215    }
216
217    /// Real power `q^t` through `exp(t ln q)`; for a unit rotation this scales the angle by `t`.
218    pub fn powf(&self, t: f64) -> Self {
219        (self.ln() * t).exp()
220    }
221
222    /// Spherical linear interpolation along the shortest arc from `self` (t = 0) to `other` (t = 1),
223    /// for unit quaternions. Constant angular velocity.
224    // ANCHOR: slerp
225    pub fn slerp(&self, other: &Self, t: f64) -> Self {
226        let mut b = *other;
227        let mut d = self.dot(&b);
228        if d < 0.0 {
229            b = -b;
230            d = -d;
231        }
232        if d > 1.0 - 1e-10 {
233            return self.nlerp(&b, t);
234        }
235        let theta = d.acos();
236        let s = theta.sin();
237        (*self * (((1.0 - t) * theta).sin() / s) + b * ((t * theta).sin() / s)).normalized()
238    }
239    // ANCHOR_END: slerp
240
241    /// Normalised linear interpolation: cheaper than [`Quaternion::slerp`], not constant-speed.
242    pub fn nlerp(&self, other: &Self, t: f64) -> Self {
243        let b = if self.dot(other) < 0.0 { -*other } else { *other };
244        (*self * (1.0 - t) + b * t).normalized()
245    }
246
247    /// The angle in radians (0 to π) of the rotation taking `self` to `other`.
248    pub fn angle_to(&self, other: &Self) -> f64 {
249        2.0 * self.normalized().dot(&other.normalized()).abs().min(1.0).acos()
250    }
251
252    /// Whether the two quaternions are within `tol` componentwise (not modulo sign).
253    pub fn approx_eq(&self, other: &Self, tol: f64) -> bool {
254        (self.w - other.w).abs() <= tol && (self.x - other.x).abs() <= tol && (self.y - other.y).abs() <= tol && (self.z - other.z).abs() <= tol
255    }
256}
257
258fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
259    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
260}
261fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
262    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
263}
264fn norm3(a: [f64; 3]) -> f64 {
265    dot3(a, a).sqrt()
266}
267fn scale3(a: [f64; 3], s: f64) -> [f64; 3] {
268    [a[0] * s, a[1] * s, a[2] * s]
269}
270
271impl Default for Quaternion {
272    fn default() -> Self {
273        Self::identity()
274    }
275}
276
277impl Add for Quaternion {
278    type Output = Quaternion;
279    fn add(self, o: Quaternion) -> Quaternion {
280        Quaternion::new(self.w + o.w, self.x + o.x, self.y + o.y, self.z + o.z)
281    }
282}
283impl Sub for Quaternion {
284    type Output = Quaternion;
285    fn sub(self, o: Quaternion) -> Quaternion {
286        Quaternion::new(self.w - o.w, self.x - o.x, self.y - o.y, self.z - o.z)
287    }
288}
289impl Neg for Quaternion {
290    type Output = Quaternion;
291    fn neg(self) -> Quaternion {
292        Quaternion::new(-self.w, -self.x, -self.y, -self.z)
293    }
294}
295impl Mul<f64> for Quaternion {
296    type Output = Quaternion;
297    fn mul(self, s: f64) -> Quaternion {
298        Quaternion::new(self.w * s, self.x * s, self.y * s, self.z * s)
299    }
300}
301impl Div<f64> for Quaternion {
302    type Output = Quaternion;
303    fn div(self, s: f64) -> Quaternion {
304        Quaternion::new(self.w / s, self.x / s, self.y / s, self.z / s)
305    }
306}
307/// The Hamilton product: `a * b` applies `b` first, then `a`, when used as rotations.
308impl Mul for Quaternion {
309    type Output = Quaternion;
310    fn mul(self, o: Quaternion) -> Quaternion {
311        Quaternion::new(
312            self.w * o.w - self.x * o.x - self.y * o.y - self.z * o.z,
313            self.w * o.x + self.x * o.w + self.y * o.z - self.z * o.y,
314            self.w * o.y - self.x * o.z + self.y * o.w + self.z * o.x,
315            self.w * o.z + self.x * o.y - self.y * o.x + self.z * o.w,
316        )
317    }
318}
319
320impl From<FreeVector3D> for Quaternion {
321    /// The pure quaternion of a vector.
322    fn from(v: FreeVector3D) -> Self {
323        Quaternion::from_vector(v.cartesian_components().map(f64::from))
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330    use std::f64::consts::{FRAC_PI_2, FRAC_PI_3, PI};
331
332    fn close3(a: [f64; 3], b: [f64; 3]) -> bool {
333        (0..3).all(|i| (a[i] - b[i]).abs() < 1e-12)
334    }
335
336    #[test]
337    fn axis_angle_rotates_vectors() {
338        let q = Quaternion::from_axis_angle([0.0, 0.0, 1.0], FRAC_PI_2);
339        assert!(close3(q.rotate_vector([1.0, 0.0, 0.0]), [0.0, 1.0, 0.0]));
340        let q = Quaternion::from_axis_angle([1.0, 1.0, 1.0], 2.0 * FRAC_PI_3); // cycles the axes
341        assert!(close3(q.rotate_vector([1.0, 0.0, 0.0]), [0.0, 1.0, 0.0]));
342        let (axis, angle) = q.to_axis_angle();
343        assert!(close3(axis, [1.0 / 3f64.sqrt(); 3]) && (angle - 2.0 * FRAC_PI_3).abs() < 1e-12);
344        assert_eq!(Quaternion::from_axis_angle([0.0; 3], 1.0), Quaternion::identity());
345    }
346
347    #[test]
348    fn hamilton_product_composes_rotations() {
349        let a = Quaternion::from_axis_angle([1.0, 0.0, 0.0], 0.7);
350        let b = Quaternion::from_axis_angle([0.0, 1.0, 0.0], -1.1);
351        let v = [0.3, -0.5, 2.0];
352        assert!(close3((a * b).rotate_vector(v), a.rotate_vector(b.rotate_vector(v))));
353        let inv = a.inverse().unwrap();
354        assert!((a * inv).approx_eq(&Quaternion::identity(), 1e-14));
355        assert!(Quaternion::new(0.0, 0.0, 0.0, 0.0).inverse().is_none());
356        // i j = k
357        assert_eq!(Quaternion::new(0.0, 1.0, 0.0, 0.0) * Quaternion::new(0.0, 0.0, 1.0, 0.0), Quaternion::new(0.0, 0.0, 0.0, 1.0));
358    }
359
360    #[test]
361    fn rotation_matrix_round_trip_for_all_branches() {
362        for (axis, angle) in [([1.0, 2.0, 3.0], 0.4), ([1.0, 0.0, 0.0], 3.0), ([0.0, 1.0, 0.0], 3.0), ([0.0, 0.0, 1.0], 3.1), ([1.0, -1.0, 2.0], PI)] {
363            let q = Quaternion::from_axis_angle(axis, angle);
364            let m = q.to_rotation_matrix();
365            let back = Quaternion::from_rotation_matrix(&m);
366            assert!(q.angle_to(&back) < 1e-7, "{axis:?} {angle}");
367            let v = [0.2, 0.9, -0.4];
368            let mv = [dot3(m[0], v), dot3(m[1], v), dot3(m[2], v)];
369            assert!(close3(mv, q.rotate_vector(v)));
370        }
371    }
372
373    #[test]
374    fn euler_round_trip_and_gimbal_lock() {
375        let (r, p, y) = (0.3, -0.8, 2.0);
376        let (r2, p2, y2) = Quaternion::from_euler(r, p, y).to_euler();
377        assert!((r - r2).abs() < 1e-12 && (p - p2).abs() < 1e-12 && (y - y2).abs() < 1e-12);
378        // Pure yaw of 90 degrees maps x to y.
379        assert!(close3(Quaternion::from_euler(0.0, 0.0, FRAC_PI_2).rotate_vector([1.0, 0.0, 0.0]), [0.0, 1.0, 0.0]));
380        let q = Quaternion::from_euler(0.4, FRAC_PI_2, 0.0);
381        let (_, pitch, _) = q.to_euler();
382        assert!((pitch - FRAC_PI_2).abs() < 1e-9);
383        // At either gimbal lock the angles returned must reproduce the rotation.
384        for pitch in [FRAC_PI_2, -FRAC_PI_2] {
385            let q = Quaternion::from_euler(0.86, pitch, 1.77);
386            let (r, p, y) = q.to_euler();
387            assert!(y == 0.0 && q.angle_to(&Quaternion::from_euler(r, p, y)) < 1e-6, "pitch {pitch}");
388        }
389    }
390
391    #[test]
392    fn slerp_has_constant_angular_velocity() {
393        let a = Quaternion::identity();
394        let b = Quaternion::from_axis_angle([0.0, 0.0, 1.0], 1.2);
395        for k in 0..=10 {
396            let t = k as f64 / 10.0;
397            let (_, angle) = a.slerp(&b, t).to_axis_angle();
398            assert!((angle - 1.2 * t).abs() < 1e-12, "t={t}");
399        }
400        // Takes the short way round even if the operands have opposite sign.
401        assert!(a.slerp(&-b, 0.5).angle_to(&Quaternion::from_axis_angle([0.0, 0.0, 1.0], 0.6)) < 1e-12);
402        assert!(a.nlerp(&b, 0.5).angle_to(&a.slerp(&b, 0.5)) < 1e-3);
403    }
404
405    #[test]
406    fn exp_ln_powf_and_two_vector_rotation() {
407        let q = Quaternion::from_axis_angle([0.0, 1.0, 0.0], 0.9);
408        assert!(q.ln().exp().approx_eq(&q, 1e-12));
409        assert!(q.powf(2.0).angle_to(&Quaternion::from_axis_angle([0.0, 1.0, 0.0], 1.8)) < 1e-12);
410        let r = Quaternion::from_two_vectors([1.0, 0.0, 0.0], [0.0, 2.0, 0.0]);
411        assert!(close3(r.rotate_vector([1.0, 0.0, 0.0]), [0.0, 1.0, 0.0]));
412        let flip = Quaternion::from_two_vectors([0.0, 0.0, 1.0], [0.0, 0.0, -3.0]);
413        assert!(close3(flip.rotate_vector([0.0, 0.0, 1.0]), [0.0, 0.0, -1.0]));
414        assert_eq!(Quaternion::from_two_vectors([0.0; 3], [1.0, 0.0, 0.0]), Quaternion::identity());
415    }
416
417    #[test]
418    fn works_with_crate_vector_types() {
419        let q = Quaternion::from_axis_angle([0.0, 0.0, 1.0], FRAC_PI_2);
420        let v = q.rotate_free_vector(&FreeVector3D::new(1.0, 0.0, 0.0));
421        assert!((v.x()).abs() < 1e-6 && (v.y() - 1.0).abs() < 1e-6);
422        let p = q.rotate_point(&CoordinateVector3D::new(0.0, 2.0, 5.0));
423        assert!((p.x() + 2.0).abs() < 1e-6 && (p.z() - 5.0).abs() < 1e-6);
424        let pure: Quaternion = FreeVector3D::new(1.0, 2.0, 3.0).into();
425        assert_eq!(pure, Quaternion::new(0.0, 1.0, 2.0, 3.0));
426    }
427}