./jerome{m}jack in

~/Notes/Compute shaders in raylib.md · note · seedling · 7 min · updated

Compute shaders in raylib

// status: seedling

raylib has no LoadComputeShader. Its compute path sits one layer down, in rlgl, and it only exists in a raylib compiled for OpenGL 4.3. The default desktop build targets 3.3, where the same functions are declared, link without complaint, and do nothing.

So the first question is which build you have, not which function to call. This note answers that, then walks the calls through raylib's own example, a Game of Life on two storage buffers, and ends with what to do where compute does not exist at all: macOS and the web. It follows raylib 6.2; the two names that changed since 5.5 are in a table below. What a compute shader is, with its workgroups, shared memory and barriers, is in Compute shaders; the rest of rlgl is in Raylib 3D rendering.

Where it runs

In src/rlgl.h, the body of every compute, storage-buffer and image-binding function is wrapped in #if defined(GRAPHICS_API_OPENGL_43). That define is fixed when raylib itself is compiled, and the desktop default is GRAPHICS_API_OPENGL_33.

TargetCompute through rlglWhy
Windows, Linuxyes, in a 4.3 buildthe driver has to offer an OpenGL 4.3 core context
macOSnoApple's OpenGL stops at 4.1
WebnoWebGL 2 follows OpenGL ES 3.0, which has no compute stage
Android, Raspberry Pi (DRM)nothey build the ES backends, where the same bodies are compiled out

OpenGL ES 3.1 does have compute shaders; rlgl's ES path stops at 3.0.

In a 3.3 build nothing fails loudly:

  • rlLoadShaderProgramCompute returns 0 and logs SHADER: Compute shaders not supported, enable GRAPHICS_API_OPENGL_43.
  • rlLoadShaderBuffer returns 0 and logs SSBO: SSBO not enabled. Define GRAPHICS_API_OPENGL_43.
  • rlComputeShaderDispatch, rlBindShaderBuffer, rlUpdateShaderBuffer and rlReadShaderBuffer compile to empty functions and log nothing.

A program id of 0 is the thing to test for. rlGetVersion() answers the same question before anything is loaded:

c
bool ComputeBuild(void)
{
    return rlGetVersion() == RL_OPENGL_43;
}

On macOS there is no build to switch to. A 4.3 build asks GLFW for a 4.3 core context (src/platforms/rcore_desktop_glfw.c), GLFW's window guide says creation fails when the context it gets is older than the one requested, and Apple's table of Macs lists nothing above OpenGL 4.1. raylib's CMake sets GRAPHICS_API_OPENGL_33 on Apple and prints a warning when OPENGL_VERSION overrides it.

Building raylib for OpenGL 4.3

With CMake the option is OPENGL_VERSION (CMakeOptions.txt), which cmake/LibraryConfigurations.cmake turns into the define:

bash
cmake -B build -DOPENGL_VERSION=4.3
cmake --build build

When raylib arrives through FetchContent, put the option in the cache before FetchContent_MakeAvailable. Raym's CMakeLists.txt does the same thing with "ES 3.0" for its web build:

text
set(OPENGL_VERSION "4.3" CACHE STRING "" FORCE)
FetchContent_MakeAvailable(raylib)

With the Makefile in src/, it is the GRAPHICS variable, which lands on the compiler line as a -D:

bash
make PLATFORM=PLATFORM_DESKTOP GRAPHICS=GRAPHICS_API_OPENGL_43

Both routes default to 3.3, so treat any raylib you did not build yourself as a 3.3 build until rlGetVersion() says otherwise. A 4.3 build keeps the rest of raylib as it was: the define switches GRAPHICS_API_OPENGL_33 on as well, and raylib's default shader stays at #version 330. Your own shaders are free to say #version 430.

The calls

c
// Stage, program, dispatch
unsigned int rlLoadShader(const char *code, int type);    // type: RL_COMPUTE_SHADER
unsigned int rlLoadShaderProgramCompute(unsigned int csId);
void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ);

// Shader storage buffers
unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint);
void rlUnloadShaderBuffer(unsigned int ssboId);
void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset);
void rlBindShaderBuffer(unsigned int id, unsigned int index);
void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset);
void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count);
unsigned int rlGetShaderBufferSize(unsigned int id);

// Image textures
void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly);

Each one wraps a single OpenGL call or a short run of them: glDispatchCompute, glBindBufferBase, glBufferSubData. A compute program is a bare program id, not a raylib Shader, so it is switched on with rlEnableShader(id) and off with rlDisableShader().

Two names changed between 5.5 and 6.0. The rest of the list has the same signatures in both.

raylibCompile the stageLink the programExample
5.5rlCompileShaderrlLoadComputeShaderProgramexamples/others/rlgl_compute_shader.c
6.0, 6.2rlLoadShaderrlLoadShaderProgramComputeexamples/shaders/shaders_rlgl_compute.c

A Game of Life on two buffers

raylib's example is Conway's Game of Life, the automaton from Game of Life in Haskell with the neighbour count moved into a compute shader. Two storage buffers hold one uint per cell; each generation reads one and writes the other. This is the example's logic shader with the comments trimmed and the two upper-bound comparisons changed, for a reason given at the end of the note:

glsl
#version 430

#define GOL_WIDTH 768

layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;

layout(std430, binding = 1) readonly restrict buffer golLayout {
    uint golBuffer[];
};

layout(std430, binding = 2) writeonly restrict buffer golLayout2 {
    uint golBufferDest[];
};

#define fetchGol(x, y) ((((x) < 0) || ((y) < 0) || ((x) >= GOL_WIDTH) || ((y) >= GOL_WIDTH)) \
    ? (0) \
    : golBuffer[(x) + GOL_WIDTH * (y)])

#define setGol(x, y, value) golBufferDest[(x) + GOL_WIDTH*(y)] = value

void main()
{
    uint neighbourCount = 0;
    uint x = gl_GlobalInvocationID.x;
    uint y = gl_GlobalInvocationID.y;

    neighbourCount += fetchGol(x - 1, y - 1);
    neighbourCount += fetchGol(x, y - 1);
    neighbourCount += fetchGol(x + 1, y - 1);
    neighbourCount += fetchGol(x - 1, y);
    neighbourCount += fetchGol(x + 1, y);
    neighbourCount += fetchGol(x - 1, y + 1);
    neighbourCount += fetchGol(x, y + 1);
    neighbourCount += fetchGol(x + 1, y + 1);

    if (neighbourCount == 3) setGol(x, y, 1);
    else if (neighbourCount == 2) setGol(x, y, fetchGol(x, y));
    else setGol(x, y, 0);
}

x and y are unsigned, so x - 1 at the left edge wraps to a very large number and the upper-bound test rejects it. The < 0 tests never fire.

The C side compiles that file as one stage and links it into a program of its own:

c
char *golLogicCode = LoadFileText("resources/shaders/glsl430/gol.glsl");
unsigned int golLogicShader = rlLoadShader(golLogicCode, RL_COMPUTE_SHADER);
unsigned int golLogicProgram = rlLoadShaderProgramCompute(golLogicShader);
UnloadFileText(golLogicCode);

The buffers come next. size is in bytes, a NULL data pointer makes rlgl clear the buffer to zero, and a usage hint of 0 falls back to RL_STREAM_COPY. The example fills its grid with the mouse through a second compute shader; seeding from the CPU is shorter:

c
unsigned int gridBytes = GOL_WIDTH*GOL_WIDTH*sizeof(unsigned int);
unsigned int *seed = (unsigned int *)MemAlloc(gridBytes);
for (int i = 0; i < GOL_WIDTH*GOL_WIDTH; i++) seed[i] = (GetRandomValue(0, 3) == 0);

unsigned int ssboA = rlLoadShaderBuffer(gridBytes, seed, RL_DYNAMIC_COPY);
unsigned int ssboB = rlLoadShaderBuffer(gridBytes, NULL, RL_DYNAMIC_COPY);
MemFree(seed);

One generation is a bind, a dispatch and a swap. The index passed to rlBindShaderBuffer is the binding = N of the shader's layout, and the dispatch counts workgroups, not cells: 768 / 16 = 48 on each axis, which is why the width has to be a multiple of 16.

c
rlEnableShader(golLogicProgram);
rlBindShaderBuffer(ssboA, 1);
rlBindShaderBuffer(ssboB, 2);
rlComputeShaderDispatch(GOL_WIDTH/16, GOL_WIDTH/16, 1);
rlDisableShader();

unsigned int temp = ssboA;
ssboA = ssboB;
ssboB = temp;

Nothing is copied back to draw it. A fragment shader reads the same buffer at binding 1 and turns each cell into a pixel:

glsl
#version 430

in vec2 fragTexCoord;
out vec4 finalColor;

layout(std430, binding = 1) readonly buffer golLayout
{
    uint golBuffer[];
};

uniform vec2 resolution;

void main()
{
    ivec2 coords = ivec2(fragTexCoord*resolution);

    if ((golBuffer[coords.x + coords.y*uvec2(resolution).x]) == 1) finalColor = vec4(1.0);
    else finalColor = vec4(0.0, 0.0, 0.0, 1.0);
}

LoadShader(NULL, path) pairs it with raylib's default vertex shader, which supplies fragTexCoord, and a blank texture the size of the window gives it a quad whose coordinates run from 0 to 1:

c
Shader golRenderShader = LoadShader(NULL, "resources/shaders/glsl430/gol_render.glsl");
const Vector2 resolution = { (float)GOL_WIDTH, (float)GOL_WIDTH };
SetShaderValue(golRenderShader, GetShaderLocation(golRenderShader, "resolution"), &resolution, SHADER_UNIFORM_VEC2);

Image whiteImage = GenImageColor(GOL_WIDTH, GOL_WIDTH, WHITE);
Texture2D whiteTex = LoadTextureFromImage(whiteImage);
UnloadImage(whiteImage);

// Each frame, after the dispatch and the swap: the render shader reads binding 1 too
rlBindShaderBuffer(ssboA, 1);

BeginDrawing();
    ClearBackground(BLANK);
    BeginShaderMode(golRenderShader);
        DrawTexture(whiteTex, 0, 0, WHITE);
    EndShaderMode();
    DrawFPS(10, 10);
EndDrawing();

Moving data in and out

Both directions take the buffer id, a pointer, a size in bytes and an offset in bytes:

c
// CPU -> GPU: data, size in bytes, offset in bytes
rlUpdateShaderBuffer(ssboA, cells, gridBytes, 0);

// GPU -> CPU: destination, size in bytes, offset in bytes
rlReadShaderBuffer(ssboA, cells, gridBytes, 0);

rlReadShaderBuffer is a plain glGetBufferSubData, so it waits for the GPU to finish the work the buffer depends on. It is a tool for tests and for saving state, not for every frame.

A compute program has no Shader struct, so its uniforms go through rlgl as well. rlSetUniform takes no program id; it writes to whichever program is enabled:

c
int widthLoc = rlGetLocationUniform(golLogicProgram, "width");
unsigned int width = GOL_WIDTH;

rlEnableShader(golLogicProgram);
rlSetUniform(widthLoc, &width, RL_SHADER_UNIFORM_UINT, 1);
rlDisableShader();

Pair it with uniform uint width; in the shader and the #define repeated in every file goes away.

Writing to a texture

Storage buffers suit structured data. For an image, bind a texture to an image unit instead:

c
Image blank = GenImageColor(512, 512, BLANK);
Texture2D target = LoadTextureFromImage(blank);    // R8G8B8A8, which rlgl maps to GL_RGBA8 on desktop
UnloadImage(blank);

rlEnableShader(program);
rlBindImageTexture(target.id, 0, target.format, false);    // image unit 0, read-write
rlComputeShaderDispatch(512/16, 512/16, 1);
rlDisableShader();

The format argument is a raylib pixel format. rlgl translates it with rlGetGlTextureFormats, so R8G8B8A8 becomes GL_RGBA8, R32 becomes GL_R32F and R32G32B32A32 becomes GL_RGBA32F. The shader has to declare the matching qualifier, layout(rgba8, binding = 0) uniform image2D target;, or it runs into the format mismatch described in Compute shaders. Access is read-only or read-write, and rlgl always binds mip level 0. None of raylib's examples uses this call.

Without compute

Where the table at the top says no, the usual substitute is a fragment-shader ping-pong: keep the state in a texture, draw a full-size quad into a second render texture through a shader that computes the next state, swap, repeat. raylib 6.0 added exactly this as shaders_game_of_life.c. Its shader ships in GLSL 330 and GLSL 100 and the example asks for nothing beyond OpenGL 3.3 or ES 2.0, which covers a default build, macOS and the web:

c
RenderTexture2D world1 = LoadRenderTexture(worldWidth, worldHeight);
RenderTexture2D world2 = LoadRenderTexture(worldWidth, worldHeight);
RenderTexture2D *currentWorld = &world2;
RenderTexture2D *previousWorld = &world1;

// Render textures are stored upside down: a negative source height flips them back
const Rectangle source = { 0, 0, (float)worldWidth, (float)-worldHeight };
const Rectangle dest = { 0, 0, (float)worldWidth, (float)worldHeight };

// Each generation: draw the previous world into the current one through the shader
RenderTexture2D *tempWorld = currentWorld;
currentWorld = previousWorld;
previousWorld = tempWorld;

BeginTextureMode(*currentWorld);
    BeginShaderMode(step);
        DrawTexturePro(previousWorld->texture, source, dest, (Vector2){ 0, 0 }, 0.0f, RAYWHITE);
    EndShaderMode();
EndTextureMode();

The shader samples the eight neighbours with texture() and writes one colour. That is also the limit of the technique: one output per pixel, at that pixel. No scattered writes, no atomics, no variable-length output. A pipeline like Marching Cubes on the GPU - Count, Scan, Emit does not fit, and it also wants an indirect draw, which rlgl does not wrap. At that point the choices are raw OpenGL beside raylib (OpenGL - learning log) or the CPU.

The CPU version is worth keeping in any case: the same rule as a plain loop, to diff against what rlReadShaderBuffer returns.

Things that tripped me up

  • count is in bytes — rlReadShaderBuffer and rlCopyShaderBuffer hand count straight to glGetBufferSubData and glCopyBufferSubData (src/rlgl.h). rlCopyShaderBuffer also takes the destination first.
  • The grid size is repeated in every file — GOL_WIDTH is a #define in shaders_rlgl_compute.c and in each shader, and the C file carries a comment saying they must match. Nothing checks it.
  • The example's bounds test is off by one — gol.glsl rejects x > GOL_WIDTH and y > GOL_WIDTH, so a coordinate equal to GOL_WIDTH gets through: the right-hand neighbour of the last column is read from the first cell of the next row, and the row under the last one is read from past the end of the buffer. The listing above uses >= for both.
  • rlgl has no memory barrier — glMemoryBarrier appears nowhere in rlgl.h, and the example draws from the buffer its dispatch has just written without one. The OpenGL reference only promises that shader-storage reads "will reflect data written by shaders prior to the barrier" once there is a barrier. src/external/glad.h does declare the function and GL_SHADER_STORAGE_BARRIER_BIT.
  • Draws are batched — raylib queues its 2D and immediate-mode draws until the batch is flushed, so a dispatch written between two draws does not run between them. The example dispatches before BeginDrawing; rlDrawRenderBatchActive() forces the flush when the order matters.

References


Back to Notes · see also Compute shaders · Raylib 3D rendering · GPU Marching Cubes · OpenGL - learning log · Game of Life in Haskell