# Why do game programmers use quaternions to rotate a vector?

This topic is 4344 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

[Edited by - Kambiz on March 29, 2006 8:36:21 AM]

##### Share on other sites
Do game programers do so? Yes, but very seldom. In fact the matrix vector product is much better suited to rotate a vector.

However, quaternions are good for operations occuring _before_ rotating a vector, namely in intra-/extrapolating rotations, in concatenating rotations, and a bit also in storing rotations (if the memory footprint plays a remarkable role).

But, hey, formula 4) seems me a look worth ;) That is an axis/angle pair rotation, right?

##### Share on other sites
Because sometimes, rotating a vector is not the goal, it's part of the process you must follow, in order to achieve the goal.

And quaternions -sometimes- make it easier to achieve some goals, than just rotate a vector.

##### Share on other sites
Quote:
 Original post by haegarrBut, hey, formula 4) seems me a look worth ;) That is an axis/angle pair rotation, right?

Yes

Quaternion rotations are easy to combine, that is a good reason to use them, but I think many programmers use quaternions just because they do not know formula 4 or think that quaternions are cool!

##### Share on other sites
Quote:
 Original post by someusernameAnd quaternions -sometimes- make it easier to achieve some goals, than just rotate a vector.

Give me an example.

##### Share on other sites
Orientation interpolation at constant angular speed

##### Share on other sites
I saw an engine once that serialized rotations as a quaternion using 3 8-bit values. It used w = 1-sqrt(x^2+y^2+z^2) (or something like that) when it loaded them from disk, then converted that to a 3x3 matrix. So basically it compressed the 3x3 matrix down to 24-bits.

Not sure I'd do that, but it seemed to work okay.

##### Share on other sites
Quote:
 Original post by someusernameOrientation interpolation at constant angular speed

Why do you need a quaternion? In classical mechanics people use just a vector and it works well.

##### Share on other sites
Quote:
 Original post by Anonymous PosterI saw an engine once that serialized rotations as a quaternion using 3 8-bit values. It used w = 1-sqrt(x^2+y^2+z^2)...Not sure I'd do that, but it seemed to work okay.

The same way you can use a vector to represent the rotation... as you see you just need 3 values x,y,z and w is useless.

##### Share on other sites
You're talking about the angular velocity vector which describes the instantaneous rate of change of an object's axes.
I'm talking about arbitrarily setting the object's axes to any two orientations, and interpolating smoothly from one to the other.

If you just want to rotate a vector, there must be a million ways. You could even change to spherical coordinates, offset the angles and reproject to cartesian.
Have you seen anyone using that? It's all a matter of what you want to achieve in the first place.

And I said "quaternions sometimes make it easier", not that they can do something when there is no other way.
Anyway, I don't feel like arguing about this. Anyone who has ever used them can decide for themselves whether they are worth the fuss.

##### Share on other sites
Do not understand me wrong I have nothing against quaternions, I really like them but I see many programmers specially beginners here talking about quaternions without knowing basic mathematics, one of the reasons I have started this threat is to show this people that there are easier ways if they just want to rotate a vector and that Mathematical knowledge is important for a programmer.

##### Share on other sites
Indeed. Quaternions were conceived for a totally different purpose. Fundamental proofs of stereometry and geometry were written with quaternions first, long before the advent of vectors and matrices.
I doubt whether a textbook on quaternions would have more than 5% dedicated to their isomorphism with SO3. There are so many things about them, that rotations is the last you could mention.

My opinion is that most beginners use quaternions in order to avoid gimbal lock. And indeed, when I was younger myself, I probably wouldn't give a damn about what causes it, or having to rotate about three mutually perpendicular axes to get rid of it. I would only care about how to get the damn spaceship to rotate :) , and
if I had seen it written somewhere that "quaternions avoid gimbal lock" I would probably be flaming now, with arguments like: "dude come on! They avoid gimbal lock, but I don't know what causes it in the first place!"

IMHO, this is not bad; it's only natural. It's just a matter of prorities.

##### Share on other sites
I don't use quaternions because I believe it is important to have a good Understanding of the math you use (unlike many beginners, as Kambiz pointed out)
consequently, seeing as how I cannot understand Why they work, and Hamilton(the inventor) as far as I can tell was insane, I don't use them.

I get by just fine, I use a largely vector and matrix approach.
Although even matrices tend to be rare for me, If I want to rotate a vector I just add a direction offset to it then Normalize.

It was mentioned that interpolating between two orientations at fixed speed was a 'killer app' for quaternion rotations. However I generally don't ever do that kind of thing; my engine is entirely based on physics not animation keyframes. So when I want to rotate between two orientations I use a PID controller that dynamically handles the motion...

Quote:
 Original post by someusernameMy opinion is that most beginners use quaternions in order to avoid gimbal lock.

I think I should point out, that quaternions don't avoid gimbal lock....
gimbal lock is a property of the sequence of rotations you use, not how those rotations are represented.

##### Share on other sites
Quaternions definitely get a lot of abuse, from both sides. A lot of people dismiss them without understanding what they have to offer (there have been some surprisingly ill-informed articles published online to this effect), and a lot of people embrace them with equally little understanding (just look at any of the various 'simple quaternion camera' tutorials that use them in completely pointless ways).

As usual, the truth is somewhere in the middle (obviously the posters in this thread know this, but it's always good to reiterate it for those new to the subject). The fact is, there is hardly anything (if anything) you can do with a quaternion that you can't do with a matrix. Matrices and quaternions do essentially the same things, but not always with equal ease or efficiency. So in the end it's just a matter of choosing the best (or perhaps just preferred) tool for the job.

##### Share on other sites
Quote:
Original post by haphazardlynamed
Quote:
 Original post by someusernameMy opinion is that most beginners use quaternions in order to avoid gimbal lock.

I think I should point out, that quaternions don't avoid gimbal lock....
gimbal lock is a property of the sequence of rotations you use, not how those rotations are represented.

Correct me if I'm wrong, but gimbal lock comes from the fact that you perform three rotations around axes that depend on the previous rotations.
It is almost impossible that all three of them are perpendicular to each other. (that depends on the actual angles too)
This way, you may end up rotating twice around "one" axis, and this makes the model seem to rotate erratically.
This is what causes the weird behaviour we call "gimbal lock".
Quaternions avoid this problem, by performing a single rotation on the right plane...

Quote:
 Original post by jykAs usual, the truth is somewhere in the middle (obviously the posters in this thread know this, but it's always good to reiterate it for those new to the subject). The fact is, there is hardly anything (if anything) you can do with a quaternion that you can't do with a matrix. Matrices and quaternions do essentially the same things, but not always with equal ease or efficiency. So in the end it's just a matter of choosing the best (or perhaps just preferred) tool for the job.

I couldn't agree more. There may be problems with matrix rotation that do not affect quaternions.
Similarly, there are problems with quaternions, that can be handled much easier with matrices. E.g. creating a quaternion that rotates one set of base vectors to another.
Their true power comes when you can use them interchangeably to get what you want with the "least effort".

##### Share on other sites
I actually could not find the nicely condinsed equation #4, which you provided. I have google searched for "rotate point/vector around arbitrary vector/axis" with minimal results (other searches as well). Most results are quanternions and the others have around 12 steps of costly math to rotate the point. I never had the patience to condense the formulas found down to #4 and just went with, oh well lets use freaking quanternions.

QUESTION: what the heck does #3 mean? Exp( vector_axis cross??? wha??? ). Does not seem to make a lick of sense to me.

ANOTHER QUESTION: in #2, what is the vector J? The original vector you whish to rotate around axis p? If so, why are you not using the variable x, like equation #4 for consistancy and less confusion?

YET ANOTHER QUESTION: I assume your applying all these trig/exp functions to every x,y,z component of the original vectors to obtain your new vector, correct?

LAST QUESTION: what is passive rotation, ive never heard that before.

##### Share on other sites
one use of quaternions is their ability for spherical interpolation, which really improves quality of animations. I listened to a seminar about quaternions 2 months ago, unfortunately the person speaking didn t seem to understand them very well.

##### Share on other sites
#4 doesn't look all that great to me. qvq* seems to be a very simple equation to me. Even when it's fully expanded out to [cos(a/2),n sin(a/2)]v[cos(a/2),n -sin(a/2)], it seems no more complex than #4. It's also much more comprehensible to me. If I see the quaternion equation somewhere I know exactly what's going on. I can't tell immediately that #4 is a rotation operation.

##### Share on other sites
Quote:
 Original post by someusernameCorrect me if I'm wrong, but gimbal lock comes from the fact that you perform three rotations around axes that depend on the previous rotations. It is almost impossible that all three of them are perpendicular to each other. (that depends on the actual angles too)This way, you may end up rotating twice around "one" axis, and this makes the model seem to rotate erratically.This is what causes the weird behaviour we call "gimbal lock".Quaternions avoid this problem, by performing a single rotation on the right plane...

Yes, that is essentialy how gimbal lock works.

However, lets put it this way:
a quaternion can perform a rotation on an arbitrary axis.
a matrix can perform a rotation on an abitrary axis.

Gimbal lock is a problem with the 'Euler Angles' representation; of sequential Axis Aligned rotations that might recombine to move an axis onto one you already used, thus doing the 'rotating twice around one axis' effect you described. Euler Angles are merely a logical representation; a notation system. Whether you perform the rotation using a matrix or quaternion is an idependant issue.

a 'single rotation on the right plane' could be peformed by a quaternion, or by a matrix. the real question is, given an Euler Angles representation, how do you want to recombine those 3 succesive x,y,z rotations into a single 'right plane'? the process of recombination may or may not eliminate the gimbal lock, but this is also a separate problem from either the quaternion or the matrix used to peform the final rotation.

final killer example:
Gimbal Lock is a term that comes from Robotics, where the manuverability of a robot arm for example, would become limited if its joints were to align to lose an axis of freedom. Consider then, if your physical robot arm is capable of gimbal locking, then does it matter wheter the controller program hooked up to that arm represents the rotations as quaternions or as matrixes? Gimbal Lock is a logic control problem, not a math problem.

anyhow... I don't have anything against quaternions
I just get tired of people assuming that gimbal lock is exclusively a matrix issue and that switching to quaternions will magically fix everything
a search of the archives should reveal a few begginers' topics of "I switched to quaternions but still have gimbal lock! Help!" that will attest to the problems caused by this misconception...

[Edited by - haphazardlynamed on March 29, 2006 12:43:12 PM]

##### Share on other sites
One reason why you would prefer quaternions to an axis-angle representation for vector rotation is if you need to accomodate a stack of several rotation operations. Concatenating quaternions is really easy; concatenating two axis-angle transformations is considerably harder.

Also, I don't think anyone mentioned the advantage quarternions have over a matrix representation in terms of maintaining the orthonormality of the transformation (that is, the transformation is less likely to become distorted or scaled due to rounding errors, since many fewer floating point operations are necessary for quaternion composition).

One final thought: because I don't feel like I understand quaternions very well, I set myself a while ago to deriving an alternative matrix formulation that was simpler than quaternions, didn't require composition of component matrix transforms (like Euler Angles), and didn't have any more special cases than Quats do (e.g., the degenerate case of a 180 degree pole-to-pole slerp). I succeeded pretty well, but then I thought about everything I'd have to do to actually use it; all the thunking code that would need to be written to map from quaternion orientation representations into my own system, the extra porting code needed for quat based animation systems, all the good, portable math libraries that would no longer be very useful to me. I eventually decided it was the lesser of two evils to pursue quaternions, despite not understanding them entirely. There is a pretty significant advantage to following the herd, after all :p

##### Share on other sites
OK.
1)Quaternions can represent rotations in a compact form.
2)Rotations are easy to combine.

I do not want to add a point “Gimbal Lock”.

But we should not forget that we need just 3 values to represent a rotation even when we are using matrix transformations but extracting this values from a matrix and creating the matrix from such 3 values is not so easy.

[attention] What I really like about matrix transformations is that they can do much more than just rotating an object, specially by using homogeneous coordinates we can translate objects and that is really interesting.

##### Share on other sites
Quote:
 Original post by KambizWhat I really like about matrix transformations is that they can do much more than just rotating an object, specially by using homogeneous coordinates we can translate objects and that is really interesting.

Which is often a very bad thing. Similarly, you could use strings to represent all the integers in your program, because they can do much more than just numbers. It is entirely possible to have too much expressivity.

##### Share on other sites
For anybody working with quaternions, I recommend two books:

Quaternions and Rotation Sequences
Visualizing Quaternions

Let me clearly state I have read neither all the way through. I've read the half way through the first book. I've found it's mathematical analyses much more accessible than the second. There are some great proofs in there that have helped me more fully understand what's going on.

I've only read about a quarter of the second book. The math isn't nearly as clear and well-presented as the first title. OTOH, it's focused primarily on graphics whereas the first is primarily oriented towards aerospace and astrodynamics. It also has some very intriguing material in its introductory material that really makes me want to read it all the way through.

What do other people think?

##### Share on other sites
Quote:
 Original post by haphazardlynamedanyhow... I don't have anything against quaternionsI just get tired of people assuming that gimbal lock is exclusively a matrix issue and that switching to quaternions will magically fix everythinga search of the archives should reveal a few begginers' topics of "I switched to quaternions but still have gimbal lock! Help!" that will attest to the problems caused by this misconception...

I think you've misunderstood the point I was trying to make. My exact words, were: "My opinion is that most beginners use quaternions in order to avoid gimbal lock."
I only used this expression, to stress out that someone may blindly start using them -without understanding fundamental things about them- just because it is common belief that they "avoid gimbal lock".

Of course, gimbal lock is a problem inherent to the euler angles representation of rotations. Even if you used quaternions for each subsequent X/Y/Z rotation in euler angles, and concatenated them into a single quaternion, you'd still be experiencing the same problem. It doesn't mean that because you used quaternions inbetween, you would get rid of it!
And, in fact, no rotation is actually performed with a quaternion. In the end, you turn it into a matrix and apply it as world/model transformation.
Would this mean that it should be prone to "gimbal lock" just because it's not a quaternion anymore?
I think you misunderstood me; I'm sorry if it wasn't clear.

Quote:
 Original post by MuseAlso, I don't think anyone mentioned the advantage quarternions have over a matrix representation in terms of maintaining the orthonormality of the transformation (that is, the transformation is less likely to become distorted or scaled due to rounding errors, since many fewer floating point operations are necessary for quaternion composition).

Indeed, this is a very important argument for the use of quaternions.
And in fact, the cost of re-orthogonalization is minimum compared to an orthogonal matrix.

##### Share on other sites
Please correct me if I'm wrong, don't flame me to ashes.
I was under the impression that quaternions are generally more computationally expensive than matrices for the same use/applications and that matrices are themselves more expensive than equations for the same use/applications. I must admit this is probably a biased, personal but not necessarily untrue opinion. I've never used quaternions but I've been using rotation/translation/orbit/etc. equations for a long time now.

And I've never understood how using matrices for applying 3D rotations could somehow be less expensive than:
xi:=xo[ver]-rlx;yi:=yo[ver]-rly;xi:=zo[ver]-rlz;v1:=calf*xi+salf*zi;v2:=calf*zi-salf*xi;v3:=cbet*yi+sbet*v2; zr[ver]:=cbet*v2-sbet*yi+rlz;xr[ver]:=cgam*v1+sgam*v3+rlx;yr[ver]:=cgam*v3-sgam*v1+rly;

This is a very old little snippet of code I once used for offset camera rotation, around some arbitrary point in the world space. So it has 3 float adds and 3 float subs in addition to the rotation equations themselves.

And it's still probably much faster than using unbroken down matrices and applying matrix multiplication. But seeing as how today's GPUs do mostly all the work, nobody's getting too worked up about how horrendously wasteful matrix operations are... in both memory and processor time.

I presume it's even worse using quaternions to do smth. instead of just about anything else. If this is true, and a known fact, why do people use them so readily? I think it's because not all that many people INTUITIVELY understand the math behind some stuff. Instead of getting into the knitty gritty details of software optimisation through optimising its math, they just go the lazy man's way.

People would rather shave a little math research work off their development schedule than help their finished software save hundreds of millions of processor cycles needlessly wasted each runtime second. And what's worse, I'm pretty sure that whole established, fundamental 3D apis like OGL and D3D as well as their hardware implementation were and are developed the lazy (at maths) man's way also. There are tutorials written on how to do it the lazy man's way too!!!

I mean, just look at this "tutorial" on 3D rotation:

From the very beginning:
Quote:
 Okay, so I assume going into this tutorial that you know how to perform matrix multiplication.

If you're gonna do it using the CPU not GPU, I'd expect you'd at least try to NOT BLATANTLY WASTE processor time. And then goes on to say:

Quote:
 Sure, it's easy to make equations that will represent a rotation on any one of those axes, but just go ahead and try to make equations that will represent changes on three axes at once. If you manage to pull that off, make sure to let us know. Meanwhile, I'll present a way to do the rotations with matrices.

I rest my case.

[Edited by - sonyafterdark on April 1, 2006 4:31:44 PM]