graphene

view gmath/vec.h @ 1:f85a59195206

foo
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 24 Jul 2015 01:28:00 +0300
parents
children
line source
1 #ifndef GMATH_VEC_H_
2 #define GMATH_VEC_H_
4 #include <math.h>
6 namespace gmath {
8 class Vec3 {
9 public:
10 float x, y, z;
12 Vec3() : x(0), y(0), z(0) {}
13 Vec3(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {}
15 void normalize()
16 {
17 float len = length(*this);
18 if(len != 0.0f) {
19 x /= len;
20 y /= len;
21 z /= len;
22 }
23 }
24 };
26 inline Vec3 operator +(const Vec3 &a, const Vec3 &b)
27 {
28 return Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
29 }
31 inline Vec3 operator -(const Vec3 &a, const Vec3 &b)
32 {
33 return Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
34 }
36 inline Vec3 operator *(const Vec3 &a, const Vec3 &b)
37 {
38 return Vec3(a.x * b.x, a.y * b.y, a.z * b.z);
39 }
41 inline Vec3 operator /(const Vec3 &a, const Vec3 &b)
42 {
43 return Vec3(a.x / b.x, a.y / b.y, a.z / b.z);
44 }
46 inline Vec3 operator *(const Vec3 &v, float s)
47 {
48 return Vec3(v.x * s, v.y * s, v.z * s);
49 }
51 inline Vec3 operator *(float s, const Vec3 &v)
52 {
53 return Vec3(s * v.x, s * v.y, s * v.z);
54 }
56 inline Vec3 operator /(const Vec3 &v, float s)
57 {
58 return Vec3(v.x / s, v.y / s, v.z / s);
59 }
61 inline Vec3 operator /(float s, const Vec3 &v)
62 {
63 return Vec3(s / v.x, s / v.y, s / v.z);
64 }
66 inline Vec3 &operator +=(Vec3 &a, const Vec3 &b)
67 {
68 a.x += b.x;
69 a.y += b.y;
70 a.z += b.z;
71 return *this;
72 }
74 inline Vec3 &operator -=(Vec3 &a, const Vec3 &b)
75 {
76 a.x -= b.x;
77 a.y -= b.y;
78 a.z -= b.z;
79 return *this;
80 }
82 inline Vec3 &operator *=(Vec3 &a, const Vec3 &b)
83 {
84 a.x *= b.x;
85 a.y *= b.y;
86 a.z *= b.z;
87 return *this;
88 }
90 inline Vec3 &operator /=(Vec3 &a, const Vec3 &b)
91 {
92 a.x /= b.x;
93 a.y /= b.y;
94 a.z /= b.z;
95 return *this;
96 }
98 inline Vec3 &operator *=(Vec3 &v, float s)
99 {
100 v.x *= s;
101 v.y *= s;
102 v.z *= s;
103 return *this;
104 }
106 inline Vec3 &operator /=(Vec3 &v, float s)
107 {
108 v.x /= s;
109 v.y /= s;
110 v.z /= s;
111 return *this;
112 }
114 inline float dot(const Vec3 &a, const Vec3 &b)
115 {
116 return a.x * b.x + a.y * b.y + a.z * b.z;
117 }
119 inline Vec3 cross(const Vec3 &a, const Vec3 &b)
120 {
121 return Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
122 }
124 inline float length(const Vec3 &v)
125 {
126 return (float)sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
127 }
129 inline float length_sq(const Vec3 &v)
130 {
131 return v.x * v.x + v.y * v.y + v.z * v.z;
132 }
134 inline Vec3 normalize(const Vec3 &v)
135 {
136 float len = length(v);
137 if(len == 0.0f) {
138 return v;
139 }
141 return Vec3(v.x / len, v.y / len, v.z / len);
142 }
144 }
146 #endif /* GMATH_VEC_H_ */