PDA

View Full Version : Equation for Distance to A Pixel



rangers99
11-13-2002, 12:32 AM
Hi

I know this has been asked before and Ive searched the previous threads. However the only equation I can find gave a wrong answer when I tried to implement it.

So given the z-buffer value and the near and far plane distances , how do I get the distance to the point?

thanks.

Bob
11-13-2002, 02:00 AM
You mean how far into the scene a specific Z-buffer value is located?

This is a piece of code I have written. It takes the near plane, far plane and the Z-buffer value, and returns the distance from the near plane. If you want the distance from the viewpoint, just add the near plane to the result.



double convertZ(double n, double f, double z)
{
// Convert Z from [0, 1] to [-1, 1]
double wz = (2.0 * z) - 1.0;

double a = -(f - n) / (2.0 * f * n);
double b = (f + n) / (2.0 * f * n);

return -1.0 / (wz * a + b);
}

rangers99
11-13-2002, 08:51 PM
Bob,

Any idea why I am getting a negative result?

rangers99
11-13-2002, 09:01 PM
Found this equation on the Internet. Looks similar to yours Bob.

distance = Zn*Zf / (Zf - Zdepth *(Zf-Zn))

Bob
11-14-2002, 02:34 AM
You're getting negative values because the positive Z-axis is poiting out from the screen. Therefore you get negative values into the screen.

mm_freak
11-15-2002, 12:05 AM
The distance from the camera to any point in space ((camx,camy,camz) is the camera and (px,py,pz) the point), if that's what you need:

dist = sqrt(pow(camx - px,2) + pow(camy - py,2) + pow(camz - pz,2))