Tag: programming

# Math for Game Programmers 05 – Vector Cheat Sheet

This is the long due fifth article in this series. If you aren’t comfortable with vectors, you might want to take a look at the first four articles in this series before: Introduction, Vectors 101, Geometrical Representation of Vectors, Operations on Vectors.

This cheat sheet will list several common geometrical problems found in games, and how to solve them with vector math.

# Best of Game Development Videos and Presentations

Here’s a list of my favourite videos and presentations on several subjects related to game development. I strongly recommend every single video listed below, at least those that match your area of expertise.

If you can think of any good videos that I missed, please leave a link on the comments. I will update the post with any videos that I enjoy.

### C++

(Most of the following are highly technical and specific, but I recommend the first presentation, “Why C++?”, to every programmer.)

Those who have used OpenGL are probably aware that you can only invoke OpenGL procedures for a given context on the thread that currently owns it – usually, the main thread. This leads many programmers to assume that OpenGL is strictly single-threaded, and that no loading can be done on the background, inside some loader thread. This is not the actual case, and it’s actually fairly simple to work around this.

The key to multi-threaded OpenGL is in creating multiple contexts that share data between them. On Windows, it is done with the wglShareLists() procedure. On X and Apple APIs, it can be done during context creation (glXCreateContext() and aglCreateContext(), respectively). It boils down to creating a second context for the loader thread, and setting it to share data with the main context. This way, all data loaded on the second context will be available on the main one – you can just create a texture normally on the loader thread, and then glBindTexture() it on the main thread, for example.

On Windows/C++0x, the code looks like this:

```void startLoader(HWND hwnd)
{
// Assuming that this is the main thread
HDC hdc = GetDC(hwnd);
HGLRC mainContext = wglGetCurrentContext();

wglMakeCurrent(nullptr, nullptr);
});
}```

Most APIs (such as Allegro, SDL, wxWidgets, etc) will provide you with a simple method of retrieving the window handle, which is all that you require to call the above procedure.

Note that you could create the context and share the lists inside the loader thread, but wglShareLists() must be called BEFORE anything is done on the main context, so the safest way is to do it on the main thread (otherwise, the new thread could take a while to run and be too late to do it).

IMPORTANT! I have observed that, on some cases (Windows 7 64, NVIDIA 320M), attempting to use a texture after it has been created (via glGenTextures()) but before its data finished uploaded (in this case, via glTexSubImage2D()) resulted in the texture being corrupted, and remaining corrupted even after it was uploaded. This will happen even if you wait for glTexSubImage2D() to return before using it on the main thread, since OpenGL is asynchronous. To avoid this problem, make sure that you glFinish() the loader thread before you attempt to use any textures initialized there.

# If programming languages were religions…

I originally wrote this article in December 15, 2008, and posted it on the Aegisub blog. I’m re-posting it here for archival purposes.

“If programming languages were religions”

(Inspired by “If programming languages were cars“)

C would beĀ Judaism – it’s old and restrictive, but most of the world is familiar with its laws and respects them. The catch is, you can’t convert into it – you’re either into it from the start, or you will think that it’s insanity. Also, when things go wrong, many people are willing to blame the problems of the world on it.

# Understanding the Game Main Loop

Video games are simply ordinary software – there’s nothing intrinsically special about them. However, they SEEM to behave in a very different way from your ordinary everyday applications – so much that many experienced programmers are at a complete loss when faced with the task of developing a game from scratch. This difference is mostly caused by game’s close ties to their main loop. In this article, we’ll examine what is the main loop, how it works, and why it’s important.

A simple model

How simply could we model a computer game? Let’s start by separating the game in two parts: the data inside the computer, and everything outside the computer. This might seem like a strange thing to say, but remember that games are, first and foremost, interactive software. So, outside the computer, we have (at the very least) the player. Inside the computer we have all sorts of data, but the most important is what we call the game state: it contains all the dynamic information of the game: the position of the player, monsters and camera; the current time; the score – in essence, everything that changes with time.

A computer game can then be understood as a system in which those two entities – player and game state – interact with each other according to a specific pattern of rules. The player inputs data into the system, and the system uses the game state to generate output to display to the player. This is not very different from ordinary applications, in which e.g. a click (input) might cause a dialog to show up (output). The difference is how that behaves in respect with time.

The Game Loop

Most applications are developed in a reactive way – your program just sits around waiting for the user to click something, and then it does something in response. There is a main loop behind your application as well, but it’s not important – it’s abstracted away. With games, your code is constantly being invoked, even in the absence of user input.

The pseudo-code for a video game will often look like this:

```void GameClass::main() {
init();
runMainLoop();
deInit();
}
```

The main loop looks something like this:

```while (running) {
processInput();
updateGameState();
drawScreen();
}
```

First, it reads input from the user and stores it somewhere. Here, it will check the keyboard, gamepad, plastic guitar and network message queues – basically, it will collect all information from the outside world.

After that, it will use that information to update the game state – depending on what conditions we have, they will have different results. For example, on the menu screen, detecting that the “down” arrow got pressed might increment the “currently selected menu item” variable, but the same input while on the game might instead trigger the “set player as moving down” flag. Note that the world update is invoked even if the user didn’t perform any input. This is a very important property of most video games.

Lastly, it will collect the current game state data to generate the output – it will figure out where the player and camera and everything else are, and generate an image to display on the screen. A more complicated game will also have to deal with other forms of output – audio and network, for example.

A More Sophisticated Main Loop

The loop pseudo-code above suffers from a major flaw: it will run at unpredictable speeds – on fast machines it might run thousands of times per second (which would be a waste), and on slow machines it might run on unacceptably slow speeds – perhaps only five updates per second or so. Besides the obvious issues, this makes the game much harder to program – it’s much easier to write your game logic when you know that you’ll have a fixed number of steps per second.

Consider this: the player presses the right arrow, and you store a flag containing that information. Now, on every step, regardless of any player action, you’ll move the player to the right by 1 unit in the game state (which, let’s say, corresponds to 1 pixel on the screen). If the game runs at 5 Hz (that is, 5 updates per second), the player will move VERY slowly. If it runs at 5000 Hz, he’ll be out of the screen before you can even see it!

A possible solution to this is to calculate the real time elapsed between two steps and use this information during the step. In practice, however, this makes the game development much harder and error prone. It will also make networking a true nightmare, and will essentially make reliable behavior (e.g. replays) impossible.

A much better solution is to fix the rate at which your game performs its updates. Most modern games use an internal clock of 60 Hz or 30 Hz. Let’s assume 60 Hz for our example. This means that, 60 times per second, your game will check the input from the player, update the game state, and try to display something on the screen. But how do we control that?

First, let’s consider the case of a very fast computer. In this case, before each iteration of the main loop, we’ll check if it’s time for the update. If it isn’t, we’ll simply wait (preferably yielding the time slice back to the operating system), without doing any processing.

In the case of a slower computer, things are trickier – we can’t skip on updating the game state, or the game will run in slow motion, so we must sacrifice the output – the screen rendering. On most games, screen rendering is the slowest part of the pipeline, meaning that most games WILL be able to run at 60 Hz given enough sacrifice on graphics. If not, then the game will be way too slow, and we have no choice but ask the player to get a better computer.

In pseudo-code, our new algorithm now looks somewhat like this:

```while (running) {
if (isTimeToUpdate()) {
processInput();
updateGameState();
if (hasTimeToDraw()) drawScreen();
} else {
waitUntilItsTime();
}
}
```

It’s simple, but it’s very similar to real game loops found in real games.

The Foundation

At this point, it should be clear that the vast majority of the game code will run inside the main loop – in a simple game, everything except for initialization and deinitialization. Also, that code is now separated in three functions: processing input, updating the game state, and rendering the screen. Since all three of them are controlled by the loop, it’s the foundation block of every game.

Having this foundation, your task of implementing a game has been reduced into three simpler and relatively independent tasks. The input you collect will be used on the state updating stage, and the state created by that step will be used to generate the output to the user, but they are each their own logically distinct operations, and how they interact with each other is now clear.

If you understand the topic discussed in this article, then all you have to figure out in order to make a (very) simple game is “how to read user input?”, “how to draw stuff on the screen?” and “how to keep track of my state and update it?”. None of those are, at a basic level, difficult, but they might be different from what programmers are used to coding.

On the next article, we’ll try to figure those things out and write an extremely simple real-time game using those concepts.