Acheron
Loading...
Searching...
No Matches
matrix4.hpp
1#pragma once
2
3#include <cmath>
4
5#pragma once
6
7#include <cmath>
8#include <cstddef>
9
10namespace acheron {
14 struct Matrix4 {
15 float data[16] = {};
16
17 float& operator[](std::size_t idx) { return data[idx]; }
18 const float& operator[](std::size_t idx) const { return data[idx]; }
19
20 operator float*() { return data; }
21 operator const float*() const { return data; }
22
23 Matrix4 operator*(const Matrix4& other) const {
24 return Matrix4::Multiply(*this, other);
25 }
26
27 static Matrix4 Identity() {
28 Matrix4 m{};
29 m[0] = m[5] = m[10] = m[15] = 1.0f;
30 return m;
31 }
32
33 static Matrix4 Translate(float x, float y, float z) {
34 Matrix4 m = Identity();
35 m[12] = x;
36 m[13] = y;
37 m[14] = z;
38 return m;
39 }
40
41 static Matrix4 Scale(float sx, float sy, float sz) {
42 Matrix4 m = Identity();
43 m[0] = sx;
44 m[5] = sy;
45 m[10] = sz;
46 return m;
47 }
48
49 static Matrix4 RotateZ(float radians) {
50 float c = std::cos(radians);
51 float s = std::sin(radians);
52 Matrix4 m = Identity();
53 m[0] = c; m[1] = s;
54 m[4] = -s; m[5] = c;
55 return m;
56 }
57
58 static Matrix4 Multiply(const Matrix4& a, const Matrix4& b) {
59 Matrix4 result{};
60 for(int row = 0; row < 4; ++row) {
61 for(int col = 0; col < 4; ++col) {
62 result[col + row * 4] =
63 a[0 + row * 4] * b[col + 0 * 4] +
64 a[1 + row * 4] * b[col + 1 * 4] +
65 a[2 + row * 4] * b[col + 2 * 4] +
66 a[3 + row * 4] * b[col + 3 * 4];
67 }
68 }
69 return result;
70 }
71
72 static Matrix4 Ortho(float width, float height) {
73 Matrix4 m{};
74 m[0] = 2.0f / width;
75 m[5] = 2.0f / height;
76 m[10] = -1.0f;
77 m[12] = -1.0f;
78 m[13] = -1.0f;
79 m[15] = 1.0f;
80 return m;
81 }
82
83 static Matrix4 OrthoTopLeft(float width, float height) {
84 Matrix4 m{};
85 m[0] = 2.0f / width;
86 m[5] = -2.0f / height;
87 m[10] = -1.0f;
88 m[12] = -1.0f;
89 m[13] = 1.0f;
90 m[15] = 1.0f;
91 return m;
92 }
93 };
94
95}