The heart of all games.

How are games put together at a high level? How do they work? When starting out, it can be frustrating trying to find the answers to these questions. Game programming articles dive straight into talking about frameworks and programming languages; highlevel architecture is rarely discussed.

Let me tell you how it all works. From Tetris to Super Mario to Final Fantasy the basic architecture for all games is the same; they're built around a game loop. A game loop is a piece of code thats runs tens to hundreds of times a second and tells the hardware what to draw on screen. With very few exceptions all games are structured in this way. You want to make a game? You’ll need to write a game loop.

Computers are FAST

Assuming you’re a healthy adult, your heart beats sixty to one hundred times a minute. That heart beat is an eternity to a computer, processor cycles are measured in billions per second. Computers are really fast; they operate at timescales that exist outside of day-to-day human experience.

When was the last time you went to the cinema? The last movie you watched was probably digital but in the past cinemas used film-reels and projectors. A film reel is a strip of pictures that are projected onto the cinema screen. For every second of a movie there are 24 pictures on the film. Another way to phrase this, is to say that movies in the cinema run at 24 frames per second. To a gamer that sounds horribly slow but that's that way it is!

The human eye and brain perceives images individually if only 10 to 12 are shown per second. Start to show the images at a faster rate and the brain no longer perceives individual images but starts to perceive them as a continuous animation.

Games often talk about frames per second too, but games have no film, so where do the images come from? As we've said, computers are fast and while the previous frame is shown, the computer generates the next image on the fly! It’s like a demon with a paint brush drawing so fast you don’t even notice. The canvas the demon draws on is the called the framebuffer and you can think of this as a big grid of pixels that are shown on your monitor.

Frames Per Second

A game only needs to update the screen every 12 seconds to trick the brain into seeing continuous motion but it's more normal to use 30 or 60 fps. The higher the framerate the smoother animations appear and more thoroughly the brain is convinced by them.

If your game runs at 30 frames per second that means it has 0.0333 seconds to generate the next frame. If your game runs at 60 frames per second, you have even less time; just 0.01666 seconds to generate the next frame. In that timeframe you can barely blink but fortunately the computer isn't working on human time. In these few fractions of a second it can paint a photo-realistic vista of an alien planet and still have time to respond to input, simulate virtual creatures and play sound effects!

In that 0.01666 second the computer can run hundreds of thousands of operations. It’s up to you as programmer and game designer to decide how you’ll use the operations to create your game.

(As a general rule reality is almost always messier than theory. Modern video game systems have a main processor, often with several cores, called the CPU and a special graphics processor called the GPU. Operations are split between these two processors; the CPU does general operations and GPU does graphics specific operations often in parallel. The GPU has a lot of hardware just for doing 3D such as graphics and lighting calculations. The game code runs on both these processors and they work together to run the game.)

From Code to Screen

Now we have a general sense that games are similar to movies and they display lots of pictures to give a sense of motion. But what's the role of the game code and the game loop? Well, somewhere in the game code there’s something looks like this

function update()
    draw_something()
    update_frame_buffer()
end

The exact details of how the update function gets called and how it tells the frame buffer to update are often handled by libraries such as SDL and OpenGL or an engine like Unity or Unreal. The key takeaway is that when this update loop runs it updates the picture on the screen. The game calls this loop 30 or 60 times a second. If the update tries to do too much then the game will feel laggy because the refresh rate won’t be consistent.

Games are more than just graphics. Graphics are expensive and a AAA game spends up to 60% of the frame time on graphics alone, meaning the rest of the game needs to fit in the remainder. That means if a game runs at 60fps there’s just 0.005 seconds to handle everything else in game! (And you wonder why simple first-person shooters are so popular?). Thats 0.005 seconds to detect and respond to player input, to fire off sounds, to update the world, to handle AI, to do physics and collision detection; it’s not much!

A more fleshed out computer game loop looks like

function update()
    handle_input() // keyboard, gamepad etc
    update_world() // ai, physics, hit detection etc
    render() // draw to the screen
end

These are the three main stages of the loop: update the player input, update the game world, and then tell the graphics card what to render. In every game you've ever played this loop lies at center like a beating heart driving the game forward.

What does a real-world game loop look like? Well, here's the update loop from Quake:

WinMain
{
    while (1)
    {
            newtime = Sys_DoubleTime();
            time = newtime - oldtime;
            Host_Frame (time)
            {
                setjmp
                Sys_SendKeyEvents
                IN_Commands
                Cbuf_Execute

                /* Network */
                CL_ReadPackets
                CL_SendCmd

                /* Prediction//Collision */
                CL_SetUpPlayerPrediction(false)
                CL_PredictMove
                CL_SetUpPlayerPrediction(true)
                CL_EmitEntities

                /* Rendition */
                SCR_UpdateScreen
            }
            oldtime = newtime;
    }
}

Now Quake is a realtime multiplayer game so the structure in this gameloop reflects that. If you want a more detail blow-by-blow of what's happening there's a good review here.

Take Aways

I hope you now understand the basic structure of games and role of the game loop. This should provide a framework to slot in future knowledge about the structure and execution of games.