Search code examples
c++openglapi-design

OpenGL - API design


I've been working on my new opengl based rendering engine, and I ran into the following issue: I would like to expose opengl functionalities, like glClear(); glUniformxx, ... but I need the user to create an opengl context before calling any of those functions. The problem is that opengl does not manage contexts for you, and calling any gl functions before results in undefined behaviour(most of the time a segfault). So my question would be How should I impose context creation before any openGL function calls ?

  • My first idea was to create a singleton class called GLFeatures, that would expose all openGL functionalities and only call them if it has been passed a valid context.

Solution

  • TOTALLY OPINION BASED:

    I'd suggest writing an entirely different class for OpenGL context management, this way you can switch between them for multi-window rendering. Your "GLFeatures" class can have a function called "SetCurrentContext", which sets a pointer to the context management class. You can still guard all functions from being called before the context is initialized by just asserting the context pointer at the beginning of each function.

    However, just using the singleton for all of that should work as well, the above is just how I'd do it.