-
Notifications
You must be signed in to change notification settings - Fork 2
/
gwQuaternion.cpp
executable file
·82 lines (65 loc) · 2.21 KB
/
gwQuaternion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*************************************************************************\
Engine: gearWorks
File: gwQuaternion.cpp
Author: Zachry Thayer
Description: implements quaternions
Requires:
\*************************************************************************/
#include "gwQuaternion.h"
gwQuaternion::gwQuaternion()
{
m_x = m_y = m_z = 0.0f;
m_w = 1.0f;
}
gwQuaternion::~gwQuaternion()
{
}
void gwQuaternion::createFromAxisAngle(float x, float y, float z, float degrees)
{
// First we want to convert the degrees to radians
// since the angle is assumed to be in radians
float angle = float((degrees / 180.0f) * PI);
// Here we calculate the sin( theta / 2) once for optimization
float result = (float)sin( angle / 2.0f );
// Calcualte the w value by cos( theta / 2 )
m_w = (float)cos( angle / 2.0f );
// Calculate the x, y and z of the quaternion
m_x = float(x * result);
m_y = float(y * result);
m_z = float(z * result);
}
void gwQuaternion::createMatrix(float *pMatrix)
{
// Make sure the matrix has allocated memory to store the rotation data
if(!pMatrix) return;
// First row
pMatrix[ 0] = 1.0f - 2.0f * ( m_y * m_y + m_z * m_z );
pMatrix[ 1] = 2.0f * (m_x * m_y + m_z * m_w);
pMatrix[ 2] = 2.0f * (m_x * m_z - m_y * m_w);
pMatrix[ 3] = 0.0f;
// Second row
pMatrix[ 4] = 2.0f * ( m_x * m_y - m_z * m_w );
pMatrix[ 5] = 1.0f - 2.0f * ( m_x * m_x + m_z * m_z );
pMatrix[ 6] = 2.0f * (m_z * m_y + m_x * m_w );
pMatrix[ 7] = 0.0f;
// Third row
pMatrix[ 8] = 2.0f * ( m_x * m_z + m_y * m_w );
pMatrix[ 9] = 2.0f * ( m_y * m_z - m_x * m_w );
pMatrix[10] = 1.0f - 2.0f * ( m_x * m_x + m_y * m_y );
pMatrix[11] = 0.0f;
// Fourth row
pMatrix[12] = 0;
pMatrix[13] = 0;
pMatrix[14] = 0;
pMatrix[15] = 1.0f;
// Now pMatrix[] is a 4x4 homogeneous matrix that can be applied to an OpenGL Matrix
}
gwQuaternion gwQuaternion::operator *(gwQuaternion q)
{
gwQuaternion r;
r.m_w = m_w*q.m_w - m_x*q.m_x - m_y*q.m_y - m_z*q.m_z;
r.m_x = m_w*q.m_x + m_x*q.m_w + m_y*q.m_z - m_z*q.m_y;
r.m_y = m_w*q.m_y + m_y*q.m_w + m_z*q.m_x - m_x*q.m_z;
r.m_z = m_w*q.m_z + m_z*q.m_w + m_x*q.m_y - m_y*q.m_x;
return(r);
}