./jerome{m}jack in

~/Notes/Raylib 3D rendering.md · note · budding · 13 min · updated

Raylib for 3D

// status: budding

Raylib is Ramon Santamaria's "videogame programming without the fuss" library — a thin C layer over OpenGL (desktop 2.1/3.3/4.3, ES 2.0/3.0, or WebGL) that gets a triangle on screen in about ten lines. I used it in Raym to focus on the algorithm rather than the boilerplate, and these are the bits of its 3D side worth writing down.

The sections on conventions, lighting, shadows, instancing, batching and skyboxes were checked against the raylib 6.x source: a master commit from 14 October 2026, the day before the 6.2 release. Where 5.x differs, they say so.

Why pick raylib for 3D

  • Small C API — include raylib.h and link the compiled static/shared library. No framework-sized build-system archaeology.
  • Batteries included — windowing, input, audio, file I/O, image loading, and a math library (raymath.h). The similarly styled raygui is a separate companion library.
  • Readable internals — the code is genuinely small and well-commented. When you hit a weird behaviour, reading the source is faster than searching for docs.
  • Portability — same code compiles to desktop, web (emscripten), Android, and RPi.

Where it stops being the right tool: anything that needs a modern GPU pipeline (raylib's rlgl compute path targets OpenGL 4.3), large-scene culling, or a more involved lighting architecture. At that point, raw OpenGL or Vulkan gives you more control.

The hello-cube

c
#include "raylib.h"

int main(void) {
    InitWindow(1280, 720, "hello 3d");
    SetTargetFPS(60);

    Camera3D camera = {
        .position   = { 6.0f, 6.0f, 6.0f },
        .target     = { 0.0f, 0.0f, 0.0f },
        .up         = { 0.0f, 1.0f, 0.0f },
        .fovy       = 45.0f,
        .projection = CAMERA_PERSPECTIVE,
    };

    while (!WindowShouldClose()) {
        UpdateCamera(&camera, CAMERA_ORBITAL);

        BeginDrawing();
            ClearBackground(RAYWHITE);
            BeginMode3D(camera);
                DrawCube((Vector3){0,0,0}, 2,2,2, MAROON);
                DrawCubeWires((Vector3){0,0,0}, 2,2,2, BLACK);
                DrawGrid(10, 1.0f);
            EndMode3D();
            DrawFPS(10, 10);
        EndDrawing();
    }
    CloseWindow();
    return 0;
}

Everything inside BeginMode3D(camera) / EndMode3D() uses the 3D pipeline. Outside, it's 2D and UI.

Cameras

Camera3D is a plain struct. Five built-in modes via UpdateCamera(&camera, mode):

  • CAMERA_FREE — fly-through with mouse + WASD + E/Q.
  • CAMERA_ORBITAL — auto-orbits the target. Great for demos.
  • CAMERA_FIRST_PERSON — mouselook + WASD, stays on ground.
  • CAMERA_THIRD_PERSON — follows a target with mouse orbit.
  • CAMERA_CUSTOM — do nothing, you drive it yourself.

For anything real, bypass UpdateCamera and move position/target yourself — the built-in modes are prototype-grade. The camera exposes its matrices via GetCameraMatrix and GetCameraProjectionMatrix when you need them.

Coordinates & conventions

Raylib keeps OpenGL's defaults, and most "why is my mesh invisible" questions come down to one of these.

  • Right-handed, Y up. raylib.h describes Matrix as "column major, OpenGL style, right-handed", and MatrixLookAt builds a view in which the camera looks down −Z. Y-up is a convention rather than a rule, since the camera's up field decides, but the library assumes it wherever it has to choose: DrawGrid and DrawPlane lie in the XZ plane and GenMeshHeightmap displaces Y. With X to the right and Y up, +Z points at the viewer.
  • Counter-clockwise is front, and back faces are culled. rlglInit sets glFrontFace(GL_CCW) and glCullFace(GL_BACK) and enables culling, so a triangle that appears clockwise from the camera is not drawn at all. DrawTriangle3D asks for the same order.
  • No frustum culling. The back-face test is the only culling raylib does for you: DrawModel submits every mesh, on screen or not. GetModelBoundingBox and GetMeshBoundingBox give you the boxes; the visibility test is yours to write, and Spatial acceleration structures and GPU-Driven Visibility for Large Worlds are where that goes next. Clipping does exist: the near and far planes default to 0.05 and 4000 units.
  • Degrees outside, radians inside. Camera3D.fovy, the angle of DrawModelEx and rlRotatef take degrees. Everything in raymath.h takes radians: MatrixRotate, MatrixRotateXYZ, QuaternionFromAxisAngle, the fovY of MatrixPerspective. In orthographic mode fovy is not an angle at all but the height of the view in world units.
  • Matrices. Field names are column-major: m12, m13 and m14 hold the translation. MatrixMultiply(a, b) applies a first and b second, the reverse of how the maths is usually written; DrawModelEx builds its transform as scale, then rotation, then translation that way.

Culling and the clip planes are changed through rlgl.h:

c
#include "rlgl.h"

rlDisableBackfaceCulling();                 // foliage, cloth, the inside of a box
    DrawModel(leaves, pos, 1.0f, WHITE);
rlEnableBackfaceCulling();

rlSetCullFace(RL_CULL_FACE_FRONT);          // cull fronts instead
rlSetCullFace(RL_CULL_FACE_BACK);           // back to the default

rlSetClipPlanes(0.1, 10000.0);              // read by the next BeginMode3D

What to draw

Two families of API sit on top of the same mesh pipeline:

  • Immediate-mode primitives — DrawCube, DrawSphere, DrawCylinder, DrawPlane, DrawLine3D, DrawRay, DrawBoundingBox, DrawGrid. Good for debug viz, placeholder geometry, and gizmos. These helpers submit geometry through rlgl's internal path; reuse a Mesh or Model when persistent geometry is the better fit.
  • Meshes & models — persistent GPU buffers. Mesh, Material, and Model structs. This is what you want for anything drawn more than once.

DrawGrid and DrawRay are the two I keep reaching for while debugging. Any time a 3D coordinate seems off, dropping a DrawSphere at that point answers it faster than a printf.

Meshes

A Mesh is a flat struct of CPU-side geometry arrays plus GPU object IDs:

c
typedef struct Mesh {
    int vertexCount;
    int triangleCount;

    float *vertices;          // positions  (xyz)
    float *texcoords;         // (uv)
    float *normals;           // (xyz)
    float *colors;            // optional (rgba)
    unsigned short *indices;  // optional

    // ... boneIds, boneWeights, tangents, texcoords2, animVertices, animNormals ...

    unsigned int vaoId;
    unsigned int *vboId;
} Mesh;

UploadMesh(&mesh, dynamic) copies CPU-side arrays to GPU buffers. UpdateMeshBuffer(mesh, i, data, size, offset) patches one buffer for dynamic geometry. UnloadMesh(mesh) frees both sides.

Built-in generators for the usual primitives:

c
Mesh sphere   = GenMeshSphere(1.0f, 32, 32);
Mesh torus    = GenMeshTorus(0.3f, 1.0f, 32, 24);
Mesh knot     = GenMeshKnot(1.0f, 2.0f, 32, 24);
Mesh plane    = GenMeshPlane(10, 10, 10, 10);            // subdivided
Mesh hf       = GenMeshHeightmap(imgHeight, (Vector3){16,4,16});
Mesh cubicmap = GenMeshCubicmap(imgMap,    (Vector3){1,1,1});

GenMeshHeightmap and GenMeshCubicmap are the "terrain in one line" shortcuts — the first turns a grayscale image into a plane with displaced Y, the second turns a black-and-white image into blocky stacked cubes. For anything organic, generate your own vertex arrays and call UploadMesh.

Models & materials

A Model bundles one or more meshes with materials and an optional skeleton:

c
Model model = LoadModel("castle.glb");
model.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = LoadTexture("castle_diffuse.png");

DrawModel(model, (Vector3){0,0,0}, 1.0f, WHITE);
UnloadModel(model);

Depending on the build configuration, current raylib supports OBJ, IQM (skeletal animation), glTF/glb, VOX (MagicaVoxel), and M3D. glTF/glb is a practical interchange format for an asset pipeline.

A Material is a default-shader + up to 12 texture maps:

MapSlot
MATERIAL_MAP_DIFFUSE / ALBEDObase colour
MATERIAL_MAP_METALNESSmetallic
MATERIAL_MAP_NORMALnormal map
MATERIAL_MAP_ROUGHNESSroughness
MATERIAL_MAP_OCCLUSIONAO
MATERIAL_MAP_EMISSIONemissive
MATERIAL_MAP_HEIGHTheight/parallax
MATERIAL_MAP_CUBEMAPenvironment
MATERIAL_MAP_IRRADIANCEdiffuse IBL
MATERIAL_MAP_PREFILTERspecular IBL
MATERIAL_MAP_BRDFsplit-sum LUT

The stock shader is unlit and primarily handles the base texture and tint. For lighting or PBR, you ship a custom shader and wire the required maps and uniforms yourself; PBR in raylib walks through the metallic-roughness case. The raylib-extras organisation collects useful community examples and helpers.

Shaders

Shader is a vertex+fragment program pair loaded from files:

c
Shader sh = LoadShader("shaders/mine.vs", "shaders/mine.fs");
int locTime = GetShaderLocation(sh, "uTime");

model.materials[0].shader = sh;

// in the draw loop
float t = (float)GetTime();
SetShaderValue(sh, locTime, &t, SHADER_UNIFORM_FLOAT);

DrawModel(model, ...);

Locations raylib discovers automatically when a custom shader uses its conventional names:

  • mvp — full MVP matrix.
  • matModel, matView, matProjection — components.
  • colDiffuse — the tint passed to DrawModel.
  • texture0..texture2 — up to three samplers.

Other application-specific uniforms still need an explicit location. Camera-dependent examples commonly assign SHADER_LOC_VECTOR_VIEW themselves with GetShaderLocation(sh, "viewPos").

Pass NULL for either stage to use the built-in one:

c
Shader sh = LoadShader(NULL, "shaders/fragment.fs");  // default VS, custom FS

Cross-platform tip: the shader source still has to match the selected graphics backend. Raylib's examples usually choose separate GLSL 330 desktop and GLSL 100/300 ES files at compile time; LoadShaderFromMemory is useful when you prefer to assemble those variants in code.

Lighting — rlights.h

Raylib doesn't ship built-in lighting: the stock shader is unlit and nothing in raylib.h creates a light. What tutorials call raylib lighting is examples/shaders/rlights.h, a header from the examples folder that you copy into your project along with the lighting.vs / lighting.fs pair it was written for. It feeds up to four lights to a forward shader, and it is a single-header library, so exactly one source file defines RLIGHTS_IMPLEMENTATION before including it:

c
#define RLIGHTS_IMPLEMENTATION
#include "rlights.h"

Shader sh = LoadShader("shaders/lighting.vs", "shaders/lighting.fs");

sh.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(sh, "viewPos");
int ambientLoc = GetShaderLocation(sh, "ambient");
float ambient[4] = { 0.1f, 0.1f, 0.1f, 1.0f };
SetShaderValue(sh, ambientLoc, ambient, SHADER_UNIFORM_VEC4);

Light lights[MAX_LIGHTS] = {
    CreateLight(LIGHT_POINT,       (Vector3){-2,1, 2}, Vector3Zero(), YELLOW, sh),
    CreateLight(LIGHT_DIRECTIONAL, (Vector3){ 2,2,-2}, Vector3Zero(), WHITE,  sh),
};

Each frame the shader needs the camera position, and any light you changed has to be pushed again:

c
float t = (float)GetTime();
float cam[3] = { camera.position.x, camera.position.y, camera.position.z };
SetShaderValue(sh, sh.locs[SHADER_LOC_VECTOR_VIEW], cam, SHADER_UNIFORM_VEC3);

lights[0].position = (Vector3){ sinf(t)*4.0f, 2.0f, cosf(t)*4.0f };
UpdateLightValues(sh, lights[0]);           // nothing reaches the GPU until this call

BeginMode3D(camera);
    BeginShaderMode(sh);                    // immediate-mode shapes: per block
        DrawPlane(Vector3Zero(), (Vector2){ 10.0f, 10.0f }, WHITE);
    EndShaderMode();
    DrawModel(model, Vector3Zero(), 1.0f, WHITE);   // models: model.materials[0].shader = sh
EndMode3D();

The whole header is a struct and two functions:

  • Light — type, enabled, position, target, color and attenuation, plus the uniform locations it caches.
  • CreateLight(type, position, target, color, shader) — fills the struct, looks up lights[i].enabled, .type, .position, .target and .color in the shader, and uploads them once. i is a static counter inside the header, so lights take slots in creation order.
  • UpdateLightValues(shader, light) — uploads those five values again. Call it after any change, toggling enabled included.
  • Two types — LIGHT_DIRECTIONAL, whose rays run from position towards target, and LIGHT_POINT.
  • MAX_LIGHTS is 4, and lighting.fs carries its own #define MAX_LIGHTS 4. Change both or neither.

The shading in lighting.fs is plain: Lambert diffuse per light, a Phong specular term from reflect() with the exponent fixed at 16, an ambient uniform that the shader divides by ten, and a pow(1.0/2.2) gamma step at the end. Its vertex shader wants matModel and matNormal; raylib fills those, and mvp, for any shader that uses the conventional names. viewPos and ambient are yours to set.

What it does not give you:

  • Attenuation. The struct has the field, but the header never uploads it and the shader has no such uniform: a point light is as bright at fifty units as at one.
  • Spot lights, shadows, normal mapping, a shininess per material, or a fifth light without editing both files.

Past that point it is often simpler to drop the helper than to extend it. Raym doesn't include rlights.h at all: its terrain shader takes one lightPos / lightColor pair set with plain SetShaderValue calls and does the rest in GLSL, with Blinn-Phong from a half vector and the diffuse term quantised into four bands:

glsl
// Raym — resources/shaders/lighting_shader.fs (excerpt)
vec3 lightDir = normalize(lightPos - fragPosition);
float diff = max(dot(normal, lightDir), 0.0);

// Calculate specular reflection (Blinn-Phong)
vec3 halfwayDir = normalize(lightDir + viewDir);
float spec = pow(max(dot(normal, halfwayDir), 0.0), shininess);

// Apply cell shading to diffuse lighting (4 bands for better definition)
diff = cellShade(diff, 4);

vec3 ambient = ambientStrength * lightColor;
vec3 diffuse = diff * lightColor;
vec3 specular = specularStrength * spec * lightColor;

For many lights you graduate to your own pipeline (see Deferred vs forward rendering); raylib's shaders_deferred_rendering.c example is a G-buffer version that still creates its lights with rlights.h. The header is "demo quality" but perfect for small projects.

Shadows

rlights.h has no shadows, and neither does anything in raylib.h. The reference is examples/shaders/shaders_shadowmap_rendering.c: one directional light, a 1024×1024 depth map, and a 3×3 percentage-closer lookup with a slope-scaled bias. Three things in it are worth knowing before you start:

  1. It builds its own depth-only framebuffer with rlgl (rlLoadFramebuffer, rlLoadTextureDepth(w, h, false), rlFramebufferAttach), because LoadRenderTexture attaches its depth as a renderbuffer, which a shader cannot sample.
  2. The light is an ordinary orthographic Camera3D, and its view and projection are read back with rlGetMatrixModelview() and rlGetMatrixProjection() while the scene is drawn from it.
  3. The depth texture is bound by hand to a spare slot with rlActiveTextureSlot and rlEnableTexture before the second pass.

The theory, cascades and the biasing problem are in Shadow mapping.

Textures & render targets

c
Texture2D tex   = LoadTexture("grass.png");
Image img       = LoadImage("grass.png");          // CPU-side
RenderTexture2D rt = LoadRenderTexture(1920, 1080); // FBO

Render-to-texture is the gateway to post-processing:

c
BeginTextureMode(rt);
    ClearBackground(BLACK);
    BeginMode3D(camera);
        DrawModel(model, ...);
    EndMode3D();
EndTextureMode();

BeginDrawing();
    ClearBackground(BLACK);
    BeginShaderMode(postFX);
        DrawTextureRec(rt.texture,
                       (Rectangle){0, 0, rt.texture.width, -rt.texture.height},  // Y flip!
                       (Vector2){0, 0}, WHITE);
    EndShaderMode();
EndDrawing();

The negative height is the Y-flip for the flipped FBO coordinate system — easy to forget and produces an "everything is upside down" bug that baffles for longer than it should.

SetConfigFlags(FLAG_MSAA_4X_HINT) asks for a 4× multisampled window, but only if it runs before InitWindow, and only for the main framebuffer: a scene drawn into a RenderTexture2D gets no MSAA and needs a post-process filter instead (see real-time anti-aliasing).

Instancing

DrawMeshInstanced takes an array of transforms and a custom shader that reads them from the conventional instanceTransform mat4 attribute. Use raylib's semantic location instead of hard-coding a numeric attribute index:

c
#define N 10000
Matrix *transforms = MemAlloc(sizeof(Matrix) * N);
for (int i = 0; i < N; i++)
    transforms[i] = MatrixTranslate(randX(), 0, randZ());

Shader instanceSh = LoadShader("shaders/instance.vs", "shaders/default.fs");
instanceSh.locs[SHADER_LOC_MATRIX_MVP] = GetShaderLocation(instanceSh, "mvp");
instanceSh.locs[SHADER_LOC_VERTEX_INSTANCETRANSFORM] =
    GetShaderLocationAttrib(instanceSh, "instanceTransform");

Material mat = LoadMaterialDefault();
mat.shader = instanceSh;

DrawMeshInstanced(cubeMesh, mat, transforms, N);

The instance VS multiplies by instanceTransform before MVP:

glsl
in vec3 vertexPosition;
in mat4 instanceTransform;      // one per instance, not per vertex

uniform mat4 mvp;

void main() {
    gl_Position = mvp*instanceTransform*vec4(vertexPosition, 1.0);
}

What DrawMeshInstanced expects, and what it does with it:

  • The attribute. A mat4 attribute occupies four consecutive locations, and raylib enables all four with a divisor of 1. In 6.x, LoadShader resolves SHADER_LOC_VERTEX_INSTANCETRANSFORM (and mvp) by itself when the names are the conventional ones, so the two assignments above are belt and braces. In 5.x that enum did not exist and the attribute location went in shader.locs[SHADER_LOC_MATRIX_MODEL], which is the line older tutorials show.
  • The material. The shader comes from material.shader, not from BeginShaderMode. The material's diffuse colour arrives as colDiffuse and its texture maps are bound as they are for DrawMesh.
  • The matrices. mvp here is view × projection only, plus whatever rlPushMatrix transform is active. The model matrix is identity and matModel is not uploaded, so world-space position has to come from instanceTransform. matNormal is uploaded as identity for the same reason, and the stock lighting_instancing.vs uses it: rotated instances are lit with unrotated normals. Build the normal from the instance matrix instead:
glsl
fragPosition = vec3(instanceTransform*vec4(vertexPosition, 1.0));
fragNormal   = normalize(transpose(inverse(mat3(instanceTransform)))*vertexNormal);
  • The cost. Every call allocates an array, converts the matrices, creates a VBO, draws, and deletes the VBO again. That is fine for a few thousand moving instances; for a large static set it is pure overhead, and the fix is your own instance buffer through rlgl (rlLoadVertexBuffer, rlSetVertexAttributeDivisor, rlDrawVertexArrayInstanced).
  • The limits. The transform is the only per-instance data, nothing is culled per instance, and the function body exists only for the OpenGL 3.3 and ES backends.

Instancing is not batching, which is the other mechanism and is automatic. Everything drawn through rlBegin / rlEnd (DrawCube, DrawSphere, lines, text, 2D textures) is appended to one CPU-side vertex buffer, the render batch. A change of primitive mode or texture starts a new draw call inside it. The batch is uploaded and drawn when its buffer fills (8,192 quads by default on desktop, 2,048 on the ES backends), when its 256 draw-call slots run out, when the active shader changes, or when a function such as BeginMode3D, EndMode3D, BeginTextureMode or EndDrawing runs. Meshes never go through it: each DrawMesh, and so each mesh of each DrawModel, is its own draw call. Many small immediate shapes are already batched; many copies of one mesh want DrawMeshInstanced.

rlgl — the layer below

rlgl.h is Raylib's OpenGL abstraction layer: a thin wrapper that presents an immediate-mode interface (rlBegin, rlVertex3f, rlColor4ub, rlEnd) and batches draws internally. It is how DrawCube is implemented, and how you drop below the friendly API when you need to:

  • Build custom meshes vertex-by-vertex without touching OpenGL directly.
  • Push/pop matrix state (rlPushMatrix, rlRotatef, rlTranslatef) à la old GL.
  • Manage your own VBOs/VAOs/SSBOs (rlLoadVertexBuffer, rlLoadVertexArray).
  • Dispatch compute shaders on GL 4.3+ with rlLoadShaderProgramCompute (named rlLoadComputeShaderProgram before 6.0) and rlComputeShaderDispatch; Compute shaders in raylib has the walk-through.

When you need a modern feature Raylib doesn't expose at the top level, rlgl is almost always where it lives. If that fails, you can mix raw OpenGL into a raylib program — the GL context is just there.

Custom mesh via rlgl

The cleaner path is usually: build float arrays, call UploadMesh, done. When you need immediate-mode for viz:

c
rlBegin(RL_TRIANGLES);
    rlColor4ub(255, 0, 0, 255);
    rlVertex3f(0, 0, 0);
    rlVertex3f(1, 0, 0);
    rlVertex3f(0, 1, 0);
rlEnd();

Raylib's internal batcher starts a new draw call when the primitive type or texture changes, and flushes when the shader changes, its buffers fill, or EndMode3D/EndDrawing runs (the details are under Instancing above). Keep all your immediate-mode calls contiguous per material to avoid unnecessary draw calls.

Skyboxes

Standard cube-map skybox — the examples/models/models_skybox_rendering.c sample is the reference:

  1. Load an image in a supported cubemap layout with LoadTextureCubemap, or convert an equirectangular panorama to a cubemap with a shader pass.
  2. Create a unit cube mesh and assign a material with a custom shader that samples the cubemap.
  3. Draw from inside the cube with back-face culling and depth writes temporarily disabled. The sample shader removes view translation so the skybox stays centred on the camera.

In code, following the sample:

c
Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
Model skybox = LoadModelFromMesh(cube);
skybox.materials[0].shader = LoadShader("shaders/skybox.vs", "shaders/skybox.fs");

// "environmentMap" is not one of raylib's conventional names: point it at the cubemap's unit by hand
SetShaderValue(skybox.materials[0].shader,
               GetShaderLocation(skybox.materials[0].shader, "environmentMap"),
               (int[1]){ MATERIAL_MAP_CUBEMAP }, SHADER_UNIFORM_INT);

Image img = LoadImage("skybox.png");        // all six faces in one image
skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture =
    LoadTextureCubemap(img, CUBEMAP_LAYOUT_AUTO_DETECT);
UnloadImage(img);

// each frame, first thing inside BeginMode3D
rlDisableBackfaceCulling();             // we are inside the cube
rlDisableDepthMask();                   // the sky writes no depth
    DrawModel(skybox, (Vector3){ 0, 0, 0 }, 1.0f, WHITE);
rlEnableBackfaceCulling();
rlEnableDepthMask();

The parts that are easy to get wrong:

  • The sampler value is the map index. DrawMesh binds each material map to the texture unit of its own index, and the cubemap, irradiance and prefilter slots as cubemaps. The uniform therefore gets MATERIAL_MAP_CUBEMAP, not 0.
  • One image, six faces. LoadTextureCubemap takes a single image and a layout: a vertical or horizontal strip, a 3×4 or 4×3 cross, or CUBEMAP_LAYOUT_AUTO_DETECT.
  • Translation is stripped in the vertex shader, with mat4 rotView = mat4(mat3(matView));, so the cube turns with the camera but never moves away from it.
  • Draw it first. With depth writes off, the sky leaves nothing in the depth buffer and everything drawn afterwards covers it. Drawn last, the same small cube would paint over anything further away than its faces.

HDR equirectangular → cubemap conversion is also one example away, using a LoadShader pass and an FBO. The sample's useHDR switch loads the panorama as a plain texture and renders it into the six faces with GenTextureCubemap, a static helper inside the example rather than a raylib function; the skybox shader then tone-maps and gamma-encodes when its doGamma uniform is set.

Things that tripped me up

  • Y axis on render textures — DrawTextureRec with height = -texture.height is the fix. The Raylib coordinate system is Y-up but FBO textures are stored Y-down.
  • Repeated high-detail primitives add up — for many spheres or other repeated shapes, profile the immediate helper and consider drawing a reused mesh or instanced model.
  • Material slot 0 is the common case — a successfully loaded model normally has a default material there, and most tutorials assume it. Multi-material models have the per-mesh material index in model.meshMaterial[i].
  • Model-relative assets matter — LoadModel resolves referenced textures from the model's directory. Keep the expected asset layout intact or wire textures explicitly.
  • Shader uniforms must be set while bound — SetShaderValue binds the shader implicitly, but cache the locations with GetShaderLocation once, not per-frame.
  • Y-up vs Y-down in glTF — both coordinates conventions appear in the wild. A flipped normal map usually means your tangent space disagrees with the asset's.
  • Render-state ownership — BeginMode3D switches projection/view state and enables depth testing. If you mix rlgl or raw OpenGL calls with Raylib helpers, verify the state at the point of use instead of assuming every state is reset.
  • Batch capacity is configurable — rlgl batches immediate-mode geometry, and compile-time settings such as RL_DEFAULT_BATCH_BUFFER_ELEMENTS control its capacity. Defaults can change between Raylib versions, so check the version you build against before tuning them.
  • rlgl compute is backend-specific — raylib exposes it for the OpenGL 4.3 backend, not its WebGL path. Cross-platform projects need another implementation for that work.
  • State changes don't wait for the batch — rlDisableBackfaceCulling() and its neighbours change GL state at once, while immediate-mode geometry is only drawn at the next flush. Around DrawCube-style helpers, call rlDrawRenderBatchActive() before changing state; DrawModel draws straight away.
  • rlights.h counts lights globally — the slot index is one static counter, not one per shader. Lights for a second shader continue from where the first stopped, and a fifth CreateLight returns a zeroed Light that should not reach UpdateLightValues.

Ecosystem

  • raygui — immediate-mode UI in the same spirit.
  • raylib-extras — community extras: PBR, particle systems, glTF tooling, camera controllers.
  • r3d — a third-party project that describes itself as a "3D Extension Library for raylib", with PBR among its listed topics.
  • rres — Raylib's resource packaging format.
  • raymath.h — the built-in math lib. Quaternions, matrices, SLERP, everything you'd want.

References

  • raylib.com — docs and API cheatsheet.
  • raylib examples — the models/ and shaders/ folders are the most useful.
  • Raylib cheatsheet — one-page API reference on the site.
  • Ramon Santamaria's talks on the philosophy and internals of Raylib.

Back to Notes · see also Ray Picking Through the Rendering Pipeline · real-time anti-aliasing · Debugging Graphics Without Guessing · Raym