I tried this example but it doesn't work:
CVector3 GetMouse3DCoords()
{
static POINT IMousePos;
//GetCursorPos(&IMousePos);
IMousePos.x = g_mousex;
IMousePos.y = g_mousey;
int IViewPort[4];
glGetIntegerv(GL_VIEWPORT, IViewPort);
unsigned int IDepth;
// Get the Z coordinate for the pixel location
glReadPixels( IMousePos.x, (IViewPort[3] - IMousePos.y ), 1, 1, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, &IDepth);
int zdepth;
float IDistTermInv;
glGetIntegerv(GL_DEPTH_BITS, &zdepth);
switch(zdepth)
{
case 16:
IDistTermInv = (float) 1.5259018967e-5; //65535
break;
default:
IDistTermInv = (float) 2.32830643708e-10; // 4294967295
break;
}
double IDistance = (float) IDepth * IDistTermInv;
double IModelMatrix[16], IProjMatrix[16];
glGetDoublev(GL_MODELVIEW_MATRIX, IModelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX, IProjMatrix);
double IPos[3];
gluUnProject(IMousePos.x, (IViewPort[3] - IMousePos.y), IDistance, IModelMatrix, IProjMatrix, IViewPort, &IPos[0], &IPos[1], &IPos[2]);
CVector3 ITarget = CVector3( IPos[0], IPos[1], IPos[2] );
return ITarget;
}