SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
Matrix.hpp
Go to the documentation of this file.
1#ifndef _MATRIX_H_
2#define _MATRIX_H_
3
4#include <Core/OSDef.hpp>
5#include <cassert>
6#include <iomanip>
7#include <iostream>
8#include <stdexcept>
9#include <type_traits>
10
11#include "Math.hpp"
12#include "Quaternion.hpp"
13#include "Vector.hpp"
14
15namespace Sleak {
16namespace Math {
17/// Row-major fixed-size matrix with the usual algebra plus 4x4 view/projection
18/// factory methods. Rows==Cols gives an identity default.
19/// @ingroup math
20template <typename T, size_t Rows, size_t Cols>
21class Matrix {
22 public:
23 // Optimized default constructor
24 constexpr Matrix() noexcept {
25 if constexpr (Rows == Cols) {
26 // Identity matrix for square matrices
27 for (size_t i = 0; i < Rows; ++i) {
28 for (size_t j = 0; j < Cols; ++j) {
29 data[i][j] =
30 (i == j) ? static_cast<T>(1) : static_cast<T>(0);
31 }
32 }
33 } else {
34 // Zero matrix for non-square matrices
35 std::memset(data, 0, sizeof(data));
36 }
37 }
38
39 // Optimized initializer list constructor with bounds checking
40 Matrix(std::initializer_list<std::initializer_list<T>> list) {
41 if (list.size() != Rows) {
42 throw std::invalid_argument(
43 "Number of rows does not match matrix dimension");
44 }
45
46 size_t i = 0;
47 for (const auto& row : list) {
48 if (row.size() != Cols) {
49 throw std::invalid_argument(
50 "Number of columns does not match matrix dimension");
51 }
52
53 size_t j = 0;
54 for (const auto& val : row) {
55 data[i][j++] = val;
56 }
57 ++i;
58 }
59 }
60
61 /// Element access; indices are bounds-checked by assert in debug builds.
62 T& operator()(size_t row, size_t col) {
63 assert(row < Rows && col < Cols && "Matrix indices out of range");
64 return data[row][col];
65 }
66
67 /// Read-only element access; bounds-checked by assert in debug builds.
68 const T& operator()(size_t row, size_t col) const {
69 assert(row < Rows && col < Cols && "Matrix indices out of range");
70 return data[row][col];
71 }
72
73 // Efficient matrix addition
76 for (size_t i = 0; i < Rows; ++i) {
77 for (size_t j = 0; j < Cols; ++j) {
78 result(i, j) = data[i][j] + other(i, j);
79 }
80 }
81 return result;
82 }
83
84 // Efficient matrix subtraction
87 for (size_t i = 0; i < Rows; ++i) {
88 for (size_t j = 0; j < Cols; ++j) {
89 result(i, j) = data[i][j] - other(i, j);
90 }
91 }
92 return result;
93 }
94
95 /// Row-by-column matrix product.
96 template <size_t OtherCols>
98 const Matrix<T, Cols, OtherCols>& other) const {
100
101 for (size_t i = 0; i < Rows; ++i) {
102 for (size_t j = 0; j < OtherCols; ++j) {
103 T sum = static_cast<T>(0);
104 for (size_t k = 0; k < Cols; ++k) {
105 sum += data[i][k] * other(k, j);
106 }
107 result(i, j) = sum;
108 }
109 }
110
111 return result;
112 }
113
114 /// Returns the transposed matrix; does not modify this one.
117 for (size_t i = 0; i < Rows; ++i) {
118 for (size_t j = 0; j < Cols; ++j) {
119 result(j, i) = data[i][j];
120 }
121 }
122 return result;
123 }
124
125 // Improved determinant calculation with recursive approach
126 T Determinant() const {
127 static_assert(Rows == Cols,
128 "Determinant is only defined for square matrices");
129
130 if constexpr (Rows == 1) return data[0][0];
131 if constexpr (Rows == 2) {
132 return data[0][0] * data[1][1] - data[0][1] * data[1][0];
133 }
134 if constexpr (Rows == 3) {
135 return data[0][0] *
136 (data[1][1] * data[2][2] - data[1][2] * data[2][1]) -
137 data[0][1] *
138 (data[1][0] * data[2][2] - data[1][2] * data[2][0]) +
139 data[0][2] *
140 (data[1][0] * data[2][1] - data[1][1] * data[2][0]);
141 }
142
143 throw std::runtime_error(
144 "Determinant not implemented for matrices larger than 3x3");
145 }
146
147 // Improved inverse for 2x2 matrices with error handling
149 static_assert(Rows == Cols,
150 "Inverse is only defined for square matrices");
151
152 T det = Determinant();
153 if (std::abs(det) < std::numeric_limits<T>::epsilon()) {
154 throw std::runtime_error(
155 "Matrix is singular (determinant is near zero)");
156 }
157
158 if constexpr (Rows == 2) {
160 result(0, 0) = data[1][1] / det;
161 result(0, 1) = -data[0][1] / det;
162 result(1, 0) = -data[1][0] / det;
163 result(1, 1) = data[0][0] / det;
164 return result;
165 }
166
167 throw std::runtime_error(
168 "Inverse not implemented for matrices larger than 2x2");
169 }
170
171 // Optimized output method
172 std::string ToString() const {
173 std::ostringstream ss;
174 ss << "Matrix:\n";
175 for (size_t i = 0; i < Rows; ++i) {
176 ss << "| ";
177 for (size_t j = 0; j < Cols; ++j) {
178 ss << std::setw(10) << std::fixed << std::setprecision(4)
179 << data[i][j] << " ";
180 }
181 ss << "|\n";
182 }
183 return ss.str();
184 }
185
186 // Stream operator
187 friend std::ostream& operator<<(std::ostream& os,
188 const Matrix<T, Rows, Cols>& matrix) {
189 os << matrix.ToString();
190 return os;
191 }
192
193 // Static matrix creation methods remain the same
195 static_assert(Rows == Cols,
196 "Identity matrix is only defined for square matrices");
198 return result;
199 }
200
201 /// Builds a left-handed perspective projection (reversed-Z: near maps to depth 1).
202 static Matrix<T, 4, 4> Perspective(T fovY, T aspectRatio, T nearPlane,
203 T farPlane) {
204 static_assert(Rows == 4 && Cols == 4, "Perspective matrix must be 4x4");
205 T tanHalfFovY = tan(fovY / 2.0f);
206
208
209 result(0, 0) = 1.0f / (aspectRatio * tanHalfFovY);
210 result(1, 1) = 1.0f / tanHalfFovY;
211 result(2, 2) = farPlane / (farPlane - nearPlane);
212 result(2, 3) = 1.0f;
213 result(3, 2) = (-nearPlane * farPlane) / (farPlane - nearPlane);
214 result(3, 3) = 0.0f;
215
216 return result;
217 }
218
219
220
221 /// Builds an orthographic projection over the given box.
222 static Matrix<T, 4, 4> Orthographic(T left, T right, T bottom, T top, T nearPlane, T farPlane) {
223 static_assert(Rows == 4 && Cols == 4, "Orthographic matrix must be 4x4");
224
226
227 // Diagonal elements
228 result(0, 0) = 2.0f / (right - left); // Scale X
229 result(1, 1) = 2.0f / (top - bottom); // Scale Y
230 result(2, 2) = -2.0f / (farPlane - nearPlane); // Scale Z (negative for right-handed systems)
231
232 // Translation elements
233 result(0, 3) = -(right + left) / (right - left); // Translate X
234 result(1, 3) = -(top + bottom) / (top - bottom); // Translate Y
235 result(2, 3) = -(farPlane + nearPlane) / (farPlane - nearPlane); // Translate Z
236
237 return result;
238 }
239
240 /// Left-handed view matrix looking from eye toward center.
242 const Vector<T, 3>& center,
243 const Vector<T, 3>& up) {
244 static_assert(Rows == 4 && Cols == 4, "View matrix must be 4x4");
245
246 Vector<T, 3> zAxis = (center - eye).Normalized();
247 Vector<T, 3> xAxis = up.Cross(zAxis).Normalized();
248 Vector<T, 3> yAxis = zAxis.Cross(xAxis);
249
250 Matrix<T, 4, 4> result;
251
252 // Assign basis vectors correctly (Column-major order)
253 result(0, 0) = xAxis[0];
254 result(1, 0) = xAxis[1];
255 result(2, 0) = xAxis[2];
256 result(3, 0) = -xAxis.Dot(eye);
257
258 result(0, 1) = yAxis[0];
259 result(1, 1) = yAxis[1];
260 result(2, 1) = yAxis[2];
261 result(3, 1) = -yAxis.Dot(eye);
262
263 result(0, 2) = +zAxis[0];
264 result(1, 2) = +zAxis[1];
265 result(2, 2) = +zAxis[2];
266 result(3, 2) = -zAxis.Dot(eye);
267
268 result(0, 3) = 0;
269 result(1, 3) = 0;
270 result(2, 3) = 0;
271 result(3, 3) = 1;
272
273 return result;
274 }
275
276
277
278 /// Right-handed view matrix looking from eye toward center.
280 const Vector<T, 3>& center,
281 const Vector<T, 3>& up) {
282 Vector<T, 3> zAxis = (center - eye).Normalized(); // Notice: reversed direction
283 Vector<T, 3> xAxis = up.Cross(zAxis).Normalized();
284 Vector<T, 3> yAxis = zAxis.Cross(xAxis);
285
287 result(0, 0) = xAxis[0];
288 result(1, 0) = xAxis[1];
289 result(2, 0) = xAxis[2];
290
291 result(0, 1) = yAxis[0];
292 result(1, 1) = yAxis[1];
293 result(2, 1) = yAxis[2];
294
295 result(0, 2) = -zAxis[0]; // Negate z-axis
296 result(1, 2) = -zAxis[1];
297 result(2, 2) = -zAxis[2];
298
299 result(3, 0) = -xAxis.Dot(eye);
300 result(3, 1) = -yAxis.Dot(eye);
301 result(3, 2) = zAxis.Dot(eye); // Negate translation for right-handed
302 return result;
303 }
304
305 /// Left-handed view matrix looking from eye along a direction (rather than at a point).
307 const Vector<T, 3>& direction,
308 const Vector<T, 3>& up) {
309 Vector<T, 3> zAxis = direction.Normalized(); // Forward direction
310 Vector<T, 3> xAxis = up.Cross(zAxis).Normalized();
311 Vector<T, 3> yAxis = zAxis.Cross(xAxis);
312
314 result(0, 0) = xAxis[0];
315 result(1, 0) = xAxis[1];
316 result(2, 0) = xAxis[2];
317
318 result(0, 1) = yAxis[0];
319 result(1, 1) = yAxis[1];
320 result(2, 1) = yAxis[2];
321
322 result(0, 2) = zAxis[0];
323 result(1, 2) = zAxis[1];
324 result(2, 2) = zAxis[2];
325
326 result(3, 0) = -xAxis.Dot(eye);
327 result(3, 1) = -yAxis.Dot(eye);
328 result(3, 2) = -zAxis.Dot(eye);
329
330 return result;
331 }
332
333 /// View matrix for a yaw/pitch-driven free camera at position.
334 static Matrix<T, 4, 4> FreeLook(const Vector<T, 3>& position,
335 T yaw, T pitch) {
336 Vector<T, 3> forward;
337 forward[0] = cos(yaw) * cos(pitch);
338 forward[1] = sin(pitch);
339 forward[2] = sin(yaw) * cos(pitch);
340
341 return LookToLH(position, forward, Vector<T, 3>{0, 1, 0});
342 }
343
344 /// View matrix for a camera orbiting target at the given distance and angles.
346 T distance,
347 T theta, T phi) {
348 Vector<T, 3> direction = {
349 sin(phi) * cos(theta),
350 cos(phi),
351 sin(phi) * sin(theta)
352 };
353
354 Vector<T, 3> eye = target + direction * distance;
355 return LookAtLH(eye, target, Vector<T, 3>{0, 1, 0});
356 }
357
358 /// Builds a translation matrix.
359 static Matrix<T, 4, 4> Translate(const Vector3D& translation) {
361
362 result(3, 0) = translation.GetX(); // Move to last row, first column
363 result(3, 1) = translation.GetY(); // Move to last row, second column
364 result(3, 2) = translation.GetZ(); // Move to last row, third column
365
366 return result;
367 }
368
369
370 /// Builds a rotation matrix from a quaternion.
371 static Matrix<T, 4, 4> Rotate(const Quaternion& rotation) {
372 return rotation.toRotationMatrix(); // Assuming Quaternion has toRotationMatrix()
373 }
374
375 /// Builds a matrix that scales about the origin.
376 static Matrix<T, 4, 4> Scale(const Vector3D& scale) {
377 Matrix<T, 4, 4> result =
378 Matrix<T, 4, 4>::Identity(); // Ensure identity
379 result(0, 0) = scale.GetX();
380 result(1, 1) = scale.GetY();
381 result(2, 2) = scale.GetZ();
382 return result;
383 }
384
385 /// Builds a matrix that scales about an arbitrary center point.
386 static Matrix<T, 4, 4> Scale(const Vector3D& scale, const Vector3D& center) {
387 Matrix<T, 4, 4> translateToOrigin = Translate(center*(-1));
388
390 scaling(0, 0) = scale.GetX();
391 scaling(1, 1) = scale.GetY();
392 scaling(2, 2) = scale.GetZ();
393
394 Matrix<T, 4, 4> translateBack = Translate(center);
395
396 return translateBack * scaling * translateToOrigin;
397 }
398
399 private:
400 T data[Rows][Cols];
401};
402
403// Type alias for 4x4 matrix
405
406
407#ifdef PLATFORM_WIN
408#include <DirectXMath.h>
409
410/// Converts a DirectXMath matrix into Sleak's Matrix4 (row-major copy).
411static Matrix<float, 4, 4> XMToMatrix(DirectX::XMMATRIX mat) {
413 DirectX::XMMATRIX worldMatrix;
414
415 DirectX::XMMATRIX normalMatrix = XMMatrixTranspose(XMMatrixInverse(nullptr, worldMatrix));
416
417 // Store the matrix in row-major order
418 DirectX::XMFLOAT4X4 floatMat;
419 DirectX::XMStoreFloat4x4(&floatMat, mat);
420
421 // Copy the elements from XMFLOAT4X4 to Sleak::Math::Matrix4
422 for (int row = 0; row < 4; ++row) {
423 for (int col = 0; col < 4; ++col) {
424 matr(row, col) = floatMat.m[row][col];
425 }
426 }
427
428 return matr;
429}
430
431#endif
432
433} // namespace Math
434} // namespace Sleak
435
436#endif // _MATRIX_H_
static Matrix< T, 4, 4 > Scale(const Vector3D &scale, const Vector3D &center)
Builds a matrix that scales about an arbitrary center point.
Definition Matrix.hpp:386
T Determinant() const
Definition Matrix.hpp:126
static Matrix< T, Rows, Rows > Identity()
Definition Matrix.hpp:194
Matrix< T, Rows, Cols > Inverse() const
Definition Matrix.hpp:148
static Matrix< T, 4, 4 > FreeLook(const Vector< T, 3 > &position, T yaw, T pitch)
View matrix for a yaw/pitch-driven free camera at position.
Definition Matrix.hpp:334
static Matrix< T, 4, 4 > Perspective(T fovY, T aspectRatio, T nearPlane, T farPlane)
Builds a left-handed perspective projection (reversed-Z: near maps to depth 1).
Definition Matrix.hpp:202
static Matrix< T, 4, 4 > Orthographic(T left, T right, T bottom, T top, T nearPlane, T farPlane)
Builds an orthographic projection over the given box.
Definition Matrix.hpp:222
static Matrix< T, 4, 4 > LookTo(const Vector< T, 3 > &eye, const Vector< T, 3 > &direction, const Vector< T, 3 > &up)
Left-handed view matrix looking from eye along a direction (rather than at a point).
Definition Matrix.hpp:306
T & operator()(size_t row, size_t col)
Element access; indices are bounds-checked by assert in debug builds.
Definition Matrix.hpp:62
Matrix(std::initializer_list< std::initializer_list< T > > list)
Definition Matrix.hpp:40
Matrix< T, Cols, Rows > Transpose() const
Returns the transposed matrix; does not modify this one.
Definition Matrix.hpp:115
const T & operator()(size_t row, size_t col) const
Read-only element access; bounds-checked by assert in debug builds.
Definition Matrix.hpp:68
static Matrix< T, 4, 4 > Rotate(const Quaternion &rotation)
Builds a rotation matrix from a quaternion.
Definition Matrix.hpp:371
static Matrix< T, 4, 4 > Scale(const Vector3D &scale)
Builds a matrix that scales about the origin.
Definition Matrix.hpp:376
friend std::ostream & operator<<(std::ostream &os, const Matrix< T, Rows, Cols > &matrix)
Definition Matrix.hpp:187
static Matrix< T, 4, 4 > Translate(const Vector3D &translation)
Builds a translation matrix.
Definition Matrix.hpp:359
static Matrix< T, 4, 4 > OrbitView(const Vector< T, 3 > &target, T distance, T theta, T phi)
View matrix for a camera orbiting target at the given distance and angles.
Definition Matrix.hpp:345
Matrix< T, Rows, OtherCols > operator*(const Matrix< T, Cols, OtherCols > &other) const
Row-by-column matrix product.
Definition Matrix.hpp:97
static Matrix< T, 4, 4 > LookAt(const Vector< T, 3 > &eye, const Vector< T, 3 > &center, const Vector< T, 3 > &up)
Left-handed view matrix looking from eye toward center.
Definition Matrix.hpp:241
Matrix< T, Rows, Cols > operator-(const Matrix< T, Rows, Cols > &other) const
Definition Matrix.hpp:85
Matrix< T, Rows, Cols > operator+(const Matrix< T, Rows, Cols > &other) const
Definition Matrix.hpp:74
static Matrix< T, 4, 4 > LookAtRH(const Vector< T, 3 > &eye, const Vector< T, 3 > &center, const Vector< T, 3 > &up)
Right-handed view matrix looking from eye toward center.
Definition Matrix.hpp:279
constexpr Matrix() noexcept
Definition Matrix.hpp:24
std::string ToString() const
Definition Matrix.hpp:172
Represents a quaternion for 3D rotations.
Matrix< float, 4, 4 > toRotationMatrix() const
float GetY() const
Definition Vector.hpp:362
float GetX() const
Definition Vector.hpp:361
float GetZ() const
Definition Vector.hpp:363
T Dot(const Vector< T, N > &other) const
Definition Vector.hpp:104
std::enable_if< M==3, Vector< T, N > >::type Cross(const Vector< T, N > &other) const
Definition Vector.hpp:115
Vector< T, N > Normalized() const
Definition Vector.hpp:145
Vectors, matrices, quaternions, colors, AABBs, and random helpers.
Matrix< float, 4, 4 > Matrix4
Definition Matrix.hpp:404
Root namespace for everything the engine exposes.
Definition Camera.hpp:10