z-erica / cosmopolitan-sdl2

BSD Zero Clause License
30 stars 0 forks source link

Cosmopolitan SDL2

screenshot of the Dear ImGui demo

What is this?

This is a compatibility layer that aims to allow access to a native version of SDL from portable executables linked through Cosmopolitan Libc. The provided API is pinned to SDL 2.0.9.

How does this work?

This replaces the entire implementation of SDL with a shim which leverages its existing dynamic API facility to hook into a version of SDL that is specific to the current runtime platform.

Currently, this dynamic version of SDL is obtained through the first of these steps that is successful:

See sdl2/SDL_dynapi_cosmo.c for specifics. Note that the SDL_CosmoInit procedure, defined in SDL_cosmo.h (which replaces SDL.h), must be executed before any other SDL procedure so the hooks are properly set up. If this fails, the relevant error message must be obtained through SDL_CosmoGetError instead of SDL_GetError, since the latter is dynamically loaded. Neither SDL_CosmoInit or SDL_CosmoGetError are thread safe.

How do you build this?

You will need the cosmocc toolchain in your path. At least version 3.2.2 is needed for proper dlopen support. Running a compatible version of make will yield following the examples in the o/ subdirectory, as portable executables:

Please note that this process will download several files, including prebuilt binaries for some of the runtime targets. The hashes of these executable files are validated with known values to ensure the resulting artifact is reproducible.

The OpenGL loader

To minimize the requirements on the native SDL implementation, the Dear ImGui demo is not bundled with its SDL_Renderer backend. Instead, it includes the OpenGL 3.0 rendering backend, which means that as part of its setup, it is necessary to load the necessary function pointers. SDL provides this functionality through SDL_GL_GetProcAddress. Naturally, the returned pointers require the same treatment as the hooks in sdl2/SDL_dynapi_cosmo.c. A modified version of gl3w generates code that transparently dispatches between calling conventions.

Ideas for improvement