Raylib Module

GX includes a raylib module for game and graphics development. Raylib is a simple C library for games — no callbacks, no complex setup, just a polling game loop. The GX module wraps raylib’s C API directly via extern fn and extern struct, keeping the familiar PascalCase naming.

Prerequisites

Raylib must be installed separately. You need:

  1. raylib.h — place in modules/raylib/c/
  2. raylib.lib (MSVC) or libraylib.a (GCC) — place in modules/raylib/lib/
  3. Clang or GCC — required for linking

Usage

Import the sub-modules you need:

import raylib.core      // window, timing, drawing, shaders, camera, structs
import raylib.input     // keyboard/mouse enums and functions
import raylib.shapes    // 2D shape drawing, splines, collision
import raylib.text      // text drawing, fonts, codepoints
import raylib.textures  // texture/image loading, drawing, color utilities
import raylib.colors    // color constants (rl_red, rl_blue, etc.)
import raylib.models    // 3D shapes, model loading, mesh, materials
import raylib.audio     // sound, music streaming, audio streams

Build with -I modules:

gx myapp.gx -I modules -o myapp.exe

Hello World

import raylib.core
import raylib.input
import raylib.shapes
import raylib.text
import raylib.colors

fn main() {
    InitWindow(800, 450, "GX + Raylib")
    SetTargetFPS(60)

    while (!WindowShouldClose()) {
        BeginDrawing()
        ClearBackground(rl_raywhite())

        DrawText("Hello from GX!", 190, 200, 20, rl_darkgray())
        DrawRectangle(100, 100, 200, 80, rl_red())
        DrawCircle(400, 300, 50.0, rl_blue())
        DrawFPS(10, 10)

        if (IsKeyPressed(KEY_ESCAPE)) {
            CloseWindow()
            return
        }

        EndDrawing()
    }
    CloseWindow()
}

Core (raylib.core)

Structs

All raylib types are declared as extern struct and used directly:

StructFieldsDescription
Vector2x, y: f322D vector/point
Vector3x, y, z: f323D vector/point
Vector4x, y, z, w: f324D vector/quaternion
Matrixm0..m15: f324x4 transformation matrix
Colorr, g, b, a: u8RGBA color
Rectanglex, y, width, height: f32Rectangle
Imagedata: *void, width, height, mipmaps, formatCPU image data
Textureid: c_uint, width, height, mipmaps, formatGPU texture
RenderTextureid, texture, depthRender target
NPatchInfosource: Rectangle, left, top, right, bottom, layoutN-patch layout
GlyphInfovalue, offsetX, offsetY, advanceX, imageGlyph data
FontbaseSize, glyphCount, glyphPadding, texture, recs, glyphsFont data
Camera2Doffset, target: Vector2, rotation, zoom: f322D camera
Camera3Dposition, target, up: Vector3, fovy: f32, projection3D camera
Shaderid: c_uint, locs: *c_intShader program
MaterialMaptexture, color, valueMaterial texture map
Materialshader, maps, paramsRendering material
MeshvertexCount, triangleCount, vertices, normals, ...Vertex data
Modeltransform, meshes, materials, bones, ...3D model
ModelAnimationboneCount, frameCount, bones, framePoses, nameSkeletal animation
Rayposition, direction: Vector3Ray for raycasting
RayCollisionhit: bool, distance, point, normalRay hit result
BoundingBoxmin, max: Vector3Axis-aligned box
Transformtranslation, rotation, scaleBone transform
BoneInfoname, parentSkeleton bone
WaveframeCount, sampleRate, sampleSize, channels, dataAudio wave data
AudioStreambuffer, processor, sampleRate, sampleSize, channelsAudio stream
Soundstream: AudioStream, frameCountLoaded sound
Musicstream, frameCount, looping, ctxType, ctxDataStreamed music

Construct structs by declaring a variable and setting fields:

var pos:Vector2
pos.x = 100.0
pos.y = 200.0

Window Functions

FunctionSignatureDescription
InitWindow(c_int, c_int, cstr)Create window with width, height, title
CloseWindow()Close window and clean up
WindowShouldClose→ boolCheck if window should close
IsWindowReady→ boolCheck if window initialized
IsWindowFullscreen→ boolCheck fullscreen state
IsWindowMinimized→ boolCheck if minimized
IsWindowMaximized→ boolCheck if maximized
IsWindowFocused→ boolCheck if focused
IsWindowResized→ boolCheck if resized last frame
SetWindowTitle(cstr)Change window title
SetWindowSize(c_int, c_int)Resize window
SetWindowPosition(c_int, c_int)Set window position
SetWindowMinSize(c_int, c_int)Set minimum dimensions
SetWindowMaxSize(c_int, c_int)Set maximum dimensions
SetWindowOpacity(f32)Set opacity (0.0..1.0)
GetScreenWidth→ c_intGet current width
GetScreenHeight→ c_intGet current height
GetRenderWidth→ c_intRender width (HiDPI)
GetRenderHeight→ c_intRender height (HiDPI)
GetMonitorCount→ c_intNumber of monitors
GetMonitorWidth(c_int) → c_intMonitor width
GetMonitorHeight(c_int) → c_intMonitor height
GetMonitorRefreshRate(c_int) → c_intMonitor refresh rate
GetWindowPosition→ Vector2Window position
ToggleFullscreen()Toggle fullscreen mode
ToggleBorderlessWindowed()Toggle borderless windowed
MaximizeWindow()Maximize window
MinimizeWindow()Minimize window
RestoreWindow()Restore window
SetConfigFlags(c_uint)Set window flags before InitWindow
SetClipboardText(cstr)Set clipboard text
GetClipboardText→ cstrGet clipboard text

Drawing Lifecycle

FunctionDescription
BeginDrawing()Start frame drawing
EndDrawing()End frame, swap buffers
ClearBackground(color)Clear framebuffer
BeginMode2D(camera)Begin 2D camera mode
EndMode2D()End 2D camera mode
BeginMode3D(camera)Begin 3D camera mode
EndMode3D()End 3D camera mode
BeginTextureMode(target)Draw to render texture
EndTextureMode()Stop drawing to render texture
BeginShaderMode(shader)Begin custom shader
EndShaderMode()End custom shader
BeginBlendMode(mode)Begin blending mode
EndBlendMode()End blending mode
BeginScissorMode(x, y, w, h)Begin scissor clipping
EndScissorMode()End scissor clipping

Shader Functions

FunctionSignatureDescription
LoadShader(cstr, cstr) → ShaderLoad vertex + fragment shader
LoadShaderFromMemory(cstr, cstr) → ShaderLoad shader from strings
IsShaderValid(Shader) → boolCheck shader validity
GetShaderLocation(Shader, cstr) → c_intGet uniform location
SetShaderValue(Shader, c_int, *void, c_int)Set shader uniform
SetShaderValueMatrix(Shader, c_int, Matrix)Set matrix uniform
UnloadShader(Shader)Free shader

Screen-Space

FunctionDescription
GetScreenToWorldRay(pos, camera)Screen point to 3D ray
GetWorldToScreen(pos3d, camera)3D point to screen coords
GetWorldToScreen2D(pos, camera2d)2D world to screen
GetScreenToWorld2D(pos, camera2d)Screen to 2D world
GetCameraMatrix(camera)Get camera transform matrix

Timing

FunctionSignatureDescription
SetTargetFPS(c_int)Set target FPS (0 = unlimited)
GetFPS→ c_intGet current FPS
GetFrameTime→ f32Delta time in seconds
GetTime→ f64Time since InitWindow

Mouse (Core)

FunctionSignatureDescription
GetMousePosition→ Vector2Mouse position
GetMouseDelta→ Vector2Mouse movement since last frame
GetMouseWheelMove→ f32Mouse wheel movement
GetMouseWheelMoveV→ Vector2Mouse wheel XY movement
GetMouseX→ c_intMouse X position
GetMouseY→ c_intMouse Y position
SetMousePosition(c_int, c_int)Set mouse position
SetMouseCursor(c_int)Set mouse cursor icon

Touch & Gestures

FunctionDescription
GetTouchPosition(index)Touch position for finger
GetTouchPointCount()Number of touch points
SetGesturesEnabled(flags)Enable gesture types
IsGestureDetected(gesture)Check gesture detected
GetGestureDragVector()Drag direction
GetGesturePinchVector()Pinch delta

Camera

FunctionDescription
UpdateCamera(camera, mode)Update camera with built-in mode
UpdateCameraPro(camera, movement, rotation, zoom)Manual camera update

Gamepad

FunctionDescription
IsGamepadAvailable(id)Check if gamepad connected
GetGamepadName(id)Get gamepad name
IsGamepadButtonPressed(id, btn)Button pressed this frame
IsGamepadButtonDown(id, btn)Button held
GetGamepadAxisMovement(id, axis)Axis value (-1.0..1.0)
SetGamepadVibration(id, left, right, dur)Rumble

Random

FunctionDescription
SetRandomSeed(seed)Set random seed
GetRandomValue(min, max)Random integer in range

Misc

FunctionDescription
TakeScreenshot(fileName)Save screenshot
OpenURL(url)Open URL in browser

Input (raylib.input)

Keyboard

if (IsKeyPressed(KEY_SPACE)) { jump() }
if (IsKeyDown(KEY_A)) { move_left() }
FunctionSignatureDescription
IsKeyPressedKeyboardKey → boolKey pressed this frame
IsKeyPressedRepeatKeyboardKey → boolKey pressed (with repeat)
IsKeyDownKeyboardKey → boolKey being held
IsKeyReleasedKeyboardKey → boolKey released this frame
IsKeyUpKeyboardKey → boolKey not being held
GetKeyPressed→ c_intGet key from queue

All keyboard keys are available as enum constants: KEY_A through KEY_Z, KEY_ZERO through KEY_NINE, KEY_SPACE, KEY_ESCAPE, KEY_ENTER, KEY_TAB, KEY_F1 through KEY_F12, arrow keys (KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT), modifiers (KEY_LEFT_SHIFT, KEY_LEFT_CONTROL, KEY_LEFT_ALT), and more.

Mouse Buttons

if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) { shoot() }
FunctionSignatureDescription
IsMouseButtonPressedMouseButton → boolButton pressed this frame
IsMouseButtonDownMouseButton → boolButton being held
IsMouseButtonReleasedMouseButton → boolButton released this frame
IsMouseButtonUpMouseButton → boolButton not being held

Constants: MOUSE_BUTTON_LEFT, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_MIDDLE.

Shapes (raylib.shapes)

Lines

FunctionDescription
DrawLine(x1, y1, x2, y2, color)Draw line (integer coords)
DrawLineV(start, end, color)Draw line (Vector2)
DrawLineEx(start, end, thick, color)Draw thick line

Circles

FunctionDescription
DrawCircle(cx, cy, radius, color)Filled circle
DrawCircleV(center, radius, color)Filled circle (Vector2)
DrawCircleLines(cx, cy, radius, color)Circle outline
DrawCircleGradient(cx, cy, radius, inner, outer)Gradient circle

Rectangles

FunctionDescription
DrawRectangle(x, y, w, h, color)Filled rectangle
DrawRectangleV(pos, size, color)Filled rectangle (Vector2)
DrawRectangleRec(rec, color)Filled rectangle (Rectangle)
DrawRectanglePro(rec, origin, rotation, color)Rotated rectangle
DrawRectangleLines(x, y, w, h, color)Rectangle outline
DrawRectangleLinesEx(rec, thick, color)Thick outline
DrawRectangleRounded(rec, roundness, segments, color)Rounded corners
DrawRectangleGradientV(x, y, w, h, top, bottom)Vertical gradient
DrawRectangleGradientH(x, y, w, h, left, right)Horizontal gradient

Triangles and Polygons

FunctionDescription
DrawTriangle(v1, v2, v3, color)Filled triangle
DrawTriangleLines(v1, v2, v3, color)Triangle outline
DrawPoly(center, sides, radius, rotation, color)Regular polygon

Collision Detection

FunctionDescription
CheckCollisionRecs(r1, r2)Rectangle vs rectangle
CheckCollisionCircles(c1, r1, c2, r2)Circle vs circle
CheckCollisionCircleRec(center, radius, rec)Circle vs rectangle
CheckCollisionPointRec(point, rec)Point vs rectangle
CheckCollisionPointCircle(point, center, radius)Point vs circle
GetCollisionRec(r1, r2)Get overlap rectangle

Text (raylib.text)

FunctionSignatureDescription
DrawText(cstr, x, y, fontSize, color)Draw with default font
DrawFPS(x, y)Draw FPS counter
MeasureText(cstr, fontSize) → c_intGet text width in pixels
LoadFont(cstr) → FontLoad font from file
UnloadFont(Font)Free font resources
DrawTextEx(font, cstr, pos, size, spacing, color)Draw with custom font
GetFontDefault→ FontGet built-in default font

Textures (raylib.textures)

FunctionSignatureDescription
LoadTexture(cstr) → TextureLoad from file (PNG, JPG, etc.)
UnloadTexture(Texture)Free GPU texture
DrawTexture(texture, x, y, tint)Draw at position
DrawTextureV(texture, pos, tint)Draw at Vector2 position
DrawTextureEx(texture, pos, rot, scale, tint)Draw with transforms
DrawTextureRec(texture, source, pos, tint)Draw sub-rectangle
LoadRenderTexture(w, h) → RenderTextureCreate render target
UnloadRenderTexture(RenderTexture)Free render target

Colors (raylib.colors)

Raylib colors are provided as functions prefixed with rl_:

var bg = rl_raywhite()       // Light background
var fg = rl_darkgray()       // Dark text
var highlight = rl_red()     // Bright red
FunctionRGBDescription
rl_white()255, 255, 255White
rl_black()0, 0, 0Black
rl_red()230, 41, 55Red
rl_green()0, 228, 48Green
rl_blue()0, 121, 241Blue
rl_yellow()253, 249, 0Yellow
rl_orange()255, 161, 0Orange
rl_pink()255, 109, 194Pink
rl_purple()200, 122, 255Purple
rl_skyblue()102, 191, 255Sky Blue
rl_gray()130, 130, 130Gray
rl_darkgray()80, 80, 80Dark Gray
rl_lightgray()200, 200, 200Light Gray
rl_raywhite()245, 245, 245Raylib White
rl_blank()0, 0, 0, 0Transparent

Custom colors with rl_color:

var custom = rl_color(128, 64, 200, 255)    // r, g, b, a

Models (raylib.models)

3D Shape Drawing

DrawCube(pos, 2.0, 2.0, 2.0, rl_red())
DrawSphere(pos, 1.0, rl_blue())
DrawGrid(10, 1.0)
FunctionDescription
DrawCube/VDraw cube (size or Vector3)
DrawCubeWires/VCube wireframe
DrawSphere/Ex/WiresSphere (solid/custom/wireframe)
DrawCylinder/Ex/Wires/WiresExCylinder variants
DrawCapsule/WiresCapsule shape
DrawPlaneFlat plane
DrawLine3D3D line
DrawPoint3D3D point
DrawCircle3D3D circle
DrawTriangle3D3D triangle
DrawGridReference grid
DrawRayVisualize a ray

Model Loading & Drawing

FunctionDescription
LoadModel(fileName)Load 3D model from file
LoadModelFromMesh(mesh)Create model from mesh
UnloadModel(model)Free model resources
IsModelValid(model)Check model validity
DrawModel(model, pos, scale, tint)Draw model
DrawModelEx(model, pos, axis, angle, scale, tint)Draw with rotation
DrawBillboard(cam, tex, pos, scale, tint)Camera-facing quad

Mesh Generation

var cube = GenMeshCube(1.0, 1.0, 1.0)
var sphere = GenMeshSphere(0.5, 16, 16)

Functions: GenMeshPoly, GenMeshPlane, GenMeshCube, GenMeshSphere, GenMeshHemiSphere, GenMeshCylinder, GenMeshCone, GenMeshTorus, GenMeshKnot, GenMeshHeightmap, GenMeshCubicmap.

3D Collision

FunctionDescription
CheckCollisionSpheresSphere vs sphere
CheckCollisionBoxesAABB vs AABB
CheckCollisionBoxSphereAABB vs sphere
GetRayCollisionSphere/Box/Mesh/Triangle/QuadRay intersection tests

Audio (raylib.audio)

Setup

InitAudioDevice()
defer CloseAudioDevice()

Sound (short samples)

var sfx = LoadSound("explosion.wav")
PlaySound(sfx)
SetSoundVolume(sfx, 0.8)
// ...
UnloadSound(sfx)
FunctionDescription
InitAudioDevice/CloseAudioDeviceInit/shutdown audio
IsAudioDeviceReadyCheck audio ready
SetMasterVolume/GetMasterVolumeMaster volume (0.0..1.0)
LoadSound(fileName)Load sound from file
LoadSoundFromWave(wave)Create sound from wave
UnloadSound(sound)Free sound
PlaySound/StopSound/PauseSound/ResumeSoundPlayback control
IsSoundPlaying(sound)Check if playing
SetSoundVolume/Pitch/PanSound properties

Music (streaming)

var music = LoadMusicStream("background.ogg")
PlayMusicStream(music)
// In game loop:
UpdateMusicStream(music)
FunctionDescription
LoadMusicStream(fileName)Load music for streaming
UnloadMusicStream(music)Free music
PlayMusicStream/Stop/Pause/ResumePlayback control
UpdateMusicStream(music)Call every frame
IsMusicStreamPlaying(music)Check if playing
SeekMusicStream(music, position)Seek to position
SetMusicVolume/Pitch/PanMusic properties
GetMusicTimeLength/TimePlayedDuration and position

Wave Processing

FunctionDescription
LoadWave(fileName)Load wave data
WaveCopy/WaveCrop/WaveFormatProcess wave data
LoadWaveSamples/UnloadWaveSamplesAccess raw samples
ExportWave(wave, fileName)Save wave to file

Config Flags

Set before InitWindow with SetConfigFlags:

SetConfigFlags(FLAG_WINDOW_RESIZABLE)
InitWindow(800, 600, "Resizable Window")
FlagDescription
FLAG_VSYNC_HINTEnable V-Sync
FLAG_FULLSCREEN_MODEStart fullscreen
FLAG_WINDOW_RESIZABLEAllow resizing
FLAG_WINDOW_UNDECORATEDNo window frame
FLAG_WINDOW_TRANSPARENTTransparent framebuffer
FLAG_WINDOW_HIGHDPIHigh-DPI support
FLAG_MSAA_4X_HINT4x MSAA anti-aliasing
FLAG_WINDOW_ALWAYS_RUNKeep running when minimized

Platform Notes

  • Windows: Auto-switches to Clang for linking. The -DNOGDI -DNOUSER flags are automatically applied to prevent windows.h from conflicting with raylib’s Rectangle, CloseWindow, and ShowCursor definitions.
  • Linux: Links against libraylib.a with -lGL -lm -lpthread -ldl -lrt -lX11.
  • macOS: Links against libraylib.a with CoreVideo, IOKit, Cocoa, OpenGL frameworks.
  • TCC: Not supported for raylib (can’t link static libraries). Clang is used automatically.

Why Not Source Compilation?

Unlike Sokol (which uses a single @cfile bridge), raylib cannot be compiled in a single translation unit. Its internal headers (rlgl.h, glad.h) define global variables that cause redefinition errors when multiple .c files are included together. Additionally, TCC lacks the Windows SDK headers that raylib’s GLFW backend requires. The prebuilt library approach is the most reliable path.

Module Layout

modules/
  raylib/
    c/
      raylib.h         Raylib header (v5.5)
    lib/
      raylib.lib       Prebuilt static library (MSVC/Windows)
      libraylib.a      Prebuilt static library (GCC/Linux/macOS)
    gx/
      core.gx          Build directives, 29 structs, window, timing, camera, shaders
      input.gx         Keyboard/mouse enums and query functions
      shapes.gx        2D shapes, splines, 2D collision
      text.gx          Text drawing, fonts, codepoints, text utilities
      textures.gx      Image/texture loading, manipulation, color utilities
      colors.gx        Color constants (rl_red, rl_blue, etc.)
      models.gx        3D shapes, model/mesh/material, animations, 3D collision
      audio.gx         Sound, music streaming, wave processing, audio streams