Files
SoftwareRenderer/renderer.hpp
2025-11-29 10:08:13 +01:00

120 lines
4.3 KiB
C++

#ifndef RENDERER_H
#define RENDERER_H
#include "fastmath.hpp"
#include "model.hpp"
#include "polygon.hpp"
#include "rendertarget.hpp"
#include <bits/stdc++.h>
#include <cstring>
#include <memory.h>
#define SCREEN_SPACE_SIZE 8.0
class Renderer {
public:
Rendertarget *target;
bool clearTarget = true;
void toScreenSpace(vec3 *p) {
p->x() = p->x() / p->z() * decimal(2.0) * decimal(SCREEN_SPACE_SIZE) +
decimal(SCREEN_SPACE_SIZE);
p->y() = p->y() / p->z() * decimal(2.0) * decimal(SCREEN_SPACE_SIZE) +
decimal(SCREEN_SPACE_SIZE);
p->z() = p->z();
}
void render(const model *model) {
decimal widthScale =
decimal(SCREEN_SPACE_SIZE * 2) / decimal((float)target->width);
decimal heightScale =
decimal(SCREEN_SPACE_SIZE * 2) / decimal((float)target->height);
decimal invWidthScale =
decimal((float)(target->width / SCREEN_SPACE_SIZE / 2));
decimal invHeightScale =
decimal((float)(target->height / SCREEN_SPACE_SIZE / 2));
// TODO clear target with memset
if (clearTarget) {
// memset((wchar_t *)target->pixels, 0,
// target->height * target->width * sizeof(target[0]));
target->clearDepth();
}
vec3 verts[model->verts.size()] = {};
std::copy(model->verts.begin(), model->verts.end(), verts);
for (int i = 0; i < model->verts.size(); i++) {
toScreenSpace(verts + i);
}
polygon testP;
for (int f = 0; f < model->faces.size(); f += 3) {
for (int p = 0; p < 3; p++) {
testP.points[p] = verts[std::get<0>(model->faces[f + p])];
testP.colors[p] =
model->colors[std::get<0>(model->faces[f + p])];
testP.normals[p] =
model->normals[std::get<1>(model->faces[f + p])];
}
testP.calcDelta();
int startX = std::max(
(testP.bounding[0] * invWidthScale).i >> SHIFT_AMOUNT, 0);
int endX =
std::min((testP.bounding[1] * invWidthScale).i >> SHIFT_AMOUNT,
target->width - 1);
int startY = std::max(
(testP.bounding[2] * invHeightScale).i >> SHIFT_AMOUNT, 0);
int endY =
std::min((testP.bounding[3] * invHeightScale).i >> SHIFT_AMOUNT,
target->height - 1);
vec3 pos = vec3(testP.bounding[0], testP.bounding[2], 0.0);
for (int x = startX; x < endX; x++) {
for (int y = startY; y < endY; y++) {
if (testP.contains(pos)) {
vec3 factors = testP.calcBarycentric(pos);
factors = factors.normalize();
decimal depth = testP.calcDepth(factors);
if (depth < target->getDepth(x, y)) {
// std::cout << factors << std::endl;
vec3 normal = testP.calcNormal(factors);
vec3 color = testP.calcColor(factors);
decimal lightFac =
std::max(
normal *
(-vec3(1.0, -1.0, 1.0).normalize()),
decimal(0.0)) +
decimal(0.5);
target->setDepth(x, y, depth);
target->set(x, y,
(color * decimal(120.0)) * lightFac);
// target->set(x, y,
// (normals + vec3(1.0, 1.0, 1.0)) *
// decimal(120.0));
// target->set(x, y, factors * decimal(200.0));
// if (!factors.isSmall())
// target->set(x, y, vec3(0., 255.0, 0.));
}
// target->set(x, y, vec3(0.0, 255.0, 0.0));
}
pos.y() += heightScale;
}
pos.y() = decimal(testP.bounding[2]);
pos.x() += widthScale;
}
}
}
};
#endif