Z-Buffer Algorithm

N.B : Case of the Painter's Algorithm : objects are painted from back-to-front

The painter's algorithm, sometimes called depth-sorting, gets its name from the process which an artist renders a scene using oil paints. First, the artist will paint the background colors of the sky and ground. Next, the most distant objects are painted, then the nearer objects, and so forth. Note that oil paints are basically opaque, thus each sequential layer completely obscures the layer that its covers. A very similar technique can be used for rendering objects in a three-dimensional scene. First, the list of surfaces are sorted according to their distance from the viewpoint. The objects are then painted from back-to-front.
While this algorithm seems simple there are many subtleties. The first issue is which depth-value do you sort by? In general a primitive is not entirely at a single depth. Therefore, we must choose some point on the primitive to sort by.
1. Sort by the minimum depth extent of the polygon
2. Sort by the maximum depth extent of the polygon
3. Sort by the polygon's centriod (Sum(vi, i = 1..N)/N)
But the main issue is that it is easy to face some absurdity like Triangle1 covers part of Triangle2 which covers part of Triangle3 wich covers part of triangle1

z-buffer algorithm

The basic idea is to test the z - depth of each surface to determine the closest (visible) surface. Declare an array z buffer(x, y) with one entry for each pixel position. Initialize the array to the maximum depth. So initialize all values to maximum depth. Then the algorithm is as follows:

for each polygon P
  for each pixel (x, y) in P 
    compute z_depth at x, y
    if z_depth < z_buffer (x, y) then 
       set_pixel (x, y, color) 
       z_buffer (x, y) = z_depth 

Advantages of z-buffer algorithm: