Feature guide » Platform support

Integration into windowing toolkits and creation of windowless contexts.

The Platform namespace contains *Application classes integrating Magnum into various toolkits, both windowed and windowless. Each class has slightly different dependencies and platform requirements, see documentation of the Platform namespace and particular *Application classes for more information about building and usage with CMake.

The classes aim to provide a common API to achieve static polymorphism, which ultimately means you should be able to use different toolkits on different platforms by only changing an #include and linking to a different library.

Windowed applications

Windowed applications provide a window, keyboard and pointer input handling. The most widely used toolkit is SDL2, which is implemented in Platform::Sdl2Application. At the very least, provide an one-argument constructor and the drawEvent() function. The class can be then used directly in main(), but for convenience and portability to other toolkits and platforms it's better to use the MAGNUM_SDL2APPLICATION_MAIN() macro. If just a single application header is included, the class is aliased to a Platform::Application typedef and to a MAGNUM_APPLICATION_MAIN() macro.

Barebone application implementation which will just clear the window to dark blue color is shown in the following code listing.

#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Platform/ScreenedApplication.h>
#include <Magnum/Platform/Screen.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Platform/GLContext.h>

using namespace Magnum;
using namespace Magnum::Math::Literals;

class MyApplication: public Platform::Application {
    public:
        explicit MyApplication(const Arguments& arguments);

    private:
        void drawEvent() override;
};

MyApplication::MyApplication(const Arguments& arguments):
    Platform::Application{arguments}
{
    /* Set clear color to a nice blue */
    GL::Renderer::setClearColor(0x2f83cc_rgbf);
}

void MyApplication::drawEvent() {
    /* Clear the window */
    GL::defaultFramebuffer.clear(GL::FramebufferClear::Color);

    /* The context is double-buffered, swap buffers */
    swapBuffers();
}

/* main() function implementation */
MAGNUM_APPLICATION_MAIN(MyApplication)

Handling mouse, touch and pen events

All application implementations have a generalized pointer input that covers mouse, (multi-)touch and pen input in a single interface, exposed through pointerPressEvent(), pointerReleaseEvent() and pointerMoveEvent(). Override a subset based on the events you want to handle. Mouse input is present in every application, touch and pen support varies based on the underlying toolkit.

To make the application touch- and pen-aware, all you need to do is treat Pointer::Finger (and Pointer::Pen) the same way as Pointer::MouseLeft. The pointer types can be ORed into an enum set for a simpler check, as shown below. Additionally, pointer events report also secondary touches from multi-touch interfaces. Unless you specifically handle multi-touch gestures in the application, it makes sense to handle only primary touches, i.e. only the first pressed finger, with PointerEvent::isPrimary(). Mouse and pen input is marked as primary always.

class MyApplication: public Platform::Application {
    

    private:
        void pointerPressEvent(PointerEvent& event) override {
            /* Handling just left mouse press or equivalent */
            if(!event.isPrimary() ||
               !(event.pointer() & (Pointer::MouseLeft|Pointer::Finger)))
                return;

            
            event.setAccepted();
        }

        void pointerReleaseEvent(PointerEvent& event) override {
            /* Handling just left mouse press or equivalent */
            if(!event.isPrimary() ||
               !(event.pointer() & (Pointer::MouseLeft|Pointer::Finger)))
                return;

            
            event.setAccepted();
        }

        void pointerMoveEvent(PointerMoveEvent& event) override {
            /* Handling just left mouse drag or equivalent */
            if(!event.isPrimary() ||
               !(event.pointers() & (Pointer::MouseLeft|Pointer::Finger)))
                return;

            
            event.setAccepted();
        }
};

In addition to the above generalized interface, there's scrollEvent() providing 2D scroll events from a mouse wheel, trackball or touchpad.

See Touch input in SDL2, Touch input in HTML5 and Touch input on Android for additional tookit-specific information. A Platform::TwoFingerGesture helper provides recognition of common two-finger gestures for zoom, rotation and pan.

Attaching to keyboard and text input

The keyPressEvent() and keyReleaseEvent() provide key input events, both a from a physical keyboard and a virtual one on touch-only devices. Apart from the Key being pressed or released, they track information about which keyboard Modifiers are pressed.

For text input there's textInputEvent(), which has to be explicitly enabled with startTextInput() and then disabled again with stopTextInput(). The text input directly gives the application bits of UTF-8 text, matching current keyboard layout, system configuration and other platform-specific state.

Key events are still fired even with text input enabled in order to be able to react to arrow keys for cursor movement, editing shortcuts and such. Key events should not be used for getting actual typed characters, attempting to do so will never lead to a solution that works reliably on all platforms.

class MyApplication: public Platform::Application {
    

    private:
        void keyPressEvent(KeyEvent& event) override {
            /* Editing shortcuts */
            if(event.key() == Key::Z &&
               event.modifiers() == Modifier::Ctrl)
                performUndo();
            else if(event.key() == Key::Z &&
                    event.modifiers() == (Modifier::Shift|Modifier::Ctrl))
                performRedo();
            
            else return;

            event.setAccepted();
        }

        void textInputEvent(TextInputEvent& event) override {
            /* Assuming text input is currently active */
            performInput(, event.text());

            event.setAccepted();
        }
};

For IME and other advanced text editing, certain application implementations provide also a textEditingEvent().

Specifying configuration

By default the application is created with reasonable defaults (such as a window size of 800x600 pixels). Pass a Configuration instance to the application constructor to modify those. Using method chaining it can be done conveniently like this:

MyApplication::MyApplication(const Arguments& arguments):
    Platform::Application{arguments, Configuration{}
        .setTitle("My Application")
        .setSize({12800, 800})}
{
    
}

Responding to window size changes

By default the application doesn't respond to window size changes in any way, and the window has a fixed size. To make the window resizable and properly respond to size changes, construct the application with Configuration::WindowFlag::Resizable and override the viewportEvent() function, where you pass the new size to the default framebuffer and where else is appropriate:

class MyApplication: public Platform::Application {
    public:
        explicit MyApplication(const Arguments& arguments):
            Platform::Application{arguments, Configuration{}
                .addWindowFlags(Configuration::WindowFlag::Resizable)}
        {
            
        }

    private:
        void viewportEvent(ViewportEvent& event) override {
            GL::defaultFramebuffer.setViewport({{}, event.framebufferSize()});
            
        }
};

Windowless applications

Windowless applications provide just a context for offscreen rendering or for performing tasks on a GPU. For OpenGL there is no platform-independent toolkit which could handle this in portable way, thus you have to use platform-specific implementations. Magnum provides windowless applications for GLX and EGL on Unix, CGL on macOS and WGL or EGL on Windows. To make things simple, as an example we will use only Platform::WindowlessEglApplication, below is a link to a bootstrap application for a fully cross-platform example.

You need to implement just the exec() function. The class can be then used directly in main(), but again, for convenience and portability it's better to use the MAGNUM_WINDOWLESSEGLAPPLICATION_MAIN() macro.

Similarly as with windowed applications, if just a single windowless application header is included, the library provides a Platform::WindowlessApplication typedef and a MAGNUM_WINDOWLESSAPPLICATION_MAIN() macro. Changing the code to use a different toolkit is then again a matter of using a different #include and linking to a different library. Aliases for windowless applications are separated from aliases for windowed applications, because projects commonly contain both graphics applications and helper command-line tools for data processing and such.

A barebone application which will just print out the current OpenGL version and renderer string is in the following code listing.

#include <Corrade/Containers/StringView.h>
#include <Magnum/GL/Context.h>
#include <Magnum/Platform/WindowlessEglApplication.h>

using namespace Magnum;

class MyApplication: public Platform::WindowlessApplication {
    public:
        MyApplication(const Arguments& arguments);

        int exec() override;
};

MyApplication::MyApplication(const Arguments& arguments):
    Platform::WindowlessApplication{arguments} {}

int MyApplication::exec() {
    Debug{} << "OpenGL version:" << GL::Context::current().versionString();
    Debug{} << "OpenGL renderer:" << GL::Context::current().rendererString();

    /* Exit with success */
    return 0;
}

/* main() function implementation */
MAGNUM_WINDOWLESSAPPLICATION_MAIN(MyApplication)

Compilation with CMake

Barebone compilation consists just of finding Magnum library with, for example, Sdl2Application component, compilation of the executable and linking Magnum::Magnum and Magnum::Sdl2Application to it.

Again, to simplify porting, you can also use generic Magnum::Application aliases (or Magnum::WindowlessApplication for windowless applications), but only if only one application (windowless application) component is requested to avoid ambiguity. Changing the build script to use different toolkit is then matter of replacing only the requested *Application component (and one #include line in the actual code, as said above).

find_package(Magnum REQUIRED Sdl2Application)

add_executable(myapplication MyApplication.cpp)
target_link_libraries(myapplication
    Magnum::Magnum
    Magnum::Application)

Delayed context creation

Sometimes you may want to set up the application based on a configuration file or system introspection, which can't really be done inside the base class initializer. You can specify NoCreate in the constructor instead and pass the Configuration later to a create() function:

MyApplication::MyApplication(const Arguments& arguments):
    Platform::Application{arguments, NoCreate}
{
    

    create(Configuration{}
        .setTitle("My Application")
        .setSize(size));

    
}

If context creation in the constructor or in create() fails, the application prints an error message to standard output and exits. While that frees you from having to do explicit error handling, sometimes a more graceful behavior may be desirable — with tryCreate() the function returns false instead of exiting and it's up to you whether you abort the launch or retry with different configuration. You can for example try enabling MSAA first, and if the context creation fails, fall back to no-AA rendering:

MyApplication::MyApplication(const Arguments& arguments):
    Platform::Application{arguments, NoCreate}
{
    

    Configuration conf;
    conf.setTitle("My Application");
    GLConfiguration glConf;
    glConf.setSampleCount(16);

    if(!tryCreate(conf, glConf))
        create(conf, glConf.setSampleCount(0));

    
}

Using custom platform toolkits

In case you want to use some not-yet-supported toolkit or you don't want to use the application wrappers in Platform namespace, you can initialize Magnum manually. First create OpenGL context and then create instance of Platform::GLContext class, which will take care of proper initialization and feature detection. The instance must be alive for whole application lifetime. Example main() function with manual initialization is in the following code listing.

int main() {
    // Create OpenGL context ...

    {
        /* Initialize Magnum */
        Platform::GLContext context;

        // Main loop ...

        /* Magnum context gets destroyed */
    }

    // Delete OpenGL context ...
}

On majority of platforms the Platform::GLContext class does GL function pointer loading using platform-specific APIs. In that case you also need to find particular *Context library, add its include dir and then link to it. These platform-specific libraries are available:

  • CglContext — CGL context (macOS)
  • EglContext — EGL context (everywhere except Emscripten)
  • GlxContext — GLX context (X11-based Unix)
  • WglContext — WGL context (Windows)

Systems not listed here (such as Emscripten) don't need any Context library, because dynamic function pointer loading is not available on these.

For example, when you create the OpenGL context using GLX, you need to find GlxContext component, and link to Magnum::GlxContext target. Similarly to application libraries, you can also use the generic Magnum::GLContext target, providing you requested only one *Context component in the find_package() call. Complete example:

find_package(Magnum REQUIRED GlxContext)

add_executable(myapplication MyCustomApplication.cpp)
target_link_libraries(myapplication
    Magnum::Magnum
    Magnum::GLContext)

Manually managing windowless contexts

In case you need to manage windowless OpenGL contexts manually (for example to use Magnum for data processing in a thread or when having more than one OpenGL context), there is a possibility to directly use the context wrappers from windowless applications. Each Platform::Windowless*Application is accompanied by a Platform::Windowless*Context class that manages just GL context creation, making it current and destruction. Similarly to using custom platform toolkits above, the workflow is to first create a GL context instance, then making it current and finally instantiating the Platform::GLContext instance to initialize Magnum.

Similarly as with the applications, to simplify the porting, the library provides Platform::WindowlessGLContext typedef, but only if just one windowless application header is included.

int main(int argc, char** argv) {
    Platform::WindowlessGLContext glContext{{}};
    glContext.makeCurrent();
    Platform::GLContext context{argc, argv};

    // Your GL code ...

    /* Make another context current */
    eglMakeCurrent(display, surface, surface, anotherContext);

    // Someone else's code ...

    /* Make Magnum context current again */
    glContext.makeCurrent();

    // Your GL code again ...

    /* Magnum context gets destroyed */
    /* Windowless GL context gets destroyed */
}

The main purpose of windowless contexts is threaded OpenGL, used for example for background data processing. The workflow is to create the windowless context on the main thread, but make it current in the worker thread. This way the main thread state isn't affected so it can have any other GL context current (for example for the main application rendering). See Thread safety and CORRADE_BUILD_MULTITHREADED for more information.

int main() {
    Platform::WindowlessGLContext glContext{{}};

    std::thread worker{[&glContext]{
        glContext.makeCurrent();
        Platform::GLContext context;

        // Use Magnum here ...
    }};

    // Independent main application code here ...

    worker.join();
}