glClear()无法正常工作

时间:2014-11-21 15:58:32

标签: c++ opengl

我正在尝试创建一个旋转的立方体bur由于某种原因我在OpenGL中清除屏幕时遇到了麻烦。我正在使用带有SDL2的OpenGL创建窗口并将窗口渲染到窗口但我不确定它为什么不起作用。

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

SDL_Window* window;
SDL_GLContext glContext;

void CreateWindow(SDL_Window* window, SDL_GLContext glContext, const std::string& title, int width, int height) {
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
    if (window == NULL) {
        std::cerr << "Window could not be created" << std::endl;
    }
    glContext = SDL_GL_CreateContext(window);
    if (glContext == NULL) {
        std::cerr << "OpenGL context could not be opened" << std::endl;
    }
    GLuint status = glewInit();
    if (status != GLEW_OK) {
        std::cerr << "GLEW could not be initialized" << std::endl;
    }
}
void DestroyWindow() {
    SDL_GL_CreateContext(window);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

void draw() {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    SDL_GL_SwapWindow(window);
}

int main() {
    CreateWindow(window, glContext, "Hello", 800, 600);
    draw();
    SDL_Delay(2000);
    DestroyWindow();

    return 0;
}

我构建并运行它创建窗口的程序,不清除屏幕然后在SDL_Delay()之后关闭窗口。我对OpenGL有点新意,并且很想知道我将来做错了什么以避免它。提前谢谢!

1 个答案:

答案 0 :(得分:4)

问题在于函数CreateWindow按值接受window。您创建一个窗口并将其存储在局部变量中,而全局变量window的值仍未定义。稍后,在draw函数中,您调用SDL_GL_SwapWindow(window),也就是说,您使用某个未定义的值调用SDL_GL_SwapWindow

查看代码样式,最简单的选择是从window函数中删除glContextCreateWindow个参数,并直接写入全局变量。

更好的C ++解决方案是创建一个包含所有这些变量的类。