Files
Tower-Defense/src/misc/Maths.cpp
2023-06-03 16:23:56 +02:00

59 lines
1.3 KiB
C++

#include "misc/Maths.h"
namespace td {
namespace maths {
Mat4f Perspective(float fovY, float aspectRatio, float zNear, float zFar) {
const float tanHalfFovy = std::tan(fovY / 2.0f);
Mat4f result{};
result.x0 = 1.0f / (aspectRatio * tanHalfFovy);
result.y1 = 1.0f / (tanHalfFovy);
result.z2 = -(zFar + zNear) / (zFar - zNear);
result.z3 = -1.0f;
result.w2 = -(2.0f * zFar * zNear) / (zFar - zNear);
return result;
}
Mat4f LookAt(const Vec3f& eye, const Vec3f& center, const Vec3f& up) {
const Vec3f f = Normalize(center - eye);
const Vec3f s = Normalize(Cross(f, up));
const Vec3f u = Cross(s, f);
Mat4f result = Identity<float>();
result.x0 = s.x;
result.y0 = s.y;
result.z0 = s.z;
result.x1 = u.x;
result.y1 = u.y;
result.z1 = u.z;
result.x2 = -f.x;
result.y2 = -f.y;
result.z2 = -f.z;
result.w0 = -Dot(s, eye);
result.w1 = -Dot(u, eye);
result.w2 = Dot(f, eye);
return result;
}
Mat4f Dot(const Mat4f& mat, const Mat4f& other) {
Mat4f result {};
static const std::size_t MAT_SIZE = 4;
for (std::size_t i = 0; i < MAT_SIZE; i++) {
for (std::size_t j = 0; j < MAT_SIZE; j++) {
for (std::size_t k = 0; k < MAT_SIZE; k++) {
result[i * MAT_SIZE + j] += mat[i * MAT_SIZE + k] * other[k * MAT_SIZE + j];
}
}
}
return result;
}
} // namespace maths
} // namespace td