Skip to content

Commit

Permalink
Fleshing out the quaternion implementation a bit.
Browse files Browse the repository at this point in the history
  • Loading branch information
vilya committed Aug 10, 2010
1 parent c4d04af commit db4bed8
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
4 changes: 4 additions & 0 deletions NOTES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ This will mean unprojecting the screen coordinates from the previous and current
mouse positions and subtracting the previous from the current to find the
translation vector. Add that vector to the camera position & that should be it,
I think?

A decent (and mercifully brief!) explanation of quaternions is at:
http://www.genesis3d.com/~kdtop/Quaternions-UsingToRepresentRotation.htm

49 changes: 46 additions & 3 deletions src/vgl_quaternion.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ Quaternion<Num> operator - (const Quaternion<Num>& a, const Quaternion<Num>& b)
template <typename Num>
Quaternion<Num> operator * (const Quaternion<Num>& a, const Quaternion<Num>& b)
{
// TODO
Vec3<Num> av(a.x, a.y, a.z);
Vec3<Num> bv(b.x, b.y, b.z);
Vec3<Num> rv = a.w * bv + b.w * av + cross(av, bv);
return Quaternion<Num>(rv.x, rv.y, rv.z, a.w * b.w - dot(av, bv));
}


Expand Down Expand Up @@ -142,14 +145,14 @@ const Quaternion<Num>& operator /= (Quaternion<Num>& a, Num k)
template <typename Num>
Num lengthSqr(const Quaternion<Num>& a)
{
// TODO
return sqr(a.x) + sqr(a.y) + sqr(a.z) + sqr(a.w);
}


template <typename Num>
Num length(const Quaternion<Num>& a)
{
// TODO
std::sqrt(lengthSqr(a));
}


Expand All @@ -167,6 +170,46 @@ Quaternion<Num> norm(const Quaternion<Num>& a)
}


template <typename Num>
Quaternion<Num> conjugate(const Quaternion<Num>& a)
{
return Quaternion<Num>(-a.x, -a.y, -a.z, a.w);
}


template <typename Num>
Quaternion<Num> inverse(const Quaternion<Num>& a)
{
const Quaternion<Num> c = conjugate(a);
return c / (a * c);
}


// Rotate vector v by quaternion q.
template <typename Num>
Vec3<Num> rotate(const Quaternion<Num>& q, const Vec3<Num>& v)
{
// FIXME: need to define multiplication operators for quaternion * vec3 and vec3 * quaternion
return q * v * inverse(q);
}


// Rotate vector v by quaternion q.
template <typename Num>
Vec4<Num> rotate(const Quaternion<Num>& q, const Vec4<Num>& v)
{
// FIXME: need to define multiplication operators for quaternion * vec3 and vec3 * quaternion
return q * v * inverse(q);
}


template <typename Num>
Quaternion<Num> slerp(const Quaternion<Num>& a, const Quaternion<Num>& b, Num k)
{
return k * a + (1 - k) * b;
}


} // namespace vgl

#endif // vgl_quaternion_h
Expand Down

0 comments on commit db4bed8

Please sign in to comment.