Upcoming Events
Unite 2010
11/10 - 11/12 @ Montréal, Canada

GDC China
12/5 - 12/7 @ Shanghai, China

Asia Game Show 2010
12/24 - 12/27  

GDC 2011
2/28 - 3/4 @ San Francisco, CA

More events...
Quick Stats
100 people currently visiting GDNet.
2406 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!
Link to us Events 4 Gamers
Intel sponsors gamedev.net search:

Normalizing a quaternion

Normalizing a quaternion is almost the same as normalizing a vector. We start by computing the length of the quaternion to be normalized, which is done using the Euclidean distance forumula:

|Q| = sqrt( w^2 + x^2 + y^2 + z^2)

A function to implement this formula might look like this:

double length(quaternion quat)
  return sqrt(quat.x * quat.x + quat.y * quat.y +
              quat.z * quat.z + quat.w * quat.w);

Not too hard is it? Now to get the normalized vector Q, which we'll call Q*, we just divide every element of Q by |Q|.

Q* = Q/|Q| = [w/|Q|, v/|Q|]

Here's some sample code for this function:

quaternion normalize(quaternion quat)
  double L = length(quat);

  quat.x /= L;
  quat.y /= L;
  quat.z /= L;
  quat.w /= L;

  return quat;

This will give us a quaternion of length 1 (which is very important for rotations). Still nothing scary right? Well, it doesn't really get much harder than this.

The conjugate of a quaternion

Let's compute the conjugate of a quaternion and call it Q'. The conjugate is simply

Q' = [ w, -v ]

Here's the code for the conjugate:

quaternion conjugate(quaternion quat)
  quat.x = -quat.x;
  quat.y = -quat.y;
  quat.z = -quat.z;
  return quat;

The last thing you need to know is quaternion multiplication. Then you'll be ready to make a quaternion based camera.

Multiplying quaternions

Multiplication with quaternions is a little complicated as it involves dot-products cross-products. However, if you just use the following forumula that expands these operations, it isn't too hard. To multiply quaternion A by quaternion B, just do the following:

C = A * B

such that:

C.x = | A.w*B.x + A.x*B.w + A.y*B.z - A.z*B.y |
C.y = | A.w*B.y - A.x*B.z + A.y*B.w + A.z*B.x |
C.z = | A.w*B.z + A.x*B.y - A.y*B.x + A.z*B.w |
C.w = | A.w*B.w - A.x*B.x - A.y*B.y - A.z*B.z |

Here's some code for multiplication:

quaternion mult(quaternion A, quaternion B)
  quaternion C;

  C.x = A.w*B.x + A.x*B.w + A.y*B.z - A.z*B.y;
  C.y = A.w*B.y - A.x*B.z + A.y*B.w + A.z*B.x;
  C.z = A.w*B.z + A.x*B.y - A.y*B.x + A.z*B.w;
  C.w = A.w*B.w - A.x*B.x - A.y*B.y - A.z*B.z;
  return C;

That's not too that hard is it? Now we'll look at how to use these operations to make a quaternion based camera.

The Quaternion Camera

  Quaternion Operations
  The Quaternion Camera

  Printable version
  Discuss this article