-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vec3.cpp
82 lines (66 loc) · 2.06 KB
/
Vec3.cpp
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
77
78
79
80
81
82
#include <cmath>
#include "Vec3.h"
Vec3::Vec3(): e{0.0, 0.0, 0.0} {}
Vec3::Vec3(float x, float y, float z): e{x, y, z} {};
Vec3::Vec3(const Vec3& other) : e(other.e) {};
Vec3& Vec3::operator=(const Vec3& other) {
e = other.e;
return *this;
}
float Vec3::operator[](int i) const { return e[i]; }
float& Vec3::operator[](int i) { return e[i]; }
Vec3 operator+(const Vec3& u, const Vec3& v) { return Vec3(u[0] + v[0], u[1] + v[1], u[2] + v[2]); }
Vec3 operator-(const Vec3& u, const Vec3& v) { return Vec3(u[0] - v[0], u[1] - v[1], u[2] - v[2]); }
Vec3 operator*(const Vec3& v, float s) { return Vec3(v[0] * s, v[1] * s, v[2] * s); }
Vec3 operator*(float s, const Vec3& u) { return u * s; }
Vec3 operator*(const Vec3& u, const Vec3& v) { return Vec3(u[0] * v[0], u[1] * v[1], u[2] * v[2]); }
Vec3 operator/(const Vec3& v, float s) { return Vec3(v[0] / s, v[1] / s, v[2] / s); }
Vec3& Vec3::operator+=(const Vec3& v) {
e[0] += v[0];
e[1] += v[1];
e[2] += v[2];
return *this;
}
Vec3& Vec3::operator-=(const Vec3& v) {
e[0] -= v[0];
e[1] -= v[1];
e[2] -= v[2];
return *this;
}
Vec3& Vec3::operator*=(float s) {
e[0] *= s;
e[1] *= s;
e[2] *= s;
return *this;
}
Vec3& Vec3::operator/=(float s) {
e[0] /= s;
e[1] /= s;
e[2] /= s;
return *this;
}
float Vec3::length_squared() const { return e[0]*e[0] + e[1]*e[1] + e[2]*e[2]; }
float Vec3::length() const { return std::sqrt(length_squared()); }
void Vec3::rotate_y(float a) {
float tmp0(e[0]);
const float sina = std::sin(a);
const float cosa = std::cos(a);
e[0] = e[0] * cosa + e[2] * sina;
e[2] = e[2] * cosa - tmp0 * sina;
}
float dot(const Vec3&u, const Vec3& v) { return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; }
Vec3 cross(const Vec3& u, const Vec3& v) {
return Vec3(u[1] * v[2] - u[2] * v[1],
u[2] * v[0] - u[0] * v[2],
u[0] * v[1] - u[1] * v[0]);
}
Vec3 unit_vector(Vec3 v) { return v / v.length(); }
/*
void rotate(Vec3& u, float angle) {
float s = std::sin(angle);
float c = std::cos(angle);
float tempx = u[0];
u[0] = u[0] * c - u[1] * s;
u[1] = tempx * s + u[1] * c;
}
*/