Z-buffer algorithm implementation problem

Hi guys, now I’m making a 3d game engine in Java from scratch.

Now I’m working at the Z-buffer because I didn’t like the effect of the Painter’s Algorithm(Z-sorting).

My question is: what is the easiest way to determine the Z value of each pixel? Please include a source code if you can :wink:

P.S.: The renderer contains just triangles, something like that:

class Vector3d {
double x,y,z;
}
class Triangle {
Vector3d v1,v2,v3;
Color color;
}
class Renderer {
public Triangle[] triangles;
[ . . . ]
}

When you transform the 3d points into 2d screen coordinares the z value of the transformed point is the z value you use.

  1. So don’t I need the z value of the points inside the triangle?
    EDIT
  2. if so, what if the triangle’s vertices have different Z values?

You need to do perspective-correct interpolation of the three vertices’ Z values for each fragment generated within the triangle.

OK, I understand a bit.
Can someone give me a function like that:


public void getZ(point3d v1,point3d v2,point3d v3, // triangle vertices
                        point2d screen) // x y coordinates
{
    // [what I need] (calculate the Z value of the pixel located at screen.x X screen.y)
}

PLS answer as soon possible

Are you familiar with linear interpolation?

Consider the function X1 = X1 + F(X2-X1)
Where X1 is the start value, X2 is the end value, and F is the fraction between 0 and 1.
This fraction represents how far along in between X1 and X2 you want to go. For example,
if F = 0 you’ll get X1, if F = 1, you’ll get X2, and if F = 0.5, you’ll get a value half way in between X1 and X2.

You use linear interpolation to find values along the triangle’s edges, and across the triangle’s surface. So for your Z problem, you interpolate between the Z values of vertex 1 (X1) and vertex 2 (X2). An F value of 0 will give you the Z value of vertex 1 and an F value of 1 will give you the Z value of vertex 2.

In order to find the F value, you need to find the change of Z over the change in Y. This dz/dy is the F value and is constant for the entire edge of the triangle.

Loop over each of the Y values between vertex 1 and vertex 2, incrementing a counter by F.



float F = (vertex2.z - vertex1.z) / (vertex2.y - vertex1.y);
float interpZ = vertex1.z;
while (vertex1.y < vertex2.y) {
     // interpolate across X using a similar method
     // interpZ is the Z value in between the edges.
     interpZ += F;
}

I’VE FINALLY FOUND WHAT I NEED!
Thank you a lot, you made my day!

And your 3d renderer is very cool. It seems that you wanted to remake the OpenGL. Nice work!

Haha yup, no problem. And thanks, you’re doing the same stuff I was doing when I started working on my renderer. So keep going! :stuck_out_tongue: