I am using this code from NEHE tutorial in my MFC based application on mouseclick
void CRightOGL::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
GLint viewport[4];
GLdouble modelview[16]={0};
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
GLfloat mv[16];
glGetFloatv( GL_MODELVIEW_MATRIX, mv );
glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );
winX = (float)point.x;
winY = (float)viewport[3] - (float)point.y;
glReadPixels(point.x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
COpenGLControl::OnLButtonDown(nFlags, point);
}
But the problem is that i am getting incorrect values every time posX, &posY, &posZ... and values always comes in -9.25555 , -9.255555 ,-9.255555. Not only this but also modelview matrix is returning same -9.555 value everytime.
If i initialize everything as 0 then posX,posY and PosZ returns me only 0 instead of correct coordinates. Mouse x and y values are perfectly fine so from mouse side there is no issue.
What i am doing wrong?
my opengl initialization code is as follow
void COpenGLControl::oglInitialize(void)
{
// Initial Setup:
//
static PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32, // bit depth
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
16, // z-buffer depth
0, 0, 0, 0, 0, 0, 0,
};
// Get device context only once.
hdc = GetDC()->m_hDC;
// Pixel format.
m_nPixelFormat = ChoosePixelFormat(hdc, &pfd);
SetPixelFormat(hdc, m_nPixelFormat, &pfd);
// Create the OpenGL Rendering Context.
hrc = wglCreateContext(hdc);
wglMakeCurrent(hdc, hrc);
// Basic Setup:
//
// Set color to use when clearing the background.
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
// Turn on backface culling
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
// Turn on depth testing
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH);
//glEnable(GL_TEXTURE_2D); // Enable 2D textures
// Send draw request
GLenum a = glGetError();
OnDraw(NULL);
}