Code部分還蠻簡單的,就直接貼上去做memo。
CDSVector3d COpenGLDrawer::ConvertWinPos2OGLPos(int x, int y)
{
//Reference:http://nehe.gamedev.net/data/articles/article.asp?article=13
//1. Viewport Origin And Extent
// We need to grab the current viewport.
// The information we need is the starting X and Y position of our GL viewport along with the viewport width and height.
// Once we get this information using glGetIntegerv(GL_VIEWPORT, viewport), viewport will hold the following information:
// viewport[0]=x
// viewport[1]=y
// viewport[2]=width
// viewport[3]=height
GLint glnViewPort[4]; //Where the Viewport will be stored
::glGetIntegerv(GL_VIEWPORT, glnViewPort); //Retrieves the Viewport values (X, Y, Width, Height)
//2. The Modelview Matrix
// Once we have the viewport information, we can grab the Modelview information.
// The Modelview Matrix determines how the vertices of OpenGL primitives are transformed to eye coordinates.
GLdouble gldModelView[16]; //Where the 16 doubles of the Modelview matrix are to be stored
::glGetDoublev(GL_MODELVIEW_MATRIX, gldModelView); //Retrieve the Modelview Matrix
//3. The Projection Matrix
// After that, we need to get the Projection Matrix. The Projection Matrix transforms vertices in eye coordinates to clip coordinates.
GLdouble gldProjection[16]; //Where the 16 doubles of the Projection Matrix are to be strored
::glGetDoublev(GL_PROJECTION_MATRIX, gldProjection); //Retrieve the Projetion Matrix
//4. The Windows Screen Coordinates
// After we have done all of that, we can grab the Windows screen coordinates. We are interested in the current mouse position.
GLfloat glfWinX = 0.0f, glfWinY = 0.0f, glfWinZ = 0.0f; //Holds Our X, y and Z coordinates
glfWinX = (float)x; //Holds the mouse X Coordinate
glfWinY = (float)y; //Holds the mouse Y Corrdinate
//Now Windows coordinates start with (0, 0) being at the top left whereas OpenGL coords start at the lower left. To convert to OpenGL coordinates we do the following:
glfWinY = (float)(glnViewPort[3] - glfWinY); //Subtract the current Mouse Y Corrdinate from the screen height.
//Get z corrdinate
::glReadPixels(glfWinX, glfWinY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &glfWinZ);
//5. Variables Where The Output OpenGL Coords Will Be Stored
// All that is left to do is calculate our final OpenGL coordinates.
GLdouble gldPosX, gldPosY, gldPosZ; //Hold the Final value
::gluUnProject( glfWinX, glfWinY, glfWinZ, gldModelView, gldProjection, glnViewPort, &gldPosX, &gldPosY, &gldPosZ);
return CDSVector3d(gldPosX, gldPosY, gldPosZ);
}
這邊用到的CDSVector3d是自訂的座標物件。
No comments:
Post a Comment