Demo - Avoiding Gimbal LockFinally, we've reached what you all been waiting for: "How can quaternions avoid gimbal lock.?" The basic idea is
Firstly, I want to make a disclaimer regarding the sample code. The code is ugly and very poorly organized. But do remember, this is just a cut down version of my program when I was testing quaternions, and I'm not getting paid for this. There are two executable samples that I have included. The first program, CameraEuler.exe, is an example for camera implementation using Euler angles. The main concern should be the Main_Loop function in main.cpp. The main thing you should take note (in the while loop) is
Use the up/down keys to rotate around the X axis, left/right to rotate around the Y axis and Insert/PageUp to rotate around the Z axis. This program suffers from gimbal lock. If you want to see it in action, rotate the camera so that the yaw is 90 deg. Then try rotating in the X and Z direction. See what happens. Now for the quaternion solution. The program is CameraQuat.exe and it is a slight modification of the previous program. The main point you should take note (in the while loop) is
When a key is pressed, I generate a temporary quaternion corresponding to the key for a small rotation in that particular axis. I then multiply the temporary quaternion into the camera quaternion. This concatenation of rotations in 4D space will avoid gimbal lock. Try it and see for yourself. The camera quaternion has to be changed into either a matrix form or equivalence form so that you can concatenate it into a final transformation matrix. You have to do this for every quaternion you use, as 4D space and 3D space just don't mix. In the case of OpenGL, I just changed the quaternion to an Axis Angle representation and let the API do the rest. Although I did not use the global Euler angles for rotations in the second program, I have left them there as a guide for you to see the similar Euler rotations in the first program. Note the Euler angles will be incorrect if you rotate more than 1 axis (because it counts the keypress rather than getting the Euler angles from the camera quaternion). It is just a reference for you to see that when you rotate the yaw to 90 deg when the program starts, the gimbal lock problem is no more. Note: I don't recommend you use my math library as it is. Understand the quaternion and write your own. For your information, I am going to throw all of that away and rewrite it too. It is just too messy and ugly for my taste. |
|||||||||||