Skip to content

SDL OpenGL

SDL에서 OpenGL 사용하기.

Example

SDL을 사용한 OpenGL초기화 코드는 아래와 같다.

/**
 * @file   main.cpp
 * @brief  Entry-point source file.
 * @author your
 * @date   2015-10-29
 *
 * @remarks
 *  Windows Compile:
 *  @code
 *   g++ -std=c++11 main.cpp -lmingw32 -lSDL2main -lSDL2 -lopengl32
 *  @endcode
 *  @n
 *  Linux Compile:
 *  @code
 *   g++ -std=c++11 main.cpp -lSDL2 -lgl
 *  @endcode
 */

#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <GL/GLU.h>

#include <iostream>
#include <string>

char const * const TITLE = "OPENGL";

int const WINDOW_WIDTH  = 800;
int const WINDOW_HEIGHT = 480;

SDL_Window  * g_window = nullptr;
SDL_GLContext g_opengl = nullptr;

bool init(char const * title, int width, int height)
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        std::cerr << SDL_GetError() << std::endl;
        return false;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

    g_window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED
            , width, height, (SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN));

    if (g_window == nullptr) {
        std::cerr << SDL_GetError() << std::endl;
        return false;
    }

    g_opengl = SDL_GL_CreateContext(g_window);
    if (g_opengl == nullptr) {
        std::cerr << SDL_GetError() << std::endl;
        return false;
    }

    // Use the VSYNC.
    if (SDL_GL_SetSwapInterval(1) < 0) {
        std::cerr << SDL_GetError() << std::endl;
    }

    // Initialize Projection Matrix.
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    // Initialize model view Matrix.
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glClearColor(1.f, 0.f, 0.f, 1.f);

    return true;
}

int main(int argc, char ** args)
{
    if (init(TITLE, WINDOW_WIDTH, WINDOW_HEIGHT) == false) {
        return -1;
    }

    std::cerr << "Start program.\n";

    bool quit = false;
    SDL_Event e;

    while (quit == false) {
        while (SDL_PollEvent(&e) != 0) {
            if (e.type == SDL_QUIT) {
                quit = true;
            }
        }

        glClear(GL_COLOR_BUFFER_BIT);
        glBegin(GL_QUADS);
            glVertex2f(-0.5f, -0.5f);
            glVertex2f( 0.5f, -0.5f);
            glVertex2f( 0.5f,  0.5f);
            glVertex2f(-0.5f,  0.5f);
        glEnd();

        SDL_GL_SwapWindow(g_window);
    }

    SDL_DestroyWindow(g_window);
    SDL_Quit();

    return 0;
}

아래와 같이 컴파일 한다.

$ g++ -std=c++11 main.cpp -lmingw32 -lSDL2main -lSDL2 -lopengl32

See also

Favorite site