2

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
}
Community
  • 1
  • 1
Tyler Wall
  • 3,747
  • 7
  • 37
  • 52
  • possible duplicate of [how do i calculate the Touch on openGL using glUnProject](http://stackoverflow.com/questions/6464232/how-do-i-calculate-the-touch-on-opengl-using-glunproject) – datenwolf Feb 03 '12 at 09:14
  • That one's in Objective C... and there's no concrete answer - I think getting this answered in C will help others in whatever platform they're using :) – Tyler Wall Feb 04 '12 at 02:18
  • @Walter: The language makes no difference here. OpenGL itself is not concerned with actually handling input events, that's task of the framework used. A generalized answer had to take into account all frameworks out there – or none at all. I answered it in the most general way possible. Also the code in the question itself (gluUnproject) works in plain C as well. – datenwolf Feb 04 '12 at 12:49

2 Answers2

5
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

Tyler Wall
  • 3,747
  • 7
  • 37
  • 52
1

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;

nedret ozay
  • 21
  • 1
  • 4