As you might remember from BOX1.CPP, we save the Z value of each point, even after we've rotated it. This can now be used for depth sorting.
Instead of drawing all the triangles in the order they are entered we store their index in a vector. We then sort this vector according to the Z value of each triangle. We base the sorting on the average Z value of each triangle, i.e. (Z1+Z2+Z3)/3, but since we only sort triangles we really don't need to divide the sum by three. This is because we'll devide all sums by three, therefore all sums will be treated equaly even without the division.
Ok, we find the average Z value for each triangle and store that together with an index value for each triangle in a vector. This vector is the sorted so that the triangle closest to the view point is the last one.
This method has got a problem, it cannot handle "cyclic overlapping" (see illustration).
This will end up with a mess. The most complex objects can therefore not be represented through this method, but it's good enough for our purposes.
Binary Space Partition Trees
Binary Space Partition Trees, or BSP trees are a different way of representing the 3D world. It avoids the sorting part, but requires the redrawing of more triangles. This may pay of in very complex scenes when it's easier to rewrite the redrawing routines in assembler, than the actual sorting.
This tecnique is alot more complex to setup and to use when it includes detection of which side of an object another object is positioned, recursive redrawing routines and memory trees doubling the number of members for each level. If I ever will use this method, I'll of course write a chapter about it.
If you want me to include it earlier, please let me know (you can reach me by mail at e8johan@etek.chalmers.se.)