0
\$\begingroup\$

I am using GLUT's glutMouseFunc() function to retrieve the coordinates of mouse clicks. I want to move the object on that coordinate to another coordinate. But when I click on the object the coordinates returned by glutMouseFunc() are different than the original.

windowWidth=1250;
windowHeight=1000;

void onMouse(int button, int state, int x, int y);

int main(int argc, char** argv) {

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(1250, 1000);
    glutCreateWindow("OpenGL - First window demo");
    // ...
    glutMouseFunc(onMouse);
    // ...
    glutMainLoop();
    return 0;
}

void onMouse(int button, int state, int x, int y) {
    flag++;
    if (state != GLUT_DOWN && button!=GLUT_LEFT_BUTTON)
        return;

    GLbyte color[4];
    GLfloat depth;
    GLuint index;

    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, color);
    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);

    printf("Clicked on pixel %d, %d, color %02hhx%02hhx%02hhx%02hhx, depth %f, stencil index %u\n", x, y, color[0], color[1], color[2], color[3], depth, index);
    move();
}

Inside my render function i have set the window coordinates to 0,0 using glortho

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, windowWidth, windowHeight, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); 

If my object is at (550, 900), onMouse() reports it as (556, 650) while if I click on an object which is at position (375, 475) the onMouse() returns (376, 342).

Basically there is a huge difference between the value of y axis returned by the function.

How can i get the correct screen coordinates?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The documentation explicitly says that the sizes you provide to GLUT are hints to the windowing system. The actual size of the window has to be determined either via the reshape callback or by querying for the actual client area size, if available.

Your orthographic projection is thus probably not 1:1 mapping to pixels.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .