initial commit, eq circuit emulator
[eqemu] / src / vmath.h
1 /*
2 eqemu - electronic queue system emulator
3 Copyright (C) 2014  John Tsiombikas <nuclear@member.fsf.org>,
4                     Eleni-Maria Stea <eleni@mutantstargoat.com>
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19 #ifndef VMATH_H_
20 #define VMATH_H_
21
22 #include <math.h>
23
24 class Vector2 {
25 public:
26         float x, y;
27
28         Vector2() : x(0), y(0) {}
29         Vector2(float xa, float ya) : x(xa), y(ya) {}
30
31         float &operator [](int idx) { return (&x)[idx]; }
32         const float &operator [](int idx) const { return (&x)[idx]; }
33 };
34
35 class Vector3 {
36 public:
37         float x, y, z;
38
39         Vector3() : x(0), y(0), z(0) {}
40         Vector3(float xa, float ya, float za) : x(xa), y(ya), z(za) {}
41
42         float &operator [](int idx) { return (&x)[idx]; }
43         const float &operator [](int idx) const { return (&x)[idx]; }
44 };
45
46 inline Vector3 operator +(const Vector3 &a, const Vector3 &b)
47 {
48         return Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
49 }
50
51 inline Vector3 operator -(const Vector3 &a, const Vector3 &b)
52 {
53         return Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
54 }
55
56 inline Vector3 operator *(const Vector3 &a, float s)
57 {
58         return Vector3(a.x * s, a.y * s, a.z * s);
59 }
60
61 inline float dot(const Vector3 &a, const Vector3 &b)
62 {
63         return a.x * b.x + a.y * b.y + a.z * b.z;
64 }
65
66 inline float length(const Vector3 &v)
67 {
68         return sqrt(dot(v, v));
69 }
70
71 inline Vector3 normalize(const Vector3 &v)
72 {
73         float len = length(v);
74         if(len == 0.0) {
75                 return v;
76         }
77         return Vector3(v.x / len, v.y / len, v.z / len);
78 }
79
80 class Vector4 {
81 public:
82         float x, y, z, w;
83
84         Vector4() : x(0), y(0), z(0), w(0) {}
85         Vector4(float xa, float ya, float za, float wa) : x(xa), y(ya), z(za), w(wa) {}
86
87         float &operator [](int idx) { return (&x)[idx]; }
88         const float &operator [](int idx) const {  return (&x)[idx]; }
89 };
90
91 class Ray {
92 public:
93         Vector3 origin, dir;
94
95         Ray() : origin(0, 0, 0), dir(0, 0, 1) {}
96         Ray(const Vector3 &o, const Vector3 &d) : origin(o), dir(d) {}
97 };
98
99 #endif  // VMATH_H_