I've read a lot of topics here, on SO, opengl.org etc. Example how gluUnProject should work (from NeHe tutorial):
winX = (float)x;
winY = (float)viewport[3] - (float)y;
glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
The problem is that gluUnProject
returns mostly zeros, if not zeros then it returns Camera position in World Coords. Value winZ
I'm getting from glReadPixels
is always correct, if I scale it like below:
float z_distance = ProjectionMatrix[14] / (winZ * -2.0 + 1.0 - ProjectionMatrix[10]);
I get distance between near plane and parallel plane that contains mouse click point. Look at the sample below:
gluUnProject( winX, winY, -1, modelview, projection, viewport, &posX1, &posY1, &posZ1);
gluUnProject( winX, winY, 0, modelview, projection, viewport, &posX2, &posY2, &posZ2);
gluUnProject( winX, winY, 1, modelview, projection, viewport, &posX3, &posY3, &posZ3);
gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX4, &posY4, &posZ4);
The result is always the same (posX1,posY1,posZ1)=(posX2,posY2,posZ2)=(posX3,posY3,posZ3)=(posX4,posY4,posZ4)
and is either (0,0,0)
or (Camera-Position.x,Camera-Position.y,Camera-Position.z)
After gluUnProject
I tried to do it manually:
float NDC_x = 2.0f * winX / Width - 1.0f;
float NDC_y = 1.0f - 2.0f * winY / Height;
float winZ = 0;
glReadPixels(winX, (Height - winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
vec4 point1 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, winZ, 1.0f);
vec4 point2 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, -1.0f, 1.0f);
vec4 point3 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, 0.0f, 1.0f);
vec4 point4 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, 1.0f, 1.0f);
Now all points coordinates are different and never zeros but some values, seems like real ones but I don't know how to handle it or I missed something.
BTW I used different approach to get ray (using angles) and it works perfectly. Check here.
Q1: Any suggestions what's wrong with gluUnProject
?
Q2: What is my mistake in manual implementation?
I thought that I messed with row\column-major format, but transposition of matrices had no effect. I read\write matrices as column-major format so last column is (ViewMatrix[12], ViewMatrix[13], ViewMatrix[14], ViewMatrix[15])