feat: add drawline function, also fix M_PI function

This commit is contained in:
2025-09-03 18:49:02 +02:00
parent 64711af006
commit f467275b84
4 changed files with 54 additions and 9 deletions

View File

@@ -3,9 +3,13 @@
#include <math.h>
#ifndef M_PI // MSCV doesn't implement M_PI by default
#define M_PI 3.14159265358979323846
#endif
Mat4f_t perspCam(float fov, float asp, float near, float far)
{
const float t = 1.f / tanf(fov * 0.5f * (M_PI/180.f));
const float t = 1.f / tanf(fov * 0.5f * (float)(M_PI/180.));
const float fn = far - near;
const float persp[16] =
{

View File

@@ -3,6 +3,7 @@
#include <string.h>
#include "draw.h"
#include "math/vec4.h"
#include "math.h"
char* canvas;
@@ -29,6 +30,39 @@ static char drawPixel(float zBuffer)
else return '#';
}
void drawLine(Vec4f_t p0, Vec4f_t p1, int width, int height)
{
int x0 = (int)roundf(p0.x);
int y0 = (int)roundf(p0.y);
int x1 = (int)roundf(p1.x);
int y1 = (int)roundf(p1.y);
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = dx - dy;
int len = (int)sqrtf((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
int step = 0;
while (1) {
float t = len == 0 ? 0.f : (float)step / (float)len;
Vec4f_t p = vec4f_lerp(p0, p1, t);
drawCanvas(p, width, height);
if (x0 == x1 && y0 == y1) break;
int e2 = 2*err;
if (e2 > -dy) { err -= dy; x0 += sx; }
if (e2 < dx) { err += dx; y0 += sy; }
step++;
}
}
void drawCanvas(Vec4f_t p, int width, int height)
{
int x = (int)p.x;

View File

@@ -6,6 +6,7 @@
void initCanvas(int width, int height);
void editCanvas(int width, int height);
void drawCanvas(Vec4f_t p, int width, int height);
void drawLine(Vec4f_t p0, Vec4f_t p1, int width, int height);
void renderCanvas(int width, int height);
void freeCanvas(void);

View File

@@ -11,18 +11,24 @@ int main(int argc, const char** argv)
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);
// xyz = [-1; 1]
Vec4f_t vec0 = vec4f(0.f, 0.f, -1.f, 1.f);
Vec4f_t v_clip0 = mat4f_mul_vec4f(proj, vec0);
normCoord_r(&v_clip0);
viewport_r(&v_clip0, width, height);
normCoord_r(&v_clip);
viewport_r(&v_clip, width, height);
Vec4f_t vec1 = vec4f(0.f, 0.6f, -1.f, 1.f);
Vec4f_t v_clip1 = mat4f_mul_vec4f(proj, vec1);
normCoord_r(&v_clip1);
viewport_r(&v_clip1, width, height);
initCanvas(width, height);
drawCanvas(v_clip, width, height);
// drawCanvas(v_clip, width, height);
drawLine(v_clip0, v_clip1, width, height);
renderCanvas(width, height);
printf("%f", v_clip.z);
freeCanvas();
return 0;
}