Search code examples
openglsdlsdl-2opengl-2.0

Resizing window using SDL and OpenGL


Before writing this question, I have read the question: Handling window resizing using OpenGL and SDL. However that question does not solve my problem, since I am using SDL2 and not SDL1.2. But I do use OpenGL2. My complete source code is available at: http://dpaste.com/17BVBP6

I am writing a program that displays a white square in the window. However I am having trouble while handling window resize events.Here is my resize function:

void resize(int width,int height)
{
    if(height<=0)    height=1;

    glViewport(0,0,(GLsizei)width,(GLsizei)height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0f,float(width)/float(height),1.0f,100.0f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

My Main event loop:

while( !quit )
        {
            while( SDL_PollEvent( &e ) != 0 )
            {
                switch (e.type) {
                case SDL_QUIT:
                    quit=true;
                    break;
                case SDL_WINDOWEVENT_SIZE_CHANGED:
                    resize(e.window.data1,e.window.data2);
                    break;
                case SDL_KEYDOWN:
                    switch (e.key.keysym.sym) {
                    case SDLK_ESCAPE:
                        quit=true;
                        break;
                    default:
                        break;
                    }
                default:
                    break;
                }
            }

            render();

            update(gWindow);
        }

Here is my window when it is not resized: Rendering is done properly when not resized

Here is my window when it is resized: Rendering is not properly done when resized

What is the causing the problem here??


Solution

  • SDL_WINDOWEVENT_SIZE_CHANGED is not an event type, it is variation of SDL_WINDOWEVENT. Your event checking should be like

    switch(e.type) {
        case SDL_WINDOWEVENT:
            if(e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
                resize(e.window.data1,e.window.data2);
            }
            break;
    

    Also remove your perspective projection setting - it is inconsistend with your draw, and you don't have perspective setup before resize.