Programming Linux Games: The Anatomy of a Game
In 1991 a Finnish university student named Linus Torvalds began working on a new operating system in his spare time.
He didn’t work in isolation, nor did hemake a big deal about what he was doing; rather, he modestly invitedprogrammers from all over the world to join his project, which he dubbed “Linux.”
This loosely knit team of students, professionals, and hobbyistscollaborated through the Internet, with the expectation of learning a bit about programming and having a good time. Linus never thought that his project would spawn an entire industry.

Since then, Linux has grown into a general-purpose operating system for a wide variety of hardware platforms. With more than 10 million users (a number that is constantly growing), the Linux platform o ers a sizable audience for computer games. It is now capable of accelerated 3D graphics, environmental audio, and seamless game controller handling, in addition to the server tasks that UNIX-like operating systems generally carry out. Although Linux is still evolving, it is already a solid environment for serious game development.
This book describes the toolkits and the environments that allow programmers to write 2D and 3D games for Linux. We will learn how to draw animated graphics on the screen, how to play high-quality digital sound through several di erent software libraries, and how to set up OpenGL to create uid 3D graphics. By the end of this book, you will know what makes Linux games tick,and how to create your own games for this platform.
This book is not about game design, the mathematics of 3D graphics, or advanced OpenGL programming. These topics are best left to books of their own; I could not hope to do them justice here. However, with the knowledge you will gain from this book, you will be prepared to tackle these topics later on.
Before we begin our discussion of Linux game programming, let’s take a quick glance at our surroundings in the gaming industry so that you can better understand what goes into this type of project.
A Quick Survey of Game Genres
Computer games tend to fall into any one of a number of distinct genres. Many players have strong preferences for certain genres, which makes this an important issue for game designers to consider. And, the presentation of a game concept can make an enormous di erence in its success.
Simulation Games
The simulation genre encompasses a wide variety of games, from ight simulators to Mech combat scenarios. An ideal simulator provides a high level of realism in graphics, sound, and game physics. Some popular simulation games are Heavy Gear II, MechWarrior, and Microsoft Flight Simulator. The basic goal of any simulation game is to put the player behind the controls of something exciting, something that he or she probably would not have access to in real life.
Simulations strive for immersion.
Simulation games (sims) are basically at two extremes. Some simulations aim for absolute realism, seeking to entertain the player with an almost completely accurate portrayal of real life. These “games” are sometimes even used for real-life training purposes. Other sims, like the Heavy Gear and MechWarrior series, trade realism for pure entertainment value. These games are based only loosely on reality; they simulate imaginary vehicles with extraordinary but rather impossible capabilities. (Interestingly, the MechWarrior and Heavy Gear computer games are based on pencil-and-paper role-playing games.)
Simulations pose a serious development challenge.
Since a good modern simulation requires high-quality 3D graphics, detailed vehicle models, a game physics system for simulating the physics of the real world, realistic input response, network capabilities, and possibly a certain amount of artificial intelligence for the computer-controlled players, a contemporay sim is not trivial to construct.
What makes a simulation game successful?
Let’s look at a couple of examples: a “realistic” simulator and an “action” simulator. Microsoft Flight Simulator is a popular ight simulator for the PC (and is in fact the current iteration of a long line of ight simulators by the same developers, dating back to the Commodore 64) that combines realistic control with excellent 3D graphics and interesting airplanes, and the terrain looks reasonably close to the real world’s.1 An experienced pilot could certainly tell the di erence between Microsoft Flight Simulator and a real airplane, but it’s nonetheless an enjoyable simulation.
Microsoft Flight Simulator tries to make the players feel like they were in the cockpit, not just collecting cellulite behind the keyboard of a fast computer.
Although this game will not run under Linux (except possibly under WINE2), it’s certainly worth a look if ou’re thinking of writing a ight simulator.
On another front, the Flight Gear project is presently developing a free ight simulator for Linux. The imulator already sports a realistic physics model and an excellent terrain engine, and it is slated to ventually become one of the best ight simulators ever. Flight Gear is portable to many platforms, as it is based lmost entirely on open technology.
Heavy Gear II from Activision is a good example of an action simulator. It puts the player behind the controls of a multiton Gear (a two-legged walking vehicle with big guns) and succeeds because of its realistic graphics, simple but capable control system, damage simulation, and interesting gameplay. The player is in complete control of his or her Gear and is free to do anything during the game (although accomplishing the mission without getting killed is usually the best plan). Heavy Gear II creates a sense of power and euphoria in the player, and this makes it a pleasant experience. Activision has also published several MechWarrior titles that are very similar to the Heavy Gear series.
Finally, one of my personal favorite simulation games (from many years ago) is Corncob 3D, a completely unrealistic shareware, DOS-based ight simulator.
Guised as a ight simulator, this is a classic “Defend Earth from Space Invasion” game with lots of missions, missiles, and mayhem. By today’s standards, of course, this game is laughable. But it ran well on the low-end hardware of the day, and it was a lot of fun to play. Corncob 3D is a good example of a simulator
that trades realism for entertainment value.
First-Person Shooters
First-person shooters are some of the most popular games today. They typically involve a weak story line (with exceptions, of course), hordes of enemies, big explosions, and lots of blood. The basic premise of most first-person shooters is to give the player an adrenaline rush by putting him in the middle of a hostile environment with insidious monsters and powerful weapons. These games have improved in quality over the years and are beginning to reach a very high level of realism. Some popular ones are Quake 3, Half-Life, and Soldier of Fortune, all of which are available for Linux (although Half-Life is not native to Linux, and
requires the WINE library to run).
High-quality first-person shooters are di cult to produce, not just because they’re hard to program (facilitated by standard 3D libraries such as OpenGL), but also because they require detailed 3D character models and levels. 3D game-engine programming requires a solid knowledge of linear algebra and a firm
grasp of certain types of data structures. However, mathematically inclined people are likely to find 3D game programming both challenging and rewarding.
Valve’s Half-Life is one of the most successful first-person shooters, combining the thrill of a typical FPS with a compelling storyline, amazingly realistic enemies, and an excellent multiplayer mode. Half-Life is based on Quake II’s rendering technology, but that is where the similarities end. Unlike the Quake series, Half-Life has a plot, an excellent single-player mode as well as network game support, and a more complex virtual environment (complete with moveable objects and vehicles).
Another interesting first-person shooter (also based on the Quake II engine) is Activision’s Soldier of Fortune. Decried by critics as gratuitously violent (and hence “indexed” in Germany and classified as an adult title elsewhere), Soldier of Fortune combines traditional first-person shooter action with frightening
realism, even going so far as to correctly simulate bodily damage due to gunshot wounds. It also has a solid plot that develops throughout the game. Overall, a very enjoyable title, if you’re not disturbed by the violence. (I won’t go into the highly emotional politics surrounding this subject.)
A current trend is to mix first-person 3D technology with the role-playing game.
Deus Ex is one such example, a role-playing game based on the Unreal engine.
Deus Ex has been ported to Linux, and I strongly recommend giving it a try.
Real-time Strategy Games
The genre of games known as Real-Time Strategy (RTS ) games includes such popular titles as StarCraft, Command and Conquer, and Total Annihilation—games that allow the player to command individual parts of an army from an overhead view, with success in battle usually leading to better equipment and soldiers. Because success is usually determined by a player’s tactics, these are considered strategy games. RTS games often have a high replay value; they’re fun to play again and again.
RTS games are comparatively easy to program, because, with some exceptions, they do not involve 3D graphics or complicated mathematics; however, good RTS games are hard to produce, and they tend to be few and far between. They often involve a certain amount of artificial intelligence (AI) programming for
controlling the simulated opponents in single-player games—a fascinating field, but one that we’ll leave to other sources.
excellent example. This is not the first notable game from Blizzard Entertainment, and it will be interesting to see what Blizzard comes up with in the future.
Turn-Based Strategy Games
Turn-Based Strategy (TBS ) games are like real-time strategy games, but the gameplay is divided into turns, usually with no time limit, thus giving the player time to think and relax, and lending the game an entirely di erent feel from the faster-paced strategy games. TBS games are not decided by re exes, but rather
by careful planning, which often makes them more di cult, and more attractive to many players. Sid Meier’s Civilization I I is widely regarded as the best turn-based strategy game, because of its balance and replay value.
Deceptively Complex
I once thought that TBS games were easy to write, but then I saw the source code to Sid Meier’s Alpha Centauri (SMAC). Most players don’trealize it, but SMAC actually uses a 3D technique called voxels to
render its units on the y and to draw a height-sensitive landscape with perspective texture mapping and dynamic palette mapping (made possible by self-modifying assembly code). Sid Meier’s Alpha Centauri
was obviously not easy to port to Linux. While it’s possible to write a good TBS game without such sophistication, don’t think of the TBS genre as an easy way out—its complexity can be deceiving.
Role-Playing Games
Role-Playing Games (RPGs) stem from the Dungeons and Dragons role-playing system.3 In this type of game, the player assumes the role of one or more 3 There are lots of similar role-playing systems; I just give DND as an example.
Role-playing games put the player in a world with many possibilities; a good RPG gives its players a sense of immersion and true interaction, and allows them to e ectively become someone else.
The quality of a role-playing game depends much more on its storyline, interaction, and depth than on its graphics. Ultima Online is an example of a good online RPG. While its graphics are not spectacular, the depth of its gameplay is incredible, because it allows for complex interactions between players in a virtual universe. Ultima is not exactly a “hard core” RPG, however; true die-hard RPG gamers often prefer other types of RPGs, such as those published by Simutronics (http://www.simutronics.com).
Puzzle GamesPuzzle games receive less attention than the other game genres, but they deserve to be mentioned. Puzzle games challenge the player with problems that require thought and patience. This genre includes everything from simple box-pushing games (Boxxel and the dangerously addictive Sokoban) to the animated and
ubiquitous Tetris.
A successful puzzle game is usually challenging (but not impossible), pleasant to look at (graphics should not be ignored), and replayable (one-shot puzzle games are usually not very enjoyable the second time around, and players don’t appreciate that). The di culty involved in creating a puzzle game depends on the particular game; some are extremely complex, involving massive amounts of artwork and graphics processing, while others are simple to implement.
Multiuser Dungeons
Multiuser Dungeons (commonly known as MUDs) are massively multiplayer games, typically hosted on Internet servers and accessed with special MUD client programs. MUDs are extremely popular because one’s opponents are real people, not computer-controlled robots. MUDs are essentially text-based role-playing
games, immersing their players in worlds with magical objects, wizardry, and battle. MUD fans wishing to host a game of their own often obtain a prewritten MUD server program and develop their own “world” through configuration files and scripting languages. If they do a good job, they may attract lots of players,
which is very satisfying. Two popular MUD server programs are ROM and DikuMud, which may be downloaded from the Internet. There are untold thousands of private ROM-based MUDs on the Internet.
MUDs are relatively easy to create, though writing a MUD server is not trivial, requiring a solid background in C or similar and a knowledge of network programming. Creating MUD datafiles requires little programming knowledge but a lot of creativity. A good MUD has an interesting game world to explore and a good balance of races and abilities. Also, some MUDs are prone to “god moding,” or abuse by the person running the server; while this obviously depends on the players, good design can lessen this undesirable e ect.
If you’ve never been “mudding,” give it a try. A good MUD can provide a truly interesting experience. You can find MUDs all over the Internet; just search the Web for the word “mud.”
A Quick Look Under the Hood
Most games have a lot in common behind the scenes. The engine, or main code, of a “typical” game (if there is such a thing) can be logically divided into several subsystems: the input subsystem, the display subsystem, the audio subsystem, the networking subsystem, the update subsystem, and the main loop. These subsystems are rarely labelled as such, but you are likely to find all of these components in any given game engine. Each subsystem is most often implemented with several separate source files; two or three in small games, but easily a hundred or more in a large production. We’ll look brie y at each of
these subsystems now, and throughout the rest of the book we will explore possible ways to implement each.
This Code Is Awful!
If you ever get a peek at the code behind a major commercial game, please do not take it as a treatise on proper software design or co ding!
Games often start out as well-designed software, and they sometimes even make it to the shelves in a tolerable state of internal organization,but more often than not a game’s code falls into disarray during the last few months of development.
Why, you might ask? The gaming industry is volatile, dangerous, and extremely competitive. Game studios seem to find themselves in a perpetual struggle to meet release deadlines, get their games out ahead
of their competitors, and implement the features that players demand, lest they be left in the dust with a stack of unsold games. This often results in extremely hurried and sloppy code. Unfortunately, this often
causes serious problems if someone later tries to add an expansion pack to the game or port the game to another operating system.
The Input Subsystem
The input subsystem receives the user’s commands through an input device (like the keyboard or a joystick) and records these commands for further processing.
While input device programming is not di cult, it should be done carefully, because awed input processing can easily ruin an otherwise excellent game. The first version of Apogee’s Rise of the Triad (a first-person shooter from several years ago) su ered from particularly bad input handling, and the game was
aggravating to play until this problem was fixed.
One of the input subsystem’s most important jobs is to simultaneously support a variety of input devices. A well-written input subsystem should be able to integrate just about any type of oddball game controller with minimal e ort (this is made a bit easier by libraries like SDL, but it’s still something to keep in mind as you code). Some players prefer to use joysticks rather than mice, and an input subsystem should be able to accommodate this preference without modification to the main game code. As far as the game is concerned, the joystick should appear as a generic device, capable of producing “left,” “right,” “up,” and “down” commands. We will discuss SDL’s input handling and abstraction in Chapter 4, and we’ll touch on the lower levels of input handling in Linux later on.
Nearly every game on the market allows you to remap the keyboard and other input devices to your liking, and this is a feature that players demand. Many people have non-US keyboards with di erent key locations, and you’ll end up cutting o a lot of would-be players unless you allow them to configure the game
to work with their keyboards. Fortunately, this is not di cult; it can be accomplished with a simple lookup table. It is also a good idea to allow the player to store and retrieve multiple key mappings, in case a friend prefers a di erent configuration.
he Display Subsystem
The display subsystem conveys the game’s status to the player in a visually impressive way, whether through simple 2D graphics, or advanced 3D rendering (the type of graphics you use doesn’t matter, as long as they are appropriate for the game). Regardless of the type of graphics produced by the display subsystem, the structure of the code is substantially the same.
The display subsystem is responsible for taking advantage of the available display hardware. Serious gamers often equip their machines with snazzy 3D graphics cards, which can bring enormous performance and quality improvement to 3D games. However, this performance boost is no t automatic and requires special e ort by the programmer, which is usually accomplished through an API (application programming interface, essentially a big library of routines) like OpenGL. 3D acceleration is beyond the scope of this book, but we’ll
demonstrate how to get OpenGL up and running in Chapter 4.
Before you can show o your graphics code, you’ll need something to display.
Players are a finicky bunch, and they are most intolerant of subpar graphics.
Game programmers should spend a great deal of time developing a good graphics engine, and a designer should place a high priority on obtaining quality artwork for a game.
The Audio Subsystem
Although computer audio technology has not been hyped as much as computer rendering technology during the past few years, a game’s audio subsystem is every bit as important as its graphics subsystem. Fortunately, producing high-quality sound on a computer is not as di cult as producing high-quality graphics.
seriously damage a game’s potential.
3D enhanced audio is one of the latest trends in computer sound technology with modern sound cards (like Creative’s SB Live! series) supporting four-speaker surround-sound, and 3D-aware sound-processing to simulate the Doppler e ect and other complex sound wave interactions. (Simple two-channel stereo sound
just falls short of the immersive environments of today’s 3D games.) In fact, some sound cards can even accelerate these e ects in hardware.
Multiplayer gaming is very popular these days, and it is reasonable to assume that this trend will continue. The network subsystem connects a game to other computers over a network so that multiple players can participate in the action.
Network programming is not as di cult as it used to be, especially with the advent of the Internet as we know it. Still, the network subsystem must be extremely robust and exible, as, not surprisingly, gamers are rather intolerant
of network failures during games. Basically, the network subsystem informs the other computers in a network of
Above all, do not implement network support as an afterthought, because it often a ects the entire design of the game. Decide whether your game lends itself to netwok play and build this requirement into the fundamental game design; doing so will save headaches later on when the designer invariably demands that multiplayer capabilities be added.
The Update Subsystem
Games generally have to track a lot of rapidly changing data, including the state of the player and the condition of each enemy—information that must be updated frame by frame to keep the game moving. The update subsystem manages this data.
game modules are merely interfaces to the update subsystem.
Keyboard
Input Subsystem
Mouse
Game Pad
Network Subsystem LAN or
Internet
Update Subsystem
3D Hardware /
Framebuffer
Display Subsystem
Audio Subsystem Sound Card
cycle; make the update system a separate module to begin with. If you don’t pay attention to code organization, you’ll end up with code that looks like the 500,000 lines of spaghetti behind (no o ense, Activision) Civilization: Call To Power.
The Game Loop
The game loop is the “glue” that binds the various game subsystems. It is simply a while loop that runs throughout the entire game, looping anywhere from 30 to 60 times per second. The game loop invokes the
The game loop should start as soon as the game’s other subsystems have been initialized, and should end when the player exits the game. It may be a good idea to separate the menu system from the main game loop in some cases, but doing so could actually complicate the game’s code. With a properly written
game loop, a game becomes a “state machine” that acts on its current state based on the player’s input.
Organization is important too, since the game loop sequences the other subsystems. This should not be a haphazard decision; for instance, the data gathered from the networking subsystem often in uences the decisions of the other subsystems, so it should be invoked first. The graphics subsystem should probably be last, since it re ects the data generated by all of the other subsystems.
As you can see, a game engine is conceptually simple, but the devil is in the details. In the next chapter we’ll become familiar with the tools we’ll use for Linux game programming, and then we’ll start to work with the libraries and interfaces that make it all possible.
Latest Posts
-
05/05 – Ubuntu's OpenGL Face Browser with GNOME Desktop Manager
-
25/04 – Veritas NetBackup: Dedicated or Shared Backup Environment
-
16/04 – Dvd+rw-tools makes it possible to burn Dvd images created by “dvdauthot” or “mkisofs”
-
15/04 – FEBE (Firefox Environment Backup Extension) 5.3.1 released
-
14/04 – Veritas NetBackup, Backup Planning and Configuration Guidelines
-
13/04 – Ubuntu Server Guide, Part 3: PostFix, PostgreSQL, Databases and SMTP Authentication
-
10/04 – New Compiz Fusion: Cubereflex rename to Cubeaddon with new effect Cylinder
-
08/04 – RSS Buttons Collection Pack for Your Blog: The Ultimate List
-
05/04 – MP3Roaster is a Perl hack for Burning Audio Cds out of Mp3 OGG Vorbis and FLAC files
-
26/03 – Picasa is a software application for organizing and editing digital photos
-
19/03 – Dvd+rw-tools makes it possible to burn Dvd images created by “dvdauthor” or “mkisofs”
-
15/03 – The Burgner project aims to be a complete free burning suite
-
14/03 - Software Packages in Hardy Heron: Administration Utilities
Linux Links
-
05/05 – GNU Cpio Copies Files into or out of a Cpio or tar Archive
-
04/05 – Simple Linux Backup is a easy-to-use backup to automatically backup a Linux Desktop System
-
03/05 – DIBS is a Backup System that Protects your Data by Giving your Files to Peer
-
02/05 – Updates Medibuntu Repostories for Ubuntu 8.04 Hardy Heron
-
30/04 – Enigmail, extension to the Mail Client of Mozilla Thunderbird and Mozilla SeaMonkey
-
24/04 – Timidity ++ is an Open Source MIDI to WAVE converter and player
-
23/04 – Ubuntu Start Manager for the bootloader (Grub o Grub2) and boot splash (Usplash or Splashy)
-
23/04 – Gvtray for Xubuntu, a voume control for four system tray
-
22/04 – a MSN is a Windows Live Messenger clone licensed under the GPL
-
20/04 – VLC VideoLan Media Player 0.86 f release for Ubuntu Linux
-
16/04 – HacBurn a script written in Perl aid in writting CDs
-
25/03 – Phaser, a frontend to Cd record with the aim for Making Cd Burning Under Linux Easier
-
19/03 – Gnash, the free software Flash Player , has released its first beta
-
16/03 – Burn CDDA console frontend for cdrecord, mpg 123, oggdec, mppdec, flac
-
03/03 – KPDF viewer based on the code of the xpdf application




digg it
del.icio.us










