Notes
42 (X): Cub3D, raycasting and walls that look 3D
A 3D engine without an engine: Wolfenstein-style raycasting, textures, and the project
2 min read
There are projects that change the way you look at video games. Cub3D is one of them: a 3D engine without an engine, built from scratch in C, where the walls you see aren't modeled anywhere — they're the result of firing rays of light through a maze grid and seeing where they hit. Before this came minishell, which I explained in 42 (IX): minishell, a terminal from scratch.
How the trick works
Raycasting (firing rays for each line of the screen) is a simple idea with spectacular consequences. From the player, a ray is launched for each column of pixels (the colored dots that form the image); the ray advances through the 2D map until it hits a wall; the distance traveled determines the height that column is painted. The farther the wall, the shorter. The viewer's brain does the rest and believes it's in a three-dimensional world. It's the trick from Wolfenstein 3D (1992), and reconstructing it means understanding trigonometry, distances, and perspectives in a way no book teaches you.
What I had to build
Before drawing anything, the map must be loaded: parse .cub files (read them and convert them into data) with textures, colors, and the maze layout, and validate it all. I created thirteen error maps, one for every way I could think of getting stuck: open walls, strange characters, missing textures, players outside the map. If the map is suspicious, the program refuses to start with a clear message.
Then: minilibX (the school's graphics library) for the window and pixels, directional textures (north, south, east, and west each have their own image), movement with collisions so you don't pass through walls, and smooth camera rotation.
The part that doesn't make it into tutorials
minilibX is an old library with different versions on macOS and Linux, and getting the project to compile and behave the same on both platforms is a project in itself. There were days when the graphic debugging (the hunt for bugs) was more about compilation than geometry.
And the performance: when every pixel is calculated by hand, you learn to look at the inner loop with respect. One extra calculation on the ray distance and the performance plummets.
What I take away
It was the project where more people stopped to look at the screen while it ran. Watching the maze appear column by column, with the textures in place and the camera rotating, has a magic that no other 42 tool had given. And, like with all big projects, you come out with the feeling that next time someone tells you "it's just a game", you'll want to explain to them exactly how much there is inside.
The next step was to go down from 3D to networks: 42 (XI): NetPractice, networks without a server.