Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a triangle in 3D to a depth buffer

I am experimenting with 3D graphics without relying on any 3D library, such as Java3D, OpenGL, DirectX, etc. I have a working Z-buffer (aka. "depth buffer"), yet I cannot think of a way of drawing a triangle to that buffer. (Every triangle is specified by three points in 3D.)

Can anyone please provide pseudocode for drawing a triangle to the Z-buffer?

like image 971
coderodde Avatar asked Mar 16 '23 16:03

coderodde


1 Answers

The answer to your question (as is) involves complex algorithms and a complete answer would require many chapters. I'll only provide key words and links.

First, you need to project the three 3D coordinates (usually called vertex, vertices for the plural form) of your triangle in 2D space. You can start with this article about 3D projection. If you're not familiar with vector operations, matrix transformations, world space and view/camera space, be warned that it may be a long run before you get results. Orthogonal or perspective projection, it's your choice (though I suppose you wish for perspective projection). I only provided a link to the wikipedia article (the less likely to break in the future), thus it mainly talks about involved maths behind it. But with those key words, you should be able to find thousands of good articles about the subject with source code.

Once you transformed (projected) your 3D coordinates in the view/camera space, your X and Y coordinates are the 2D triangle corners/vertices coordinates (let's assume you decided that X goes from left to right, Y goes from top to bottom, this is quite common). You then need to rasterize this triangle into your buffer (which is basically a 2D bitmap). Here's a triangle rasterization article which will teach you (with C-like source code) popular techniques to do this (though this is only about rasterization with a constant color, the principle remains the same).

The next step is that instead of writting a constant color for all pixels, you need a variable depth value. Time to make use of those 3 Z values in your projected vertices. For each horizontal line, you'll have to find the Z depth of the left-most & right-most pixels (using linear interpolation from top vertex Z to bottom vertex Z, just be careful as one side will likely have a top, middle and bottom vertices, so here you must interpolate from top to middle, then from middle to bottom. If you divided your triangle in two like described in the article, no need to bother with it). Then write all pixels between them, also linear interpolating your left Z and right Z.

like image 56
Alex Avatar answered Mar 31 '23 10:03

Alex