Monday, April 4, 2016

Quaternion-Based Rotation in OpenGL

This is yet another blog about quaternion. Assuming that we have quaternion [q0, q1, q2, q3]. Can we directly use it to rotation object in OpenGL? The answer is yes. At first, let us normalize this quaternion (written with Java)

     norm = (float) Math.sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);
    if (norm == 0)
    {
    return 0;
    }
    else
    {
    q0 = q0 / norm;
    q1 = q1 / norm;
    q2 = q2 / norm;
    q3 = q3 / norm;
    }

Then, glRotatef function in OpenGL is a natural fit for rotation using quaternion.
 
        // Rotate the object according to quaternion
        theta = (float) (Math.acos(q0) * 2);
        
        aNorm = (float) Math.sqrt(q1 * q1 + q2 * q2 + q3 * q3);
        if (aNorm != 0)
        {
        gl.glRotatef(theta*180f/PI, q1/aNorm, q2/aNorm, q3/aNorm);
        }
        else
        {
        gl.glRotatef(theta*180f/PI, q1, q2, q3);
        }

Note that except for quaternion, glRotatef can also be used for rotation along x, y or z axis. In that way, glRotatef needs to be called three times instead of once with quaternion-based method.

    glRotatef(xRot , 1.0, 0.0, 0.0);
    glRotatef(yRot , 0.0, 1.0, 0.0);
    glRotatef(zRot , 0.0, 0.0, 1.0);

No comments:

Post a Comment