Kai Schmidt
Kai Schmidt

Reputation: 731

How to draw shapes in the proper order when rendering?

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.

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.

At the moment, the only shapes I am rendering are triangles. My current render order algorithm sorts the triangles by the average depth of their 3 points. I knew when I started it that it would not be perfect, but I wanted a placeholder for testing.

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: enter image description here

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:

enter image description here

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.

Is there a better method of ordering shapes so that they are rendered in the correct order?

Upvotes: 3

Views: 1885

Answers (1)

Amit
Amit

Reputation: 46323

The standard method to draw 3D in correct depth order is to use a Z-buffer.

Basically, the idea is that for each pixel you set in the color buffer, you also set it's interpolated depth in the z (depth..) buffer. Whenever you're about to paint the next pixel, you first check that z-buffer to validate the new pixel if in front of the already painted pixel.

On top of that you can add various sorts of optimizations, such as sorting triangles in order to minimize the number of times you actually paint the color buffer.

On the other hand, it's sometimes required to do the exact opposite in order to properly handle transparency or other "advanced" effects.

Upvotes: 2

Related Questions