feat: add viewport and test

This commit is contained in:
2025-08-28 21:36:55 +02:00
parent 471b21b952
commit d94ccfbbaa
3 changed files with 49 additions and 7 deletions

View File

@@ -1,18 +1,18 @@
#include "math/mat4.h"
#include "math/vec3.h"
#include "math/vec4.h"
#include <math.h>
Mat4f_t perspCam(float fov, float asp, float near, float far)
{
const float t = 1 / tanf(fov/2);
const float t = 1.f / tanf(fov*0.5f);
const float fn = near - far;
const float persp[16] =
{
t/asp, 0.f, 0.f, 0.f,
0.f, t, 0.f, 0.f,
0.f, 0.f, (far + near) / (far - near), -1.f,
0.f, 0.f, (2.f * far * near) / (far - near), 0.f
0.f, 0.f, (far + near) / fn, -1.f,
0.f, 0.f, (2.f * far * near) / fn, 0.f
};
return mat4f_from_array(persp);
@@ -27,4 +27,10 @@ Vec4f_t* normCoord_r(Vec4f_t* vec)
return vec;
}
// Vec3f_t
// first off, apply to your vec normCoord fn
Vec4f_t* viewport_r(Vec4f_t* vec, float width, float height)
{
vec->x = (vec->x + 1.f) * 0.5f * width;
vec->y = (1.f - vec->y) * 0.5f * height;
return vec;
}

View File

@@ -0,0 +1,6 @@
#include "math/mat4.h"
#include "math/vec4.h"
Mat4f_t perspCam(float fov, float asp, float near, float far);
Vec4f_t* normCoord_r(Vec4f_t* vec);
Vec4f_t* viewport_r(Vec4f_t* vec, float width, float height);

View File

@@ -1,8 +1,38 @@
#include <stdio.h>
#include "math/mat4.h"
#include "cam.h"
#include "math/vec4.h"
Vec4f_t mat4f_mul_vec4f(const Mat4f_t mat, Vec4f_t v)
{
Vec4f_t out;
for (int i = 0; i < 4; i++)
{
out.data[i] = 0.f;
for (int j = 0; j < 4; j++)
out.data[i] += mat.m[i*4 + j] * v.data[j];
}
return out;
}
int main(int argc, const char** argv)
{
printf("hello world");
const float fov = 60;
const float width = 1000, height = 800;
const float near = 0.1, far = 1000;
const float aspect = width / height;
// xyz = [-1, 1]
Vec4f_t vec = vec4f(0.f, 0.f, -1.f, 1.f);
Mat4f_t proj = perspCam(fov, aspect, near, far);
Vec4f_t v_clip = mat4f_mul_vec4f(proj, vec);
normCoord_r(&v_clip);
viewport_r(&v_clip, width, height);
printf("Screen coordinates: x = %f, y = %f, z = %f\n",
v_clip.x, v_clip.y, v_clip.z);
return 0;
}