//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;