Hello,
I am trying to obtain the depth to a selected object in my opengl rendering from my camera.
I have positioned a projection camera using gluLookAt , and then I am running a glRenderMode(GL_SELECT) to get the object under the mouse cursor. This all works fine.
Having done this, I need not only the object, but also the distance from the camera to that object, such that the user can move the object in the plane whose normal is the same as the camera, but is positioned at “depth” away.
I have tried to use gluUnproject to do this, by first calling glReadPixels, however glReadPixels seems to always return 1, even with an object completetly filling the screen.
GluUnproject’s value changes as I move the camera, but not as a function of the object depth, so I guess I am doing something wrong.
Does GL_SELECT draws to the depth buffer? I assume it must in order to work out the hit record distances…
//Push on the matrix stack
glPushMatrix();
GLint oldViewport[4];
glGetIntegerv(GL_VIEWPORT, oldViewport);
//5x5px picking region. Picking is done by modifying the view
//to enlarge the selected region.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPickMatrix(p.x, oldViewport[3]-p.y,5, 5, oldViewport);
glMatrixMode(GL_MODELVIEW);
GLuint *selectionBuffer = new GLuint[512];
glSelectBuffer(512, selectionBuffer);
glRenderMode(GL_SELECT);
glInitNames();
glPushMatrix();
... Apply camera transform, this is done with a class, so I have omitted it here for brevity. ..
glFlush();
GLint hits = glRenderMode(GL_RENDER);
//Hit query records
GLuint *ptr = selectionBuffer;
GLuint *closestNames = 0;
GLuint minZ = 0xffffffff;
GLuint numClosestNames = 0;
for ( int i=0; i<hits; ++i )
{
if ( *(ptr+1) < minZ )
{
numClosestNames = *ptr;
minZ = *(ptr+1);
closestNames = ptr+3;
}
ptr+=*ptr+3;
}
//Use transformation matrix to work out scene depth
GLdouble model[16];
GLdouble proj[16];
GLint view[4];
glGetDoublev(GL_MODELVIEW_MATRIX, model);
glGetDoublev(GL_PROJECTION_MATRIX, proj);
glGetIntegerv(GL_VIEWPORT, view);
//Map display coordinates [0-1] into depth coordinates.
double xR,yR,zR;
float pixelDepth;
glReadPixels(0, 0, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &pixelDepth);
std::cerr << " PixelDepth :" << pixelDepth << std::endl;
std::cerr << "UnProj:" << gluUnProject(0.5, 0.5, pixelDepth, model,
proj, view, &xR, &yR, &zR) << std::endl;
Thanks.