-
Notifications
You must be signed in to change notification settings - Fork 0
/
quaternion.cpp
130 lines (107 loc) · 2.25 KB
/
quaternion.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include "quaternion.h"
std::ostream& operator<<(std::ostream& out, Quaternion q)
{
std::cout << q.s << "(" << q.v.x << "," << q.v.y << "," << q.v.z << ")" << std::endl;
return out;
}
Quaternion::Quaternion()
{
s = 1.0f;
v = glm::vec3(0.0f);
}
Quaternion& Quaternion::operator=(const Quaternion& rhs)
{
this->s = rhs.s;
this->v = rhs.v;
return *this;
}
Quaternion::Quaternion(const Quaternion& obj)
{
*this = obj;
}
Quaternion::Quaternion(glm::vec3 image)
{
s = 0.0f;
v = image;
}
Quaternion::Quaternion(float real, glm::vec3 image)
{
s = real;
v = image;
}
Quaternion::~Quaternion()
{
}
float Quaternion::Dot(Quaternion rhs)
{
return s * rhs.s + glm::dot(v, rhs.v);
}
float Quaternion::Length()
{
return sqrt(SqrLength());
}
float Quaternion::SqrLength()
{
return s * s + glm::dot(v, v);
}
void Quaternion::Normalize()
{
float invLength = 1.0f / Length();
s *= invLength;
v *= invLength;
}
Quaternion Quaternion::Normalized()
{
float invLength = 1.0f / Length();
Quaternion normalized(s, v);
normalized.s *= invLength;
normalized.v *= invLength;
return normalized;
}
Quaternion Quaternion::Scale(float c)
{
return Quaternion(s * c, v * c);
}
Quaternion Quaternion::Inverse()
{
Quaternion conjugate(this->s, -this->v);
return conjugate.Scale(1.0f / SqrLength());
}
Quaternion Quaternion::operator+(Quaternion rhs)
{
Quaternion result;
result.s = s + rhs.s;
result.v = v + rhs.v;
return result;
}
Quaternion Quaternion::operator*(Quaternion rhs)
{
Quaternion result;
result.s = s * rhs.s - glm::dot(v, rhs.v);
result.v = s * rhs.v + v * rhs.s + glm::cross(v, rhs.v);
return result;
}
Quaternion Quaternion::operator*(glm::vec3 rhs)
{
return operator*(Quaternion(rhs));
}
void quatTest()
{
Quaternion q1(0.7f, glm::vec3(0, 0.8f, 2.9f));
Quaternion q2(glm::vec3(0, 0.2f, 2.1f));
Quaternion q3 = q1.Normalized();
q2.Normalize();
Quaternion q4 = q1.Inverse();
Quaternion q5 = q2 * q2.Inverse();
Quaternion q6 = q3 * q3.Inverse();
Quaternion q7 = q2 * q3.v;
std::cout << q1 << std::endl;
std::cout << q2 << std::endl;
std::cout << q3 << std::endl;
std::cout << q4 << std::endl;
std::cout << q5 << std::endl;
std::cout << q6 << std::endl;
std::cout << q7 << std::endl;
std::cout << q1 << std::endl;
std::cout << q2 << std::endl;
}