LoreleiRS
LoreleiRS

Reputation: 103

glClear() not working

I'm trying to create a rotating cube bur for some reason I'm having trouble just clearing the screen in OpenGL. I'm using OpenGL with SDL2 to create the window and render out things to the window but I'm not sure why it isn't working.

#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;
}

I build and run the program it creates the window, doesn't clear the screen then closes the window after the SDL_Delay(). I'm a little new to OpenGL and would love to know what I'm doing wrong to avoid it in the future. Thanks in advance!

Upvotes: 0

Views: 2577

Answers (1)

lisyarus
lisyarus

Reputation: 15522

The problem is in the fact that the function CreateWindow accepts the window by value. You create a window and store it in a local variable, while the value of global variable window is still undefined. Later, in draw function, you call SDL_GL_SwapWindow(window), that is, you call SDL_GL_SwapWindow with some undefined value.

Looking at your code style, the most simple option would be to remove window and glContext arguments from CreateWindow function and write directly to global variables.

A better C++ solution would be to create a class holding all this variables.

Upvotes: 4

Related Questions