-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vector3.h
76 lines (67 loc) · 2.47 KB
/
Vector3.h
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
#ifndef RAY_TRACER_VECTOR3_H
#define RAY_TRACER_VECTOR3_H
#include <cmath>
class Vector3 {
public:
float x, y, z;
Vector3() : x(0), y(0), z(0) {}
Vector3(float x, float y, float z) : x(x), y(y), z(z) {}
Vector3 operator+(const Vector3& v) const { return Vector3(x + v.x, y + v.y, z + v.z); }
Vector3 operator-(const Vector3& v) const { return Vector3(x - v.x, y - v.y, z - v.z); }
float dot(const Vector3& v) const { return x * v.x + y * v.y + z * v.z; }
Vector3 cross(const Vector3& v) const { return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); }
float length() const { return std::sqrt(x * x + y * y + z * z); }
Vector3 normalize() const { return *this / length(); }
Vector3 operator*(float scalar) const { return Vector3(x * scalar, y * scalar, z * scalar); }
friend Vector3 operator*(float scalar, const Vector3& v) { return Vector3(scalar * v.x, scalar * v.y, scalar * v.z); }
Vector3 operator/(float scalar) const { return Vector3(x / scalar, y / scalar, z / scalar); }
Vector3 operator-() const { return Vector3(-x, -y, -z); }
Vector3& operator+=(const Vector3& v) {
x += v.x;
y += v.y;
z += v.z;
return *this;
}
Vector3& operator-=(const Vector3& v) {
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
Vector3& operator*=(float scalar) {
x *= scalar;
y *= scalar;
z *= scalar;
return *this;
}
Vector3& operator/=(float scalar) {
x /= scalar;
y /= scalar;
z /= scalar;
return *this;
}
// Comparison operators
bool operator==(const Vector3& v) const {
const float epsilon = 1e-5f;
return std::fabs(x - v.x) < epsilon &&
std::fabs(y - v.y) < epsilon &&
std::fabs(z - v.z) < epsilon;
}
bool operator!=(const Vector3& v) const {
return !(*this == v);
}
friend std::ostream& operator<<(std::ostream& os, const Vector3& v) {
os << "(" << v.x << ", " << v.y << ", " << v.z << ")";
return os;
}
Vector3 operator*(const Vector3& v) const { return Vector3(x * v.x, y * v.y, z * v.z); }
void clamp() {
x = std::min(std::max(x, 0.0f), 1.0f);
y = std::min(std::max(y, 0.0f), 1.0f);
z = std::min(std::max(z, 0.0f), 1.0f);
}
bool isBlack() const { // For debugging
return x == 0.0f && y == 0.0f && z == 0.0f;
}
};
#endif //RAY_TRACER_VECTOR3_H