glMouseFun(fun);回调的函数void fun(int button,int state, int x, int y)中,(x,y)表示的是鼠标在窗口内的位置,我们需要将其转化为世界坐标系中的位置
//求鼠标在世界坐标系中的位置
void mouse(int button, int state, int x, int y)
{
GLint viewport[4];
GLdouble mvmatrix[16], projmatrix[16];
GLint realy;
GLdouble wx, wy, wz;
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN) {
glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);
glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
realy = viewport[3] - y - 1;
printf("Coordinate at curosr are (%4d, %4d, %4d)\n", x, y,viewport[3]);
gluUnProject(x, realy, 0, mvmatrix, projmatrix, viewport, &wx,
&wy, &wz);
printf("World coords at z=0 are (%f, %f, %f)\n", wx, wy, wz);
gluUnProject(x, realy, 1, mvmatrix, projmatrix, viewport, &wx,
&wy, &wz);
printf("World coords at z=1 are (%f, %f, %f)\n", wx, wy, wz);
}break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN)
exit(0); break;
default: break;
}
}