aboutsummaryrefslogtreecommitdiff
path: root/src/core/vector.cpp
blob: 51d8e2e14262419b6d23988a18885a722178374a (plain)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include "vector.hpp"

#include <math.h>
#include <stdexcept>

Vec3d::Vec3d() {
    set(0, 0, 0);
}

Vec3d::Vec3d(double x, double y, double z) {
    set(x, y, z);
}

void Vec3d::set(double x, double y, double z) {
    m_x = x;
    m_y = y;
    m_z = z;
}

void Vec3d::normalize() {
    auto len = length();
    if (len == 0) {
        throw std::runtime_error("Normalizing zero vector");
    }

    m_x /= len;
    m_y /= len;
    m_z /= len;
}

double Vec3d::length() const {
    return sqrt(m_x * m_x + m_y * m_y + m_z * m_z);
}

double Vec3d::dot(const Vec3d &vec) const {
    return m_x * vec.m_x + m_y * vec.m_y + m_z * vec.m_z;
}

Vec3d Vec3d::cross(const Vec3d &vec) const {
    return Vec3d(
        m_y * vec.m_z - m_z * vec.m_y,
        m_z * vec.m_x - m_x * vec.m_z,
        m_x * vec.m_y - m_y * vec.m_x
        );
}

Vec3d Vec3d::operator+(const Vec3d &vec) const {
    return Vec3d(
            m_x + vec.m_x, 
            m_y + vec.m_y,
            m_z + vec.m_z
            );
}

Vec3d& Vec3d::operator+=(const Vec3d &vec) {
    m_x += vec.m_x;
    m_y += vec.m_y;
    m_z += vec.m_z;
    return *this;
}

Vec3d Vec3d::operator-(const Vec3d &vec) const {
    return Vec3d(
            m_x - vec.m_x, 
            m_y - vec.m_y,
            m_z - vec.m_z
            );
}

Vec3d Vec3d::operator-() const {
    return Vec3d(
            -m_x,
            -m_y,
            -m_z
            );
}


Vec3d Vec3d::operator*(double op) const {
    return Vec3d(
            m_x * op,
            m_y * op,
            m_z * op
            );
}

Vec3d Vec3d::operator*(const Vec3d &vec) const {
    return Vec3d(
            m_x * vec.m_x,
            m_y * vec.m_y,
            m_z * vec.m_z
            );
}

Vec3d Vec3d::operator/(double op) const {
    return Vec3d(
            m_x / op,
            m_y / op,
            m_z / op
            );
}

std::ostream& operator<<(std::ostream &out, const Vec3d &v){
    out << "[ " << v.m_x << ", " << v.m_y << ", " << v.m_z << " ]";
    return out;
}