gluUnProject()
返回的值是预期值的一半。
答案 0 :(得分:1)
视网膜显示屏具有DPI缩放比例,因此帧缓冲区大小和屏幕大小不匹配。
解决方法是将屏幕坐标与devicePixelRatio相乘,可以如下计算
const GLint WIDTH = 800, HEIGHT = 800;
glfwCreateWindow(WIDTH, HEIGHT, "Test Window", NULL, NULL);
int bufferWidth, bufferHeight;
glfwGetFramebufferSize(mainWindow, &bufferWidth, &bufferHeight);
devicePixelRatio = bufferWidth / WIDTH;
然后,您可以使用以下代码段来计算世界坐标。
void cursor_position_callback(GLFWwindow *window, double xpos, double ypos) {
xpos *= devicePixelRatio;
ypos *= devicePixelRatio;
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ = 0;
GLdouble posX, posY, posZ;
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
winX = (float)xpos;
winY = (float)viewport[3] - (float)ypos;
glReadPixels(xpos, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY,
&posZ);
cout<<posx<<posy<<posz<<endl;
}