I’ve built projects with OpenGL before, specifically the custom Game Engine. However, I never quite understood the math behind turning vertices into pixels on the screen.
Out of curiosity, I’ve built a software renderer and it proved to be a real eye-opener into the world of 3D graphics programming.
It may be obvious, but I realized that: We are always looking at a flat screen, the illusion of a 3D world sustains because the right pixels are drawn in the correct places.
It’s crazy when you think about it – we stare into these flat screens for hours on end. Games really do take place in our minds.
It was based mostly on this tutorial by thebennybox. I’ve written it in C++ with SFML as a starting point.
Sample Code
class Instance {
public:
Instance(const Mesh& mesh, const Bitmap& texture) :
mesh(mesh),
texture(texture) {
}
void render(RenderContext& target, Matrix4 vp) {
target.drawMesh(mesh, vp, transform, texture);
}
const Mesh& mesh;
const Bitmap& texture;
Matrix4 transform;
};
int main() {
RenderContext context(1080 / scale, 720 / scale);
Display display(context, scale);
Matrix4 projection;
projection.perspective(90.0f, 800.0f/600.0f, 0.1f, 100.0f);
Mesh marioMesh("assets/mario.obj");
Bitmap marioTexture = Bitmap::LoadFromFile("assets/mario.png");
Instance mario (marioMesh, marioTexture);
while(display.isOpen()) {
mario.render(context, viewProjection);
}
}
Video
Image used from Evas GL Programming Guide