title: How to draw shapes in the proper order when rendering?
body: <p>I am trying my hand at writing a 3d graphics engine, but I am having some trouble with drawing the shapes in the correct order. </p>
  
  <p>When I translate the points of triangles into window space, i.e. the 2-dimensional space that directly correlates to position on the screen, in addition to an x and y position of each point, I also assign them a depth variable that stores how far away from the viewer that point was in 3d space.</p>
  
  <p>At the moment, the only shapes I am rendering are triangles. My current render order algorithm <strong>sorts the triangles by the average depth of their 3 points.</strong> I knew when I started it that it would not be perfect, but I wanted a placeholder for testing.</p>
  
  <p>For testing purposes, I constructed a square box with an open top, each side being a different color and made from 2 triangles, as shown below:
  <a href="https://i.stack.imgur.com/iuAvC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iuAvC.png" alt="enter image description here"></a></p>
  
  <p>As you can see from the image above, the algorithm I am using works most of the time. However, at certain angles and positions, the triangles will be rendered in the wrong order, as show below:</p>
  
  <p><a href="https://i.stack.imgur.com/LcYpu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LcYpu.png" alt="enter image description here"></a></p>
  
  <p>As you can see, one of the cyan triangles on the bottom of the box is being drawn before one of the yellow triangles on the side. Clearly, sorting the triangles by the average depth of their points is not satisfactory.</p>
  
  <p>Is there a better method of ordering shapes so that they are rendered in the correct order?</p>