Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing an OpenGL window causes it to fall apart

For some reason when I resize my OpenGL windows, everything falls apart. The image is distorted, the coordinates don't work, and everything simply falls apart. I am sing Glut to set it up.

//Code to setup glut
glutInitWindowSize(appWidth, appHeight);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutCreateWindow("Test Window");

//In drawing function
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);

//Resize function
void resize(int w, int h)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, h, 0);
}

The OpenGL application is strictly 2D.

This is how it looks like initially: http://www.picgarage.net/images/Corre_53880_651.jpeg

this is how it looks like after resizing: http://www.picgarage.net/images/wrong_53885_268.jpeg

like image 1000
Alexander Avatar asked Dec 04 '22 16:12

Alexander


1 Answers

You should not forget to hook the GLUT 'reshape' event:

glutReshapeFunc(resize);

And reset your viewport:

void resize(int w, int h)
{
    glViewport(0, 0, width, height); //NEW
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, h, 0);
}

A perspective projection would have to take the new aspect ratio into account:

void resizeWindow(int width, int height)
{
    double asratio;

    if (height == 0) height = 1; //to avoid divide-by-zero

    asratio = width / (double) height;

    glViewport(0, 0, width, height); //adjust GL viewport

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(FOV, asratio, ZMIN, ZMAX); //adjust perspective
    glMatrixMode(GL_MODELVIEW);
}
like image 187
aib Avatar answered Dec 09 '22 15:12

aib