summary refs log tree commit diff
path: root/src/Math/MVP.cpp
blob: dd5b5e7a213ecfb14e1f18fa431c72ec10721e70 (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
#include <cmath>
#include "MVP.hpp"
#include "Common.hpp"

namespace Math::MVP {

Matrix<4, 4> model(Vector<3> position, Rotation angles) {
    auto transformation = Matrix<4, 4>::transformation(position);
    auto rotation = Matrix<4, 4>::rotation(angles);

    return transformation * rotation;
}

Matrix<4, 4> view(Vector<3> position, Rotation angles) {
    auto rotation = Matrix<4, 4>::rotation(angles);
    auto transformation = Matrix<4, 4>::transformation(-position);

    return rotation * transformation;
}

Matrix<4, 4> perspective_projection(float aspect, float fov, float near, float far) {
    auto fov_radians = Math::radians(fov);

    float x_scale = 1.0f / (tan(fov_radians / 2.0f) * aspect);
    float y_scale = 1.0f / tan(fov_radians / 2.0f);

    float frustum_length = far - near;
    float z_near = -(far + near) / frustum_length;
    float z_far = -(2 * far * near) / frustum_length;

    Matrix<4, 4> projection{
        x_scale, 0.0f,    0.0f,   0.0f,
        0.0f,    y_scale, 0.0f,   0.0f,
        0.0f,    0.0f,    z_near, z_far,
        0.0f,    0.0f,    -1.0f,   0.0f,
    };

    return projection;
}

Matrix<4, 4> orthographic_projection(float width, float height, float near, float far) {
    float x_scale = 2.0f / width;
    float y_scale = 2.0f / -height;

    float frustum_length = far - near;
    float z_near = -(far + near) / frustum_length;
    float z_far = -2 / frustum_length;

    Matrix<4, 4> projection{
            x_scale, 0.0f,    0.0f,   -1.0f,
            0.0f,    y_scale, 0.0f,   1.0f,
            0.0f,    0.0f,    z_near, z_far,
            0.0f,    0.0f,    0.0f,   1.0f,
    };

    return projection;
}

}