Search code examples
openglsdl

Creating an OpenGL context using SDL2 on macOS


How do I create an OpenGL context using SDL2 on macOS, without incorporating any external libraries like GLAD or GLEW, relying solely on SDL?

I expect to simply open an OpenGL window using SDL2, serving that as a starting point for further graphics development.


Solution

  • To get started, you'll first need to install the Command Line Tools onto your system. This can be done by executing xcode-select --install in the terminal. This will install some essential dependencies required for executing specific commands. If you haven't already installed SDL2, you'll also need to do so and make sure it is located in your ~/Library/Frameworks folder.

    Once you have completed these prerequisites, you're ready to establish an OpenGL context. However, it's important to note that Apple deprecated OpenGL a few years back. As a result, you are limited to using older supported versions of OpenGL, specifically versions 4.1 and 3.2.

    To create the OpenGL context, include the following libraries in your project: SDL.h and SDL_openGL.h. These will ensure you have the right dependencies to be able to open up an OpenGL window.

    Below is a basic program in c++ I've written to initialize an OpenGL window. This example should help you get started with your project:

    #include <SDL.h>
    #include <SDL_opengl.h>
    
    int main(int argc, char* argv[]) {
        SDL_Init(SDL_INIT_VIDEO);
    
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    
        SDL_Window* window = SDL_CreateWindow("OpenGL Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
        SDL_GLContext context = SDL_GL_CreateContext(window);
    
        bool running = true;
        SDL_Event event;
        while (running) {
            while (SDL_PollEvent(&event)) {
                if (event.type == SDL_QUIT) {
                    running = false;
                }
            }
    
            glClear(GL_COLOR_BUFFER_BIT);
            SDL_GL_SwapWindow(window);
        }
    
        SDL_GL_DeleteContext(context);
        SDL_DestroyWindow(window);
        SDL_Quit();
    
        return 0;
    }
    

    Good luck!