c++openglglutglu

Resizing makes the window's content become thinner on each loop


I was trying to fix an issue where the window stretched out the content, and I finished fixing that. But after trying it out, it works halfway through only.

Here are some images and below is the explanation of the problem:

Image A: (when the app starts)

Original window (after starting up the app)

Image B: (after resizing once in any direction)

The window when resized once in any direction

When I start the application, it is like Image A, a square startup window as expected, without stretching.

Then, if I resize the window in any direction, it begins to stretch more and more each time I resize, as Image B shows.

The resize function runs each time the window is resized thanks to this line in the main function:

glutReshapeFunc(resizeCallback);

Here's the function's code, which I'd assume is causing this:

void resizeCallback(int w, int h) {
glViewport(0, 0, w, h);

glMatrixMode( GL_PROJECTION );

const GLfloat aspectRatio = (GLfloat)w / (GLfloat)h;
gluOrtho2D(-aspectRatio, aspectRatio, -1.0f, 1.0f);

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

I'd appreciate it if anyone helped. It's been a year since I last used OpenGL in C++ and I never got around fixing stretched content issues.


Solution

  • gluOrtho2D not only sets the projection matrix, but defines an orthographic projection matrix and multiplies the current matrix by the new matrix. You need to load the Identity matrix with glLoadIdentity before gluOrtho2D:

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    const GLfloat aspectRatio = (GLfloat)w / (GLfloat)h;
    gluOrtho2D(-aspectRatio, aspectRatio, -1.0f, 1.0f);