These are some notes on how to manually draw triangles in code. Possibly useful if you’re trying to write your own software renderer, or are just curious how it works.
There’s two ways to do this. One is quite CPU intensive, the other is mathematical and less CPU intensive. The CPU intensive version scales well if run on something with multiple cores, like a GPU. So there’s tradeoffs in which method is used and when.
Scanline Rasterisation
This is the mathematical way. It’s based around the idea of splitting a triangle into two halves. The top half will be a triangle with a point at the top and a flat bottom. The bottom half will be a triangle with a flat top and a point at the bottom.
This does require sorting the vertices of the triangle into Y order. This can be done with an actual sorting routine, but triangles only have three points, so it’s not difficult to just figure it out with a few if statements.
How it works with some sample code is on this website here In fact this entire website is pretty interesting if low level graphics algorithms are interesting to you!
Barycentric Triangle Drawing
Another way to draw a triangle is to take all the points on the screen, and for each one work out if they’re inside a triangle or not.
Clearly doing this for every pixel on the screen, just to draw one triangle is complete madness. So the testing of each point is restricted to just the inside of the triangle’s bounding rectangle.
This is still quite computationally intensive, but can be done very well on a GPU. It doesn’t rely on knowing which triangle your points are within. So the code can just work out “is this pixel inside any of the triangles I want to draw?”
It works off the fairly simple logic that a point is inside a triangle ABC if
- It is on the “inside” of the line A-B and
- also inside the line B-C and
- also inside the line C-A
Working out if a point is “inside” requires walking round the points in a consistent direction, and then using a dot product. This is why OpenGL and other 3D libraries require a winding order for their triangles.
This site explains some of it however it’s quite wordy and maths heavy. This site explains it mathematically and if you read the two in combination, have some drawing paper and a calculator it makes sense after some effort.