Read me About Demoscene? Links Contact

Translating mouse clicks

Building user interfaces for games or other applications for PC and Mac requires input handlers for mouse, keyboard, etc. I often tend to forget how easy it is to unwrap the 2D-mouse coordinates into 3D-screenspace coordinates. Below is a snippet that I use - it takes 2D-screen coordinates as inputs and unprojects using the model view and projection matrices. As a little bonus it will read the depth buffer for the Z-coordinate.

    vector3f ConvertMouseCoordinates(int screen_pos_x, int screen_pos_y)
    {
        GLint viewport[4];
        GLdouble modelview[16];
        GLdouble projection[16];
        GLfloat winX, winY, winZ;
        GLdouble posX, posY, posZ;

        glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
        glGetDoublev( GL_PROJECTION_MATRIX, projection );
        glGetIntegerv( GL_VIEWPORT, viewport );

        winX = (float)screen_pos_x;
        winY = (float)viewport[3] - (float)screen_pos_y;
        glReadPixels( screen_pos_x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );

        gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

        return vector3f((float)posX, (float)posY, (float)posZ);
    }