Hello,
Before you get scared away - my issue does not particular seem to relate to Quaternions or Vectors.
More generally, it appears to be something compiler or C++ standard related, as my return call from the function is acting strange. You can eventually start reading the concluding issue at the bottom.
Thank you so much!
So I've got this class with Quaternion mathematics.
This particular function (operator *) is to rotate a Vector3 based on the current Quaternion.
Here's the code I want to discuss.
Vector3 Class
class Vector3
{
float y, z, x;
...
};
Vector3 Vector3::crossProduct(const Vector3& rkVector) const
{
return Vector3(
y * rkVector.z - z * rkVector.y,
z * rkVector.x - x * rkVector.z,
x * rkVector.y - y * rkVector.x);
}
const Vector3 Vector3::operator +(const Vector3& arg) const
{
return Vector3(x+arg.x, y+arg.y, z+arg.z);
}
Quaternion Class
class Quaternion
{
float x, y, z;
...
};
Vector3 Quaternion::operator *(const Vector3& v) const
{
Vector3 v2, v3;
Vector3 qvec(x, y, z);
v2 = qvec.crossProduct(v);
v3 = qvec.crossProduct(v2);
v2 *= (2.0f * w);
v3 *= 2.0f;
Vector3 pre_result = v + v2 + v3;
Vector3 result = pre_result;
return result;
}
I have a Quaternion as so:
Quaternion q(0.0120516298, 0.594058931, -0.00890144333, 0.804294169); // x, y, z, w
I then call the * operator:
Vector3 v = q * Vector3(0, 0, -1);
First issue appears when checking value v in debugger. The value seems to be
x = -nan(0x7fe450), y = 4.59163468e-41, z = 4.76441478e-44
This is not good.
I dive into the operator* function with my beloved debugger...
Note: I'm typing what I see, in comment on the line where I'm reaching a breakpoint. Also note, that x, y, z and w are the values set on construction time of the quaternion.
Vector3 Quaternion::operator *(const Vector3& v) const
{
Vector3 v2, v3;
Vector3 qvec(x, y, z); // v(0, 0, -1), v2(0, 0, 0), v3(0, 0, 0)
v2 = qvec.crossProduct(v); // qvec(0.0120516298, 0.594058931, -0.00890144333)
v3 = qvec.crossProduct(v2); // v2(-0.594058931, 0.0120516298, 0)
v2 *= (2.0f * w); // v3(0.0001007276901, 0.00528798206, 0.353051275)
v3 *= 2.0f; // v2(-0.955596268, 0.0193861108, 0)
Vector3 pre_result = v + v2 + v3; // v3(0.000214553802, 0.0105759641, 0.70610255)
Vector3 result = pre_result; // IMPORTANT: pre_result(-0.955381691, 0.029962074, -0.29389745)
return result; // IMPORTANT: result(-nan(0x7fe260), 4.59163468e-41, -nan(0x7fe230)) - SO WHY ISN'T THIS THE SAME AS pre_result?
}
- Issue Conclusion
The returned value, stored in a Vector3 equals the (junk) value of "result".
I've spent 4½ hour trying to figure out, why I'm not getting a sane value returned.
The values are just looking fine in pre_result then all of a sudden they are junk.
I tried many variations, but actually no matter what variable I pass to return, it is just turned into junk.
I tried cleaning and rebuilding my project.
I'm using GDB and G++ through Make.
PLEASE! Give me your advice or suggestion on this issue.