<?xml version="1.0" encoding="iso-8859-1"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en">
  <title>Games from Within</title>
  <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/" />
  <modified>2007-04-12T07:06:10Z</modified>
  <tagline>An engineering look at the game development process</tagline>
  <id>tag:,2007:/2</id>
  <generator url="http://www.movabletype.org/" version="2.65">Movable Type</generator>
  <copyright>Copyright (c) 2007, llopis</copyright>
  <entry>
    <title>Starting Power of Two Games</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0704/000113.html" />
    <modified>2007-04-12T07:06:10Z</modified>
    <issued>2007-04-12T00:06:10-08:00</issued>
    <id>tag:,2007:/2.113</id>
    <created>2007-04-12T07:06:10Z</created>
    <summary type="text/plain">I know, things have been pretty slow around here for a while. The good news is that the slience is over. Charles Nicholson and I decided to take the plunge and create our own game development company: Power of Two...</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>General</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      <![CDATA[<p>I know, things have been pretty slow around here for a while. The good news is that the slience is over.</p>

<p>Charles Nicholson and I decided to take the plunge and create our own game development company: <a href="http://powerof2games.com">Power of Two Games</a>. So I finally get the chance to follow the dream I've had for a long time!</p>

<p>From now on, I'll be writing mostly on the <a href="http://powerof2games.com">Power of Two Games web site</a>. We'll talk about about everything from the details on getting a company off the ground to development processes that we're using. But this time we'll be writing much more frequently, so subscribe to our <a href="http://powerof2games.com/rss.xml">RSS feed</a> and follow us along in this wild ride.</p>]]>
      
    </content>
  </entry>
  <entry>
    <title>Agile Game Development: Tales From The Trenches</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0611/000112.html" />
    <modified>2006-11-13T05:54:05Z</modified>
    <issued>2006-11-12T21:54:05-08:00</issued>
    <id>tag:,2006:/2.112</id>
    <created>2006-11-13T05:54:05Z</created>
    <summary type="text/plain">Still curious about how to apply agile development to games? These presentations from Gamefest 2006 and the Montréal Games Summit 2006 give an overview of agile game development, and then get into some of the practices we use at High Moon Studios.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>Agile development</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      Still curious about how to apply agile development to games? These presentations from Gamefest 2006 and the Montréal Games Summit 2006 give an overview of agile game development, and then get into some of the practices we use at High Moon Studios.
      <![CDATA[<p>
Still curious about how to apply agile development to games? These presentations from Gamefest 2006 and the Montréal Games Summit 2006 give an overview of agile game development, and then get into some of the practices we use at High Moon Studios.
</p>
<ul>
<li><a href="http://convexhull.com/articles/gamefest2006_agile.pdf">Gamefest 2006 presentation</a>. This one is a gentle introduction to agile game development, covering both process and technical issues <a href="http://download.microsoft.com/download/8/5/2/852b36ac-97d5-4014-8865-06016041ee24/Developer%20Tools%20-%20XNA%20and%20Visual%20Studio.zip">(audio also available)</a>.
</li>
<li><a href="http://convexhull.com/articles/migs2006_agile.pdf">Montreal 2006 presentation</a>. This one deals only with technical agile game development topics, and gets into more detail about when and how to use them.
</li>
</ul>]]>
    </content>
  </entry>
  <entry>
    <title>Bringing Back The Dream</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0608/000111.html" />
    <modified>2006-08-17T04:56:32Z</modified>
    <issued>2006-08-16T21:56:32-08:00</issued>
    <id>tag:,2006:/2.111</id>
    <created>2006-08-17T04:56:32Z</created>
    <summary type="text/plain">A lot of people have a particular moment or experience that defined their future. It can be anything: reading a particular book, traveling through a different country,
meeting somebody special, or going through a very painful (or happy) experience. For me, the future crystallized on a Fall afternoon in 1985, when I sat in front of an 8-bit computer at a friend&apos;s house. It was the beginning of a long personal journey.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>General</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      A lot of people have a particular moment or experience that defined their future. It can be anything: reading a particular book, traveling through a different country,
meeting somebody special, or going through a very painful (or happy) experience. For me, the future crystallized on a Fall afternoon in 1985, when I sat in front of an 8-bit computer at a friend&apos;s house. It was the beginning of a long personal journey.
      <![CDATA[
<p>A lot of people have a particular
moment or experience that defined their future. It can be anything:
reading a particular book, traveling through a different country,
meeting somebody special, or going through a very painful (or
happy) experience. For me, the future crystallized on a Fall
afternoon in 1985, when I sat in front of an 8-bit computer at a
friend's house. It was the beginning of a long personal journey.
Without it, I wouldn't be developing games today, and I certainly
wouldn't be writing this article (which means you would probably be
reading <a href=
"http://www.randomwebsite.com/cgi-bin/random21.pl">this web
site</a> instead).</p>

<p>The computer was laughably primitive
by today's standards: <a href=
"http://en.wikipedia.org/wiki/Zilog_Z80">Z80</a> 4MHz CPU with 64KB
of RAM. What made <a href=
"http://en.wikipedia.org/wiki/Amstrad_CPC">it stand out from other
computers</a> at the time was a whopping 16 simultaneous colors (as
long as you gave up half your horizontal resolution), three-channel
square wave sound generation, and 3&rdquo; floppy disks. Cell
phones these days are hundreds of times more powerful than that
computer. Heck, the chip inside your microwave oven is probably
more powerful!</p>

<p>What was it that caused love at first
sight with that computer? Impressive as they were at the time, it
wasn't the technical specs that attracted me. It wasn't the
<a href="http://www.cpcgamereviews.com/">silly games</a> either,
even though <a href=
"http://tacgr.emuunlim.com/downloads/filedetail.php?recid=829">those
were fun for a few days</a>. It was being able to give commands to
the machine and have it execute them immediately.</p>

<p>The computer booted directly into a
Basic interpreter. I started experimenting with a few PRINT
statements, then moved to FOR loops, getting input and solving
algebra problems as if by magic. I spent endless hours typing game
listings that came in magazines (usually with a few printing
errors, which made them so much more fun to get working correctly).
I experimented with graphics, sounds, and animations.</p>

<p><img src="http://www.gamesfromwithin.com/images/50_dream/amstrad.jpg" align="right" 
width="298" height="224" alt="Amstrad CPC" />

Before I knew it, the Basic
interpreter was too slow and bloated and I had to graduate to
assembly. Programming became a bit slower (especially since for
some reason I could only save the assembly onto tapes, not disks),
but the programs became thousands of times faster. I was finally
able to draw sprites without annoying flickering, use all available
memory, and even overwrite part of the ROM jump table to squeeze in
a few extra KB.</p>

<p>I was hooked.</p>

<p>That experience totally changed the
rest of my life. It caused me to study computer engineering and
computer science, and eventually to write games professionally
(much to my parents' dismay).</p>

<p>If that little, primitive computer
had that effect on me, today's dazzling multimedia computers with
broadband Internet connection must have a hundred times that effect
on today's children, right? Quite the opposite.</p>

<p>Today's computers might be a lot more
powerful, but they're also a lot more complicated. Windows is very
large and intimidating to a newcomer. It doesn't exactly scream
&ldquo;play with me, experiment!&rdquo;. Instead, it is a very
closed system. It discourages experimentation, and you're in
constant fear of disturbing any of the overly complex
configurations (like the registry or system dlls), not to even
mention dealing with viruses and other malware. Linux is much more
transparent, but it's still far from an inviting system to play and
experiment with for newcomers to computers.</p>

<p>Another problem with modern computers
is the lack of a programming language out of the box. Things are
actually a bit better now than they were a few years ago. Microsoft
offers a free express edition of <a href=
"http://msdn.microsoft.com/vstudio/express/">Visual Studio</a>.
<a href="http://www.python.org/">Python</a> and <a href=
"http://www.ruby-lang.org/en/">other scripting languages</a> are
also free downloads, and they also <a href=
"http://www.pygame.org/">have libraries for game development</a>.
Unfortunately none of those tools come pre-installed, which makes
it hard to get started and even harder to share your results with
other people. Also, a lot of free development tools and
environments today are geared towards GUI programming, which is
very different from the free-form, take-control-of-the-machine
approach that you need not just for games, but to really learn
about the machine. There really aren't many better ways to
permanently scare people away from programming than showing them
<a href=
"http://msdn.microsoft.com/vstudio/previous/2003/posters/posterfiles/Namespaces_Selected_Classes_X0910395pst_a_OL.pdf">
something like this</a>.</p>

<p>Web development is a bit better
because it tends to be simpler, and once you have a web server set
up, it's easy to show the results to anybody with an Internet
connection (which I hope is everybody these days). Unfortunately
it's not particularly well suited for something like games with the
exception of things like <a href=
"http://www.adobe.com/products/flash/flashpro/">Flash</a>.</p>

<p>Although I'm sure that part of it is
nostalgia, I'm clearly not the only one who feels this way.
<a href="http://www.internetnews.com/ent-news/article.php/3520606">Computer
science enrollment has been dropping dramatically in recent
years</a> and there seems to be a lack of interest in learning more
about these machines that surround us, beyond how to use a browser
and how to share videos with friends.</p>

<p>Really, when I look at things this
way, I feel bad for kids growing up today. They're missing out on a
huge source of enjoyment that I had growing up as a kid. Of course,
today there are other new frontiers to explore, and they have the
Internet with all the new social aspects, but it's not the
same.</p>

<p>So, is the dream dead?</p>

<p>I have often wondered, isn't there a
platform out there that is more like the 8-bit computers were in
their day? The closest parallel today is game consoles, except that
they're very closed and proprietary and they're only intended to
play games. Sony started making some progress along these lines
with the <a href=
"http://en.wikipedia.org/wiki/Net_Yaroze">Yaroze</a> program for
PSX and <a href="http://playstation2-linux.com/">Linux for the
Playstation 2</a>. Unfortunately neither program was particularly
successful for a variety of reasons, but it was a start.</p>

<p><img src="http://www.gamesfromwithin.com/images/50_dream/xbox.jpg" align="left" 
width="178" height="194" alt="Xbox 360" />


A couple of days ago, in the keynote for GameFest, Microsoft announced that
they're taking things further on the Xbox 360 with <a href=
"http://www.microsoft.com/presspass/press/2006/aug06/08-13xnagamestudiopr.mspx">
Game Studio Express</a>. They're planning to open it up and allow
everybody to develop games for it. Even better, the code will be
mostly common between Windows and the Xbox 360, so it will be
possible to do a lot of development on the PC and then move it over
to the 360 relatively painlessly. How cool will it be for kids to
write their own games running on the Xbox 360 and be able to show
them off in their friends' living room?</p>

<p>It seems that the only language
available will be C#. At first I was disappointed as I was hoping
it would work with C++. Then I realized it wasn't such a bad idea.
If anything, it would be better if it were something simpler, more
like <a href="http://darkbasic.thegamecreators.com/">Dark
Basic</a>, that people with very little programming experience can
quickly start messing around with. Game Studio Express is supposed
to include several tools and APIs that allow you to program things
at a really high level, so that might be good enough.</p>

<p>I'm very curious about the details,
though. For instance, are we going to be able to get our hands
dirty and write as much C# as we want, or are we going to be
limited to a very strict framework? Is the link between the PC and
the 360 something that they're going to expose? In other words,
will we be able to create other tools that use that functionality
to create new types of content?</p>

<p>A really important question is
whether anybody will be able to play content created by users, or
will they have to have some special payment-based subscription.
Having to pay to develop for the 360 is not ideal, but I don't see
it as an unsurmountable barrier. However, if users have to pay and
be part of the developer program just to be able to play some
user-generated content, that would come close to killing its
usefulness. I hope that Microsoft learns some lessons from <a href=
"http://www.youtube.com/">YouTube</a> and <a href=
"http://video.google.com/">Google Video</a> and realize that the
lower the barriers for people to browse the content, the more
successful it is going to make the product. People have been able
to share videos for a long time already, but it involved
downloading them, getting a player that could decode them, and
playing them back. Now it's as simple as clicking on a link, and
that's why it has finally reached critical mass.</p>

<p>I'm definitely keeping a very close
eye on this project, and I'll try to give it a test drive as soon
as I get a chance. It's a bit ironic that with dozens of
multi-million AAA titles out there, the reason I might end up
buying an Xbox 360 is the chance to do play around with some
sprites on the screen and re-create a bit of the old 8-bit days.
The dream might indeed be back.</p>
]]>
    </content>
  </entry>
  <entry>
    <title>Fundamentally Agile</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0608/000110.html" />
    <modified>2006-08-08T04:40:24Z</modified>
    <issued>2006-08-07T21:40:24-08:00</issued>
    <id>tag:,2006:/2.110</id>
    <created>2006-08-08T04:40:24Z</created>
    <summary type="text/plain">In the past, I&apos;ve given presentations about agile game development to two distinct
groups of people: game developers without much exposure to agile development, and agile developers who were unfamiliar with game development. This morning I realized how interesting it was to explain the goals and reasons behind agile development to someone completely outside those circles.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>Agile development</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      In the past, I&apos;ve given presentations about agile game development to two distinct
groups of people: game developers without much exposure to agile development, and agile developers who were unfamiliar with game development. This morning I realized how interesting it was to explain the goals and reasons behind agile development to someone completely outside those circles.
      <![CDATA[
<!-- Fundamentally Agile -->

<p>Today I had lunch with an old friend. Even though he's not a
programmer, he's enough of a tech-head that our conversation
eventually turned towards agile development. In the past, I've
given presentations about agile game development to two distinct
groups of people: game developers without much exposure to agile
development, and agile developers who were unfamiliar with game
development. This morning I realized how interesting it was to
explain the goals and reasons behind agile development to someone
completely outside those circles. It forced me to go back to basics
and think about the fundamentals of a topic I've been so involved
in that I'd stopped thinking about in those terms..</p>
<p>What exactly is the key concept behind agile development? One possible
definition is &ldquo;a set of
techniques and procedures with minimal overhead that allow us to make sound, just-in-time
decisions.&rdquo; <a href="#ref1">[1]</a></p>
There are several important parts to that definition:</p>

<ul>
<li><b>Decisions</b>: It's not about the code, or the team, or the
tests. It's about decisions. The ultimate goal is to deliver a
useful product, but agile development helps us to make the
decisions along the way. What do we create next? How do we want
this thing to look? What features do we have to ship with?</li>

<li><b>Just-in-time</b>: Maybe the agile community has a better term
for this, but the concept strongly reminded me of the just-in-time
compiling strategy of Java interpreters. Basically, agile methods
will delay decisions until the last moment they have to be made.
Not only does this help avoiding design paralysis and having to
make too many decisions early on, but it also means that a lot of
decisions will never have to be made because things changed from
the original expectations.</li>

<li><b>Sound</b>: I originally left this one out, but I realized
that an 8-ball can make just-in-time decisions with the best. It's
making sound ones that is difficult. Whenever a decision needs to
be made, agile teams will draw on all the information they've
acquired up until then.. Not only will they know more about market
trends and competitors' products, but they'll also know about their
own team strengths, technology limitations, or the shortcomings of
past implementations. That's a lot more information that they would
have had available at the beginning of the project, during the
traditional waterfall planning phase.</li>

<li><b>Minimal overhead</b>: Agile processes are, by definition, very light.
The goal is to create a valuable product, not the process itself. Agile 
techniques introduce the minimal amount of overhead to achieve their purpose.</li>
</ul>

<p>My friend was very curious about this approach, since it's quite
different from the normal way of working he's used to in his
company. He had a very insightful question:
&ldquo;Don't you end up doing a lot of re-work?&rdquo;.
And the answer is, yes, absolutely. However,
it's not as wasteful as it sounds. It's actually quite an efficient
approach for a lot of projects.</p>

<p>Let's visualize the progress made in a project as a path on a 2D
surface. The amount of work is the length of the path. The progress
is how far from the starting point you've gone, and the direction
represents different approaches, designs, or implementations. An
ideal project would look like this:</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/49_agile/chart00.png" align="middle" 
width="180" height="174" alt="Ideal project" /></p>

<p>The project starts, knows exactly where it's going, and
progresses in a straight line. Euclid would agree: You can't be
more efficient than by taking the straight line between two
points.</p>

<p>This diagram can be used to represent any scale: from the whole
project spanning several years, to how a particular feature is
implemented in a couple of weeks, or how a class is implemented in
one morning. The same principles apply in all cases.</p>

<p>As a comparison, I suppose a <a href="http://en.wikipedia.org/wiki/Death_march_(software_development)">
death march project</a> would look more like this:</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/49_agile/chart01.png" align="middle" 
width="180" height="174" alt="Death march project" /></p>

<p>You are constantly doing work, but you aren't getting any closer
to your destination. The project eventually gets canned, or
development stops somewhere and it gets patched up the best it can
and shipped to unsuspecting customers.</p>

<p>You might hope that an agile project looks more like this:</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/49_agile/chart02.png" align="middle" 
width="180" height="174" alt="Possible agile" /></p>

<p>A project like that implies that some changes happened during
development, but while always making steady progress. That would be
nice, but in practice it often doesn't work that way. When you change
your plans or even some implementation, you often end up with some
amount of rework:</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/49_agile/chart03.png" align="middle" 
width="180" height="174" alt="Agile with rework" /></p>

<p>You can see all the rework by the zigzags going in and out
indicating varying levels of progress. I believe this rework is
inevitable (and maybe even desirable) in agile projects. It happens
at a low level, like changing interfaces to a class and having up
update all the hundred tests you wrote that relied on that
interface. But it also happens at a higher level, when you realize
that a game feature isn't as fun as you thought and you drop it in
favor of another one that could be more promising.</p>

<p>From the above diagrams, agile development really looks
inefficient. Clearly, we have traveled a much longer path to reach
our destination (work done). But agile development can actually do
better. How can we be more efficient than traveling in a straight
line without resorting to strange relativistic warped space?</p>

<p>The diagram doesn't tell the whole picture. Remember that agile
development relies on just-in-time decisions. That includes the
final goal: As we're working towards that goal, we might see other,
better or easier-to-reach ones. As a matter of fact, this is
something that happens most of the time. In that case, the picture
looks quite different:</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/49_agile/chart04.png" align="middle" 
width="180" height="174" alt="Real agile" /></p>

<p>Now the amount of work done is less than it was in the ideal
first case! And we might have a better solution to boot. Who says
you can't have your cake and eat it too?</p>

<p>With this in mind, are there some cases in which it is better
not to use agile development? Clearly. If you know things won't
change and you have a clear idea of how to reach your final goal,
then go for it. Agile development won't help much there. I have yet
to see a project that worked that way. Maybe a sports game that
ships year after year, or another simple port to a mobile platform.
But most projects I've seen have such a high level of chaos and
uncertainty due to all sorts of external factors that they could
all greatly benefit from an agile approach.</p>

<p>This can be visualized very well by mapping the characteristics
of a project in terms of requirements vs. technology. Projects that fit agile
development well fall anywhere in the complicated to anarchy zone (a fair
amount of technology uncertainty and requirements disagreement). On the
other hand, projects in the lower left corner, which are very well
understood and are very certain, would benefit the least from an
agile approach. <a href="#ref2">[2]</a></p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/49_agile/certainty.png" align="middle" 
width="300" height="260" alt="Uncertainty vs. agreement" /></p>

<p>I don't usually bash agile development because I truly believe
it's a great way to do development, especially for games. But how
would an agile development project gone bad look?</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/49_agile/chart05.png" align="middle" 
width="180" height="174" alt="Agile gone bad" /></p>

<p>Here there was a huge amount of rework without having any
significant impact in the project. The project ended up very near
the original goal (a bit further actually), but it spent most of
its time thrashing around. You could argue that maybe some of that
was exploring different solutions, but it's probably not a sign of
a good project anyway.</p>

<p>This brings up a good point: With agile development, it's
important to let go of the control-freak mindset. It's good to have
an idea of what your ultimate goal is, but it should never take
precedence over what you discover along the way.</p>

<p>I see this frequently in people who have just learned the
mechanics of test-driven development: they go through the cycle
correctly, writing a test, coding, and then refactoring. But
they're still implementing the design they had in their head when
they started instead of letting the tests dictate how the design
should look. Often they get quite frustrated because they can't
figure out how to test things. This also applies at a larger scale.
If a feature isn't giving you good results, maybe it should be
dropped or significantly changed.</p>

<p>This is one of the reasons I try to do my best not to talk about
things as concrete as classes or functions during early discussions
about some feature we will implement. I find that doing so tends to
solidify those concepts too much and I tend to be much more likely
to follow them instead of letting design evolve from what we
learned during its implementation. So now instead, I prefer to talk
about more abstract concepts like operations, modules, or data
flow.</p>

<p>Whether you're an agile developer or not, it's always important
to step back and question what you're doing and how you're doing
it. Think about it in the context of your projects and needs, and
re-evaluate it accordingly. Sometimes you'll be surprised what new
insights you achieve by stepping back and looking at the
fundamentals of something you're intimately familiar with. Just
make sure you don't bore your friends with too much technobabble.</p>

<hr/>


<ol>

<li><a name="ref1"></a>Scott Ambler has <a href="http://www.agilemodeling.com/essays/agileSoftwareDevelopment.htm">
a very good, much more detailed definition of agile development</a> that describes 
more the practices rather than the goals.</li>

<li><a name="ref2"></a>Diagram adapted from <a href="http://agilegamedevelopment.com/GDC2006/gdc2006_ClintonKeith_0323.ppt">Clinton Keith's Agile Game Development GDC 2006 presentation</a></li>

</ol>
]]>
    </content>
  </entry>
  <entry>
    <title>A Whirlwind Tour Through GDC 2006</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0604/000109.html" />
    <modified>2006-04-06T16:51:23Z</modified>
    <issued>2006-04-06T09:51:23-08:00</issued>
    <id>tag:,2006:/2.109</id>
    <created>2006-04-06T16:51:23Z</created>
    <summary type="text/plain">Spring was supposed to be the season of flowers, new leaves, and good weather returning. Here in San Diego we don&apos;t get much of that, or rather, we get it all year around. So Spring can really sneak up on you, and before you realize it, it&apos;s already gone. Spring also seems to be the season for game-development conferences
and travel.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>Conferences and events</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      <![CDATA[<img src="http://www.gamesfromwithin.com/images/48_gdc2006/gdc.png" width="129" height="32" align="right" alt="gdc"/>

Spring was supposed to be the season of flowers, new leaves, and good weather returning. Here in San Diego we don't get much of that, or rather, we get it all year around. So Spring can really sneak up on you, and before you realize it, it's already gone. Spring also seems to be the season for game-development conferences
and travel.]]>
      <![CDATA[<!-- A Whirlwind Tour Through GDC 2006 -->

<p>Spring was supposed to be the season of flowers, new leaves, and
good weather returning. Here in San Diego we don't get much of
that, or rather, we get it all year around. So Spring can really
sneak up on you, and before you realize it, it's already gone.
Spring also seems to be the season for game-development conferences
and travel: just a few weeks apart we get Sony's conference,
Microsoft's, and, of course, <a href="http://gdconf.com/">GDC</a>.
I'm not even going to count <a href=
"http://www.dicesummit.org/">Dice</a> and <a href=
"http://www.e3expo.com/">E3</a>, also happening around the same
time.</p>

<p>With all that going on, I realized I never got around to writing
my impressions about GDC. It really was a great conference with
some very good highlights. My travel is far from over, and I'm
heading out to the airport to catch my plane to London in a couple
of hours, but until then, here is my quick take on this year's
GDC.</p>

<p>This year I decided to come for the tutorials happening two days
before the main conference. The first day I bounced between
&ldquo;Advanced Visual Effects with OpenGL&rdquo; and
&ldquo;Software Engineering Issues in Multiplayer Games.&rdquo;</p>

<p>The OpenGL tutorial was exactly what you would expect: lots of
material from previous years and a few good bits of information.
The first thing I was happy to learn is that Microsoft changed
their decision on how OpenGL will be implemented in <a href=
"http://www.microsoft.com/Windowsvista/">Vista</a>. It will no
longer be a layer on top of DirectX; instead it will be a
first-class citizen in its own right. Now, I'm not an OpenGL fan.
Up until recently I never had to work much with it, and now that I
have, I admit that I like the Direct3D API much better (I'm just
not a fan of implicit global states). But I'm very glad to see that
OpenGL is going to be treated correctly in Vista and given the
opportunity to compete with Direct3D.</p>

<p>I was also pleasantly surprised by the tools NVidia is releasing
for OpenGL development. <a href=
"http://developer.nvidia.com/page/home.html">NVPerfKit</a> is a bit
like Pix for DirectX; combined with gDebugger, it starts making
OpenGL a lot more attractive. They're supposed to release version
2.0 soon, but I didn't find it on their web site. It's really
interesting how much NVidia is pushing OpenGL lately. At one point
it felt that it was over for OpenGL, but it really has been making
a comeback in the last couple of years. Now if they can only
improve Cg...</p>

<p>The tutorial "Software Engineering Issues in Multiplayer Games"
managed to surprise me, and I wish I had spent longer there than I
did. It really was focused on the software engineering aspects,
rather than on the multiplayer part of it. Lots of good information
and war stories of large-scale game development.</p>

<p>Tuesday I spent it exclusively in the Direct3D tutorial. The
biggest new thing was DirectX 10, with several talks focused on
that. Apart from the new cool tech features (such as the stream out
feature or the geometry shaders), DirectX 10 is quite a departure
from earlier versions of the API. A couple of things make me
scratch my head in puzzlement. DirectX 10 supposedly won't have any
caps to query anymore. Hardware is either DirectX 10 compliant or
it isn't. That's great news for developers. However, I also learned
that DirectX 10 is going to be tied to the Vista operating system,
and new versions of DirectX will only be released as part of new
versions of Windows. Unless I'm missing something, that means that
hardware won't have an opportunity to change and grow while running
on Vista. That would be horrible for hardware manufacturers, but at
least they have OpenGL to show their new features. Or maybe it
means that Microsoft is planning on doing a yearly operating system
release. It will be interesting to see how it plays out.</p>

<p>The best session on Tuesday was clearly Natalya Tatarchuk's
<a href=
"http://www.ati.com/developer/techpapers.html#gdc06">talk</a> on
the <a href="http://www.ati.com/developer/demos/rx1800.html">Toy
Shop demo</a>. She spent a full hour dissecting the demo, covering
every rendering trick and effect they used. Considering how
impressive and packed the demo is, it was clear that she could have
spent a full day talking about it. Some effects are awesome, like
their smeared rain reflections on the road, but it was funny to see
how they clearly spent quite a bit of time doing things that are
completely lost, like diffraction on the light that goes through
the droplets on the store window. In any case, if you haven't seen
the demo, <a href=
"http://www.ati.com/developer/demos/rx1800.html">download it right
now</a>.</p>

<p>Wednesday was the start of the main GDC sessions. To kick things
off, <a href="http://www.mungosmash.com/Author.php">Sean</a> and I
gave <a href=
"http://www.gamesfromwithin.com/articles/0603/000107.html">our talk
on test-driven development</a>. I was really surprised at how
packed the room was and how well received it was, judging by all
the questions and positive comments. It's great to see that other
people are also very interested in TDD and are thinking about
applying to it game development.</p>

<p>The next-generation animation panel was pretty interesting as an
overview of what could be coming down the pipe for animation. I was
already familiar with most of the content except for <a href=
"http://mrl.nyu.edu/~perlin/">Ken Perlin</a>'s new foot-placement
work, but it was a great overview anyway. I've been quite excited
about data-driven animation for a couple of years, and <a href=
"http://www.cs.wisc.edu/~kovar/">Lucas Kovar</a>'s work is very
promising. I think the only thing holding that technique back from
being applied to games is the memory requirements, but I would love
to spend some time trying to make it practical. <a href=
"http://www.cs.ucr.edu/~vbz/">Victor Zordan</a>'s work is also very
promising, combining dynamics with data from motion capture, which
would be great for games (using ragdolls to predict and blend into
falling animations for example).</p>

<p>Thursday was definitely the big day (for sessions, although
that's always the biggest day for parties too). The day started
with the excellent session on "Advanced Prototyping" by <a href=
"http://www.d6.com/users/checker/">Chris Hecker</a> and <a href=
"http://www.slackworks.com/~cog/">Chaim Gingold</a>. I really can't
say enough good things about it: it was packed with interesting,
non-obvious information, it was very well presented and full of
energy (it's Chris we're talking about, so of course it is!), and
extremely motivational. They did a top-notch job preparing for the
presentation and it showed. The pair had a very interesting
presentation style that felt almost like a conversation between
them two, and it worked very well. It was hands-down the best
session of GDC for me. The talk covered things like why you want to
prototype, what constitutes a good prototype, how you go about
prototyping things, what to prototype and what to leave out, how to
put the results together, etc, etc.</p>

<p>I don't really understand why it was classified under the game
design track. It really was more of a programming, production, or
just all-around session. Even so, apparently the session was full
and they had to turn people away. I really hope that they recorded
it on video and they make it available online.</p>

<p>At one point they described what they considered to be a good
codebase for prototyping. The funny thing is, I completely agree
with every point they brought up, but for me those are
characteristics I want in <b>any</b> codebase, not just one for
prototyping. They are all things I value very much: ability to
change, flexible, code vs. content, use of scripting, etc. In
particular, the comment of frameworks vs. toolsets really hit the
mark. That's something I've been pitching for a while, but I really
consider frameworks to be fundamentally broken for the type of
development I want to do. Instead, I want a set of tools
(functions, classes, whatever) that I can put together in any way I
want instead of being constrained to one predefined structure (even
if it has hundreds of callbacks, like MFC).</p>

<p>I think I was the only person in the packed Civic Auditorium
left cold by the Nintendo keynote. Yes, it's great to have <a href=
"http://en.wikipedia.org/wiki/Satoru_Iwata">Satoru Iwata</a> give a
GDC keynote, but I really didn't connect with his speaking style or
his message. I found it content-free and not very engaging (it
didn't help any that I was stuck in a corner of the top
balcony&mdash;apparently there was a screen in the middle of the
stage that I was not able to see that explained a lot of his
strange comments).</p>

<p>On the other hand, <a href=
"http://en.wikipedia.org/wiki/Will_Wright">Will Wright</a>'s
keynote was just the bomb. Somehow every year he manages to deliver
amazing talk after amazing talk. I knew I really wanted to hear his
session, so I chose to stay in the auditorium instead of going out
again to get a <a href=
"http://www.nintendo.com/gamemini?gameid=tYVqJgro-KG6QL_mMbXFoQTkQIzgi9nU">
free DS game</a> and have to wait through that whole line. Good
choice! I was able to get the best seat in the house this time
around.</p>

<p>Will's keynote cannot really be described in one paragraph.
People have asked me what it was about, and I'm left without words.
The point is not what it was about, it was the whole experience!
It's like being 12 years old again and going to a summer
blockbuster that hits you from the beginning and doesn't let you go
for the next two hours. I left the auditorium dazzled and
super-motivated. Isn't that enough?</p>

<p>On the surface, the talk was about how he goes about researching
new projects, interleaved with what he learned about astrobiology
for the development of <a href="http://www.spore.com/">Spore</a>.
You can try getting more of an idea what it was about <a href=
"http://www.gamedev.net/columns/events/gdc2006/article.asp?id=485">here</a>
and <a href=
"http://www.kotaku.com/gaming/will-wright/gdc-06-liveblogging-will-wright-162561.php">
here</a> (and a <a href=
"http://www.kotaku.com/gaming/keynote/index.php">short video
here</a>). That's another talk I hope GDC puts online very
soon.</p>

<p>I have to admit, that after Will's keynote, the rest of GDC was
fairly anticlimactic. Maybe next time they should leave it for the
last day to build up the grand finale. The only session that I
attended that really stands out was Tim Moss' <i>God of War</i>
talk. I was expecting something a bit different, but it turned out
to be a mini-postmortem of <i>God of War</i>. In particular, he
talked about how they were organized, what their priorities were,
and how they went about solving problems. I found it very
interesting on many different levels, but the most interesting part
was that they do things very differently to how I would go about
doing them (or how we're doing them at work right now). They also
have a very different set of constraints: they have a very small
number of very senior programmers, so they do anything they can to
minimize using their time. They end up developing very general
solutions, while right now I would advocate for the very specific
solutions. It's clear that their approach worked very well for
them, so it's great to see how different teams can tackle different
problems in a variety of ways.</p>

<p><br /></p>

<p>One pattern I noticed in this year's GDC is that, for technical
talks, the more general the talk, the more I enjoyed it. As soon as
they got bogged down in details, they became much less effective. A
lot of it has to do with the dry nature of the topics, and the fact
that I can get all those details from a well-written paper. On the
other hand, the more general talks (advanced prototyping, Will's
keynote, or the <i>God of War</i> one) were all very motivational
and inspirational. In the end of the day, that's what GDC is about
for me: inspiration and socializing. And this year's GDC was a huge
success by that measure.</p>
]]>
    </content>
  </entry>
  <entry>
    <title>UnitTest++ v1.0 Released</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0603/000108.html" />
    <modified>2006-03-19T03:48:16Z</modified>
    <issued>2006-03-18T19:48:16-08:00</issued>
    <id>tag:,2006:/2.108</id>
    <created>2006-03-19T03:48:16Z</created>
    <summary type="text/plain">We grabbed the best features of each framework and created what we think it&apos;s the best C++ unit-testing framework out there (for our needs anyway). We took the results and put them up in Sourceforge under a veryunrestrictive license, and that&apos;s how UnitTest++ was born.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>Test-Driven Development</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      <![CDATA[<img src="http://www.gamesfromwithin.com/images/icons/tdd_icon.png" width="77" height="77" align="right" alt="tdd"/>

We grabbed the best features of each framework and created what we think it's the best C++ unit-testing framework out there (for our needs anyway). We took the results and put them up in Sourceforge under a veryunrestrictive license, and that's how UnitTest++ was born.]]>
      <![CDATA[
<!-- UnitTest++ v1.0 is out -->

<p>I had been using a modified version of CppUnitLite for quite a
while, slowly fixing the parts in need of mending, and adding new
functionality as it became needed. Eventually I
released most of those changes as CppUnitLite2, and I thought that
would be the end of that. It turns out that was just the
beginning.</p>

<p>Shortly after that, several people started emailing me with new
functionality, fixes, patches, suggestions, etc. At the same time,
<a href="http://cnicholson.net/">Charles Nicholson</a> was starting to get quite a bit of response as
well for his own testing framework, sometimes with similar fixes
and suggestions.</p>

<p>If this was going to grow to be a real project, developing over
time, supporting users' needs, and accepting code contributions,
clearly it would make sense to join forces. And that's exactly what
we did. We grabbed the best features of each framework and created
what we think it's the best C++ unit-testing framework out there
(for our needs anyway).</p>

<p>We took the results and put them up in <a href=
"http://sourceforge.net/projects/unittest-cpp/">Sourceforge</a>
under a <a href="http://en.wikipedia.org/wiki/MIT_License">very
unrestrictive license</a>, and that's how <a href=
"http://unittest-cpp.sourceforge.net/">UnitTest++</a> was born.</p>

<p>Our ultimate goal is to apply test-driven development to game
development. All of the existing frameworks fell short in one area
or another. Specifically, the driving forces behind the design of
UnitTest++ are:</p>

<ul>
<li>Portability. As game developers, we need to write tests for a
variety of platforms, most of which are not supported by normal
software packages (all the game consoles). So the ability to easily
port the framework to a new platform was very important.</li>

<li>Simplicity. The simpler the framework, the easier it is to add
new features or adapt it to meet new needs, especially in very
limited platforms.</li>

<li>Development speed. Writing and running tests should be as fast
and straightforward as possible. We're going to be running many
tests hundreds of times per day, so running the tests should be
fast and the results well integrated with the workflow.</li>
</ul>

<p>UnitTest++ is a fully featured testing framework, with many of
the features you may expect from Xunit-style frameworks such as
fixtures and reporting. Additionally, here are some of the specific
features that make UnitTest++ unique:</p>

<ul>
<li>Minimal work required to create a new test. For TDD development,
we write lots and lots of tests, so creating a new test should be
as quick and painless as possible. UnitTest++ does not require
explicit test registrations, and creating new tests requires
minimal work.</li>

<li>Good assert and crash handling. When automated tests are
executed, it's very important not to hang the process or abort the
tests any time the program crashes or an assert fails. UnitTest++
will catch and report exceptions as failed tests and print a lot of
information about them. It will translate signals to exceptions as
well as be able to catch invalid memory accesses and other
problems.</li>

<li>Minimal footprint and minimal reliance on heavy libraries. When
you intend to run tests on a <a href="http://www.research.ibm.com/cell/SPU.html">Cell SPU</a> with a
measly 256 KB of RAM, you really want to be as lean and mean as
possible. UnitTest++ is very lightweight, and it will get even
lighter weight once strstream is replaced.</li>

<li>No dynamic memory allocations done by the framework, which makes
it much easier to track memory leaks and generally more attractive
for embedded systems.</li>

<li>Multiplatform support. Right now it supports Win32, Linux, and
Mac OS X out of the &ldquo;box,&rdquo; and other platforms will
probably work without any changes. The source code makes use of
platform-specific functions whenever necessary, so it is easy to
hook up special timers, allocators, or reporters for specific
platforms. The code comes with a makefile as well as with project
and solution files for Visual Studio 2003 and 2005.</li>

<li>Full set of unit tests for itself. UnitTest++ was TDD'd from the
ground up, including some of the ugly macros (imagine how much fun
it was bending the framework to test itself that way!). It goes
without saying, all the tests are included with the source code, so
you can go totally wild with them :-)</li>
</ul>

<p>This was just the first release. UnitTest++ is ready for full
production work, but we already have plans beyond this release.
This is a peek at some of the features we have in mind for upcoming
versions:</p>

<ul><li>Out-of-the-box support for game console platforms (Xbox 360, PS3
PPU and SPU, and Nintendo Revolution). Of course, this is dependent
on us getting permission from the console manufacturers to release
some code that works with their SDK.</li>

<li>Ability to trade some features (such as rich check reporting)
for some extra memory. In some platforms, like Cell SPUs, you
really need to go barebones.</li>

<li>Suites to group tests together.</li>

<li>Different reporters (HTML, GUIs, etc). Don't worry, all those
modules will be optional and well separated, so they won't affect
the simplicity of the framework.</li>

<li>Per-test timings. Maybe the ability to flag some tests as not
exceeding a certain amount of time, or just failing any test that
goes over a threshold.</li>

<li>Built-in memory leak detection.</li>
</ul>

<p>So that's it. <a href="http://sourceforge.net/project/showfiles.php?group_id=158151">Download the source code</a>
and give it a try. We welcome any comments and suggestions (best
channels would be through the <a href="https://lists.sourceforge.net/lists/listinfo/unittest-cpp-devel">project
mailing list</a> or comments here). We hope you find it useful and
that it makes your TDDing even more productive.</p>
]]>
    </content>
  </entry>
  <entry>
    <title>Backwards Is Forward: Making Better Games with Test-Driven Development</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0603/000107.html" />
    <modified>2006-03-13T04:55:57Z</modified>
    <issued>2006-03-12T20:55:57-08:00</issued>
    <id>tag:,2006:/2.107</id>
    <created>2006-03-13T04:55:57Z</created>
    <summary type="text/plain">We have all experienced how development slows down to a crawl towards the end of a project. We have seen first-hand the difficulty of squashing insidious many-headed bugs. We have wrestled with somebody else&apos;s code, just to give up or fully re-write it in despair. We have sat in frustration, unable to do any work for several hours while the game build is broken. Code can get too complex for its own good.

See how doing something so apparently backwards as writing unit tests before any code can help with all those problems.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>Test-Driven Development</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      <![CDATA[<img src="http://www.gamesfromwithin.com/images/icons/tdd_icon.png" width="77" height="77" align="right" alt="tdd"/>

<p>We have all experienced how development slows down to a crawl towards the end of a project. We have seen first-hand the difficulty of squashing insidious many-headed bugs. We have wrestled with somebody else's code, just to give up or fully re-write it in despair. We have sat in frustration, unable to do any work for several hours while the game build is broken. Code can get too complex for its own good.</p>

See how doing something so apparently backwards as writing unit tests before any code can help with all those problems.]]>
      <![CDATA[<!--Backwards Is Forward: Making Better Games with Test-Driven Development-->

<p>This paper will be presented at the 2006 Game Developers Conference</p>
<p>Noel Llopis and Sean Houghton<br/>
High Moon Studios
</p>

<p>
<a href="http://www.convexhull.com/articles/tdd_gdc06.pdf">Printer-friendly format</a>.<br/>
<a href="http://www.convexhull.com/articles/tdd_gdc06_slides.pdf">Presentation slides</a>.<br/>
<a href="http://www.convexhull.com/articles/tdd_example.zip">Sample code from presentation</a>.<br/>
</p>

<p><br/></p>

<div class="quote"><p>The programmer, like the poet, works only
slightly removed from pure thought-stuff. He builds his castles in
the air, from air, creating by exertion of the imagination. Few
media of creation are so flexible, so easy to polish and rework, so
readily capable of realizing grand conceptual structures.<br />
Frederick P. Brooks, Jr.</p></div>

<h3>1. Introduction</h3>

<p>Part of the appeal of programming is that, as
Brooks describes, it allows us to build ornate castles in the air,
where our imagination is the only limit. As our target platforms
increase in power and memory, our castles become larger and more
intricate.</p>

<p>However, it's the same facility to weave code
out of thin air that can become our greatest danger. Code has a
tendency to grow beyond initial expectations, quickly surpassing
our capacity to fully understand it. Our castles in the air can
quickly become snowballs that are too large to be moved and shaped
to fit our needs.</p>

<p>We have all experienced how development slows
down to a crawl towards the end of a project. We have seen
first-hand the difficulty of squashing insidious many-headed bugs.
We have wrestled with somebody else's code, just to give up or
fully re-write it in despair. We have sat in frustration, unable to
do any work for several hours while the game build is broken. We
have seen countless hours of work go up in smoke as code is thrown
away and started from scratch for the next project.</p>

<p>Code can get too complex for its own good.
Milestone pressures, a fluctuating game industry, growing teams and
budgets, and the breakneck pace of hardware change don't help an
already difficult situation.</p>

<p>This is where test-driven development comes
in.</p>

<h3>2. What is test-driven development?</h3>

<p>Let's start by looking at the traditional
programming process. Once you decide to implement a specific piece
of functionality, you break the problem down mentally into smaller
problems, and you start implementing each of them. You write code,
and you compile it to know whether things are going well. After a
while, you might have written enough code that you can run the game
and try to see if the feature works. Maybe you run through a level,
checking that feature and making sure nothing else looks obviously
broken, or maybe you even step in the debugger to make sure your
code is getting called and doing what it's supposed do. Once you're
happy with it, you check it into source control and move on to
another task.</p>

<p>Test-driven development (TDD) turns the
programming process around: As before, you break down a problem
mentally into smaller problems (or at least a single smaller
problem), but now you write a unit test for that small feature, see
it fail (since you still haven't implemented anything), and then
write the code to make that test pass. Then you repeat the process
with another, very small piece of functionality that will get you
closer to the full feature you're trying to implement. The cycles
are very short, perhaps only a minute or two.</p>

<p>Let's have a more detailed look at the TDD
cycle:</p>
<ul><li>Write a single unit test for a very small piece of functionality.</li>
<li>Run it and see it fail (in C++, it's likely that it won't even compile).</li>
<li>Write the simplest amount of code that will make the test compile and pass.</li>
<li>Refactor the code and/or tests. Run tests and see them pass.</li>
</ul>

<p>A <i>unit test</i> is a test that verifies a
single, small behavior of the system (also called a developer
test). Specifically, in this context, each unit test deals with
something almost trivially small, which can probably be done in
less than a minute. For example, it can test that a health pack
doesn't add more health past the player's maximum, or it can test
that a particular effect disables depth writes. We'll see an
example of a simple test in the next section.</p>

<p>How does TDD help us deal with the complexity of
software, and, more specifically, how does it solve some of the
problems listed in the introduction? These are the benefits, listed
roughly in our order of importance:</p>

<p><b>Better code design</b></p>

<p>What is the first thing you do when writing some
code with TDD? You are forced to use that code in a test. That
simple fact makes it so all code is created with the user of the
code in mind, not the implementation details. The resulting code is
much easier to work with as a result, and it directly solves the
problems it was intended to fix. Also, because the code was first
created by testing it in isolation from the rest of the code, you
will end up with a much more modular, simpler design.</p>

<p><b>Safety net</b></p>

<p>With TDD, just about every bit of code has some
associated tests with it. That means you can be merciless about
refactoring your code, and you can still be confident that it will
work if all the tests continue to run. Even though we find
refactoring to be an extremely important part of the development
process, the safety net goes way beyond refactoring. You can
confidently apply obscure performance optimizations to squeeze that
last bit of performance out of the hardware and know that nothing
is broken. Similarly, changing functionality or adding new feature
towards the end of the development cycle suddenly becomes a lot
less risky and scary.</p>

<p><b>Instant feedback</b></p>

<p>The unit tests provide you with instant feedback
up to several times per minute. If at any point you thought tests
should be passing and they aren't, you know something has gone
wrong: not an hour ago, not ten minutes ago, but sometime in the
last minute. In the worst case, you can just revert your changes
and start over. This is quite subjective, but the constant feedback
has a surprising morale-boosting effect. No problem seems too large
as long as you're taking small steps in its direction and getting
feedback that you're in the correct track. For some of us, TDD has
rekindled the same joy of programming that we discovered in the
8-bit computers we cut our teeth on.</p>

<p><b>Documentation</b></p>

<p>What's worse than uncommented code? Code with
outdated comments. We all know how easy it is for comments to get
out of date, yet there is very little we can do about it. The unit
tests created through TDD serve as a very effective form of
documentation. You can browse through them to see what kind of use
a class is intended to have, you can look up a particular test to
see what kind of assumptions a function makes about its parameters,
or you can even comment out some code that makes no sense and see
what tests break to give an idea of what it does. The best thing
about unit tests as documentation: they can never get out of date.
We have found that in codebases that are developed with TDD,
comments have almost disappeared, being used only to explain why
something was done in a particular way, or to document what paper
an algorithm we implemented came from.</p>

<p>One thing that should be clear and is important
to stress is that TDD is not just writing unit tests. TDD is a
development methodology, not a testing one. That's why TDD's
benefits deal with better code design and structure, ease of
refactoring, etc, and not with correctness. TDD ensures that your
code does whatever you wanted it to do, not that it does it
correctly.</p>

<h3>3. Implementing TDD</h3>

<p>Let's put TDD in practice by following the
normal practice and writing our first test. Let's assume we already
have a game up and running, and our task is to implement health
powerups. The very first thing we want to implement is that if the
player walks over a health powerup, he receives some amount of
health. That's actually even more complicated than what we want for
our small testing steps, so let's start with an even simpler test
that requires the least amount of effort: if we have a player and a
powerup, and the player isn't anywhere near the powerup, his amount
of health doesn't change. Simple, right?</p>

<p>Ideally, how would we like to test that?
Probably by writing some code like this:</p>

<pre class="code">
	World world;
	const initialHealth = 60;
	Player player(initialHealth);
	world.Add(&amp;player, Transform(AxisY, 0, Vector3(10,0,10)));
	HealthPowerup powerup;
	world.Add(&amp;powerup, Transform(AxisY, 0, Vector3(-10,0,20)));
	world.Update(0.1f);
	CHECK_EQUAL(initialHealth, player.GetHealth());
</pre>

<p>And that's exactly what the test will look like,
only we'll have to surround it with a macro to take care of all the
bookkeeping and to give it a descriptive name. Our full test looks
like this:</p>


<pre class="code">
TEST (PlayersHealthDoesNotIncreaseWhileFarFromHealthPowerup)
{
	World world;
	const initialHealth = 60;
	Player player(initialHealth);
	world.Add(&amp;player, Transform(AxisY, 0, Vector3(10,0,10)));
	HealthPowerup powerup;
	world.Add(&amp;powerup, Transform(AxisY, 0, Vector3(-10,0,20)));
	world.Update(0.1f);
	CHECK_EQUAL(initialHealth, player.GetHealth());
}
</pre>

<p>The macros <code>TEST</code> and
<code>CHECK_EQUAL</code> are part of a unit testing
framework. The framework is intended to make the task for writing
and running unit tests as simple as possible. As you can see, it
can't get much easier than that. There are a variety of
freely-available unit-test frameworks for C++ and other languages.
We recommend UnitTest++, which is a lightweight C++ unit-test
framework that supports multiple platforms, is easy to adapt and
port, and was created after using TDD in games for several
years.</p>

<p>Now we compile this code and we get the
following output:</p>

<pre class="code">
Running unit tests...
1 tests run
There were no test failures.
Test time: 0 seconds.
</pre>

<p>The <code>CHECK_EQUAL</code>
macro is the part that performs the actual check, and it takes as
parameters the expected value and the actual value. If they are
different, it will mark the test as failed, and output a message
with as much information as possible. As a bonus, UnitTest++
formats the failed test message so it can be parsed by Visual
Studio and it is easy to navigate to the location of the test.</p>

<p>The reason we have macros like <code>CHECK_EQUAL</code> is that unit tests need to be fully
automated. There should be no need for visual inspection or reading
some text. The test program should know whether any tests failed or
not without any ambiguity, that way it can be easily integrated
into the build process.</p>

<h3>4. How to test</h3>

<p>When writing unit tests, there are three main
ways of testing your code:</p>

<p><b>Return value</b></p>
<p>Make a function
call, and check the return value. This is the most direct way of
testing, and it works great for functions that do computations and
return the computed value. Because this is the easiest and most
straightforward way of testing, we should use this approach
whenever possible.</p>

<p>For example, a
function called <code>GetNearestEnemy()</code>
would be a perfect candidate to be tested this way. We can easily
set up a world with a couple of enemies, call that function, and
verify that it returns the enemy entity we expected.</p>

<p>Beware of testing
functions that return boolean results indicating if the function
failed or succeeded. You really want to test that the function does
things correctly, not just that it reports it did them.</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/46_tdd_gdc/test1.jpg" align="middle" 
width="350" height="142" alt="Return value" /></p>

<p><b>Object state</b></p>
<p>Make a function
call, then check that the state of the object or some part of the
system has changed correctly. This tests that state changes
directly, so it's also a very straightforward form of testing.</p>

<p>For example, we
could send an event of nearby noise to an AI in &ldquo;idle&rdquo;
state and check that its state changes to &ldquo;alert&rdquo; in
response.</p>

<p>Sometimes it might
force you to expose some state that would otherwise be private, but
if it's something that you need to test from the user point of
view, then making it public is probably not a bad idea anyway. It
might lead to larger interfaces than absolutely necessary, but it
also sometimes shows that a class really should be split into two,
and one of the classes should contain the other one.</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/46_tdd_gdc/test2.jpg" align="middle" 
width="350" height="139" alt="Return value" /></p>

<p><b>Object interaction</b></p>

<p>This is the
trickiest aspect to test. Here we make a function call, and we want
to test that the object under test did a sequence of actions with
other objects. We don't really care about state, just that a
certain number of function calls happened. The most common testing
pattern for this situation is a <i>mock object</i>. A mock object
is an object that implements the interface of another object, but
its only purpose is to help with the test. For example, a mock
object could record what functions were called and what values were
passed, or could be set up to return a set of fixed values when one
of its functions is called.</p>

<p>Because this is the
most complex form of testing, we recommend using it only when the
other two forms of testing are not possible. Using mock objects
frequently could be an indication that the code relies too much on
heavy objects with complex interactions instead of many,
loosely-coupled, simpler objects.</p>

<p>A good situation for
using a mock object could be testing HUD rendering. We want to
verify that the HUD elements are rendered in a specific order, so
we create a mock for the rendering canvas which will keep an
ordered list of the elements that get passed to it. We pass the
mocked rendering canvas to the HUD renderer and make the render
call. Then we can examine that the list in our mocked canvas
matches our expectations.</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/46_tdd_gdc/test3.jpg" align="middle" 
width="350" height="151" alt="Return value" /></p>

<h3>5. Best practices</h3>

<p>This is a set of best practices we have found
to be particularly important for all of our development with
TDD.</p>

<p><b>Run tests frequently</b></p>

<p>Being able to write tests easily is a
requirement for successfully rolling out TDD. Nobody wants to spend
extra time writing unit tests when they can be implementing the
features that are due for this milestone. But even more
importantly, tests should run very frequently, and a failed test
should be treated the same way as a failed build.</p>

<p>At High Moon, every library has a separate test
project that creates an executable that links with the library and
runs all the tests. We have hooked up running the executable itself
as the post-build step in Visual Studio (or as the last command in
a make file). That means that making any changes to the library or
tests and triggering a compile will also run all the tests.
Additionally, since the test executable returns a value with the
number of failed tests, a failing test will return a non-zero
value, which is interpreted by the build chain as a failed build.
This makes it so everybody is running unit tests for all code all
the time, which greatly improves the build stability.</p>

<p>In addition to running tests locally, the build
server also runs all the unit tests at the same time it does code
builds. In our case, since the tests are a postbuild step, there
was nothing special we had to do in the build server, and a failed
test would be reported just as code that didn't compile
correctly.</p>

<p><b>Test only code under test</b></p>

<p>This is a key practice for writing good unit
tests. The most important reason to minimize the amount of code
involved in a test is to keep things simple. Ideally, when
something breaks, you want only a small number of tests failing so
you can quickly pinpoint the problem. If some tests involve a large
amount of the codebase, they will constantly break for unrelated
reasons.</p>

<p>Also, if you are able to use the code under test
with a minimal amount of other code or libraries, it means you are
creating very modular, self-contained code, which will help with
the overall design. Finally, another very good reason to avoid
involving extra code is that tests that only work on a small set of
code are typically much faster than tests that involve large
systems and complex initialization/shutdown sequences.</p>

<p>Continuing with the health powerup example,
notice that the test involved a <code>World</code>
object, a <code>Player</code> object, and a
<code>HealthPowerup</code> object. There was no
graphics system initialization, databases, etc. The <code>World</code> 
object can be a very lightweight container
for game entities without any other dependencies. Try setting
something like that in your current engine and you might be
surprised by how many implicit dependencies you find in different
parts of the engine.</p>

<p>A test that involves a lot of code across many
different systems is usually referred to as a <i>functional
test</i>(also called a <i>customer test</i>).
Functional tests are extremely useful, especially if they are fully
automated, but they fill a very different role than unit tests.</p>

<p><b>Keep tests simple</b></p>

<p>This is related to the previous best practice.
You want a test to check one thing and only one thing; that way,
when something breaks, it's immediately clear what went wrong.</p>

<p>A good start is to label each test clearly with
a name that describes exactly what the test is supposed to do. For
example, a test named <code>PlayerHealth</code> is
not very helpful. A much better name would be 
<code>PlayerHealthGoesUpWhenRunningOverHealthPowerup</code>.</p>
<p>Keeping each unit test to just a handful of
lines makes it much easier to understand at a glance. In our case,
it is unusual to have unit tests that are more than 15 lines long.
Needing to write overly long unit tests is usually a sign that the
test is involving too much code and could probably be re-written in
a better way.</p>

<p>We also found that limiting each unit test to a
single check statement or two resulted in tests that were the
easiest to understand. Sometimes that means you'll have to write
some duplicate setup code between two tests, but it's a small price
to pay to keep the tests as simple as possible.</p>

<p>Whenever you have some common code in two or
more tests, you can use a fixture. A fixture is a set of common
code that is executed before and after each test that uses that
fixture. Using fixtures can cut down tremendously on the amount of
test code you have to write. Any decent unit test framework should
support fixtures, so use them whenever they're needed.</p>

<p><b>Keep tests independent</b></p>

<p>Unit tests should be completely independent of
each other. Creating an object in a test and reusing it in a
different test is asking for trouble for the same reasons as we
discussed earlier: when a test fails, you want to be able to zero
in on the failing test and the problem that is causing it to fail.
Having tests depend on each other will cause chains of failing
tests, making it difficult to track the problem down to the
source.</p>

<p><b>Keep tests very fast</b></p>

<p>The unit tests we write are compiled and
executed as a postbuild step. We have hundreds or thousands of
tests per library, so that means they have to run blazingly fast or
they'll get in the way. If unit tests are only dealing with the
minimum amount of code, they should be able to run really fast.
That means they shouldn't be talking to the hardware, they
shouldn't be initializing and shutting down expensive systems, and
they most definitely should not be doing any file I/O.</p>

<p>All our unit tests are timed (another feature of
UnitTest++), and the overall time for the test run is printed after
it runs. As a general rule, whenever a set of unit tests goes over
two seconds, it means something is wrong and we try to fix it (even
if a unit test takes a full ms, which is a huge amount for a unit
test, you can still run 1000 of them in a single second).</p>

<h3>6. TDD and game development</h3>

<p>Applying TDD to game development has its own
unique challenges that are not usually discussed in the TDD
literature.</p>

<p><b>Different platforms</b></p>

<p>Most game developers today need to develop for a
variety of platforms: PCs (Windows, Macs, or Linux), game consoles,
handhelds, etc. Even though at High Moon we develop console games,
we use Windows as our primary development environment because of
the good development tools and the fast iteration time. That means
we always have a version of our engine and tools that runs under
Windows, which makes running unit tests very easy and
convenient.</p>

<p>We also wanted to run the unit tests in each
platform we develop for, but we had to make a few changes to
compensate for the shortcomings of those platforms. The minimum
support that we needed was the ability to run an executable through
the command line and capture the output and, ideally, the return
code. Surprisingly, none of the game console environments we
develop for supports that simple operation, so we were forced to
write a small set of programs using the system API to do exactly
that.</p>

<p>After we wrote those small utility programs, we
were able to run unit tests on the consoles just like we did under
Windows. The main difference was that running any program on the
consoles had a noticeable startup time delay. It's a matter of just
a few seconds, but it was too long to run the unit tests
automatically as a postbuild step after every compilation. Besides,
we don't yet have one dev kit for every developer station, so we
couldn't count on always having a target platform available.
Because of that, our unit tests on platforms other than Windows are
only executed manually, and by the build server. It is not ideal,
but the large majority of the problems show up in the Windows
tests, so as long as those continue being run all the time, we
catch most problems on time.</p>

<p><b>Graphics, middleware, and other APIs</b></p>

<p>Probably the biggest barrier that people see to
doing unit testing and TDD with games is how to deal with graphics.
It's certainly not the textbook-perfect example you'll read about
in TDD books, but it's certainly possible.</p>

<p>The first thing to realize is that graphics are
just part of a game. It is common sense and a good software
engineering practice to keep all the graphics-related code in one
library or module, and make the rest of the game independent of the
platform graphics API and hardware. Once we had that organization,
we were able to test any part of the game or engine without having
to worry about graphics.</p>

<p>Ideally, we wanted to develop the graphics
renderer library with TDD as well, and there's no way to avoid
dealing with platform-specific graphics calls. We tried three
different approaches, from most involved to least involved:</p>
<ul>
<li><b>Catch all graphics function calls</b>. We
inserted a layer between the graphics renderer and the graphics API
that exactly mimicked the platform API. That way we could make any
graphics API calls that we needed without having to worry about the
underlying hardware. As a bonus, that layer could report which
functions were called and with what parameters. This approach made
for extremely thorough tests. The testing layer could be removed in
the final build and the functions would call directly into the
graphics API so there would be no performance penalties. However,
it was quite labor-intensive, especially for the Direct3D API
because it uses classes and not just plain functions like
OpenGL.</li>

<li><b>Check for state</b>. Another approach is to actually work on the
graphics hardware and check that things are working correctly by
querying the graphics API state. For example, rendering a certain
mesh should set a specific vertex declaration. This approach is
much simpler, but there were some things we couldn't test. For
example, we could render a mesh, but we wouldn't be able to find
out how many triangles were sent to the hardware. Also, since
OpenGL is so state-based, it was important for most functions to
clean up after themselves, so it was often very hard to check for
any state. On platforms in which the internals of the graphics API
are more open, you might be able to examine more states by looking
at the graphics command buffer.</li>

<li><b>Isolate graphics calls</b>. 
When all else fails, this is a useful technique for
dealing with calls into external APIs. Isolate an API function call
or a group of API function calls into a single function, and test
that your function is called at the right time. The function that
calls into the graphics API itself won't be tested, but all it does
it make some straight calls. Remember, what we really want to test
is that our code behaves correctly, not that the graphics API works
as documented.</li>

</ul>

<p>We started with the first approach, wrapping the
API as we were using it, but the amount of extra work we had to
do to wrap complex APIs like Direct3D and OpenGL quickly became
overwhelming. Maybe if we were working on a commercial graphics
rendering middleware it would be worth the effort. For us, after
doing that for a few weeks, we realized that the benefits we were
deriving from it weren't worth the time we were spending. It was
also discouraging us from using new API functions just because they
hadn't been wrapped before.</p>

<p>In the end, we ended up settling for a
combination for the second and third approaches: testing the state
whenever possible, and isolating the calls the rest of the time.
One of the drawbacks of this approach is that we're working
directly with the hardware, so tests actually do initialize and
shutdown the graphics system every time (except for those platforms
out there that can only initialize the graphics system once), so
they can be more time consuming. On the positive side, because the
tests are exercising the graphics API and hardware directly, we
catch things that the first approach wouldn't have caught (for
example, sending incorrect parameters to a function).</p>

<p>The same three approaches can be used for any
middleware or external API. The important thing to remember is to
make sure you're testing your code, not the API itself. Keeping
that in mind helps to write true unit tests and not functional
tests for the API.</p>

<p>
<img src="http://www.gamesfromwithin.com/images/46_tdd_gdc/mock.jpg" align="right" 
width="300" height="388" alt="Mocks" />

A good example of this approach is how we wrote
our input system with TDD. The input system deals with getting
input values from gamepads and other controllers. Even though at
first glance it might seem like the whole system is about making
system calls to poll the data, there is a lot of common code that
is totally platform independent: button mappings, edge detection,
filtering, plugging/unplugging controllers, etc.</p>

<p>In our system, we have an interface named
<code>GameController</code> with a Sample()
function. Each platform implements a platform-specific version of
the <code>GameController</code> (for example
<code>D3DController</code>) and does the raw
sampling of all buttons and axis through platform-specific API
calls. That part is fully untested. The rest of the input system
works through the <code>GameController</code>
interface, but for all the tests we provide a 
<code>MockGameController()</code> which allows us to control
what input values we feed to the tests.</p>

<p>We are hoping that as TDD becomes more common in
the games industry, middleware providers will make their APIs more
TDD friendly and even ship with their unit tests.</p>

<p><b>Third-party game engines</b></p>

<p>If dealing with APIs was not straightforward,
working with a full third-party game engine that was not developed
with TDD is even more challenging. After all, an API is just a list
of classes or functions, and you have a lot of control over how and
when they get called. Working with a full game engine, you might
end up writing a small module that is fully surrounded by the
engine code. If the engine was not developed with TDD, it can be
very difficult to use your code in isolation or figure out how to
break things up so they can be tested.</p>

<p>At High Moon, we are working on several projects
with the Unreal Engine 3, and we're using TDD on them. Even though
the engine is not TDD-friendly at all, we still find more benefit
from doing TDD with it. Imagine then how useful TDD can be on a
full engine developed with TDD from the start.</p>

<p>The most important thing to do in this situation
is to separate the code we write as much as possible from the
engine code. Not only does this allow us to unit-test our code in
isolation, but we also keep future merges with Epic's codebase as
simple as possible. However, that severely limits the amount of
large-scale refactorings we can do to keep things as testable as
possible, so it's a tough trade-off..</p>

<p>One unique aspect of the Unreal Engine is that
it makes heavy use of its scripting language, UnrealScript. Because
a lot of the high-level game engine is written in UnrealScript, we
had little choice but to use it to write most of the game code. The
first thing we had to do was to create a unit-testing framework for
UnrealScript. The resulting framework is called UnUnit and is
freely available for download through UDN (Unreal Developer
Network). Several companies working with the Unreal Engine are
currently using UnUnit for their game projects.</p>

<p>UnrealScript is a surprisingly good language for
unit testing. By default, all functions are virtual, so overriding
behaviors and creating mocks is simpler than C++. Also, compilation
is very fast, which keeps iteration times low (large, badly
organized C++ codebases can take a long time to link). All of that
makes TDD with UnrealScript not just possible, but very
effective.</p>

<p><b>Randomness and games</b></p>

<p>Most games involve a fair amount of randomness:
the next footstep sound you play can be any one of a set of sounds,
the next particle emitted has a random speed between a minimum and
a maximum, etc. As a general rule, you want to remove the
randomness from your tests. A few times we caught ourselves
starting to write a unit test that called a function many times in
a loop and then averaged the result, but that's totally the wrong
way to go. Unit tests are supposed to be simple and fast, so any
loops in a test are usually very suspect.</p>

<p>A better approach is to separate the random
decision from the code that uses it. For example, instead of just
having a <code>PlayFootstep()</code> function that
takes care of computing a random footstep and then playing it, we
can break it into int <code>ComputeNextFootstep()</code> which is just a random
function call, and a <code>PlayFootstep(int index)</code>, which we can now test very easily.</p>

<p>Another approach is to take control over the
random number generator at the beginning of the test and rig the
output so we know what sequence of numbers is going to come up. We
can do this either by mocking the random number generator object or
by setting some global state on the random number generator,
depending on how it is implemented. Then tests can count on a
specific sequence of numbers being generated and check the results
accordingly.</p>

<p><b>High-level game scripts</b></p>

<p>How far is it worth taking TDD? Should TDD be
used for every single line of code? How about game-specific script
code? The answer depends on your priorities and game.</p>

<p>As a general rule, we find that if any other
part of the game is going to depend on the code we are writing,
then it's probably worth doing it with TDD and having a full set of
unit tests for it. Otherwise, if it's a one-shot deal with the
highest-level code, then it's probably fine without TDD. Also, code
at that level is often written by designers in a game-specific
scripting language, so TDD might not be a viable option.</p>

<p>An example of some code that we would not use
TDD for is trigger code: when the player goes around the corner,
wake up two AIs and trigger a different background music.</p>

<p>Functional tests are a great complement to unit
tests, so it's important not to forget about them. Automated
functional tests can be extremely useful catching high-level
problems, gathering performance and memory utilization data, and
removing some of the mechanical testing from QA and letting them
concentrate on issues such as gameplay balance and flow.</p>

<h3>7. Lessons learned</h3>

<p><b>Design and TDD</b></p>

<p>One of the most important benefits we get from
TDD is the better code design that it creates. For this to happen,
it's important to let the tests guide the code and not the other
way around. It can be disconcerting to always be looking only a few
minutes into the future and implementing the &ldquo;simplest thing
that could possibly work,&rdquo; but it really works. The key to
working with TDD is to realize that refactoring is an integral part
of the development process and should happen regularly every few
tests. Good design will come up through those refactorings as
needed by the tests we have written and the code we have
implemented.</p>

<p>Does this mean you shouldn't do any design ahead
of time? That depends on your situation and experience, and the
type of code you're writing. In general, the less known or more
likely to change something is, the less design we do. If you're
working on the 10<sup>th</sup> iteration of a well-known sports
game franchise, for a known platform, and you know exactly what
you're going to do, up front design can be more beneficial.</p>

<p>In our case, we prefer to discuss very rough
concepts of where we expect something to go, what it should do in
the future, and maybe some very, very rough organizational
structure. In general, we prefer not to even think of classes or
draw UML diagrams on whiteboards before starting, because such
discussions can then lead implementation too much. We prefer to let
the tests guide us, and if at some point we're going away from what
we had in mind at the beginning, we can stop to reconsider if we're
heading in the right direction. Most of the time we are, and we
simply hadn't thought things through enough at the beginning (or
thought through them too much and we simply didn't need that level
of flexibility).</p>

<p><b>TDD and high-level code</b></p>

<p>One of the questions we had when we jumped into
TDD is whether it was going to hold for high-level code. We had
seen in practice from previous projects that we can certainly do
TDD to create low-level and intermediate-level libraries (math,
collision, messaging, etc). But would it really work for high-level
code that would build on low-level code?</p>

<p>The answer is an unconditional yes. We have
developed a full codebase doing TDD from the start, and we had no
difficulty writing high-level code with TDD. Things like character
state machines, game flow, or specific game entities were done
through TDD without any problems, and greatly benefited from the
TDD approach.</p>

<p>Two tips that helped us apply TDD to high-level
code:</p>
<ul>
<li>Keep tests as true unit tests. When working on
high-level code, it can be tempting to let tests degenerate into
functional tests that involve the whole game engine. Don't do that.
Even if it takes a few more minutes to make an enemy character
testable in isolation, it is well worth it in the long run.</li>

<li>Keep the engine architecture as flat as
possible. This is a general good practice, but it is more so with
TDD. Clearly, avoid having your engine as one big, intertwined
module. But even if it's broken down into libraries or modules,
keep them as independent of each other as possible instead of as
one long list of dependencies. For example, there's no reason the
AI module needs to know anything about graphics or sound, but it
will need to know about a world representation and have access to
the messaging system.</li>
</ul>

<p><b>Tests as a measure of progress</b></p>

<p>Software developers have been struggling for a
long time to find a good measure of progress or work done. Some
projects use code line counts to determine progress, others use
features completed, while others just look at the number of hours
spent at the office. Clearly, none of those approaches are
ideal.</p>

<p>We have found that counting the number of unit
tests is a really good measure of progress. Especially when tests
are developed through TDD, they deal less with corner cases and
more with program features. If a library has 500 tests associated
with it, we can say that it's roughly half as complex as a library
with 1000 tests.</p>

<p>As an added benefit, people tend to behave based
on how they think they are being measured. So if this is made
clear, people will be much more likely to be strict about applying
TDD and not falling back on writing code without tests. In our
groups, we have a test chart, which is updated every day and shows
the total count of tests. If tests aren't going up, or they're
going up more slowly than other times, we know something is wrong
and we're not making much progress.</p>

<p><b>Build stability</b></p>

<p>As we expected, having almost full code coverage
with unit tests greatly improves the code stability. Broken builds
happen much less frequently, and they're usually caused by a
missing file or a different platform not compiling correctly. What
was a pleasant surprise is that broken builds are much easier to
fix. By following our best practices for unit tests, it becomes
really obvious when something breaks, and we can usually check in a
fix right away. Builds are rarely broken for more than a few
minutes at a time, which can completely change how you organize
your code in source control.</p>

<p><b>Amount of code</b></p>

<p>It will probably come as no surprise to anybody
that writing code with TDD results in more code being written.
Sometimes the test code is as large as the code under test itself.
Even though this can initially sound like a scary proposition, it
really isn't a problem. The extra code does not take significantly
longer to write initially, and it allows us to move a lot faster
once we have accumulated more code and we need to refactor or
optimize the code in any way.</p>

<p>Just because we have twice as much code it
doesn't mean we have twice the complexity. Quite the contrary. The
test code has been written so it's extremely simple, so its
complexity is minimal. Its only job is to check the non-test code,
so it's keeping an eye out for us, helping us, and letting us know
when something breaks. Additionally, the TDD approach results in
much simpler, decoupled code. Overall, the complexity of the
codebase is greatly reduced with TDD.</p>

<p>A good analogy to TDD is scaffolding in a
building construction. It's not something you're going to deliver
to your customer, but it's an absolute necessity, it needs some
time commitment to set it up, and you wouldn't dream of doing any
complex building without it.</p>

<p><b>Development speed</b></p>

<p>This is the million-dollar question: Does TDD
slow development? We're not doing TDD because it's a
&ldquo;good&rdquo; thing to do, but because we want to ship a
better-quality product faster and cheaper than we did before. If
TDD doesn't help with this, then there's very little point to it
(other than keeping programmers happy).</p>

<p>As with other aspects of software development,
it is difficult to make an objective study and measure exactly the
effects of TDD versus a control group. Things change too much from
project to project and team to team. Still, some initial studies
have some interesting initial findings
(http://collaboration.csc.ncsu.edu/laurie/Papers/TDDpaperv8.pdf),
even if the study was not very rigorous and had a very small
sample.</p>

<p>Our experience is that TDD, like any other new
development technique, slows development down at the beginning
while the team is learning it and becoming familiar with it. This
can take as long as a couple of months. Once the team is over the
hump, and given the right tools and development environment, the
impact of TDD on development speed is minimal.</p>

<p>It is possible to simply write code faster than it
is to write the tests first, but as soon as that code needs to be
refactored, debugged, used by somebody else, or simply gets more
complex, any time savings quickly disappear. The larger the team
and the more complex the problem, the more TDD saves time in the
long run. It's very important to not fall for the temptation of
skipping TDD for a very short-term gain (aka milestone of the
month).</p>

<p>Ideally, TDD and refactoring can flatten out the
classical cost-of-change over time curve into something like this.
Notice the trade-off between slightly slower short-term speed vs.
massive gains later on.</p>

<p align="center"><img src="http://www.gamesfromwithin.com/images/46_tdd_gdc/costofchange.png" align="middle" 
width="483" height="327" alt="Cost of change" /></p>

<p><b>Adopting TDD</b></p>

<p>We started with TDD by first trying it with a
small group on a separate project. In our particular case, not only
were we doing TDD, but we were doing all the extreme programming
practices (pair programming, continuous integration, collective
code ownership, etc). When doing this, it can be extremely useful
to have somebody on board with previous TDD experience who can help
guide the process, set up the environment, and avoid common early
mistakes.</p>

<p>Applying it on a small scale initially was very
useful in many different ways. It let the team become more
comfortable with TDD and get to the point where they are as
productive as they were before. It also makes any bad practices
apparent early on and they can be dealt with before rolling it out
(making overly complex tests or functional, rather than unit
tests).</p>

<p>It also had the effect of creating new
evangelists for the new technique. Members of that team were then
moved on to other teams, where they became the resident TDD
expert.</p>

<p>TDD fits best with other agile development
practices. Having an agile mindset fits very well with the idea of
finding the design through tests. Pair programming can be extremely
helpful, especially at the beginning while rolling out TDD and
getting everybody on board. Pair programing also has the added
advantage of making programmers less likely to skip writing tests,
which can be a common reaction early on.</p>

<p>If you're interested in applying TDD but you
don't have a commitment from your manager or lead, it is possible
to start doing it on the side on your assigned tasks. The most
important thing is to make sure your tests run automatically
(remember the postbuild trick). Slowly, other people might see how
useful the tests are, or how much easier it is to refactor that
code, and eventually the time might be right to roll out TDD.</p>

<p>A few people can have a hard time switching over
to the TDD mentality, but to take full advantage of TDD, it is best
to let the design emerge from the tests and the refactoring rather
than trying to plan everything up front. It is very interesting to
note though, that most programmers at High Moon quickly accepted
TDD, and soon became very enthusiastic about it and started using
it in all their code, including their home projects.</p>

<p>There is no doubt that the best situation to
roll out TDD is with a fresh new codebase. Not everybody has that
luxury, so it is important to learn how to apply TDD even with an
existing legacy codebase. Michael Feathers' book <i>Working
Effectively with Legacy Code</i>, explains exactly that situation
and gives some very good guidelines on how to go about unit testing
with a codebase without existing unit tests. Sometimes it just
takes a little bit of refactoring of the existing code and it
becomes a lot easier to add new tests.</p>

<h3>8. Conclusion</h3>

<p>Test-driven development can be a very effective
development technique. We have successfully applied it to game
development in a variety of situations, and we're convinced of the
many benefits it has provided us. Right now, the idea of writing
code without writing tests first feels quite alien to most of us,
and we treat TDD like the scaffolding in building construction: a
necessary tool that will not be shipped to the customer but that
helps tremendously during development.</p>

<h3>9. Resources</h3>

<p>This is required reading before you start doing
any TDD:</p>
<ul><li><a href="http://www.amazon.com/exec/obidos/ASIN/0321146530/ref=nosim/gamesfromwith-20">
Beck, Kent, <i>Test Driven Development: By Example.</i> Addison-Wesley, 2002</a></li></ul>

<p>These other books will also come in handy:</p>
<ul>
<li><a href="http://www.amazon.com/exec/obidos/ASIN/0201485672/ref=nosim/gamesfromwith-20">
Fowler, Martin, <i>Refactoring: Improving the Design of Existing Code.</i> Addison-Wesley, 1999</a></li>
<li><a href="http://www.amazon.com/exec/obidos/ASIN/0131016490/ref=nosim/gamesfromwith-20">
Astels, David, <i>Test Driven Development: A Practical Guide.</i> Prentice Hall, 2003</a></li>
<li><a href="http://www.amazon.com/exec/obidos/ASIN/0321278658/ref=nosim/gamesfromwith-20">
Beck, Kent, and Cynthia Andres, <i>Extreme Programming Explained: Embrace Change (2nd Edition)</i>, Addison-Wesley, 2004</a></li>
</ul>

<p>Very useful mailinglists and web sites:</p>
<ul>
<li><a href="http://www.testdriven.com/">TestDriven.com</a></li>
<li><a href="http://groups.yahoo.com/group/testdrivendevelopment">TDD mailing list</a></li>
</ul>

<p>Resources dealing with TDD and agile game development:</p>
<ul>
<li><a href="http://www.gamesfromwithin.com/">Noel's blog, Games from Within</a></li>
<li><a href="http://www.agilegamedevelopment.com/blog.html">Clinton Keith's blog, Agile Game Development</a></li>
</ul>

<p>C++ unit-testing frameworks:</p>
<ul>
<li><a href="http://unittest-cpp.sourceforge.net/">UnitTest++</a>. A C++ unit-testing framework
designed with game development in mind.</li>
<li><a href="http://cppunit.sourceforge.net/cppunit-wiki">CppUnit</a></li>
<li><a href="http://www.gamesfromwithin.com/articles/0412/000061.html">Comparison of C++ unit-test frameworks</a></li>
</ul>
]]>
    </content>
  </entry>
  <entry>
    <title>High Moon Blog Roll</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0603/000106.html" />
    <modified>2006-03-11T05:49:13Z</modified>
    <issued>2006-03-10T21:49:13-08:00</issued>
    <id>tag:,2006:/2.106</id>
    <created>2006-03-11T05:49:13Z</created>
    <summary type="text/plain"> A couple of weeks ago Jim Tilander, a co-worker from High Moon and good friend, finally took the plunge and started putting some of his writings online. He already wrote two very interesting articles on Python (surprise, surprise knowing...</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>General</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      <![CDATA[<img src="http://www.gamesfromwithin.com/images/hms.png" alt="high moon" align="right" width="75" height="122"/>

A couple of weeks ago <a href="http://www.tilander.org/jim/">Jim Tilander</a>, a co-worker from High Moon and good friend, finally took the plunge and started putting some of <a href="http://www.tilander.org/aurora/">his writings online</a>. He already wrote two very interesting articles on <a href="http://www.tilander.org/aurora/articles/000008.html">Python</a> (surprise, surprise knowing Jim) and how to <a href="http://www.tilander.org/aurora/articles/000009.html">pull in static data for unit tests</a>. I'm sure there will be lots more interesting articles to come.]]>
      <![CDATA[<p>A couple of weeks ago <a href="http://www.tilander.org/jim/">Jim
Tilander</a>, a co-worker from High Moon and good friend, finally
took the plunge and started putting some of <a href=
"http://www.tilander.org/aurora/">his writings online</a>. He
already wrote two very interesting articles on <a href=
"http://www.tilander.org/aurora/articles/000008.html">Python</a>
(surprise, surprise knowing Jim) and how to <a href=
"http://www.tilander.org/aurora/articles/000009.html">pull in
static data for unit tests</a>. I'm sure there will be lots more
interesting articles to come.</p>

<p>That makes quite a few of us from High Moon with active web
sites on technical topics. These are the ones I'm aware of:</p>

<ul>
<li><a href="http://www.agilegamedevelopment.com/blog.html">Agile
Game Development</a>. Clinton Keith's blog on agile game
development and Scrum.</li>

<li><a href="http://alpatrick.blogspot.com/">Al's Game Programming
Blog</a>. Al Patrick's writings.</li>

<li><a href="http://cnicholson.net/">Charles Nicholson</a>. Not a
lot of writing there yet, but home to a couple of interesting
projects.</li>

<li><a href="http://www.tilander.org/aurora/">Aurora</a>. Jim
Tilander's blog.</li>

</ul>

<p>Agile development seems to be a common theme to all of them. 
Coincidence? I think not :-)</p>

<p>Any others that I missed? Let me know and I'll add them to the
list.</p>
]]>
    </content>
  </entry>
  <entry>
    <title>A Day in the Life</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0602/000104.html" />
    <modified>2006-02-06T00:43:06Z</modified>
    <issued>2006-02-05T16:43:06-08:00</issued>
    <id>tag:,2006:/2.104</id>
    <created>2006-02-06T00:43:06Z</created>
    <summary type="text/plain">High Moon Studios is an unusual company in the games industry. We&apos;re applying agile methodologies for all of our development. My team in particular is using both Scrum (an agile management methodology) and Extreme Programming (an agile engineering methodology). And yes, that means we&apos;re doing pair programming, test-driven development, and all the other often controversial practices. I expect that in a few years, these practices will be a lot more common than they are today.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>Project management</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      <![CDATA[<img src="http://www.gamesfromwithin.com/images/hms.png" alt="high moon" align="right" width="75" height="122"/>

High Moon Studios is an unusual company in the games industry. We're applying agile methodologies for all of our development. My team in particular is using both Scrum (an agile management methodology) and Extreme Programming (an agile engineering methodology). And yes, that means we're doing pair programming, test-driven development, and all the other often controversial practices. I expect that in a few years, these practices will be a lot more common than they are today.]]>
      <![CDATA[This article was first published in the 2005 Career Guide issue of Game Developer
Magazine.<br/>

<p><br/></p>


<p><a href="http://highmoonstudios.com/">High Moon Studios</a> is an unusual company in the games industry.
We're applying agile methodologies for all of our development. My
team in particular is using both Scrum (an agile management
methodology) and Extreme Programming (an agile engineering
methodology). And yes, that means we're doing pair programming,
test-driven development, and all the other often controversial
practices. I expect that in a few years, these practices will be a
lot more common than they are today.</p>

<p>I lead the R&amp;D team here, and my team's primary
responsibility is to come up with the technology that game teams
use for different projects. Nowadays, that means putting a lot of
middleware programs through their paces and choosing the ones that
suit our needs. But it also means getting down and dirty and
writing a lot of code for our engine and tools.</p>

<p>With that in mind, come on and follow me through a typical
workday.</p>

<p><b>8:10 AM</b></p>

<p>I roll in to work on my bicycle like I do every day. Even though
I'm an early bird, Jim, a programmer in my team, arrived a few
minutes earlier and is already at his desk.</p>

<p>I quickly catch up with my email. I also notice that the PCLint
pass on our codebase last night caught a couple of minor warnings,
so I quickly fix those and check them in.</p>

<p><b>8:20 AM</b></p>

<p>Today is Tuesday and our two-week iteration ends on Friday. An
iteration consists of a fixed period (usually two weeks in our
case) during which the team commits to deliver a set of
functionality described through customer stories. The customer (in
our case the other internal teams in our company) creates and
prioritizes a set of stories. My team then breaks down those
stories into tasks and estimates how long they will take to
complete (tasks vary between 1 and 8 hours).</p>

<p>Jim and I walk over to the "war room" (the room with all the
task cards corresponding to user stories pinned to the wall) and we
choose the task that reads "Blend ragdoll and animation," which is
part of the user story listed as "Throwing a rigid body at a
character and seeing a hit reaction." The task was originally
estimated at 3 hours, but now that we know that the ragdoll system
is a bit more complicated than we thought, we re-estimate it at 4
hours.</p>

<p><b>8:23 AM</b></p>

<p>In addition to our own personal desk areas, we have
pair-programming stations in the R&amp;D lab, with two monitors,
two keyboards, two mice, two chairs, and plenty of room for two
people. All production code is written by pairs of programmers. We
grab a station and start working on the task.</p>

<p>Since we're using test-driven development, we first write a very
simple unit test for what we want to do, and only then write the
code to make it pass. In this case, our first test checks that we
create a blender object without inputs and that it produces no
output. Then we write the blender class and make the test pass.
It's a tiny step, but it's a step in the right direction. The whole
cycle of write test, write code to make test pass, refactor, takes
only 5-10 minutes, and we do it over and over.</p>

<p><b>8:39 AM</b></p>
<p>We have implemented a small amount of functionality, and all the code builds and all tests
pass, so we check it in source control. This is called continuous
integration, and it requires that programmers work on the latest
version in source control and check in their own changes many times
throughout the day.</p>

<p><b>8:50 AM</b></p>
<p>Other people from the team roll in, grab other pair programming
stations, and start going at it. On their way in we have a quick
chat and find out what we're all working on.</p>

<p align="center">
<img src="http://www.gamesfromwithin.com/images/42_hms/highmoon1.jpg"
 width="500" height="289" hspace="10" align="middle" alt="Work hard..." /><br/>
<span class="caption">Work hard...</span>
</p>

<p><b>9:37 AM</b></p>
<p>I overhear Joel and Gary discussing how they're going to test
something that requires updating the physics simulations. I just
did that a couple of days ago so I jump in the discussion. It turns
out they need to do something that is almost the same as what I
already did, so I point them to what I wrote and they will modify
it to suit their needs.</p>

<p><b>10:05 AM</b></p>
<p>Things are moving along very nicely. We've checked in four times
already this morning. When a pair gets really going, they might
check in as many as 20 or more times in a single day. At this rate
we might be done sooner than the four hours we had estimated.</p>

<p><b>10:14 AM</b></p>
<p>We have the daily Scrum meeting at 10:15, so we head over to the
war room. Scrum meetings are very short, standup meetings with the
whole team (eight people plus Brian, our producer). We quickly go
around the room discussing what people are doing to get everybody
up to speed.</p>

<p><b>10:23 AM</b></p>
<p>During the meeting the topic of how we're loading physics assets
came up. So we return to the pair programming area and have a quick
discussion with everybody involved. We draw some quick UML charts
on a whiteboard, think about how the data is going to be passed
around, and after ten minutes we reach an agreement and go back to
work on our tasks.</p>

<p><b>11:15 AM</b></p>
<p>We got the blending working correctly. All the unit tests pass,
although we haven't implemented it in the demo yet. There's another
task card for that. We check the code in right away. The code
definitely can stand to improve in a few places because we were
just concentrating on getting things working, so we spend some time
refactoring. We have lots of unit tests, so we're confident our
refactoring isn't introducing any bugs.</p>

<p><b>11:56 AM</b></p>
<p>The code is now in a much better state. We check it in and wait
a few minutes for the build server to report that everything built
correctly and all tests passed. During that time we talk about what
the next task should be.</p>

<p><b>12:05 PM</b></p>
<p>We have nice shoulder-high surf today, so I'm going out surfing
at lunch with several of my teammates. If it's not surfing, it's a
basketball game, cycling, running, or even yoga. If all else fails,
there's always a game of <i>Guild Wars</i> with the rest of the
High Moon clan.</p>

<p><b>1:10 PM</b></p>
<p>Back at my desk I eat a quick lunch while I catch up on my email
(which I haven't read since this morning because I've been at the
pair programming station). I read an email from a middleware
developer in response to one of our queries earlier in the day and
fire back a quick response.</p>

<p><b>1:25 PM</b></p>
<p>Sean stops by my desk. He's ready to go back to work, but the
programmer he was pairing with in the morning got pulled to work on
some last-minute issues with <i>Darkwatch</i>, which is about to go gold and has
priority over anything we're doing.</p>

<p>Sean quickly brings me up to speed on what they had been working
on that morning, which was to display the exact memory usage for
our physics system. I remember them mentioning that in this
morning's Scrum meeting. I also worked on the physics system last
week, so I'm pretty familiar with the code. In a couple of minutes
we're already making progress.</p>

<p align="center">
<img src="http://www.gamesfromwithin.com/images/42_hms/highmoon2.jpg"
 width="500" height="282" hspace="10" align="middle" alt="...rock hard" /><br/>
<span class="caption">... rock hard :-)</span>
</p>

<p><b>2:07 PM</b></p>
<p>After writing several unit tests and implementing some
functionality, we're ready to add the memory display to the demo
program. A couple of minutes later, we have a display in the demo
indicating how much memory the physics system is using, and we see
it go up and down as we add and remove rigid bodies from the
demo.</p>

<p>But something is wrong. When we remove rigid bodies, the memory
doesn't come down to the same level it was before. We exit the demo
and we see a long memory leak dump. First things first, we check in
our changes, and then we dive in and look for the code that is
leaking memory. It's probably not caused by the code we just wrote,
but we have "collective code ownership," which means that everybody
is expected to fix anything that needs fixing anywhere.</p>

<p><b>2:12 PM</b></p>
<p>The build just broke! The build server detected a failed build
and notified us through a system tray application. I bring up the
latest build log and I see that one of the unit tests failed in
release mode. Tyson, who is sitting at the station next to ours,
says "Oh yeah, I know what that is. I'll fix it right now." In less
than 30 seconds he makes the change, and checks it in. A few
minutes later, the build system reports a passing build and
everything is back to normal.</p>

<p><b>2:17 PM</b></p>
<p>We found the memory leak. It was a misuse of reference counting.
We first wrote a unit test that showed it failing, and then we
fixed in the physics library. We check in our code.</p>

<p><b>2:18 PM</b></p>
<p>We go to the war room and grab the next task. This one has to do
with being able to expose different variables and functions on the
demo to tweak them through a GUI. We sign up for the task and start
working on it.</p>

<p><b>3:43 PM</b></p>
<p>We're totally in the zone. We've been writing tests and code
like crazy and this task is going really well. We've done three
check-ins for this task alone in the last hour.</p>

<p><b>4:12 PM</b></p>
<p>Another pair is discussing how to handle errors for some
particular case. This is an important topic and it should be done
consistently across all the code, so we have a quick discussion
about it involving most of the team. Five minutes later we've made
a decision and we all resume working on what we were doing
before.</p>

<p><b>5:40 PM</b></p>
<p>We do our last check in for the day. We're almost done with the
task, but not quite there yet. Even though we could stay another
hour and try to finish it, we're both quite tired by now and we're
starting to not think as clearly and make some mistakes. We can
wrap this up tomorrow morning as soon as we get in. The important
part is that we got to a state where we could check in.</p>

<p>We have a rule that says nobody can check in code and leave. You
have to wait for the build server to build the code successfully
and pass all the tests. We keep build times short, so that usually
means hanging around an extra 4-5 minutes. If anything breaks, you
need to fix it or revert what you did, but there's no excuse to
leave with a broken build.</p>

<p>While I'm waiting for the build server to finish, I check the
pile of email that accumulated in my inbox during the day.</p>

<p><b>5:44 PM</b></p>
<p>After a few minutes we get the green go ahead from the build
server. Today was a pretty productive day, and at this pace we will
definitely complete all the user stories by Friday. The demo we're
putting together is also starting to look very cool.</p>

<p>One of the things that agile development, and especially pair
programming, does is to make each day very intense. There are no
little breaks to read email, check a web site, or just goof around.
We get a lot accomplished in a work day, but we can't keep that
pace for a long time, so it's important to call it quits and go
home. That leaves me with time at home to read technical books,
prototype different ideas, or work on side projects in addition to
unwinding, spending time with my family, and enjoying other
hobbies.</p>

<p>I hop on my bike and head home with a big smile on my face.</p>
]]>
    </content>
  </entry>
  <entry>
    <title>CppUnitLite2 1.1</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0512/000103.html" />
    <modified>2005-12-18T04:18:57Z</modified>
    <issued>2005-12-17T20:18:57-08:00</issued>
    <id>tag:,2005:/2.103</id>
    <created>2005-12-18T04:18:57Z</created>
    <summary type="text/plain">At this point, we have been using CppUnitLite2 for a year at High Moon Studios doing test-driven development on Windows, Xbox 360, and some PS3. It has been used to unit test libraries of an engine, pipeline tools, GUI applications, and production game code.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>Test-Driven Development</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      At this point, we have been using CppUnitLite2 for a year at High Moon Studios doing test-driven development on Windows, Xbox 360, and some PS3. It has been used to unit test libraries of an engine, pipeline tools, GUI applications, and production game code.
      <![CDATA[<p>
<a href="http://www.gamesfromwithin.com/bin/CppUnitLite2_1_1.tar.gz">
	<img src="http://www.gamesfromwithin.com/images/script.png" width="20" height="22" border="0" alt="icon"/>CppUnitLite2_1_1.tar.gz</a><br/>
</p>
<p><br/></p>

<p>About a year ago, I wrote <a href=
"http://www.gamesfromwithin.com/articles/0412/000061.html">an
article comparing unit test frameworks</a> that went to become one
of the most popular in this site. The article concluded with the
recommendation of one of the less well known frameworks:
CxxTest.</p>

<p>Shortly after writing that article, it came time to roll out
test-driven development at work. Interestingly, once I weighted in
all the requirements, I ended up not following my own advice.
Instead, I decided to go with a customized version of CppUnitLite,
which was listed in the article as the second choice. The idea of
an extremely simple unit testing framework was too attractive to
pass up in an environment where we have to support a large variety
of environments and target platforms.</p>

<p>At this point, we have been using CppUnitLite2 for a year at
<a href="http://www.highmoonstudios.com/">High Moon Studios</a> to
do TDD on Windows, Xbox 360, and some PS3 (we even have a
stripped-down version that runs on a <a href=
"http://cell.scei.co.jp/e_download.html">PS3 SPU</a>). It has been
used to unit test libraries of an engine, pipeline tools, GUI
applications, and production game code.</p>

<p>CppUnitLite2 was originally released along with my article a
year ago. It was a heavily modified version of the original
CppUnitLite by Michael Feathers. This version introduces the
changes we made at work as different issues came up and we needed
more functionality from the framework. In particular, <a href=
"http://www.tilander.org/jim/">Jim Tilander</a> and <a href=
"http://cnicholson.net/content.php?id=1">Charles Nicholson</a> were
responsible for a lot of those changes. By now, I doubt there's a
single line left from the original code. Additionally, CppUnitLite2
itself has a set of tests using itself in an interestingly
recursive way.</p>

<h3>What's new</h3>

<p><b>Fixtures created and destroyed around each test.</b></p>

<p>I can't believe that the original
version of CppUnitLite2 didn't have this feature. It was the
biggest glaring problem with the framework (I even pointed it out
in the article). Each fixture used to be created at static
initialization time, which, apart from being a really bad idea,
caused a lot of objects to be created and live in memory at the
same time. Considering that some of those objects would
initialize/shutdown some important game systems, we clearly needed
to manage their lifetime a bit better.</p>

<p>The test macro was changed to
register a temporary test with the TestRegistry, which in turn will
create the fixture at execution time. Now fixtures and tests are
created just before each test, and destroyed right after, just as
you would expect from any sane framework.</p>

<p>For those masochists out there, here's the ugly macro for a test
with fixture in all its glory. Notice how the TestRegistrar
registers the dummy test class that we created as part of the
macro.</p>

<div class="code"><pre>
#define TEST_F(fixture, test_name)                                                      \
    struct fixture##test_name : public fixture {                                        \
        fixture##test_name(const char * name_) : m_name(name_) {}                       \
        void test_name(TestResult&amp; result_);                                            \
        const char * m_name;                                                            \
    };                                                                                  \
    class fixture##test_name##Test : public Test                                        \
    {                                                                                   \
        public:                                                                         \
            fixture##test_name##Test ()                                                 \
                : Test (#test_name "Test", __FILE__, __LINE__) {}                       \
        protected:                                                                      \
            virtual void RunTest (TestResult&amp; result_);                                 \
    } fixture##test_name##Instance;                                                     \
    TestRegistrar fixture##test_name##_registrar (&amp;fixture##test_name##Instance);       \
    void fixture##test_name##Test::RunTest (TestResult&amp; result_) {                      \
        fixture##test_name mt(m_name);                                                  \
        mt.test_name(result_);                                                          \
    }                                                                                   \
    void fixture ## test_name::test_name(TestResult&amp; result_)
</pre></div>

<p></p>

<p><b>Improved check statements</b></p>

<p>Another one of the major weaknesses of CppUnitLite as it stood
was the check statements. You needed to have a custom check macro
for each data type you cared to check. The generic CHECK_EQUAL
macro will now work on any data type as long as it can be compared
with operator == and output to a stream.</p>

<p>This version of CppUnitLite2 also includes some special macros
to check arrays with one and two dimensions. Again, this works on
any data type that supports operator == and operator[]. It came it
very handy for checking equality of vectors and matrices in a game
engine. For example, the following code checks that two matrices
are equal:</p>

<div class="code">
CHECK_ARRAY2D_CLOSE (m1, m2, 4, 3, kEpsilon);
</div>

<p>Ironically, in some heavily restricted environments (like the
PS3 cell processors), we can't use streams, so in that case we're
forced to go back to the old specialized check macros.</p>

<p><b>Invariant statements in checks</b></p>

<p>Another really annoying feature of the previous version of
CppUnitLite2 was that the code in a check statement was called
multiple times, which could cause strange side effects.</p>

<p>Consider the following code:</p>
<div class="code">
CHECK_EQUAL (FunctionWithSideEffects1(), FunctionWithSideEffects1());
</div>

<p>The way the check statement was expanded out, both those
functions could be evaluated multiple times. If the functions had
side effects, they would be executed several times, causing
unexpected results (for example, the check could fail but the
printed result could be different). The fix wasn't trivial because
we couldn't save off the value of each statement because they could
be of any type and we have no way of finding the type from within
the macro.</p>

<p>The check macro now expands out to a templated function, which
is able to evaluate both statements only once and work with the
saved value to avoid any surprising side effects.</p>

<p><b>Optional fixture initialization</b></p>

<p>As we continued hammering on the unit test framework for all our
development, one clear pattern appeared that wasn't handled by the
framework: Being able to create fixtures with parameters defined in
the test. For example, the fixture might do ten different steps,
but we want to set a particular value in one of those steps, and by
the time control reaches the test code itself it's too late.</p>

<p>We started getting around that by creating different fixtures,
and then by inhereting from other fixtures and changing some
parameters. Both of those solutions were less than ideal (lots of
code duplication and added complexity). Things got out of hand when
we made the fixtures a templated class on a value, and created them
by specifying the value as part of the texture name. Now it was a
pain to debug and things were even less clear.</p>

<p>So we finally implemented it natively in CppUnitLite2 as
fixtures with initialization parameters. We introduced a new macro,
TEST_FP (test with fixture and parameters), which takes any
parameters you want to pass to the fixture constuctor.</p>

<p>Now you can declare tests like this:</p>
<div class="code">
TEST_FP (VectorFixture, VectorFixture(10), MyTest)<br />
{<br />
}<br />
</div>

<p>We should probably simplify that to avoid repeating the fixture
name, but that works fine for now.</p>

<p><b>Include cleanup</b></p>

<p>The original version of CppUnitLite was pretty casual about what
headers it included. Unfortunately, that means that all test code
were automatically exposed to a variety of standard headers,
whether you wanted it or not. This version is a lot more strict,
and the only header that will get pulled in from using it will be
iosfwd, which is even a fairly lightweight one.</p>

<p><b>Memory allocations</b></p>

<p>We have very strict memory allocation wrappers around our tests,
and if any memory leaks, it is reported as a failed test. Since
checking for memory allocations is very platform specific, it is
left out of the framework (although it could be added pretty easily
in the platform-specific sections). In any case, some of the
static-initialization time allocations were confusing the memory
tracker, so we removed them completely. All it means is that we use
an array to register tests instead of a std::vector and we cap the
maximum number of tests to a fixed amount. If you need more than
the default 5000 tests, go right ahead and add a few zeros.</p>

<p><b>New license</b></p>

<p>Previous versions of CppUnitLite were not released with an
explicit license. To make things clear, I explicitly added the
license text for the <a href=
"http://www.opensource.org/licenses/mit-license.php">MIT
license</a> with an added restriction. The MIT license allows you
to use the code in any project, commercial or otherwise, without
any restrictions. The added restriction to the license prohibits
its use in any military applications or projects with any military
funding.</p>

<h3>Ratings</h3>

<p>How does this release of the CppUnitLite2 compare with respect
to my initial set of features I used to rate the different unit
tests frameworks?</p>
<ul>

<li><b>Minimal amount of work needed to add new tests.</b> Nothing
has changed there. Still passes with flying colors.</li>

<li><b>Easy to modify and port.</b> That has always been the strong
suite of this framework.</li>

<li><b>Supports setup/teardown steps (fixtures).</b> Much improved
now by creating them correctly around each test.</li>

<li><b>Handles exceptions and crashes well.</b> No changes there.
Still one of the best I've seen.</li>

<li><b>Good assert functionality.</b> The check macros have been
much improved to match the best frameworks out there.</li>

<li><b>Supports different outputs.</b> Yup. Still there.</li>

<li><b>Supports suites.</b> It still doesn't. It just shows that I
really haven't needed this feature yet.</li>

</ul>

<h3>Future work</h3>

<p>So, what's next for CppUnitLite2? It's really quite usable right
now, but I could see a few changes happening in the next year, and
maybe a few others will come up and surprise me.</p>

<p>Test registration is based on static initialization of global
variables, which is not very reliable across compliers. For
example, if you try to put the tests in a static library, MSVC will
strip out the registration code leaving you with no tests. To get
around that, we could introduce a custom build step in a scripting
language that would generate a simple file with explicit
registration of tests. This could also be used to collect tests
from many different libraries into a single executable.</p>

<p>A couple of times it would have been convenient to have
parameterized tests (I think that's the correct term for it).
Basically, to have tests that could run with different data.
Something like this:</p>

<div class="code"><pre>
TEST_PARAM(MyCustomTest, int a, int b)
{
    CHECK (something);
    CHECK(something else);
    CHECK(yadda yadda);
}

TEST(MyTest)
{
    CALL_TEST(MyCustomTest, 10, 5);
}
TEST(MyTest)
{
    CALL_TEST(MyCustomTest, 12, 7);
}
</pre></div>


<p>The key point is that a test fails in the parameterized test, it
should report the error correctly indicating where it came
from.</p>

<p>This is actually pretty easy to implement with a couple of
macros. We simply haven't needed it more than a couple of times, so
we haven't bothered yet. But I imagine next time we run up against
this we'll bite the bullet and implement it.</p>

<h3>Wrap-up</h3>

<p>Charles had so much fun working with this framework, he decided
to write his own from scratch. He made <a href=
"http://cnicholson.net/content.php?id=52">it available on his web
site</a>, so go check it out.</p>

<p>Thanks to High Moon Studios for being open and letting us
release the changes we made and share them back with everybody. If
you end up using the framework and you make any changes, drop me an
email and I'll add them for the next release.</p>

]]>
    </content>
  </entry>
  <entry>
    <title>Are We There Yet? SlickEdit&apos;s C++ Refactoring</title>
    <link rel="alternate" type="text/html" href="http://www.gamesfromwithin.com/articles/0510/000102.html" />
    <modified>2005-10-11T02:50:24Z</modified>
    <issued>2005-10-10T19:50:24-08:00</issued>
    <id>tag:,2005:/2.102</id>
    <created>2005-10-11T02:50:24Z</created>
    <summary type="text/plain">Jumbo shrimp. Instant classic. Military intelligence. C++ refactoring browser. Spot the pattern yet? Up until recently, there have been more sightings of Nessy and Bigfoot than of working C++ refactoring browsers. After months of using refactoring intensively in C++, my fingers are screaming for mercy and threatening me with repetitive stress syndrome. Fortunately, things seem to be changing a bit.</summary>
    <author>
      <name>llopis</name>
      
      <email>llopis@convexhull.com</email>
    </author>
    <dc:subject>Tools</dc:subject>
    <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://www.gamesfromwithin.com/">
      <![CDATA[<img src="http://www.gamesfromwithin.com/images/icons/tool_icon.jpg" width="77" height="77" align="right" alt="tools"/>

Jumbo shrimp. Instant classic. Military intelligence. C++ refactoring browser. Spot the pattern yet? Up until recently, there have been more sightings of Nessy and Bigfoot than of working C++ refactoring browsers. After months of using refactoring intensively in C++, my fingers are screaming for mercy and threatening me with repetitive stress syndrome. Fortunately, things seem to be changing a bit.]]>
      <![CDATA[<!--Are We There Yet? SlickEdit's C++ Refactoring-->

<p>Jumbo shrimp. Instant classic. Military intelligence. C++
refactoring browser. Spot the pattern yet? Up until recently, there
have been more sightings of <a href="http://www.lochness.co.uk/livecam/">Nessy</a>
and <a href="http://www.unmuseum.org/bigfoot.htm">Bigfoot</a> than of
working C++ refactoring browsers. After months of using refactoring
intensively in C++, my fingers are screaming for mercy and
threatening me with repetitive stress syndrome. Fortunately, things
seem to be changing a bit. I recently learned of <a href="http://www.slickedit.c