TExcelTAD
Home › Game Engine Architecture in C++ › Mini Project 1: Window and Triangle

Mini Project 1: Window and Triangle

Time to build a tiny engine. Over three lessons you will follow the classic path: window → triangle → camera → mesh → lighting → ECS → playable demo. Each stage runs, so you always have something on screen, and each stage reuses the systems from this course instead of inventing new ones.

Stage Lesson You add Course lessons it uses
1. Window and input this one CMake + vcpkg project, SDL3 window, OpenGL 3.3 context, event loop Platform Layer, Game Loop
2. Triangle this one shaders, vertex buffer, first draw call Graphics APIs, RAII
3. Camera, mesh, lighting Mini Project 2 glm matrices, indexed meshes, OBJ loading, depth, Blinn-Phong Math for Games, Shaders
4. ECS and demo Mini Project 3 components, systems, input actions, a small game Sparse-Set ECS, Input Mapping

The stack: SDL3 for the window and input, OpenGL 3.3 core loaded with glad, and glm for math. OpenGL is not the newest API, but it is the shortest path from nothing to a lit 3D scene, and every concept (buffers, shaders, pipeline state, draw calls) carries over to Vulkan, D3D12, Metal or sokol_gfx. The Graphics APIs lesson compares the options.

Note: This code needs a desktop with a GPU, so it can't run in the playground. The runnable parts of the project (a software rasterizer here, the OBJ loader and lighting math in part 2, the whole engine core in part 3) run in the browser and print their results.

Step 1: The project

text
tiny-engine/
  CMakeLists.txt
  CMakePresets.json
  vcpkg.json
  src/
    main.cpp
    gl_util.hpp / gl_util.cpp     (shader helpers, added in step 2)

vcpkg.json lists the dependencies; vcpkg's manifest mode builds them automatically during CMake configure. The glad port generates an OpenGL loader for the API version you request through a feature:

json
{
  "name": "tiny-engine",
  "version": "0.1.0",
  "dependencies": [
    "sdl3",
    { "name": "glad", "features": ["gl-api-33"] },
    "glm"
  ]
}
cmake
cmake_minimum_required(VERSION 3.25)
project(TinyEngine LANGUAGES C CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(SDL3 CONFIG REQUIRED)
find_package(glad CONFIG REQUIRED)
find_package(glm CONFIG REQUIRED)

add_executable(tiny src/main.cpp src/gl_util.cpp)
target_link_libraries(tiny PRIVATE SDL3::SDL3 glad::glad glm::glm)

if(MSVC)
  target_compile_options(tiny PRIVATE /W4)
else()
  target_compile_options(tiny PRIVATE -Wall -Wextra)
endif()

A preset points CMake at vcpkg's toolchain file, so nobody has to remember the command line:

json
{
  "version": 6,
  "configurePresets": [
    {
      "name": "dev",
      "binaryDir": "${sourceDir}/build/dev",
      "cacheVariables": {
        "CMAKE_BUILD_TYPE": "Debug",
        "CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
      }
    }
  ],
  "buildPresets": [{ "name": "dev", "configurePreset": "dev" }]
}
bash
cmake --preset dev        # first run builds SDL3, glad and glm through vcpkg
cmake --build --preset dev
./build/dev/tiny

On Windows with the Visual Studio generator, CMAKE_BUILD_TYPE is ignored and the executable lands in build/dev/Debug/. The Toolkit: CMake, vcpkg and Conan lesson covers presets, triplets and Conan as an alternative.

Step 2: A window with an OpenGL context

The context attributes must be set before the window is created. macOS only provides core profiles with the forward-compatible flag, and caps OpenGL at 4.1, so 3.3 core works everywhere.

cpp
// src/main.cpp (stage 1)
#include <glad/glad.h>
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>

int main(int argc, char* argv[]) {
    if (!SDL_Init(SDL_INIT_VIDEO)) {
        SDL_Log("SDL_Init failed: %s", SDL_GetError());
        return 1;
    }
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#ifdef __APPLE__
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
#endif
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    SDL_Window* window = SDL_CreateWindow("Tiny Engine", 1280, 720,
        SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY);
    if (!window) { SDL_Log("SDL_CreateWindow failed: %s", SDL_GetError()); return 1; }

    SDL_GLContext context = SDL_GL_CreateContext(window);
    if (!context) { SDL_Log("SDL_GL_CreateContext failed: %s", SDL_GetError()); return 1; }
    SDL_GL_MakeCurrent(window, context);
    if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) {
        SDL_Log("Failed to load OpenGL functions");
        return 1;
    }
    SDL_GL_SetSwapInterval(1);                       // vsync; may fail on some drivers, that's fine
    SDL_Log("OpenGL %s, %s", (const char*)glGetString(GL_VERSION), (const char*)glGetString(GL_RENDERER));

    bool running = true;
    while (running) {
        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_EVENT_QUIT) running = false;
            if (e.type == SDL_EVENT_KEY_DOWN && e.key.key == SDLK_ESCAPE) running = false;
        }
        int w = 0, h = 0;
        SDL_GetWindowSizeInPixels(window, &w, &h);    // pixels, correct on high-DPI screens
        glViewport(0, 0, w, h);
        glClearColor(0.10f, 0.12f, 0.16f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        SDL_GL_SwapWindow(window);                    // blocks for vsync: paces the loop
    }

    SDL_GL_DestroyContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

Run it: a dark blue-grey window that closes with Escape, and a log line naming your GPU. Checkpoint 1. If the window opens but gladLoadGLLoader fails, the context wasn't made current; if SDL_GL_CreateContext fails on an old GPU or VM, try 3.2 or check the driver.

Step 3: Shaders and the first triangle

Two small helpers compile and link GLSL and print the driver's error log, which is the only feedback you get when a shader is wrong. The shader language itself is taught in Shaders & Graphics Programming.

cpp
// src/gl_util.cpp
#include <glad/glad.h>
#include <SDL3/SDL.h>

static GLuint compile(GLenum type, const char* source) {
    GLuint shader = glCreateShader(type);
    glShaderSource(shader, 1, &source, nullptr);
    glCompileShader(shader);
    GLint ok = GL_FALSE;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
    if (!ok) {
        char log[1024];
        glGetShaderInfoLog(shader, sizeof log, nullptr, log);
        SDL_Log("shader compile error:\n%s", log);
    }
    return shader;
}

GLuint makeProgram(const char* vertexSrc, const char* fragmentSrc) {
    GLuint vs = compile(GL_VERTEX_SHADER, vertexSrc);
    GLuint fs = compile(GL_FRAGMENT_SHADER, fragmentSrc);
    GLuint program = glCreateProgram();
    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    GLint ok = GL_FALSE;
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    if (!ok) {
        char log[1024];
        glGetProgramInfoLog(program, sizeof log, nullptr, log);
        SDL_Log("program link error:\n%s", log);
    }
    glDeleteShader(vs);                 // the linked program keeps what it needs
    glDeleteShader(fs);
    return program;
}

The triangle: three vertices with a 2D position and a color, uploaded once into a vertex buffer (VBO). A vertex array object (VAO) records how the buffer's bytes map to the shader's inputs.

cpp
// in main.cpp, after gladLoadGLLoader
GLuint makeProgram(const char* vertexSrc, const char* fragmentSrc);   // from gl_util.cpp

const char* kVertex = R"(#version 330 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec3 aColor;
out vec3 vColor;
void main() {
    vColor = aColor;
    gl_Position = vec4(aPos, 0.0, 1.0);
})";

const char* kFragment = R"(#version 330 core
in vec3 vColor;
out vec4 fragColor;
void main() {
    fragColor = vec4(vColor, 1.0);
})";

GLuint program = makeProgram(kVertex, kFragment);

const float vertices[] = {
    //  x      y      r     g     b
     0.0f,  0.6f,  1.0f, 0.3f, 0.3f,
    -0.6f, -0.5f,  0.3f, 1.0f, 0.3f,
     0.6f, -0.5f,  0.3f, 0.3f, 1.0f,
};
GLuint vao = 0, vbo = 0;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(2 * sizeof(float)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);

// in the loop, after glClear:
glUseProgram(program);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);

// after the loop, before destroying the context:
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glDeleteProgram(program);

Checkpoint 2: a triangle with red, green and blue corners, the colors blended smoothly across its surface. Resize the window: the triangle stretches, because positions are in normalized device coordinates (-1..1 on both axes) and there is no camera yet. Part 2 fixes that.

Tip: Wrap vao, vbo and program in move-only RAII types (as in RAII, Ownership and Lifetimes) as soon as you have more than one. They must be destroyed before SDL_GL_DestroyContext, so keep them in a scope or a renderer object that ends first.

What the GPU just did: a software model

glDrawArrays hides the rasterizer. This runnable model does the same job on the CPU for a tiny 32×16 "framebuffer": map NDC to pixels, test each pixel center against the three edge functions, and blend the vertex colors with the resulting barycentric weights, which is exactly how vColor gets interpolated.

cpp · try it yourself
#include <cstdio>

struct V { float x, y, r, g, b; };

// Twice the signed area of triangle (a, b, p): > 0 if p is to the left of a->b
float edge(float ax, float ay, float bx, float by, float px, float py) {
    return (bx - ax) * (py - ay) - (by - ay) * (px - ax);
}

int main() {
    const int W = 32, H = 16;
    V tri[3] = {{0.0f, 0.6f, 1, 0.3f, 0.3f}, {-0.6f, -0.5f, 0.3f, 1, 0.3f}, {0.6f, -0.5f, 0.3f, 0.3f, 1}};
    float sx[3], sy[3];
    for (int i = 0; i < 3; i++) {                    // viewport transform: NDC -> pixels
        sx[i] = (tri[i].x * 0.5f + 0.5f) * W;
        sy[i] = (1.0f - (tri[i].y * 0.5f + 0.5f)) * H;  // y flipped: row 0 at the top
    }
    float area = edge(sx[0], sy[0], sx[1], sy[1], sx[2], sy[2]);
    int covered = 0;
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) {
            float px = x + 0.5f, py = y + 0.5f;      // sample at the pixel center
            float w0 = edge(sx[1], sy[1], sx[2], sy[2], px, py) / area;
            float w1 = edge(sx[2], sy[2], sx[0], sy[0], px, py) / area;
            float w2 = edge(sx[0], sy[0], sx[1], sy[1], px, py) / area;
            if (w0 < 0 || w1 < 0 || w2 < 0) { std::putchar('.'); continue; }
            covered++;
            float r = w0 * tri[0].r + w1 * tri[1].r + w2 * tri[2].r;   // interpolated color
            float g = w0 * tri[0].g + w1 * tri[1].g + w2 * tri[2].g;
            float b = w0 * tri[0].b + w1 * tri[1].b + w2 * tri[2].b;
            std::putchar(r >= g && r >= b ? 'R' : g >= b ? 'G' : 'B');  // strongest channel
        }
        std::putchar('\n');
    }
    std::printf("%d of %d pixels covered, signed area %.1f\n", covered, W * H, area);
}
................................
................................
................................
................................
...............RR...............
.............RRRRRR.............
............RRRRRRRR............
...........RRRRRRRRRR...........
..........GGGGRRRRBBBB..........
.........GGGGGGGBBBBBBB.........
........GGGGGGGGBBBBBBBB........
.......GGGGGGGGGBBBBBBBBB.......
................................
................................
................................
................................
86 of 512 pixels covered, signed area -169.0

The R, G and B regions show which vertex dominates each pixel's interpolated color. Dividing by the signed area makes the weights independent of the vertex order, but the sign of the area itself tells you the winding: here it is negative, because flipping y turns the counter-clockwise NDC triangle into a clockwise one in pixel rows. GPUs use exactly this sign to decide which triangles face away from the camera and can be culled (glEnable(GL_CULL_FACE), counter-clockwise front faces by default).

Where this lives in the engine

Before moving on, split main.cpp along the layers from Engine Layers and Subsystems: a Platform class (SDL init, window, event pump, timer), a Renderer class (context, programs, buffers, draw) and a small main that owns both and runs the loop. Part 2 adds the camera and meshes to the renderer; part 3 adds the ECS and gameplay above it.

Test yourself

Why must SDL_GL_SetAttribute calls come before SDL_CreateWindow?

  1. They are ignored after SDL_Init
  2. The window's pixel format and the context are chosen when the window and context are created
  3. glad requires it
  4. They only work in release builds

What does the vertex array object (VAO) store?

  1. The vertex data itself
  2. How buffer bytes map to shader inputs: which buffer, offsets, strides and formats
  3. The compiled shader
  4. The window size

In the software rasterizer, what are the three weights w0, w1, w2 used for?

  1. Depth sorting
  2. Interpolating vertex attributes such as color across the triangle
  3. Choosing the shader
  4. Clipping to the screen