Jump to content
  • Advertisement
Sign in to follow this  

I need to know if my quaternion to matrix function is correct.

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a function that converts a quaternion to a 3x3 row major matrix. I'm not sure if it's correct though since I got the code from a random site.

Here is the source:

AxMatrix33 AxMatrixQuaternion( AxVector4* q )
AxMatrix33 out = {0};
float sqw = q->w * q->w;
float sqx = q->x * q->x;
float sqy = q->y * q->y;
float sqz = q->z * q->z;
float invs = 1 / (sqx + sqy + sqz + sqw);
out._11 = ( sqx - sqy - sqz + sqw) * invs;
out._22 = (-sqx + sqy - sqz + sqw) * invs;
out._33 = (-sqx - sqy + sqz + sqw) * invs;
float tmp1 = q->x * q->y;
float tmp2 = q->z * q->w;
out._21 = 2.0f * (tmp1 + tmp2) * invs;
out._12 = 2.0f * (tmp1 - tmp2) * invs;
tmp1 = q->x * q->z;
tmp2 = q->y * q->w;
out._31 = 2.0f * (tmp1 - tmp2) * invs;
out._13 = 2.0f * (tmp1 + tmp2) * invs;
tmp1 = q->y * q->z;
tmp2 = q->x * q->w;
out._32 = 2.0f * (tmp1 + tmp2) * invs;
out._23 = 2.0f * (tmp1 - tmp2) * invs;
return out;

Share this post

Link to post
Share on other sites
I didn't proof the code, but there are many references available online that show how to convert a quaternion to a rotation matrix. What I'd recommend is finding maybe four or five such references and checking your code against them. There's always a chance a reference will be incorrect, but if you check against several of them, you should be fine.

One variation you'll see is that some of the references will assume column vectors are being used, while others will assume row vectors are being used. So, if your indices are transposed relative to what you see in the reference, that's fine; it just means that the conventions are opposite.

That said, it *is* important to make sure your matrix is set up correctly for whatever convention you're using (row or column vectors). I've seen math libraries that have gotten this wrong (that is, the 'quaternion' matrix is transposed relative to what it should be). Here's how you can check that this is correct: for row vectors, the expression for matrix element 12 (using 1-based indexing) should incorporate an addition rather than a subtraction, and for column vectors, element 21 should incorporate an addition (pretty sure I got that right).

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!