
Game Programming Patterns - GuiA
http://gameprogrammingpatterns.com/
======
Jare
Most lists of design patterns (including but not limited to the GoF and this
site) are written with the noblest of intentions, and contain a lot of
insights and interesting solutions. Patterns can provide specific solutions to
specific problems, and also a common vocabulary for developers to talk about
these problems and solutions.

Unfortunately, for the past 18 years I have seen repeatedly (in the game
industry and outside) that they tend to be used as shopping lists by
developers who can't (or don't have time to) think, design and architect
properly. The result of such approach to development, let's call it Pattern
Oriented Design, are bloated, overengineered and underperforming systems that
are still harder to write, document, test and evolve, than the disorganized
messes they replaced.

So, nice work, but beware programmers: you must first understand the problem
you are trying to solve, before you go shopping for a solution.

~~~
tieTYT
I've have to make a confession: Almost every time I use a pattern it makes my
code more complex and harder to understand. I've used visitor, composite,
singleton, all sorts of factories, decorator, proxy, state, strategy, etc.

You have a problem, then you realize, "I think this is what the x pattern is
for. How does that pattern work, again?" You then google it and try to
implement it correctly. Almost by definition, you're not implementing the most
obvious solution. If you were, you probably wouldn't have to google it. It'd
be better to implement the simplest solution that could possibly work.

I think design patterns may be good as a communication tool, and no more. It's
faster to say, "factory" than to describe the pattern's implementation. But
code maintainability is way higher priority than using a pattern and in my
experience pattern implementation and code maintainability are mutually
exclusive.

~~~
GuiA
Design patterns are a thing that are useful only when you've essentially
rediscovered them for yourself in natural solutions.

I developed games as a kid for many years, and I developed solutions to some
problems that I identified later as patterns while reading the GoF book.

However, if I had read the GoF book in the first place and tried to forcefully
implement patterns just based on reading about them in a book, I'd have done a
miserable job.

------
exemd
A pattern: deterministic game state, updated only by player input.

It's used for multiplayer synchronization. Instead of sending thousands of
objects, it's enough to send mouse clicks and keystrokes.

"1500 Archers on a 28.8: Network Programming in Age of Empires and Beyond"
[http://www.gamasutra.com/view/feature/3094/1500_archers_on_a...](http://www.gamasutra.com/view/feature/3094/1500_archers_on_a_288_network_.php)

It's also used for game replays.

~~~
asperous
Also one of the hardest patterns to do right (explained somewhere else)... one
small glitch in the world state and the state goes out of sync.

~~~
qznc
Yes, these are very subtle. For example, floating point computation has
different precision depending on the machine. This might lead to small
differences in the game state, which grow over time (chaos theory yay). It is
really hard to hunt such bugs. The fix might look like this:

    
    
      - double result = x * y * z;
      + double tmp = x * y;
      + double result = tmp * z;
    

The intermediate value x*y is rounded to double precision afterwards, whereas
it had machine precision before.

(disclaimer: second hand war story from OpenTTD, might not be entirely
accurate)

~~~
vog
Indeed, if determinism is very important, fixed-point arithmetics should be
preferred over floating point arithmetics - at least in the game engine, for
the rendering floating point should be fine.

Note that fixed-point arithmetics is almost identical to integer arithmetics,
thus easy to implement. If you define your physical units small enough (e.g.
velocity as pixels/ms instead of pixels/s), then you can use integer
arithmetics right away without any confusion.

One minor drawback is that you don't have easy access to cos(), sin(), sqrt(),
etc. without going through floating point. However, you usually don't need
those in the game engine anyway. For instance, instead of "sqrt(x _x + y_ y) <
r", just write "x _x + y_ y < r*r".

The major drawback is that you now might have to deal with integer overflows
(and underflows). You should deal with them in floating point, too, but these
are more unlikely there. One might think that this won't destroy determinism
if you are using e.g. always 32 bit integers on all platforms, but note that
some kinds of (signed) underflows or overflows are technically undefined, at
least in the C standard, so some compilers might do optimizations that lead to
different underflow/overflow results than expected.

~~~
epsylon
Floating point arithmetic is deterministic if you are careful enough:

> "I work at Gas Powered Games and i can tell you first hand that floating
> point math is deterministic. You just need the same instruction set and
> compiler and of course the user’s processor adheres to the IEEE754 standard,
> which includes all of our PC and 360 customers. The engine that runs
> DemiGod, Supreme Commander 1 and 2 rely upon the IEEE754 standard."

See [http://gafferongames.com/networking-for-game-
programmers/flo...](http://gafferongames.com/networking-for-game-
programmers/floating-point-determinism/)

------
krakensden
I love big long articles on the main loop. It's one of those wonderful
problems that seems like it ought to be easy but turns out to have lots of
subtle (and important) complications.

~~~
karl_gluck
The early GPU Gems books might be of interest to you. They are full of stuff
like frame timing subtleties and interesting ways to solve common game loop
problems. These days, you can probably get them for less than $50 each, too.

~~~
vilya
GPU Gems is available online for free, courtesy of Nvidia:
[http://developer.nvidia.com/object/gpu_gems_home.html](http://developer.nvidia.com/object/gpu_gems_home.html)

------
babuskov
Very well written. I was a bit skeptic, so I went directly into Singleton
pattern that many get wrong... All I can say that this is some of the best and
cleanest explanation why Singleton is an anti-pattern, and also what do use
instead.

~~~
munificent
Thanks! When I was at EA, I swear every source file had like five singletons
in it. It was terrible. I was highly motivated to write that chapter at the
time.

~~~
jason_slack
But lets talk about Singletons just for a sec. I am currently writing a game
and I do have 2 singletons. My director class (that controls initialization
and instantiation of all the things I need) and my main game scene (when the
user presses Play from the menu). To me this made perfect sense.

But I can see how singletons get out of hand, but could also make sense to the
developer to do so. (Meaning the developer thinks it makes sense to over use
when it might not)

How do you approach the fact that maybe your game scene, layers on that scene,
HUDS, all would just have a single instance ever?

I have read that singletons are used a lot in games and well games are
playable (meaning they run and work) so do you ever apply "if it ain't broke"
philosophy?

Your site will be very useful to a lot of people. Singleton alone.

~~~
munificent
Sure, I'm not saying never ever ever use Singletons, just try to limit them.
Most games and apps I've seen, even well-written ones, still have a little
static state floating around. The idea is just to constrain it, know what
problems it causes, and be deliberate about it.

------
robertkrahn01
A must have architectural pattern for such a list: "Entity Component System"
[http://en.wikipedia.org/wiki/Entity_component_system](http://en.wikipedia.org/wiki/Entity_component_system)

~~~
interpol_p
Not to take away from the value of component systems, but I find them
remarkably tedious to code with.

In Unity 3D they work well because the component attachments are driven by the
visual interface. Your coding happens inside components, and is then linked up
in the scene visually.

The second game engine I implemented used an entity component system, and I
found myself not wanting to use it. Attaching and building components in code
just to do trivial things was tiresome.

I think such a system is valuable for a game that's already designed,
prototyped and ready to be implemented cleanly, but it's not a great pattern
for prototyping/rapid game development.

It's almost like you need one set of patterns for game prototyping (messy,
hacky, and immediate operations), and an orthogonal set of patterns for final
game implementation.

~~~
drblast
Conceptually, I think it is harder and kind of a pain to code for at first.
But one of the advantages I've found using it is the ability to completely
decouple the state of game objects from the code that manipulates them. This
gives you the following (rarely mentioned) benefits:

1\. Saving game state is trivial (as is replaying it, like in a rewind or
time-travel)

2\. For garbage-collected environments, it's easy to completely avoid GC
pauses by re-using old game state objects.

3\. Adding existing functionality to any object is trivial.

#2 was the biggest win for me. I made some small bullet-hell style shoot-em-
ups in C# that would pause for GC until I reworked the game into a component
system where all game objects were stored in a table, and each row in the
table contained all columns for all possible objects properties.

So when a bullet went offscreen, the row its state was stored in became
available for the next game object (bullet, alien, etc.) The only step
necessary was to wire that row to the various components that would control
the game object. The GC pauses disappeared, and this made changing the game
and prototyping extremely easy. I'd imagine this would simplify memory
management in C++ in the same manner.

I also really enjoyed have things like "AffectedByGravity" as a component and
the ability add objects arbitrarily into it, instead of some hackish
inheritance chain.

~~~
interpol_p
I mostly agree with you, I just found that trivial things — like drawing
sprites — became cumbersome.

In my case it involved adding the transform component, the sprite render
component, any movement components (usually custom subclasses for the specific
game) and then adding that node into the graph.

When I wanted to hack away quickly on ideas I found I avoided my own engine
because of all the typing it took just to get something up on the screen and
moving. Or I found myself creating simple wrappers on top of the component
system that killed the flexibility for the sake of brevity and readability.

In my personal experience coding with components did something to stop the
creative, messy part of my brain that just wanted to see things on the screen
and moving as soon as possible.

~~~
drblast
Yeah, I see that. The reason I think what I did became so easy is that I took
the component model to the absolute extreme. There were no objects at all,
just a table of state data and a collection of functions you could add to an
"entity."

I think most implementations mix and match some sort of OO and that would get
messy quick. What I did worked great for the particular bullet-hell style
shmup I was making. I don't know how well it would work with other types of
games, particularly those with game entities that had a ton of state that
wasn't shared.

With the bullet-hell game, an enemy shared a lot of state with the main
character and bullets. An RPG might be a different story.

------
Ellipsis753
It looks interesting and well written. However I would prefer to read it when
it is complete or at least more complete.

~~~
karl_gluck
I wouldn't hold your breath. When I last used this site in 2010 [1] it wasn't
that much less complete.

Still, what is has is very useful and I'd suggest giving it a read.

[1]
[http://web.archive.org/web/20100131082252/http://gameprogram...](http://web.archive.org/web/20100131082252/http://gameprogrammingpatterns.com/)

~~~
munificent
It was on hiatus for a couple of years: I left the game industry, moved across
the country, and had a couple of kids. But I'm back to working on it now and I
hope I can get it finished.

~~~
karl_gluck
Hi! Wow, very nice to meet the author. Most of this was written after I'd
already finished my game, but the Object Pool article was part of the
inspiration for my memory pool class [1]. Thanks for everything you've
written, it has helped more people than you probably know.

[1]
[https://github.com/karlgluck/Evidyon/blob/master/Source/comm...](https://github.com/karlgluck/Evidyon/blob/master/Source/common/DirectCraft/dcx/dcxmemorypool.h)

~~~
munificent
That's great to hear! I'm glad you got some use out of it. Feedback like this
is the only thing that gives the book a chance of being finished. I'm
generally terrible at staying focused on one thing but hearing stuff like this
really helps.

~~~
tripzilch
I only just found it, read the "Game Loop" chapter and it's great stuff! I
like how you clearly enumerate the pros and cons of several approaches. And
even if an approach was already familiar to me, that made it very useful
providing new ways of thinking and comparing about it.

So please do keep it up :)

~~~
xradionut
"If there is one pattern this book couldn’t live without, this is it. Game
loops are the quintessential example of a "game programming pattern". Almost
every game has one, no two are exactly alike, and relatively few programs
outside of games use them."

I've borrowed many of the game loop and other game programming principles when
developing code for controlling external equipment like robots and radio
transceivers. It's a better model than some of the crazy state machine code
I'd written in the past.

------
seivan
I was hoping to see how to deal with Path finding and interpolation.

Do you run the pathfinding and set the position in each game tick, or does the
pathfinding has it's own tick.

~~~
mtinkerhess
There are two stages: first, the path is found. Second, the path is followed.

To find the path often takes longer than one update tick. The old way to
handle distributing the job over multiple ticks was threads; the new way is
coroutines.

------
scott_s
I'm going to jump on the bandwagon and say that these are very well written -
clear and concise, but they still retain authorial voice, and the examples
work as intended. I found them of interest even though I work in general
systems, but not games.

But, one question: in the "Subclass Sandbox"
([http://gameprogrammingpatterns.com/subclass-
sandbox.html](http://gameprogrammingpatterns.com/subclass-sandbox.html))
chapter, shouldn't the activate member function be public? That is, isn't that
function the interface to the outside world? As written, the Superpower
abstract class has no external interface.

------
stonemetal
I find most pattern texts rather weird, this one is no exception. They start
out with a super convoluted OOD, then refactor to something better but still
fairly ridiculous. Case in point the Type Object Pattern, ridiculous straw man
design refactored to something cleaner but still more complicated than
necessary. If you find yourself working on a team and some one purposes the
starting point you must be dead because you are in one of the inner circles of
hell.

------
nickporter
I remember reading through that website when I was researching game object
systems. Very useful resource!

Here's my implementation of a component-based game object system, if
interested:

[https://github.com/surjikal/cbgos-
experiment](https://github.com/surjikal/cbgos-experiment)

------
benjamincburns
Now if only there was an annotated encyclopedia of discrete approximations to
accompany this...

------
Scramblejams
Would love to see a version of this tuned for a language like Erlang.

------
jwmoz
Type Object aka the Strategy Pattern.

------
zamalek
It's surprising that the singleton is there - from what I have read on
altdevblogaday and other gamedev websites it seems that game developers have
long since moved past that antipattern. Honestly, I wouldn't have re-iterated
the GoF patterns at all: there is already plenty of literature covering them.

Otherwise, quite informative.

~~~
GeneralMayhem
If you'd bothered to click through to that chapter, you'd have seen that it's
actually a lengthy dissertation on why singletons are a bad idea, including
seductive patterns that are actually singletons in disguise and a couple
better alternatives for when global state is really unavoidable.

