Skip to main content
khairallah.dev

Graphics9 min read

Ray-casting, from a single pixel

Building cub3D — a Wolfenstein-style 3D engine in pure C — was the closest I've come to feeling like I understood graphics from the metal up.

The trick is the trick

Ray-casting feels like 3D, but it's really 2D wearing a costume. For each column of pixels on screen, you cast a single ray on a 2D map; the distance to the wall determines how tall to draw the slice. That's the whole engine. The rest is bookkeeping.

for (int x = 0; x < SCREEN_W; x++) {
  double cameraX = 2.0 * x / SCREEN_W - 1.0;
  Ray ray = cast(player, cameraX);
  draw_slice(x, ray);
}

The DDA algorithm

Digital Differential Analysis sounds intimidating; it's a five-line loop that walks a grid one cell at a time, choosing the nearer of two grid lines at each step. When you draw it on paper, it becomes obvious. When you draw it on paper first, the code writes itself.

A whiteboard is the cheapest debugger you'll ever own.