//! Quaternion definition. #![allow(missing_docs)] // we allow missing to avoid having to document the dispatch trait. use std::mem; use std::slice::{Iter, IterMut}; use std::ops::{Add, Sub, Mul, Div, Neg, Index, IndexMut}; use std::iter::{FromIterator, IntoIterator}; use rand::{Rand, Rng}; use num::{Zero, One}; use structs::{Vec3, Pnt3, Rot3, Mat3}; use traits::operations::{ApproxEq, Inv, POrd, POrdering, Axpy}; use traits::structure::{Cast, Indexable, Iterable, IterableMut, Dim, Shape, BaseFloat, BaseNum, Bounded, Repeat}; use traits::geometry::{Norm, Rotation, RotationMatrix, Rotate, RotationTo, Transform}; #[cfg(feature="arbitrary")] use quickcheck::{Arbitrary, Gen}; /// A quaternion. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)] pub struct Quat { /// The scalar component of the quaternion. pub w: N, /// The first vector component of the quaternion. pub i: N, /// The second vector component of the quaternion. pub j: N, /// The third vector component of the quaternion. pub k: N } impl Quat { /// Creates a new quaternion from its components. #[inline] pub fn new(w: N, i: N, j: N, k: N) -> Quat { Quat { w: w, i: i, j: j, k: k } } /// The vector part `(i, j, k)` of this quaternion. #[inline] pub fn vector<'a>(&'a self) -> &'a Vec3 { // FIXME: do this require a `repr(C)` ? unsafe { mem::transmute(&self.i) } } /// The scalar part `w` of this quaternion. #[inline] pub fn scalar<'a>(&'a self) -> &'a N { &self.w } } impl + Copy> Quat { /// Compute the conjugate of this quaternion. #[inline] pub fn conjugate(&self) -> Quat { Quat { w: self.w, i: -self.i, j: -self.j, k: -self.k } } /// Replaces this quaternion by its conjugate. #[inline] pub fn conjugate_mut(&mut self) { self.i = -self.i; self.j = -self.j; self.k = -self.k; } } impl> Inv for Quat { #[inline] fn inv(&self) -> Option> { let mut res = *self; if res.inv_mut() { Some(res) } else { None } } #[inline] fn inv_mut(&mut self) -> bool { let sqnorm = Norm::sqnorm(self); if ApproxEq::approx_eq(&sqnorm, &::zero()) { false } else { self.conjugate_mut(); self.w = self.w / sqnorm; self.i = self.i / sqnorm; self.j = self.j / sqnorm; self.k = self.k / sqnorm; true } } } impl Norm for Quat { #[inline] fn sqnorm(&self) -> N { self.w * self.w + self.i * self.i + self.j * self.j + self.k * self.k } #[inline] fn normalize(&self) -> Quat { let n = self.norm(); Quat::new(self.w / n, self.i / n, self.j / n, self.k / n) } #[inline] fn normalize_mut(&mut self) -> N { let n = Norm::norm(self); self.w = self.w / n; self.i = self.i / n; self.j = self.j / n; self.k = self.k / n; n } } impl Mul> for Quat where N: Copy + Mul + Sub + Add { type Output = Quat; #[inline] fn mul(self, right: Quat) -> Quat { Quat::new( self.w * right.w - self.i * right.i - self.j * right.j - self.k * right.k, self.w * right.i + self.i * right.w + self.j * right.k - self.k * right.j, self.w * right.j - self.i * right.k + self.j * right.w + self.k * right.i, self.w * right.k + self.i * right.j - self.j * right.i + self.k * right.w) } } impl + BaseFloat> Div> for Quat { type Output = Quat; #[inline] fn div(self, right: Quat) -> Quat { self * right.inv().expect("Unable to invert the denominator.") } } rand_impl!(Quat, w, i, j, k); /// A unit quaternion that can represent a 3D rotation. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)] pub struct UnitQuat { q: Quat } impl UnitQuat { /// Creates a new unit quaternion from the axis-angle representation of a rotation. #[inline] pub fn new(axisangle: Vec3) -> UnitQuat { let sqang = Norm::sqnorm(&axisangle); if ::is_zero(&sqang) { ::one() } else { let ang = sqang.sqrt(); let (s, c) = (ang / Cast::from(2.0)).sin_cos(); let s_ang = s / ang; unsafe { UnitQuat::new_with_unit_quat( Quat::new( c, axisangle.x * s_ang, axisangle.y * s_ang, axisangle.z * s_ang) ) } } } /// Creates a new unit quaternion from a quaternion. /// /// The input quaternion will be normalized. #[inline] pub fn new_with_quat(q: Quat) -> UnitQuat { UnitQuat { q: q.normalize() } } /// Creates a new unit quaternion from Euler angles. /// /// The primitive rotations are applied in order: 1 roll − 2 pitch − 3 yaw. #[inline] pub fn new_with_euler_angles(roll: N, pitch: N, yaw: N) -> UnitQuat { let _0_5: N = Cast::from(0.5); let (sr, cr) = (roll * _0_5).sin_cos(); let (sp, cp) = (pitch * _0_5).sin_cos(); let (sy, cy) = (yaw * _0_5).sin_cos(); unsafe { UnitQuat::new_with_unit_quat( Quat::new( cr * cp * cy + sr * sp * sy, sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy) ) } } /// Builds a rotation matrix from this quaternion. pub fn to_rot(&self) -> Rot3 { let _2: N = Cast::from(2.0); let ww = self.q.w * self.q.w; let ii = self.q.i * self.q.i; let jj = self.q.j * self.q.j; let kk = self.q.k * self.q.k; let ij = _2 * self.q.i * self.q.j; let wk = _2 * self.q.w * self.q.k; let wj = _2 * self.q.w * self.q.j; let ik = _2 * self.q.i * self.q.k; let jk = _2 * self.q.j * self.q.k; let wi = _2 * self.q.w * self.q.i; unsafe { Rot3::new_with_mat( Mat3::new( ww + ii - jj - kk, ij - wk, wj + ik, wk + ij, ww - ii + jj - kk, jk - wi, ik - wj, wi + jk, ww - ii - jj + kk ) ) } } } impl UnitQuat { /// Creates a new unit quaternion from a quaternion. /// /// This is unsafe because the input quaternion will not be normalized. #[inline] pub unsafe fn new_with_unit_quat(q: Quat) -> UnitQuat { UnitQuat { q: q } } /// The `Quat` representation of this unit quaternion. #[inline] pub fn quat<'a>(&'a self) -> &'a Quat { &self.q } } impl One for UnitQuat { #[inline] fn one() -> UnitQuat { unsafe { UnitQuat::new_with_unit_quat(Quat::new(::one(), ::zero(), ::zero(), ::zero())) } } } impl> Inv for UnitQuat { #[inline] fn inv(&self) -> Option> { let mut cpy = *self; cpy.inv_mut(); Some(cpy) } #[inline] fn inv_mut(&mut self) -> bool { self.q.conjugate_mut(); true } } impl Rand for UnitQuat { #[inline] fn rand(rng: &mut R) -> UnitQuat { UnitQuat::new(rng.gen()) } } impl> ApproxEq for UnitQuat { #[inline] fn approx_epsilon(_: Option>) -> N { ApproxEq::approx_epsilon(None::) } #[inline] fn approx_ulps(_: Option>) -> u32 { ApproxEq::approx_ulps(None::) } #[inline] fn approx_eq_eps(&self, other: &UnitQuat, eps: &N) -> bool { ApproxEq::approx_eq_eps(&self.q, &other.q, eps) } #[inline] fn approx_eq_ulps(&self, other: &UnitQuat, ulps: u32) -> bool { ApproxEq::approx_eq_ulps(&self.q, &other.q, ulps) } } impl> Div> for UnitQuat { type Output = UnitQuat; #[inline] fn div(self, other: UnitQuat) -> UnitQuat { UnitQuat { q: self.q / other.q } } } impl Mul> for UnitQuat { type Output = UnitQuat; #[inline] fn mul(self, right: UnitQuat) -> UnitQuat { UnitQuat { q: self.q * right.q } } } impl Mul> for UnitQuat { type Output = Vec3; #[inline] fn mul(self, right: Vec3) -> Vec3 { let _2: N = ::one::() + ::one(); let mut t = ::cross(self.q.vector(), &right); t.x = t.x * _2; t.y = t.y * _2; t.z = t.z * _2; Vec3::new(t.x * self.q.w, t.y * self.q.w, t.z * self.q.w) + ::cross(self.q.vector(), &t) + right } } impl Mul> for UnitQuat { type Output = Pnt3; #[inline] fn mul(self, right: Pnt3) -> Pnt3 { ::orig::>() + self * *right.as_vec() } } impl> Mul> for Vec3 { type Output = Vec3; #[inline] fn mul(self, right: UnitQuat) -> Vec3 { let mut inv_quat = right; inv_quat.inv_mut(); inv_quat * self } } impl> Mul> for Pnt3 { type Output = Pnt3; #[inline] fn mul(self, right: UnitQuat) -> Pnt3 { ::orig::>() + *self.as_vec() * right } } impl Rotation> for UnitQuat { #[inline] fn rotation(&self) -> Vec3 { let _2 = ::one::() + ::one(); let mut v = *self.q.vector(); let ang = _2 * v.normalize_mut().atan2(self.q.w); if ::is_zero(&ang) { ::zero() } else { Vec3::new(v.x * ang, v.y * ang, v.z * ang) } } #[inline] fn inv_rotation(&self) -> Vec3 { -self.rotation() } #[inline] fn append_rotation_mut(&mut self, amount: &Vec3) { *self = Rotation::append_rotation(self, amount) } #[inline] fn append_rotation(&self, amount: &Vec3) -> UnitQuat { *self * UnitQuat::new(*amount) } #[inline] fn prepend_rotation_mut(&mut self, amount: &Vec3) { *self = Rotation::prepend_rotation(self, amount) } #[inline] fn prepend_rotation(&self, amount: &Vec3) -> UnitQuat { UnitQuat::new(*amount) * *self } #[inline] fn set_rotation(&mut self, v: Vec3) { *self = UnitQuat::new(v) } } impl RotationMatrix, Vec3> for UnitQuat { type Output = Rot3; #[inline] fn to_rot_mat(&self) -> Rot3 { self.to_rot() } } impl> Rotate> for UnitQuat { #[inline] fn rotate(&self, v: &Vec3) -> Vec3 { *self * *v } #[inline] fn inv_rotate(&self, v: &Vec3) -> Vec3 { *v * *self } } impl> Rotate> for UnitQuat { #[inline] fn rotate(&self, p: &Pnt3) -> Pnt3 { *self * *p } #[inline] fn inv_rotate(&self, p: &Pnt3) -> Pnt3 { *p * *self } } impl> RotationTo for UnitQuat { type AngleType = N; type DeltaRotationType = UnitQuat; #[inline] fn angle_to(&self, other: &Self) -> N { let delta = self.rotation_to(other); let _2 = ::one::() + ::one(); _2 * delta.q.vector().norm().atan2(delta.q.w) } #[inline] fn rotation_to(&self, other: &Self) -> UnitQuat { *other / *self } } impl> Transform> for UnitQuat { #[inline] fn transform(&self, v: &Vec3) -> Vec3 { *self * *v } #[inline] fn inv_transform(&self, v: &Vec3) -> Vec3 { *v * *self } } impl> Transform> for UnitQuat { #[inline] fn transform(&self, p: &Pnt3) -> Pnt3 { *self * *p } #[inline] fn inv_transform(&self, p: &Pnt3) -> Pnt3 { *p * *self } } #[cfg(feature="arbitrary")] impl Arbitrary for UnitQuat { fn arbitrary(g: &mut G) -> UnitQuat { UnitQuat::new(Arbitrary::arbitrary(g)) } } pord_impl!(Quat, w, i, j, k); vec_axis_impl!(Quat, w, i, j, k); vec_cast_impl!(Quat, w, i, j, k); conversion_impl!(Quat, 4); index_impl!(Quat); indexable_impl!(Quat, 4); at_fast_impl!(Quat, 4); repeat_impl!(Quat, val, w, i, j, k); dim_impl!(Quat, 3); container_impl!(Quat); add_impl!(Quat, w, i, j, k); sub_impl!(Quat, w, i, j, k); scalar_add_impl!(Quat, w, i, j, k); scalar_sub_impl!(Quat, w, i, j, k); scalar_mul_impl!(Quat, w, i, j, k); scalar_div_impl!(Quat, w, i, j, k); neg_impl!(Quat, w, i, j, k); zero_one_impl!(Quat, w, i, j, k); approx_eq_impl!(Quat, w, i, j, k); from_iterator_impl!(Quat, iterator, iterator, iterator, iterator); bounded_impl!(Quat, w, i, j, k); axpy_impl!(Quat, w, i, j, k); iterable_impl!(Quat, 4); iterable_mut_impl!(Quat, 4); arbitrary_impl!(Quat, w, i, j, k); dim_impl!(UnitQuat, 3);