0

I'm trying to use the z-buffer to measure distances, but I found a unexpected issue.

I'm aware that the z-buffer returns a 0..1 float number through my code:

    zImageData = new osg::Image;
zImageData->allocateImage(720, 576, 1, GL_DEPTH_COMPONENT ,GL_FLOAT); 
osgCam->setProjectionMatrixAsPerspective(45.0, 1.0, nearplane, farplane);
osgCam->setViewMatrixAsLookAt(osg::Vec3(0,0,camera_high), osg::Vec3(0,0,0),osg::Vec3(0,1,0) ); 
osgCam->attach(osg::Camera::DEPTH_BUFFER, zImageData);
//osgCam is my master camera.

I then postprocess the z-buffer value using a callback function:

  z = ((float*)sonar->zImageData->data())[1];

  float true_distance = farplane*nearplane/(farplane - z*(farplane-nearplane));

Everything works just fine until I reach 24 distance units, as shown below.


I have 3 variables, nearplane (the viewport), farplane and camera_high. The last one is the distance of the camera from the ground. It's looking at a plane (which is meant to be the ground). That's the program output:

const float nearplane = 0.2; const float farplane = 200;

const float camera_high = 5;
z value : 0.960961
z distance value : 5
*** Exited normally ***

const float camera_high = 10;
z value : 0.980981
z distance value : 10
*** Exited normally ***

const float camera_high = 20;
z value : 0.990991
z distance value : 20
*** Exited normally ***

const float camera_high = 23;
z value : 0.992297
z distance value : 22.9999
*** Exited normally ***

const float camera_high = 25;
z value : 1
z distance value : 200.003
*** Exited normally ***

const float nearplane = 20;

const float camera_high = 25;
z value : 1
z distance value : 200
*** Exited normally ***

const float camera_high = 23;
z value : 0.144928
z distance value : 23
*** Exited normally ***

const float nearplane = 24;

const float camera_high = 25;
z value : 1
z distance value : 200
*** Exited normally ***

I just can't get any difference in the z-buffer beyond 24, despite the position of my nearplane and farplane.

elael
  • 1
  • 1
  • 1
    ... Okay? Is there a question or problem that you have? – Xymostech Dec 11 '13 at 16:04
  • @Xymostech Closevoting takes just three clicks more :) – Bartek Banachewicz Dec 11 '13 at 16:15
  • Sorry guys, I miss clicked the send button before =\ – elael Dec 11 '13 at 16:17
  • Are you familiar with the non-linear distribution of the depth buffer values? Long story short, the closer you get to the far, the less precise it becomes. You should not use it in calculations unless you want a very rough approximation. And even then, you'll still get crap. – Jean-Simon Brochu Dec 11 '13 at 20:00
  • Yes, I've tried overcome this by putting the nearplane as close as I could to the object, given that the closer it gets more precision we have. But, as shown in my last program output, it didn't work. – elael Dec 12 '13 at 01:52

0 Answers0