<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>#AltDevBlogADay &#187; Thaddaeus Frogley </title>
	<atom:link href="http://www.altdevblogaday.com/author/thaddaeus-frogley/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.altdevblogaday.com</link>
	<description>Each day a little more #gamedev love</description>
	<lastBuildDate>Thu, 17 May 2012 03:06:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>From the Codeface, a Bug Fixing Story</title>
		<link>http://www.altdevblogaday.com/2011/11/30/from-the-codeface-a-bug-fixing-story/</link>
		<comments>http://www.altdevblogaday.com/2011/11/30/from-the-codeface-a-bug-fixing-story/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 10:00:23 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[low level]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=20823</guid>
		<description><![CDATA[<p>It was March, 2009, and I was working on a high profile multi platform psychological horror game. We were &#8220;in QA&#8221;, Milestone 12, and my code was holding up well. I had been at 0-bugs for most of the week, and had spent most of my time testing, and helping whoever I could with debugging whatever problems were bouncing around the team.</p>
<p><a href="http://www.altdevblogaday.com/2011/11/30/from-the-codeface-a-bug-fixing-story/" class="more-link">Read more on From the Codeface, a Bug Fixing Story&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>It was March, 2009, and I was working on a high profile multi platform psychological horror game. We were &#8220;in QA&#8221;, Milestone 12, and my code was holding up well. I had been at 0-bugs for most of the week, and had spent most of my time testing, and helping whoever I could with debugging whatever problems were bouncing around the team.</p>
<p>One particularly tricky bug from that time stuck in my memory.</p>
<p><span id="more-20823"></span></p>
<p>It was Wednesday when I got the email from the project&#8217;s technical lead.</p>
<p>Our memory profiling system had been spitting out a warning on one of our target platforms that indicated a memory trample. Both the technical lead, and the programmer who implemented the system were snowed under, so I was asked to take a look and find out what the problem was.</p>
<p>Now, at this stage there were two possibilities: either (a) there was a memory trample, but for whatever reason we could only see it on one platform, or (b) the memory profiler code is not working correctly on that platform.</p>
<p>My first step was to put a breakpoint on the line of code that spits out the warnings and run the code in a debugger on the target platform.</p>
<p>Execution stops, and I examine the code in some more detail. The code that fires the warning works as follows: When a pointer to memory is about to be freed it is passed to the memory profiler, which calls a &#8220;<code>GetMemSize</code>&#8221; function to determine the size of the allocation, then fetches a value from the last 4 bytes of the block and checks if it is the expected value. If the value read isn&#8217;t as expected a warning is printed.</p>
<p>The callstack does not make me happy. The code freeing the memory is my code &#8211; it&#8217;s my generic array class (like <code>std::vector</code>, but awesome). This is code I&#8217;ve brought with me and has been in production use on shipping projects for years. It is unlikely, in my opinion, that this code is broken, but not impossible &#8211; so I keep looking.  </p>
<p>I look at the code using the array &#8211; is it doing anything untoward? The array class has assertions on the element access to trap bounds errors, but the iterators do not. The code using the array class does not (that I can see) use iterators.  It uses: <code>push_back</code>, <code>pop_back</code> and <code>operator[]</code>.  All calls with debug guards to trap misuse.</p>
<p>So I take a step back. The profiling code itself is quite new, so I look at it in more detail. I check where the trapped value is supposed to be set, and find something that might be a lead &#8211; a complex nest of preprocessor conditional compilation.</p>
<p>Our memory manager is layered &#8211; Micro-Allocator, Turbo-Allocator and then the system (vendor/OS) allocator. The memory profiler is currently turned off for allocations that go via the micro and turbo allocators, so maybe there is a mistake in the way the #ifdefs have been structured that means the value is being checked, but not set up at all.</p>
<p>This seems like a good lead at first, and I follow it for a while, but it turns out that the #ifdefs are all set up correctly.  The allocation in question is going via the system allocator, and the profiler is inserting it&#8217;s pad value at the end correctly.</p>
<p>Back to square one.</p>
<p>The problem is happening at start up, which is deterministic, and the OS uses a fixed memory model that means allocations always end up at the exact same address run after run. Time for some hardware breakpoints.</p>
<p>I run the game again, find out the address of the value the system is complaining about, and set up a breakpoint-on-write, then restart the run.</p>
<p>I filter my way through the breakpoints hits, checking if what is writing there should be, and find nothing. Nothing relevant at all. Nothing writes to that byte. It is unused. The value is not touched.</p>
<p>What on earth?</p>
<p>So I backtrack. Again. Double check my numbers. Did I have the right address? Yes. Break point the set up function. Breakpoint the creation of the array. Single-step though lots of code. The allocator is setting up the boundary value &#8211; <em>but not in the same place as it is being fetched from!</em></p>
<p>So, a moment of clarity &#8211; it isn&#8217;t the value at the end of the array getting stomped, but the address the code is getting for the end of the array that is wrong!</p>
<p>Perhaps it&#8217;s the value at the start of the array getting stamped?</p>
<p>New hardware breakpoint, at the start of the array this time. Run. Watch were we stop. The breakpoint hits in system malloc and system free. It makes sense. The callstack looks right. Hits in malloc, then free, malloc, free, malloc, free. </p>
<p>Nothing that shouldn&#8217;t touch that memory was touching it. I see a bunch of mallocs and frees and then the system falls over.</p>
<p>What on earth is going on?</p>
<p>And then I notice it. The system that is using the array is an XML parser. There isn&#8217;t one array &#8211; there are <em>loads</em> of them.</p>
<p>This is the mind boggling part: The moment the call to free stamps on the size value of array &#8216;A&#8217; was not the moment that the memory owned by &#8216;A&#8217; was freed.  It was when some other array was freeing memory.</p>
<p>So: We have a two blocks of memory allocated by the operating system. At the start of each one, we have a 4-byte <code>int</code> for the total size of the block. At the end of each one we have the guard value. We know the location of the guard value by checking the size of the memory block, but when we free &#8216;B&#8217; the size of &#8216;A&#8217; changes.</p>
<p>Nice.</p>
<p>Lets have a look at <code>GetMemSize</code>. For the platfrom in question <code>GetMemSize(ptr)</code> returns <code>ptr[-1]-5</code>. </p>
<p>Note the vendor in question does not provide a <code>memstat</code>/<code>memsize</code> function so this is the result of deduction and reverse engineering.  </p>
<p>And it&#8217;s wrong. The version of the function for another platform by the same vendor has a hack of a work around that does:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>memSize <span style="color: #339933;">%</span> <span style="color: #0000dd;">2</span> <span style="color: #339933;">!=</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> memSize <span style="color: #339933;">=</span> memSize <span style="color: #339933;">+</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Oh Hello.</p>
<p>So, it seems like the system memory manager uses those first 4 bytes for more than just the size. After all, the memory allocations are all 4 byte aligned, so those first 2 bits aren&#8217;t really needed, and it seems like they are used for something else, perhaps to do with the availablity of neighboring blocks for use with realloc? </p>
<p>Who knows.</p>
<p>But the fix now is clear, mask off the bottom bit, and we are good.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">UInt32 memSize <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Ptr<span style="color: #009900;">&#91;</span><span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">-</span><span style="color: #0000dd;">4</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">&amp;</span>~<span style="color: #0000dd;">1</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Perhaps I should&#8217;ve masked off the bottom 2 bits?</p>
<p>Who knows, it all seemed to work after that. And the game shipped in December without major bugs.</p>
<p><em>This story is a rewrite of one I originally posted here: <a href="http://www.hulver.com/scoop/story/2009/3/20/133915/125">http://www.hulver.com/scoop/story/2009/3/20/133915/125</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/11/30/from-the-codeface-a-bug-fixing-story/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Type Names Matter</title>
		<link>http://www.altdevblogaday.com/2011/10/31/type-names-matter/</link>
		<comments>http://www.altdevblogaday.com/2011/10/31/type-names-matter/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 23:07:10 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=19648</guid>
		<description><![CDATA[<p>Names matter. Some 10 years ago or so, I wrote an article for a blog on using typedef when working with templated C++ types, such as the STL containers.</p>
<p>You can read the original article (<a href="http://homepage.mac.com/codemonkey_uk/using_typedefs.html">Using Typedefs</a>) if you want. I&#8217;d like now to try to distil why I think this advice still holds up, 10 years later, even if you aren&#8217;t using templates, the STL or C++.<br />
<span id="more-19648"></span></p>
<p><a href="http://www.altdevblogaday.com/2011/10/31/type-names-matter/" class="more-link">Read more on Type Names Matter&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Names matter. Some 10 years ago or so, I wrote an article for a blog on using typedef when working with templated C++ types, such as the STL containers.</p>
<p>You can read the original article (<a href="http://homepage.mac.com/codemonkey_uk/using_typedefs.html">Using Typedefs</a>) if you want. I&#8217;d like now to try to distil why I think this advice still holds up, 10 years later, even if you aren&#8217;t using templates, the STL or C++.<br />
<span id="more-19648"></span></p>
<p>Programming is a form of communication. As a programmer you write for two audiences: You write for the compiler, and you write for the future other programmer.</p>
<p>For most programmers who are game developers, that future other programmer is someone already on your team, or as yet hired future team member. </p>
<p>Even for the solo programmer, the indie developer, working from home, will on occasion return to code written many years ago, and use it as the basis of new work.</p>
<p>Who knows, if that solo project goes viral, one day you might be hiring people to port it to the latest console or handheld device.</p>
<p>Any professional writer will tell you, one of the many important principles of good writing is to consider your audience. This applies to programming as well.</p>
<p>Now, I&#8217;m not going to say that the human audience comes first. A programmers primary job is to get the computer to Do The Right Things, and sacrificing how clearly you are instructing the computer in order to better communicate with the human reader may well be a questionable trade off, especially when performance is an important factor in the engineering goals.</p>
<p>But even with the primary function of writing code that works dealt with, there is often room to improve how <em>literate</em> your programming is, and one of the most powerful tools as your disposal as a programmer is giving things good names.</p>
<p>A good type name can tell the reader not just what a type is for, but also what it is <em>not</em> for. Consider a <em>Name</em> vs a <em>String</em>, or a <em>NameList</em> vs a <em>StringContainer</em>.</p>
<p>So, please, think carefully about how you name your<br />
types, your functions, methods, and variables, because it&#8217;s not just the compiler reading the code.</p>
<p>One day it might be me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/10/31/type-names-matter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Overflowing your Comfort Zone</title>
		<link>http://www.altdevblogaday.com/2011/09/16/overflowing-your-comfort-zone/</link>
		<comments>http://www.altdevblogaday.com/2011/09/16/overflowing-your-comfort-zone/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 08:00:49 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[ASM]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=16404</guid>
		<description><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/09/IMG_4620.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2011/09/IMG_4620-300x300.jpg" alt="" width="300" height="300" class="alignleft size-medium wp-image-16418" /></a>I love C++. I&#8217;m a big fan of it&#8217;s expressiveness. I think carefully constructed abstractions can be enormously powerful, and that C++ gives you the tools to construct those abstractions efficiently. </p>
<p><a href="http://www.altdevblogaday.com/2011/09/16/overflowing-your-comfort-zone/" class="more-link">Read more on Overflowing your Comfort Zone&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/09/IMG_4620.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2011/09/IMG_4620-300x300.jpg" alt="" width="300" height="300" class="alignleft size-medium wp-image-16418" /></a>I love C++. I&#8217;m a big fan of it&#8217;s expressiveness. I think carefully constructed abstractions can be enormously powerful, and that C++ gives you the tools to construct those abstractions efficiently. </p>
<p>There are however, some problems that C/C++ simply can&#8217;t solve well. Sometimes the best tool for the job isn&#8217;t going to be your favourite tool, and rather than try to twist the tool you like to the job you need to do, you should leave your comfort zone and try something new.</p>
<p>This article explores once such problem, and what happened when I left my comfort zone.</p>
<p><span id="more-16404"></span></p>
<p>This problem came up on a C++ mailing list I subscribe too:</p>
<blockquote><p>I&#8217;m working on a problem where integer multiplicative overflow is plausible and I want to check for it.</p></blockquote>
<p>The poster had already constructed a solution that looked like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">overflow <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>a<span style="color: #339933;">!=</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>a<span style="color: #339933;">*</span>b<span style="color: #009900;">&#41;</span><span style="color: #339933;">/</span>a<span style="color: #339933;">!=</span>b<span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>Given that mathematically: (a*b)/b == a, the poster was concerned that the optimiser would spot that and eliminate the test. He also wondered if there were better ways of doing it.</p>
<p>The question prompted a fair amount of discussion. The general consensus was that the test worked, and that the compiler would not optimise it away.</p>
<p>Some other solutions were proposed, none of them unambiguously better.</p>
<p>But it got me thinking. Given that every CPU architecture that I have any experience with has an overflow bit, shouldn&#8217;t we be able to check that? A divide is relatively expensive, and the test includes a compare and a branch to set a boolean that will then most certainly be used in a compare and a branch. </p>
<p>Wouldn&#8217;t it be better to just check the overflow bit?</p>
<p>So I started with this as my baseline:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// returns true (non-zero) if the result of a*b is within the valid range of an integer</span>
<span style="color: #666666; font-style: italic;">// the value of the multiplication is stored in the address pointed to by result</span>
BOOL SafeMultiply<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> b<span style="color: #339933;">,</span> <span style="color: #993333;">int</span><span style="color: #339933;">*</span> result <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> c <span style="color: #339933;">=</span> a <span style="color: #339933;">*</span> b<span style="color: #339933;">;</span>
    <span style="color: #339933;">*</span>result <span style="color: #339933;">=</span> c<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span>a<span style="color: #339933;">==</span><span style="color: #0000dd;">0</span> <span style="color: #339933;">||</span> c<span style="color: #339933;">/</span>a<span style="color: #339933;">==</span>b<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Which can be used like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>SafeMultiply<span style="color: #009900;">&#40;</span>a<span style="color: #339933;">,</span>b<span style="color: #339933;">,&amp;</span>c<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #666666; font-style: italic;">// do something with c</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #666666; font-style: italic;">// report an error   </span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>I then spent about an hour relearning some assembly code. I knew it could be done, but the specific opcodes, mnemonics, and inline-asm syntax were fuzzy. It&#8217;s been probably 16  years since I actually wrote any assembler. Debugging it, sure, looking at the generated code, yes. But writing assembler just hasn&#8217;t come up in my work for a very long time.</p>
<p>I wrote the first version on my lunch break at work, so I used MSVC, and thus MASM syntax inline assembler.What I wrote looked something like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> SafeMultiply<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> b<span style="color: #339933;">,</span> <span style="color: #993333;">int</span><span style="color: #339933;">*</span> result <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">char</span> good<span style="color: #339933;">;</span> 
    __asm<span style="color: #009900;">&#123;</span>
        mov eax<span style="color: #339933;">,</span> a<span style="color: #339933;">;</span>
        imul eax<span style="color: #339933;">,</span> b<span style="color: #339933;">;</span>
        setno good<span style="color: #339933;">;</span>
        mov ebx<span style="color: #339933;">,</span> result<span style="color: #339933;">;</span>
        mov dword ptr <span style="color: #009900;">&#91;</span>ebx<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> eax<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">return</span> good<span style="color: #339933;">;</span> 
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>MASM made it easy. I was pleased. I should have stopped there. What happened next, however, was that I decided to write this article for #AltDevBlogADay.</p>
<p>When I write for #AltDevBlogADay, I do it at home. On my laptop. Which doesn&#8217;t have MSVC. The #AltDevBlogADay readers deserve, I thought, more than just MASM. They deserve a GNUC compatible version. They deserve that, and a comparison of the code generated, with inline assembler and pure C compiled with -O3.</p>
<p>What I learnt, my friends, is that the GNUC inline assembler syntax is evil. Pure evil. Evil genius, perhaps. Remarkably powerful in ways I hadn&#8217;t even considered possible. But still evil.</p>
<p>It is not for the faint-hearted, and might not be the optimal solution, but here it is:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> SafeMultiply<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> b<span style="color: #339933;">,</span> <span style="color: #993333;">int</span><span style="color: #339933;">*</span> result <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">char</span> good<span style="color: #339933;">;</span> 
    __asm__<span style="color: #009900;">&#40;</span>
        <span style="color: #ff0000;">&quot;imull %2, %3;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\t</span>&quot;</span>
        <span style="color: #ff0000;">&quot;setno %0;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\t</span>&quot;</span>
        <span style="color: #ff0000;">&quot;movl %3, %1;&quot;</span>
            <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;=r&quot;</span> <span style="color: #009900;">&#40;</span>good<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;=r&quot;</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>result<span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> <span style="color: #ff0000;">&quot;r&quot;</span> <span style="color: #009900;">&#40;</span>a<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;r&quot;</span> <span style="color: #009900;">&#40;</span>b<span style="color: #009900;">&#41;</span> 
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>   
    <span style="color: #b1b100;">return</span> good<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Note, that I&#8217;ve shown here each version on it&#8217;s own. In reality it&#8217;s all mashed together with appropriate _MSC_VER and __GNUC__ #ifdefs.</p>
<p>I shan&#8217;t waste your time trying to explain the syntax, if you&#8217;d like to get into that (and I recommend you do, it is fascinating), then the two pages I give at the bottom of this article could be a good place to start.</p>
<p>Anyway, I promised a look at the generated code. This was compiled on OS X with GCC, using -O3 and the -save-temps command line. I have stripped out the function call header code, and parred it down to only what is relevant: the different bodies of the functions.</p>
<p>The C implementation generates this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;">	movl	<span style="color: #339933;">%</span><span style="color: #00007f;">esi</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">ecx</span>
	imull	<span style="color: #339933;">%</span><span style="color: #00007f;">edi</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">ecx</span>
	movl	<span style="color: #339933;">%</span><span style="color: #00007f;">ecx</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #339933;">%</span>rdx<span style="color: #009900; font-weight: bold;">&#41;</span>
	movl	$<span style="color: #0000ff;">1</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">eax</span>
	testl	<span style="color: #339933;">%</span><span style="color: #00007f;">edi</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">edi</span>
	<span style="color: #00007f; font-weight: bold;">je</span>	L4
	movl	<span style="color: #339933;">%</span><span style="color: #00007f;">ecx</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">edx</span>
	movl	<span style="color: #339933;">%</span><span style="color: #00007f;">ecx</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">eax</span>
	sarl	$<span style="color: #0000ff;">31</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">edx</span>
	idivl	<span style="color: #339933;">%</span><span style="color: #00007f;">edi</span>
	cmpl	<span style="color: #339933;">%</span><span style="color: #00007f;">esi</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">eax</span>
	<span style="color: #00007f; font-weight: bold;">sete</span>	<span style="color: #339933;">%</span><span style="color: #00007f;">al</span>
	movzbl	<span style="color: #339933;">%</span><span style="color: #00007f;">al</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">eax</span>
L4<span style="color: #339933;">:</span>
	<span style="color: #00007f; font-weight: bold;">leave</span>
	<span style="color: #00007f; font-weight: bold;">ret</span></pre></td></tr></table></div>

<p>And the inline assembler (GNUC version), generates this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;">	imull	<span style="color: #339933;">%</span><span style="color: #00007f;">edi</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">esi</span><span style="color: #666666; font-style: italic;">;</span>
	<span style="color: #00007f; font-weight: bold;">setno</span>	<span style="color: #339933;">%</span>dil<span style="color: #666666; font-style: italic;">;</span>
	movl	<span style="color: #339933;">%</span><span style="color: #00007f;">esi</span><span style="color: #339933;">,</span> <span style="color: #339933;">%</span><span style="color: #00007f;">eax</span><span style="color: #666666; font-style: italic;">;</span>
	movl	<span style="color: #339933;">%</span><span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #339933;">%</span>rdx<span style="color: #009900; font-weight: bold;">&#41;</span>
	movsbl	<span style="color: #339933;">%</span>dil<span style="color: #339933;">,%</span><span style="color: #00007f;">eax</span>
	<span style="color: #00007f; font-weight: bold;">leave</span>
	<span style="color: #00007f; font-weight: bold;">ret</span></pre></td></tr></table></div>

<p>Now I&#8217;m no expert, and I&#8217;ve not timed it, but I can see that the latter is smaller, and I think its a safe bet that it&#8217;s also faster.</p>
<p>Thanks for reading!</p>
<ul>
<li> <a href="http://www.osdever.net/tutorials/view/a-brief-tutorial-on-gcc-inline-asm">A Brief Tutorial on GCC inline asm (x86 biased)</a>
<li> <a href="http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html">GCC-Inline-Assembly-HOWTO</a>
</ul>
<p><em>With thanks to everyone who gave me feedback on my initial draft, and especially to Fabian Giesen and Don Olmstead for their constructive critisism, and for the title suggestion.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/09/16/overflowing-your-comfort-zone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing Code To Write Code</title>
		<link>http://www.altdevblogaday.com/2011/07/18/writing-code-to-write-code/</link>
		<comments>http://www.altdevblogaday.com/2011/07/18/writing-code-to-write-code/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 21:03:19 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=11774</guid>
		<description><![CDATA[<p>So, as I mentioned <a href="http://altdevblogaday.com/2011/04/19/three-tools-i-love-and-so-should-you/" title="Three Tools I Love (And So Should You)" target="_blank">in an earlier post</a>, there is this tool I like called <a href="http://code.google.com/p/metalscroll/" title="MetalScroll" target="_blank">MetalScroll</a>, which includes some basic syntax colorising of C/C++/C#, but not Unreal Script.</p>
<p>Since I&#8217;m now working with Unreal Script some of the time, and the plug-in is open source, I decided to see if it would be straightforward to extend that functionality. My assumption was that it would be pretty easy, and in the end <a href="http://code.google.com/p/metalscroll/source/detail?r=81" title="r81" target="_blank">it was</a>.</p>
<p><a href="http://www.altdevblogaday.com/2011/07/18/writing-code-to-write-code/" class="more-link">Read more on Writing Code To Write Code&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>So, as I mentioned <a href="http://altdevblogaday.com/2011/04/19/three-tools-i-love-and-so-should-you/" title="Three Tools I Love (And So Should You)" target="_blank">in an earlier post</a>, there is this tool I like called <a href="http://code.google.com/p/metalscroll/" title="MetalScroll" target="_blank">MetalScroll</a>, which includes some basic syntax colorising of C/C++/C#, but not Unreal Script.</p>
<p>Since I&#8217;m now working with Unreal Script some of the time, and the plug-in is open source, I decided to see if it would be straightforward to extend that functionality. My assumption was that it would be pretty easy, and in the end <a href="http://code.google.com/p/metalscroll/source/detail?r=81" title="r81" target="_blank">it was</a>.</p>
<p>But that isn&#8217;t really what I want to write about now. It is what that work led me too that I think is interesting.<br />
<span id="more-11774"></span><br />
See, turning on the syntax highlighting for Unreal Script wasn&#8217;t too hard, but as it stood &#8211; as it still stands as I write this &#8211; the keyword colouring code in MetalScroll still only recognises C++ keywords, because when I dug deeper what I discovered was fascinating and took me off on a total tangent.</p>
<p>The initial work was done on office time &#8211; it was a worthwhile effort to boost productivity of multiple teams where I work by improving a popular tool, but then I dug a little deeper: How hard would it be to make it use an Unreal Script specific keyword list when highlighting Unreal Script? All I have to do is find the list of keywords, and swap it out for a different list depending on filetype. Right?</p>
<p>So away I go reading the code: <a href="http://code.google.com/p/metalscroll/source/browse/trunk/TextFormatting.cpp#276" target="_blank">RenderText</a> calls <a href="http://code.google.com/p/metalscroll/source/browse/trunk/CppLexer.cpp#80">IsCppKeyword</a>, which has a list &#8212; but &#8212; hang on &#8212; it does what? But what if, oh, wait, so &#8230; but what if &#8230; oh, then what does that <a href="http://code.google.com/p/metalscroll/source/browse/trunk/CppLexer.cpp#28" target="_blank">hash</a> do? Oh. That&#8217;s <em>neat</em>. It&#8217;s got to be fast. Smart guy. So did he, really, make that by hand? I scroll up. Ah. So what&#8217;s this: /* <a href="http://code.google.com/p/metalscroll/source/browse/trunk/CppLexer.cpp#20" target="_blank">C code produced by gperf version 3.0.3</a> */</p>
<p>Interesting.</p>
<p>Google: gperf.</p>
<p>Result: It&#8217;s a GNU tool for generating hash functions.</p>
<blockquote><p>GNU gperf is a perfect hash function generator. For a given list of strings, it produces a hash function and hash table, in form of C or C++ code, for looking up a value depending on the input string. The hash function is perfect, which means that the hash table has no collisions, and the hash table lookup needs a single string comparison only.</p></blockquote>
<p>That, right there, is gold. Right away I think back, all my years in the industry, and almost all the problems I&#8217;ve ever seen with asset names and hash functions, would have been solved. Like magic. Beautiful. If you can feed it a full list of your asset id names, it can spit out a hash function with guaranteed no clashes.</p>
<p>If you use asset names and hash them, and I&#8217;m betting a lot of people do, because I&#8217;ve seen it a ton of times, then you could to be using this.</p>
<p>But I didn&#8217;t stop there.</p>
<p>That&#8217;s a pretty tight way of spotting keywords. A fast hash, and a string compare. </p>
<p>But we still need to look at some of the characters in the input string more than once. There is an extra 1 to 3 reads from the input string to build the hash, before the character-by-character string compare.</p>
<p>If we are generating code for a fixed list of keywords (which is reasonable) then that could be improved on, I&#8217;m sure.</p>
<p>So I thought about it, and came up with this: If we treat the keyword list as a possibility tree, where each character narrows down which possible keywords it could be, we can stop as soon as we know it&#8217;s not a keyword, and if we are still &#8220;in&#8221; the tree when we hit the end (of both the keyword and the input string) we have a winner.</p>
<p>I started thinking through ways of building the tree structure with look up tables in static data, and then it dawned on me: since it&#8217;s generating code, the tree can be directly encoded in the structure of the source code. We can let the compiler do something C and C++ compilers tend to be very good it: Compiling switch statements.</p>
<p>So that evening I went home and I wrote this: <a href="http://code.google.com/p/gen-is-keyword-fn/" title="gen-is-keyword-fn" target="_blank">gen-is-keyword-fn</a>, and stuck it up on google-code.</p>
<p>It&#8217;s not finished yet &#8211; I&#8217;ve been absurdly busy recently (this post is being hastily rattled out at the 11th hour) &#8211; but it shows some initial promise. I haven&#8217;t timed yet how well it performs against a gperf based keyword identifier, since I haven&#8217;t yet implemented the generator for functions that accept keyword candidates of a known length, but initial testing vs a textbook binary search of a sorted list, give some very promising results: Specifically, with the switch-case coming in at 10%-20% of the execution time of the binary_search.</p>
<p>So, writing code that writes code can pay off. And is fun.</p>
<p>Which is point of my story, I think. For now.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/07/18/writing-code-to-write-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From the Codeface</title>
		<link>http://www.altdevblogaday.com/2011/07/03/from-the-codeface/</link>
		<comments>http://www.altdevblogaday.com/2011/07/03/from-the-codeface/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 07:30:41 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=9869</guid>
		<description><![CDATA[<p>Last week I was asked the following question. This is not unusual, but it being a real live game programming question, I thought perhaps, just perhaps, the answer might be of interest to more than just the person who asked it. Names have been changed to protect the innocent. </p>
<p><a href="http://www.altdevblogaday.com/2011/07/03/from-the-codeface/" class="more-link">Read more on From the Codeface&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Last week I was asked the following question. This is not unusual, but it being a real live game programming question, I thought perhaps, just perhaps, the answer might be of interest to more than just the person who asked it. Names have been changed to protect the innocent. </p>
<blockquote><p>
How do I stop this code generating a:</p>
<p>MyClass(123) : warning: &#8216;result&#8217; may be used uninitialized in this function</p>
<p>Without pragma&#8217;ing the warning off ?
</p></blockquote>
<p><span id="more-9869"></span><br />
<code><br />
T Remove(int key)<br />
{<br />
&nbsp;&nbsp;// !!! We need a pragma here or something to tell the compiler to ignore the<br />
&nbsp;&nbsp;// fact that "result" is not initialized.</p>
<p>&nbsp;&nbsp;T result;</p>
<p>&nbsp;&nbsp;m_Mutex.Lock();</p>
<p>&nbsp;&nbsp;Iterator it = m_Map.Find(key);<br />
&nbsp;&nbsp;if (it != m_Map.End())<br />
&nbsp;&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;result = *it;<br />
&nbsp;&nbsp;&nbsp;&nbsp;m_Map.Erase(it);<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;m_Mutex.Unlock();</p>
<p>&nbsp;&nbsp;return result;<br />
}<br />
</code><br />
To which I answered:</p>
<blockquote><p>Burn it with fire.</p></blockquote>
<p>Then, more seriously: As the code stands you can&#8217;t fix this. It is a fundamental error in the interface design. Presumably this is a member of a container class template that deals with value types.</p>
<p>In my opinion the method in question should be changed to one or other of:</p>
<p><code>// returns true on success, contents of result will be set to the value<br />
// returns false if key does not exist, the contents of result<br />
bool Remove(u32 key, T* result);</code></p>
<p>Or</p>
<p><code>// where, if key does not exist, return value "default"<br />
T Remove(u32 key, const T&amp; default);</code></p>
<p>Or if Remove is widely used and changing the signature is too big a change, then consider have the &#8220;default&#8221; value specified during construction of the object.</p>
<p>Of the three possible solutions, I prefer the first.</p>
<p>Note the use of mutexes implies this is used in a multithreaded context, so double-checking &#8220;exists&#8221; before &#8220;remove&#8221; is unreliable (as well as inefficient), and so there is no way to check if the Remove operation was successful when using this container with built in types (int, float, etc) with the current interface methods.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/07/03/from-the-codeface/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Making Of Pirate Pennywise</title>
		<link>http://www.altdevblogaday.com/2011/06/18/the-making-of-pirate-pennywise/</link>
		<comments>http://www.altdevblogaday.com/2011/06/18/the-making-of-pirate-pennywise/#comments</comments>
		<pubDate>Sat, 18 Jun 2011 20:39:29 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=8811</guid>
		<description><![CDATA[<p><a title="Pirate Pennywise" href="http://homepage.mac.com/codemonkey_uk/pennywise/" target="_blank">Pirate Pennywise</a> is a simple browser hosted game (tested in: Safari, Firefox, Chrome) that I made in my spare time. It is a personal side project, that has taken approximately 3 months (of occasional evenings) to complete. In this post I&#8217;d like to reflect on the development process, and what I have learnt. Do not expect this to be a masterclass in web development, my goal was as much about learning as it was about making a new game.<br />
<span id="more-8811"></span><br />
<strong>Some Background</strong><br />
Pennywise (originally called &#8220;FIGHT!&#8221;) is a multiplayer coin game, designed by <a title="@cheapassjames" href="http://twitter.com/#!/cheapassjames" target="_blank">James Ernest</a> for <a title="Cheapass Games" href="http://www.cheapass.com/" target="_blank">Cheapass Games</a>, released under a creative commons licence, and distributed at board game conventions as a promotional device. It is a game that has interested me for a long time as it&#8217;s fun to play, and presents some interesting strategic challenges.</p>
<p><a href="http://www.altdevblogaday.com/2011/06/18/the-making-of-pirate-pennywise/" class="more-link">Read more on The Making Of Pirate Pennywise&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a title="Pirate Pennywise" href="http://homepage.mac.com/codemonkey_uk/pennywise/" target="_blank">Pirate Pennywise</a> is a simple browser hosted game (tested in: Safari, Firefox, Chrome) that I made in my spare time. It is a personal side project, that has taken approximately 3 months (of occasional evenings) to complete. In this post I&#8217;d like to reflect on the development process, and what I have learnt. Do not expect this to be a masterclass in web development, my goal was as much about learning as it was about making a new game.<br />
<span id="more-8811"></span><br />
<strong>Some Background</strong><br />
Pennywise (originally called &#8220;FIGHT!&#8221;) is a multiplayer coin game, designed by <a title="@cheapassjames" href="http://twitter.com/#!/cheapassjames" target="_blank">James Ernest</a> for <a title="Cheapass Games" href="http://www.cheapass.com/" target="_blank">Cheapass Games</a>, released under a creative commons licence, and distributed at board game conventions as a promotional device. It is a game that has interested me for a long time as it&#8217;s fun to play, and presents some interesting strategic challenges.</p>
<p>I created an AI &amp; tournament framework for it called &#8220;<a title="cppFIGHT" href="http://tech.groups.yahoo.com/group/cppfight/" target="_blank">C++FIGHT!</a>&#8221; around 10 years ago and used it as a sandbox for exploring turn-based game AI techniques, such as <a title="Minimax Algorithm on Wikipedia" href="http://en.wikipedia.org/wiki/Minimax" target="_blank">MiniMax</a>, <a title="Alpha-Beta Pruning" href="http://en.wikipedia.org/wiki/Alpha-beta_pruning" target="_blank">AlphaBeta</a>, and heuristic tuning with genetic algorithms.</p>
<p>I had briefly experimented with implementing it as a playable game in Java about 8 years ago, but lost interest in Java as a language and never got further than sprites that could be moved around with the mouse.</p>
<p>So when, after finishing <a title="Syd Sym Post Mortem here on #AltDevBlogADay" href="http://altdevblogaday.com/2011/05/04/syd-sym-post-mortem/" target="_blank">Syd Sym</a>, I decided that I wanted to try making a browser game (but not with flash) as my next hobby project, it seemed like the natural thing to pick up unfinished business and finally give the AI I&#8217;d made for Pennywise some human opponents to play against. The realisation that the art requirements would be minimal was the icing on the cake.</p>
<p><strong>The First Month</strong><br />
Initially the progress was slow. I spent long evenings reading poorly written HTML, CSS and Javascript tutorials, and figuring out very simple things, like how to implement drag and drop. I made a deliberate choice not to use &lt;canvas&gt;  but to work within the HTML document structure (I figured I&#8217;d learn more that way, and I think I was right). So I created a simple document structure that mirrored the games conceptual structure, a &lt;div&gt; for the game &#8220;table&#8221; containing a &lt;div&gt; for each player, and a &lt;div&gt; for the pool of change in the middle. I set up the HTML so they basically stacked on top of each other, and I placed a &lt;div&gt; for each type of coin in each of the player &lt;divs&gt;.</p>
<p>I then deleted huge chunks of it, wrote a javascript port of the game state objects from cppFIGHT and generated the HTML in the onload event handler for the page.</p>
<p>After which I researched how web apps normally implement drag and drop and used what I had learnt about onmousedown, onmousemove and onmouseup to implement my own drag drop system for picking up, moving coins and detecting which container div they had been dropped onto.</p>
<p>Each time a coin was dropped, I deduced how that related to a move in the game, applied an appropriate change to the game state, and regenerated the innerHTML from that.</p>
<p>At that stage I was becoming confident I&#8217;d be able to turn out a working game in a reasonable amount of time, so I roped <a title="Roger Barnett" href="http://www.rogerbarnettanimation.com/" target="_blank">an artist friend of mine</a> into creating some original art for the game.</p>
<p>Enthused by the promise of real professional art for the game, I finally got around to creating a <a title="Hg" href="http://mercurial.selenic.com/" target="_blank">mercurial</a> repository for it on my laptop.</p>
<p><strong>The Second Month</strong><br />
With the basic framework for interacting in place and the promise of art in the not too distant future, I dived into the next major piece of the puzzle: the opponent player. As previously mentioned, I had already written some simple AIs for this game in C++, but a major unknown for me was Javascript performance. Would I be able to do a fully fledged AI, or would that result in the dreaded &#8220;<em>A script on this page may be busy, or it may have stopped responding</em>&#8221; message? I started by implementing a very simple non-searching opponent player strategy from the collection I had on the cppFIGHT repository, which worked, but with the game state updating the HTML immediately, tracking what was happening in the game was hard.</p>
<p>I spent about a week implementing a system for moving the coins (liner interpolation) to show the opponents moves, tidying up the code, testing and bug fixing before implementing any other AIs.</p>
<p>I then implemented 2 more rule-based AIs, the ones that eventually became the &#8220;Shipman&#8221; (easy) and &#8220;Ensign&#8221; (Normal) difficulties, along with support for AI vs AI matches and support for the human player to play 1st or 2nd, at either top or bottom position on the table.<br />
<div id="attachment_8812" class="wp-caption alignright" style="width: 310px"><a href="http://altdevblogaday.com/wp-content/uploads/2011/06/coin-mock-up-copy.jpg"><img class="size-medium wp-image-8812" src="http://altdevblogaday.com/wp-content/uploads/2011/06/coin-mock-up-copy-300x211.jpg" alt="Not the Mona Lisa." width="300" height="211" /></a><p class="wp-caption-text">1st mock up</p></div>It was at this point that Roger (the artist) suggested that the game should be played with a perspective effect so the player faces into the screen, with his opponent, a pirate, looking back out at him.  He sent me this mock up and I couldn&#8217;t help but agree that this was the way to go:</p>
<p>To implement the scaling, the coin &lt;div&gt; lost it&#8217;s background style and gained an <img alt="" />&lt;img&gt; tag, the click detection had to be modified to traverse the object graph and the new width (scale) had to be applied to the coin as it moved.  Determining the correct scale to create a perspective illusion was simply a matter mapping the coins position on the trapezoid of the table:</p>
<div>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="js" style="font-family:monospace;">function GetScaleOnTableAt( height )
{
	// where height = 0, result = TABLE_VERTICAL_RATIO
	// and where height = TABLE_HEIGHT, result = 1
	var v = 1.0 - TABLE_VERTICAL_RATIO;
	var f = height / TABLE_HEIGHT;
	return TABLE_VERTICAL_RATIO + f*v;
}</pre></td></tr></table></div>

</div>
<p>With the perspective effect proven, I decided that rather than rebuild the innerHTML for each game-state changing action, it would be better to manipulate the DOM to keep the HTML and game-state in sync. This gave a consistency of layout across turns that I think makes the game feel more &#8220;solid&#8221; and &#8220;physical&#8221; but bugs where the DOM didn&#8217;t match the game state were a major source of headaches for the remainder of the project.</p>
<p>Up to this point I&#8217;d done all of the development work using Safari as my test browser, so it was a huge surprise and a great relief to discover that I only had 2 minor issues to fix when I tested it in Firefox. One extra null check in the mouse event hander and a minor change to the CSS to anchor the img style with {top:0;left:0};.</p>
<p>Once the game worked in both Safari and Firefox it became clear that differences in browser rendering and Javascript performance meant a slightly more sophisticated approach to animation timing would be required to keep the movement speed of objects consistent. Changing the movement offset code (simplified here for brevity) from this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="js" style="font-family:monospace;">	var l = Math.sqrt(dx*dx + dy*dy)
	var ox = dx / l;
	var oy = dy / l;
&nbsp;
    	element.style.left = (left-ox) + 'px';
    	element.style.top = (top-oy) + 'px';</pre></td></tr></table></div>

<p>To this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="js" style="font-family:monospace;">	var t = new Date().getTime();
	var elapsed = (t - oldTime) / 10;
	oldTime = t;
&nbsp;
	var l = Math.sqrt(dx*dx + dy*dy);
	var ox = elapsed*dx / l;
	var oy = elapsed*dy / l;
&nbsp;
    	element.style.left = (left-ox) + 'px';
    	element.style.top = (top-oy) + 'px';</pre></td></tr></table></div>

<p>Over the next week I tested a lot and fixed minor bugs as I found them, but  my activity on the project was tailing off as I waited for the art to arrive.</p>
<p>Around halfway through the second month Roger sent me his first style-concept sketch:</p>
<div id="attachment_8859" class="wp-caption alignleft" style="width: 310px"><a href="http://altdevblogaday.com/wp-content/uploads/2011/06/Pirate_BG_03sepia.jpeg"><img class="size-medium wp-image-8859" src="http://altdevblogaday.com/wp-content/uploads/2011/06/Pirate_BG_03sepia-300x200.jpg" alt="Art Style / Concept Sketch" width="300" height="200" /></a><p class="wp-caption-text">Art Style / Concept Sketch</p></div>
<p>Around the same time I decided to implement support for the player to move back to the select game menu using the history.pushState / window.onpopstate API. This didn&#8217;t go well and ended up being replaced with the argument passing via the URL you see in the game now.</p>
<p>In the last week of the second month I split the opponent player code off into it&#8217;s own <a href="http://homepage.mac.com/codemonkey_uk/pennywise/ai.js">ai.js</a> file, and implemented an AI based on the MiniMax with AlphaBeta prune that I had implemented for cppFIGHT. I first implemented the MiniMax with game state copy-and-modify (without a prune), and timed it in each of Safari, Chrome, and Firefox. </p>
<blockquote><p><a href="http://twitter.com/#!/codemonkey_uk/status/68051249907511296">Mini Max implemented in Javascript, unpruned search to a depth of 4, timing results: Firefox = 224ms, Chrome = 306ms, Safari = 793ms.</a></p></blockquote>
<p>I then tested a speculative optimisation where the game state is not copied, but after each recursive step the move (a modification to the game state) that was begin evaluated was un-done. This proved to be more efficient in all 3 browsers, so I kept the change.</p>
<blockquote><p><a href="http://twitter.com/#!/codemonkey_uk/status/68055029109633024">Replaced creation of new game state per move with apply/undo logic: Firefox: 148ms, Chrome: 175ms, Safari: 424ms</a></p></blockquote>
<blockquote><p><a href="http://twitter.com/#!/codemonkey_uk/status/68057344973606912">Surprising twist in Javascript performance test, bump search depth to 5 and this happens: Chrome: 883ms, Firefox: 982ms, Safari: 2567ms.</a></p></blockquote>
<p>I then implemented the alpha beta prune, which gave an order-of-magnitude performance improvement and allowed the search to look enough moves ahead to provide an interesting challenge to most players.</p>
<blockquote><p><a href="http://twitter.com/#!/codemonkey_uk/status/68418514179997696">So, is it turns out an alpha beta prune is SUPER EFFECTIVE for this game. AI Decisions that took 2.5s now take 5ms. \o/</a>
</p></blockquote>
<p><strong>The Third (And Final) Month</strong><br />
It was at this stage I received the finished art and discovered I was on the receiving end of Roger&#8217;s wicked sense of humour. I was the pirate. Nice. I swallowed my pride, accepted looking silly on the internet is part of life now and got on with finishing the game.</p>
<p>Sorting out the layout to fit the new art, CSS changes and testing on multiple browsers took the best part of a week. At this stage of the project I was desperate to finish before I went on holiday and worked every evening. The biggest chunk of work came from the different sized coins in the final art, up to this point I had assumed all the coin types would be the same size on screen and had written most of the code with that assumption.</p>
<p>The following week was spent on fine tuning appearance and AI difficulty. Discovering the use of CSS and tiny divs to give non-rectangular text flow (for the scroll) was a great moment:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="js" style="font-family:monospace;">&lt;style&gt; .lW { float: left; clear: left; height: 16px; } &lt;/style&gt;
&lt;script&gt;
function InjectScrollFlowElements()
{
	var scrollDiv = document.getElementById('scroll');
	var innerHTML = scrollDiv.innerHTML;
	var prefix = &quot;&quot;;
	var th = 280;
	for(h=0;h&lt;th;h+=16)
	{
		prefix += &quot;&lt;div class='lW' style='width:&quot; + Math.floor(21*Math.sin(h/th*Math.PI)) + &quot;px;'&gt;&lt;/div&gt;&quot;;
	}
	scrollDiv.innerHTML = prefix + innerHTML;
}
&lt;/style&gt;</pre></td></tr></table></div>

<p>The last week before the &#8220;public release&#8221; of the game was mostly spent testing it and asking friends to try it out. The final code fix was a redesign and rewrite of how placing coins on top of each other, so that the hidden coin cannot be picked up, would be prevented by the game. The final Hg commit was a set of single pixel CSS layout adjustments.</p>
<p>After announcing the game on twitter I went on holiday for 10 days.</p>
<p>It being an HTML/CSS/JS game, the full source code is of course available if you are interested. I have left it uncompressed and unobsficated. The whole thing comes in at less than 2000 lines of (poorly written) code, including white space.</p>
<p><strong>Postscript</strong><br />
Since returning from my holiday I&#8217;ve added a &#8220;Tweet&#8221; button and a &#8220;Like&#8221; button, I also centred the whole game game in the browser window.</p>
<p>Using the &#8220;HTML5&#8243; toolset was an interesting learning experience. Javascript is a more powerful language than I was expecting, though I did miss certain C++ features, especially compile time diagnostics and strong typing!</p>
<p>I hope you&#8217;ve enjoyed reading this and I hope you enjoy the game. If you have any feedback on either, please feel free to comment below.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/06/18/the-making-of-pirate-pennywise/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Introducing Flexible Array Members</title>
		<link>http://www.altdevblogaday.com/2011/06/03/introducing-flexible-array-members/</link>
		<comments>http://www.altdevblogaday.com/2011/06/03/introducing-flexible-array-members/#comments</comments>
		<pubDate>Fri, 03 Jun 2011 20:00:36 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=6589</guid>
		<description><![CDATA[<p>The C99 standard officially introduced flexible array members. You may also know them as Unsized Arrays. They are a useful tool for any game programmer working in C or C++, who must take care of memory usage. Despite being over 10 years old, and a widely supported construct, usable in most C and C++ compilers, they are little used and less talked about. In this article I intend to introduce the reader to their proper use in C++.<br />
<span id="more-6589"></span><br />
To begin, consider this toy example class, that implements a pascal style string. Note: I have cut many C++ stylistic corners for the sake of brevity:</p>
<p><a href="http://www.altdevblogaday.com/2011/06/03/introducing-flexible-array-members/" class="more-link">Read more on Introducing Flexible Array Members&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>The C99 standard officially introduced flexible array members. You may also know them as Unsized Arrays. They are a useful tool for any game programmer working in C or C++, who must take care of memory usage. Despite being over 10 years old, and a widely supported construct, usable in most C and C++ compilers, they are little used and less talked about. In this article I intend to introduce the reader to their proper use in C++.<br />
<span id="more-6589"></span><br />
To begin, consider this toy example class, that implements a pascal style string. Note: I have cut many C++ stylistic corners for the sake of brevity:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">struct</span> PascalString
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">size_t</span> mLength<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> mBytes<span style="color: #008080;">;</span>
&nbsp;
    PascalString<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> c_string<span style="color: #008000;">&#41;</span>
        <span style="color: #008080;">:</span> mLength<span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">strlen</span><span style="color: #008000;">&#40;</span>c_string<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#41;</span>
        , mBytes<span style="color: #008000;">&#40;</span> <span style="color: #0000dd;">new</span> <span style="color: #0000ff;">char</span><span style="color: #008000;">&#91;</span>mLength<span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000dd;">memcpy</span><span style="color: #008000;">&#40;</span>mBytes, c_string, mLength <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    ~PascalString<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000dd;">delete</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> mBytes<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #666666;">// more stuff ...</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>The essence of this class is that it is a data structure that stores a pointer to a block of memory, and a count of how many elements there are in that data block. It also has construction and destruction behaviour implemented, so that the book keeping work of acquiring and releasing of the memory is handled automatically for users of the class.</p>
<p>An example of how this type might be used follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;">ostream<span style="color: #000040;">&amp;</span> operator<span style="color: #000080;">&lt;&lt;</span> <span style="color: #008000;">&#40;</span>ostream<span style="color: #000040;">&amp;</span> out, <span style="color: #0000ff;">const</span> PascalString<span style="color: #000040;">&amp;</span> s<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i<span style="color: #000080;">=</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>i<span style="color: #000040;">!</span><span style="color: #000080;">=</span>s.<span style="color: #007788;">mLength</span><span style="color: #008080;">;</span><span style="color: #000040;">++</span>i<span style="color: #008000;">&#41;</span>
        out <span style="color: #000080;">&lt;&lt;</span> s.<span style="color: #007788;">mBytes</span><span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">return</span> out<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> argc, <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span> argv<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    PascalString<span style="color: #000040;">*</span> p <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> PascalString<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Hello, World!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #000040;">*</span>p<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000dd;">delete</span> p<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Note that the object is created on the heap, and destroyed manually, with the &#8220;new&#8221; and &#8220;delete&#8221; operators. While for such a simple case p could have been a value object placed on the stack, the use pattern shown is more typical of production code, since the lifetime of game objects is usually more complex than this, and the allocations made are entirely relevant to the discussion!</p>
<p>So what&#8217;s wrong with this code? Nothing, really. It&#8217;s perfectly fine. If you are happy with the trade offs that have been made. The compromise implicit in the design.</p>
<p>This class trades space and time for simplicity of use and flexibility. This basic structure can be fleshed out to be a fully fledged <a href="http://en.wikipedia.org/wiki/Value_type">value type</a>. We could, from this starting point, implement assignment, concatenation, and so on and so forth.</p>
<p>These are perfectly fine trade offs, until they&#8217;re not. Optimisation is often about fitting the functionality implemented as tightly to the requirements as is feasible. If your data holding object is only created and interrogated, not modified (a situation that vastly more common in games development than is typically assumed), if the amount of data is known at the time the object is created, then the flexible array feature of C99 gives us a language level tool for creating code that more tightly fits that requirement.</p>
<p>Section 6.7.2.1, paragraph 16 of the C99 standard describes flexible arrays as follows:</p>
<blockquote><p>As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. However, when a . (or -&gt;) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.</p></blockquote>
<p>So instead of having a pointer as the last member of a struct, we can declare a flexible array member, like so:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">struct</span> PascalString
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">size_t</span> mLength<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">char</span> mBytes<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
    <span style="color: #666666;">// ...</span></pre></td></tr></table></div>

<p>The array at the end of the structure allows you to allocate a variable-sized block of memory in which to store the struct, and the array elements, thus avoiding the run-time execution cost of an extra pointer dereference.</p>
<p>If you apply the sizeof operator to this structure, the array adds nothing to it&#8217;s size (alignment padding not withstanding).  To get the true size of an object of this type, you need to consider the array size as well.</p>
<p>So now to complete the picture, we need to provide a new way to create and destroy objects of this type. Since the amount of memory required to allocate the struct itself now depends on the size of the data stored, and the compiler can&#8217;t rely on sizeof semantics, some of our construction logic has to be pulled outside the constructor, and the use of &#8220;new&#8221; and &#8220;delete&#8221; is no longer appropriate (you can make them private, to ensure they are never used &#8220;accidentally&#8221;):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;">    <span style="color: #666666;">// ...</span>
    <span style="color: #0000ff;">static</span> PascalString<span style="color: #000040;">*</span> Create<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> c_string<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// measure:</span>
        <span style="color: #0000ff;">size_t</span> length <span style="color: #000080;">=</span> <span style="color: #0000dd;">strlen</span><span style="color: #008000;">&#40;</span>c_string<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #666666;">// allocate enough memory for the &quot;struct&quot; and the data it manages, in one block:</span>
        PascalString<span style="color: #000040;">*</span> result <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>PascalString<span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span><span style="color: #0000dd;">malloc</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">sizeof</span><span style="color: #008000;">&#40;</span>PascalString<span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> length<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #666666;">// initialise the members </span>
        result<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>mLength <span style="color: #000080;">=</span> length<span style="color: #008080;">;</span>
        <span style="color: #0000dd;">memcpy</span><span style="color: #008000;">&#40;</span>result<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>mBytes, c_string, result<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>mLength <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">return</span> result<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Destroy<span style="color: #008000;">&#40;</span>PascalString<span style="color: #000040;">*</span> p_string<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000dd;">free</span><span style="color: #008000;">&#40;</span>p_string<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>Thus creation is changed for the user like so:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>10
11
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;">    <span style="color: #666666;">// PascalString* p = new PascalString(&quot;Hello, World!\n&quot;);</span>
    PascalString<span style="color: #000040;">*</span> p <span style="color: #000080;">=</span> PascalString<span style="color: #008080;">::</span><span style="color: #007788;">Create</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Hello, World!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>And destruction becomes:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>14
15
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;">    <span style="color: #666666;">// delete p;</span>
    PascalString<span style="color: #008080;">::</span><span style="color: #007788;">Destroy</span><span style="color: #008000;">&#40;</span> p <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>If you already hide your object lifetime management behind some kind of factory interface then there should be very little code to change. If on the other hand, your game is littered with calls to new and delete, then it&#8217;ll be more work to apply this optimisation.</p>
<p>So what benefits can we expect to see from a change like this? To demonstrate, I created a simple allocation tracker. For the trivial Hello World example, I got the following results: <em>Unoptimised, Cumulative &amp; Peak: 2 Allocations, 32 Bytes.<br />
With Flexible Array Optimisation, Cumulative &amp; Peak 1 Allocation, 32 Bytes.</em></p>
<p>So as expected, we have halved the number of allocations required to create objects of this type on the heap.  Given sizeof(PascalString) is 16 bytes unoptimised, and 8 bytes with flexible array, and that the string &#8220;Hello, World!\n&#8221; is 14 bytes long, we have also learnt that the allocator for my operating system appears to allocate in 16 byte blocks. </p>
<p>In order to give you a clearer picture I also wrote a test function that creates 1000 objects of various sizes and puts them into an array.  In this test the unoptimised version used 1032192 bytes, and the flexible array version used 1016192, a saving of roughly 2%. This measurement doesn&#8217;t include any savings in memory from the reduced allocation count, which depends very much on how your memory manager is implemented.  Allocator book keeping can be significant when working with small objects. Given the per-allocation overhead can be anywhere between 2 &#8211; 16 bytes (or more, but lets be reasonable here), the true savings in memory use are closer to 3%, or 32k.</p>
<p>Now just think what you could do with that extra 32k!</p>
<p>The cumulative <strong>time</strong> savings from reduced allocation count, and the improved <a href="http://en.wikipedia.org/wiki/Locality_of_reference">data locality</a> of keeping the count adjacent to the data in memory are left as an exercise for the reader.</p>
<p><em>Disclaimer: While the technique described in this article has been successfully applied as an optimisation in a production environment, and was a critical part of getting a game running inside the fixed memory limits of a console platform, please keep in mind the effectiveness of this approach is entirely dependant on the existing code base and data set. Your milage may vary.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/06/03/introducing-flexible-array-members/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Syd Sym Post-mortem</title>
		<link>http://www.altdevblogaday.com/2011/05/04/syd-sym-post-mortem/</link>
		<comments>http://www.altdevblogaday.com/2011/05/04/syd-sym-post-mortem/#comments</comments>
		<pubDate>Wed, 04 May 2011 08:00:15 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=5096</guid>
		<description><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/05/syd_sym_fb_ad.png"><img class="alignleft size-full wp-image-5107" style="border: 4px solid black" src="http://altdevblogaday.com/wp-content/uploads/2011/05/syd_sym_fb_ad.png" alt="Syd Sym" width="109" height="80" /></a>Today is the last day of my Apple Developer account being active.  I took the decision a month ago not to renew, so depending on the specific timings of this blog post, and the account expiring, you may or may not be too late to download my iPhone game, <a href="http://itun.es/i6n62n">Syd Sym</a>. As such, I thought now would be a good time to reflect on what went wrong, and why I&#8217;m glad I did it anyway.<span id="more-5096"></span><br />
Syd Sym is a real time single player &#8220;arcade&#8221; style puzzle/action game, in the spirit of Tetris, inspired by a turn based 2 player board game called &#8220;Entropy&#8221;. I started work on it early 2010, after getting an iPhone.</p>
<p><a href="http://www.altdevblogaday.com/2011/05/04/syd-sym-post-mortem/" class="more-link">Read more on Syd Sym Post-mortem&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/05/syd_sym_fb_ad.png"><img class="alignleft size-full wp-image-5107" style="border: 4px solid black" src="http://altdevblogaday.com/wp-content/uploads/2011/05/syd_sym_fb_ad.png" alt="Syd Sym" width="109" height="80" /></a>Today is the last day of my Apple Developer account being active.  I took the decision a month ago not to renew, so depending on the specific timings of this blog post, and the account expiring, you may or may not be too late to download my iPhone game, <a href="http://itun.es/i6n62n">Syd Sym</a>. As such, I thought now would be a good time to reflect on what went wrong, and why I&#8217;m glad I did it anyway.<span id="more-5096"></span><br />
Syd Sym is a real time single player &#8220;arcade&#8221; style puzzle/action game, in the spirit of Tetris, inspired by a turn based 2 player board game called &#8220;Entropy&#8221;. I started work on it early 2010, after getting an iPhone.</p>
<p>Given that I&#8217;m letting my developer account expire, you may have already concluded that the game was not a run away smash hit, and you&#8217;d be right. The paid version is bought, on average, just under once per week, and the free version (with iAds) is downloaded around 100 times per week. The iAds earn me around $6 a month. After developer fees and incidental costs, the game made me a grand total of £58.78 gross profit last year.</p>
<p>&nbsp;</p>
<p>But the App Store is supposed to be a gold mine! Free money for developers! What went wrong? Why aren&#8217;t I writing this on a sold-gold laptop and wearing a money hat?</p>
<ol>
<li>I was too slow. I missed the gold-rush. The development itself wasn&#8217;t particularly drawn out, but I really didn&#8217;t even start until the iOS game scene was already well established. At the time I released Syd Sym, I am told, there were literally hundreds of new apps released every single day.</li>
<li>I massively underestimated the effort required to market a game on iOS. As a behind the scenes game programmer I had no industry press contacts to lean on (and still don&#8217;t really). Getting reviews was excruciating. I sent out hundreds of emails, and was largely ignored, an experience I found almost monumentally frustrating. I doubt most of my press releases, review requests, tweets, forums posts, and begging emails were even read. I do of course understand why, 100s of new games a week, most of them rubbish. Why expect mine to be any different? I actually still don&#8217;t really know what I could or should have done differently to get any attention, but there you go.</li>
<li>The first review had a damning headline, and stayed at the top of the google search for the game for a long time. I&#8217;m not sure that really was something I did wrong (Because I released too soon? Bad press-releations? Poor SEO skills?) but it still sucked.</li>
<li>The game was, in all honesty, a poor fit for the way people play iPhone games. It simply takes too long to finish &#8220;one game&#8221;. It may be crude, but if you can&#8217;t play one &#8220;round&#8221; of an iOS game in the time it takes to poop, then you won&#8217;t be a hit.</li>
<li>What the game <em>was</em> was too open, and thus confusing for many players. I had done my best to make the game &#8220;easy to play, hard to master&#8221;, but since a play through of the game takes a long time relative to what&#8217;s expected on iOS, I think a lot of people only saw the &#8220;easy to play&#8221; bit (passing levels), and missed the deeper strategies required to master the high score tables.</li>
<li>The collect&#8217;em&#8217;up replay value aspect of the game was too subtle, and since early versions of the game only told you how many combos you had collected, with no way to see which ones you&#8217;d got already, this aspect of the game was overlooked.</li>
<li>The tutorial was too hard. Many players could not get past the last level of the tutorial, and thus failed to unlock the full game. Even after realising this, I failed to settle on a solution I liked, so the problem was never fixed.</li>
<li>I localised too soon, leaning on friends around the world to translate the game text left me in an awkward situation with putting out updates that added too or modified in game text, which discouraged me from iterating on in game messages, help text and tutorials, and left me locked in to design and UI choices I had made early on for fear of having to remove a localisation.</li>
<li>I bought Facebook Ads. At first it seemed like a hilarious free win, since you pay for clicks not page views, and I got thousands of page views for almost nothing. But actually, in retrospect, I&#8217;m fairly sure that it was a stupid waste of money, and didn&#8217;t result in a single additional sale.</li>
<li>I made two versions, a paid download and a free version.  In retrospect I probably should have made it free, with in-app-purchises (or maybe just accepted it as loss-making hobby project, and kept it 100% free).</li>
</ol>
<p>An utter disaster, right? Not really, in all honesty, I am glad I did it, and may make another iOS game in the future. So what went right? This list is, I must admit, more &#8220;why I&#8217;m glad I made it&#8221; than &#8220;the things I did right in making it&#8221;, but I hope it&#8217;s useful or interesting anyway:</p>
<ol>
<li>I kept my costs absolutely rock bottom, and didn&#8217;t quit the day job. Even with the lacklustre reception, I avoided losing my shirt by keeping it a hobby project.</li>
<li>I had fun, it was interesting, and entertaining, and the time spent developing Syd Sym pretty much weened me off of my WoW habit.</li>
<li>I got interviewed by <a href="http://www.joystiq.com/2010/08/11/the-joystiq-indie-pitch-syd-sym/">Joystiq</a>.</li>
<li>The game got more positive reviews than negative reviews.</li>
<li>I made something that someone really liked. I know this, because the top high score on game centre requires frankly surprising level of dedication to achieve.</li>
</ol>
<p>Over all, although I can identify more &#8220;bad&#8221; things than &#8220;good&#8221; things, it was a worthwhile experience, and a game I&#8217;m glad I made. I am not sworn off of iOS or mobile at all, but I&#8217;m trying to explore and learn new things, so for now (in my hobby-time) I&#8217;ll be focusing on my writing here, and finishing my browser hosted html/javascript game.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/05/04/syd-sym-post-mortem/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Three Tools I Love (And So Should You)</title>
		<link>http://www.altdevblogaday.com/2011/04/19/three-tools-i-love-and-so-should-you/</link>
		<comments>http://www.altdevblogaday.com/2011/04/19/three-tools-i-love-and-so-should-you/#comments</comments>
		<pubDate>Tue, 19 Apr 2011 10:30:29 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=4217</guid>
		<description><![CDATA[<p>This week I have written a short post to share with you some tools that I use daily, but that are perhaps are less well known than they deserve to be: MetalScroll, Beyond Compare &#38; Code Collaborator.<br />
<span id="more-4217"></span></p>
<p><a href="http://www.altdevblogaday.com/2011/04/19/three-tools-i-love-and-so-should-you/" class="more-link">Read more on Three Tools I Love (And So Should You)&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>This week I have written a short post to share with you some tools that I use daily, but that are perhaps are less well known than they deserve to be: MetalScroll, Beyond Compare &amp; Code Collaborator.<br />
<span id="more-4217"></span></p>
<h2>MetalScroll</h2>
<p><a href="http://code.google.com/p/metalscroll/">http://code.google.com/p/metalscroll/</a><br />
MetalScroll is a free Visual Studio add-in which replaces the editor scrollbar with a graphic representation of the code. When working on my Laptop, (a PowerBook running OS X), using XCode or TextWrangler, this is without a doubt, the single thing I miss the most.</p>
<h2>Beyond Compare</h2>
<p><a href="http://www.scootersoftware.com/">http://www.scootersoftware.com/</a><br />
Beyond Compare is a file diff/merge tool for windows that I discovered whilst working on the GTA &#8220;Double Pack&#8221;, work that, for various reasons, involved a lot a diffing and merging of sections of large codebases. Despite the abundance of free and commercial tools that provide equivalent functionality, many of which I&#8217;ve tried at various times, Beyond Compare has been my 1st choice for heavy duty diff/and merge jobs for over 5 years. Highly recommended. Also pure gold for log file post-mortum work, handling even very large files without a hiccup.</p>
<h2>Code Collaborator</h2>
<p><a href="http://smartbearsoftware.co.uk/codecollab.php">http://smartbearsoftware.co.uk/codecollab.php</a><br />
Code Collaborator is a web based tool for performing and managing code reviews. If you have ever thought code reviews sound like a good idea, but that the gritty details of managing the whole process get in the way, then this tool is well worth investigating.</p>
<p><p>
<em>Why not post a comment telling us about the tools that make your life easier.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/04/19/three-tools-i-love-and-so-should-you/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Water Off A Duck&#8217;s Back</title>
		<link>http://www.altdevblogaday.com/2011/04/04/water-off-a-ducks-back/</link>
		<comments>http://www.altdevblogaday.com/2011/04/04/water-off-a-ducks-back/#comments</comments>
		<pubDate>Mon, 04 Apr 2011 00:00:07 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=2758</guid>
		<description><![CDATA[<p>Critics, eh? Where would the games industry be without them? Well, that might be a good topic for a rant, but what I want to waffle on about today is how we as developers deal with criticism.</p>
<p><a href="http://www.altdevblogaday.com/2011/04/04/water-off-a-ducks-back/" class="more-link">Read more on Water Off A Duck&#8217;s Back&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Critics, eh? Where would the games industry be without them? Well, that might be a good topic for a rant, but what I want to waffle on about today is how we as developers deal with criticism.</p>
<p>It&#8217;s a tough world out there. People are not nice.<br />
<span id="more-2758"></span></p>
<blockquote><p>You&#8217;ll feel as if you&#8217;re waging war on the set of The Muppet Show.</p></blockquote>
<blockquote><p>If you think this sounds a bit repetitive, you&#8217;re right…</p></blockquote>
<blockquote><p>The texture work is blurred and repetitive. The game is saturated by grays. The particle system is lacking. The lighting effects are underdeveloped.</p></blockquote>
<blockquote><p>I’ve been playing it for over an hour nonstop and I just don’t get it.</p></blockquote>
<blockquote><p>In times like this there aren&#8217;t just a lack of words at the situation, but a lack of faith in people, because whatever shit-hole idea you think you can attach to a license in order to gain revenue, it&#8217;s nothing compared to what game devs that will do anything for a dollar are capable of.</p></blockquote>
<p>All quotes from reviews of games I&#8217;ve worked on. Were those comments fair? Some of them, to an extent. In their own way. As hard as it can be to swallow, there are lessons to be learnt from all criticism. Even if you don&#8217;t always agree with it.</p>
<div id="attachment_2764" class="wp-caption alignleft" style="width: 190px"><img class="size-medium wp-image-2764  " src="http://altdevblogaday.com/wp-content/uploads/2011/04/duck-300x232.jpg" alt="A Duck" width="180" height="139" /><p class="wp-caption-text">A Duck</p></div>
<p>If you can&#8217;t look back at your past self, and shake your head in disapproval of your own naïvety… If you can&#8217;t look back on your older work, and know with confidence what you did wrong… and what you&#8217;d do differently next time, then you are not growing. You are not advancing in your art. If you don&#8217;t swim, eventually you sink.</p>
<p>Recognising your own mistakes, and learning from them, is how one improves. Criticism provides vital feedback, points to consider. You don&#8217;t have to take it personally, but do take it to heart so you can learn from it.</p>
<p>One of the differences, I think, that sets the triple-A studios apart is their ability to self criticise, and their refusal to accept anything less than the best for their games. To survive working in a top studio, to be able to make the best of the best games, means having the strength to accept criticism as an important part of a positive feedback loop. Get rid of the crap, and what you&#8217;ve got left at the end, if there is anything left, must be good.</p>
<p>But if you can&#8217;t handle being told when your shit stinks, you are in the wrong industry. Round these parts you could be pooping rainbows and someone is going to tell you that your rainbow excretions are the worst they have ever seen.</p>
<p>So suck it up. Take it in. But don&#8217;t let it get you down. Criticism, like water off a ducks back. But you know what? Ducks also swim on water. Without it, they&#8217;d just be waddling around. The ducks need the water, and we need to accept that criticism is an important part of the process.</p>
<p>Now, before I sign off there is one last thing I want to talk about: <a title="Metacritic" href="http://www.metacritic.com/">Metacritic</a>.</p>
<p>Last week metacritic showcased a new feature, they added a developer&#8217;s career score. Then retracted it the next day<sup><a href="http://www.escapistmagazine.com/news/view/108808-Metacritic-Adds-Then-Pulls-Developer-Review-Scores">[1]</a></sup>. I was not, and am still not, so sure how to feel about that. Many developers will work on games that review badly at some point in their career, and often a game will review badly for reasons completely out of the individual&#8217;s control. Given the weight that the industry already places on metacritic scores, is it reasonable to meta-score individual developers? Probably not. After all, the industry is already struggling with the growing disconnect between what the core gaming reviewers want from a game, and what the average (read: casual/social) gamer wants. Adding a further incentive to pander the critics, or encouraging people to &#8220;Alan Smithee&#8221; their involvement with a project they&#8217;re not sure will review well, is probably not a healthy move for the future of games.</p>
<p><em>If this subject interests you, you may also enjoy reading Nicholas Lovell&#8217;s &#8220;</em><a href="http://www.gamesbrief.com/2011/03/what-jacqueline-howetts-professional-self-immolation-can-teach-us-all"><em>What Jacqueline Howetts Professional Self-Immolation Can Teach Us All</em></a><em>&#8220;.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/04/04/water-off-a-ducks-back/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>So You Wanna Be a Senior?</title>
		<link>http://www.altdevblogaday.com/2011/03/20/so-you-wanna-be-a-senior/</link>
		<comments>http://www.altdevblogaday.com/2011/03/20/so-you-wanna-be-a-senior/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 00:00:14 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=2010</guid>
		<description><![CDATA[<p>So you&#8217;ve been in the industry a few years, maybe even shipped a few games, and you&#8217;re thinking: <em>It&#8217;s about time I got a promotion</em>. Or maybe you&#8217;ve seen a job ad, and they&#8217;re looking for a senior in your discipline, and you&#8217;re thinking: <em>I could do that</em>.</p>
<p><a href="http://www.altdevblogaday.com/2011/03/20/so-you-wanna-be-a-senior/" class="more-link">Read more on So You Wanna Be a Senior?&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>So you&#8217;ve been in the industry a few years, maybe even shipped a few games, and you&#8217;re thinking: <em>It&#8217;s about time I got a promotion</em>. Or maybe you&#8217;ve seen a job ad, and they&#8217;re looking for a senior in your discipline, and you&#8217;re thinking: <em>I could do that</em>.</p>
<p>Well, it probably is, and you probably could. But what does &#8220;senior&#8221; mean in a job title these days? What do employers mean, what do they expect, when they say that they&#8217;re hiring a senior developer?<br />
<span id="more-2010"></span><br />
This post was inspired by a question posted to a mailing list, that asked: &#8220;Senior X Developer, what does Company Y expect?&#8221;. Also, two of the guys I work with recently got the &#8220;senior&#8221; promotion.  Congratulations to both of them. But anyway, I&#8217;d like to try to answer that question for X = Game. I&#8217;ll keep the general stuff at the start, so designers and artists can stop reading when I get to the programming specific bits.</p>
<p>Please keep in mind, what is written here is my personal opinion only. I have been on both sides of the interview process, at a few different organisations, but my observations here do not represent the official policies of any of my employers, past or present.</p>
<p>Now, any company worth it&#8217;s salt will be looking for the magic combination, so eloquently summarised by Spolsky in his <a href="http://www.joelonsoftware.com/articles/fog0000000073.html">Guerrilla Guide to Interviewing</a>: Smart and Get&#8217;s Things Done. That, as they say, is the magic ingredient, but it&#8217;s not what makes someone senior. It may be what keeps them in a job long enough to become senior, but it&#8217;s not a defining characteristic of seniority.</p>
<p>In the games industry, at least, what is expected of a senior developer is <em>experience</em>. The real question of course, is how experienced. According to the <a href="http://www.tiga.org/PressReleaseDetail.aspx?id=f09a5b38-24ad-4c65-9ee4-7a02b152ec45">2010 Tiga Industry Salary Survey</a>, the average length of service for a game developer is between 7 and 10 years. While it&#8217;s not impossible to gain the title of senior after as little as 2 years, and one completed project, 4 or more years industry experience, with 2 or more shipped games is more in line what what seems to be expected.</p>
<p>Beyond the requirement of time done, the question then becomes, what will you have been expected to learn in that time, because the value of time accumulated doing the job comes from the lessons learnt, and experience gained.</p>
<p>A senior developer needs to talk-the-talk and walk-the-walk. This means, beyond doing their job, completing the tasks assigned to them by their lead, a senior is usually expected to have a basic understanding of how developer/publisher relationships work, and how the the roles of art, design, programming, &amp; management typically work together to produce a finished game.</p>
<p>A senior developer should have had some experience of a full development cycle, from pre-production, through production, alpha, beta, and delivering a final finished master for publication.</p>
<p>A senior developer (of any discipline) will be expected to have a grasp of what it means to work with a version control system, usually one of P4, Subversion, or AlienBrain.</p>
<p>A senior hire may also be expected to have had some experience with planning &amp; scheduling (at the least, task estimation), producing documentation, and mentoring or lead work.</p>
<p>For programmers (designers and artists can skip to the end now, if they like), seniority tends to imply a greater breadth of experience (unless the title gives specific sub domain, like Senior <em>Physics</em> Programmer, or Senior <em>AI</em> Programmer &#8211; that usually just means you can get that specific job done without any hand holding from your lead). A senior programmer will usually be expected to have worked on more than one platform (hardware or middleware), or have shipped games in more than one genre. More than one programming language may also be expected (think, C++ plus one of C#, Java[script], Lua, Python, Action Script, Objective C, a HLSL or other GPU/SPU programming).</p>
<p>So, if you can comfortably tick off most of those expectations, then you are probably ready. It&#8217;s time to do it. Go and tell your boss it&#8217;s time for that Senior title, or apply for that new job. You deserve it. Do it now. Do it while it still means something.</p>
<p>Photograph (c) Étienne Ljóni Poisson</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/03/20/so-you-wanna-be-a-senior/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Check Yourself</title>
		<link>http://www.altdevblogaday.com/2011/03/05/check-yourself/</link>
		<comments>http://www.altdevblogaday.com/2011/03/05/check-yourself/#comments</comments>
		<pubDate>Sat, 05 Mar 2011 08:00:35 +0000</pubDate>
		<dc:creator>Thaddaeus Frogley </dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=1431</guid>
		<description><![CDATA[<p>The detection and handling of errors and unexpected conditions during game development can be a surprisingly complicated and controversial topic. In this post I hope to help programmers understand the range of problems, the tools available, and how to apply them.</p>
<p><a href="http://www.altdevblogaday.com/2011/03/05/check-yourself/" class="more-link">Read more on Check Yourself&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>The detection and handling of errors and unexpected conditions during game development can be a surprisingly complicated and controversial topic. In this post I hope to help programmers understand the range of problems, the tools available, and how to apply them.</p>
<p><span id="more-1431"></span><strong><em>Expect The Unexpected</em></strong></p>
<p>Before you start, you need to think carefully about what you are trying to do. What problem is it you need to solve? Is it just one problem? Or is it several different problems? How are they different? How are they similar? I have found that there are five broad types of errors that programming teams should be aware off so that they can be actively detected and handled.</p>
<p><strong>Programming Mistakes</strong></p>
<p>Nobody is perfect. Everybody makes mistakes. Even programmers<sup><a href="#foot1">1</a></sup>. We make assumptions about how things work, and write code based on those assumptions. When the assumptions are wrong, the game doesn’t work as intended. In order to ship a game that doesn’t crash, we must find the mistakes, and fix them. The team also needs a regularly updated version of the work in progress so that the content team can work. Ideally all programming mistakes will be eliminated before a build is even distributed to the designers and artists. Let me be clear on one point: <em>A “broken” build distributed to  the whole team can halt productive work in its tracks and cost your employer tens of, if not hundreds of, thousands of pounds<sup><a href="#foot2">2</a></sup>.</em> When an error is detected that will crash or otherwise break the game, a programmer will need to investigate, debug and fix the problem.</p>
<p><strong>Game Data Problems</strong></p>
<p>For the game to load and run, the data assets (art, levels, scripts, and so on) must be present and in the formats expected by the game. During development game data problems should be detected and reported clearly so that developers (artists, level designers, etc) can fix them independently. Having the build crash because an asset is broken most likely means that a content creator has to stop what they are doing and ask a programmer for help. The programmer may well have to get a copy of the artist’s local work, and debug it at their own machine. This is not a cost effective way to work. What’s worse though, is that an undetected error in an asset that has been checked into the build can be just as devastating to the teams productivity as broken code build. However, error messages of the kind we need during development are not appropriate for a shipping build<sup><a href="#foot3">3</a></sup>.</p>
<p><strong>Save File and User Created Content Hack Protection</strong></p>
<p>Any data loaded by the system should not be trusted, be it save game files or user created content. If you want to get certified for publication on any of the closed console platforms, or indeed, simply wish to prevent save-edit cheating and exploits in general, you need to create a game-save &amp; load system that is robust against malicious modification. This must work and be present in a shipping build.</p>
<p><strong>Bad Disk Errors</strong></p>
<p>File IO errors must not be ignored, and indeed, must be handled in very specific ways on the console platforms for a game to be certified for publication. In addition to checking success and failure, all data loaded should be validated to ensure it is as expected and will not crash the engine. As with save hack protection, loading IO handling must be present in your shipping build.</p>
<p><strong>Lost Network Connections</strong></p>
<p>Network IO errors must be handled gracefully, and as with save game data, it cannot be assumed that network packets are arriving as they were sent, so must be validated and checked to prevent cheating. This is especially important for multiplayer PC games operating over the internet.</p>
<p><strong><em>The Tools Of The Trade</em></strong></p>
<p>Please note, I will not be discussing development <em>processes</em> that are designed to improve quality and reduce mistakes. While techniques such as Code Review, Test Driven Development, and/or Pair Programming can help with the early detection and prevention of programming mistakes, and in improving code quality, they will not be covered here.</p>
<p><strong>Assertions</strong></p>
<p>Assertions both document and check at runtime the assumptions made by a programmer.  They are placed in the code at the point where, should those assumptions be incorrect, the program will fail. As such, they should be simple, fast and free from side effects. Usually they check function pre &amp; post conditions, and class invariants. It is usual for game engines to define their own assertion macro(s). The canonical assertion macro accepts one argument, and checks if it is true, then calls an error handler if not. Mature engines can end up with some remarkably complex assertion failure behaviour. They can stack trace, screen dump, attach to a bug database over the network or simply stop in the debugger. The assertion error handling behavior can change with the requirements of the team, and can have (or not have) whatever you think is useful<sup><a href="#foot4">4</a></sup>. The macro <em>usually</em> looks <em>something</em> like this:</p>
<p><strong> </strong></p>
<pre escaped="true" lang="C++" line="1">#ifdef MY_ASSERT_ENABLED
#define MY_ASSERT( c ) \
{if (!(c)){MyAssertHandler(#c,__FILE__,__LINE__);}}
#else
#define MY_ASSERT( c ) ;
#endif</pre>
<p><strong> </strong></p>
<p>Note that assertions are usually turned off in shipping builds, and may also be turned off in builds intended for artist &amp; level designers use. As such, assertion statements should never include code that actually does something.</p>
<p><strong>Unit Tests</strong></p>
<p>Unit tests, like assertions, check that the code does what the programmer expects it to do. Also like assertions, unit tests function as a form of documentation, showing by example the correct use of interfaces and data structures. Unlike assertions, however, unit tests are not part of the running game executable, and are instead compiled into a “test harness” which is then executed as part of the build process. Unit tests provide a certain amount of guaranteed code coverage, and reduce the risk involved in modifying the code.</p>
<p>This decoupling of test and execute is elegant, and can ensure that corner cases that may be not be checked by assertions during a normal run, are definitely checked every time the game is built.</p>
<p>On the other hand, unit tests do not catch incorrect use of an API, or anything that the test authors didn’t think of that might go wrong at runtime.</p>
<p>The difference between unit tests and assertions can be summed up by saying: Unit Tests test that your code does what you expect it to do when it is used as you designed it to be used. Whereas Assertions check that your code is being used as you designed it to be used and that the rest of the application is doing the things you expected it to do.</p>
<p><strong>Data Validation and Reporting</strong></p>
<p>Data validation and error reporting is <em>simply a matter of programming</em>. That said, having a clear architecture decision made about where in the code the validation checks should appear, and how they should be reported is vital to avoiding a proliferation of redundant checking in code. You should check the data that comes into the engine, and you should have a strategy in place for reacting to the unexpected in an appropriate manner.</p>
<p><strong>Defensive Programming</strong></p>
<p>Defensive programming is the practice of assuming that the things that can (and can’t) go wrong will go wrong, and attempting to carry on regardless. At the core of the defensive programming philosophy is the idea that it is reasonable to sacrifice performance for the sake of stability. This is an anathema to many games programmers, and I would strongly advise against belt-and-braces code that combines assertions with defensive programming, often seen like so:</p>
<p><strong> </strong></p>
<pre escaped="true" lang="c++" line="1">assert( pObj );
if ( pObj ) {
// ...
}</pre>
<p><strong> </strong></p>
<p>In this case the assertion is redundant, since the null pointer case is in fact handled, so including an assertion to check for it should not be necessary. Assertions and Defensive Programming do not go hand in hand. The more you have of one, the less you should see of the other.</p>
<p>That said, coding defensively should not be rejected out of hand, especially where the productivity of the content creators may be negatively affected. Implementing coherent strategy for defensive handling data errors that allows the game to continue after a data error has been reported is usually time well spent.</p>
<p><strong>Advice</strong></p>
<p>So, having outlined the different problems, and the usual tools, what now? If you’ve got this far without falling asleep you are probably expecting some advice from me. So here are my top 10 tips for dealing with errors:</p>
<ol>
<li>Think about the problems you are trying to solve for your project, and the consequences of each solution on your team and your customers. This point overrides anything else I might suggest.</li>
<li>Accept that there are several types of error that you are interested in detecting and reporting. Treat each one separately. Do not try to create a one-size-fits-all solution.</li>
<li>Use Assertions and Unit Tests to detect programming errors. A bug caught by an assertion or a failed unit test is a bug you’ve caught early, and a core dump you are not downloading from your QA outsource provider at 1am.</li>
<li>Use assertions to check that your code is being used as you designed it to be used and that the rest of the application is doing the things you expect it to be doing.</li>
<li>Use Unit Tests to test that your code does what you want it to do and to provide examples of how the interfaces you have written are intended to be used.</li>
<li>Create separate build configurations for each of: Debugging, Content Checking and Shipping. Programmers should use a debugging build, content creators should use a content checking build and the shipping build is what you intend on giving to your customer(s).</li>
<li>Create a mechanism for reporting problems with textures, meshes and other loaded data, that can be understood by an artist, and make sure that it is used consistently. Do not use assertions to check loaded content and do not provide data-loading APIs that allows errors to be ignored.</li>
<li>Try to avoid content errors from being fatal. If a texture or mesh is in some way un-loadable, have the loading code return a default object after reporting the error.</li>
<li>Content Checking, Bad Disk and Save Hack detection may be very similar in the things they check, but how the build responds to problems once detected should differ greatly, depending on the context. Where the content error messages are not appropriate for a shipping build, the content checking error handler in a shipping build can route to the bad-disk handler for an extra layer of game hack protection.</li>
<li>Trust no data that can be tampered with, use encryption and/or checksums to prevent and detect tampering (the platform SDK likely provides functions specifically for this), but even after validating checksums, sanity check everything and have the code handle gracefully (ignore or report) anything that could break your game.</li>
</ol>
<p><strong>Related Articles On #AltDevBlogADay</strong></p>
<p>If this topic interests you, you may also enjoy:</p>
<ul>
<li><a href="http://altdevblogaday.com/2011/02/25/do-or-do-not-2/">Do or do not</a> by Paul Evans.</li>
<li><a href="http://altdevblogaday.com/2011/02/16/elegance-in-failure-how-and-when-to-crash-horribly/">Elegance in Failure: How and when to crash horribly</a> by Ben Carter.</li>
<li><a href="http://altdevblogaday.com/2011/02/07/debugging-tools/">Debugging Tools</a> by Justin Liew.</li>
<li><a href="http://altdevblogaday.com/2011/01/28/the-pain-of-debuggery/">The Pain Of Debuggery</a> by Tony Albrecht.</li>
<li><a href="http://altdevblogaday.com/2011/01/25/tips-and-tricks-for-debugging-optimized-code/">Tips and Tricks for Debugging Optimized Code</a> by Max Burke.</li>
<li><a href="http://altdevblogaday.com/2011/01/17/why-names-matter/">Why Names Matter</a> by Ben Carter.</li>
</ul>
<p><strong>With Thanks</strong></p>
<p>To Bjoern Knafla, Richard Fine and Andrea Frogley for proof reading and wonderful editorial feedback.</p>
<p><strong>Fin</strong></p>
<p>If you have any questions about this article, please feel free to post them in the comments section below, or ask me on twitter <a href="http://twitter.com/codemonkey_uk">@codemonkey_uk</a>.</p>
<p><strong>Footnotes</strong><br />
<a id="foot1">1</a> But don’t go telling any artists I said that.<br />
<a id="foot2">2</a> Or dollars. Or euros. Or Yen. Or whatever. Lots of money.<br />
<a id="foot3">3</a> The exception to this being PC games that actively support a modding community.<br />
<a id="foot4">4</a> Except a “Skip” or “Ignore” button &#8211; if you add that, then you’re not thinking. An assertion states what the programmer knows to be true. If an assertion fails then all bets are off and the toys should leave the pram.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/03/05/check-yourself/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.594 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-17 03:27:16 -->
<!-- Compression = gzip -->
