Skip to content

Instantly share code, notes, and snippets.

@andrey-str
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrey-str/ee07947562ac6c559d28 to your computer and use it in GitHub Desktop.
Save andrey-str/ee07947562ac6c559d28 to your computer and use it in GitHub Desktop.
a bit of quaternions algebra;
SCNQuaternion CalculateRotation(CMRotationMatrix a){
SCNQuaternion q;
float trace = a.m11 + a.m22 + a.m33; // I removed + 1.0f; see discussion with Ethan
if( trace > 0 ) { // I changed M_EPSILON to 0
float s = 0.5f / sqrtf(trace + 1.0f);
q.w = 0.25f / s;
q.x = ( a.m32 - a.m23 ) * s;
q.y = ( a.m13 - a.m31 ) * s;
q.z = ( a.m21 - a.m12 ) * s;
}
else{
if ( a.m11 > a.m22 && a.m11 > a.m33 ) {
float s = 2.0f * sqrtf( 1.0f + a.m11 - a.m22 - a.m33);
q.w = (a.m32 - a.m23 ) / s;
q.x = 0.25f * s;
q.y = (a.m12 + a.m21 ) / s;
q.z = (a.m13 + a.m31 ) / s;
}
else if (a.m22 > a.m33) {
float s = 2.0f * sqrtf( 1.0f + a.m22 - a.m11 - a.m33);
q.w = (a.m13 - a.m31 ) / s;
q.x = (a.m12 + a.m21 ) / s;
q.y = 0.25f * s;
q.z = (a.m23 + a.m32 ) / s;
}
else {
float s = 2.0f * sqrtf( 1.0f + a.m33 - a.m11 - a.m22 );
q.w = (a.m21 - a.m12 ) / s;
q.x = (a.m13 + a.m31 ) / s;
q.y = (a.m23 + a.m32 ) / s;
q.z = 0.25f * s;
}
}
return q;
}
SCNQuaternion mulQuaternions(SCNQuaternion q1, SCNQuaternion q2){
SCNQuaternion q;
q.x = q1.x * q2.w + q1.y * q2.z - q1.z * q2.y + q1.w * q2.x;
q.y = -q1.x * q2.z + q1.y * q2.w + q1.z * q2.x + q1.w * q2.y;
q.z = q1.x * q2.y - q1.y * q2.x + q1.z * q2.w + q1.w * q2.z;
q.w = -q1.x * q2.x - q1.y * q2.y - q1.z * q2.z + q1.w * q2.w;
return q;
}
GLKQuaternion GLKQuaternionFromSCNVector4(SCNVector4 v){
return GLKQuaternionMake(v.x, v.y, v.z, v.w);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment