c++openglglutfreeglutglu

Center viewport after resize OpenGL / GLUT


Im working in my reshape callback but i cant get the viewport centered after resize, it stays in the top-left corner. Im working with FreeGLUT.

This is my reshape function:

void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, h, 0);
    glMatrixMode(GL_MODELVIEW);
}

This is the un-resized window (1024x768): enter image description here

As you can see, there is a circle in the center of the screen.

This is the full resized window: enter image description here

What im trying to do is no to change the draw resolution, but to center it in the middle of the resized viewport.


Solution

  • The problem is the orthographic projection and the view space coordinates:

    gluOrtho2D(0, w, h, 0);
    

    In this projection, the upper left coordinate is (0, 0) and the lower right is (w, h), so the center is (w/2, h/2), which depends on the size of the view. Since the object's coordinate has not changed, it is no longer in the center of the scene, since the object's coordinate is still the old center (old_w/2, old_h/2).

    Use a projection where the center is (0, 0):

    gluOrtho2D(-w/2, w/2, h/2, -h/2);
    

    Of course, now you need to specify different coordinates for your objects in the scene. e.g. (0, 0) for the center.

    If you want to keep the scene as is, you need to keep the projection. Just change the viewport (glViewport(0, 0, w, h)) but don't change the projection (remove gluOrtho2D(0, w, h, 0)).