A (properly) working Matrix to Euler Angels conversion!! (matrix4::getRotationDegrees())
This was a hard one because a) it took a while to find out that the bug is actually in that function b) the function was working "a little bit". Like sometimes you would get proper results, sometimes not. And c) because it's hard to tell if the result is ok, because the conversion from matrix to euler is not always unique.
To visualize I took 2 reference objects (each consisting of a red x, a green y and a blue z arrow according to the axes), placed them next to each other and rotated them arbitrarilly in all axes in a wild fashion (via the keyboard). The first directly with euler angels, the second with the result of getRotationDegrees(matrix.setRotationDegrees(theSameEulerAngels)). The old function would not always be in sync.
Here's an impression:

Also I made everything double precision (f64) for better accuracy!
Now here is the fixed function with the changes pointed out:
matrix4.h:
Code: Select all
inline core::vector3df matrix4::getRotationDegrees() const
{
const matrix4 &mat = *this;
f64 Y = -asin(mat(2,0));
f64 D = Y;
f64 C = cos(Y);
Y *= GRAD_PI; // <- this was "180.000f/PI" before
// (not part of the bug)
f64 rotx, roty, X, Z;
if (fabs(C)>0.0005f) // <- C not Y
{
rotx = mat(2,2) / C;
roty = mat(2,1) / C;
X = atan2( roty, rotx ) * GRAD_PI;
rotx = mat(0,0) / C;
roty = mat(1,0) / C;
Z = atan2( roty, rotx ) * GRAD_PI;
}
else
{
X = 0.0f;
rotx = mat(1,1); // <- no minus here
roty = -mat(0,1); // <- but here, and not (1,0)
Z = atan2( roty, rotx ) * (f32)GRAD_PI;
}
// fix values that get below zero
// before it would set (!) values to 360
// that where above 360:
if (X < 0.00f) X += 360.00;
if (Y < 0.00f) Y += 360.00;
if (Z < 0.00f) Z += 360.00;
return vector3df((f32)X,(f32)Y,(f32)Z);
}
What also helped is the "The Matrix and Quaternions FAQ". I recommend this one:
http://www.j3d.org/matrix_faq/matrfaq_latest.html
because it's the most up to date that I could find (Version 1.21 30th November 2003). It also has a version history.
Have fun rotating!
Jonas
ps: I still have other issues with matrix4.h, but more about that in a later post...
pps: Niko, your engine rocks! I really appreciate your hard work and it's just a pleasure for me to contribute things that make it better and less bogus! Thank you!