1 | // |
---|
2 | // Lol Engine |
---|
3 | // |
---|
4 | // Copyright: (c) 2010-2011 Sam Hocevar <sam@hocevar.net> |
---|
5 | // This program is free software; you can redistribute it and/or |
---|
6 | // modify it under the terms of the Do What The Fuck You Want To |
---|
7 | // Public License, Version 2, as published by Sam Hocevar. See |
---|
8 | // http://sam.zoy.org/projects/COPYING.WTFPL for more details. |
---|
9 | // |
---|
10 | |
---|
11 | // |
---|
12 | // The Matrix classes |
---|
13 | // ------------------ |
---|
14 | // |
---|
15 | |
---|
16 | #if !defined __DH_MATRIX_H__ |
---|
17 | #define __DH_MATRIX_H__ |
---|
18 | |
---|
19 | #include <cmath> |
---|
20 | |
---|
21 | #define VECTOR_OP(elems, op) \ |
---|
22 | inline Vec##elems<T> operator op(Vec##elems<T> const &val) const \ |
---|
23 | { \ |
---|
24 | Vec##elems<T> ret; \ |
---|
25 | for (int n = 0; n < elems; n++) \ |
---|
26 | ret[n] = (*this)[n] op val[n]; \ |
---|
27 | return ret; \ |
---|
28 | } |
---|
29 | |
---|
30 | #define SCALAR_OP(elems, op) \ |
---|
31 | inline Vec##elems<T> operator op(T const &val) const \ |
---|
32 | { \ |
---|
33 | Vec##elems<T> ret; \ |
---|
34 | for (int n = 0; n < elems; n++) \ |
---|
35 | ret[n] = (*this)[n] op val; \ |
---|
36 | return ret; \ |
---|
37 | } |
---|
38 | |
---|
39 | #define OPERATORS(elems) \ |
---|
40 | T& operator[](int n) { return *(&x + n); } \ |
---|
41 | T const& operator[](int n) const { return *(&x + n); } \ |
---|
42 | \ |
---|
43 | VECTOR_OP(elems, -) \ |
---|
44 | VECTOR_OP(elems, +) \ |
---|
45 | VECTOR_OP(elems, *) \ |
---|
46 | VECTOR_OP(elems, /) \ |
---|
47 | \ |
---|
48 | SCALAR_OP(elems, -) \ |
---|
49 | SCALAR_OP(elems, +) \ |
---|
50 | SCALAR_OP(elems, *) \ |
---|
51 | SCALAR_OP(elems, /) \ |
---|
52 | \ |
---|
53 | inline float len() const \ |
---|
54 | { \ |
---|
55 | T acc = 0; \ |
---|
56 | for (int n = 0; n < elems; n++) \ |
---|
57 | acc += (*this)[n] * (*this)[n]; \ |
---|
58 | return sqrtf((float)acc); \ |
---|
59 | } |
---|
60 | |
---|
61 | template <typename T> struct Vec2 |
---|
62 | { |
---|
63 | Vec2() { x = y = 0; } |
---|
64 | Vec2(T _x, T _y) { x = _x; y = _y; } |
---|
65 | |
---|
66 | OPERATORS(2) |
---|
67 | |
---|
68 | union { T x; T a; T i; }; |
---|
69 | union { T y; T b; T j; }; |
---|
70 | }; |
---|
71 | |
---|
72 | typedef Vec2<float> Float2; |
---|
73 | typedef Vec2<int> Int2; |
---|
74 | |
---|
75 | template <typename T> struct Vec3 |
---|
76 | { |
---|
77 | Vec3() { x = y = z = 0; } |
---|
78 | Vec3(T _x, T _y, T _z) { x = _x; y = _y; z = _z; } |
---|
79 | |
---|
80 | OPERATORS(3) |
---|
81 | |
---|
82 | union { T x; T a; T i; }; |
---|
83 | union { T y; T b; T j; }; |
---|
84 | union { T z; T c; T k; }; |
---|
85 | }; |
---|
86 | |
---|
87 | typedef Vec3<float> Float3; |
---|
88 | typedef Vec3<int> Int3; |
---|
89 | |
---|
90 | #endif // __DH_MATRIX_H__ |
---|
91 | |
---|