闪烁的背景色

时间:2019-02-17 22:08:00

标签: opengl background-color sdl-2

我使用SDL2创建了一个OpenGL窗口,但是背景一直在黑色和黄色之间切换。

#include <SDL2/SDL.h>
#include <GL/glew.h>

#define SCREEN_WIDTH 500
#define SCREEN_HEIGHT 500

int main( int argc, char** argv )
    {
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );

    SDL_Window* gWindow = SDL_CreateWindow( 
        "Title", 
        SDL_WINDOWPOS_UNDEFINED, 
        SDL_WINDOWPOS_UNDEFINED, 
        SCREEN_WIDTH, 
        SCREEN_HEIGHT, 
        SDL_WINDOW_OPENGL);
    SDL_GL_CreateContext( gWindow );

    glewExperimental = GL_TRUE;
    glewInit();

    glPointSize(3);
    glClearColor(1,1,0,0);
    glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    glClear(GL_COLOR_BUFFER_BIT);
    SDL_GL_SetSwapInterval(1);

    int quit=0;
    SDL_Event event;

    while( !quit )
        {
        while(SDL_PollEvent( &event ))
            {
            if( event.type == SDL_QUIT )
                quit = 1;
            }
        SDL_GL_SwapWindow( gWindow );
        }
    SDL_DestroyWindow(gWindow);
    return 0;
    }

我希望背景为黄色,如glClearColor(1,1,0,0)所定义,在程序运行时不会闪烁。代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

闪烁的原因是您正在使用双缓冲,但是没有清除黄色的缓冲区之一(即请注意,您在代码中只调用一次glClear)。

我建议您每帧调用glClear。要修复您的代码,您可以将调用移到SDL_GL_SwapWindow之前的循环中:

while( !quit )
{
    while(SDL_PollEvent( &event ))
    {
        if( event.type == SDL_QUIT )
            quit = 1;
    }

    glClear(GL_COLOR_BUFFER_BIT);
    SDL_GL_SwapWindow( gWindow );
}