|
1 /* |
|
2 * C++ RayTracer |
|
3 * file: vector.h |
|
4 * |
|
5 * Radek Brich, 2006 |
|
6 */ |
|
7 |
|
8 #ifndef VECTOR_H |
|
9 #define VECTOR_H |
|
10 |
|
11 #include <math.h> |
|
12 #include <iostream> |
|
13 |
|
14 using namespace std; |
|
15 |
|
16 class Vector3 |
|
17 { |
|
18 public: |
|
19 // data |
|
20 union { |
|
21 struct { |
|
22 float x, y, z; |
|
23 }; |
|
24 struct { |
|
25 float r, g, b; |
|
26 }; |
|
27 float cell[3]; |
|
28 }; |
|
29 |
|
30 // constructors |
|
31 Vector3(): x(0.0f), y(0.0f), z(0.0f) {}; |
|
32 Vector3(float ax, float ay, float az): x(ax), y(ay), z(az) {}; |
|
33 |
|
34 // index operator |
|
35 float &operator[](int index) { return cell[index]; }; |
|
36 |
|
37 // normalize |
|
38 Vector3 normalize() |
|
39 { |
|
40 float f = 1.0f / mag(); |
|
41 x *= f; |
|
42 y *= f; |
|
43 z *= f; |
|
44 return *this; |
|
45 } |
|
46 |
|
47 // get normalized copy |
|
48 Vector3 unit() |
|
49 { |
|
50 Vector3 u(*this); |
|
51 return u.normalize();; |
|
52 } |
|
53 |
|
54 // square magnitude, magnitude |
|
55 float mag2() { return x * x + y * y + z * z; } |
|
56 float mag() { return sqrtf(mag2()); } |
|
57 |
|
58 // negative |
|
59 Vector3 operator-() { return Vector3(-x, -y, -z); } |
|
60 |
|
61 // accumulate |
|
62 Vector3 operator+=(const Vector3 &v) |
|
63 { |
|
64 x += v.x; |
|
65 y += v.y; |
|
66 z += v.z; |
|
67 return *this; |
|
68 }; |
|
69 |
|
70 // sum |
|
71 friend Vector3 operator+(const Vector3 &a, const Vector3 &b) |
|
72 { |
|
73 return Vector3(a.x + b.x, a.y + b.y, a.z + b.z); |
|
74 }; |
|
75 |
|
76 // difference |
|
77 friend Vector3 operator-(const Vector3 &a, const Vector3 &b) |
|
78 { |
|
79 return Vector3(a.x - b.x, a.y - b.y, a.z - b.z); |
|
80 }; |
|
81 |
|
82 // dot product |
|
83 friend float dot(const Vector3 &a, const Vector3 &b) |
|
84 { |
|
85 return a.x * b.x + a.y * b.y + a.z * b.z; |
|
86 }; |
|
87 |
|
88 // cross product |
|
89 friend Vector3 cross(const Vector3 &a, const Vector3 &b) |
|
90 { |
|
91 return Vector3(a.y * b.z - a.z * b.y, |
|
92 a.z * b.x - a.x * b.z, |
|
93 a.x * b.y - a.y * b.x); |
|
94 }; |
|
95 |
|
96 // product of vector and scalar |
|
97 Vector3 operator*(const float &f) |
|
98 { |
|
99 return Vector3(f * x, f * y, f * z); |
|
100 } |
|
101 |
|
102 friend Vector3 operator*(const float &f, Vector3 &v) |
|
103 { |
|
104 return v * f; |
|
105 }; |
|
106 |
|
107 // cell by cell product (only usable for colours) |
|
108 friend Vector3 operator*(const Vector3 &a, const Vector3 &b) |
|
109 { |
|
110 return Vector3(a.x * b.x, a.y * b.y, a.z * b.z); |
|
111 }; |
|
112 |
|
113 // print |
|
114 friend ostream & operator<<(ostream &st, const Vector3 &v) |
|
115 { |
|
116 return st << "(" << v.x << ", " << v.y << ", " << v.z << ")"; |
|
117 } |
|
118 }; |
|
119 |
|
120 typedef Vector3 Colour; |
|
121 |
|
122 #endif |