Reputation: 3788
Like this question states - I want to convert a click (2D) into coordinates relating to the rendering on the screen. I have the function glutMouseFunc
bound to my function (below) but can not make sense of the x and y that are passed in - they seem to be relating to distance in pixels from the top left corner.
I would like to know how to convert the x and y to world coordinates :)
void mouse(int button, int state, int x, int y) {
switch(button) {
case GLUT_LEFT_BUTTON:
printf(" LEFT ");
if (state == GLUT_DOWN) {
printf("DOWN\n");
printf("(%d, %d)\n", x, y);
}
else
if (state == GLUT_UP) {
printf("UP\n");
}
break;
default:
break;
}
fflush(stdout); // Force output to stdout
}
Upvotes: 2
Views: 10303
Reputation: 3788
GLdouble ox=0.0,oy=0.0,oz=0.0;
void Mouse(int button,int state,int x,int y) {
GLint viewport[4];
GLdouble modelview[16],projection[16];
GLfloat wx=x,wy,wz;
if(state!=GLUT_DOWN)
return;
if(button==GLUT_RIGHT_BUTTON)
exit(0);
glGetIntegerv(GL_VIEWPORT,viewport);
y=viewport[3]-y;
wy=y;
glGetDoublev(GL_MODELVIEW_MATRIX,modelview);
glGetDoublev(GL_PROJECTION_MATRIX,projection);
glReadPixels(x,y,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,&wz);
gluUnProject(wx,wy,wz,modelview,projection,viewport,&ox,&oy,&oz);
glutPostRedisplay();
}
Where ox, oy, oz
are your outputted values
http://hamala.se/forums/viewtopic.php?t=20
Upvotes: 5
Reputation: 21
In Windowing system, origin (0,0) is at the Upper Left corner, but OpenGL world window origin (0,0) is at the Lower Left corner.
So you need to convert y coordinates only like such a way:
new_y = window_height - y;
Upvotes: 1