Mini Project 3: ECS and a Playable Demo
Parts 1 and 2 gave the engine a window, a renderer, a camera, meshes and lighting. What it still lacks is a game: objects with behavior, rules, input that means something, and a loop that keeps simulation and rendering apart. This last part adds the engine core from this course (an ECS, a scene hierarchy, a fixed-step loop, input actions and an event queue) and builds a small game on top: Coin Dash. The hero collects three coins while a guard patrols between them. Touching the guard costs a life, followed by a second of invulnerability.
The core has no SDL and no OpenGL in it, so the whole game runs headless below: the "player" is a script of held keys, the clock is a script of frame times, and the "renderer" is a printf of the game state. That is not just a trick for this playground. A headless build of the same core is what runs your automated tests, your replay system and your dedicated server.
The architecture
platform (SDL3) engine core (this lesson, runnable) renderer (part 2)
─────────────── ────────────────────────────────────────────── ────────────────────
SDL_PollEvent ──► keys held ─► mapInput ─► Actions
SDL_GetTicksNS ──► frame time ─► accumulator ─► fixed steps:
playerControl ─► patrol ─► movement ─►
transform (hierarchy) ─► collision ─► events ─►
rules (score, lives, win) ─► deferred destroy
WorldPos + mesh/color components ──────────────► draw each entity| Piece | Lesson it comes from | In this program |
|---|---|---|
| Sparse-set component storage | A Sparse-Set ECS | Storage<T> with sparse, dense, data and swap-and-pop removal |
| Systems as plain functions | Entities, Components and Systems | playerControlSystem, patrolSystem, … called in a fixed order |
| Parent/child transforms | Scene Graph and Dirty Transforms | the camera rig is a child of the hero |
| Fixed timestep with a scripted clock | The Game Loop | 30 Hz steps driven by uneven frame times |
| Input actions | Input Mapping and Actions | keys become moveX/moveZ, diagonals normalized |
| Queued events | Event Bus and Messaging | collisions produce events, rules consume them |
| Deferred destruction | RAII, Ownership and Lifetimes | coins are removed at the end of the step, never mid-iteration |
The headless game
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
// ---------------- ECS: sparse-set storage per component type ----------------
using Entity = std::uint32_t;
template <class T>
struct Storage {
std::vector<int> sparse; // entity -> index in dense, -1 if absent
std::vector<Entity> dense;
std::vector<T> data;
void add(Entity e, T value) {
if (e >= sparse.size()) sparse.resize(e + 1, -1);
sparse[e] = int(dense.size());
dense.push_back(e);
data.push_back(std::move(value));
}
bool has(Entity e) const { return e < sparse.size() && sparse[e] >= 0; }
T& get(Entity e) { return data[sparse[e]]; }
void remove(Entity e) {
if (!has(e)) return;
int i = sparse[e], last = int(dense.size()) - 1;
dense[i] = dense[last];
data[i] = std::move(data[last]);
sparse[dense[i]] = i;
dense.pop_back();
data.pop_back();
sparse[e] = -1;
}
};
// ---------------- components ----------------
struct Transform { float x = 0, z = 0; }; // local position (relative to parent)
struct WorldPos { float x = 0, z = 0; }; // computed by the transform system
struct Parent { Entity parent; };
struct Velocity { float vx = 0, vz = 0; };
struct Collider { float radius; };
struct Player { float speed; int lives; int score; int invulnerableSteps = 0; };
struct Coin { int value; };
struct Patrol { float ax, az, bx, bz, speed; bool toB = true; };
struct Name { std::string text; };
struct World {
Entity next = 0;
std::vector<Entity> pendingDestroy;
Storage<Transform> transform; Storage<WorldPos> world; Storage<Parent> parent;
Storage<Velocity> velocity; Storage<Collider> collider; Storage<Player> player;
Storage<Coin> coin; Storage<Patrol> patrol; Storage<Name> name;
Entity create(const char* n, float x, float z) {
Entity e = next++;
name.add(e, {n});
transform.add(e, {x, z});
world.add(e, {x, z});
return e;
}
void destroyLater(Entity e) { pendingDestroy.push_back(e); }
void flushDestroyed() { // safe point: end of the step
for (Entity e : pendingDestroy) {
transform.remove(e); world.remove(e); parent.remove(e); velocity.remove(e);
collider.remove(e); player.remove(e); coin.remove(e); patrol.remove(e); name.remove(e);
}
pendingDestroy.clear();
}
};
// ---------------- input mapping (actions, not keys) ----------------
struct Actions { float moveX = 0, moveZ = 0; };
enum Key { KeyW = 1, KeyA = 2, KeyS = 4, KeyD = 8 };
Actions mapInput(int keysDown) {
Actions a;
a.moveX = ((keysDown & KeyD) ? 1.f : 0.f) - ((keysDown & KeyA) ? 1.f : 0.f);
a.moveZ = ((keysDown & KeyW) ? 1.f : 0.f) - ((keysDown & KeyS) ? 1.f : 0.f);
return a;
}
// ---------------- events ----------------
enum class EventType { CoinCollected, PlayerHit };
struct Event { EventType type; Entity a, b; };
// ---------------- systems ----------------
void playerControlSystem(World& w, const Actions& in) {
for (Entity e : w.player.dense) {
float len = std::sqrt(in.moveX * in.moveX + in.moveZ * in.moveZ);
float s = len > 0 ? w.player.get(e).speed / len : 0; // normalize diagonals
w.velocity.get(e) = {in.moveX * s, in.moveZ * s};
}
}
void patrolSystem(World& w) {
for (Entity e : w.patrol.dense) {
Patrol& p = w.patrol.get(e);
Transform& t = w.transform.get(e);
float tx = p.toB ? p.bx : p.ax, tz = p.toB ? p.bz : p.az;
float dx = tx - t.x, dz = tz - t.z, d = std::sqrt(dx * dx + dz * dz);
if (d < 0.05f) { p.toB = !p.toB; w.velocity.get(e) = {0, 0}; continue; }
w.velocity.get(e) = {dx / d * p.speed, dz / d * p.speed};
}
}
void movementSystem(World& w, float dt) {
for (Entity e : w.velocity.dense) {
Transform& t = w.transform.get(e);
Velocity& v = w.velocity.get(e);
t.x += v.vx * dt;
t.z += v.vz * dt;
}
}
void transformSystem(World& w) { // parents were created before children
for (Entity e : w.transform.dense) {
Transform& t = w.transform.get(e);
WorldPos wp{t.x, t.z};
if (w.parent.has(e)) {
WorldPos& pw = w.world.get(w.parent.get(e).parent);
wp.x += pw.x;
wp.z += pw.z;
}
w.world.get(e) = wp;
}
}
void collisionSystem(World& w, std::vector<Event>& events) {
for (Entity p : w.player.dense) {
WorldPos& pp = w.world.get(p);
for (Entity o : w.collider.dense) {
if (o == p) continue;
WorldPos& op = w.world.get(o);
float dx = op.x - pp.x, dz = op.z - pp.z, r = w.collider.get(p).radius + w.collider.get(o).radius;
if (dx * dx + dz * dz > r * r) continue;
if (w.coin.has(o)) events.push_back({EventType::CoinCollected, p, o});
else if (w.patrol.has(o)) events.push_back({EventType::PlayerHit, p, o});
}
}
}
bool rulesSystem(World& w, std::vector<Event>& events, int step) { // returns true when the game is over
for (const Event& ev : events) {
Player& pl = w.player.get(ev.a);
if (ev.type == EventType::CoinCollected) {
pl.score += w.coin.get(ev.b).value;
std::printf(" [step %3d] picked up %s, score %d\n", step, w.name.get(ev.b).text.c_str(), pl.score);
w.destroyLater(ev.b);
} else {
if (pl.invulnerableSteps > 0) continue; // still blinking from the last hit
pl.lives--;
pl.invulnerableSteps = 30; // 1 s of mercy at 30 Hz
std::printf(" [step %3d] hit by %s, lives %d\n", step, w.name.get(ev.b).text.c_str(), pl.lives);
}
}
for (Entity e : w.player.dense)
if (w.player.get(e).invulnerableSteps > 0) w.player.get(e).invulnerableSteps--;
events.clear();
w.flushDestroyed();
if (w.coin.dense.empty()) { std::printf(" [step %3d] all coins collected: YOU WIN\n", step); return true; }
if (w.player.get(w.player.dense[0]).lives <= 0) { std::printf(" [step %3d] GAME OVER\n", step); return true; }
return false;
}
int main() {
World w;
Entity hero = w.create("hero", 0, 0);
w.velocity.add(hero, {});
w.collider.add(hero, {0.3f});
w.player.add(hero, {3.0f, 2, 0});
Entity cam = w.create("camera", 0, -4); // camera rig follows the hero
w.parent.add(cam, {hero});
Entity guard = w.create("guard", 3, 1);
w.velocity.add(guard, {});
w.collider.add(guard, {0.4f});
w.patrol.add(guard, {3, 1, -2, 1, 1.5f});
const float coins[][2] = {{2, 0}, {2, 2}, {-1, 2}};
const char* coinNames[] = {"coin A", "coin B", "coin C"};
for (int i = 0; i < 3; i++) {
Entity c = w.create(coinNames[i], coins[i][0], coins[i][1]);
w.collider.add(c, {0.3f});
w.coin.add(c, {10});
}
// Scripted input per rendered frame: which keys are held
auto keysAt = [](int frame) {
if (frame < 40) return int(KeyD);
if (frame < 80) return int(KeyW);
if (frame < 140) return int(KeyA);
return 0;
};
const std::int64_t stepUs = 33333; // 30 Hz simulation
const std::int64_t frameUs[] = {16667, 16667, 16666, 25000, 8333}; // repeating pattern
std::int64_t accumulator = 0;
std::vector<Event> events;
int step = 0;
bool over = false;
for (int frame = 0; frame < 300 && !over; frame++) {
Actions in = mapInput(keysAt(frame)); // once per rendered frame
accumulator += frameUs[frame % 5];
while (accumulator >= stepUs && !over) {
accumulator -= stepUs;
playerControlSystem(w, in);
patrolSystem(w);
movementSystem(w, stepUs / 1e6f);
transformSystem(w);
collisionSystem(w, events);
over = rulesSystem(w, events, step);
if (step % 15 == 0) {
WorldPos h = w.world.get(hero), c = w.world.get(cam), g = w.world.get(guard);
std::printf("step %3d hero (%5.2f, %5.2f) camera (%5.2f, %5.2f) guard (%5.2f, %5.2f)\n",
step, h.x, h.z, c.x, c.z, g.x, g.z);
}
step++;
}
}
Player& p = w.player.get(hero);
std::printf("final: score %d, lives %d, %d steps simulated, %zu entities with transforms\n", p.score, p.lives,
step, w.transform.dense.size());
}step 0 hero ( 0.10, 0.00) camera ( 0.10, -4.00) guard ( 2.95, 1.00)
[step 14] picked up coin A, score 10
step 15 hero ( 1.60, 0.00) camera ( 1.60, -4.00) guard ( 2.20, 1.00)
[step 23] hit by guard, lives 1
step 30 hero ( 2.00, 1.10) camera ( 2.00, -2.90) guard ( 1.45, 1.00)
[step 34] picked up coin B, score 20
step 45 hero ( 1.40, 2.00) camera ( 1.40, -2.00) guard ( 0.70, 1.00)
step 60 hero (-0.10, 2.00) camera (-0.10, -2.00) guard (-0.05, 1.00)
[step 64] picked up coin C, score 30
[step 64] all coins collected: YOU WIN
final: score 30, lives 1, 65 steps simulated, 3 entities with transforms
Things to look for in the output:
- Frames are not steps. The uneven frame-time pattern (16.7, 16.7, 16.7, 25, 8.3 ms) runs zero or one step per frame, yet the hero advances exactly 0.1 units per step at 3 units per second. Frame durations never enter the movement math; they only decide when the next step runs.
- The hierarchy. The camera's world position is always the hero's plus
(0, -4), computed bytransformSystem, which relies on parents being stored before their children (the Scene Graph lesson shows how to guarantee that order and skip clean subtrees). - Events decouple systems.
collisionSystemdoesn't know what coins or guards mean; it only reports overlaps.rulesSystemdecides that a coin adds score and a guard costs a life. Adding a "speed boost" pickup touches the rules, not the collision code. - Safe destruction. Coins are destroyed in
flushDestroyed()after all systems ran, so no system ever iterates over a storage that changes under it.
Step 8: Connecting the core to SDL3 and the renderer
The real build swaps the scripts for the platform and adds a render system. Gameplay code doesn't change at all. Input comes from SDL scancodes:
int keysHeld(const bool* keys) { // keys = SDL_GetKeyboardState(nullptr)
int k = 0;
if (keys[SDL_SCANCODE_W]) k |= KeyW;
if (keys[SDL_SCANCODE_A]) k |= KeyA;
if (keys[SDL_SCANCODE_S]) k |= KeyS;
if (keys[SDL_SCANCODE_D]) k |= KeyD;
return k;
}The main loop reads the real clock, clamps hitches, runs the same fixed steps, and draws once per frame:
const Uint64 stepNs = 33'333'333; // 30 Hz, as in the headless build
Uint64 previous = SDL_GetTicksNS(), accumulator = 0;
bool running = true, over = false;
while (running) {
SDL_Event e;
while (SDL_PollEvent(&e))
if (e.type == SDL_EVENT_QUIT) running = false;
Actions in = mapInput(keysHeld(SDL_GetKeyboardState(nullptr)));
Uint64 now = SDL_GetTicksNS();
accumulator += std::min<Uint64>(now - previous, 100'000'000); // clamp hitches to 0.1 s
previous = now;
while (accumulator >= stepNs && !over) {
accumulator -= stepNs;
playerControlSystem(world, in);
patrolSystem(world);
movementSystem(world, stepNs / 1e9f);
transformSystem(world);
collisionSystem(world, events);
over = rulesSystem(world, events, step++);
}
renderSystem(world, renderer, cam, hero); // part 2's renderer
SDL_GL_SwapWindow(window);
}The render system is one more ECS system. It reads WorldPos plus a MeshRenderer component (a mesh and a color, stored in a new Storage<MeshRenderer> meshRenderer in World and added to the hero, guard and coins at creation), builds each model matrix, and draws with the lit program from part 2. The camera entity's world position drives the view matrix:
struct MeshRenderer { const Mesh* mesh; glm::vec3 color; float scale; };
void renderSystem(World& w, Renderer& r, Entity cameraEntity, Entity target) {
WorldPos c = w.world.get(cameraEntity), t = w.world.get(target);
glm::mat4 view = glm::lookAt(glm::vec3(c.x, 5.0f, c.z), glm::vec3(t.x, 0.0f, t.z), glm::vec3(0, 1, 0));
r.beginFrame(view); // sets uViewProj, light, camera position
for (Entity e : w.meshRenderer.dense) {
const MeshRenderer& m = w.meshRenderer.get(e);
WorldPos p = w.world.get(e);
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(p.x, 0.5f * m.scale, p.z))
* glm::scale(glm::mat4(1.0f), glm::vec3(m.scale));
r.drawLit(*m.mesh, model, m.color);
}
}The world stores positions as (x, z) on the ground plane, and the renderer lifts them into 3D (y from the object's size). Render interpolation (drawing between the previous and current step with alpha) is the next refinement: keep the previous WorldPos per entity and blend, as shown in The Game Loop.
Checkpoint 4, the finish line: a lit ground plane, a hero cube you steer with WASD, three spinning coin meshes, a guard cube walking back and forth, a camera that follows from behind, and a win or game-over message in the log. You have built a tiny engine that runs a playable demo.
Where to take it next
Pick extensions that teach you something, one at a time, and profile before and after each (see Profiling):
| Extension | Roadmap step | Lessons |
|---|---|---|
| Textures and materials | 6 | Resource Cache, Graphics APIs |
| Load the level from a file | 8 | Scene Files and Prefabs, Binary Serialization |
| Replace the circle checks with Jolt bodies | 10 | Physics with Jolt |
| Coin and hit sounds | 11 | Audio with miniaudio |
| Hot-reloaded shaders and levels | 12 | Hot Reload |
| An entity inspector and frame-time graph | 13 | Tools with Dear ImGui, Profiling |
| Gameplay in Lua | – | Scripting with Lua and sol2 |
| Swap OpenGL for sokol_gfx or Vulkan | – | Graphics APIs, Vulkan |
And keep the headless build working as you go. A test that runs the scripted game and checks the final score catches gameplay regressions on every commit, with no window, no GPU and no human.
Test yourself
Why can the whole Coin Dash game run in the playground without a window?
- Compiler Explorer emulates a GPU
- The engine core has no platform or rendering dependencies; input and time come from scripts and output is printed
- The game is drawn as ASCII by SDL
- Because the ECS doesn't need memory
Why does collisionSystem push events instead of changing the score itself?
- Events are faster
- It keeps collision detection independent of game rules; rulesSystem decides what an overlap means
- Systems may not write components
- To support multithreading only
Coins are removed in flushDestroyed() at the end of the step. What would go wrong if rulesSystem removed them immediately with swap-and-pop?
- Nothing
- A system iterating over the same storage could skip or revisit entities because elements move during iteration
- The coin would be collected twice by design
- Memory would leak