<?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</title>
	<atom:link href="http://www.altdevblogaday.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.altdevblogaday.com</link>
	<description>Each day a little more #gamedev love</description>
	<lastBuildDate>Sun, 20 May 2012 20:56:17 +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>That&#8217;s Not Normal&#8211;the Performance of Odd Floats</title>
		<link>http://www.altdevblogaday.com/2012/05/20/thats-not-normalthe-performance-of-odd-floats/</link>
		<comments>http://www.altdevblogaday.com/2012/05/20/thats-not-normalthe-performance-of-odd-floats/#comments</comments>
		<pubDate>Sun, 20 May 2012 20:51:25 +0000</pubDate>
		<dc:creator>Bruce-Dawson</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[denormal]]></category>
		<category><![CDATA[floating point]]></category>
		<category><![CDATA[infinity]]></category>
		<category><![CDATA[NaN]]></category>
		<category><![CDATA[special numbers]]></category>
		<category><![CDATA[specials]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26308</guid>
		<description><![CDATA[<p>Denormals, NaNs, and infinities round out the set of standard floating-point values, and these important values can sometimes cause performance problems. The good news is, it’s getting better, and there are diagnostics you can use to watch for problems.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/20/thats-not-normalthe-performance-of-odd-floats/" class="more-link">Read more on That&#8217;s Not Normal&#8211;the Performance of Odd Floats&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Denormals, NaNs, and infinities round out the set of standard floating-point values, and these important values can sometimes cause performance problems. The good news is, it’s getting better, and there are diagnostics you can use to watch for problems.</p>
<p>In this post I briefly explain what these special numbers are, why they exist, and what to watch out for.</p>
<p><span id="more-26308"></span>
<p>This article is the last of my series on floating-point. The complete list of articles in the series is:</p>
<ul>
<ul>
<li>1: <a href="http://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/">Tricks With the Floating-Point Format</a> – an overview of the float format </li>
<li>2: <a href="http://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/">Stupid Float Tricks</a> – incrementing the integer representation of floats </li>
<li>3: <a href="http://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/">Don’t Store That in a Float</a> – a cautionary tale about time </li>
<li>3b: <a href="http://randomascii.wordpress.com/2012/02/11/they-sure-look-equal/">They sure look equal…</a> – special bonus post (not on altdevblogaday) </li>
<li>4: <a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/">Comparing Floating Point Numbers, 2012 Edition</a> – tricky but important </li>
<li>5: <a href="http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/">Float Precision—From Zero to 100+ Digits</a> – what does precision mean, really? </li>
<li>5b: <a href="http://randomascii.wordpress.com/2012/03/11/c-11-stdasync-for-fast-float-format-finding/">C++ 11 std::async for Fast Float Format Finding</a> – special bonus post (not on altdevblogaday) on fast scanning of all floats </li>
<li>6: <a href="http://randomascii.wordpress.com/2012/03/21/intermediate-floating-point-precision/">Intermediate Precision</a> – their effect on performance and results </li>
<li>7.0000001: <a href="http://randomascii.wordpress.com/2012/04/05/floating-point-complexities/">Floating-Point Complexities</a> – a lightning tour of all that is weird about floating point </li>
<li>8: <a href="http://randomascii.wordpress.com/2012/04/21/exceptional-floating-point/">Exception Floating point</a> – using floating-point exceptions to find bugs </li>
<li>9: That’s Not Normal–the Performance of Odd Floats </li>
</ul>
</ul>
<p>The special float values include:</p>
<h2>Infinities</h2>
<p>Positive and negative infinity round out the number line and are used to represent overflow and divide-by-zero. There are two of them.</p>
<h2>NaNs</h2>
<p>NaN stands for Not a Number and these encodings have no numerical value. They can be used to represent uninitialized data, and they are produced by operations that have no meaningful result, like infinity minus infinity or sqrt(-1). There are about sixteen million of them, they can be signaling and quiet, but there is otherwise usually no meaningful distinction between them.</p>
<h2>Denormals</h2>
<p>Most IEEE floating-point numbers are normalized – they have an implied leading one at the beginning of the mantissa. However this doesn’t work for zero so the float format specifies that when the exponent field is all zeroes there is no implied leading one. This also allows for other non-normalized numbers, evenly spread out between the smallest normalized float (FLT_MIN) and zero. There are about sixteen million of them and they can be quite important.</p>
<p>If you start at 1.0 and walk through the floats towards zero then initially the gap between numbers will be 0.5^24, or about 5.96e-8. After stepping through about eight million floats the gap will halve – adjacent floats will be closer together. This cycle repeats about every eight million floats until you reach FLT_MIN. At this point what happens depends on whether denormal numbers are supported.</p>
<p>If denormal numbers are supported then the gap does not change. The next eight million numbers have the same gap as the previous eight million numbers, and then zero is reached. It looks something like the diagram below, which is simplified by assuming floats with a four-bit mantissa:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image18.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb18.png" width="694" height="145" /></a></p>
<p>With denormals supported the gap doesn’t get any smaller when you go below FLT_MIN, but at least it doesn’t get larger.</p>
<p>If denormal numbers are not supported then the last gap is the distance from FLT_MIN to zero. That final gap is then about 8 million times <em>larger</em> than the previous gaps, and it defies the expectation of intervals getting smaller as numbers get smaller. In the not-to-scale diagram below you can see what this would look like for floats with a four-bit mantissa. In this case the final gap, between FLT_MIN and zero, is sixteen times larger than the previous gaps. With real floats the discrepancy is much larger:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image19.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb19.png" width="692" height="144" /></a></p>
<p>If we have denormals then the gap is filled, and floats behave sensibly. If we don’t have denormals then the gap is empty and floats behave oddly near zero.</p>
<h2>The need for denormals</h2>
<p>One easy example of when denormals are useful is the code below. Without denormals it is possible for this code to trigger a divide-by-zero exception:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">float</span> GetInverseOfDiff<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">float</span> a, <span style="color: #0000ff;">float</span> b<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>a <span style="color: #000040;">!</span><span style="color: #000080;">=</span> b<span style="color: #008000;">&#41;</span>
        <span style="color: #0000ff;">return</span> <span style="color:#800080;">1.0f</span> <span style="color: #000040;">/</span> <span style="color: #008000;">&#40;</span>a <span style="color: #000040;">-</span> b<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">return</span> <span style="color:#800080;">0.0f</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>This can happen because only with denormals are we guaranteed that subtracting two floats with different values will give a non-zero result.</p>
<p>To make the above example more concrete lets imagine that ‘a’ equals FLT_MIN * 1.125 and ‘b’ equals FLT_MIN. These numbers are both normalized floats, but their difference (.125 * FLT_MIN) is a denormal number. If denormals are supported then the result can be represented (exactly, as it turns out) but the result is a denormal that only has twenty-one bits of precision. The result has no implied leading one, and has two leading zeroes. So, even with denormals we are starting to run on reduced precision, which is not great. This is called gradual underflow.</p>
<p>Without denormals the situation is much worse and the result of the subtraction is zero. This can lead to unpredictable results, such as divide-by-zero or other bad results.</p>
<p>Even if denormals are supported it is best to avoid doing a lot of math at this range, because of reduced precision, but without denormals it can be catastrophic.</p>
<h2>Performance implications on the x87 FPU</h2>
<p>The performance of Intel’s x87 units on these NaNs and infinites is pretty bad. Doing floating-point math with the x87 FPU on NaNs or infinities numbers caused a 900 times slowdown on Pentium 4 processors. Yes, the same code would run 900 times slower if passed these special numbers. That’s impressive, and it makes many legitimate uses of NaNs and infinities problematic.</p>
<p>Even today, on a SandyBridge processor, the x87 FPU causes a slowdown of about 370 to one. I’ve been told that this is because Intel really doesn’t care about x87 and would like you to not use it. I’m not sure if they realize that the Windows 32-bit ABI actually mandates use of the x87 FPU (for returning values from functions).</p>
<p>The x87 FPU also has some slowdowns related to denormals, typically when loading and storing them.</p>
<p>Historically AMD has handled these special numbers much faster on their x87 FPUs, often with no penalty. However I have not tested this recently.</p>
<h2>Performance implications on SSE</h2>
<p>Intel handles NaNs and infinities much better on their SSE FPUs than on their x87 FPUs. NaNs and infinities have long been handled at full speed on this floating-point unit. However denormals are still a problem.</p>
<p>On Core 2 processors the worst-case I have measured is a 175 times slowdown, on SSE addition and multiplication.</p>
<p>On SandyBridge Intel has fixed this for addition – I was unable to produce any slowdown on ‘addps’ instructions. However SSE multiplication (‘mulps’) on Sandybridge has about a 140 cycle penalty if one of the inputs or results is a denormal.</p>
<h2>Denormal slowdown – is it a real problem?</h2>
<p>For some workloads – especially those with poorly chosen ranges – the performance cost of denormals can be a huge problem. But how do you know? By temporarily turning off denormal support in the SSE and SSE2 FPUs with _controlfp_s:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &lt;float.h&gt;</span>
<span style="color: #666666;">// Flush denormals to zero, both operands and results </span>
_controlfp_s<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">NULL</span>, _DN_FLUSH, _MCW_DN <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> 
… 
<span style="color: #666666;">// Put denormal handling back to normal. </span>
_controlfp_s<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">NULL</span>, _DN_SAVE, _MCW_DN <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></div></div>

<p>This code does not affect the x87 FPU which has no flag for suppressing denormals. Note that 32-bit x86 code on Windows always uses the x87 FPU for some math, especially with VC++ 2010 and earlier. Therefore, running this test on a 64-bit process may provide more useful results.</p>
<p>If your performance increases noticeably when denormals are flushed to zero then you are inadvertently creating or consuming denormals to an unhealthy degree.</p>
<p>If you want to find out exactly where you are generating denormals you could try enabling the underflow exception, which triggers whenever one is produced. To do this in a useful way you would need to record a call stack and then continue the calculation, in order to gather statistics about where the majority of the denormals are produced. Alternately you could monitor the underflow bit to find out which functions set it. See <a href="http://randomascii.wordpress.com/2012/04/21/exceptional-floating-point/">Exceptional Floating Point</a> for some thoughts on this, or read <a href="http://software.intel.com/en-us/articles/x87-and-sse-floating-point-assists-in-ia-32-flush-to-zero-ftz-and-denormals-are-zero-daz/">this paper</a>.</p>
<h2>Don’t disable denormals</h2>
<p>Once you prove that denormals are a performance problem you might be tempted to leave denormals disabled – after all, it’s faster. But if it gives you a speedup means that you are using denormals a lot, which means that if you disable them you are going to change your results – your math is going to get a lot less accurate. So, while disabling denormals is tempting, you might want to consider investigating to find out why so many of your numbers are so close to zero. Even with denormals in play the accuracy near zero is poor, and you’d be better off staying farther away from zero. You should fix the root cause rather than just addressing the symptoms.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/20/thats-not-normalthe-performance-of-odd-floats/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Playing (with) Video</title>
		<link>http://www.altdevblogaday.com/2012/05/20/playing-with-video/</link>
		<comments>http://www.altdevblogaday.com/2012/05/20/playing-with-video/#comments</comments>
		<pubDate>Sun, 20 May 2012 06:49:06 +0000</pubDate>
		<dc:creator>Niklas Frykholm</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[bink]]></category>
		<category><![CDATA[H.264]]></category>
		<category><![CDATA[video]]></category>
		<category><![CDATA[VP8]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26301</guid>
		<description><![CDATA[<p>So you want to play some video? Shouldn&#8217;t be too hard, right? Just download some video playing library and call the <em>play_video()</em> function. Easy-peasy-lemon-squeezy.</p>
<p>Well, you have to make sure that the video is encoded correctly, that the library works on all platforms and plays nice with your memory, file, sound and streaming abstractions, and that the audio and video doesn&#8217;t desynchronize, which for some inexplicable reason seems to be a huge problem.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/20/playing-with-video/" class="more-link">Read more on Playing (with) Video&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>So you want to play some video? Shouldn&#8217;t be too hard, right? Just download some video playing library and call the <em>play_video()</em> function. Easy-peasy-lemon-squeezy.</p>
<p>Well, you have to make sure that the video is encoded correctly, that the library works on all platforms and plays nice with your memory, file, sound and streaming abstractions, and that the audio and video doesn&#8217;t desynchronize, which for some inexplicable reason seems to be a huge problem.</p>
<p>But this is just technical stuff. We can deal with that. What is worse is that video playback is also a legal morass.</p>
<p>There are literally  <em>thousands</em> of broad patents covering different aspects of video decompression. If you want to do some video coding experiments of your own you will have to read, understand and memorize all these patents so that you can carefully tip-toe your code and algorithms around them.</p>
<p>Of course, if you had a big enough pool of patents of your own you might not have to care as much, since if someone sued you, you could sue them right back with something from your own stockpile. Mutually assured destruction through lawyers. Ah, the wonderful world of software patents.</p>
<p>So, creating your own solution is pretty much out of the question. You have to pick one of the existing alternatives and do the best you can with it. In this article I&#8217;m going to look at some different options and discuss the advantages and drawbacks of each one:</p>
<ul>
<li>
<p>Just say no</p>
</li>
<li>
<p>Bink</p>
</li>
<li>
<p>Platform specific</p>
</li>
<li>
<p>H.264</p>
</li>
<li>
<p>WebM</p>
</li>
</ul>
<p>There are other alternatives that didn&#8217;t make it to this list, such as Dirac, Theora, and DivX. I&#8217;ve decided to focus on these five, since in my view H.264 is the best of the commercial formats and WebM the most promising of the &#8220;free&#8221; ones.</p>
<p>An initial idea might be: Why not just do whatever it is <a class="link" href="http://www.videolan.org/vlc/">VLC</a> does? Everybody&#8217;s favorite video player plays pretty much whatever you throw at it and is open source software.</p>
<p>Unfortunately that doesn&#8217;t work, for two reasons. First, VLC:s code is a mix of GPL and LGPL stuff. Even if you just use the LGPL parts you will run into trouble on platforms that don&#8217;t support dynamic linking. Second, the VLC team doesn&#8217;t really care about patents and just infringe away. You can probably not afford to do the same. (As a result, there is a very <a class="link" href="http://www.videolan.org/press/patents.html">real threat</a> that VLC might be sued out of existence.)</p>
<h2>A quick introduction</h2>
<p>Before we start looking at the alternatives I want to say something short about what a video file <em>is</em>, since there is some confusion in the matter, even among educated people.</p>
<p>A video file has three main parts:</p>
<ul>
<li>
<p>Video data (H.264, DivX, Theora, VP8, &#8230;)</p>
</li>
<li>
<p>Audio data (MP3, AAC, Vorbis, &#8230;)</p>
</li>
<li>
<p>A container format (Avi, Mkv, MP4, Ogg, &#8230;)</p>
</li>
</ul>
<p>The container format is just a way of packing together the audio and video data in a single file, together with some additional information.</p>
<p>The simplest possible container format would be to just concatenate the audio data to the video data and be done with it. But typically we want more functionality. We want to be able to <em>stream</em> the content, i. e. start playing it before we have downloaded the whole file, which means that audio and video data must be multiplexed. We also want to be able to quickly seek to specific time codes, so we may need an index for that. We might also want things like audio tracks in different languages, subtitling, commentary, DVD menus, etc. Container formats can become quite intricate once you start to add all this stuff.</p>
<p>A common source of confusion is that the extension of a video file (.avi, .mkv, .mp4, .ogg) only tells you the container format, not the codecs used for the audio and video data <em>in</em> the container. So a video player may fail to play a file even though it understands the container format (because it doesn&#8217;t understand what&#8217;s inside it).</p>
<h2>Option 1: Just say no</h2>
<p>Who says there has to be video in a game? The alternative is to do all cut scenes, splash screens, logos, etc in-game and use the regular renderer for everything. As technology advances and real-time visuals come closer and closer in quality to offline renders, this becomes an increasingly attractive option. It also has a number of advantages:</p>
<ul>
<li>
<p>You can re-use the in-game content.</p>
</li>
<li>
<p>Production is simpler. If you change something you don&#8217;t have to re-render the entire movie.</p>
</li>
<li>
<p>You don&#8217;t have to decide on resolution and framerate, everything is rendered at the user&#8217;s settings.</p>
</li>
<li>
<p>You can dynamically adapt the content, for example dress the players in their customized gear.</p>
</li>
<li>
<p>Having everything be &#8220;in-game visuals&#8221; is good marketing.</p>
</li>
</ul>
<p>If I was making a game I would do everything in-game. But I&#8217;m not, I&#8217;m making an engine. And I can&#8217;t really tell my customers what they can and cannot do. The fact is that there are a number of legitimate reasons for using video:</p>
<ul>
<li>
<p>Some scenes are too complex to be rendered in-game.</p>
</li>
<li>
<p>Producing videos <em>can</em> be simpler than making in-game content, since it is easier to outsource. Anybody can make a video, but only the core team can make in-game content and they may not have much time left on their hands.</p>
</li>
<li>
<p>Playing a video while streaming in content can be used to hide loading times. An in-game scene could be used in the same way, but a high-fidelity in-game scene might require too much memory, not leaving enough for the content that is streaming in.</p>
</li>
</ul>
<p>As engine developers it seems we should at least provide <em>some</em> way of playing video, even if we <em>recommend</em> to our customers to do their cutscenes in-game.</p>
<h2>Option 2: Bink</h2>
<p><a class="link" href="http://www.radgametools.com/bnkmain.htm">Bink</a> from RAD game tools is as close as you can get to a de facto standard in the games industry, being used in more than 5800 games on 14 different platforms.</p>
<p>The main drawback of Bink is the pricing. At $ 8500 per platform per game it is not exactly expensive, but for a smaller game targeting multiple platforms that is still a noticeable sum.</p>
<p>Many games have quite modest video needs. Perhaps they will just use the video player for a 30 second splash screen at the start of the game and nothing more. Paying $ 34 000 to get that on four platforms seems excessive.</p>
<p>At Bitsquid our goal has always been to develop an engine that works for both big budget and small budget titles. This means that all the essential functionality of an engine (animation, sound, gui, video, etc) should be available to the licensees without any additional licensing costs (above what they are already paying for an engine). Licensees who have special interest in one particular area may very well choose to integrate a special middleware package to fulfill their needs, but we don&#8217;t want to force <em>everybody</em> to do that.</p>
<p>So, in terms of video, this means that we want to include a basic video player without the $ 8500 price tag of Bink. That video player may not be as performant as Bink in terms of memory and processor use, but it should work well enough for anyone who just wants to play a full screen cutscene or splash screen when the CPU isn&#8217;t doing much else. People who want to play a lot of video in CPU taxing situations can still choose to integrate Bink. For them, the price and effort will be worth it.</p>
<h2>Option 3: Platform specific</h2>
<p>One approach to video playing is to not develop a platform-independent library but instead use the video playing capabilities inherent in each platform. For example, Windows has <em>Windows Media Foundation</em>, MacOS has <em>QuickTime</em>, etc.</p>
<p>Using the platform&#8217;s own library has several advantages. It is free to use, even for proprietary formats, because the platform manufacturers have already payed the license fees for the codecs. (Note though, that for some formats you need a license not just for the player, but for the distribution of content as well.) The implementation is already there, even if the APIs are not the easiest to use.</p>
<p>The biggest advantage is that on low-end platforms, using the built-in platform libraries can give you access to special video decoding hardware. For example, many phones have built-in H.264 decoding hardware. This means you can play video nearly for free, something that otherwise would be very costly on a low-end CPU.</p>
<p>But going platform specific also has a lot of drawbacks. If you target many platforms you have your work cut out for you in integrating all their different video playing backends. It adds an additional chunk of work that you need to do whenever you want to add a new platform. Furthermore, it may be tricky to support the same capabilities on all different platforms. Do they all support the same codecs, or do you have to encode the videos specifically for each platform? Do all platforms support &#8220;play to texture&#8221; or can you only play the videos full screen? What about the sound? Can you extract that from the video and position it as a regular source that reverbs through your 3D sound world? Some platforms (i.e. Vista) have almost no codecs installed by default, forcing you to distribute codecs together with your content.</p>
<p>Since we are developing a generic engine we want to cover as many platforms as possible and minimize the effort required to move a project from one platform to another. For that reason, we need a platform independent library as the primary implementation. But we might want to complement it with platform specific libraries for low end platforms that have built-in decoding hardware.</p>
<h2>Option 4: H.264 (MPEG-4, AVC)</h2>
<p>Over the last few years H.264 has emerged as the most popular commercial codec. It is used in Blu-ray players, video cameras, on iTunes, YouTube, etc. If you want a codec with good tool support and high quality, H.264 is the best choice.</p>
<p>However, H.264 is covered by patents. Patents that need to be licensed if you want to use H.264 without risking a lawsuit.</p>
<p>The H.264 patents are managed by an entity known as MPEG LA. They have gathered all the patents that they believe pertain to H.264 in &#8220;patent pool&#8221; that you can license all at once, with a single agreement. That patent pool contains 1700 patents. Yes, you read that right. The act of encoding/decoding a H.264 file is covered by 1700 patents. You can find the list in all its 97 page glory at <a class="link" href="http://www.mpegla.com/main/programs/avc/Documents/avc-att1.pdf">http://www.mpegla.com/main/programs/avc/Documents/avc-att1.pdf</a>.</p>
<p>I am not a lawyer, as they say on Slashdot, but this is my best understanding of how this patent game works:</p>
<ul>
<li>
<p>Buying a license from MPEG LA gives you the right to use the 1700 patents in the pool.</p>
</li>
<li>
<p>This doesn&#8217;t mean you can&#8217;t be sued for patent infringement. Anyone that holds a patent which is not one of the 1700 in the pool could claim that H.264 infringes on it and sue you. That seems unlikely, MPEG LA has made an effort to gather all relevant patents, but there is no way to be certain.</p>
</li>
<li>
<p>MPEG LA doesn&#8217;t by itself go after people who use H.264 without a license, that is up to the holders of the 1700 patents in the pool.</p>
</li>
</ul>
<p>The licensing terms of H.264 are irritating, but not necessarily a big financial burden:</p>
<ul>
<li>
<p>If you distribute an encoder or decoder you can distribute 100 000 copies for free, then you have to pay $ 0.20 per unit.</p>
</li>
<li>
<p>If you distribute a H.264 encoded movie, it is free if it is shorter than 12 minutes, then you have to pay $ 0.02 per copy.</p>
</li>
</ul>
<p>Note that unlike the case with other popular codecs such as MP3, it is not just the decoder/encoder that you need to license, you also need a license just for distributing H.264 content.</p>
<p>From what I&#8217;ve been able to discern, but don&#8217;t take my word for it, a game that only plays a fixed set of movies/cutscenes would not be regarded as a general decoder (even though it contains decoding software), but rather as content, which means you would pay $0.02 per copy sold if you had more than 12 minutes of video in your game and nothing otherwise (you would still need to obtain a license though).</p>
<p>Of course, if you support H.264, you may also want to support AAC, the standard audio format that accompanies it. AAC is covered by a separate licensing body (Via Licensing) that has its own licensing terms. I haven&#8217;t investigated them in any great detail.</p>
<p>You have to decide for yourself how well these terms sit with you. At Bitsquid we finally decided that if we should have a standard video playing facility, it should be one that people could use without thinking too much about patents and licensing (to the extent that is possible).</p>
<h2>Option 5: VP8 (WebM)</h2>
<p>VP8 is a &#8220;free&#8221; video codec owned by Google. It is covered by patents, but Google has granted free use of those patents and also provides a BSD licensed library <em>libvpx</em> for encoding and decoding video files. The format is also endorsed by the Free Software Foundation.</p>
<p>It is generally acknowledged that when it comes to quality, VP8 is not quite as good as H.264, though the differences are not enormous. So you are trading some visual quality for the convenience of a license free format.</p>
<p>There has been some discussion (most of it about a year ago) about whether VP8 really is unencumbered by patents. MPEG LA claimed that it knew several patents that VP8 was infringing and showed interest in creating a &#8220;patent pool&#8221; for VP8 similar to the one it holds for H.264. Nothing has come of that yet and MPEG LA has not disclosed which patents it thinks VP8 is infringing, which means that Google cannot really respond to the allegations. It is hard to know how much stock to put in this and whether anything will come of it.</p>
<p>You could argue that with this potential &#8220;threat&#8221; against VP8, it would be better to use another &#8220;free&#8221; alternative such as Dirac or Theora. However, there is not much evidence that they would fare better. Everyone who makes a &#8220;free&#8221; codec tries their best to make sure that they don&#8217;t infringe on any patents. But with thousands of these patents around, each open to legal interpretation, there is just no way to be sure.</p>
<p>This is just the sad state of affairs of software patents. And you are not safe with the commercial formats either. Even if you have licensed the 1700 patents in the MPEG LA patent pool, someone can still sue you for violating patent number 1701. <em>No one</em> in this business offers indemnification against patent suits. Not Google. Not MPEG LA. Not Bink (I think).</p>
<p>It all becomes a question of risk. Bink has been around a long time without being sued, which is reassuring. VP8 hasn&#8217;t been around that long.</p>
<p>Will there be patent claims made against VP8? Maybe. Who knows. Similar threats were made against Theora, but nothing happened there. If it does happen, Google will most likely fight back and the whole thing will drag on in the courts. Will there be patent claims against <em>you</em> for using VP8? Seems extremely unlikely. Games are not interesting enough targets. Video decoding is not our main business, and we can easily switch technology if needed. Phone manufacturers, YouTube and TV companies are more interesting targets.</p>
<p>Do you have to care about any of this at all? Up to you to decide.</p>
<h2>Our conclusion</h2>
<p>None of these alternatives are really attractive, it is more about picking the least worst than finding the best, which is frustrating for a perfectionist with self-worth issues. Good cases can be made for all of them. This is what we have decided:</p>
<ul>
<li>
<p>We will provide VP8 decoding on all platforms through libvpx. All other things equal, the &#8220;most free&#8221; format will give us most flexibility in the long run.</p>
</li>
<li>
<p>We will not (at least not right now) support matroska or other advanced container formats. Instead, we will play the videos from simple IVF streams. Sound will be played as Vorbis files through our regular sound system so we get positioning, reverb, etc.</p>
</li>
<li>
<p>If needed, we will complement this basic approach with platform-specific libraries that take advantage of the hardware decoders on low-end platforms (phones and tablets).</p>
</li>
<li>
<p>Customers that need to play a lot of movies while doing other CPU intense tasks and that aren&#8217;t happy with the performance of libvpx are recommended to look into Bink.</p>
</li>
<li>
<p>Customers that are worried about &#8220;patent risk&#8221; with VP8 are recommended to do whatever their lawyers tell them to do. (Use Bink, a platform specific library, obtain a H.264 license or avoid video all together.)</p>
</li>
</ul>
<p>This has also been posted to <a class="link" href="http://bitsquid.blogspot.com">The Bitsquid blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/20/playing-with-video/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The devolution of gaming culture</title>
		<link>http://www.altdevblogaday.com/2012/05/17/the-devolution-of-gaming-culture/</link>
		<comments>http://www.altdevblogaday.com/2012/05/17/the-devolution-of-gaming-culture/#comments</comments>
		<pubDate>Thu, 17 May 2012 02:54:52 +0000</pubDate>
		<dc:creator>Kyle-Kulyk</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[General Interest]]></category>
		<category><![CDATA[culture]]></category>
		<category><![CDATA[devolution]]></category>
		<category><![CDATA[indie. gaming]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26275</guid>
		<description><![CDATA[<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/troll-71.jpg"><img class="alignleft  wp-image-26284" style="margin: 5px" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/troll-71.jpg" alt="" width="214" height="290" /></a></p>
<p>Gaming culture has a problem and that problem has a lot to do with gamers themselves.  To be clear, I’m not talking about all gamers but rather a subset of gamers whose antisocial behaviour and habits drive people away from gaming.  Analysts at Piper Jaffray recently conducted a survey that found nearly 66% of high school students surveyed across the US claimed they were losing interest in traditional videogames with slightly over 66% stating they were interested in social, mobile games which was an increase from 34% who answered the same question the year prior.  Gaming as we know it is changing for a variety of reasons and one of those reasons is gamers have chosen to turn on each other as well as the people who make the videogames they play.  While gaming culture tries to evolve and leave the primordial seas, certain gamers are busy running along the shore with sharpened sticks trying to force us all back in.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/17/the-devolution-of-gaming-culture/" class="more-link">Read more on The devolution of gaming culture&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/troll-71.jpg"><img class="alignleft  wp-image-26284" style="margin: 5px" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/troll-71.jpg" alt="" width="214" height="290" /></a></p>
<p>Gaming culture has a problem and that problem has a lot to do with gamers themselves.  To be clear, I’m not talking about all gamers but rather a subset of gamers whose antisocial behaviour and habits drive people away from gaming.  Analysts at Piper Jaffray recently conducted a survey that found nearly 66% of high school students surveyed across the US claimed they were losing interest in traditional videogames with slightly over 66% stating they were interested in social, mobile games which was an increase from 34% who answered the same question the year prior.  Gaming as we know it is changing for a variety of reasons and one of those reasons is gamers have chosen to turn on each other as well as the people who make the videogames they play.  While gaming culture tries to evolve and leave the primordial seas, certain gamers are busy running along the shore with sharpened sticks trying to force us all back in.</p>
<p>The problem lies with the internet and the anonymity it affords its users.  This effect certainly isn’t limited to just gaming circles but as gamers tend to be a largely wired group of individuals the impact is pronounced.  Gaming has always had a social side but over the decades that’s changed, and you could certainly argue, not for the better.  Back in the 80’s and 90’s, gamers would flock to arcades or journey to friend’s houses to partake in the hottest, latest releases.  To illustrate how it’s changed, imagine four friends over for an afternoon session of GoldenEye sitting in their family den.  Now imagine one of those children lets loose with a barrage of profanity laced, racist, homophobic rants aimed at his fellow gamers.  Or imagine someone’s little sister is also invited to play and subjected to a stream of masturbation and rape jokes.  There’s a very good chance that the child would simply never be invited back for another GoldenEye marathon.  There’s also a chance that little Jimmy’s mother, having overheard the obscene rant would never allow that child in her house ever again and would make a quick phone call to inform the offending child’s parents of their unacceptable behaviour.</p>
<p>This type of antisocial behaviour infects network gaming and social interactions across the internet and therein lies the difference between gaming culture now and gaming culture then.  There are few, if any, social repercussions in gaming today and the impact of these behaviours eats at the fun factor of gaming for a large number of gamers, children and adult alike.  It doesn’t matter if you’re looking to game socially on your console or if you’re looking to partake in a general gaming discussion on the internet, odds are your experience will be sullied by another gamer hiding behind their internet pseudonym.</p>
<p>Researchers refer to this as “toxic disinhibition”.  The anonymity the internet and online gaming networks offers often results in the complete abandonment of social restrictions that would generally be present in face to face interactions such as in the days when we gamed locally with other people in the room.  The result of this &#8220;trolling&#8221; is we see more and more gamers being turned off of gaming, or seeing their enjoyment of games lessened, thus inhibiting the growth of gaming culture.  The impact of this online disinhibition also affects developers who can find themselves loathe to engage their own fan base for fear of fanboy backlash through internet flaming.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/120463-unicorn.jpg"><img class="alignleft size-full wp-image-26277" style="margin: 5px" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/120463-unicorn.jpg" alt="" width="468" height="298" /></a>Recently, gamers made headlines for their disproportionate backlash against Mass Effect 3 developer Bioware.  The actions of certain gamers painted all gamers as whiney, entitled children prone to screaming fits when denied their pacifier.  Bioware found itself facing a FTC complaint while its writers and staff were targets of hate campaigns and death threats as some found the end of their latest game offering to be unsatisfactory.  Other gamers and non-gamers alike shook their collective heads in disbelief.  Blizzard also suffered a ridiculous backlash from gamers when screenshots of their now released Diablo 3 title were deemed “too bright” by some prior to the game’s launch, prompting Blizzard to mock the users by releasing screenshots containing unicorns shooting rainbows from their posteriors.  While Blizzard used the experience to have a bit of fun, the example illustrates a growing trend among gamers to instantaneously and viciously attack developers and other gamers alike for even perceived slights and as a whole, the gaming community becomes a less inviting place.</p>
<p>The online disinhibition effect certainly isn’t limited to gaming forums either as the development community itself isn’t immune from unprofessional behaviour.  I’ve seen my own personal blog postings regarding my development experiences targeted by other developers leveling harsh and often unfair criticisms.  For example, I’ve had a developer lambast the simply inclusion of our company logo on a splash page because “no one cares about your company”.  I’ve even had a local developer I didn’t know and had never met criticize my company online for the slight of not consulting with their group prior to launching our first game.  This type of challenging behaviour is far more likely to be witnessed online than in face to face interactions or official business communication and unfortunately it is becoming more prevalent.</p>
<p>They say in general you need a thick skin to blog but backlash I received from a recent blog post made me question the value of blogging my own experiences as a developer.  I posted a personal blog listing some of the complete, all in one game engines available that may be of interest to independent developers.  While researching game engines for my company I would have found such a blog useful as I looked for a game engine that offered features I required, such as Android and iOS porting and clearly the blog was not meant as an in depth review piece.  As I had not the opportunity to try each engine I listed, I made sure to note that where I was unfamiliar with the engine I was simply relaying information and opinions from various reviews I had come across and I provided links to each product so users could conduct further research.  Rather than promote a thoughtful discussion on the merits of various game engines as I had intended or to provide a starting point for further research, the resulting comments were almost all attacks against myself personally and my attempt to inform other indie developers.</p>
<p>The comments included people calling me a liar, posters comparing my blog to vulgar activities, writers incensed that I didn’t whole heartedly endorse their particular favorite engine.  I even read claims that I was intentionally trying to harm product reputations despite the fact I noted these opinions were sometimes not even mine but were simply being passed along when I lacked particular knowledge of the product being discussed.  I was frankly shocked by the lack of decorum I witnessed in response to a personal blog intended to simply inform and facilitate further research, and if other developers hadn’t contacted me directly to offer their support (with one commenting he would have done it publicly if not afraid of being “flamed” himself) I most likely would have never written another blog regarding my game development experiences.  This general lack of professionalism in a workplace environment would never be tolerated.  Indeed, when gamers and developers are afraid to share ideas due to fear of reprisal it’s time to take a hard look at the current situation and what repercussions this could have to our industry as a whole.  As a community, this type of behaviour should not be allowed to propagate.  I&#8217;ve been subjected to all manner of hate mail and threats from casual gamers and stalking fanboys alike over the years writing opinion pieces regarding the games industry, however the lack of professionalism I&#8217;ve witnessed since becoming a developer myself truly surprised me.</p>
<p>Gaming culture is suffering due to experiences like this, due to experiences like those Bioware recently endured and due to the ongoing profane, racist and homophobic behaviour tolerated every day in online gaming matches and in internet gaming forums.  The anonymity of the internet mixed with complacency among gamers and developers has led to this situation and the associated cyberbullying that goes along with it but as the genie is out of the bottle with regards to the internet, there is little that we can do to curb its impact.  The removal of anonymity in online gaming by the companies that operate these networks could potentially result in fewer incidents as people are less inclined to act in socially unacceptable manners when their real names and locations are attached to their actions, however this system would still rely on reporting tools that already exist are underutilized by the majority of gamers.  Most prefer to simply ignore the problem, and this does nothing to stem the rise of anti-social behaviour in the gaming community.</p>
<p>As more teens are turning towards social gaming where they can exercise more direct control over their social interactions through use of things like Facebook friend lists, as more potential gamers are turned off by what they see of gamers in the news and more core gamers turn away from online gaming and game forums based on the sliding social environment, today’s gaming culture must change or it will face decline.  We’re already seeing traditional game sales slide as gamers look elsewhere and a shift towards mobile games is evident.  Partial blame falls on gamers themselves for creating and tolerating an increasingly toxic game culture that runs contrary to the social spirit that videogames created for many of us while gaming in the 80’s and 90’s, and even some developers themselves are letting professionalism standards slump in their online communications which itself is the start of a slippery slope.  We can never go back to the way gaming was, but we can shape the future of gaming culture for the better by being conscious of where it went wrong and why.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/troll-9.jpg"><img class="aligncenter size-full wp-image-26278" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/troll-9.jpg" alt="" width="650" height="718" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/17/the-devolution-of-gaming-culture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Channel API</title>
		<link>http://www.altdevblogaday.com/2012/05/16/channel-api/</link>
		<comments>http://www.altdevblogaday.com/2012/05/16/channel-api/#comments</comments>
		<pubDate>Wed, 16 May 2012 08:42:37 +0000</pubDate>
		<dc:creator>Noel Austin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[channel api]]></category>
		<category><![CDATA[google app engine]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26230</guid>
		<description><![CDATA[<p>I&#8217;m sure you&#8217;ve heard of Google App Engine &#8211; it&#8217;s a web hosting service that allows you to write server software in Java, Python or Go. Overall I think it&#8217;s a great piece of technology that helped me understand the concept of writing scalable services, it was also a useful reason to finally learn Python. Anyway I&#8217;m currently interested in the suitability of it for realtime applications like games.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/16/channel-api/" class="more-link">Read more on Channel API&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m sure you&#8217;ve heard of Google App Engine &#8211; it&#8217;s a web hosting service that allows you to write server software in Java, Python or Go. Overall I think it&#8217;s a great piece of technology that helped me understand the concept of writing scalable services, it was also a useful reason to finally learn Python. Anyway I&#8217;m currently interested in the suitability of it for realtime applications like games.</p>
<p>The traditional web model is request/response based. The client requests a resource from the server, the server responds with some data. That&#8217;s the end of the transaction. In this model there is no way for the server to update the client without first receiving a request from that client. If you want to build a multiplayer game then this is likely to be very important.</p>
<p>It can be simulated either by regular polling from the client (does not scale well), by some fairly hacky techniques falling under the umbrella of <a href="http://en.wikipedia.org/wiki/Comet_(programming)">Comet</a>, or by the new WebSockets technology available recently. Google App Engine does not support WebSockets, but it does support Comet under the guise of the <a href="https://developers.google.com/appengine/docs/python/channel/overview">Channel API</a>.</p>
<p><strong>Test App Here!</strong><br />
<a href="http://channelapistresstest.appspot.com/">http://channelapistresstest.appspot.com/</a></p>
<p>I was interested in the performance of the Channel API so I wrote a small test app. I&#8217;m a bit of a noob when it comes to Python and HTML/Javascript but if you want to take a look I uploaded my code <a href="http://code.google.com/p/channel-api-test/">here</a>.</p>
<p>Overall I was disappointed with the results, and indicates to me that if you want any kind of fast response game then you may have to look elsewhere.</p>
<ul>
<li>Very unpredictable latency (200-1000ms)</li>
<li>Big packet overhead of HTTP headers etc</li>
<li>No peer to peer support at all (limitation of current web technologies)</li>
<li>No support for broadcast messages (server must send to each client in separate call)</li>
<li>Sending several messages at once often results in a massive increase in latency</li>
</ul>
<p>That said I do think the technology is quite promising and certainly opens up the possibility of doing whole classes of games with two way communication. Strategy games, or other games where one player does not directly affect another. Adding chat for instance is a perfect use case for this. If you are thinking about using Channel then I found out a few things that might be useful to you.</p>
<ul>
<li>Reliable &#8211; in all my tests all messages eventually arrived</li>
<li>Out of order &#8211; messages are not guaranteed to be in sequence so if this is important you need to handle your own sequence checks</li>
<li>Multiple instances &#8211; don&#8217;t forget the service may spin up multiple instances to handle the requests</li>
<li>Development server is much worse than the live server (on Windows at least)! It seems to serialize all messages sent with approximately 600ms between each one.</li>
</ul>
<p>I checked the latency from my office in the UK and found it to be very unpredictable and often slow. If anyone from other parts of the world could test and report back your average latency that would be awesome! It&#8217;s entirely possible that I&#8217;ve screwed something up which is causing the poor performance, if anyone has any comments on this it would be great to hear them.</p>
<p><strong>Addendum</strong></p>
<p>After writing this I became interested in comparing the Channel API with Websockets. I took this opportunity to play with <a href="http://nodejs.org">node.js</a> and hack up a quick server. I found a great host in <a href="http://nodejitsu.com/">nodejitsu</a> who provided one free app and a fantastic tool to deploy your app. Unsurprisingly results are much better than with Channel. My average latency tends to hang around 200ms, but there are no spikes or degradation when sending a lot of messages.</p>
<p>You can test my quick and dirty app at <a href="http://echo_test.jit.su/">http://echo_test.jit.su/</a> (sorry it only works in Chrome/Firefox!). You can see the source <a href="https://gist.github.com/2708744">here</a>.</p>
<p>It is not really a fair comparison, because the back ends are designed for different purposes. The GAE server uses persistent storage to support multiple instances, whereas the node.js version will not scale. The Channel API is also fully supported on all browsers/platforms whereas support for WebSockets is still fairly thin on the ground. </p>
<p>This is a cross post from my <a href="http://noelaustin.com/">blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/16/channel-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server: High performance inserts</title>
		<link>http://www.altdevblogaday.com/2012/05/16/sql-server-high-performance-inserts/</link>
		<comments>http://www.altdevblogaday.com/2012/05/16/sql-server-high-performance-inserts/#comments</comments>
		<pubDate>Wed, 16 May 2012 08:00:03 +0000</pubDate>
		<dc:creator>Ted Spence</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26180</guid>
		<description><![CDATA[<p>In order to write high performance SQL code, we need to know more about what’s going on underneath the hood.  We won’t need to go into exhaustive details on <a href="http://www.insidesqlserver.com/">SQL</a> <a href="http://sqlserverinternals.blogspot.com/">Server’s</a> <a href="http://msdn.microsoft.com/en-us/library/aa226174(v=sql.70).aspx">internals</a>, but we’ll go in depth into a simple challenge and show you how you can create robust scalability one feature at a time.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/16/sql-server-high-performance-inserts/" class="more-link">Read more on SQL Server: High performance inserts&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>In order to write high performance SQL code, we need to know more about what’s going on underneath the hood.  We won’t need to go into exhaustive details on <a href="http://www.insidesqlserver.com/">SQL</a> <a href="http://sqlserverinternals.blogspot.com/">Server’s</a> <a href="http://msdn.microsoft.com/en-us/library/aa226174(v=sql.70).aspx">internals</a>, but we’ll go in depth into a simple challenge and show you how you can create robust scalability one feature at a time.</p>
<p><span id="more-26180"></span></p>
<p>Other articles in this series:</p>
<li><a href="http://www.altdevblogaday.com/2012/05/02/sql-server-performance-part-1/">Part 1: Effective SQL Server Techniques</a></li>
<h1>Storing Data In SQL Server</h1>
<p>Let’s imagine that we’re building the data layer for a multiplayer game.  The data layer probably contains tons of different persistent storage devices &#8211; user logs, game activity diagnostic data, auction houses, persistent user data, and so on.  For today’s lesson we’ll create a database of item drops from monster kills.  </p>
<p>To start I will assume you&#8217;re not using an <a href="http://en.wikipedia.org/wiki/Object-relational_mapping">ORM system</a> like Hibernate or Entity Framework.  Many people like ORMs since they abstract away most of the database work.  But doing so means you also lose the ability to fine tune your performance requirements, and we&#8217;re just going to skip that part.  There&#8217;s lots of good debate out there about <a href="http://www.artima.com/intv/abstract3.html">why ORM systems aren&#8217;t always the right idea</a>, so proceed there at your own risk.  </p>
<h1>Revision One: A Bad Design</h1>
<p>I’ll present, first of all, the kind of database design we may all have seen at one time or another.  Here&#8217;s a table that&#8217;s not really optimized for massive data storage; it&#8217;s ugly but workable:</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="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> item_drops_rev1 <span style="color: #66cc66;">&#40;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">-- This is the reference to the Items system ID number; it's not a foreign key </span>
    <span style="color: #808080; font-style: italic;">-- because the &quot;Items&quot; table is on a different database server</span>
    item_id <span style="color: #993333; font-weight: bold;">BIGINT</span><span style="color: #66cc66;">,</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">-- This is the internal monster class name, e.g. &quot;Creature.Wolf&quot; or &quot;Player.NPC&quot;</span>
    monster_class <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">-- The Zone ID refers to a database on the same server, so we built it as a </span>
    <span style="color: #808080; font-style: italic;">-- foreign key</span>
    zone_id <span style="color: #993333; font-weight: bold;">INT</span> <span style="color: #993333; font-weight: bold;">FOREIGN</span> <span style="color: #993333; font-weight: bold;">KEY</span> <span style="color: #993333; font-weight: bold;">REFERENCES</span> world_zones<span style="color: #66cc66;">&#40;</span>zone_id<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">-- The position and time where and when the kill happened</span>
    xpos <span style="color: #993333; font-weight: bold;">REAL</span><span style="color: #66cc66;">,</span> 
    ypos <span style="color: #993333; font-weight: bold;">REAL</span><span style="color: #66cc66;">,</span>
    kill_time datetime <span style="color: #993333; font-weight: bold;">DEFAULT</span> GETDATE<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>We can probably live with this table structure.  It&#8217;s not normalized, but it gets the job done.  I&#8217;ll explain in a moment what we can do to improve on it.</p>
<p>On the other hand, for the client code, I&#8217;m going to show you the wrong way to get things done: I&#8217;ll create a <a href="http://xkcd.com/327/">SQL injection vulnerability</a>.  Any web-facing application or service layer is at risk for SQL injection, and frankly it&#8217;s easy to overlook something and get lazy and only discover your server hacked a month later.  If you ever see this kind of code, <i>this is by far the worst thing you can ever do</i>:</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="csharp" style="font-family:monospace;">SqlConnection conn <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlConnection<span style="color: #008000;">&#40;</span>my_connection_string<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
conn<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// This is a massive SQL injection vulnerability - don't ever write your own SQL statements with string formatting!</span>
<span style="color: #6666cc; font-weight: bold;">String</span> sql <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">@&quot;INSERT INTO item_drops 
    (item_id, monster_class, zone_id, xpos, ypos) 
    VALUES 
    ({0}, '{1}', {2}, {3}, {4}, {5})&quot;</span>, item_id, monster_class, zone_id, xpos, ypos<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
SqlCommand cmd <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlCommand<span style="color: #008000;">&#40;</span>sql, conn<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">ExecuteNonQuery</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// Because this call to Close() is not wrapped in a try/catch/finally clause, it could be missed if an </span>
<span style="color: #008080; font-style: italic;">// exception occurs above.  Don't do this!</span>
conn<span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>What&#8217;s bad about it?  Do you see how the SQL statement is being assembled by a string parser?  SQL statements are basically dynamic code.  You would never let a random user type code into a web browser and execute it on your server, so don&#8217;t do the same thing with your database.  Because SQL as a language has lots of features for combining multiple statements, someone could write a malicious monster_class string that would have terrible side effects.  A simple attack might be &#8220;&#8216;;UPDATE players SET gold=gold+10000;&#8211;&#8221;, but there are lots of other more subtle attacks too.  SQL Server even has a feature called <a href="http://msdn.microsoft.com/en-us/library/ms175046.aspx">xp_cmdshell()</a> that can allow a SQL injection vulnerability to turn into a sitewide security breach.  </p>
<p>So don’t ever write your own SQL statements using string parsers; you instead want to use <a href="http://www.dotnetperls.com/sqlparameter">SQL Parameters</a>.  There&#8217;s also a little improvement we can make to avoid leaving dangling connections &#8211; the <a href="http://www.w3enterprises.com/articles/using.aspx">using</a> statement.  When the .NET execution environment exits a &#8220;using() { }&#8221; clause, it automatically disposes all resources that were obtained in the initialization.  So those two items said, here&#8217;s what good code looks like:</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="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>SqlConnection conn <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlConnection<span style="color: #008000;">&#40;</span>my_connection_string<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    conn<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> sql <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;INSERT INTO item_drops_rev1 (item_id, monster_class, zone_id, xpos, ypos) VALUES (@item_id, @monster_class, @zone_id, @xpos, @ypos)&quot;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>SqlCommand cmd <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlCommand<span style="color: #008000;">&#40;</span>sql, conn<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@item_id&quot;</span>, item_id<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@monster_class&quot;</span>, monster_class<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@zone_id&quot;</span>, zone_id<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@xpos&quot;</span>, xpos<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@ypos&quot;</span>, ypos<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">ExecuteNonQuery</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Besides being easier to read, this approach guarantees that SQL injection will not be a problem.  So this is where I&#8217;ll start.</p>
<p>This code, using the SQLCommand and parameters, gets the job done and it&#8217;s fast.  Running a test on an old laptop I have around, I was able to insert 10,000 records in 7.768 seconds.  This kind of performance is good enough for most companies; running on a proper server it would be 3-4 times faster and everyone would be happy.  For a business application this code is fine, easy to maintain, and reliable.</p>
<p>That said, we’re a gaming company, and what works for us is a bit different than the code used by an accounts payable system that processes a few tens of thousands of records per day.  You&#8217;re probably going to put this code up in front of a web service that gets called every time a zone server in your game records a kill, so maybe 10,000 kills in 7-8 seconds isn&#8217;t good enough.  Let&#8217;s see what we can find to make improvements.</p>
<h1>Performance Limitations Of Revision One</h1>
<p>In order to make this database insert process fast, let&#8217;s start looking at what happens when you execute this command.  I’ll overlook all the internal stuff that we don’t have control over, and show you instead a list of a few problems this code suffers from:</p>
<ul>
<li><span style="font-weight: bold">Connection time.</span>  When you execute “conn.Open()”, the client computer must parse the connection string, identify the SQL server, open a channel, and begin a dialogue; this can take up to a second or two.  Fortunately, if you’re using C#, the .NET environment will automatically use <a href="http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx">connection pooling</a> to retrieve a previously opened connection with an identical connection string.  If you’re not using C# for your client library, make certain that your environment provides pooling!</li>
<li><span style="font-weight: bold">Network latency.</span>  Your data layer server has to communicate with your SQL server, and each packet it sends has a round trip time.  It’s possible to run SQL server on the same physical machine as your data layer, but it’s not recommended.  Ideally, you’d create a dedicated SQL network for reduced overhead and increased security.  With modern switches it’s very easy to <a href="http://www.petri.co.il/csc_setup_a_vlan_on_a_cisco_switch.htm">configure a VLAN</a> to do this, and most servers nowadays have lots of spare ethernet ports.</li>
<li><span style="font-weight: bold">Parser overhead.</span>  SQL Server sees the string “INSERT INTO …” and has to evaluate it into actual work.  The parser is the bit of code that turns the sql string into a “plan” &#8211; basically a list of function calls that the server will execute internally.  The <a href="http://www.sqlmag.com/article/tsql3/inside-sql-server-parse-compile-and-optimize">SQL Server Parser</a> is so fast its timing is often negligible; but we can still help cut down on its work by using stored procedures instead of straight SQL.</li>
<li><span style="font-weight: bold">Database contention.</span>  To provide <a href="http://en.wikipedia.org/wiki/ACID">ACID compliance</a>, SQL Server has to ensure that all database changes are serialized.  It does this by using locks to ensure that database inserts don’t conflict with each other.  Most SQL Servers are multi-user machines: in addition to your &#8220;INSERT&#8221; statement, the SQL server is probably handling dozens or hundreds of other clients at the same time.  Maybe client A is inserting item drop records, while client B is running reports on these records, and client C is sending stats to the community manager in realtime.
<p>Well, when SQL Server is doing all of these things, it generates locks to ensure that A, B, and C each receive sensible results.  SQL Server guarantees that each statement is executed while the database is in a fully predictable state, and managing those locks takes time.  Additionally, if SQL Server is just overloaded with too many clients, it doesn&#8217;t matter how well written your query is &#8211; it will be slow!  You need to take a holistic look at the server&#8217;s load levels, and continue to monitor each and every client that connects to the server to see where optimizations can take place.</li>
<li><span style="font-weight: bold">Constraint processing.</span>  When inserting data, each <a href="http://www.w3schools.com/sql/sql_constraints.asp">constraint</a> (a foreign key, or a default, or a “check” statement) takes a non-zero amount of time to test.  SQL server guarantees that each record inserted, updated, or deleted will continue to satisfy all constraints on the table.  Do you really need foreign keys for large, high volume tables?</li>
<li><span style="font-weight: bold">Page faults.</span>  While executing the query, SQL Server needs to pull all the required information into memory.  If SQL is under memory pressure, it will have to discard some pages and reload them from disk.  Make sure to give it as much RAM as you can afford, and design your tables to reduce each record&#8217;s size.  Be careful when designing your indexes; too many indexes means lots of paging.  But of course, buying RAM is far cheaper than anything else you can do, and it’s a one-time cost, unlike that <a href="http://wiki.apache.org/hadoop/AmazonEC2">Hadoop cluster on Amazon EC2</a> that you keep paying for each month.</li>
<li><span style="font-weight: bold">Varchars.</span>  Varchars are essential tools, but they can also lead to lots of unexpected overhead.  Each time you store a variable length column, SQL Server has to do more memory management to pack records together.  Strings can easily consume hundreds of bytes of memory each.  If you put a VARCHAR column in an index, SQL Server has to execute tons of O(string length) comparisons as it searches through the B-tree, whereas integer compare instructions are limited only by memory latency and processor frequency.</li>
<li><span style="font-weight: bold">Data storage.</span>  You can also help to optimize the amount of work SQL Server must perform by shrinking your data size.  When inserting data, normalizing your database helps reduce the amount of data written to disk; but when querying, denormalizing helps reduce the number of tables that need to be joined.  You should ideally <a href="http://www.codinghorror.com/blog/2008/07/maybe-normalizing-isnt-normal.html">wage constant war between normalizing and denormalizing</a>; don’t ever let yourself get stuck on one side of the fence or the other.</li>
</ul>
<p>After all this overhead, your query will return.  In most cases, the query is so fast you won’t even realize all this overhead happened.  However, there’s one more thing to keep in mind:</p>
<ul>
<li><span style="font-weight: bold">Disk IO</span>.  SQL Server will eventually write the data you’ve just inserted to disk.  In SQL Server, data is first written to a transaction log, then the transaction log is merged with the permanent database file when a backup is executed.  This happens in the background, so it won’t delay your query directly; but each transaction that occurs must have its own lump of disk IO.  You can reduce this overhead by giving SQL server physically separate disks for transaction logs and main DB files. Of course, the best solution is to actually reduce the number of transactions you execute.  </li>
</ul>
<p>As you can see, there&#8217;s a lot to consider when optimizing SQL.  The good news is that these limitations are manageable, provided you pay attention to them.</p>
<h1>Revision Two: Free Improvements</h1>
<p>Given what we’ve learned, let’s rewrite the SQL Insert command and see what benefit we can get.  First, we can normalize our database by moving “monster_class” into its own table.  We can then load into our client application the list of monster classes and use a hashtable to find the ID number to insert into the database directly.  That reduces the amount of data stored in each record, and it makes each record identical in size.  It offloads some of the work that SQL server has to perform and distributes it to the application tier.</p>
<p>With these improvements, we&#8217;ll see a reduction in data storage size per record:</p>
<div id="attachment_26189" class="wp-caption aligncenter" style="width: 526px"><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/sql-2-memory.png"><img src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/sql-2-memory.png" alt="One row in memory" width="516" height="268" class="size-full wp-image-26189" /></a><p class="wp-caption-text">The old vs new record layouts</p></div>
<p>These changes cut down the size of the record noticeably.  The original record used to take between 41 and 91 bytes, probably averaging 60 or so bytes per record; the new record takes exactly 35 bytes.  Since SQL server stores records in 8K pages, that means that you can now store over 200 records per page, whereas the old system could only hold about 130.  This increases the number of rows you can insert before SQL Server succumbs to memory pressure, it speeds up your inserts, and since each record is a fixed length, SQL Server reduces the amount of offset calculation work that&#8217;s done to rapidly scan through records in memory.</p>
<p>Next, let’s eliminate our constraints.  This should be done when you’ve tested your code and know that removing the constraint won’t make your data integrity suffer.  In the initial table, we had two constraints: a foreign key and a default value.  If we’re not really worried about ensuring that each zone ID is rigidly correct, we can forego the foreign key.  That means for each insert we no longer need to test the zone database to ensure each ID exists.  For a business application, that kind of foreign ID testing is valuable; but for my game I’ll just write a test script to check once per day that no bad zone IDs are being written.</p>
<p>Finally, I’ll replace the custom SQL text with a stored procedure.  This can potentially reduce parser overhead, although our program is simple enough that the parser overhead is pretty low and highly likely to be cached anyways.  </p>
<p>The revised table, stored procedure, and client program is now capable of inserting 10,000 records into my ancient laptop in about 6.552 seconds, for a performance boost of ~15%.  The code now looks like these snippets:</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
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> item_drops_rev2 <span style="color: #66cc66;">&#40;</span>
    item_id <span style="color: #993333; font-weight: bold;">BIGINT</span><span style="color: #66cc66;">,</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">-- This is now a pointer to a lookup table</span>
    monster_class_id <span style="color: #993333; font-weight: bold;">INT</span><span style="color: #66cc66;">,</span> 
&nbsp;
    <span style="color: #808080; font-style: italic;">-- Zone no longer has a FOREIGN KEY constraint.  SQL Server will allow bad</span>
    <span style="color: #808080; font-style: italic;">-- values to be loaded, and it's our responsibility to handle them.</span>
    zone_id <span style="color: #993333; font-weight: bold;">INT</span><span style="color: #66cc66;">,</span> 
    xpos <span style="color: #993333; font-weight: bold;">REAL</span><span style="color: #66cc66;">,</span> 
    ypos <span style="color: #993333; font-weight: bold;">REAL</span><span style="color: #66cc66;">,</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">-- No longer has a DEFAULT constraint; this means we have to insert the date</span>
    <span style="color: #808080; font-style: italic;">-- ourselves, but it reduces the work on SQL server</span>
    kill_time datetime 
<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">-- This procedure allows SQL server to avoid virtually all parser work</span>
<span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">PROCEDURE</span> insert_item_drops_rev2
     @item_id <span style="color: #993333; font-weight: bold;">BIGINT</span><span style="color: #66cc66;">,</span> @monster_class_id <span style="color: #993333; font-weight: bold;">INT</span><span style="color: #66cc66;">,</span> @zone_id <span style="color: #993333; font-weight: bold;">INT</span><span style="color: #66cc66;">,</span> @xpos <span style="color: #993333; font-weight: bold;">REAL</span><span style="color: #66cc66;">,</span> @ypos <span style="color: #993333; font-weight: bold;">REAL</span> 
<span style="color: #993333; font-weight: bold;">AS</span>
&nbsp;
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> item_drops_rev2 
    <span style="color: #66cc66;">&#40;</span>item_id<span style="color: #66cc66;">,</span> monster_class_id<span style="color: #66cc66;">,</span> zone_id<span style="color: #66cc66;">,</span> xpos<span style="color: #66cc66;">,</span> ypos<span style="color: #66cc66;">,</span> kill_time<span style="color: #66cc66;">&#41;</span> 
<span style="color: #993333; font-weight: bold;">VALUES</span> 
    <span style="color: #66cc66;">&#40;</span>@item_id<span style="color: #66cc66;">,</span> @monster_class_id<span style="color: #66cc66;">,</span> @zone_id<span style="color: #66cc66;">,</span> @xpos<span style="color: #66cc66;">,</span> @ypos<span style="color: #66cc66;">,</span> GETDATE<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>


<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
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>SqlConnection conn <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlConnection<span style="color: #008000;">&#40;</span>my_connection_string<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    conn<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>SqlCommand cmd <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlCommand<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;insert_item_drops_rev2&quot;</span>, conn<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// Setting the command type ensures that SQL server doesn’t need to do any complex parsing</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">CommandType</span> <span style="color: #008000;">=</span> CommandType<span style="color: #008000;">.</span><span style="color: #0000FF;">StoredProcedure</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@item_id&quot;</span>, item_id<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@monster_class_id&quot;</span>, monster_class_id<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@zone_id&quot;</span>, zone_id<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@xpos&quot;</span>, xpos<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@ypos&quot;</span>, ypos<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">ExecuteNonQuery</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>This is a great set of simple improvements.  However, there’s one more change you can make, and that’s the big one.</p>
<h1>Revision Three: Lazy Writes</h1>
<p>Think about your data requirements.  Is it essential that every record be written to the database immediately?  Can it wait a minute?  Five minutes?  What would the penalty be if a record was lost?  How many records could you lose before your business failed?</p>
<p>For a bank, losing any monetary transactions can be life or death; but for a game you can define your own risk level.  Let’s imagine that, for our monster drop table, we only want to risk losing at most five minutes&#8217; worth of data.  This gives us an incredible opportunity for performance improvement: we&#8217;ll keep a list of records to insert and batch-insert them once every five minutes!  SQL Server offers us a great way to reduce overhead when we batch up work like this: the <a href="http://en.wikipedia.org/wiki/Database_transaction">Transaction</a>.</p>
<p>A transaction is basically an atomic lump of work.  SQL Server guarantees that each transaction will either succeed and be written to the database permanently, or fail completely and no data will be written to the database.  This sounds complicated, but keep in mind that transactions also allow SQL Server to forego lots of extra overhead.  If you execute ten statements all by themselves, you get ten lock-based overheads; but if you wrap them in a transaction you only have to do your lock-based overhead once.</p>
<p>The only downside to batching is that we can&#8217;t use <a href="http://msdn.microsoft.com/en-us/library/ms188383.aspx">GETDATE()</a> anymore, since records may be inserted a few minutes after they were generated.  Instead we must preserve all the data for all records in memory while waiting for the time to insert a batch.  The new code looks 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
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>SqlConnection conn <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlConnection<span style="color: #008000;">&#40;</span>my_connection_string<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    conn<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// This transaction tells SQL server to obtain locks once and keep them on hand until the transaction is committed</span>
    SqlTransaction trans <span style="color: #008000;">=</span> conn<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginTransaction</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> INSERT_SIZE<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>SqlCommand cmd <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlCommand<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;insert_item_drops_rev3&quot;</span>, conn<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// Setting the command type ensures that SQL server doesn’t need to do any complex parsing</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">CommandType</span> <span style="color: #008000;">=</span> CommandType<span style="color: #008000;">.</span><span style="color: #0000FF;">StoredProcedure</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// Joining a transaction means that SQL Server doesn't have to close and re-open locks</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Transaction</span> <span style="color: #008000;">=</span> trans<span style="color: #008000;">;</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@item_id&quot;</span>, item_id<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@monster_class_id&quot;</span>, monster_class_id<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@zone_id&quot;</span>, zone_id<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@xpos&quot;</span>, xpos<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@ypos&quot;</span>, ypos<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@kill_time&quot;</span>, kill_time<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">ExecuteNonQuery</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// This statement tells SQL server to release all its locks and write the data to disk.</span>
    <span style="color: #008080; font-style: italic;">// If your code had thrown an exception above this statement, SQL Server would instead</span>
    <span style="color: #008080; font-style: italic;">// do a &quot;rollback&quot;, which would undo all the work since you began this transaction.</span>
    trans<span style="color: #008000;">.</span><span style="color: #0000FF;">Commit</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>With this change, we&#8217;re now able to insert 10,000 records in 2.605 seconds.  That&#8217;s about a 66% performance improvement &#8211; pretty major!  Even more importantly, wrapping sensible objects into a transaction significantly reduces database contention and can really alleviate concurrency bottlenecks.  Of course, if we weren&#8217;t batching these inserts together, adding a transaction is a slight performance penalty; but whenever you&#8217;re grouping lots of commands into one transaction you&#8217;ll cut down overhead.</p>
<h1>Revision Four: Table Parameters</h1>
<p>You can see that the above approach really saved us a ton of time.  However, to insert 10,000 records into the database we&#8217;re still contacting the database 10,000 times.  In fact, each call to &#8220;cmd.ExecuteNonQuery&#8221; generates a roundtrip message from your client application to the database.  What if there was a way that we could insert all ten thousand records, but only contact the database server once?</p>
<p>The good news is that SQL Server 2008 introduced an incredible new capability called “<a href="http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters">Table Parameters</a>”.  Table Parameters work by grouping tons of records together into a single parameter into a stored procedure or SQL statement.  This essentially converts overhead performance penalties from O(number of records) to O(number of times you batch insert).  Additionally, by reducing the number of SQL commands being executed, you dramatically reduce database contention and improve performance for other programs.  </p>
<p>Here’s the final insert code including table parameters.  You may notice that I&#8217;ve removed the BeginTransaction() and Commit() calls &#8211; those only boost our performance when we&#8217;re doing more than one ExecuteNonQuery() command at a time.  So here goes:</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
19
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TYPE</span> item_drop_bulk_table_rev4 <span style="color: #993333; font-weight: bold;">AS</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #66cc66;">&#40;</span>
    item_id <span style="color: #993333; font-weight: bold;">BIGINT</span><span style="color: #66cc66;">,</span>
    monster_class_id <span style="color: #993333; font-weight: bold;">INT</span><span style="color: #66cc66;">,</span>
    zone_id <span style="color: #993333; font-weight: bold;">INT</span><span style="color: #66cc66;">,</span>
    xpos <span style="color: #993333; font-weight: bold;">REAL</span><span style="color: #66cc66;">,</span>
    ypos <span style="color: #993333; font-weight: bold;">REAL</span><span style="color: #66cc66;">,</span>
    kill_time datetime
<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">PROCEDURE</span> insert_item_drops_rev4
    @mytable item_drop_bulk_table_rev4 READONLY
<span style="color: #993333; font-weight: bold;">AS</span>
&nbsp;
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> item_drops_rev4 
    <span style="color: #66cc66;">&#40;</span>item_id<span style="color: #66cc66;">,</span> monster_class_id<span style="color: #66cc66;">,</span> zone_id<span style="color: #66cc66;">,</span> xpos<span style="color: #66cc66;">,</span> ypos<span style="color: #66cc66;">,</span> kill_time<span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> 
    item_id<span style="color: #66cc66;">,</span> monster_class_id<span style="color: #66cc66;">,</span> zone_id<span style="color: #66cc66;">,</span> xpos<span style="color: #66cc66;">,</span> ypos<span style="color: #66cc66;">,</span> kill_time 
<span style="color: #993333; font-weight: bold;">FROM</span> 
    @mytable</pre></td></tr></table></div>


<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
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">DataTable dt <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DataTable<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
dt<span style="color: #008000;">.</span><span style="color: #0000FF;">Columns</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> DataColumn<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;item_id&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>Int64<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
dt<span style="color: #008000;">.</span><span style="color: #0000FF;">Columns</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> DataColumn<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;monster_class_id&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
dt<span style="color: #008000;">.</span><span style="color: #0000FF;">Columns</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> DataColumn<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;zone_id&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
dt<span style="color: #008000;">.</span><span style="color: #0000FF;">Columns</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> DataColumn<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;xpos&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">float</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
dt<span style="color: #008000;">.</span><span style="color: #0000FF;">Columns</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> DataColumn<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;ypos&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">float</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
dt<span style="color: #008000;">.</span><span style="color: #0000FF;">Columns</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> DataColumn<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;timestamp&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>DateTime<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> MY_INSERT_SIZE<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    dt<span style="color: #008000;">.</span><span style="color: #0000FF;">Rows</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> item_id, monster_class_id, zone_id, xpos, ypos, DateTime<span style="color: #008000;">.</span><span style="color: #0000FF;">Now</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Now we&amp;#039;re going to do all the work with one connection!</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>SqlConnection conn <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlConnection<span style="color: #008000;">&#40;</span>my_connection_string<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    conn<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>SqlCommand cmd <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlCommand<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;insert_item_drops_rev4&quot;</span>, conn<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">CommandType</span> <span style="color: #008000;">=</span> CommandType<span style="color: #008000;">.</span><span style="color: #0000FF;">StoredProcedure</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// Adding a &quot;structured&quot; parameter allows you to insert tons of data with low overhead</span>
        SqlParameter param <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlParameter<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@mytable&quot;</span>, SqlDbType<span style="color: #008000;">.</span><span style="color: #0000FF;">Structured</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        param<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span> <span style="color: #008000;">=</span> dt<span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Parameters</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>param<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">ExecuteNonQuery</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>And what does the performance of this logic look like for inserting 10,000 records?  We&#8217;re now down to 0.218 seconds, an improvement of over 97% from our initial attempt.  </p>
<h1>Conclusions</h1>
<p>Although this calculation isn&#8217;t perfect, I&#8217;m going to suggest the following estimates for the overhead we encountered in this test.  Out of a total 97% speedup we obtained, I&#8217;m guessing the breakdown goes roughly as follows:</p>
<ul>
<li>First priority: Reducing contention and removing unnecessary locks (a 51 percentage point gain)</li>
<li>Second priority: Reducing the general SQL statement processing overhead by combining multiple queries together (a 31 percentage point gain)</li>
<li>Third priority: Removing unnecessary constraints, VARCHARs, and SQL parser overhead (a 15 percentage point gain)</li>
</ul>
<p>As you can see, you don’t need to abandon SQL Server to get massive performance improvements.  However, it&#8217;s easy to forget about SQL Server performance because the technology is so effective.  We use database wrappers and database abstraction layers that speed our development time, but separate us from the fine details.  If you want to get lots of high performance work out of SQL server, use the same process you’d do if you were tuning C++ code: profile it, track the most frequently called functions, optimize the heck out of them, and finally rethink your work so you call them less frequently.</p>
<p>Finally let me pass some credit to Tom Gaulton and Rich Skorski who provided valuable feedback in the editing of this article.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/16/sql-server-high-performance-inserts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Embrace Freemium</title>
		<link>http://www.altdevblogaday.com/2012/05/15/embrace-freemium/</link>
		<comments>http://www.altdevblogaday.com/2012/05/15/embrace-freemium/#comments</comments>
		<pubDate>Tue, 15 May 2012 09:46:03 +0000</pubDate>
		<dc:creator>Tom Gaulton</dc:creator>
				<category><![CDATA[General Interest]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26212</guid>
		<description><![CDATA[<p><img class="alignleft" style="border-style: initial;border-color: initial;border-width: 0px;margin: 3px" src="http://freemium-games.com/wp-content/uploads/2011/01/freemiumgames.jpg" alt="" width="300" height="240" />Like it or not, the freemium gaming model (i.e. games are free and the money is made via in-app purchases) appears to be here to stay. I’ve seen a lot of concern voiced recently that freemium content is driving down the quality of games, but I don’t believe that’s necessarily true. There are problems that need addressing – but let’s not throw the baby out with the bathwater.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/15/embrace-freemium/" class="more-link">Read more on Embrace Freemium&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft" style="border-style: initial;border-color: initial;border-width: 0px;margin: 3px" src="http://freemium-games.com/wp-content/uploads/2011/01/freemiumgames.jpg" alt="" width="300" height="240" />Like it or not, the freemium gaming model (i.e. games are free and the money is made via in-app purchases) appears to be here to stay. I’ve seen a lot of concern voiced recently that freemium content is driving down the quality of games, but I don’t believe that’s necessarily true. There are problems that need addressing – but let’s not throw the baby out with the bathwater.</p>
<p><strong>A Brief History of Freemium</strong></p>
<p>Take away the freemium model and you’re left with users having to pay for games up front. With traditional disk-based media that worked, the barrier to entry meant that there were relatively few titles on sale so it was possible to get a game noticed given a decent advertising push and by word of mouth – and that meant publishers could afford decent budgets and take a few risks. The business model wasn’t perfect, but it sufficed. Innovation wasn’t always top priority, but the quality bar was fairly consistent.</p>
<p>Fast forward to the age of downloads, in particular the AppStore, and the barrier to entry for developers was suddenly much lower – almost anyone with a computer and a compiler could release a game. Initially this seemed like a good thing, there was much excitement about “indie gaming” and a few notable success stories, but soon the market was flooded and developers began undercutting each other on price in order to get sales.</p>
<p>This process, commonly dubbed “the race to the bottom”, now seems to have run its course, with the majority of games now in the $1-2 bracket, and that has warped the general perception of value. Paying $5 for a game may have seemed cheap once but now looks expensive against the backdrop of bargain bucket titles – despite the fact that people will happily fork out more than that for a latte and a sandwich. As a result it has become incredibly risky to invest in making a high quality game for the mobile and tablet market. Even if your $5+ game is awesome, the chances of enough people finding it and paying for it are slim. They’re more likely to download half a dozen separate dollar titles and conclude that all mobile games are rubbish.</p>
<p>That’s where freemium enters the frame. If you can give your game away for free there’s nothing (bar the initial download) to stop people trying it out – sure, the market is still flooded with choice, but you’ve improved your chances dramatically. Once you’ve got people hooked on your game, then you can start billing them for items, and make your money that way instead &#8211; and because you&#8217;ve already hooked people in you can charge them a lot more than the minimum app price that people have come to expect for paid apps. Recently we’ve seen a few games exploit this system to make large sums of money.</p>
<p><strong>So what’s the problem?</strong></p>
<p>Notice I used the word “exploit” in the last sentence? Well, that’s the problem with freemium at the moment. Games don’t simply draw you in and then ask for a single payment to continue playing; they attempt to sell you a whole plethora of in-game items, often using devious means that encourage addictive behaviour and disguise the true cost. A while back I played a game called Paradise Island on Android that was a perfect example; you could buy special buildings for your island, but the way you did so involved so many different forms of currency along the way that it wasn’t immediately obvious what the cost would be. I once sat down and calculated that the true cost of a single building in their Halloween pack was a staggering $50.</p>
<p>It’s this addiction-feeding style of game which I believe has given freemium such a bad name. After all, if you look back to the era when magazine cover-disks were the norm you realise that freemium has been with us in spirit for decades, even if the buzzword hasn’t.</p>
<p><strong>Can the problem be fixed?</strong></p>
<p>I think we’re beginning to see light at the end of the tunnel. Some recent games have started to implement less aggressive forms of in-app purchasing – for example Triple Town works by limiting the free version to a fixed number of ‘turns’ per day, and gives you the option to purchase unlimited turns for a fixed fee. It still has the option to buy items to essentially cheat your way to victory, but at least you can opt out of that and make a one off payment. It’s a step in the right direction.</p>
<p>Perhaps more importantly though, the Japanese courts have just stepped in to ban the “kompu gacha” mechanic, whereby players pay a small fee for the chance of unlocking a rare item (in essence, a lottery), but can only do so after unlocking a whole set of other items more common items through the same mechanic. It’s only one specific mechanic that they’ve banned, and it’s only the tip of the iceberg, but the case has drawn a lot of attention from the press over the last few days, and looks like it might be the tipping point that wakes regulatory bodies, and players themselves, up to the devious way in which they’ve been manipulated.</p>
<p><strong>Nice Freemium</strong></p>
<p>Much as the makers of yoghurt products keep telling us there “bad bacteria” and “good bacteria”, I believe there can also be “evil freemium” and “nice freemium”. The evil freemium games are built purely to extort money from their players, while nice freemium are good honest fun, that just happens to come in a freemium package.</p>
<p>I doubt we’ve seen the back of evil freemium just yet, but rather than despair at the state of the freemium market, why not try making your own game freemium – just make sure it’s nice freemium.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/15/embrace-freemium/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why I went back into the studio&#8230;&#8230;</title>
		<link>http://www.altdevblogaday.com/2012/05/11/why-i-went-back-into-the-studio/</link>
		<comments>http://www.altdevblogaday.com/2012/05/11/why-i-went-back-into-the-studio/#comments</comments>
		<pubDate>Fri, 11 May 2012 08:26:29 +0000</pubDate>
		<dc:creator>Kevin Dent</dc:creator>
				<category><![CDATA[#AltDev Updates]]></category>
		<category><![CDATA[#AltDevConf]]></category>
		<category><![CDATA[#AltDevPodcast]]></category>
		<category><![CDATA[#AltDevUnconference]]></category>
		<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Audio]]></category>
		<category><![CDATA[Bizdev]]></category>
		<category><![CDATA[Computer Graphics]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Game design]]></category>
		<category><![CDATA[General Interest]]></category>
		<category><![CDATA[Guest Post]]></category>
		<category><![CDATA[Production]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Track]]></category>
		<category><![CDATA[Protected]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[UI and UX]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Visual Arts]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26204</guid>
		<description><![CDATA[<p>I LOVE working in the studio, I really do. I love the freedom it affords me. I love trying to create games that I want to play!</p>
<p>I also really love having a cerabal cortex, so I left the studio life and learned biz magic.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/11/why-i-went-back-into-the-studio/" class="more-link">Read more on Why I went back into the studio&#8230;&#8230;&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I LOVE working in the studio, I really do. I love the freedom it affords me. I love trying to create games that I want to play!</p>
<p>I also really love having a cerabal cortex, so I left the studio life and learned biz magic.</p>
<p>I make a really good living in biz, I LOVE doing what I do now; I get to work with amazing people, I get to talk to amazing people. For the love of god, I spoke to the creator of Fruit Ninja tonight to have &#8220;chat&#8221;. How cool is that? Dude totally rocks btw.</p>
<p>My gig allows me to talk to my heroes. Seriously, I love playing video games that much.</p>
<p>The most common thing people say to me is &#8220;&#8230;.wow, you are a business guy and you love playing video games?&#8221;</p>
<p>When I stepped out of the studio, I made myself the pledge that I would only work on titles that touched me deeply. I would only work on games that I personally wanted to play. I would be way richer if I just kissed ass and decided to suck it up for the lord, god, almighty dollar!</p>
<p>If I do say so myself, I was pretty decent on the creative side of things too, but to be brutally honest; I was running a studio that sucked at business.</p>
<p>So one day I stopped. One day I decided that I would step out of the studio. I put a 22 year old in charge of it and for 7 mobile games -feature phones- he was shit. Then he just flipped the page and was brilliant.</p>
<p>Recently, I met a guy called Jason Brice. He sent me @ messages constantly, he was really cool and then one day I seen the maps he made in an FPS.</p>
<p>OMFG</p>
<p>They were great!</p>
<p>I looked at them -I hated the crane on the harbor map- BUT I loved the game itself.</p>
<p>Jason was creating the game that I wanted to play.</p>
<p>His view was that there were way too many layers between the player and AK47&#8242;ing another guy in the face.</p>
<p>He had me at &#8220;hello&#8221;.</p>
<p>So as I play this game, I talk about it, I reveal things about it and then I talk about it again.</p>
<p>Simply put, THIS IS GAMING!</p>
<p>I listen to an average of 14 game pitches a week, this was one of the first game pitches that I have seen that melted my resolve. Here I thought that I knew everything and these noobz are teaching me how to love video gaming again.</p>
<p>I want to be fair, I want to be honest and I do not want to be a prick.</p>
<p>BUT I am sick of the modern day FPS titles or as I like to call them &#8220;We just came up with another feature that allows us to get you to buy another sequel&#8221;&#8230;&#8230;&#8230;&#8230;.. ok that is a long title.</p>
<p>I am sick that on NPD day that we all shiver with anticipation at how many people bought our game. Here is a novel fucking idea, I am sick with anticipation at the thought of how many people enjoyed our game.</p>
<p>The game is ReKoil BTW. BUY IT PLUX</p>
<p>I am my most vulnerable when I am sitting in front of a metrics screen looking at the numbers, asking, wanting, no begging video gamers to like my title.</p>
<p>That is weak sauce, I want them to like me. I want them, no I crave that they like me!</p>
<p>It is the vulnerable essence of every video game maker. It is that vulnerability that allows me to exist.</p>
<p>This very insecurity, allows me to make games that I want to play, this insecurity allows Jason and the team to jump off a cliff and trust the fact that someone on the team will catch him.</p>
<p>Guess what? When someone that you consider a blood friend jumps off a cliff; you always catch them.</p>
<p>I am proud of what we are making today, I love that we are participating in the conversation! Will we beat Black-Op&#8217;s 2? God no! Their budget is 60X what people say that we are worth, but we will be participating in the conversation.</p>
<p>We are basically fighting the good fight, we are throwing punches and getting the shit kicked out of us. BUT we are Marty McFly and we will knock Biff the fuck out.</p>
<p>Am I desperate? FUCK YEAH!</p>
<p>Just tonight I sent this email:</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><strong>From:</strong> Kevin Dent [mailto:<a href="mailto:kevin@XXX.XXXX">kevin@XXX.XXXX</a>]<br />
<strong>Sent:</strong> Thursday, May 10, 2012 8:50 PM<br />
<strong>To:</strong> &#8216;Andy McNamara&#8217;<br />
<strong>Subject:</strong> Front cover</p>
<p>Hi Andy,</p>
<p>Who do I have to screw to get the front cover for ReKoil?</p>
<p>Cheers,</p>
<p>Kevin</p>
<p>&nbsp;</p>
<p>As of today, we are not on Kickstarter, we are totally self-funded and we are totally throwing ourselves under the bus in an attempted to make a better game.</p>
<p>Let me be clear, Andy is an amazing person and I love him dearly. He is smart, contiencious and endearing. BUT Game Informer is owned by Game Stop and those dudes are hardcore publisher fuckers, there is zero chance of us getting the cover.</p>
<p>There is no way that, me, you or your freak parents will get us on the front cover of GI and nor should it. Brilliant games get on there 12 a year at least.</p>
<p>That said, it was worth a shot, we are living in the era of the indie.</p>
<p>There has been so many amazing titles in the last twelve months made by people with way more talent than me.</p>
<p>I rejoice at the next gen of game creators.</p>
<p>I am humbed by them.</p>
<p>But the truth is, that Jason Brice, asked me to jump off a cliff and I made the leap.</p>
<p>Who will catch me?</p>
<p>Kevin</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/11/why-i-went-back-into-the-studio/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Four reasons we&#8217;re not as good as we could be</title>
		<link>http://www.altdevblogaday.com/2012/05/10/four-reasons-were-not-as-good-as-we-could-be/</link>
		<comments>http://www.altdevblogaday.com/2012/05/10/four-reasons-were-not-as-good-as-we-could-be/#comments</comments>
		<pubDate>Thu, 10 May 2012 09:43:55 +0000</pubDate>
		<dc:creator>Chad Moore</dc:creator>
				<category><![CDATA[General Interest]]></category>
		<category><![CDATA[communication]]></category>
		<category><![CDATA[distractions]]></category>
		<category><![CDATA[simplicity]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25874</guid>
		<description><![CDATA[<pre></pre>
<blockquote><p>The lizard brain is not merely a concept. It&#8217;s real, and it&#8217;s living on the top of your spine, fighting for your survival. But, of course, survival and success are not the same thing. The lizard brain is the reason you&#8217;re afraid, the reason you don&#8217;t do all the art you can, the reason you don&#8217;t ship when you can. The lizard brain is the source of the resistance.”<br />
― <a href="http://www.sethgodin.com/sg/" target="_blank">Seth Godin</a>, <a href="http://www.amazon.com/exec/obidos/ASIN/1591843162/permissionmarket" target="_blank">Linchpin: Are You Indispensable</a>?
</p></blockquote>
<p><a href="http://www.altdevblogaday.com/2012/05/10/four-reasons-were-not-as-good-as-we-could-be/" class="more-link">Read more on Four reasons we&#8217;re not as good as we could be&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<pre></pre>
<blockquote><p>The lizard brain is not merely a concept. It&#8217;s real, and it&#8217;s living on the top of your spine, fighting for your survival. But, of course, survival and success are not the same thing. The lizard brain is the reason you&#8217;re afraid, the reason you don&#8217;t do all the art you can, the reason you don&#8217;t ship when you can. The lizard brain is the source of the resistance.”<br />
― <a href="http://www.sethgodin.com/sg/" target="_blank">Seth Godin</a>, <a href="http://www.amazon.com/exec/obidos/ASIN/1591843162/permissionmarket" target="_blank">Linchpin: Are You Indispensable</a>?
</p></blockquote>
<p>I&#8217;ve adapted a guest post I wrote over at <a href="http://www.becomingminimalist.com/2011/08/29/leveling-up-my-single-tasking/" target="_blank">becoming minimalist</a> to speak more to game development. Thanks to <a href="https://twitter.com/#!/joshua_becker" target="_blank">Joshua Becker</a> for the opportunity to write for his blog and his help with the original post. </p>
<p>I&#8217;ve been giving a lot of thought to single tasking, focus and distractions in my professional and personal life. Here is what I believe to be the four biggest factors contributing to distracting us from doing great creative work. By the way &#8220;creative work&#8221; to me means art, code, design, music you name it. Many facets and roles in gamedev are creative, perhaps not at first glance, but any creative problem solving applies, in my humble opinion.</p>
<p><strong>#1 We&#8217;re distracted by notifications</strong><br />
Everyone is “always on”. We have our email open all day and internal instant messaging clients humming – not to mention the external social networks and IM chats. Instant notifications are being pushed from everywhere to wherever we are at the moment, sitting at our desktops or walking about with our phones. Most of us are on digital leashes of some kind even when we don’t need to be. We&#8217;re in a state of constant multiple deliverables or actionable tasks as well as completely open to distractions. How do we get anything done?</p>
<p>Some studies even propose that people can be addicted to the micro-endorphin rush we get when we get an email or a tweet. That’s why we can’t stop checking our phones when we’re away from work or even when we’re <a href="http://tweetagewasteland.com/2010/08/pull-over-before-you-read-this/" target="_blank">driving</a>. Most folks agree that these short bursts of interruptions are <a href="http://www.nytimes.com/2010/06/07/technology/07brain.html?_r=1" target="_blank">changing our brains</a>. </p>
<p>Can you read through this entire 1500 hundred word post without a notification going off?</p>
<p><strong>#2 We&#8217;re distracted by geography</strong><br />
Office geography has the entire team sitting in cube farms. These close-knit cubes are designed to “enhance communication.” For example, artists can quickly look over the half-wall and ask a programmer a question. This is great for immediate problem solving, however, the creative tasks we perform require dedicated and focused work in order to be fully realized. The constant interruptions hinder our productivity. What&#8217;s the tradeoff? Does the immediate communication outweigh the lack of focus?</p>
<p>Interruptions are hurting productivity, not helping it. </p>
<p><strong>#3 We can&#8217;t focus</strong><br />
In this land of distractions, how do we concentrate long enough on a creative task to produce quality? Mental context switching is hard to quantify as there are so many variables. However, I have heard that switching between 3 tasks costs a person 40% of their available work time. You can just throw (at least) one of those tasks out the window, I hope it wasn&#8217;t important.</p>
<p>Does your company have a lot of meetings? Meetings in the middle of the day can be a drastic productivity and creativity killer. </p>
<p>Multi-tasking just doesn&#8217;t work. Is there a &#8220;sweet spot&#8221; in your workday that you can work uninterrupted for more than an hour on a single task? </p>
<p><strong>#4 We&#8217;re comfortable and afraid</strong><br />
Our lizard brains want us to be stuck in a rut. Safety is the Lizard Brain&#8217;s primary objective. Safe is free of conflicts and challenges. Safe is the same thing over and over again. Safe is not standing out in the crowd. Safe, as the lizard brain defines it, is not good for your creativity and thereby the projects you work on.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/iggy_hdr.jpeg"><img src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/iggy_hdr.jpeg" alt="" width="385" height="255" class="alignleft size-full wp-image-25995" /></a><br />
Image courtesy of <a href="http://www.altdevblogaday.com/author/alex-moore/" target="_blank">Alex Moore</a></p>
<p>Here are some of the things that I&#8217;m using or trying out to combat the lizard brain, distractions and multi-tasking. </p>
<p><strong>Control your time. </strong><br />
Batch processing your email can be effective. Once at the beginning of the day and again at the end. This is more efficient than shifting to outlook with each new notification and processing each single email. If you think that is too long to be out of contact, do the email dance for 10 minutes every two hours. Or whatever works for you, just try to keep the notifications off. If there truly is an emergency you will know, someone will come find you.</p>
<p>Turn off your work IM. Same rules as above. Maybe you&#8217;re available and on IM only in the afternoon. Or set your status to do not disturb and teach people politely what that means. Try things and see how they work for you.</p>
<p>Do one thing at a time. Make a list of the 3 or 5 most important things for that day. Do them as early in the day as you can. You&#8217;ll accomplish the &#8220;big things&#8221; early and everything else after that is icing on the cake.</p>
<p>All of this can be tricky at first if your culture wants you to respond immediately, but I think it pays off in the end. You have more uninterrupted time to do something good. Talk to your manager if you need to before implementing a radical change. </p>
<p><strong>Have the good kind of meetings.</strong><br />
The morning standup with your team is probably the best type of meeting. It&#8217;s early, not in the middle of the day. Everyone says what they are working on, if anything is blocking them and what they&#8217;ll do next. Preferably everyone stands. It is called a stand up after all. This is a bold choice, but decline any meeting that you think is a waste of time. Reply that you can&#8217;t make it and ask for a recap. Meeting Agendas and Recaps are such a great tool for meetings, we seem to forget about them. </p>
<p>The Agenda: When booking the meeting provide a list of what topics to discuss, who is responsible for talking for each topic and a guesstimate on how long they&#8217;ll have to talk. Send the agenda out a couple of days beforehand and make it known that the attendees are expected to be prepared. <a href="http://www.altdevblogaday.com/author/simon-cooke/" target="_blank">Simon Cooke</a> suggests formulating the agenda as questions to get people thinking and vested.</p>
<p>During the meeting, stick to the schedule. Get in, do good stuff, get out. </p>
<p>The Recap: briefly state what was discussed.</p>
<p>Here&#8217;s a sample meeting agenda:</p>
<p>Todays Date, Galactic Domination Meeting Agenda</p>
<ul>
<li>Overview, Palpatine, 15 minutes</li>
<li>Death Star #2 construction status, Tarkin, 5 minutes</li>
<li>Various disturbances in the force, Vader, 10 minutes</li>
</ul>
<p>And the recap:</p>
<dl>
<dt>Overview, Palpatine, 15 minutes</dt>
<dd>Squash rebellion by destroying secret base.</dd>
<dd>Eliminate Galactic Senate via political maneuvering.</dd>
<dt>Death Star #2 construction status, Tarkin, 5 minutes</dt>
<dd>We fixed the exhaust port / proton torpedo bug</dd>
<dt>Various disturbances in the force, Vader, 10 minutes</dt>
<dd>Obi-Wan is dead, but no one is sure why he just disappeared.</dd>
<dd>Follow up on plan to turn Son of Skywalker to the dark side.</dd>
</dl>
<p><strong>Wait.</strong><br />
Can you wait a while to talk to the artist? Look at him, he has his headphones on (game developer code for “Do Not Disturb”) and is obviously “in the zone” sculpting in the 3D modeling application with a ton of reference images on the other monitor. Don’t interrupt him asking for his hours spent this week on his tasks. Let him do his job. That User Interface Engineer who’s sliding her chair back and forth from her development kit and her two-screen computer rig? She’s fixing a bug in the UI on her computer, testing it on the kit, and she’s obviously busy. Do not walk over and ask her how it’s going right now. Let her do her job. Your opportunity to ask your question will come… but you may need to wait your turn to ask it.</p>
<p><strong>Get people on board.</strong><br />
Use team signals to tell others “do not disturb.” I’ve seen flags put up by artists to denote when they are in the zone and to please come back later. I’ve also seen tech teams have one team member wear a hat signaling that he/she is the person on call for help that day. Find a way of signaling people and teach them to recognize and respect it. Work it out with your team so you can be efficient together.</p>
<p><strong>Protect your industry’s most valuable asset.</strong><br />
The most valuable asset any company has are its people.  People make the art, tech and design of a game. They support the game or the other people making the games. There are certain parts of the day when creativity runs wild and other parts of the day that are more suitable for less creative tasks. Do what you can to help reduce roadblocks and ask your Manager for support. </p>
<p>I certainly don’t have all the answers. But I&#8217;m trying to communicate with one person at a time, handle one problem at a time, and work on one idea at a time. All as a part of my effort to bring the principles of minimalism, simplicity and single tasking into my personal and professional life. I&#8217;d love to hear your thoughts on these topics.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/10/four-reasons-were-not-as-good-as-we-could-be/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C/C++ Low Level Curriculum Part 8: looking at optimised assembly</title>
		<link>http://www.altdevblogaday.com/2012/05/07/cc-low-level-curriculum-part-8-looking-at-optimised-assembly/</link>
		<comments>http://www.altdevblogaday.com/2012/05/07/cc-low-level-curriculum-part-8-looking-at-optimised-assembly/#comments</comments>
		<pubDate>Mon, 07 May 2012 22:35:39 +0000</pubDate>
		<dc:creator>Alex Darby</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26021</guid>
		<description><![CDATA[<p>It&#8217;s that time again where I have managed to find a few spare hours to squoze out an article for the Low Level Curriculum. This is the 8th post in this series, which is not in any way significant except that I like the number 8. As well as being a power of two, it is also the maximum number of unarmed people who can simultaneously get close enough to attack you (according to a martial arts book I once read).</p>
<p><a href="http://www.altdevblogaday.com/2012/05/07/cc-low-level-curriculum-part-8-looking-at-optimised-assembly/" class="more-link">Read more on C/C++ Low Level Curriculum Part 8: looking at optimised assembly&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s that time again where I have managed to find a few spare hours to squoze out an article for the Low Level Curriculum. This is the 8th post in this series, which is not in any way significant except that I like the number 8. As well as being a power of two, it is also the maximum number of unarmed people who can simultaneously get close enough to attack you (according to a martial arts book I once read).</p>
<p>This post covers how to set up Visual Studio to allow you to easily look at the optimised assembly code generated for simple code snippets like the ones we deal with in this series. If you wonder why I feel this is worth a post of its own here&#8217;s the reason &#8211; optimising compilers are good, and given code with constants as input and no external output (like the snippets I give as examples in this series) the compiler will generally optimise the code away to nothing &#8211; which I find makes it pretty hard to look at. This should prove immensely useful, both to refer back to, and for your own experimentation.</p>
<p><span id="more-26021"></span>Here are the backlinks for preceding articles in the series in case you want to refer back to any of them (warning: the first few are quite long):</p>
<ol>
<li><a href="http://www.altdevblogaday.com/2011/11/09/a-low-level-curriculum-for-c-and-c/" rel="nofollow">http://altdevblogaday.com/2011/11/09/a-low-level-curriculum-for-c-and-c/</a></li>
<li><a href="http://www.altdevblogaday.com/2011/11/24/c-c-low-level-curriculum-part-2-data-types/" rel="nofollow">http://altdevblogaday.com/2011/11/24/c-c-low-level-curriculum-part-2-data-types/</a></li>
<li><a href="http://www.altdevblogaday.com/2011/12/14/c-c-low-level-curriculum-part-3-the-stack/">http://altdevblogaday.com/2011/12/14/c-c-low-level-curriculum-part-3-the-stack/</a></li>
<li><a href="http://www.altdevblogaday.com/2011/12/24/c-c-low-level-curriculum-part-4-more-stack/">http://altdevblogaday.com/2011/12/24/c-c-low-level-curriculum-part-4-more-stack/</a></li>
<li><a href="http://www.altdevblogaday.com/2012/02/07/c-c-low-level-curriculum-part-5-even-more-stack/">http://altdevblogaday.com/2012/02/07/c-c-low-level-curriculum-part-5-even-more-stack/</a></li>
<li><a href="http://www.altdevblogaday.com/2012/03/07/c-c-low-level-curriculum-part-6-conditionals/">http://altdevblogaday.com/2012/03/07/c-c-low-level-curriculum-part-6-conditionals/</a></li>
</ol>
<h1>Assumptions</h1>
<p>Strictly speaking, dear reader, I am making tonnes of assumptions about you as I write this &#8211; that you read English, that you like to program etc. but we&#8217;ll be here all day if I try to list those so let&#8217;s stick to the ones that might be immediately inconvenient if they were incorrect.</p>
<p>I will be assuming that you have access to some sub-species of Visual Studio 2010 on a Windows PC, and that you are familiar with using it to do all the everyday basics like change build configurations, open files, edit, compile, run, and debug C/C++.</p>
<h1>Creating a project</h1>
<p>Open Visual Studio and from the menu choose &#8220;File -&gt; New -&gt; Project&#8230;&#8221;.</p>
<p>Once the new project wizard window opens (see below):</p>
<ul>
<li>go to the tree view on the left of the window and select &#8220;Other Languages -&gt; Visual C++&#8221;</li>
<li>in the main pane select &#8220;Win32 Console Application   Visual C++&#8221;</li>
<li>give it a name in the <strong><em>Name </em></strong>edit box</li>
<li>browse for a location of your choosing on your PC</li>
<li>click OK to create the project</li>
</ul>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/CLLC_8OptAsm_NewProjectWizard.png"><img class="alignnone size-full wp-image-26025" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/CLLC_8OptAsm_NewProjectWizard.png" alt="" width="810" height="450" /></a></p>
<p>Once you have clicked OK just click &#8220;Finish&#8221; on the next stage of the wizard &#8211; in case you&#8217;re wondering, the options available when you click next don&#8217;t matter for our purposes (and un-checking the &#8220;Precompiled header&#8221; check box makes no difference, it still generates a console app that uses a precompiled header&#8230;).</p>
<h1>Changing the Project Properties</h1>
<p>The next step is to use the menu to select &#8220;Project -&gt; <em>&lt;YourProjectName&gt;</em> Properties&#8221;, which will bring up the properties dialog for the project.</p>
<p>When the properties dialog appears (see image below):</p>
<ul>
<li>select &#8220;All Configurations&#8221; from the Configuration drop list</li>
<li>select &#8220;Configuration Properties -&gt;General&#8221; in the tree view at the left of the window</li>
<li>in the main pane change &#8220;Whole Program Optimisation&#8221; to &#8220;No Whole Program Optimisation&#8221;.</li>
</ul>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/CLLC_8OptAsm_ProjectProperties.png"><img class="alignnone size-full wp-image-26026" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/CLLC_8OptAsm_ProjectProperties.png" alt="" width="851" height="604" /></a></p>
<p>Next, in the tree view (see image below):</p>
<ul>
<li>in the tree view, navigate to &#8220;C/C++ -&gt; Code Generation&#8221;</li>
<li>in the main pane, change &#8220;Basic Runtime Checks&#8221; to &#8220;Default&#8221; (i.e. off)</li>
</ul>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/CLLC_8OptAsm_ProjProps_RTChecks.png"><img class="alignnone size-full wp-image-26103" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/CLLC_8OptAsm_ProjProps_RTChecks.png" alt="" width="851" height="604" /></a></p>
<p>Finally (see image below):</p>
<ul>
<li>in the tree view, go to &#8220;C/C++ -&gt; Output Files&#8221;</li>
<li>in the main pane change &#8220;Assembler Output&#8221; to &#8220;Assembly With Source Code /(FAs)&#8221;</li>
<li>once you&#8217;ve done that click &#8220;OK&#8221;</li>
</ul>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/CLLC_8OptAsm_ProjProps_AsmListing.png"><img class="alignnone size-full wp-image-26028" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/CLLC_8OptAsm_ProjProps_AsmListing.png" alt="" width="851" height="604" /></a></p>
<p>Now, when you compile the Visual Studio compiler will generate an <em><strong>.asm</strong></em> file as well as an <em><strong>.exe</strong></em> file. This file will contain the intermediate assembly code generated by the compiler, with the source code inserted into it inline as comments.</p>
<p>You could alternatively choose the &#8220;Assembly, Machine Code and Source (/FAcs)&#8221; option if you like &#8211; this will generate a .cod file that contains the machine code as well as the asm and source.</p>
<p>I prefer the regular .asm because it&#8217;s less visually noisy and the assembler mnemonics are all aligned on the same column, so that&#8217;s what I&#8217;ll assume you&#8217;re using if you&#8217;re following the article, but the .cod file is fine.</p>
<h1>So, what did we do there?</h1>
<p>Well, first we turned off link time code generation. Amongst other things, this will prevent the linker stripping the .asm generated for functions that are compiled but not called anywhere.</p>
<p>Secondly, we turned off the basic runtime checks (which are already off in Release). These checks make the function prologues and epilogues generated do significant amounts of (basically unneccessary) extra work causing a worst case 5x slowdown (see <a href="http://randomascii.wordpress.com/2011/07/22/visual-c-debug-buildsfast-checks-cause-5x-slowdowns/">this post </a>by Bruce Dawson on his personal blog for an in depth explanation).</p>
<p>Finally, we asked the compiler not to throw away the assembly code it generates for our program; this data is produced by the compilation process whenever you compile but is usually thrown away, we&#8217;re just asking Visual Studio to write it into an <em><strong>.asm</strong></em> file so we can take a look at it.</p>
<p>Since we made these changes for &#8220;All Configurations&#8221; this means we will have access to <em><strong>.asm</strong></em> files containing the assembly code generated by both the Debug and Release build configurations.</p>
<h1>Let&#8217;s try it out</h1>
<p>So in the spirit of discovery, let&#8217;s try it out (for the sake of familiarity) with a language feature we looked at last time &#8211; the conditional operator:</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
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;stdafx.h&quot;</span>
&nbsp;
<span style="color: #993333;">int</span> ConditionalTest<span style="color: #009900;">&#40;</span> bool bFlag<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> iOnTrue<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> iOnFalse <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span> bFlag <span style="color: #339933;">?</span> iOnTrue <span style="color: #339933;">:</span> iOnFalse <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> argv<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> a <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> b <span style="color: #339933;">=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
    bool bFlag <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> c <span style="color: #339933;">=</span> ConditionalTest<span style="color: #009900;">&#40;</span> bFlag<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: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The question you have in your head at this moment should be &#8220;why have we put the code into a function?&#8221;. Rest assured that this will become apparent soon enough.</p>
<p>Now we have to build the code and look in the <em><strong>.asm</strong></em> files generated to see what the compiler has been up to&#8230;</p>
<p>First build the Debug build configuration &#8211; this should already be selected in the solution configuration drop-down (at the top of your Visual Studio window unless you&#8217;ve moved it).</p>
<p>Next build the Release configuration.</p>
<p>Now we need to open the .asm files. Unless you have messed with project settings that I didn&#8217;t tell you to these will be in the following paths:</p>
<p style="padding-left: 30px">&lt;<em>path where you put the project</em>&gt;/Debug/&lt;<em>projectName</em>&gt;.asm</p>
<p style="padding-left: 30px">&lt;<em>path where you put the project</em>&gt;/Release/&lt;<em>projectName</em>&gt;.asm</p>
<h1>.asm files</h1>
<p>I&#8217;m not going to go into any significant detail about how<em><strong> .asm</strong></em> files are laid out here, if you want to find out more here&#8217;s a link to the <a href="http://msdn.microsoft.com/en-us/library/afzk3475.aspx">Microsoft documentation for their assembler</a>.</p>
<p>The main thing you should note is that we can find the C/C++ functions in the <em><strong>.asm</strong></em> file by looking for their names; and that &#8211; once we find them &#8211; the mixture of source code and assembly code looks basically the same as it does in the disassembly view of Visual Studio in the debugger.</p>
<h1>main()</h1>
<p>Let&#8217;s look at main() first. This is where I explain why the code snippet we wanted to look at was put in a function. I can tell you&#8217;re excited.</p>
<p>Here&#8217;s main() from the Debug .asm (I&#8217;ve reformatted it slightly to make it take up less vertical space):</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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;">_TEXT    <span style="color: #000000; font-weight: bold;">SEGMENT</span>
_c$ = <span style="color: #339933;">-</span><span style="color: #0000ff;">16</span>                        <span style="color: #666666; font-style: italic;">; size = 4</span>
_bFlag$ = <span style="color: #339933;">-</span><span style="color: #0000ff;">9</span>                        <span style="color: #666666; font-style: italic;">; size = 1</span>
_b$ = <span style="color: #339933;">-</span><span style="color: #0000ff;">8</span>                        <span style="color: #666666; font-style: italic;">; size = 4</span>
_a$ = <span style="color: #339933;">-</span><span style="color: #0000ff;">4</span>                        <span style="color: #666666; font-style: italic;">; size = 4</span>
_argc$ = <span style="color: #0000ff;">8</span>                        <span style="color: #666666; font-style: italic;">; size = 4</span>
_argv$ = <span style="color: #0000ff;">12</span>                        <span style="color: #666666; font-style: italic;">; size = 4</span>
_main    <span style="color: #000000; font-weight: bold;">PROC</span>                        <span style="color: #666666; font-style: italic;">; COMDAT</span>
<span style="color: #666666; font-style: italic;">; 9    : {</span>
    <span style="color: #00007f; font-weight: bold;">push</span>    <span style="color: #00007f;">ebp</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">ebp</span><span style="color: #339933;">,</span> <span style="color: #00007f;">esp</span>
    <span style="color: #00007f; font-weight: bold;">sub</span>    <span style="color: #00007f;">esp</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">80</span>                    <span style="color: #666666; font-style: italic;">; 00000050H</span>
    <span style="color: #00007f; font-weight: bold;">push</span>    <span style="color: #00007f;">ebx</span>
    <span style="color: #00007f; font-weight: bold;">push</span>    <span style="color: #00007f;">esi</span>
    <span style="color: #00007f; font-weight: bold;">push</span>    <span style="color: #00007f;">edi</span>
<span style="color: #666666; font-style: italic;">; 10   :     int a = 1, b = 2;</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _a$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">1</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _b$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">2</span>
<span style="color: #666666; font-style: italic;">; 11   :     bool bFlag = false;</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #000000; font-weight: bold;">BYTE</span> <span style="color: #000000; font-weight: bold;">PTR</span> _bFlag$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">0</span>
<span style="color: #666666; font-style: italic;">; 12   :     int c = ConditionalTest( bFlag, a, b );</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _b$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
    <span style="color: #00007f; font-weight: bold;">push</span>    <span style="color: #00007f;">eax</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">ecx</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _a$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
    <span style="color: #00007f; font-weight: bold;">push</span>    <span style="color: #00007f;">ecx</span>
    <span style="color: #00007f; font-weight: bold;">movzx</span>    <span style="color: #00007f;">edx</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">BYTE</span> <span style="color: #000000; font-weight: bold;">PTR</span> _bFlag$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
    <span style="color: #00007f; font-weight: bold;">push</span>    <span style="color: #00007f;">edx</span>
    <span style="color: #00007f; font-weight: bold;">call</span>    ?ConditionalTest@@YAH_NHH@Z        <span style="color: #666666; font-style: italic;">; ConditionalTest</span>
    <span style="color: #00007f; font-weight: bold;">add</span>    <span style="color: #00007f;">esp</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">12</span>                    <span style="color: #666666; font-style: italic;">; 0000000cH</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _c$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #00007f;">eax</span>
<span style="color: #666666; font-style: italic;">; 13   :     return 0;</span>
    <span style="color: #00007f; font-weight: bold;">xor</span>    <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #00007f;">eax</span>
<span style="color: #666666; font-style: italic;">; 14   : }</span>
    <span style="color: #00007f; font-weight: bold;">pop</span>    <span style="color: #00007f;">edi</span>
    <span style="color: #00007f; font-weight: bold;">pop</span>    <span style="color: #00007f;">esi</span>
    <span style="color: #00007f; font-weight: bold;">pop</span>    <span style="color: #00007f;">ebx</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">esp</span><span style="color: #339933;">,</span> <span style="color: #00007f;">ebp</span>
    <span style="color: #00007f; font-weight: bold;">pop</span>    <span style="color: #00007f;">ebp</span>
    <span style="color: #00007f; font-weight: bold;">ret</span>    <span style="color: #0000ff;">0</span>
_main    <span style="color: #000000; font-weight: bold;">ENDP</span>
_TEXT    <span style="color: #000000; font-weight: bold;">ENDS</span></pre></td></tr></table></div>

<p>As long as you&#8217;ve read the previous posts, this should mostly look pretty familiar.</p>
<p>It breaks down as follows:</p>
<ul>
<li>lines 1-8: these lines define the offsets of the various Stack variables from <em><strong>[ebp]</strong></em> within main()&#8217;s Stack Frame</li>
<li>lines 10-15: function prologue of main()</li>
<li>lines 17-20: initialise the Stack variables</li>
<li>lines 22-30: push the parameters to ConditionalTest() into the Stack, call it, and assign its return value</li>
<li>line 32: sets up main()&#8217;s return value</li>
<li>lines 34-38: function epilogue of main()</li>
<li>line 39: return from main()</li>
</ul>
<p>Nothing unexpected there really, the only new thing to take in is the declarations of the Stack variable offsets from <em><strong>[ebp]</strong></em>.</p>
<p>I feel these tend to make the assembly code easier to follow than the code in the disassembly window in the Visual Studio debugger.</p>
<p>And, for comparison, here&#8217;s main() for the Release .asm:</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
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;">_TEXT    <span style="color: #000000; font-weight: bold;">SEGMENT</span>
_argc$ = <span style="color: #0000ff;">8</span>                        <span style="color: #666666; font-style: italic;">; size = 4</span>
_argv$ = <span style="color: #0000ff;">12</span>                        <span style="color: #666666; font-style: italic;">; size = 4</span>
_main    <span style="color: #000000; font-weight: bold;">PROC</span>                        <span style="color: #666666; font-style: italic;">; COMDAT</span>
<span style="color: #666666; font-style: italic;">; 10   :     int a = 1, b = 2;</span>
<span style="color: #666666; font-style: italic;">; 11   :     bool bFlag = false;</span>
<span style="color: #666666; font-style: italic;">; 12   :     int c = ConditionalTest( bFlag, a, b );</span>
<span style="color: #666666; font-style: italic;">; 13   :     return 0;</span>
    <span style="color: #00007f; font-weight: bold;">xor</span>    <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #00007f;">eax</span>
<span style="color: #666666; font-style: italic;">; 14   : }</span>
    <span style="color: #00007f; font-weight: bold;">ret</span>    <span style="color: #0000ff;">0</span>
_main    <span style="color: #000000; font-weight: bold;">ENDP</span>
_TEXT    <span style="color: #000000; font-weight: bold;">ENDS</span></pre></td></tr></table></div>

<p>The astute amongst you will have noticed that the Release assembly code is significantly smaller than the Debug.</p>
<p>In fact, it&#8217;s clearly doing nothing at all other than returning 0. Good optimising! High five!</p>
<p>As I alluded to earlier, the optimising compiler is great at spotting code that evaluates to a compile time constant and will happily replace any code it can with the equivalent constant.</p>
<h1>So that&#8217;s why we put the code snippet in a function</h1>
<p>It should hopefully be relatively clear by this point why we might have put the code snippet into a function, and then asked the linker not to remove code for functions that aren&#8217;t called.</p>
<p>Even if it can optimise away calls to a function, the compiler can&#8217;t optimise away the function before link time because some code outside of the object file it exists in <em>might</em> call it. Incidentally, the same effect usually keeps variables defined at global scope from being optimised away before linkage.</p>
<p>I&#8217;m going to call this <a href="http://en.wikipedia.org/wiki/Schr%C3%B6dinger%27s_cat"><em><strong>Schrödinger linkage</strong></em></a> (catchy, right?). If we want our simple code snippet to stay around after optimising we only need to make sure that it takes advantage of Schrödinger linkage to cheat the optimiser.</p>
<p>If the compiler can&#8217;t tell whether the function will be called, then it certainly can&#8217;t tell what the values of its parameters will be during one of these potential calls, or what its return value might be used for and so it can&#8217;t optimise away any code that relies on those inputs or contributes to the output either.</p>
<p>The upshot of this is that if we put our code snippet in a function, make sure that it uses the function parameters as inputs, and that its output is returned from the function then it should survive optimisation.</p>
<p>It&#8217;s really a testament to all the compiler programmers over the years that it takes so much effort to get at the optimised assembly code generated by a simple code snippet &#8211; compiler programmers we salute you!</p>
<h1>ConditionalTest()</h1>
<p>So, here&#8217;s the Debug .asm for ConditionalTest() (ignoring the prologue / epilogue):</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
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">; 5    :     return( bFlag ? iOnTrue : iOnFalse );</span>
    <span style="color: #00007f; font-weight: bold;">movzx</span>    <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">BYTE</span> <span style="color: #000000; font-weight: bold;">PTR</span> _bFlag$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
    <span style="color: #00007f; font-weight: bold;">test</span>    <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #00007f;">eax</span>
    <span style="color: #00007f; font-weight: bold;">je</span>    <span style="color: #000000; font-weight: bold;">SHORT</span> $LN3@Conditiona
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">ecx</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _iOnTrue$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> tv66<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #00007f;">ecx</span>
    <span style="color: #00007f; font-weight: bold;">jmp</span>    <span style="color: #000000; font-weight: bold;">SHORT</span> $LN4@Conditiona
$LN3@Conditiona<span style="color: #339933;">:</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">edx</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _iOnFalse$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> tv66<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #00007f;">edx</span>
$LN4@Conditiona<span style="color: #339933;">:</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> tv66<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
<span style="color: #666666; font-style: italic;">; 6    : }</span></pre></td></tr></table></div>

<p>As you should be able to see, this is doing the basically same thing as the code we looked at in the Debug disassembly in the <a href="http://http://www.altdevblogaday.com/2012/04/10/cc-low-level-curriculum-part-7-more-conditionals/">previous article</a>:</p>
<ul>
<li>branching based on the result of <em><strong>test</strong></em>ing the value of bFlag (the mnemonic <em><strong>test</strong></em> does a bitwise logical AND)</li>
<li>both branches set a Stack variable at an offset of <em><strong>tv66</strong></em> from <em><strong>[ebp]</strong></em></li>
<li>and both branches then execute the last line which copies the content of that address into <em><strong>eax</strong><strong><br />
</strong></em></li>
</ul>
<p>Again, the assembly code is arguably easier to follow than the corresponding disassembly because the <em><strong>jmp</strong></em> mnemonic jumps to labels visibly defined in the code, whereas in the disassembly view in Visual Studio you generally have to cross reference the operand to <em><strong>jmp</strong></em> with the memory addresses in the disassembly view to see where it&#8217;s <em><strong>j</strong></em>u<em><strong>mp</strong></em>ing to&#8230;</p>
<p>Let&#8217;s compare this with the Release assembler (again not showing the function prologue or epilogue):</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;"><span style="color: #666666; font-style: italic;">; 5    :     return( bFlag ? iOnTrue : iOnFalse );</span>
    <span style="color: #00007f; font-weight: bold;">cmp</span>    <span style="color: #000000; font-weight: bold;">BYTE</span> <span style="color: #000000; font-weight: bold;">PTR</span> _bFlag$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">0</span>
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _iOnTrue$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
    <span style="color: #00007f; font-weight: bold;">jne</span>    <span style="color: #000000; font-weight: bold;">SHORT</span> $LN4@Conditiona
    <span style="color: #00007f; font-weight: bold;">mov</span>    <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">DWORD</span> <span style="color: #000000; font-weight: bold;">PTR</span> _iOnFalse$<span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #009900; font-weight: bold;">&#93;</span>
$LN4@Conditiona<span style="color: #339933;">:</span>
<span style="color: #666666; font-style: italic;">; 6    : }</span></pre></td></tr></table></div>

<p>You will note that the work of this function is now done in 4 instructions as opposed to 9 in the Debug:</p>
<ul>
<li>it <em><strong>c</strong></em>o<em><strong>mp</strong></em>ares the value of bFlag against 0</li>
<li>unconditionally <em><strong>mov</strong></em>es the value of iOnTrue into <em><strong>eax</strong></em></li>
<li>if the value of bFlag was not equal to 0 (i.e. it was true) it jumps past the next instruction&#8230;</li>
<li>&#8230;otherwise this <em><strong>mov</strong></em>es the value of iOnFalse into <em><strong>eax</strong></em></li>
</ul>
<p>As I&#8217;ve stated before I&#8217;m not an assembly code programmer and I&#8217;m not an optimisation expert. Consequently, I&#8217;m not going to offer my opinion on the significance of the ordering of the instructions in this Release assembly code.</p>
<p>I am, however, prepared to go out on a limb and say it&#8217;s a pretty safe bet that the Release version with 4 instructions is going to execute significantly faster than the Debug version with 9.</p>
<p>So, why such a big difference between Debug and Release for something that when debugging at source level is a single-step?</p>
<p>Essentially this is because the unoptimised assembly code generated by the compiler must be amenable to single-step debugging at the source level:</p>
<ul>
<li>it almost always does the exact logical equivalent of what the high level code asked it to do and, specifically, in the same order</li>
<li>it also has to frequently write values from CPU registers back into memory so that the debugger can show them updating</li>
</ul>
<h1>Summary</h1>
<p>What&#8217;s the main point I&#8217;d like you to take away from this article? Optimising compilers are feisty!</p>
<p>You have to know how to stop them optimising away your isolated C/C++ code snippets if you want to easily be able to see the optimised assembly code they generate.</p>
<p>This article shows a simple boilerplate way to short-circuit the Visual Studio optimising compiler &#8211; mileage will vary on other platforms.</p>
<p>There are other strategies to stop the optimiser optimising away your code, but they basically all come down to utilising the Schrödinger linkage effect; in general:</p>
<ul>
<li>use global variables, function parameters, or function call results as inputs to the code</li>
<li>use global variables, function return values, or function call parameters as outputs from the code</li>
<li>if you&#8217;re not using Visual Studio&#8217;s compiler you may also need to turn off inlining</li>
</ul>
<p>A final extreme method I have been told about is to insert <em><strong>nop</strong></em> instructions via inline assembly around / within the code you want to isolate. Note that you should use this approach with caution, as it interferes directly with the optimiser and can easily affect the output to the point where it is no longer representative.</p>
<h1>Epilogue</h1>
<p>So, I hope you found this interesting &#8211; I certainly expect you will find it useful :)</p>
<p>The next article (as promised last time!) is about looping, which is another reason why it seemed like a good time to cover getting at optimised assembly code for simple C/C++ snippets.</p>
<p>I will be referring back to this in future articles in situations where looking at the optimised assembly code is particularly relevant.</p>
<p>If you&#8217;re wondering what you should look at first to see how Debug and Release code differ, and want to get practise at beating the optimiser, I&#8217;d suggest starting with something straight forward like adding a few numbers together.</p>
<p>Lastly, but by no means leastly, thanks to Rich, Ted, and Bruce for their input and proof reading; and Bruce for supplying me with the tip that made this post possible.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/07/cc-low-level-curriculum-part-8-looking-at-optimised-assembly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maximum Creativity: Open &amp; Closed Mode</title>
		<link>http://www.altdevblogaday.com/2012/05/07/maximum-creativity-open-closed-mode/</link>
		<comments>http://www.altdevblogaday.com/2012/05/07/maximum-creativity-open-closed-mode/#comments</comments>
		<pubDate>Mon, 07 May 2012 12:17:04 +0000</pubDate>
		<dc:creator>Claire Blackshaw</dc:creator>
				<category><![CDATA[Game design]]></category>
		<category><![CDATA[closed mode]]></category>
		<category><![CDATA[Creative]]></category>
		<category><![CDATA[open mode]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26129</guid>
		<description><![CDATA[<p>A video recently cycled through my friends’ social circles which I wanted to share. John Cleese talks about Creativity and Open and Closed thinking modes.</p>
<p><strong>The TL;DR of John Cleese’s talk</strong></p>
<p><a href="http://www.altdevblogaday.com/2012/05/07/maximum-creativity-open-closed-mode/" class="more-link">Read more on Maximum Creativity: Open &#38; Closed Mode&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>A video recently cycled through my friends’ social circles which I wanted to share. John Cleese talks about Creativity and Open and Closed thinking modes.</p>
<p><strong>The TL;DR of John Cleese’s talk</strong></p>
<dl>
<dt>Closed Mode</dt>
<dd>Purposeful <strong>Highly Productive</strong>, but not creative. Good for getting things done. Default Mode at Work.</dd>
<dt>Open Mode</dt>
<dd>Playful, Curious, Fun, Humorous, Relaxed, Contemplative <strong>without goals</strong>.</dd>
</dl>
<p><span id="more-26129"></span></p>
<span style="text-align:center; display: block;"><a href="http://www.altdevblogaday.com/2012/05/07/maximum-creativity-open-closed-mode/"><img src="http://img.youtube.com/vi/VShmtsLhkQg/2.jpg" alt="" /></a></span>
<p>I had a lot of takeaways from that but my biggest takeaway was what could I do to be more open and enable openness around me. In the past I’ve drawn mostly from my dramatic background and improv lessons, always saying yes. See <a href="http://www.altdevblogaday.com/2011/12/20/improv-acting-and-game-development-2/">Lisa Brown’s brilliant article</a> on that topic.</p>
<p>Humour and Time are key to being in the Open Mode. Also Goals, Hierarchy and Authority are not conducive to the Open Mode. An interesting thought for those of you who read the <em>Valve Employee Handbook</em> floating around the net at the moment. The key thought this lead me to is simple&#8230;</p>
<blockquote><p>You Can’t Play by Proxy</p></blockquote>
<p>Too often I espouse the brilliance of the programming designer. The real magic is simple, you  cannot play by proxy. A designer who can’t play (and change) with gameplay is like a chef who gets someone else to taste the food and describe it. An artist who cannot change the appearance of something in-game without someone else is like painting on canvas by instructing a monkey holding a paintbrush. A programmer who cannot go outside the spec is like a dancer in a straight jacket.</p>
<p>You need to hold the ball in your hand and feel it bounce. Always ensure your source control, build server and other tools do not stop someone’s experimentation.</p>
<blockquote><p>The Open Mode is Unachievable in Crunch Time</p></blockquote>
<p>A common example of the open mode in game development: someone has just implemented a system which due to an amusing bug is glitching out or not behaving in the designed fashion. In a crunch time, i.e. closed environment, a bug is filed, profanities are hurled and the bug is squashed. In an open mode and a lighter environment, possible earlier in the project, the group plays with the bug and says something like, “Isn’t that interesting&#8230;”</p>
<p>Now to be clear, most times nothing immediately comes from that comment though at times a brilliant idea or mechanic emerges. Often these moments lend themselves to interesting gameplay moments. For a prime example of game development project by open mode style thinking, look at Minecraft. Many gameplay features started as bugs or unintended behaviour which in a traditional environment would have been eradicated but the players enjoyed it and Notch left it in.</p>
<p>In order to achieve things we need to be in a closed mode. Though it’s easy to get stuck in that mode and with tunnel vision run down our path missing all the brilliant opportunities that are being thrown up during game development.</p>
<blockquote><p>Playful Tools</p></blockquote>
<p>When designing or creating a tool or pipeline think about how your tools enable playfulness, experiment and toy around with your tools. A willingness to create without fear. Observe how playful we are with pens, for many of us our primary tool.</p>
<p>Two Developers, one creating a scene in notepad with fragile .xml, the other drawing a blueprint in photoshop. The drawing based solution is more fluid and open to play. The developer can draw a “humorous shape” and see it in game without fuss. Leading to greater comfort and competence, discovering creative uses of the tools.</p>
<p>Nothing can frustrate and break playfulness more than a deep pipeline or frustrating tools. A buggy or frustrating tool ensures you&#8217;re in the Closed Mode. As in the Closed Mode we are less likely to make mistakes and can follow rigid guidelines.</p>
<blockquote><p>While being Creative Nothing is Wrong</p></blockquote>
<p>We live in a digital world of hacks and cheats, we care for results not method. The thing which appears on screen is a beautiful lie. So if your engine is refresh sensitive and those silly European televisions are giving you trouble, well, just turn up the earth’s gravity*. Remember the product is the experience, not the game.</p>
<p>Too often a professional artist, designer, programmer or otherwise will dismiss or stamp on a comment because it’s patently silly. They insist on saying it’s too complex or saying it’s daft. Now please, respect the professional skill for which the individual was hired. Though at no point should someone be crushed or demotivated by the HAMMER of authority.</p>
<blockquote><p>Jam, Jive and Jiggle</p></blockquote>
<p>Encourage people to take time out to play in fixed time periods to jam, jive and jiggle. I write this after having just finished a weekend of Ludum Dare fun. The result of the Jam is less important than the time to play. The time to ponder and play with an idea. If you have a sprint structure try to take some time out after a sprint or a whole sprint, WITHOUT GOALS! Just play. See what comes from it.</p>
<p>People need to feel free to play with ideas, in order to have great ideas.</p>
<p><em>* A real humorous example of an engine hack seen in the wild.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/07/maximum-creativity-open-closed-mode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Xperf Wait Analysis&#8211;Finding Idle Time</title>
		<link>http://www.altdevblogaday.com/2012/05/06/xperf-wait-analysisfinding-idle-time/</link>
		<comments>http://www.altdevblogaday.com/2012/05/06/xperf-wait-analysisfinding-idle-time/#comments</comments>
		<pubDate>Sun, 06 May 2012 04:25:31 +0000</pubDate>
		<dc:creator>Bruce-Dawson</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[hangs]]></category>
		<category><![CDATA[hitches]]></category>
		<category><![CDATA[idle time]]></category>
		<category><![CDATA[inputprocessdelay]]></category>
		<category><![CDATA[summary tables]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[wait analysis]]></category>
		<category><![CDATA[xperf]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25936</guid>
		<description><![CDATA[<p>The Windows Performance Toolkit, also known as <a href="http://randomascii.wordpress.com/category/xperf/">xperf</a>, is a powerful (and free!) system-wide Windows profiler. In the past I’ve talked about using xperf to identify <a href="http://randomascii.wordpress.com/2011/08/29/powerpoint-poor-performance-problem/">slowdowns in PowerPoint</a> by using xperf’s built-in sampling profiler, but that actually understates the true value of Xperf. While I think xperf is a better sampling profiler than most of the alternatives (higher frequency, lower overhead, kernel and user mode), xperf is really at its best when it reveals information that other profilers cannot measure at all.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/06/xperf-wait-analysisfinding-idle-time/" class="more-link">Read more on Xperf Wait Analysis&#8211;Finding Idle Time&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>The Windows Performance Toolkit, also known as <a href="http://randomascii.wordpress.com/category/xperf/">xperf</a>, is a powerful (and free!) system-wide Windows profiler. In the past I’ve talked about using xperf to identify <a href="http://randomascii.wordpress.com/2011/08/29/powerpoint-poor-performance-problem/">slowdowns in PowerPoint</a> by using xperf’s built-in sampling profiler, but that actually understates the true value of Xperf. While I think xperf is a better sampling profiler than most of the alternatives (higher frequency, lower overhead, kernel and user mode), xperf is really at its best when it reveals information that other profilers cannot measure at all.</p>
<p>In short, lots of profilers can tell you what your program is doing, but few profilers are excellent at telling you why your program is doing nothing.</p>
<p><span id="more-25936"></span><br />
<h2>Our story so far</h2>
<p>Xperf has a high learning curve. Therefore I highly recommend that you start by reading some previous articles from this series. The entire series can be found <a href="http://randomascii.wordpress.com/category/xperf/">here</a>, but the most important ones are:</p>
<ul>
<li><a href="http://randomascii.wordpress.com/2011/08/18/xperf-basics-recording-a-trace/">Xperf Basics: Recording a Trace</a> – this covers installing xperf (takes just a few minutes), recording traces, and adding <a href="http://msdn.microsoft.com/en-us/magazine/cc163437.aspx">ETW</a> events to your game</li>
<li><a href="http://randomascii.wordpress.com/2011/08/23/xperf-analysis-basics/">Xperf Analysis Basics</a> – the essential knowledge of how to navigate the xperf UI, including how to set up symbol paths</li>
</ul>
<p>The rest of this post assumes that you have installed xperf (preferably the Windows 8 version) and have familiarity with at least Xperf Analysis Basics.</p>
<h2>Wait Analysis Victories</h2>
<p>I’ve had good luck using Wait Analysis to find many performance problems. Some of these delays were short enough to be difficult to notice, yet long enough to matter. Others were debilitating. All were difficult or impossible to analyze through CPU sampling or other ‘normal’ CPU profilers. Some examples include:</p>
<ul>
<li>Finding the cause of brief startup hangs in Internet Explorer and various games </li>
<li>Profiling Luke Stackwalker to find out why it caused frame rate glitches in the game it was profiling </li>
<li>Finding the cause of a 10x perf-reduction when upgrading to a newer version of Windows </li>
<li>Finding the cause of frame rate hitches during fraps recording </li>
<li>Finding the chain of lock contention that caused frame rate hitches on a heavily loaded system </li>
<li>Finding the cause of (and a workaround for) repeated 2-6 second hangs in Visual Studio’s output window </li>
</ul>
<p>The last investigation is the one I want to cover today. It is sufficiently simple and self-contained that I can cover it end-to-end in a single (long) post.</p>
<h2>Finding the hang</h2>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image.png"><img style="border-right-width: 0px;padding-left: 0px;padding-right: 0px;float: right;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="image" align="right" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb.png" width="204" height="410" /></a>When profiling a transient problem such as a frame-rate glitch or a temporary hang the first challenge is to locate the hang in the trace. A trace might cover 60 seconds, and a hang might last for 2 seconds or less, so knowing where to look is crucial. There are a number of ways to do this:</p>
<ul>
<li>Find the key stroke that triggered the hang, through logging of input events </li>
<li>Use instrumentation in the functions of interest </li>
<li>Look for patterns in the CPU usage or other data </li>
<li>Use OS hang-detection events </li>
</ul>
<p>I’ve used all four of these techniques. Our internal trace recording tool has an optional input event logger which puts all keyboard and mouse input into the trace (watch for it). If a hang is triggered by a particular key press or mouse click then finding its start point in the trace is trivial.</p>
<p>Custom instrumentation (emitting ETW events at key points in your game, see the <a href="http://randomascii.wordpress.com/2011/08/18/xperf-basics-recording-a-trace/">Recording a Trace</a> post) is also a common technique. Emitting an event every frame makes a frame rate hitch plainly visible. However this doesn’t work when investigating performance problems in other people’s code, such as in Visual Studio.</p>
<p>In some cases a hang will be plainly visible in the CPU consumption. One recent hang showed a significant hole in the otherwise consistent CPU usage, plain as day.</p>
<p>A specific event that indicates the time and duration of a hang would be ideal, and Windows 7 actually has such an event. The Microsoft-WindowsWin32k ETW user provider will emit an event whenever a thread resumes pumping messages after a significant delay. Windows Vista and earlier users are out of luck, but on Windows 7 this is often exactly what is needed, and this provider is enabled by my recommended <a href="http://randomascii.wordpress.com/2011/08/18/xperf-basics-recording-a-trace/">trace recording batch files</a>.</p>
<h2>It’s hands on time</h2>
<p>I’ve uploaded a .zip file of a sample trace to <a href="ftp://ftp.cygnus-software.com/pub/VisualStudioF8Hang.zip">VisualStudioF8Hang.zip</a>. If you download this trace, load it into xperfview, and make sure that the Microsoft symbols <a href="http://randomascii.wordpress.com/2011/08/23/xperf-analysis-basics/">can be found</a> then you can follow along. This is by far the best way to learn wait analysis.</p>
<p>This trace covers over over ten minutes for some types of data, but the detailed sampling and context switch data only covers 28 seconds, from about 782 to 810 seconds.</p>
<p>Start by selecting the region where we have full data, from 782 to 810 s and cloning this selection.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image15.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb15.png" width="635" height="373" /></a></p>
<p>Our path now depends on whether you are using the new (Windows 8) version of xperfview.exe.</p>
<h2>Hands on with old versions of xperfview</h2>
<p>While this exact technique is only applicable to (and only works with) old versions of xperfview, the general concept is still applicable and the exploration of generic events is crucial whether looking for your custom events or exploring the built-in events.</p>
<p>Scroll down to the Generic Events table. Right-click the selected region and bring up a summary table. Enable the Process Name column and put it first. Enable the ThreadID column and put it after Field 3. Move the Time (s) column and put it after the ThreadID column. I also hid a couple of columns in order to get my screenshot to fit, but that’s less critical. Now we have all of the information we need in a convenient and easy to read place.</p>
<p>If we drill into the data for devenv.exe and select the MessageCheckDelay Task Name we should see something like this:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image8.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb8.png" width="678" height="184" /></a></p>
<p>The Zen of summary tables is all about looking for data columns that seem useful, enabling them, and fearlessly rearranging columns to group/sort/pivot/spindle the data to answer your question. In this case our question was when does devenv.exe (group by Process Name) hang (group by the Microsoft-Windows-Win32k provider, Task Name equals MessageCheckDelay or InputProcessDelay), and for those events, look at the TimeSinceInputRemoveMs, Thread ID, and Time (s) data.</p>
<p>So now, with relatively little effort, I know that devenv.exe hung (didn’t check for messages) for 5,304 ms, its message pump is running on thread ID 9,536, and the hang ended at 805.666 seconds into the trace.</p>
<p>Cool.</p>
<h2>Hands on with the new version of xperfview (6.2.8229)</h2>
<p>Microsoft is continuing to develop xperf and if you install the latest version (released Feb 29, 2012, and linked to from <a href="http://randomascii.wordpress.com/2011/08/18/xperf-basics-recording-a-trace/">here</a>) then there are a couple of options. Wpa.exe has a new UI which shows pretty graphs for UI delays:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image16.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb16.png" width="585" height="225" /></a></p>
<p>I don’t know how to dig in deeper so I can’t tell if it is any use, so that’s all I have to say about it.</p>
<p>The new xperfview.exe has removed the MessageCheckDelay and InputProcessDelay events from Generic Events but has added a new UI Delay Information Graph. If you scroll down to this graph and zoom in around 800 s (in the area where we have full detail) then you should see five reports of hung apps. VTrace.exe (my trace recording application) hung for a while, there are three spurious reports of Internet Explorer hanging, and there is a MsgCheckDelay report for devenv.exe. It’s really too easy.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image17.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb17.png" width="665" height="288" /></a></p>
<p>You can right-click to change the threshold for what delays are reported, or to bring up a summary table of delays. You’ll need to bring up the Delay Summary Table to find out the UI thread ID for devenv.exe.</p>
<p> Select the region around the devenv hang and we’re ready for the next step.</p>
<h2>Finding the cause</h2>
<p>The MessageCheckDelay is emitted at the end of the hang (805.666 seconds) and it tells us the length of the hang (5.304 s) so we now know the range of the hang quite accurately.</p>
<p>The hang runs from 800.362 to 805.666 seconds so we should zoom in on that area of the graphs in the xperf main window and look at CPU Usage by Process. My system has eight hardware threads (four hyperthreaded cores) so 12.5% utilization represents one busy thread. Even without that context we can see from the graph below that my CPUs are idle for most of the time. There’s a bit of devenv activity (the two blue spikes), but mostly this is an idle hang.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image9.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb9.png" width="666" height="273" /></a></p>
<p>When analyzing an idle hang you should select the entire region of the hang, and it is particularly important to select the end of the hang. It is better to select a few extra tens or hundreds of milliseconds at the end rather than risk missing the crucial events that end the hang. This selection can be done with the mouse or by right-clicking and using the Select Interval command. For easy reproducibility I right-clicked and used the Select Interval command to select the region from 800.0 s to 806.0 s. I then used Clone Selection to copy it to all of the graphs.</p>
<h2>Who woke whom?</h2>
<p>If a thread is not running, and it then starts running, then there was a context switch that started it (the new thread) running. That context switch is recorded in our ETW trace and contains all sorts of useful information. Include in this information is (for the traces recorded with my recommended batch files) the new process name and thread ID, the call stack which the thread woke up on (which is the same one it went to sleep on), the length of time it was not running and, for threads that were waiting on some synchronization primitive, the thread that woke it up.</p>
<p>Ponder that, because it’s crucial. An ETW trace tells you, for each context switch, how long the thread was not running, and who woke it up. That’s why it is important to have the end of the hang selected, because that is (presumably) the time of the context switch that gets the thread running again.</p>
<p>In the main xperf window go to the CPU Scheduling graph (make sure the correct time range is selected), right click on the selection, and select “Summary Table with Ready Thread” to view all context switches for the selected region together with the readying thread information. Make sure the columns are in this order:</p>
<ol>
<li>NewProcess – this is the process whose thread is being scheduled to run </li>
<li>NewThreadId – this is the thread ID of the thread being scheduled to run </li>
<li>NewThreadStack – this is the stack that the thread will resume running at </li>
<li>ReadyingProcess – this is the process, if any, that readied the new thread </li>
<li>ReadyingThreadId – guess. Go ahead, you can figure it out. </li>
<li>ReadyingThreadStack – this is the stack of the readying thread when it readied the new thread </li>
<li>Orange bar – columns to the left of this are used for grouping, columns to the right are for sorting and data display </li>
<li>Count – how many context switches are summarized by each row </li>
<li>Sum:TimeSinceLast (us) – the time the new thread was not running (time since it last ran) summed across all context switches summarized by each row </li>
</ol>
<p>There are more columns, and for deeper analysis they can be useful, but we don’t need them today.</p>
<p>With our columns thus arranged we can quickly find our problem. Find devenv.exe (be sure to find the correct <a href="http://en.wikipedia.org/wiki/Process_identifier">PID</a> if multiple versions are running) and expand it, find the thread of interest (9,536, from the MessageCheckDelay event), then expand the stack. If you click the “Sum:TimeSinceLast (us)” column so the little arrow is pointing down then as you drill down into the stacks (hint: select the top node and then repeatedly press right-arrow) it will go down the hot call stack. In the sample trace, over the selected region, thread 9,536 starts with a total of about 5.523 s of non-running time over 316 context switches. As we drill down we get to a single context switch that ended an idle gap of 5.202 s. That’s our hang, clear as day.</p>
<p>The NewThreadStack for this 5.202 s call stack starts at _RtlUserThreadStart and winds through a lot of Visual Studio code. Microsoft is kind enough to publish symbols for much of VS, as well as for Windows and about fifty rows down we get to the interesting details:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image10.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb10.png" width="619" height="160" /></a></p>
<p>It’s a single context switch (‘count’ goes down to one when we got a bit lower in the call stack) that put the Visual Studio UI thread to sleep for 5.202 s. It doesn’t get much clearer than that.</p>
<p>If we go down to the bottom of the stack and expand the next three columns (compressed in the screen shot above for size reasons) then we can see who woke us, which can also be described as “who we were waiting for”:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image11.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb11.png" width="601" height="218" /></a></p>
<p>In this case it was the System process (thread 5880) in an IopfCompleteRequest call that goes through MUP.SYS. If we know what MUP.SYS is then that gives us another clue as to the root cause, but even without that we know that Visual Studio called CreateFileW and it took a long time to return.</p>
<h2>What about the other threads?</h2>
<p>In our selected region their are context switch events for 11 threads in devenv.exe. For all of those threads the Sum:TimeSinceLast value is greater than for 9,536, the thread we are investigating. So why aren’t we looking at them?</p>
<p>It’s important to understand that Sum:TimeSinceLast just measures how long a thread was idle, and there is nothing wrong with a thread being idle. A thread being idle is only a problem if it is supposed to be doing something and isn’t. In fact, if devenv.exe has 11 threads then they had better be idle most of the time or else my six-core machine is going to be constantly busy.</p>
<p>Many of the threads have a Sum:TimeSinceLast time of about 15 s, which is significantly longer than the 6 s time period selected. That’s because this summary table shows all of the context switches that occurred during this time period, and the first context switch for these threads was after they had been idle for a very long time, most of that time outside of the selected region.</p>
<p>The reason we are looking at thread 9,536 is because (according to the MessageCheckDelay event) it is the UI thread and it went for 5.304 s without pumping messages. It kept me waiting, and that makes me angry. You wouldn’t like me when I’m angry.</p>
<h2>File I/O summary table</h2>
<p>Since we know that the hang is related to file I/O we should look at what file I/O is happening during this time period. Luckily this information is recorded by the xperf batch files that I <a href="http://randomascii.wordpress.com/2011/08/18/xperf-basics-recording-a-trace/">recommend</a>.</p>
<p>On the main xperf window go to the File I/O graph and bring up a summary table, for the same time region we’ve been using so far. Arrange the columns as shown below and drill in as usual. I’m sure this screen shot won’t show up very well, but I can’t shorten it any more. It contains too much glorious information. Click on the image for deeper details:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image12.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb12.png" width="687" height="70" /></a></p>
<p>We can see here that a Create file event, from devenv.exe, thread 9,536, took 5.203 s, trying to open \Device\Mup\…, and that ultimately the network path was not found.</p>
<p>Wow.</p>
<p>It turns out that \Device\Mup, or MUP.sys, means the network. The hang is because Visual Studio tried to open a non-existent network file, and sometimes that causes a 5.2 s network timeout. Hence the hang.</p>
<p>The remainder of the hang is from a few other context switches and CPU time that account for the rest of the 5.304 s, but the one long bit of idle time is all that matters in this case. It’s particularly clean.</p>
<h2>What’s the cause?</h2>
<p>The file name associated with this hang is quite peculiar. The full name is:</p>
<p>\Device\Mup\perforce\main\src\lib\public\win64\vdebug_tool.lib#227 &#8211; opened for edit</p>
<p>That doesn’t look like a file name. That looks more like the output from Perforce. And that’s exactly what it is. At Valve we store build results in Perforce so we have pre-build steps to check these files out. The checkout commands print their results to the Visual Studio output window like this:</p>
<p>//perforce/main/src/lib/public/win64/vdebug_tool.lib#227 &#8211; opened for edit</p>
<p>Visual Studio ‘helpfully’ reverses the slashes and decides that this represents a file name on <a href="//\\perforce\main">\\perforce\main</a>. Since this whole thing started with me pressing F8 (actually double-clicking the output window in this reenactment) this means that Visual Studio was trying desperately to treat this potential file name as a source-file name associated with an error or warning message.</p>
<p>Oops.</p>
<p>That explains the CResultList::AttemptToNavigate entry on the hang call stack – everything makes more sense once you understand the problem.</p>
<h2>Conclusion</h2>
<p>Once the cause of the hang was understood I modified our pre-build step to pipe the output through sed.exe and had it rewrite the output so that Visual Studio would no longer find it interesting. This avoids the hang, but also made it so that F8 would take the selection to interesting errors and warnings, instead of to these mundane progress messages. A little sed magic replaces “//” with the empty string, and “&#8230;” with “&#8212;“ :</p>
<blockquote><p>sed -e s!//!! -e s!\.\.\.!&#8212;!</p>
</blockquote>
<p>This changes the hang-prone results before:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image13.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb13.png" width="651" height="112" /></a></p>
<p>to the hang-proof benign text after:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image14.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/image_thumb14.png" width="650" height="109" /></a></p>
<p>I also reported the bug to the Visual Studio team. Having a trace is very powerful for this because it meant that I could tell them definitively what the problem was, and I could share the trace in order to let them confirm my findings. Just like minidump files are a powerful way to report crash bugs, xperf traces are a powerful way to report performance bugs. The Visual Studio team has told me that this bug will be fixed in Visual Studio 11 – UNC paths will be ignored by the output window’s parser.</p>
<p>Mup.sys is the driver used for network file I/O. Therefore its presence on the Readying Thread stack was a clue that a network delay was the problem. Doing file I/O on the UI thread is always a bit dodgy if you want to avoid hangs, and doing network file I/O is particularly problematic, so watching for mup.sys is a good idea.</p>
<h2>Wait chains</h2>
<p>Some wait analysis investigations are more complicated than this one. In several investigations I have found that the main thread of our game was idle for a few hundred milliseconds waiting on a semaphore, critical section, or other synchronization object. In that case the readying thread is critical because that is the thread that released the synchronization object. Once I find out who was holding up the main thread I can move the analysis to that thread and apply either busy-thread analysis (CPU sampling) or idle thread analysis (finding what that thread was waiting on). Usually just one or two levels of hunting is needed to find the culprit, but I did recently trace back across six context switches in four different processes in order to track down an OS scheduling problem.</p>
<p>When following wait chains it is important to understand the order of events. If thread 1234 is readied by thread 5678 at time 10.5 s, then any context switches or CPU activity that happen to thread 5678 after that point are not relevant to the wait chain. Since they happened after thread 1234 was woken they can’t be part of its wait chain.</p>
<p>For CPU activity this is dealt with by selecting the region of interest. For context switches this is dealt with by drilling down all the way and then looking at the SwitchInTime (s) column (which you may want to move to a more convenient location). This column records the time of the context switch.</p>
<p>It’s worth pointing out that if you busy wait (spinning on some global variable flag) or use your own custom synchronization primitives (CSuperFastCriticalSection) then these techniques will not work. The OS synchronization primitives are instrumented with ETW events that allow, in almost all cases, perfect following of wait chains. Even if your custom synchronization code is faster (and it probably isn’t) it isn’t enough faster to make up for the loss of wait analysis. <em>The ability to profile your code trumps any small performance improvement.</em></p>
<h2>Can’t any profiler do this?</h2>
<p>Sampling profilers and instrumented profilers might be able to tell you that your program is idle, and they might even be able to tell you <em>where</em> your program is idle, but they generally can’t tell you <em>why</em> your program is idle. Only by following the chain of readying threads and looking at other information can you be sure to find the cause of your idle stalls.</p>
<p>It’s also convenient that you can leave xperf running in continuous-capture mode, where it is constantly recording all system activity to a circular buffer. When you notice a problem you can just record the buffer to disk, and do some post-mortem profiling.</p>
<h2>It’s not baking</h2>
<p>Baking is all about precisely following a recipe – improvisation tends to lead to failure. Wait analysis, on the other hand, is all about creativity, thinking outside the box, and understanding the entire system. You have to understand context switches, you have to think about what idle time is good and what is bad, you have to think about when to look at CPU usage and when to look at idle time, and you often have to invent some new type of analysis or summary table ordering in order to identify the root cause. It’s not easy, but if you master this skill then you can solve problems that most developers cannot.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/06/xperf-wait-analysisfinding-idle-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Embracing Dynamism</title>
		<link>http://www.altdevblogaday.com/2012/05/05/embracing-dynamism/</link>
		<comments>http://www.altdevblogaday.com/2012/05/05/embracing-dynamism/#comments</comments>
		<pubDate>Sat, 05 May 2012 21:14:25 +0000</pubDate>
		<dc:creator>Niklas Frykholm</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=26033</guid>
		<description><![CDATA[<p>Are you stuck in static thinking? Do you see your program as a fixed collection of classes and functions with unchanging behavior.</p>
<p>While that view is mostly true for old school languages such as C++ and Java, the game is different for dynamic languages: Lua, JavaScript, Python, etc. That can be easy to forget if you spend most of your time in the static world, so in this article I&#8217;m going to show some of the tricks you can apply when everything is fluid and malleable.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/05/embracing-dynamism/" class="more-link">Read more on Embracing Dynamism&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Are you stuck in static thinking? Do you see your program as a fixed collection of classes and functions with unchanging behavior.</p>
<p>While that view is mostly true for old school languages such as C++ and Java, the game is different for dynamic languages: Lua, JavaScript, Python, etc. That can be easy to forget if you spend most of your time in the static world, so in this article I&#8217;m going to show some of the tricks you can apply when everything is fluid and malleable.</p>
<p>At Bitsquid our dynamic language of choice is Lua. Lua has the advantage of being fast, fully dynamic, small, simple and having a traditional (i.e. non-LISP-y) syntax. We use Lua for most gameplay code and it interfaces with the engine through an API with exposed C functions, such as <em>World.render()</em> or <em>Unit.set_position()</em>.</p>
<p>I will use Lua in all the examples below, but the techniques can be used in most dynamic languages.</p>
<h2>1. Read-eval-print-loop</h2>
<p>Dynamic languages can compile and execute code at runtime. In Lua, it is as simple as:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #b1b100;">loadstring</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;print(10*10)&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>This can be used to implement a command console where you can type Lua code and directly execute it in the running game. This can be an invaluable debugging and tuning tool. For example if you need to debug some problem with the bazooka:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;">World.spawn_unit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;bazooka&quot;</span>, Unit.position<span style="color: #66cc66;">&#40;</span>player<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Or tune the player&#8217;s run speed:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;">Unit.set_data<span style="color: #66cc66;">&#40;</span>player, <span style="color: #ff0000;">&quot;run_speed&quot;</span>, <span style="color: #cc66cc;">4.3</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<h2>2. Reload code</h2>
<p>The console can be used for more than giving commands, you can also use it to redefine functions. If the gameplay code defines a scoring rule for kills:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #b1b100;">function</span> Player.register_kill<span style="color: #66cc66;">&#40;</span>self, enemy<span style="color: #66cc66;">&#41;</span>
	self.score <span style="color: #66cc66;">=</span> self.score + <span style="color: #cc66cc;">10</span>
<span style="color: #b1b100;">end</span></pre></div></div>

<p>you can use the console to redefine the function and change the rules:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #b1b100;">function</span> Player.register_kill<span style="color: #66cc66;">&#40;</span>self, enemy<span style="color: #66cc66;">&#41;</span>
	<span style="color: #b1b100;">if</span> enemy.<span style="color: #b1b100;">type</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;boss&quot;</span> <span style="color: #b1b100;">then</span>
		self.score <span style="color: #66cc66;">=</span> self.score + <span style="color: #cc66cc;">100</span>
	<span style="color: #b1b100;">else</span>
		self.score <span style="color: #66cc66;">=</span> self.score + <span style="color: #cc66cc;">10</span>
	<span style="color: #b1b100;">end</span>
<span style="color: #b1b100;">end</span></pre></div></div>

<p>Executing this code will replace the existing <em>Player.register_kill</em> function with the new one. All code that previously called the old function will now call the new one and the new scoring rules will apply immediately.</p>
<p>If you take some care with how you use the global namespace you can write your Lua code so that <em>all</em> of it is reloadable using this technique. Then the gameplay programmer can just edit the Lua files on disk and press a key to reload them in-game. The game will continue to run with the new gameplay code, without any need for a reboot. Pretty cool.</p>
<p>You can even get this to work for script errors. If there is an error in the Lua code, don&#8217;t crash the game, just freeze it and allow the gameplay programmer to fix the error, reload the code and continue running.</p>
<h2>3. Override system functions</h2>
<p>The functions in the engine API don&#8217;t have any special privileges, they can be redefined just as other Lua functions. This can be used to add custom functionality or for debugging purposes.</p>
<p>Say, for example, that you have some units that are mysteriously popping up all over the level. You know they are being spawned somewhere in the gameplay code, but you can&#8217;t find where. One solution would be to override the <em>World.spawn_unit</em> function and print a stack trace whenever the offending unit is spawned:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;">old_spawn_unit <span style="color: #66cc66;">=</span> World.spawn_unit
<span style="color: #b1b100;">function</span> World.spawn_unit<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">type</span>, position<span style="color: #66cc66;">&#41;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #b1b100;">type</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;tribble&quot;</span> <span style="color: #b1b100;">then</span>
		<span style="color: #b1b100;">print</span> <span style="color: #ff0000;">&quot;Tribble spawned by:&quot;</span>
		print_stack_trace<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #b1b100;">end</span>
	old_spawn_unit<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">type</span>, position<span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">end</span></pre></div></div>

<p>Now, whenever a <em>tribble</em> is spawned by the script, a call stack will be printed and we can easily find who is doing the spawning.</p>
<p>Note that before we replace <em>World.spawn_unit</em>, we save the original function in the variable <em>old_spawn_unit</em>. This enables us to call <em>old_spawn_unit()</em> to do the actual spawning.</p>
<p>This technique could also be used to find all (potentially expensive) raycasts being done by the script.</p>
<h2>4. Handle deprecated functions</h2>
<p>Sometimes we need to deprecate functions in the engine API. It can be annoying to the people using the engine of course, but backwards compatibilty is the mother of stagnation. If you never throw away old code, you will eventually have a huge ugly code mess on your hands.</p>
<p>Luckily, since the script can create functions in the engine namespace, the script can provide the backwards compatibility when needed.</p>
<p>For example, we used to have a function <em>PhysicsWorld.clear_kinematic(world, actor)</em>. That naming was inconsistent with some of our other functions so we changed it to <em>Actor.set_kinematic(actor, false)</em>.</p>
<p>One way of dealing with this change would be to go through all the code in the project, find all uses of <em>PhysicsWorld.clear_kinematic</em> and change them to use <em>Actor.set_kinematic</em> instead. But <em>another</em> way would be to just implement <em>PhysicsWorld.clear_kinematic</em> in the script:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #b1b100;">function</span> PhysicsWorld.clear_kinematic<span style="color: #66cc66;">&#40;</span>world, actor<span style="color: #66cc66;">&#41;</span>
	Actor.set_kinematic<span style="color: #66cc66;">&#40;</span>actor, <span style="color: #b1b100;">false</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">end</span></pre></div></div>

<p>Now the rest of the code can go on using <em>PhysicsWorld.clear_kinematic</em> without even caring that the function has been removed from the engine API. You could even use a combination of the two strategies &#8212; implementing the deprecated function in Lua for a quick fix, and then looking into removing the uses of it.</p>
<h2>5. Dynamically inserting profiling</h2>
<p>Top-down profiling with explicit profiler scopes is a good way of finding out where a game is spending most of its time. However, to be useful, explicit profiler scopes need to be inserted in all the &#8220;right&#8221; places (all potentially expensive functions).</p>
<p>In C we need to guess where these right places are before compiling the program. In Lua, we can just insert the profiler scopes dynamically. We can even create a function that adds profiling to any function we want:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #b1b100;">function</span> profile<span style="color: #66cc66;">&#40;</span>class_name, method_name<span style="color: #66cc66;">&#41;</span>
	<span style="color: #b1b100;">local</span> f <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">_G</span><span style="color: #66cc66;">&#91;</span>class_name<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#91;</span>method_name<span style="color: #66cc66;">&#93;</span>
	<span style="color: #b1b100;">_G</span><span style="color: #66cc66;">&#91;</span>class_name<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#91;</span>method_name<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">function</span> <span style="color: #66cc66;">&#40;</span>...<span style="color: #66cc66;">&#41;</span>
		Profiler.start<span style="color: #66cc66;">&#40;</span>class_name .. <span style="color: #ff0000;">&quot;.&quot;</span> .. method_name<span style="color: #66cc66;">&#41;</span>
		f<span style="color: #66cc66;">&#40;</span>...<span style="color: #66cc66;">&#41;</span>
		Profiler.stop<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #b1b100;">end</span>
<span style="color: #b1b100;">end</span></pre></div></div>

<p>When we call this function as <em>profile(&#8216;Player&#8217;, &#8216;update&#8217;)</em> it will first save the existing <em>Player.update</em> function and then replace it with a function that calls <em>Profiler.start(&#8220;Player.update&#8221;)</em> before calling the original function and <em>Profiler.stop()</em> before returning.</p>
<p>Using this techinque, we can dynamically add profiling to any function we want during our optimization session.</p>
<h2>6. Tab completion</h2>
<p>If you implement an interactive Lua console, it is nice to support tab completion, so the user doesn&#8217;t have to remember all function names. But how do you build the list of callable functions to use with tab completion?</p>
<p>Using Lua of course! Just find all tables (i.e., classes) in the global namespace and all functions stored in those tables:</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;">t <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">for</span> class_name,class <span style="color: #b1b100;">in</span> <span style="color: #b1b100;">pairs</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">_G</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span>
	<span style="color: #b1b100;">if</span> <span style="color: #b1b100;">type</span><span style="color: #66cc66;">&#40;</span>class<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">'table'</span> <span style="color: #b1b100;">then</span>
		<span style="color: #b1b100;">for</span> function_name,<span style="color: #b1b100;">function</span> <span style="color: #b1b100;">in</span> <span style="color: #b1b100;">pairs</span><span style="color: #66cc66;">&#40;</span>class<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span>
			<span style="color: #b1b100;">if</span> <span style="color: #b1b100;">type</span><span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">function</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">'function'</span> <span style="color: #b1b100;">then</span>
				t<span style="color: #66cc66;">&#91;</span>#t+<span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">=</span> class_name .. <span style="color: #ff0000;">'.'</span> .. function_name
			<span style="color: #b1b100;">end</span>
		<span style="color: #b1b100;">end</span>
	<span style="color: #b1b100;">end</span>
<span style="color: #b1b100;">end</span></pre></div></div>

<p>After running this, <em>t</em> will contain the full list of function names.</p>
<h2>7. Looping through all objects</h2>
<p>By recursing through <em>_G</em> you can enumerate all reachable objects in the Lua runtime.</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #b1b100;">function</span> enumerate<span style="color: #66cc66;">&#40;</span>f<span style="color: #66cc66;">&#41;</span>
	<span style="color: #b1b100;">local</span> seen <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
	<span style="color: #b1b100;">local</span> recurse <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">function</span><span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #b1b100;">type</span><span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span> ~<span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'table'</span> <span style="color: #b1b100;">then</span> <span style="color: #b1b100;">return</span> <span style="color: #b1b100;">end</span>
		<span style="color: #b1b100;">if</span> seen<span style="color: #66cc66;">&#91;</span>t<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">==</span> <span style="color: #b1b100;">true</span> <span style="color: #b1b100;">then</span> <span style="color: #b1b100;">return</span> <span style="color: #b1b100;">end</span>
		f<span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span>
		seen<span style="color: #66cc66;">&#91;</span>t<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">=</span> <span style="color: #b1b100;">true</span>
		recurse<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">getmetatable</span><span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #b1b100;">for</span> k,v <span style="color: #b1b100;">in</span> <span style="color: #b1b100;">pairs</span><span style="color: #66cc66;">&#40;</span>t<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span>
			recurse<span style="color: #66cc66;">&#40;</span>k<span style="color: #66cc66;">&#41;</span>
			recurse<span style="color: #66cc66;">&#40;</span>v<span style="color: #66cc66;">&#41;</span>
		<span style="color: #b1b100;">end</span>
	<span style="color: #b1b100;">end</span>
	recurse<span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">_G</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #b1b100;">end</span></pre></div></div>

<p>Calling <em>enumerate(f)</em> will call <em>f(o)</em> on all objects <em>o</em> in the runtime. (Assuming they are reachable from <em>_G</em>. Potentially, there could also be objects only reachable through Lua references held in C.)</p>
<p>Such an enumeration could be used for many things. For example, you could use it to print the health of every object in the game.</p>

<div class="wp_syntax"><div class="code"><pre class="lua" style="font-family:monospace;"><span style="color: #b1b100;">function</span> print_health<span style="color: #66cc66;">&#40;</span>o<span style="color: #66cc66;">&#41;</span>
	<span style="color: #b1b100;">if</span> o.health <span style="color: #b1b100;">then</span> <span style="color: #b1b100;">print</span><span style="color: #66cc66;">&#40;</span>o.health<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">end</span>
<span style="color: #b1b100;">end</span>
enumerate<span style="color: #66cc66;">&#40;</span>print_health<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The technique could also be used for memory optimizations. You could loop through all Lua objects and find the memory used by each object type. Then you could focus your optimization efforts on the resource hogs.</p>
<p>This has also been posted to <a class="link" href="http://bitsquid.blogspot.com">The Bitsquid Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/05/embracing-dynamism/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating Uniformly Distributed Points on Sphere</title>
		<link>http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/</link>
		<comments>http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/#comments</comments>
		<pubDate>Thu, 03 May 2012 13:47:31 +0000</pubDate>
		<dc:creator>Jaewon Jung</dc:creator>
				<category><![CDATA[Computer Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[points on sphere]]></category>
		<category><![CDATA[random sampling]]></category>
		<category><![CDATA[sphere]]></category>
		<category><![CDATA[stratified sampling]]></category>
		<category><![CDATA[uniform distribution]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25939</guid>
		<description><![CDATA[<p>Recently, while I was working on a screen-space shader effect, I had to do some <strong>random sampling over the surface of a sphere</strong>. An effective sampling requires <strong>a uniform distribution of samples</strong>. After a quick googling, I found out a way to generate uniformly distributed samples([<em>1</em>]), and it showed a decent result for my application. But, still unsure if that was an ideal way, I performed a due research about it later. Following is the result of that short research.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/" class="more-link">Read more on Generating Uniformly Distributed Points on Sphere&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Recently, while I was working on a screen-space shader effect, I had to do some <strong>random sampling over the surface of a sphere</strong>. An effective sampling requires <strong>a uniform distribution of samples</strong>. After a quick googling, I found out a way to generate uniformly distributed samples([<em>1</em>]), and it showed a decent result for my application. But, still unsure if that was an ideal way, I performed a due research about it later. Following is the result of that short research.</p>
<p>Usually, in graphics application, one can limit it to the three-dimensional space. In that case, there are four possible approaches, all of which guarantee a uniform distribution(BTW, as for what the &#8216;uniform distribution&#8217; exactly means, [6] has some explanations). If a n-dimension support is required, one is out, so three remain. Let&#8217;s take stock of each.</p>
<h4>Rejection sampling ([<em>2</em>][<em>4</em>][<em>5</em>])</h4>
<p>One simple way is something called &#8216;rejection sampling&#8217;. For each x, y, z coordinates, choose a random value of a uniform distribution between [-1, 1]. If the length of the resulting vector is greater than one, reject it and try again. Obviously, this method can be generalized to n-dimension. But <strong>the bigger the dimension gets, the higher the rejection rate gets, so the less efficient the technique becomes</strong>.</p>
<h4>Normal deviate ([<em>2</em>][<em>5</em>])</h4>
<p>This technique chooses x, y and z from <strong>a normal distribution of mean 0 and variance 1</strong>. Then normalize the resulting vector and that&#8217;s it. [<em>2</em>] shows why this method can generate a uniform distribution over a sphere. In short,</p>
<blockquote><p><em>It works because the vector chosen (before normalization) has a density that depends only on the distance from the origin.</em></p></blockquote>
<p>as [<em>5</em>] explains. This also generalizes to n-dimension without a hassle.</p>
<h4>Trigonometry method ([<em>1</em>][<em>3</em>][<em>4</em>][<em>5</em>])</h4>
<p>This one works <strong>only for a three-dimensional sphere</strong>(called 2-sphere in literatures, which means it has two degrees of freedom), but is an easiest one to intuitively grab how it works. [<em>1</em>] nicely explains why it works from Archimedes&#8217; theorem:</p>
<blockquote><p><em>The area of a sphere equals the area of every right circular cylinder circumscribed about the sphere excluding the bases.</em></p></blockquote>
<p>The exact steps are as below:</p>
<ul>
<li>Choose z uniformly distributed in [-1,1].</li>
<li>Choose t uniformly distributed on [0, 2*pi).</li>
<li>Let r = sqrt(1-z^2).</li>
<li>Let x = r * cos(t).</li>
<li>Let y = r * sin(t).</li>
</ul>
<p>This is the one I used for my shader effect. Since I had to use a very small number of samples for the sake of performance, I did a stratified sampling with this method. <strong>A straightforward extension to a stratified sampling is another advantage of this technique</strong>.</p>
<h4>Coordinate approach ([<em>2</em>][<em>3</em>][<em>5</em>])</h4>
<p>The last one is applicable to general n-dimensions and [<em>2</em>] explains its quite math-heavy derivation in detail. This technique first gets the distribution of a single coordinate of a uniformly distributed point on the N-sphere. Then, it recursively gets the distribution of the next coordinate over (N-1)-sphere, and so on. Fortunately, <strong>for the usual 3D space(i.e. 2-sphere), the distribution of a coordinate is uniform and one can do a rejection sampling on 2D for the remaining 1-sphere(i.e. a circle).</strong> The exact way is explained in [<em>5</em>] as a variation of the trigonometry method.</p>
<h3>Codes and Pictures</h3>
<p>Even if you haven&#8217;t got it all fully up to this point, don&#8217;t worry. The source code will fill up the gaps in your understanding. You can find my <strong>naive C++ implementations</strong> of techniques above here: <a href="http://ideone.com/oYEVR">http://ideone.com/oYEVR</a></p>
<p>And some pretty pictures of random points generated by each method:</p>
<div class="wp-caption alignnone" style="width: 510px"><img src="http://i1089.photobucket.com/albums/i342/all2one/scriptogram_images/rejection_sampling.jpg" alt="500 points by rejection sampling" width="500" height="500" /><p class="wp-caption-text">500 points by rejection sampling</p></div>
<div class="wp-caption alignnone" style="width: 510px"><img src="http://i1089.photobucket.com/albums/i342/all2one/scriptogram_images/normal_deviate.jpg" alt="500 points by normal deviate" width="500" height="500" /><p class="wp-caption-text">500 points by normal deviate</p></div>
<div class="wp-caption alignnone" style="width: 510px"><img src="http://i1089.photobucket.com/albums/i342/all2one/scriptogram_images/trig_method.jpg" alt="500 points by trigonometry method" width="500" height="500" /><p class="wp-caption-text">500 points by trigonometry method</p></div>
<div class="wp-caption alignnone" style="width: 510px"><img src="http://i1089.photobucket.com/albums/i342/all2one/scriptogram_images/coordinate_approach.jpg" alt="500 points by coordinate approach" width="500" height="500" /><p class="wp-caption-text">500 points by coordinate approach</p></div>
<p>BTW, all the images above were plotted by <a href="http://math.exeter.edu/rparris/winplot.html"><strong>Winplot</strong></a>.</p>
<h3><a href="http://www.urbandictionary.com/define.php?term=tl%3Bdr" target="_blank">TL;DR</a></h3>
<p>Just use the trigonometry method above and add a stratified sampling, if necessary. That&#8217;ll be enough for the most of cases. ;)</p>
<h3>References</h3>
<ol>
<li><a href="http://repository.upenn.edu/cgi/viewcontent.cgi?article=1188&amp;context=cis_reports">http://repository.upenn.edu/cgi/viewcontent.cgi?article=1188&amp;context=cis_reports</a></li>
<li><a href="http://www-alg.ist.hokudai.ac.jp/~jan/randsphere.pdf">http://www-alg.ist.hokudai.ac.jp/~jan/randsphere.pdf</a></li>
<li><a href="http://mathworld.wolfram.com/SpherePointPicking.html">http://mathworld.wolfram.com/SpherePointPicking.html</a></li>
<li><a href="http://cgafaq.info/wiki/Uniform_random_points_on_sphere">http://cgafaq.info/wiki/Uniform_random_points_on_sphere</a></li>
<li><a href="http://www.math.niu.edu/~rusin/known-math/96/sph.rand">http://www.math.niu.edu/~rusin/known-math/96/sph.rand</a></li>
<li><a href="http://www.math.niu.edu/~rusin/known-math/95/sphere.faq">http://www.math.niu.edu/~rusin/known-math/95/sphere.faq</a></li>
</ol>
<p>(This article has also been posted to<a href="http://scriptogr.am/jj"> my personal blog</a>.)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/03/generating-uniformly-distributed-points-on-sphere/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server Performance: Part 1</title>
		<link>http://www.altdevblogaday.com/2012/05/02/sql-server-performance-part-1/</link>
		<comments>http://www.altdevblogaday.com/2012/05/02/sql-server-performance-part-1/#comments</comments>
		<pubDate>Wed, 02 May 2012 09:00:50 +0000</pubDate>
		<dc:creator>Ted Spence</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25860</guid>
		<description><![CDATA[<p>I first began working with SQL (the <a href="http://en.wikipedia.org/wiki/SQL-92">SQL-92 dialect</a>) in 1995.  At the time I’d only ever used raw disk IO for storage; and SQL was a complete shock.  Every bit of data I needed could be stored using a single API, and the database server took care of all the hard work. In 1997 I switched to Microsoft SQL Server 6.5, and it quickly became my preferred database.  Not everyone in the gaming world uses SQL, but if you do, here are some performance tuning lessons I’ve learned along the way.</p>
<p><a href="http://www.altdevblogaday.com/2012/05/02/sql-server-performance-part-1/" class="more-link">Read more on SQL Server Performance: Part 1&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I first began working with SQL (the <a href="http://en.wikipedia.org/wiki/SQL-92">SQL-92 dialect</a>) in 1995.  At the time I’d only ever used raw disk IO for storage; and SQL was a complete shock.  Every bit of data I needed could be stored using a single API, and the database server took care of all the hard work. In 1997 I switched to Microsoft SQL Server 6.5, and it quickly became my preferred database.  Not everyone in the gaming world uses SQL, but if you do, here are some performance tuning lessons I’ve learned along the way.</p>
<p><span id="more-25860"></span></p>
<h3>Part 1: Effective use of SQL Server</h3>
<p>SQL Server is almost completely devoid of “magic performance tricks.”  This article isn’t going to be about tuning configuration settings; instead, it’s going to cover how to give yourself enough flexibility and freedom to spot performance problems early, and make changes to improve performance when you identify a problem.</p>
<h3>Design Flexibility</h3>
<p>Before we start, let’s cover a few helpful design ideas that can make performance tuning easier in the future.  Each one of these could be discussed as its own topic, but let’s do a quick top level view.</p>
<ul>
<li>Use SQL only for data that must be <a href="http://en.wikipedia.org/wiki/ACID">ACID compliant</a>, relational, changeable, persistent, and cannot be recreated easily.  For example, SQL is a perfect place to store player account data, item possession data, and auction house data.  It’s not an ideal place for text chat logs (not relational &#8211; just store them in a text repository), multiplayer game invitations (not persistent &#8211; users will recreate them after a crash), images (these don’t really change &#8211; just save them in files that can be <a href="https://www.varnish-cache.org/">varnish-cached</a>), and so on.</li>
<li>Design your SQL environment to be split apart.  If you have eight or nine types of data in your system, make them each their own databases.  That way, when your game suddenly explodes in size, each one can be scaled upward at its own pace.  Within a single database, I find that it’s useful to give each subsystem its own three-character prefix so that I can rapidly group related objects together. The only drawback is that you won&#8217;t be able to use foreign keys across distributed databases; but in most cases that&#8217;s necessary for high performance anyway.
<p><div id="attachment_25863" class="wp-caption aligncenter" style="width: 421px"><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/Drawing1.png"><img class="size-full wp-image-25863" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/Drawing1.png" alt="Imagine you had to cut your database in half - make sure it's clear how to do it." width="411" height="219" /></a><p class="wp-caption-text">Isolating Tables</p></div></li>
<li>Use SQL licensing effectively.  Since <a href="http://www.microsoft.com/sqlserver/en/us/editions/2012-editions/express.aspx">SQL Express</a> is basically the same engine as <a href="http://www.microsoft.com/sqlserver/en/us/editions/2012-editions/standard.aspx">SQL Standard</a> with a size limitation, I like to use it in proof of concept environments.  When the database grows larger, I can migrate it to SQL Standard with just a new connection string.</li>
<li>If you have a physical SQL server, put your TempDB on its own, physically isolated disk drive.  Ideally, use a sub-$100 SSD for this.  There are lots of nifty tricks you can do with a high performance TempDB drive.</li>
<li>Get an <a href="http://msdn.microsoft.com/subscriptions/default.aspx">MSDN subscription</a> and use your development SQL license to have extra non-production servers sitting around.  This means you can always experiment with a new database configuration.</li>
<li>Don’t write SQL directly into your application.  Using stored procedures mostly removes the SQL language parser overhead.  Additionally, when you discover a performance problem, a stored procedure can be surgically altered while still in production.</li>
<li>Make use of your database maintenance plans.  Note that these only work on SQL Standard; but it can be awfully useful to have your database run a checkpoint and incremental backup every hour.  Indexes should be rebuilt nightly.</li>
<li>Learn “<a href="http://en.wikipedia.org/wiki/Third_normal_form">Third Normal Form</a>”.  The full details of 3NF are quite complex, but in practice, what it means is that each datum should exist in the database once and only once.  A classic example is storing the department name for an employee database; here’s the right and wrong way to do it:<br />
<div id="attachment_25865" class="wp-caption aligncenter" style="width: 472px"><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/Drawing4.png"><img class="size-full wp-image-25865" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/Drawing4.png" alt="Strings are big - so make sure each string is in the database only once." width="462" height="202" /></a><p class="wp-caption-text">Move your data into specialized tables with useful primary keys.</p></div>
</li>
</ul>
<p>I should also warn you that databases are easy to take for granted. SQL Server is a very friendly, deceptively simple program.  Often the dev database you create will seem so fast that you&#8217;ll be tempted to ignore performance tuning, until the production server grinds to a halt on deploy day. So let&#8217;s review a few tricks to enable you to see these problems before they get pushed live.</p>
<h3>Spotting Performance Problems</h3>
<p>Everyone’s best friend should be “Show Execution Plan.”  For each query you write, click the little button that shows either the estimated or actual execution plan. The results will look like this:</p>
<div id="attachment_25875" class="wp-caption aligncenter" style="width: 915px"><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/drawing2.png"><img class="size-full wp-image-25875" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/drawing2.png" alt="A Sample Execution Plan" width="905" height="367" /></a><p class="wp-caption-text">An execution plan that could be optimized.</p></div>
<p>In this screen, you see a &#8220;Table Scan&#8221; that consumes a large amount of time that could be optimized out by creating an index.  It&#8217;s the equivalent to having an unstructured array and scanning through every element blindly.  Adding an index allows your database to use the equivalent of adding a <a href="http://en.wikipedia.org/wiki/Red%E2%80%93black_tree">red/black tree</a> or <a href="http://en.wikipedia.org/wiki/Hash_table">hash table</a> to look up data faster.  The great value of SQL Server is that you can dynamically tune the indexes your application uses without modifying your code!</p>
<p>You should look through the execution plan for the following:</p>
<ul>
<li><span class="font-weight: bold;">Missing indexes</span>. SQL Server will helpfully tell you, highlighted in green, the exact index it wishes it had.  Right click on it and select “Missing Index Details;” you can then give it a name and create it for an instant performance boost …… but remember that this isn’t always the best idea.  Each index you create slows down inserts, updates, and deletes.  Indexes also consume memory, which can result in page faults when you’re under memory pressure.  If you can, make all your indexes use integer IDs, since they are very memory-dense and fast to search.  Organize indexes with multiple values so that the most restrictive values are first &#8211; that will allow the query optimizer to exclude large volumes of rows rapidly.</li>
<li><span class="font-weight: bold;">Table Scans</span>. As described above, if SQL server is spending a significant amount of time scanning your tables, try to figure out ways to modify your indexes to convert them to &#8220;Index Seek&#8221; instead.</li>
<li><span class="font-weight: bold;">Too many joins</span>.  If your execution plan is really tall and wide, this usually means that SQL server is joining lots of tables together in a single step.  Lots of joins are an inescapable side effect of a normalized database; I&#8217;ll write a future article on the subject in detail. But for the moment, look for any tables that can be optimized away. Try declaring a variable to contain some of the values you want and selecting them early.  For example, look at these two equivalent SQL snippets &#8211; one of them only joins two tables, and the other joins three:</li>
</ul>

<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
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- SLOW WAY: Get weapons sales by querying three tables</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> i<span style="color: #66cc66;">.</span>item_name<span style="color: #66cc66;">,</span> i<span style="color: #66cc66;">.</span>item_id<span style="color: #66cc66;">,</span> h<span style="color: #66cc66;">.</span>price<span style="color: #66cc66;">,</span> h<span style="color: #66cc66;">.</span>unit_count
  <span style="color: #993333; font-weight: bold;">FROM</span> act_auctionhistory h
       <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> itm_items i <span style="color: #993333; font-weight: bold;">ON</span> i<span style="color: #66cc66;">.</span>item_id <span style="color: #66cc66;">=</span> a<span style="color: #66cc66;">.</span>item_id
       <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> itm_itemclasses ic <span style="color: #993333; font-weight: bold;">ON</span> ic<span style="color: #66cc66;">.</span>itemclass_id <span style="color: #66cc66;">=</span> i<span style="color: #66cc66;">.</span>itemclass_id
 <span style="color: #993333; font-weight: bold;">WHERE</span> ic<span style="color: #66cc66;">.</span>itemclass_name <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'weapon'</span>
       <span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span> i<span style="color: #66cc66;">.</span>item_id<span style="color: #66cc66;">,</span> i<span style="color: #66cc66;">.</span>item_name
&nbsp;
<span style="color: #808080; font-style: italic;">-- FAST WAY: Get the same data but use only two tables at a time</span>
<span style="color: #993333; font-weight: bold;">DECLARE</span> @cid <span style="color: #993333; font-weight: bold;">INT</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> @cid <span style="color: #66cc66;">=</span> itemclass_id <span style="color: #993333; font-weight: bold;">FROM</span> itm_itemclasses <span style="color: #993333; font-weight: bold;">WHERE</span> itemclass_name <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'weapon'</span>
&nbsp;
<span style="color: #993333; font-weight: bold;">SELECT</span> i<span style="color: #66cc66;">.</span>item_name<span style="color: #66cc66;">,</span> i<span style="color: #66cc66;">.</span>item_id<span style="color: #66cc66;">,</span> h<span style="color: #66cc66;">.</span>price<span style="color: #66cc66;">,</span> h<span style="color: #66cc66;">.</span>unit_count
  <span style="color: #993333; font-weight: bold;">FROM</span> act_auctionhistory h
       <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> itm_items i <span style="color: #993333; font-weight: bold;">ON</span> i<span style="color: #66cc66;">.</span>item_id <span style="color: #66cc66;">=</span> a<span style="color: #66cc66;">.</span>item_id
 <span style="color: #993333; font-weight: bold;">WHERE</span> i<span style="color: #66cc66;">.</span>itemclass_id <span style="color: #66cc66;">=</span> @cid
       <span style="color: #993333; font-weight: bold;">GROUP</span> <span style="color: #993333; font-weight: bold;">BY</span> i<span style="color: #66cc66;">.</span>item_id<span style="color: #66cc66;">,</span> i<span style="color: #66cc66;">.</span>item_name</pre></td></tr></table></div>

<p>Here&#8217;s another tip. Log on to your live server (make sure you use read-only privileges of course!). Right click on your SQL Server in the left hand pane and select “Activity Monitor”, then “Recent Expensive Queries”.  I find that I get a lot of mileage out of just checking this page every few hours:</p>
<div id="attachment_25864" class="wp-caption aligncenter" style="width: 916px"><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/05/drawing3.png"><img class="size-full wp-image-25864" src="http://www.altdevblogaday.com/wp-content/uploads/2012/05/drawing3.png" alt="SQL Server's activity monitor - worth checking regularly, like a facebook page for your database." width="906" height="367" /></a><p class="wp-caption-text">Check this page regularly!</p></div>
<p>So when you get see this screen, what do you look for and how do you make use of the information? Start by right clicking on each query and show the execution plan for each one.</p>
<h3>Log Your Database Activity</h3>
<p>Another worthwhile tip is to modify your code to write a log of database queries to your debug output.  When you’re using advanced ORM tools like <a href="http://msdn.microsoft.com/en-us/data/aa937723">Entity Framework </a>or <a href="http://nhforge.org/Default.aspx">NHibernate</a>, it’s very easy to write code that has a side effect of generating unexpected database hits.  For example, consider this simple logic:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> itemarray.<span style="color: #202020;">Length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>itemarray<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #202020;">IsQuestObject</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In most cases this logic is fine and fast.  But imagine that the programmer down the hall fixes a bug by making IsQuestObject() ping the database &#8211; all of a sudden you’ve got a nearly-invisible massive performance penalty. The database is often so fast that you don&#8217;t notice these kinds of performance sinks. So I modify my ORM to emit debug output every time it executes a SQL statement.</p>
<p>As a result, when running in debug, I see the following:</p>

<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="text" style="font-family:monospace;">SQL: list_OrderedUserAccounts (Time: 00:00:00.0030000)
SQL: get_PermissionsByUser (Time: 00:00:00.0020000)
SQL: RetrievePermissionGroupObject (Time: 00:00:00.0020000)
SQL: get_JoinsByLabel (Time: 00:00:00.0010000)
SQL: get_JoinsByLabel (Time: 00:00:00.0010000)
SQL: get_JoinsByLabel (Time: 00:00:00.0010000)
SQL: ListProductObject (Time: 00:00:01.3680000)
SQL: list_OrderedPlatforms (Time: 00:00:00.0020000)</pre></td></tr></table></div>

<p>When I look at this output, I immediately check to see if I’ve accidentally written a loop that calls get_JoinsByLabel too many times.  Then next I investigate the query “ListProductObject” to see why it took 1.5 seconds.</p>
<h3>Combine multiple queries</h3>
<p>Nothing improves performance quite like reducing the number of queries you execute.  Rather than submitting ten queries rapidly, why not make use of a single stored procedure that returns ten result sets?  Let’s say you’re working on the front page of your in-game auction house, but when the user mouses over an item name or a player name, you want to show some secondary details.</p>
<p>You could do this by writing one query for the auction house page and a second query for each time the user hovers their mouse.  But that would produce dozens of queries every time the mouse moved.</p>
<p>Instead, let’s create a single compound query that returns both the auction page and the popup text for everything.  Even though at first glance you may think you’re doing unnecessary work, SQL Server is already looking up all the objects using hash tables, and you’re reducing query overhead significantly by reducing volume.  Here’s roughly how to do it:</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
19
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">PROCEDURE</span> get_AuctionHouseFirstPage <span style="color: #993333; font-weight: bold;">AS</span>
&nbsp;
<span style="color: #808080; font-style: italic;">-- Preparation: Select basic into a temporary table</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> auction_id<span style="color: #66cc66;">,</span> character_id<span style="color: #66cc66;">,</span> auction_date<span style="color: #66cc66;">,</span> …
  <span style="color: #993333; font-weight: bold;">FROM</span> ACT_Auctions<span style="color: #66cc66;">,</span> …
  <span style="color: #993333; font-weight: bold;">INTO</span> #temp_auction_page
&nbsp;
<span style="color: #808080; font-style: italic;">-- First result set: Return the auction page</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">...</span> <span style="color: #993333; font-weight: bold;">FROM</span> #temp_auction_page
&nbsp;
<span style="color: #808080; font-style: italic;">-- Second result set: Return pop-up information about characters</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> user_name<span style="color: #66cc66;">,</span> guild_name<span style="color: #66cc66;">,</span> …
  <span style="color: #993333; font-weight: bold;">FROM</span> CHR_Characters c
       <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> #temp_auction_page t <span style="color: #993333; font-weight: bold;">ON</span> c<span style="color: #66cc66;">.</span>char_id <span style="color: #66cc66;">=</span> t<span style="color: #66cc66;">.</span>char_id
&nbsp;
<span style="color: #808080; font-style: italic;">-- Third result set: Return pop-up information about items</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> item_name<span style="color: #66cc66;">,</span> item_enchantment<span style="color: #66cc66;">,</span> <span style="color: #66cc66;">...</span>
  <span style="color: #993333; font-weight: bold;">FROM</span> ITM_Items i
       <span style="color: #993333; font-weight: bold;">INNER</span> <span style="color: #993333; font-weight: bold;">JOIN</span> #temp_auction_page t <span style="color: #993333; font-weight: bold;">ON</span> i<span style="color: #66cc66;">.</span>item_id <span style="color: #66cc66;">=</span> t<span style="color: #66cc66;">.</span>item_id</pre></td></tr></table></div>

<h3>For Next Time</h3>
<p>Many of you may be asking &#8211; what about SQL vs NoSQL databases? I encourage you to tread lightly and consider them carefully on their own merits. Unlike SQL, which provides specific guarantees to data behavior at the cost of performance, NoSQL databases have their own unique advantages and drawbacks. There are many situations in gaming that are extremely well suited for NoSQL implementations; but this is a complex issue that really deserves its own article.</p>
<p>For the next SQL Server performance article, I&#8217;ll look at the speed of database inserts and updates, and the side effects of some basic choices in software style.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/05/02/sql-server-performance-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Software Rasterizer Part 2</title>
		<link>http://www.altdevblogaday.com/2012/04/29/software-rasterizer-part-2/</link>
		<comments>http://www.altdevblogaday.com/2012/04/29/software-rasterizer-part-2/#comments</comments>
		<pubDate>Sun, 29 Apr 2012 12:48:13 +0000</pubDate>
		<dc:creator>Simon Yeung</dc:creator>
				<category><![CDATA[Computer Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software rasterizer]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25741</guid>
		<description><![CDATA[<p><strong><span class="Apple-style-span" style="font-size: large">Introduction</span></strong></p>
<p>Continue with the <a href="http://simonstechblog.blogspot.com/2012/04/software-rasterizer-part-1.html">previous post</a>, after filling the triangle with scan line or half-space algorithm, we also need to interpolate the vertex attributes across the triangle so that we can have texture coordinates or depth on every pixel. However we cannot directly interpolate those attributes in screen space because projection transform after perspective division is not an <a href="http://en.wikipedia.org/wiki/Affine_transformation">affine transformation</a> (i.e. after transformation, the mid-point of the line segment is no longer the mid-point), this will result in some distortion and this artifact is even more noticeable when the triangle is large:</p>
<p><a href="http://www.altdevblogaday.com/2012/04/29/software-rasterizer-part-2/" class="more-link">Read more on Software Rasterizer Part 2&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><strong><span class="Apple-style-span" style="font-size: large">Introduction</span></strong></p>
<p>Continue with the <a href="http://simonstechblog.blogspot.com/2012/04/software-rasterizer-part-1.html">previous post</a>, after filling the triangle with scan line or half-space algorithm, we also need to interpolate the vertex attributes across the triangle so that we can have texture coordinates or depth on every pixel. However we cannot directly interpolate those attributes in screen space because projection transform after perspective division is not an <a href="http://en.wikipedia.org/wiki/Affine_transformation">affine transformation</a> (i.e. after transformation, the mid-point of the line segment is no longer the mid-point), this will result in some distortion and this artifact is even more noticeable when the triangle is large:</p>
<table>
<tbody>
<tr>
<td>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://4.bp.blogspot.com/-XOR93SRDUew/T4loMyobapI/AAAAAAAAAVc/bBYSu-0cIrg/s1600/interpolateInScrSpace.png"><img src="http://4.bp.blogspot.com/-XOR93SRDUew/T4loMyobapI/AAAAAAAAAVc/bBYSu-0cIrg/s320/interpolateInScrSpace.png" alt="" width="320" height="180" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">interpolate in screen space</td>
</tr>
</tbody>
</table>
</td>
<td>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://3.bp.blogspot.com/-zIhlNAMPUU4/T4loScmVUgI/AAAAAAAAAVk/GzOogFZwhnM/s1600/interpolatePerspectiveCorrect.png"><img src="http://3.bp.blogspot.com/-zIhlNAMPUU4/T4loScmVUgI/AAAAAAAAAVk/GzOogFZwhnM/s320/interpolatePerspectiveCorrect.png" alt="" width="320" height="180" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">perspective correct interpolation</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<p><span class="Apple-style-span" style="font-size: large;font-weight: bold">Condition for linear interpolation</span></p>
<p>When interpolating the attributes in a linear way, we are saying that given a set of vertices, <em>v</em><span class="Apple-style-span" style="font-size: xx-small"><em>i</em></span> (where i is any integer&gt;=0) with a set of attributes <em>a</em><em><span class="Apple-style-span" style="font-size: xx-small">i</span></em> (such as texture coordinates), we have a function mapping a vertex to the corresponding attributes, i.e.</p>
<div style="text-align: center"><em>f</em>(<em>v</em><em><span class="Apple-style-span" style="font-size: xx-small">i</span></em>)= <em>a</em><em><span class="Apple-style-span" style="font-size: xx-small">i</span></em></div>
<p>Say, to interpolate a vertex inside a triangle in a linear way, the function <em>f</em> need to have the following properties:</p>
<div style="text-align: center"><em>f</em>(<em>t<span class="Apple-style-span" style="font-size: xx-small">0</span></em> *<em>v</em><em><span class="Apple-style-span" style="font-size: xx-small">0</span></em> + <em>t<span class="Apple-style-span" style="font-size: xx-small">1</span></em> *<em>v</em><em><span class="Apple-style-span" style="font-size: xx-small">1</span></em> + <em>t<span class="Apple-style-span" style="font-size: xx-small">2</span></em> *<em>v</em><em><span class="Apple-style-span" style="font-size: xx-small">2</span></em> ) = <em>t<span class="Apple-style-span" style="font-size: xx-small">0</span></em> * <em>f</em>(<em>v</em><em><span class="Apple-style-span" style="font-size: xx-small">0</span></em>) + <em>t<span class="Apple-style-span" style="font-size: xx-small">1</span></em> * <em>f</em>(<em>v</em><em><span class="Apple-style-span" style="font-size: xx-small">1</span></em>) + <em>t<span class="Apple-style-span" style="font-size: xx-small">2</span></em> * <em>f</em>(<em>v</em><em><span class="Apple-style-span" style="font-size: xx-small">2</span></em>)</div>
<div style="text-align: right"><span class="Apple-style-span" style="font-size: x-small"><span class="Apple-style-span">, for any </span><em>t0</em>, <em>t1</em>, <em>t2</em><span class="Apple-style-span"> where <em>t0 </em></span>+ <em>t1 </em>+ <em>t2</em>=1</span></div>
<p>which means that we can calculate the interpolated attributes using the same weight <em>t<span class="Apple-style-span" style="font-size: xx-small">i</span></em> used for interpolating vertex position. For functions having the above properties, those functions will be an <a href="http://en.wikipedia.org/wiki/Affine_transformation">affine function</a> with the following form:</p>
<div style="text-align: center"><em>f</em>(<em>x</em>)= <em>Ax</em> + <em>b</em></div>
<div style="text-align: right"><span class="Apple-style-span" style="font-size: x-small">, where <em>A</em> is a matrix, <em>x</em> and <em>b</em> are vector</span></div>
<p><span class="Apple-style-span" style="font-size: large;font-weight: bold">Depth interpolation</span></p>
<p>When a vertex is projected from view space to normalized device coordinates(NDC), we will have the following relation (ratio of the triangles) between the view space and NDC space:</p>
<div class="separator" style="clear: both;text-align: center"><a href="http://2.bp.blogspot.com/-cI7nS4ZOEXY/T4mDh9YNMNI/AAAAAAAAAVs/s0NYz7z_VME/s1600/eqt1_2.png"><img src="http://2.bp.blogspot.com/-cI7nS4ZOEXY/T4mDh9YNMNI/AAAAAAAAAVs/s0NYz7z_VME/s320/eqt1_2.png" alt="" width="320" height="88" border="0" /></a></div>
<p>substitute equation 1 and 2 into the plane equation of the triangle lies on:</p>
<div class="separator" style="clear: both;text-align: center"><a href="http://2.bp.blogspot.com/-39mf9Y9Nq7E/T4mDn7EyE6I/AAAAAAAAAV0/jd-K65xWHmU/s1600/eqt3.png"><img src="http://2.bp.blogspot.com/-39mf9Y9Nq7E/T4mDn7EyE6I/AAAAAAAAAV0/jd-K65xWHmU/s400/eqt3.png" alt="" width="400" height="90" border="0" /></a></div>
<p>&nbsp;</p>
<div>
<div>
<p>So, 1/<em>z<span class="Apple-style-span" style="font-size: xx-small">view</span></em> is an affine function of <em>x<span class="Apple-style-span" style="font-size: xx-small">ndc</span></em> and <em>y<span class="Apple-style-span" style="font-size: xx-small">ndc</span></em> which can be interpolated linearly across the screen space (the transform from NDC space to screen space is a linear transform).</p>
<p><span class="Apple-style-span" style="font-size: large;font-weight: bold">Attributes interpolation</span></p>
<p>In last section, we know how to interpolate the depth of a pixel linearly in screen space, the next problem is to interpolate the vertex attributes(e.g. texture coordinates). In view space, we know that those attributes can be interpolated linearly, so those attributes can be calculated by an affine function with the vertex position as parameters e.g.</p>
<div class="separator" style="clear: both;text-align: center"><a href="http://3.bp.blogspot.com/-YN4TbKnFFRo/T4mDwJdsZlI/AAAAAAAAAV8/9KUBzFV_q2A/s1600/uEqt.png"><img src="http://3.bp.blogspot.com/-YN4TbKnFFRo/T4mDwJdsZlI/AAAAAAAAAV8/9KUBzFV_q2A/s320/uEqt.png" alt="" width="320" height="44" border="0" /></a></div>
<p>Similar to interpolate depth, substitute equation 1 and 2 into the above equation:</p>
<div class="separator" style="clear: both;text-align: center"><a href="http://4.bp.blogspot.com/-A7XmZcn0wjY/T4mD3I0_Q9I/AAAAAAAAAWE/2Z7GLe-jNWA/s1600/uOverZ.png"><img src="http://4.bp.blogspot.com/-A7XmZcn0wjY/T4mD3I0_Q9I/AAAAAAAAAWE/2Z7GLe-jNWA/s400/uOverZ.png" alt="" width="400" height="121" border="0" /></a></div>
<p>Therefore, <em>u</em>/<em>z<span class="Apple-style-span" style="font-size: xx-small">view</span></em> is an another affine function of <em>x<span class="Apple-style-span" style="font-size: xx-small">ndc</span></em> and <em>y<span class="Apple-style-span" style="font-size: xx-small">ndc</span></em> which can be interpolated linearly across the screen space. Hence we can interpolating <em>u</em> linearly by first interpolate <em>1</em>/<em>z<span class="Apple-style-span" style="font-size: xx-small">view</span></em> and <em>u</em>/<em>z<span class="Apple-style-span" style="font-size: xx-small">view</span></em> across screen space, and then divide them per pixel.</p>
<p><span class="Apple-style-span" style="font-size: large;font-weight: bold">The last problem&#8230;</span></p>
</div>
<div>
<p>Now, we know that we can interpolate the view space depth and vertex attributes linearly across screen space. But during the rasterization state, we only have vertices in homogenous coordinates (vertices are transformed by the projection matrix already), how can we get the <em>z<span class="Apple-style-span" style="font-size: xx-small">view</span></em> to do the perspective correct interpolation?</p>
<p>Consider the projection matrix (I use D3D one, but the same for openGL):</p>
<div class="separator" style="clear: both;text-align: center"><a href="http://4.bp.blogspot.com/-KuQCpcDZdw0/T4mD-DIDFKI/AAAAAAAAAWM/HAckGRg5sDg/s1600/proj.png"><img src="http://4.bp.blogspot.com/-KuQCpcDZdw0/T4mD-DIDFKI/AAAAAAAAAWM/HAckGRg5sDg/s200/proj.png" alt="" width="200" height="116" border="0" /></a></div>
<div class="separator" style="clear: both;text-align: -webkit-auto"></div>
<p>After transforming the vertex position, the <em>w</em>-coordinate will be the view space depth!</p>
<div style="text-align: center">i.e. <em><strong>w-</strong></em><em>homogenous </em>=<em> </em><em><strong>z</strong><span class="Apple-style-span" style="font-size: xx-small">view </span></em></div>
<p>And look at the matrix again and consider the transformed <em>z</em>-coordinates, it will in a form of:</p>
<div class="separator" style="clear: both;text-align: center"><a href="http://2.bp.blogspot.com/-_GrTrCVKp-s/T4mEEDH6IFI/AAAAAAAAAWU/4V5nVfHFB68/s1600/zHomo.png"><img src="http://2.bp.blogspot.com/-_GrTrCVKp-s/T4mEEDH6IFI/AAAAAAAAAWU/4V5nVfHFB68/s1600/zHomo.png" alt="" border="0" /></a></div>
<p>After transforming to the NDC,</p>
<div class="separator" style="clear: both;text-align: center"><a href="http://3.bp.blogspot.com/-dBLPwyegfKA/T4mEJ30EpMI/AAAAAAAAAWc/xHMvLbRdMwg/s1600/zNDC.png"><img src="http://3.bp.blogspot.com/-dBLPwyegfKA/T4mEJ30EpMI/AAAAAAAAAWc/xHMvLbRdMwg/s1600/zNDC.png" alt="" border="0" /></a></div>
<p>So the depth value can be directly interpolated using <strong>z-</strong><em>NDC  </em>for depth test.</p>
<p><strong><span class="Apple-style-span" style="font-size: large">Demo</span></strong></p>
<p>A javascript demo to rasterize the triangles can be viewed <a href="http://simonstechblog.blogspot.com/2012/04/software-rasterizer-part-2.html#softwareRasterizerDemo">here</a>(although not optimized&#8230;). And the source code can be downloaded <a href="https://sites.google.com/site/simontechblog/home/softwarerasterizer/softwareRasterizer.js">here</a>.</p>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://simonstechblog.blogspot.com/2012/04/software-rasterizer-part-2.html#softwareRasterizerDemo"><img src="http://2.bp.blogspot.com/-riodEfJnzi4/T5gNhTswj8I/AAAAAAAAAWk/6mmx8r7Ri7I/s320/scrShot.png" alt="" width="320" height="232" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">Screen shot of the demo</td>
</tr>
</tbody>
</table>
<p><strong><span class="Apple-style-span" style="font-size: large">Conclusion</span></strong><br />
In this post, the steps to linear interpolate the vertex in screen space is described. And for rasterizing the depth buffer only (e.g. for occlusion), the depth value can be linearly interpolated directly with the z coordinate in NDC space which is even simpler.</p>
<p><strong>References</strong><br />
[1] <a href="http://www.lysator.liu.se/~mikaelk/doc/perspectivetexture/">http://www.lysator.liu.se/~mikaelk/doc/perspectivetexture/</a><br />
[2] <a href="http://www.gamedev.net/topic/581732-perspective-correct-depth-interpolation/">http://www.gamedev.net/topic/581732-perspective-correct-depth-interpolation/</a><br />
[3] <a href="http://chrishecker.com/Miscellaneous_Technical_Articles">http://chrishecker.com/Miscellaneous_Technical_Articles</a><br />
[4] <a href="http://en.wikipedia.org/wiki/Affine_transformation">http://en.wikipedia.org/wiki/Affine_transformation</a></p>
<p>&nbsp;</p>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/29/software-rasterizer-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Once Upon a Time&#8230;</title>
		<link>http://www.altdevblogaday.com/2012/04/27/once-upon-a-time/</link>
		<comments>http://www.altdevblogaday.com/2012/04/27/once-upon-a-time/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 16:35:00 +0000</pubDate>
		<dc:creator>Poya Manouchehri</dc:creator>
				<category><![CDATA[General Interest]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25809</guid>
		<description><![CDATA[<p>I have a theory: everyone has or will have, at some point, an idea for a story they want to write. Or tell. And I don&#8217;t mean a real life story, but a story that is a creation of one&#8217;s imagination. Now it might be a passing thought&#8230; Maybe it&#8217;s a person, a news report, a real life event, a book, or a game that suddenly triggers an idea for a story. The process of turning that idea into something complete and finished is a whole other&#8230;well, story.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/27/once-upon-a-time/" class="more-link">Read more on Once Upon a Time&#8230;&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I have a theory: everyone has or will have, at some point, an idea for a story they want to write. Or tell. And I don&#8217;t mean a real life story, but a story that is a creation of one&#8217;s imagination. Now it might be a passing thought&#8230; Maybe it&#8217;s a person, a news report, a real life event, a book, or a game that suddenly triggers an idea for a story. The process of turning that idea into something complete and finished is a whole other&#8230;well, story.</p>
<p>Currently I&#8217;m writing the story for the game <a href="http://gamesforsoul.com/connectorium/">Connectorium</a>. It&#8217;ll be the second story I&#8217;m writing in full, after co-writing the <a href="http://www.youtube.com/watch?v=p8U_xfWTIMY">Revival</a> short film (I&#8217;m not counting the one or two short stories here and there, and a failed attempt at writing a fantasy novel after watching the first Lord of the Rings film. Who didn&#8217;t do that, right?). Here are just a collection of random thoughts, observations, and experiences about the process. Obviously these are not the opinions of an expert; I&#8217;m merely hoping it opens up the way for a conversation and invites thoughts from you.</p>
<h2>From Abstraction to Realization</h2>
<p>This is something that is universal to the creative process. You begin with an empty canvas. Maybe a concept that is completely abstract and vague. Then with every sentence, with every stroke of a brush, with every added note, or with every line of code, you bring that abstraction one step closer to existence (and also the number of possibilities of what that end product will be reduces with every step). But there is a key thing I have realized: this is a two way process. The original idea, or concept affects what you create. But what you create also affects the idea over time. To a point where the final product may in no way resemble the original idea. I think this a very important part of the creative process: the organic nature of it.</p>
<p>As far as a story goes, that initial concept and idea can be many different things. Maybe it&#8217;s a particular character, or a specific plot point. Maybe it&#8217;s a particular setting. Maybe it&#8217;s a mechanic in the game you are designing. Either way, it&#8217;s important to keep in mind that your completed story may be nothing like what you had initially conceived. And that&#8217;s OK. In fact it&#8217;s more than OK. It&#8217;s usually a good thing.</p>
<h2>Working Backwards</h2>
<div style="text-align:center">
<a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/walking-backwards.jpg"><img src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/walking-backwards.jpg" alt="" width="167" height="183" class="aligncenter size-full wp-image-25832" /></a>
</div>
<p>When I first started working on Connectorium, I had a general idea for the story. The game is about systems and connections, so the story was going to be about a little girl who wakes up one morning to a world where all connections have gone missing. Her adventure would be about her meeting various characters, helping them restore the missing connections, and solving the mystery. For some time though, I stalled fleshing out the story more. Eventually I asked myself, why am I wasting time? Why don&#8217;t I just write the story? And it occurred to me: it&#8217;s because I didn&#8217;t know how it&#8217;s going to end.</p>
<p>So one morning I decided to take my iPad, go to a quiet park, and not come back home until I have figured out how the story will end. It took a couple of hours, but eventually I came up with an idea, quite suddenly really. I had a big smile on my face right at that moment, because I knew I could start writing the story now.</p>
<p>Maybe this is more a function of the kinds of story that I enjoy and like to write, but I find that I really need to know the ending early on. Everything in the plot, the characters, the gameplay in the case of a game, is pushing the audience towards that ending. It&#8217;s what keeps the story coherent to me.</p>
<h2>Characters or Plot</h2>
<p>One of my favorite writers, Isaac Asimov, is often criticized for having somewhat uninteresting and 2D characters. Nevertheless he is an amazing story teller.</p>
<p>But one can&#8217;t argue that the best of stories combine a great plot, with believable and great characters. What I have noticed is that personally I&#8217;m much more interested and focused on the plot. So I always need to be conscious of the &#8220;flatness&#8221; of my characters. For that reason, after I have written the initial draft of the story, I&#8217;ll do an iteration where I&#8217;ll focus specifically on each character, writing more back story, fixing the dialog, descriptions, and so on, of course adjusting the plot where necessary. I can imagine the reverse can work just as well: building a detailed and interesting character, and developing the story around that character (or characters).</p>
<h2>Dialog, Dialog, Dialog</h2>
<p>For me, probably the hardest part of writing a story is the dialog. Not only is it really hard to write a believable, natural, and flowing conversation between two or more characters, it&#8217;s even harder to have all your characters not sound exactly the same! Exactly like&#8230;you!</p>
<p>More than anything, it just requires time, and rewrites to improve this. It is also important to have back stories for characters, even if none of it is ever revealed to the audience. Where do they come from? What do they do? What do they eat? What was their childhood like? What are their relationships like? What is their motivation? All of these impact how a character speaks, how they would react to a situation, and how they&#8217;d express themselves.</p>
<p>Another thing that has helped me is trying to picture a real life person acting out that character. Maybe someone you know, or an actor. Putting a face and voice to a line of dialog goes a long way to help you see if it&#8217;s the right fit. Sometimes reading it out loud in the voice that you think the character would be speaking in also helps here.</p>
<h2>On the Subject of Games</h2>
<p>I&#8217;ve been talking a lot about stories, and haven&#8217;t really talked much about games. Here is point I want to make which I can expect at least some to disagree with.</p>
<p>I feel that the gameplay must reinforce the story as much as possible. At the very least it shouldn&#8217;t contradict it, because that takes you out of the immersion that you might otherwise have. How often do you run around in a game, killing various things, and collecting numerous items, stats, etc, just to be reminded by a cut scene that you&#8217;re actually trying to resolve a much greater conflict.</p>
<div style="text-align:center">
<img src="http://lparchive.org/Neverwinter-Nights-2-Storms-of-Zehir/Update%2016/17-0009_-_what_do_you_make_of_this_barrel.jpg" width="500"></img>
</div>
<div style="text-align:center;font-size:small">
&#8220;Alright guys, just a few more crates. Then Lord what&#8217;s-his-face is gonna get it&#8230;&#8221;
</div>
<p></p>
<p>And here is another (potentially less popular) thought. Given that there are practically infinite possible stories, why is it that a good percentage of games, especially those with plots and characters, include combat in some form as their core mechanic? Is it that we are simply avoiding stories where combat isn&#8217;t an integral component? Or are we throwing in combat into the mix, regardless of whether or not it reinforces the story?</p>
<p>Just a thought. Would love to hear yours.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/27/once-upon-a-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Difficulties of an Infinite Video Game World</title>
		<link>http://www.altdevblogaday.com/2012/04/27/the-difficulties-of-an-infinite-video-game-world/</link>
		<comments>http://www.altdevblogaday.com/2012/04/27/the-difficulties-of-an-infinite-video-game-world/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 00:58:27 +0000</pubDate>
		<dc:creator>Alex Norton</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Game design]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[indie]]></category>
		<category><![CDATA[infinite]]></category>
		<category><![CDATA[procedural generation]]></category>
		<category><![CDATA[RPG]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25798</guid>
		<description><![CDATA[<h1>The Premise</h1>
<p>Procedural Generation is definitely in vogue, and I personally have believed that it is the way forward in video gaming for many years now. Using procedural generation in games is nothing new of course, as fans of games such as <a title="Elite (Video Game)" href="http://en.wikipedia.org/wiki/Elite_%28video_game%29" target="_blank">Elite</a> or <a title="The Sentinel (Video Game)" href="http://en.wikipedia.org/wiki/The_Sentinel_%28computer_game%29" target="_blank">The Sentinel</a> will know that we&#8217;ve been seeing it in games for a good 25 years.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/27/the-difficulties-of-an-infinite-video-game-world/" class="more-link">Read more on The Difficulties of an Infinite Video Game World&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<h1>The Premise</h1>
<p>Procedural Generation is definitely in vogue, and I personally have believed that it is the way forward in video gaming for many years now. Using procedural generation in games is nothing new of course, as fans of games such as <a title="Elite (Video Game)" href="http://en.wikipedia.org/wiki/Elite_%28video_game%29" target="_blank">Elite</a> or <a title="The Sentinel (Video Game)" href="http://en.wikipedia.org/wiki/The_Sentinel_%28computer_game%29" target="_blank">The Sentinel</a> will know that we&#8217;ve been seeing it in games for a good 25 years.</p>
<p>Older titles made good use of it due to the memory constraints of the hardware of the time. It was simply more efficient to have generated levels rather than hand crafted ones, but that is no excuse for games not to make better use of it now that we have better specced hardware.</p>
<p>Fans of the RPG genre will no doubt remember <a title="The Elder Scrolls II: Daggerfall" href="http://en.wikipedia.org/wiki/The_Elder_Scrolls_II:_Daggerfall" target="_blank">The Elder Scrolls II: Daggerfall</a>, which had one of the largest in-game worlds ever seen, and still to this day tramples almost every RPG made in terms of world size. I recall reading somewhere that the in-game world of Daggerfall was equal to twice the landmass of the British Isles.</p>
<p>That is a heck of a lot of world to explore, and &#8211; from a game design perspective &#8211; a nightmare to recreate by hand. Through clever use of procedural generation, however, it is easily possible, which is what Bethesda Softworks did with Daggerfall. The settlements and towns were hand-crafted, with the wilderness in between being generated by the game.</p>
<p>But why stop there? Why have world borders at all? Procedural generation code hasn&#8217;t changed much in the last 25 years. People are still stuck using fractals and diamonds and blobs to do everything, which becomes repetitive and quite simply <em>looks</em> like procedurally generated content. To any programmer looking at it, it virtually <em>smells</em> of procedural generation. On top of all this, if you get it wrong, it will end up VERY wrong. The indie crowd seems to do it best, with titles like <a title="Dwarf Fortress" href="http://en.wikipedia.org/wiki/Slaves_to_Armok_II:_Dwarf_Fortress" target="_blank">Dwarf Fortress</a> generating MASSIVE worlds with lush histories and more world than you could ever hope to explore. But still, they aren&#8217;t pushing the envelope. My aim was to fix that by making it work. An infinite game world should be possible, and indeed it is.</p>
<p>&nbsp;</p>
<h1>The Idea</h1>
<p>Just over two years ago I began assembling a team to make the first truly infinite, fully 3D fantasy RPG, entitled <a title="Malevolence: The Sword of Ahkranox" href="http://www.msoa-game.com/" target="_blank">Malevolence: The Sword of Ahkranox</a>. It was to be played in a style similar to the classic grid-based, first person RPGs of the late 80s and early 90s such as Might &amp; Magic, Eye of the Beholder and Dungeon Master, but set in a literally infinite world. We had originally thought to make it a planet-sized world, but in the end decided on the story being that the game&#8217;s world was being created within the imagination of a sentient sword, which would act as a way to &#8220;explain&#8221; the infinity of it.</p>
<p>After <em>much</em> experimentation and very complex math, we got it working, but all in raw data. Nothing really playable. But we had in front of us an infinite world filled with infinite dungeons and infinite cities filled with infinite NPCs. We then worked to get a game working in such a world (some of the efforts of which, you may have read about in <a title="Kevin Bacon in Video Gaming" href="http://www.altdevblogaday.com/2012/04/22/kevin-bacon-in-video-gaming/" target="_blank">my last post</a>)</p>
<p>Now, just to confirm, this world wasn&#8217;t being randomly generated. It was both infinite AND persistent. Without going into too much detail, this is achieved by making the world dynamically affected by the passing of time. Every part of the world is identified as either affected by time or timeless. The lay of the land with its hills and caverns&#8230; That&#8217;s all timeless, and never changes. Because those parts never change and cannot be affected by the player, they only need to be loaded into memory when the player can see them (or if they are needed to generate quest information, etc). However, if an object is affected by time (for example, the contents of a chest), then they have a time coefficient applied to the procedural algorithm that generates them. This means that a chest in a dungeon, for example, will have different items in it depending on WHEN the player opens the chest. If the player was the clear out that chest, that act is stored in a database of player changes, but then re-set when a certain amount of time has passed. This ensures that the database of player changes to the world never exceeds a certain size (which is estimated to be around 250mb at the very most, but more realistically around 50mb)</p>
<p>This generation accounts for almost everything in the game. Spell creation, item creation, weapon creation, potion creation, NPC dialogue system, even the spell effects that happen on the screen. Due to this, the world that the player explores will be ever-changing and infinite. They won&#8217;t keep finding the same old weapons or items, there will be no end to the number of spells they can find or use, they won&#8217;t even keep having the same conversations with NPCs. This is necessary to keep a player interested for long enough in an infinite world.</p>
<p>&nbsp;</p>
<h1>Public Acceptance</h1>
<p>Back when the game <a title="Elite (Video Game)" href="http://en.wikipedia.org/wiki/Elite_%28video_game%29" target="_blank">Elite</a> was first being worked on, it was planned to have around 282 <em>trillion</em> galaxies with around 256 star systems in each one, but their publisher, Firebird, were worried that such a large in-game universe would be intimidating to players and put them off. I have to say I had wondered at that, and was interested to see how the public would react to an even bigger in-game world.</p>
<p>I was surprised at the results.</p>
<p>We&#8217;ve been quite public with our development process for the game so far and generated a small cult following on communities such as <a title="IndieDB" href="http://www.indiedb.com/games/malevolence-the-sword-of-ahkranox" target="_blank">IndieDB</a>, but very few people seem to quite grasp the scale of an infinite world, despite our thorough descriptions of it. We had put up renders of the world generation data, showing just a tiny fraction of the world:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Ahk1.jpg"><img class="aligncenter size-medium wp-image-25802" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Ahk1-300x168.jpg" alt="" width="300" height="168" /></a></p>
<p>And then, we showed them this:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Ahk2.jpg"><img class="aligncenter size-medium wp-image-25803" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Ahk2-300x168.jpg" alt="" width="300" height="168" /></a></p>
<p>That inland sea is around the size of the entire in-game world of <a title="Skyrim (Video Game)" href="http://en.wikipedia.org/wiki/Skyrim" target="_blank">Skyrim</a>. Funnily enough, the largest response we got from this information was disbelief. Many called us liars and that it simply wasn&#8217;t possible. Others began to believe that the world size of Malevolence was the entire above image, rather than infinite. Only about 20% of people really <em>understood</em>.</p>
<p>So, from a marketing perspective, it&#8217;s been a bit of a nightmare to have an infinite world. We&#8217;ve even had many suggest that Malevolence is just a rip-off of <a title="Legend of Grimrock" href="http://en.wikipedia.org/wiki/Legend_Of_Grimrock" target="_blank">Legend of Grimrock</a>, despite the fact that Malevolence was started about a year before. But that&#8217;s always going to happen, no matter what the game. What happens upon release will happen, and that&#8217;s just how the cookie crumbles with game development. Funnily enough, that hasn&#8217;t been the hardest bit. The hardest bit has been the math involved in making a world like this one.</p>
<p>&nbsp;</p>
<h1>The Math</h1>
<p>Being infinite, procedural AND persistent, most of the mathematics behind Malevolence is theoretical math &#8211; that is, mathematics with few or no fixed/known values acting in a volatile space. But we&#8217;ve broken the world creation down into multiple layers.</p>
<p>The first layer is the one you saw above. A large world segment is generated which covers an area of about 400x400km. This is the only layer of the game that uses a standardised procedural generation system (<a title="Perlin Noise" href="http://en.wikipedia.org/wiki/Perlin_noise" target="_blank">perlin noise</a>)</p>
<p>That is then broken down into chunks that are around 3x3km, calculating the biome information within that area, like so:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Steps.jpg"><img class="aligncenter size-large wp-image-25804" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Steps-640x1024.jpg" alt="" width="640" height="1024" /></a>In the end, all of these steps need to be completed when each new world segment is generated in order to turn the raw data into this:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Day1.jpg"><img class="aligncenter size-medium wp-image-25805" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Day1-300x225.jpg" alt="" width="300" height="225" /></a></p>
<p>That is just for the overworld. Every world segment that is VISIBLE to the player (as in the view above) is given a unique code, generated by the procedural algorithm. If there is a dungeon entrance in that segment, the dungeon is generated using this unique code, ensuring that every time the player returns to that spot, the same dungeon will be there:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/SlimUI.jpg"><img class="aligncenter size-medium wp-image-25806" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/SlimUI-300x187.jpg" alt="" width="300" height="187" /></a></p>
<p>This same method is used for town generation, graveyards, ruins or anything else that the player may encounter. And this goes on forever. If a player was to turn off collision and hold down the &#8216;move forward&#8217; button, it would take them just under three weeks to walk from one end of a world segment to another, and then they would simply move to a new world segment seamlessly, and then another, forever.</p>
<p>The biggest question we have been given is how we have dealt with the data type limitations on player co-ordinates, but unfortunately we can&#8217;t give away <em>all</em> our secrets :) But I can tell you that Malevolence doesn&#8217;t suffer from the <a title="End of the Minecraft World" href="http://victoryroad.net/picture.php?albumid=419&amp;pictureid=5097" target="_blank">Minecraft world-edge issue</a>, it just keeps going on and on.</p>
<p>&nbsp;</p>
<h1>Conclusion</h1>
<p>Using procedural generation in your game can be a rewarding experience, but definitely don&#8217;t rush into it. It takes good planning, clever usage and most of all it needs to feel seamless, otherwise the public simply won&#8217;t accept it.</p>
<p>If you&#8217;d like to read more about Malevolence: The Sword of Ahkranox, you can check out these links:</p>
<p align="center"><a href="http://www.indiedb.com/games/malevolence-the-sword-of-ahkranox"><img src="http://4.bp.blogspot.com/-Ulb9kGFvlv0/TzjyMd3ETHI/AAAAAAAAAao/8O-GL3ljdns/s1600/IndieDB.jpg" alt="" /></a><a href="http://www.facebook.com/MalevolenceGame"><img src="http://1.bp.blogspot.com/-VUt7G6DPzEs/TzjxS58SKwI/AAAAAAAAAaI/4s9kMUY1NsM/s1600/FaceBook.jpg" alt="" /></a><a href="http://www.reddit.com/r/gaming/comments/oyyba/an_infinite_rpg_for_fans_of_oldschool_gaming/"><img src="http://3.bp.blogspot.com/-zckP8A7-3ws/TzjxURV-28I/AAAAAAAAAaQ/_Opx0Ix-wAM/s1600/Reddit.jpg" alt="" /></a><a href="https://twitter.com/#%21/SwordOfAhkranox"><img src="http://1.bp.blogspot.com/-UUsUaWzAS78/TzjxV6VP7aI/AAAAAAAAAaU/HBM9dTS2pbE/s1600/Twitter.jpg" alt="" /></a><a href="http://www.youtube.com/CumQuaT1337"><img src="http://1.bp.blogspot.com/-x09hO-6hocc/TzjxXcjLX-I/AAAAAAAAAag/Cb0lKh8U-G0/s1600/YouTube.jpg" alt="" /></a><a href="http://swordofahkranox.blogspot.com.au/"><img src="http://4.bp.blogspot.com/-vviQPjyUmqs/TzjxSNsd0-I/AAAAAAAAAaA/312rfgGttX0/s1600/BlogSpot.jpg" alt="" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/27/the-difficulties-of-an-infinite-video-game-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Functional Programming in C++</title>
		<link>http://www.altdevblogaday.com/2012/04/26/functional-programming-in-c/</link>
		<comments>http://www.altdevblogaday.com/2012/04/26/functional-programming-in-c/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 22:13:37 +0000</pubDate>
		<dc:creator>John-Carmack</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25786</guid>
		<description><![CDATA[<p class="MsoNormal">Probably everyone reading this has heard “functional programming” put forth as something that is supposed to bring benefits to software development, or even heard it touted as a silver bullet.  However, a trip to <a href="http://en.wikipedia.org/wiki/Functional_programming">Wikipedia</a> for some more information can be initially off-putting, with early references to <a href="http://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a> and <a href="http://en.wikipedia.org/wiki/Formal_system">formal systems</a>.  It isn’t immediately clear what that has to do with writing better software.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/26/functional-programming-in-c/" class="more-link">Read more on Functional Programming in C++&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal">Probably everyone reading this has heard “functional programming” put forth as something that is supposed to bring benefits to software development, or even heard it touted as a silver bullet.  However, a trip to <a href="http://en.wikipedia.org/wiki/Functional_programming">Wikipedia</a> for some more information can be initially off-putting, with early references to <a href="http://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a> and <a href="http://en.wikipedia.org/wiki/Formal_system">formal systems</a>.  It isn’t immediately clear what that has to do with writing better software.</p>
<p class="MsoNormal">My pragmatic summary:  A large fraction of the flaws in software development are due to programmers not fully understanding all the possible states their code may execute in.  In a multithreaded environment, the lack of understanding and the resulting problems are greatly amplified, almost to the point of panic if you are paying attention.  Programming in a functional style makes the state presented to your code explicit, which makes it much easier to reason about, and, in a completely pure system, makes thread race conditions impossible.</p>
<p class="MsoNormal">I do believe that there is real value in pursuing functional programming, but it would be irresponsible to exhort everyone to abandon their C++ compilers and start coding in <a href="http://en.wikipedia.org/wiki/Lisp_%28programming_language%29">Lisp</a>, <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29">Haskell</a>, or, to be blunt, any other fringe language.  To the eternal chagrin of language designers, there are plenty of externalities that can overwhelm the benefits of a language, and game development has more than most fields.  We have cross platform issues, proprietary tool chains, certification gates, licensed technologies, and stringent performance requirements on top of the issues with legacy codebases and workforce availability that everyone faces.</p>
<p class="MsoNormal">If you are in circumstances where you can undertake significant development work in a non-mainstream language, I’ll cheer you on, but be prepared to take some hits in the name of progress.  For everyone else: <em><strong>No matter what language you work in,</strong> <strong>programming in a functional style provides benefits.  You should do it whenever it is convenient, and you should think hard about the decision when it isn’t convenient</strong>.</em>  You can learn about lambdas, monads, currying, composing lazily evaluated functions on infinite sets, and all the other aspects of explicitly functionally oriented languages later if you choose.</p>
<p class="MsoNormal">C++ doesn’t encourage functional programming, but it doesn’t prevent you from doing it, and you retain the power to drop down and apply SIMD intrinsics to hand laid out data backed by memory mapped files, or whatever other nitty-gritty goodness you find the need for.</p>
<p>&nbsp;</p>
<p class="MsoNormal"><span style="font-size: 18pt">Pure Functions</span></p>
<p class="MsoNormal">A pure function only looks at the parameters passed in to it, and all it does is return one or more computed values based on the parameters.  It has no logical <em>side effects.  </em>This is an abstraction of course; every function has side effects at the CPU level, and most at the heap level, but the abstraction is still valuable.</p>
<p class="MsoNormal">It doesn’t look at or update global state.  it doesn’t maintain internal state.  It doesn’t perform any IO.  it doesn’t mutate any of the input parameters.  Ideally, it isn’t passed any extraneous data – getting an <span style="font-family: 'Courier New'">allMyGlobals</span> pointer passed in defeats much of the purpose.</p>
<p class="MsoNormal">Pure functions have a lot of nice properties.</p>
<p class="MsoNormal">Thread safety.  A pure function with value parameters is completely thread safe.  With reference or pointer parameters, even if they are const, you do need to be aware of the danger that another thread doing non-pure operations might mutate or free the data, but it is still one of the most powerful tools for writing safe multithreaded code.</p>
<p class="MsoNormal">You can trivially switch them out for <a href="http://altdevblogaday.com/2011/11/22/parallel-implementations">parallel implementations</a>, or run multiple implementations to compare the results.  This makes it much safer to experiment and evolve.</p>
<p class="MsoNormal">Reusability.  It is much easier to transplant a pure function to a new environment.  You still need to deal with type definitions and any called pure functions, but there is no snowball effect.  How many times have you known there was some code that does what you need in another system, but extricating it from all of its environmental assumptions was more work than just writing it over?</p>
<p class="MsoNormal">Testability.  A pure function has <em>referential transparency</em>, which means that it will always give the same result for a set of parameters no matter when it is called, which makes it much easier to exercise than something interwoven with other systems.   I have never been very responsible about writing test code;  a lot of code interacts with enough systems that it can require elaborate harnesses to exercise, and I could often convince myself (probably incorrectly) that it wasn’t worth the effort.  Pure functions are trivial to test; the tests look like something right out of a textbook, where you build some inputs and look at the output.  Whenever I come across a finicky looking bit of code now, I split it out into a separate pure function and write tests for it.  Frighteningly, I often find something wrong in these cases, which means I’m probably not casting a wide enough net.</p>
<p class="MsoNormal">Understandability and maintainability.  The bounding of both input and output makes pure functions easier to re-learn when needed, and there are less places for undocumented requirements regarding external state to hide.</p>
<p class="MsoNormal">Formal systems and automated reasoning about software will be increasingly important in the future.  <a href="http://altdevblogaday.com/2011/12/24/static-code-analysis/">Static code analysis</a> is important today, and transforming your code into a more functional style aids analysis tools, or at least lets the faster local tools cover the same ground as the slower and more expensive global tools.  We are a “Get ‘er done” sort of industry, and I do not see formal proofs of whole program “correctness” becoming a relevant goal, but being able to prove that certain classes of flaws are not present in certain parts of a codebase will still be very valuable.  We could use some more science and math in our process.</p>
<p class="MsoNormal">Someone taking an introductory programming class might be scratching their head and thinking “aren’t all programs supposed to be written like this?”  The reality is that far more programs are <a href="http://en.wikipedia.org/wiki/Big_ball_of_mud">Big Balls of Mud</a> than not.  Traditional imperative programming languages give you escape hatches, and they get used all the time.  If you are just writing throwaway code, do whatever is most convenient, which often involves global state.  If you are writing code that may still be in use a year later, balance the convenience factor against the difficulties you will inevitably suffer later.  Most developers are not very good at predicting the future time integrated suffering their changes will result in.</p>
<p>&nbsp;</p>
<p class="MsoNormal"><span style="font-size: 18pt">Purity In Practice</span></p>
<p class="MsoNormal">Not everything can be pure; unless the program is only operating on its own source code, at some point you need to interact with the outside world.  It can be fun in a puzzly sort of way to try to push purity to great lengths, but the pragmatic break point acknowledges that side effects are necessary at some point, and manages them effectively.</p>
<p class="MsoNormal">It doesn’t even have to be all-or-nothing in a particular function.  There is a continuum of value in how pure a function is, and the value step from almost-pure to completely-pure is smaller than that from spaghetti-state to mostly-pure.  Moving a function towards purity improves the code, even if it doesn’t reach full purity.  A function that bumps a global counter or checks a global debug flag is not pure, but if that is its only detraction, it is still going to reap most of the benefits.</p>
<p class="MsoNormal">Avoiding the worst in a broader context is generally more important than achieving perfection in limited cases.  If you consider the most toxic functions or systems you have had to deal with, the ones that you know have to be handled with tongs and a face shield, it is an almost sure bet that they have a complex web of state and assumptions that their behavior relies on, and it isn’t confined to their parameters.  Imposing some discipline in these areas, or at least fighting to prevent more code from turning into similar messes, is going to have more impact than tightening up some low level math functions.</p>
<p class="MsoNormal">The process of refactoring towards purity generally involves disentangling computation from the environment it operates in, which almost invariably means more parameter passing.  This seems a bit curious – greater verbosity in programming languages is broadly reviled, and functional programming is often associated with code size reduction.  The factors that allow programs in functional languages to sometimes be more concise than imperative implementations are pretty much orthogonal to the use of pure functions &#8212; garbage collection, powerful built in types, pattern matching, list comprehensions, function composition, various bits of syntactic sugar, etc.  For the most part, these size reducers don’t have much to do with being functional, and can also be found in some imperative languages.</p>
<p class="MsoNormal">You <em>should</em> be getting irritated if you have to pass a dozen parameters into a function; you may be able to refactor the code in a manner that reduces the parameter complexity.</p>
<p class="MsoNormal">The lack of any language support in C++ for maintaining purity is not ideal.  If someone modifies a widely used foundation function to be non-pure in some evil way, everything that uses the function also loses its purity.  This sounds disastrous from a formal systems point of view, but again, it isn’t an all-or-nothing proposition where you fall from grace with the first sin.  Large scale software development is unfortunately statistical.</p>
<p class="MsoNormal">It seems like there is a sound case for a pure keyword in future C/C++ standards.  There are close parallels with const – an optional qualifier that allows compile time checking of programmer intention and will never hurt, and could often help, code generation.  The D programming language does offer a pure keyword:  <a href="http://www.d-programming-language.org/function.html">http://www.d-programming-language.org/function.html</a>  Note their distinction between weak and strong purity – you need to also have const input references and pointers to be strongly pure.</p>
<p class="MsoNormal">In some ways, a language keyword is over-restrictive &#8212; a function can still be pure even if it calls impure functions, as long as the side effects don’t escape the outer function.  Entire programs can be considered pure functional units if they only deal with command line parameters instead of random file system state.</p>
<p class="MsoNormal"><span style="font-size: 18pt">Object Oriented Programming</span></p>
<p class="MsoNormal"><em><a href="https://twitter.com/#%21/mfeathers"><strong><span style="font-family: 'Calibri','sans-serif';color: blue">Michael Feathers</span></strong> <span class="username"><s><span style="color: blue">@</span></s></span><span class="username"><strong><span style="color: blue">mfeathers</span></strong></span> </a>  OO makes code understandable by encapsulating moving parts. FP makes code understandable by minimizing moving parts.</em></p>
<p class="MsoNormal">The “moving parts” are mutating states.  Telling an object to change itself is lesson one in a basic object oriented programming book, and it is deeply ingrained in most programmers, but it is anti-functional behavior.  Clearly there is some value in the basic OOP idea of grouping functions with the data structures they operate on, but if you want to reap the benefits of functional programming in parts of your code, you have to back away from some object oriented behaviors in those areas.</p>
<p class="MsoNormal">Class methods that can’t be const are not pure by definition, because they mutate some or all of the potentially large set of state in the object.  They are not thread safe, and the ability to incrementally poke and prod objects into unexpected states is indeed a significant source of bugs.</p>
<p class="MsoNormal">Const object methods can still be technically pure if you don’t count the implicit <em>const this</em> pointer against them, but many object are large enough to constitute a sort of global state all their own, blunting some of the clarity benefits of pure functions.  Constructors can be pure functions, and generally should strive to be – they take arguments and return an object.</p>
<p class="MsoNormal">At the tactical programming level, you can often work with objects in a more functional manner, but it may require changing the interfaces a bit.  At id we went over a decade with an idVec3 class that had a self-mutating <span style="font-family: 'Courier New'">void Normalize() </span>method, but no corresponding <span style="font-family: 'Courier New'">idVec3 Normalized() const</span> method.  Many string methods were similarly defined as working on themselves, rather than returning a new copy with the operation performed on it – <span style="font-family: 'Courier New'">ToLowerCase(), StripFileExtension(),</span> etc.</p>
<p class="MsoNormal"><span style="font-size: 18pt">Performance Implications</span></p>
<p class="MsoNormal">In almost all cases, directly mutating blocks of memory is the speed-of-light optimal case, and avoiding this is spending some performance.  Most of the time this is of only theoretical interest; we trade performance for productivity all the time.</p>
<p class="MsoNormal">Programming with pure functions will involve more copying of data, and in some cases this clearly makes it the incorrect implementation strategy due to performance considerations.  As an extreme example, you can write a pure <span style="font-family: 'Courier New'">DrawTriangle()</span> function that takes a framebuffer as a parameter and returns a completely new framebuffer with the triangle drawn into it as a result.  Don’t do that.</p>
<p class="MsoNormal">Returning everything by value is the natural functional programming style, but relying on compilers to always perform <a href="http://en.wikipedia.org/wiki/Return_value_optimization">return value optimization</a> can be hazardous to performance, so passing reference parameter for output of complex data structures is often justifiable, but it has the unfortunate effect of preventing you from declaring the returned value as const to enforce <a href="http://en.wikipedia.org/wiki/Single_assignment#Single_assignment">single assignment</a>.</p>
<p class="MsoNormal">There will be a strong urge in many cases to just update a value in a complex structure passed in rather than making a copy of it and returning the modified version, but doing so throws away the thread safety guarantee and should not be done lightly.  List generation is often a case where it is justified.  The pure functional way to append something to a list is to return a completely new copy of the list with the new element at the end, leaving the original list unchanged.  Actual functional languages are implemented in ways that make this not as disastrous as it sounds, but if you do this with typical C++ containers you will die.</p>
<p class="MsoNormal">A significant mitigating factor is that performance today means parallel programming, which usually requires more copying and combining than in a single threaded environment even in the optimal performance case, so the penalty is smaller, while the complexity reduction and correctness benefits are correspondingly larger.  When you start thinking about running, say, all the characters in a game world in parallel, it starts sinking in that the object oriented approach of updating objects has some deep difficulties in parallel environments.  Maybe if all of the object just referenced a read only version of the world state, and we copied over the updated version at the end of the frame…  Hey, wait a minute…</p>
<p>&nbsp;</p>
<p class="MsoNormal"><span style="font-size: 18pt">Action Items</span></p>
<p class="MsoNormal">Survey some non-trivial functions in your codebase and track down every bit of external state they can reach, and all possible modifications they can make.  This makes great documentation to stick in a comment block, even if you don’t do anything with it.  If the function can trigger, say, a screen update through your render system, you can just throw your hands up in the air and declare the set of all effects beyond human understanding.</p>
<p class="MsoNormal">The next task you undertake, try from the beginning to think about it in terms of the real computation that is going on.  Gather up your input, pass it to a pure function, then take the results and do something with it.</p>
<p class="MsoNormal">As you are debugging code, make yourself more aware of the part mutating state and hidden parameters play in obscuring what is going on.</p>
<p class="MsoNormal">Modify some of your utility object code to return new copies instead of self-mutating, and try throwing const in front of practically every non-iterator variable you use.</p>
<p>&nbsp;</p>
<p class="MsoNormal">Additional references:</p>
<p><a href="http://www.haskell.org/haskellwiki/Introduction">http://www.haskell.org/haskellwiki/Introduction</a></p>
<p><a href="http://lisperati.com/">http://lisperati.com/</a></p>
<p><a href="http://www.johndcook.com/blog/tag/functional-programming/">http://www.johndcook.com/blog/tag/functional-programming/</a></p>
<p><a href="http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf">http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf</a></p>
<p><a href="http://channel9.msdn.com/Shows/Going+Deep/Lecture-Series-Erik-Meijer-Functional-Programming-Fundamentals-Chapter-1">http://channel9.msdn.com/Shows/Going+Deep/Lecture-Series-Erik-Meijer-Functional-Programming-Fundamentals-Chapter-1</a></p>
<p><a href="http://www.cs.utah.edu/%7Ehal/docs/daume02yaht.pdf">http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf</a></p>
<p><a href="http://www.cs.cmu.edu/%7Ecrary/819-f09/Backus78.pdf">http://www.cs.cmu.edu/~crary/819-f09/Backus78.pdf</a></p>
<p><a href="http://fpcomplete.com/the-downfall-of-imperative-programming/">http://fpcomplete.com/the-downfall-of-imperative-programming/</a></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/26/functional-programming-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kevin Bacon in Video Gaming</title>
		<link>http://www.altdevblogaday.com/2012/04/22/kevin-bacon-in-video-gaming/</link>
		<comments>http://www.altdevblogaday.com/2012/04/22/kevin-bacon-in-video-gaming/#comments</comments>
		<pubDate>Sun, 22 Apr 2012 03:51:01 +0000</pubDate>
		<dc:creator>Alex Norton</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25662</guid>
		<description><![CDATA[<p><span style="color: #ff0000">UPDATE: This game has a campaign on KickStarter if you&#8217;re interested in helping out! Please check it out by clicking <a href="http://www.kickstarter.com/projects/malevolence/malevolence-the-infinite-rpg">here</a>.</span></p>
<p>&#160;</p>
<h1>The Premise</h1>
<p>My project team have the distinct honor of listing actor Kevin Bacon in the &#8216;Special Thanks&#8217; portion of our credits, but I doubt he has any idea that he&#8217;s in there. The fact is, he&#8217;s had a very large &#8211; albeit unknown &#8211; influence on the game&#8217;s development.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/22/kevin-bacon-in-video-gaming/" class="more-link">Read more on Kevin Bacon in Video Gaming&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000">UPDATE: This game has a campaign on KickStarter if you&#8217;re interested in helping out! Please check it out by clicking <a href="http://www.kickstarter.com/projects/malevolence/malevolence-the-infinite-rpg">here</a>.</span></p>
<p>&nbsp;</p>
<h1>The Premise</h1>
<p>My project team have the distinct honor of listing actor Kevin Bacon in the &#8216;Special Thanks&#8217; portion of our credits, but I doubt he has any idea that he&#8217;s in there. The fact is, he&#8217;s had a very large &#8211; albeit unknown &#8211; influence on the game&#8217;s development.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/TheManHimself.jpg"><img class="aligncenter  wp-image-25666" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/TheManHimself-300x276.jpg" alt="" width="221" height="204" /></a></p>
<p>The game is <a href="http://www.msoa-game.com/">Malevolence: The Sword of Ahkranox</a>, which I have been project lead on for over two years now, and its engine is quite different to most games due to the fact that the entire game world is procedurally generated, infinite and also persistent.</p>
<p>&nbsp;</p>
<h1>The Challenge</h1>
<p>Being infinite AND persistent, the team&#8217;s main challenge was to keep the game interesting so long as the player kept playing (not an easy task). We, of course, took the path of procedural item/weapon creation, even going so far as to make the game procedurally generate the graphics for the weapons, to ensure plenty of new gear to find. That, however, can only last for so long, and procedurally generated countryside, dungeons and towns can only entertain a player for so long before they all start to look the same. So we put our heads together and came up with a solution. We all agreed that would couldn&#8217;t keep the players interested infinitely, but we can take steps to ensure they get maximum enjoyment and re-playability out of the game while they do play it.</p>
<p>&nbsp;</p>
<h1>The Solution</h1>
<p>What we came up with in the end was the quest and dialog system, and the way they interacted. Both were to be procedurally generated and intricate enough to ensure long-time interest from the player. But how does Kevin Bacon get involved with this? The answer lies in his namesake header file:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/KevinBacon.jpg"><img class="aligncenter size-medium wp-image-25667" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/KevinBacon-300x127.jpg" alt="" width="300" height="127" /></a></p>
<p>Some readers will be familiar with the <a title="Six Degrees of Kevin Bacon" href="http://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon" target="_blank">Six Degrees of Kevin Bacon</a> game back in 1994. The basic concept was that you could take the name of anyone involved in the Hollywood film industry, whether they be an A-List actor or an isolated gaffer somewhere on an obscure film, and within no more than 6 steps, be able to link them to Kevin Bacon. For example, one of the voice cast in my game Malevolence, Karen Kahler, was in the short film &#8220;The Magician&#8221; with actress Jackie Zane, who was in the film &#8220;Burning Palms&#8221; with actor Nick Stahl who acted in the movie &#8220;My One and Only&#8221; with Kevin bacon. Thus, her &#8220;Bacon Index&#8221; is 3 (and through Karen, mine is 4!). Make sense?</p>
<p>Well, it&#8217;s that system (or a modification of it) which the NPCs in Malevolence work with.</p>
<p>&nbsp;</p>
<h1>So How Does it Do it?</h1>
<p>Let&#8217;s say that the player enters a town and talks to an NPC. The game determines that this NPC will have a quest for them, and so the game spreads its feelers out and works out what is relatively close to the town, and how far away each location is. Since the game world is generated procedurally, it does this process dynamically:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Locations.jpg"><img class="aligncenter size-medium wp-image-25668" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Locations-300x300.jpg" alt="" width="300" height="300" /></a></p>
<p>First the game procedurally generates the quest. The engine first selects what type of quest to generate and settles on an item centric quest. It then generates an item, and an incident and comes up with a backpack which was lost. Once this is done, the NPC tells the player that they need help recovering their backpack from a dungeon that they were exploring. Only the catch is, they fled the dungeon so quickly that they don&#8217;t remember where it was.</p>
<p>While this is happening, the engine consults the memory map shown above and looks at the area around the town for a few kilometers, then chooses a dungeon that is close enough to not be too far away, and far enough away that the player will have to search for it. However, once it has found a dungeon, it doesn&#8217;t let the player know where it is like most games. It is now the player&#8217;s mission to search for it.</p>
<p>&nbsp;</p>
<h1>Finding the Unfindable</h1>
<p>Now that you know that there is a dungeon out there somewhere with a backpack in it, you can ask around to get more info. The engine, however, is processing the dungeon&#8217;s &#8220;Kevin Bacon Index&#8221; in the background. The main difference, however, is that not everyone knows everyone else perfectly well, so if one person gives you information, they may not be 100% sure about the information. So when you get a map of people like this:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/NPCs.jpg"><img class="aligncenter size-medium wp-image-25669" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/NPCs-300x300.jpg" alt="" width="300" height="300" /></a></p>
<p>You can see the percentages between them all. That shows the familiarity of the characters between them. So, if you speak to NPC &#8216;A&#8217; and ask them about nearby dungeons, they will tell you that they have no idea about that sort of thing, but their friends Steve and Kyle might. If you speak to Steve, he may refer you to Kyle or pass you on to Bob the Blacksmith, who he&#8217;s fairly sure knows a mapmaker and a woodsman, who would probably have a better idea about dungeons in the area. When you speak to Bob the Blacksmith, he&#8217;ll tell you about Keith the Woodsman, who is familiar with the local wilderness, but will more likely put you on to Kevin the Mapmaker, who knows Keith the Woodsman quite well and may be able to help you himself (with his maps). These NPCs may all be in the same town, or they may be spread between multiple towns. It&#8217;s all generated by the procedural engine, but it&#8217;s how the player FOLLOWS the path that defines how well the quest will work out.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/NPCsSolved.jpg"><img class="aligncenter size-medium wp-image-25670" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/NPCsSolved-300x300.jpg" alt="" width="300" height="300" /></a></p>
<p>If a player is clever and good at deduction, they may have an easy time of it &#8211; for example, if they followed the path ABDEF, while it may not be the most direct route to Keith, they will get some accurate maps out of it, and maybe even a new weapon to help clear out the dungeon to find the backpack. But if they don&#8217;t follow good advice, they may have a far less fortuitous way. And keep in mind that due to the lack of familiarity between certain NPCs, sometimes the player will get false information in their searching, which can slow them down quite a bit.</p>
<p>&nbsp;</p>
<h1>That&#8217;s Very Long Winded</h1>
<p>Very true, but not all quests in the game will work like this. The quests are divided into two quest types. There are the multi-tiered quests, as mentioned above, and &#8220;b*tch quests&#8221; which are your standard &#8220;there&#8217;s a dungeon, clean it out&#8221; or &#8220;there are rats in my basement, kill them&#8221;. On top of that, even when a player is assigned a multi-tiered quest, sometimes they will have 3 steps to complete, sometimes they will have 20, it all depends on how the cookie crumbles in the procedural generation.</p>
<p>&nbsp;</p>
<h1>Conclusion</h1>
<p>Making a game which is infinite AND persistent has provided countless challenges to us as a dev team, but the solutions to intricate problems are often the most unique. I hope you enjoyed reading about this little section of our game, and if you ever end up playing it and you see Kevin Bacon in the credits, you&#8217;ll now know why.</p>
<p style="text-align: center">
<object width="560" height="315">
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="movie" value="http://www.youtube.com/v/5U7wqQPvXHs&autoplay=0&loop=0&rel=0" />
<param name="wmode" value="transparent">
<embed src="http://www.youtube.com/v/5U7wqQPvXHs&autoplay=0&loop=0&rel=0" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" allowscriptaccess="always" width="560" height="315">
</embed>
</object>

</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/22/kevin-bacon-in-video-gaming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inheriting Velocity in Ragdolls</title>
		<link>http://www.altdevblogaday.com/2012/04/20/inheriting-velocity-in-ragdolls/</link>
		<comments>http://www.altdevblogaday.com/2012/04/20/inheriting-velocity-in-ragdolls/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 21:29:39 +0000</pubDate>
		<dc:creator>Niklas Frykholm</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[ragdolls]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25654</guid>
		<description><![CDATA[<p>After a slew of abstract articles about C++ and code structuring I&#8217;d like to get back to some more meaty game engine stuff. So today I&#8217;ll talk about ragdolls. In particular, how to preserve the momentum of animated objects, so that when you switch over to the ragdoll it continues to stumble forward in the same direction that the animation was moving, before crashing to a gruesome death.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/20/inheriting-velocity-in-ragdolls/" class="more-link">Read more on Inheriting Velocity in Ragdolls&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>After a slew of abstract articles about C++ and code structuring I&#8217;d like to get back to some more meaty game engine stuff. So today I&#8217;ll talk about ragdolls. In particular, how to preserve the momentum of animated objects, so that when you switch over to the ragdoll it continues to stumble forward in the same direction that the animation was moving, before crashing to a gruesome death.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/ragdoll_velocities_1.jpg"><img src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/ragdoll_velocities_1.jpg" alt="" width="500" height="182" class="aligncenter size-full wp-image-25655" /></a></p>
<p>So this is a small, but important problem. We want to somehow get the velocities of the animated objects and then apply them to the bodies in the ragdoll. The only snag is that animated objects typically don&#8217;t know anything about velocities. Also, we need some way of matching up the physics bodies with the animated objects.</p>
<p>First, some background information. In the Bitsquid engine, physics, scene graph and animation are completely separate systems. We strongly believe in minimizing the couplings between different systems since that makes the engine easier to understand, reason about, modify, optimize and rewrite.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/ragdoll_velocities_2.jpg"><img src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/ragdoll_velocities_2.jpg" alt="" width="498" height="236" class="aligncenter size-full wp-image-25656" /></a></p>
<ul>
<li>
<p>The physics system simulates a number of bodies, possibly connected by joints.</p>
</li>
<li>
<p>The scene graph handles local-to-world transforms for a collection of nodes in a hierarchy.</p>
</li>
<li>
<p>The animation system evaluates and blends animation curves for bones.</p>
</li>
</ul>
<p>Bones and bodies hold references (just integer indices, really) to nodes in the scene graph and this how the systems communicate. After the animation has been evaluated, the resulting local transforms are written to the bones&#8217; nodes in the scene graph.</p>
<p>For keyframed physics (animated hit bodies), the animation drives the physics, which means the physics&#8217; bodies will read their world transforms from the corresponding nodes in the scene graph. For ragdolled physics, the world transforms of the bodies are written to the scene graph after the simulation has completed.</p>
<p>For partial ragdolls (such as a non-functioning, but still attached limb) or powered ragdolls (ragdolls driven by motors to achieve animation poses) it gets a little more involved (perhaps a topic for a future post), but the basic setup is the same.</p>
<p>Given this setup there are two ways of calculating the animation velocities:</p>
<ul>
<li>
<p>We can calculate the velocities directly by differentiating the animation curves.</p>
</li>
<li>
<p>We can record a node&#8217;s transform at two different time steps and compute the velocity from the difference.</p>
</li>
</ul>
<p>The first approach is doable, but not very practical. Not only do we have to differentiate all the animation curves, we must also take into account how those velocities are affected by the blend tree and local-to-world transforms. And even if we do all that, we still don&#8217;t account for movements from other sources than animation, such as scripted movements, IK or interactions with the character controller.</p>
<p>The second option is the more reasonable one. Now all we need is a way of obtaining the transforms from two different time steps. There are a number of possible options:</p>
<ul>
<li>
<p>We could add an array of Matrix4x4:s to our scene graph&#8217;s <em>last_world</em> where we store the last world transform of every object. So whenever we want to go to ragdoll we always have a <em>last_world</em> transform to calculate velocities from.</p>
</li>
<li>
<p>We could simulate the character backwards in time when we want to go to ragdoll and obtain a <em>last_world</em> transform that way.</p>
</li>
<li>
<p>We could delay the transition to ragdoll one frame, so that we have enough time to gather two world transforms for computing the velocity.</p>
</li>
</ul>
<p>The first approach is conceptually simple, but costly. We are increasing the size of all our scene graphs by about 50 % (previously they contained <em>local</em> and <em>world</em> transforms, now they will also need <em>last_world</em>). In addition we must <em>memcpy(last_world, world)</em> before we compute new world transforms. That&#8217;s a significant cost to pay all the time for something that happens very seldom (transition to ragdoll).</p>
<p>The second appraoch sounds a bit crazy, but some games actually already have this functionality. Servers in competetive multi-player fps games often need to rewind players in time in order to accurately determine if they were able to hit each other. Still, I find the approach to be a bit too complicated and invovled just to get a velocity.</p>
<p>The third aproach seems simple and cheap, but it violates one of our Bitsquid principles: <em>Thou Shalt Not Have Any Frame Delays</em>. Delaying something a frame can be a quick fix to many hairy problems, but it puts your game in a very weird transitional state where it at the same time both is and isn&#8217;t (yet) something. The character isn&#8217;t <em>really</em> a ragdoll yet, but it will be the next frame, whether I want to or not.</p>
<p>This new slightly self-contradictory state invites a host of bugs and before you know it, little logic pieces will start to seep into the code base <em>&#8220;do this</em> unless <em>you are in the special transition-to-ragdoll state&#8221;</em>. Congratulations, you have just made your codebase a lot more complicated and bug prone.</p>
<p>If this is not enough, consider the poor sucker who just wants to write a routine that does A, B, C and D, when A, B and C requires frame delays. Suddenly what was supposed to be simple function got turned into a state machine that needs to run for four frames to produce it result.</p>
<p>The simple rule that actions should take place immediately protects against such insanity.</p>
<p>So three options, none of them especially palpable.</p>
<p>I actually went with the first one, to always compute and store <em>last_world</em> in the scene graph, but with a flag so that this is only used for units that actually need it (characters that can go to ragdoll). When there is no clear winner, I always pick the simplest solution, because it is a lot easier to optimize later if the need should arise. (We could for example track <em>last_world</em> only for the nodes which have a corresponding ragdoll actor. Also we could store <em>last_world</em> as <em>(p,q)</em> instead of as a matrix.)</p>
<p>For completion, given the two transforms, the code for compting the velocities will look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Vector3 p0 = translation(tm_0);
Vector3 p1 = translation(tm_1);
Vector3 velocity = (p1 - p0) / dt
&nbsp;
Quaternion q0 = rotation(tm_0);
Quaternion q1 = rotation(tm_1);
Quaternion q = q1 * inverse(q0);
AxisAngle aa = q.decompose();
Vector3 angular_velocity = aa.axis * aa.angle / dt;</pre></div></div>

<p>This has also been posted to <a class="link" href="http://bitsquid.blogspot.com">The Bitsquid Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/20/inheriting-velocity-in-ragdolls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exceptional Floating Point</title>
		<link>http://www.altdevblogaday.com/2012/04/20/exceptional-floating-point/</link>
		<comments>http://www.altdevblogaday.com/2012/04/20/exceptional-floating-point/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 18:10:07 +0000</pubDate>
		<dc:creator>Bruce-Dawson</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[divide by zero]]></category>
		<category><![CDATA[double]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[float]]></category>
		<category><![CDATA[floating point]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25527</guid>
		<description><![CDATA[<p>Floating-point math has an answer for everything, but sometimes that’s not what you want. Sometimes instead of getting an answer to the question sqrt(-1.0) (it’s NaN) it’s better to know that your software is asking imaginary questions.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/20/exceptional-floating-point/" class="more-link">Read more on Exceptional Floating Point&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Floating-point math has an answer for everything, but sometimes that’s not what you want. Sometimes instead of getting an answer to the question sqrt(-1.0) (it’s NaN) it’s better to know that your software is asking imaginary questions.</p>
<p>The IEEE standard for floating-point math defines five exceptions that shall be signaled when certain conditions are detected. Normally the flags for these exceptions are raised (set), a default result is delivered, and execution continues. This default behavior is often desirable, especially in a shipping game, but during development it can be useful to halt when an exception is signaled.</p>
<p>Halting on exceptions can be like adding an assert to every floating-point operation in your program, and can therefore be a great way to improve code reliability, and find mysterious behavior at its root cause.</p>
<p><span id="more-25527"></span>
<p>This article is part of a series on floating-point. The complete list of articles in the series is:</p>
<ul>
<ul>
<li>1: <a href="http://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/">Tricks With the Floating-Point Format</a> – an overview of the float format</li>
<li>2: <a href="http://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/">Stupid Float Tricks</a> – incrementing the integer representation of floats</li>
<li>3: <a href="http://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/">Don’t Store That in a Float</a> – a cautionary tale about time</li>
<li>3b: <a href="http://randomascii.wordpress.com/2012/02/11/they-sure-look-equal/">They sure look equal…</a> – special bonus post (not on altdevblogaday)</li>
<li>4: <a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/">Comparing Floating Point Numbers, 2012 Edition</a> – tricky but important</li>
<li>5: <a href="http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/">Float Precision—From Zero to 100+ Digits</a> – what does precision mean, really?</li>
<li>5b: <a href="http://randomascii.wordpress.com/2012/03/11/c-11-stdasync-for-fast-float-format-finding/">C++ 11 std::async for Fast Float Format Finding</a> – special bonus post (not on altdevblogaday)</li>
<li>6: <a href="http://randomascii.wordpress.com/2012/03/21/intermediate-floating-point-precision/">Intermediate Precision</a> – their effect on performance and results</li>
<li>7.0000001: <a href="http://randomascii.wordpress.com/2012/04/05/floating-point-complexities/">Floating-Point Complexities</a> – a lightning tour of all that is weird about floating point</li>
<li>8: Exception Floating point – (return *this;)</li>
</ul>
</ul>
<h2>Let’s get it started again</h2>
<p>The five exceptions mandated by the IEEE floating-point standard are:</p>
<ol>
<li>Invalid operation: this is signaled if there is no usefully definable result, such as zero divided by zero, infinity minus infinity, or sqrt(-1). The default result is a NaN (Not a Number) </li>
<li>Division by zero: this is signaled when dividing a non-zero number by zero. The result is a correctly signed infinity. </li>
<li>Overflow: this is signaled when the rounded result won’t fit. The default result is a correctly signed infinity. </li>
<li>Underflow: this is signaled when the result is non-zero and between -FLT_MIN and FLT_MIN. The default result is the rounded result. </li>
<li>Inexact: this is signaled any time the result of an operation is not exact. The default result is the rounded result. </li>
</ol>
<p>The underflow exception is usually not of interest to game developers – it happens rarely, and usually doesn’t detect anything of interest. The inexact result is also usually not of interest to game developers – it happens frequently (although not always, and it can be useful to understand what operations are exact) and usually doesn’t detect anything of interest.</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/image1.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;float: right;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" align="right" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/image_thumb1.png" width="138" height="35" /></a>That leaves invalid operation, division by zero, and overflow. In the context of game development these are usually truly exceptional. They are rarely done intentionally, so they usually indicate a bug. In many cases these bugs are benign, but occasionally these bugs indicate real problems. From now one I’ll refer to these first three exceptions as being the ‘bad’ exceptions and assume that game developers would like to avoid them, if only so that the exceptions can be enabled without causing crashes during normal game play.</p>
<h2>When can divide by zero be useful?</h2>
<p>While the ‘bad’ exceptions typically represent invalid operations in the context of games, this is not necessarily true in all contexts. The default result (infinity) of division by zero can allow a calculation to continue and produce a valid result, and the default result (NaN) of invalid operation can sometimes allow a fast algorithm to be used and, if a NaN result is produced, a slower and more robust algorithm to be used instead.</p>
<p>The classic example of the value of the division by zero behavior is calculation of parallel resistance. The formula for this for two resistors with resistance R1 and R2 is:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/image2.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/image_thumb2.png" width="273" height="73" /></a></p>
<p>Because division by zero gives a result of infinity, and because infinity plus another number gives infinity, and because a finite number divided by infinity gives zero, this calculation calculates the correct parallel resistance of zero when either R1 or R2 is zero. Without this behavior the code would need to check for both R1 and R2 being zero and handle that case specially.</p>
<p>In addition, this calculation will give a result of zero if R1 or R2 are very small – smaller than the reciprocal of FLT_MAX or DBL_MAX. This zero result is not technically correct. If a programmer needs to distinguish between these scenarios then monitoring of the overflow and division by zero flags will be needed.</p>
<h2>Resistance is futile</h2>
<p>Assuming that we are not trying to make use of the divide-by-zero behavior we need a convenient way of turning on the ‘bad’ floating-point exceptions. And, since we have to coexist with other code (calling out to physics libraries, D3D, and other code that may not be ‘exception clean’) we also need a way of temporarily turning off all floating-point exceptions.</p>
<p>The appropriate way to do this is with a pair of classes whose constructors and destructors do the necessary magic. Here are some classes that do that, for VC++:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">// Declare an object of this type in a scope in order to suppress</span>
<span style="color: #666666;">// all floating-point exceptions temporarily. The old exception</span>
<span style="color: #666666;">// state will be reset at the end.</span>
<span style="color: #0000ff;">class</span> FPExceptionDisabler
<span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
    FPExceptionDisabler<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// Retrieve the current state of the exception flags. This</span>
        <span style="color: #666666;">// must be done before changing them. _MCW_EM is a bit</span>
        <span style="color: #666666;">// mask representing all available exception masks.</span>
        _controlfp_s<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>mOldValues, _MCW_EM, _MCW_EM<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #666666;">// Set all of the exception flags, which suppresses FP</span>
        <span style="color: #666666;">// exceptions on the x87 and SSE units.</span>
        _controlfp_s<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span>, _MCW_EM, _MCW_EM<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
    ~FPExceptionDisabler<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// Clear any pending FP exceptions. This must be done</span>
        <span style="color: #666666;">// prior to enabling FP exceptions since otherwise there</span>
        <span style="color: #666666;">// may be a 'deferred crash' as soon the exceptions are</span>
        <span style="color: #666666;">// enabled.</span>
        _clearfp<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Reset (possibly enabling) the exception status.</span>
        _controlfp_s<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span>, mOldValues, _MCW_EM<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
    <span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">int</span> mOldValues<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Make the copy constructor and assignment operator private</span>
    <span style="color: #666666;">// and unimplemented to prohibit copying.</span>
    FPExceptionDisabler<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> FPExceptionDisabler<span style="color: #000040;">&amp;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    FPExceptionDisabler<span style="color: #000040;">&amp;</span> operator<span style="color: #000080;">=</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> FPExceptionDisabler<span style="color: #000040;">&amp;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">// Declare an object of this type in a scope in order to enable a</span>
<span style="color: #666666;">// specified set of floating-point exceptions temporarily. The old</span>
<span style="color: #666666;">// exception state will be reset at the end.</span>
<span style="color: #666666;">// This class can be nested.</span>
<span style="color: #0000ff;">class</span> FPExceptionEnabler
<span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
    <span style="color: #666666;">// Overflow, divide-by-zero, and invalid-operation are the FP</span>
    <span style="color: #666666;">// exceptions most frequently associated with bugs.</span>
    FPExceptionEnabler<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">int</span> enableBits <span style="color: #000080;">=</span> _EM_OVERFLOW <span style="color: #000040;">|</span>
                _EM_ZERODIVIDE <span style="color: #000040;">|</span> _EM_INVALID<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// Retrieve the current state of the exception flags. This</span>
        <span style="color: #666666;">// must be done before changing them. _MCW_EM is a bit</span>
        <span style="color: #666666;">// mask representing all available exception masks.</span>
        _controlfp_s<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>mOldValues, _MCW_EM, _MCW_EM<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Make sure no non-exception flags have been specified,</span>
        <span style="color: #666666;">// to avoid accidental changing of rounding modes, etc.</span>
        enableBits <span style="color: #000040;">&amp;</span><span style="color: #000080;">=</span> _MCW_EM<span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Clear any pending FP exceptions. This must be done</span>
        <span style="color: #666666;">// prior to enabling FP exceptions since otherwise there</span>
        <span style="color: #666666;">// may be a 'deferred crash' as soon the exceptions are</span>
        <span style="color: #666666;">// enabled.</span>
        _clearfp<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #666666;">// Zero out the specified bits, leaving other bits alone.</span>
        _controlfp_s<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span>, ~enableBits, enableBits<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
    ~FPExceptionEnabler<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// Reset the exception state.</span>
        _controlfp_s<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span>, mOldValues, _MCW_EM<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
    <span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">int</span> mOldValues<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Make the copy constructor and assignment operator private</span>
    <span style="color: #666666;">// and unimplemented to prohibit copying.</span>
    FPExceptionEnabler<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> FPExceptionEnabler<span style="color: #000040;">&amp;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    FPExceptionEnabler<span style="color: #000040;">&amp;</span> operator<span style="color: #000080;">=</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> FPExceptionEnabler<span style="color: #000040;">&amp;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>The comments explain a lot of the details, but I’ll mention a few here as well.</p>
<p>_controlfp_s is the secure version of the portable version of the old _control87 function. _controlfp_s controls exception settings for both the x87 and SSE FPUs. It can also be used to control rounding directions on both FPUs, and on the x87 FPU it can be used to control the precision settings. These classes use the mask parameter to ensure that only the exception settings are altered.</p>
<p>The floating-point exception flags are sticky, so when an exception flag is raised it will stay set until explicitly cleared. This means that if you choose not to enable floating-point exceptions you can still detect whether any have happened. And – not so obviously – if the exception associated with a flag is enabled after the flag is raised then an exception will be triggered on the next FPU instruction, even if that is several weeks after the operation that raised the flag. Therefore it is critical that the exception flags be cleared each time before exceptions are enabled.</p>
<h2>Typical usage</h2>
<p>The floating-point exception flags are part of the processor state which means that they are per-thread settings. Therefore, if you want exceptions enabled everywhere you need to do it in each thread, typically in main/WinMain and in your thread start function, by dropping an FPExceptionEnabler object in the top of these functions.</p>
<p>When calling out to D3D or any code that may use floating-point in a way that triggers these exceptions you need to drop in an FPExceptionDisabler object.</p>
<p>Alternately, if most your code is not FP exception clean then it may make more sense to leave FP exceptions disabled most of the time and then enable them in particular areas, such as particle systems.</p>
<p>Because there is some cost associated with changing the exception state (the FPU pipelines will be flushed at the very least) and because making your code more crashy is probably not what you want for your shipping game you should put #ifdefs in the constructors and destructors so that these objects become NOPs in your retail builds.</p>
<p>There have been various instances in the past (printer drivers from a manufacturer who shall not be named) that would enable floating-point exceptions and leave them enabled, meaning that some perfectly legitimate software would start crashing after calling into third-party code (such as after printing). Having somebody’s hapless code crash after calling a function in your code is a horrible experience, so be particularly careful if your code may end up injected into other processes. In that situation you definitely need to not leave floating-point exceptions enabled when you return, and you may need to be tolerant of being called with floating-point exceptions enabled.</p>
<h2>Performance implications of exceptions</h2>
<p>Raising the exception flags (triggering a floating-point exception) should have no performance implications. These flags are raised frequently enough that any CPU designer will make sure that doing so is free. For example, the inexact flag is raised on virtually every floating-point instruction.</p>
<p>However having exceptions enabled can be expensive. Delivering precise exceptions on super-scalar CPUs can be challenging and some CPUs choose to implement this by disabling FPU parallelism when floating-point exceptions are enabled. This hurts performance. The PowerPC CPU used in the Xbox 360 CPU (and presumably the one used in the PS3) slows down significantly when any floating-point exceptions are enabled. This means that when using this technique on these processors you should just enable FPU exceptions on an as-needed basis.</p>
<h2>Sample code</h2>
<p>The sample code below calls TryDivByZero() three times – once in the default environment, once with the three ‘bad’ floating-point exceptions enabled, and once with them suppressed again. TryDivByZero does a floating-point divide-by-zero inside a Win32 __try/__except block in order to catch exceptions, print a message, and allow the tests to continue. This type of structured exception handling block should <em>not </em>(repeat <em>not</em>) be used in production code, except possibly to record crashes and then exit. I hesitate to demonstrate this technique because I fear it will be misused. Continuing after unexpected structured exceptions is pure evil.</p>
<p>With that said, here is the code:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> __cdecl DescribeException<span style="color: #008000;">&#40;</span>PEXCEPTION_POINTERS pData, <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>pFunction<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">// Clear the exception or else every FP instruction will</span>
    <span style="color: #666666;">// trigger it again.</span>
    _clearfp<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    DWORD exceptionCode <span style="color: #000080;">=</span> pData<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>ExceptionRecord<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>ExceptionCode<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> pDescription <span style="color: #000080;">=</span> <span style="color: #0000ff;">NULL</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">switch</span> <span style="color: #008000;">&#40;</span>exceptionCode<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">case</span> STATUS_FLOAT_INVALID_OPERATION<span style="color: #008080;">:</span>
        pDescription <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;float invalid operation&quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">case</span> STATUS_FLOAT_DIVIDE_BY_ZERO<span style="color: #008080;">:</span>
        pDescription <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;float divide by zero&quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">case</span> STATUS_FLOAT_OVERFLOW<span style="color: #008080;">:</span>
        pDescription <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;float overflow&quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">case</span> STATUS_FLOAT_UNDERFLOW<span style="color: #008080;">:</span>
        pDescription <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;float underflow&quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">case</span> STATUS_FLOAT_INEXACT_RESULT<span style="color: #008080;">:</span>
        pDescription <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;float inexact result&quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">case</span> STATUS_FLOAT_MULTIPLE_TRAPS<span style="color: #008080;">:</span>
        <span style="color: #666666;">// This seems to occur with SSE code.</span>
        pDescription <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;float multiple traps&quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">default</span><span style="color: #008080;">:</span>
        pDescription <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;unknown exception&quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">void</span><span style="color: #000040;">*</span> pErrorOffset <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#if defined(_M_IX86)</span>
    <span style="color: #0000ff;">void</span><span style="color: #000040;">*</span> pIP <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span>pData<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>ContextRecord<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>Eip<span style="color: #008080;">;</span>
    pErrorOffset <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span>pData<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>ContextRecord<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>FloatSave.<span style="color: #007788;">ErrorOffset</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#elif defined(_M_X64)</span>
    <span style="color: #0000ff;">void</span><span style="color: #000040;">*</span> pIP <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span>pData<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>ContextRecord<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>Rip<span style="color: #008080;">;</span>
<span style="color: #339900;">#else</span>
    <span style="color: #339900;">#error Unknown processor</span>
<span style="color: #339900;">#endif</span>
&nbsp;
    <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Crash with exception %x (%s) in %s at %p!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>,
            exceptionCode, pDescription, pFunction, pIP<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>pErrorOffset<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// Float exceptions may be reported in a delayed manner -- report the</span>
        <span style="color: #666666;">// actual instruction as well.</span>
        <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Faulting instruction may actually be at %p.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, pErrorOffset<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #666666;">// Return this value to execute the __except block and continue as if</span>
    <span style="color: #666666;">// all was fine, which is a terrible idea in shipping code.</span>
    <span style="color: #0000ff;">return</span> EXCEPTION_EXECUTE_HANDLER<span style="color: #008080;">;</span>
    <span style="color: #666666;">// Return this value to let the normal exception handling process</span>
    <span style="color: #666666;">// continue after printing diagnostics/saving crash dumps/etc.</span>
    <span style="color: #666666;">//return EXCEPTION_CONTINUE_SEARCH;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">static</span> <span style="color: #0000ff;">float</span> g_zero <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">void</span> TryDivByZero<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    __try
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">float</span> inf <span style="color: #000080;">=</span> <span style="color:#800080;">1.0f</span> <span style="color: #000040;">/</span> g_zero<span style="color: #008080;">;</span>
        <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;No crash encountered, we successfully calculated %f.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, inf<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
    __except<span style="color: #008000;">&#40;</span>DescribeException<span style="color: #008000;">&#40;</span>GetExceptionInformation<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, __FUNCTION__<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// Do nothing here - DescribeException() has already done</span>
        <span style="color: #666666;">// everything that is needed.</span>
    <span style="color: #008000;">&#125;</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;">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>
<span style="color: #339900;">#if _M_IX86_FP == 0</span>
    <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> pArch <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;with the default FPU architecture&quot;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#elif _M_IX86_FP == 1</span>
    <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> pArch <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;/arch:sse&quot;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#elif _M_IX86_FP == 2</span>
    <span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> pArch <span style="color: #000080;">=</span> <span style="color: #FF0000;">&quot;/arch:sse2&quot;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#else</span>
<span style="color: #339900;">#error Unknown FP architecture</span>
<span style="color: #339900;">#endif</span>
    <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Code is compiled for %d bits, %s.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, <span style="color: #0000dd;">sizeof</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">*</span> <span style="color: #0000dd;">8</span>, pArch<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// Do an initial divide-by-zero.</span>
    <span style="color: #666666;">// In the registers window if display of Floating Point</span>
    <span style="color: #666666;">// is enabled then the STAT register will have 4 ORed</span>
    <span style="color: #666666;">// into it, and the floating-point section's EIP register</span>
    <span style="color: #666666;">// will be set to the address of the instruction after</span>
    <span style="color: #666666;">// the fdiv.</span>
    <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>Do a divide-by-zero in the default mode.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    TryDivByZero<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #666666;">// Now enable the default set of exceptions. If the</span>
        <span style="color: #666666;">// enabler object doesn't call _clearfp() then we</span>
        <span style="color: #666666;">// will crash at this point.</span>
        FPExceptionEnabler enabled<span style="color: #008080;">;</span>
        <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>Do a divide-by-zero with FP exceptions enabled.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        TryDivByZero<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #666666;">// Now let's disable exceptions and do another</span>
            <span style="color: #666666;">// divide-by-zero.</span>
            FPExceptionDisabler disabled<span style="color: #008080;">;</span>
            <span style="color: #0000dd;">printf</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>Do a divide-by-zero with FP exceptions disabled.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
            TryDivByZero<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Typical output is:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/image3.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/image_thumb3.png" width="668" height="188" /></a></p>
<p>When generating SSE code I sometimes see STATUS_FLOAT_MULTIPLE_TRAPS instead of STATUS_FLOAT_DIVIDE_BY_ZERO. This is slightly less helpful, but the root cause should be straightforward to determine.</p>
<p>That said, determining the root cause can be slightly tricky. On the x87 FPU, floating-point exception reporting is delayed. Your program won’t actually crash until the next floating-point instruction after the the problematic one. In the example below the fdiv does the divide by zero, but the crash doesn’t happen until the fstp after.</p>
<blockquote><p>011A10DD fdiv&#160;&#160;&#160;&#160;&#160;&#160;&#160; dword ptr [__fmode+4 (11A3374h)]&#160; <br />011A10E3 fstp&#160;&#160;&#160;&#160;&#160;&#160;&#160; dword ptr [ebp-1Ch]&#160; </p>
</blockquote>
<p>Normally it is easy enough to look back one instruction to find the culprit, but sometimes the gap can be long enough to cause confusion. Luckily the CPU records the address of the actual faulting instruction and this can be retrieved from the exception record. This value is printed out when applicable in my exception handler, or you can see it in the Visual Studio registers window.</p>
<p>The sample code can be downloaded as a VisualC++ 2010 project (32-bit and 64-bit) from here:</p>
<p><a href="ftp://ftp.cygnus-software.com/pub/FloatExceptions.zip">ftp://ftp.cygnus-software.com/pub/FloatExceptions.zip</a></p>
<h2>Handle and continue</h2>
<p>If you want to get really crazy/sophisticated then it is possible to catch a floating-point exception with __try/__except, handle it in some domain specific way (handling overflow by scaling down the result and recording that you did that) and then resume. This is sufficiently esoteric that I have no more to say about it – consult the documentation for _fpieee_flt if this sounds interesting.</p>
<h2>SIMD</h2>
<p>SSE and its SIMD instructions throw a few wrinkles into the mix. One thing to be aware of is that instructions like reciprocal estimate (rcpps) never trigger divide-by-zero exceptions – they just silently generate infinity. Therefore they are a way that infinity can be generated even when the ‘bad’ exceptions are enabled.</p>
<p>Additionally, many common patterns for SIMD instructions only use some components of the four-wide registers. This could be because the code is operating on a three-float vector, or it could be because the code is operating on an array of floats that is not a multiple of four long. Either way, the ‘unused’ component or components in the registers may end up triggering floating-point exceptions. These exceptions are false-positives (they don’t indicate a bug), but they must be dealt with in order to allow floating-point exceptions to be enabled. The best way to deal with this is to ensure that the unused components are filled with valid data, at least in the development builds where floating-point exceptions are enabled. Filling them with one or zero is generally good enough.</p>
<p>Filling the unused components with valid values may also improve performance. Some CPUs drop to microcode when they encounter some ‘special’ numbers (NaNs, infinities, and/or denormals) and using well behaved values avoids that risk.</p>
<h2>Practical experience</h2>
<p>On some projects I have been able to enable these three floating-point exceptions, fix all of the accidental-but-unimportant exceptions, and then find a few crucial bugs hidden in the weeds. On these projects, enabling floating-point exceptions during development was crucial. On other projects – big messy projects with a lot of history and large teams – I was unable to get the team to buy off on the concept, so it ultimately didn’t work.</p>
<p>Your mileage may vary, but as with asserts of any type, enabling them early, and ensuring that violations get fixed promptly, is the trick to getting value from floating-point exceptions. Adding them to a large existing codebase is trickier, but can be dealt with by only enabling them in particular parts of the code where their value exceeds their cost.</p>
<h2>Practical experience, hot off the presses</h2>
<p>I’ve been trying to improve the usability of debug builds on my current project and one persistent problem was a NaN that would show up in the particle system early on, triggering many different asserts. I couldn’t tell where this NaN was being generated so I knew I had to enable floating-point exceptions, using the classes described above. This project was not designed to have floating-point exceptions enabled so there were several challenges. The process was:</p>
<ul>
<li>Enable floating-point exceptions in three key functions that called out to all of the particle system code
<li>Disable floating-point exceptions in one child function that did floating-point overflow by design
<li>Pad one of our arrays of particle system data with valid data to the next multiple of four so that the unused SIMD lanes wouldn’t trigger spurious exceptions
<li>Find and fix five bugs that were causing floating-point exceptions</li>
</ul>
<p>It worked. All of the bugs were worth fixing, and one of them was the source of the NaNs. After most of a day of investigation the crucial fix was to change one letter – from ‘e’ to ‘t’ – and this was enough to prevent us from dividing zero by zero. Now our debug builds are significantly more usable, and a genuine bug that was causing (apparently unnoticed) glitches is gone.</p>
<h2>Homework</h2>
<p>The summary is that while floating-point exceptions, even the ‘bad’ ones, aren’t necessarily bad, you can often find bugs in your code by treating them as errors. By using the classes shown above, with appropriate #ifdefs so that they go away in retail builds, you can enable floating-point exceptions in most parts of your code, and thereby improve reliability and avoid unexpected behavior.</p>
<p>But please, don’t use the __try/__except block, in debug or in retail code. It is an ugly and dangerous hack that should only be used in specialized demonstration code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/20/exceptional-floating-point/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pushing the Button More Carefully</title>
		<link>http://www.altdevblogaday.com/2012/04/20/pushing-the-button-more-carefully/</link>
		<comments>http://www.altdevblogaday.com/2012/04/20/pushing-the-button-more-carefully/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 04:44:56 +0000</pubDate>
		<dc:creator>Alex Norton</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Game design]]></category>
		<category><![CDATA[General Interest]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[feel]]></category>
		<category><![CDATA[game design]]></category>
		<category><![CDATA[immersion]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25635</guid>
		<description><![CDATA[<p>Hi all, first post on here, but it&#8217;s a topic that I feel particularly strongly about and I decided I would share my thoughts. Please keep in mind that all views expressed here are purely my opinion and I in no way intend any offense.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/20/pushing-the-button-more-carefully/" class="more-link">Read more on Pushing the Button More Carefully&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Hi all, first post on here, but it&#8217;s a topic that I feel particularly strongly about and I decided I would share my thoughts. Please keep in mind that all views expressed here are purely my opinion and I in no way intend any offense.</p>
<h1><span style="text-decoration: underline">Game Design</span></h1>
<p>Game design is always about looking back before looking forward. Sometimes this is done consciously, other times it is done unconsciously, but it always happens. Every great new idea is built on improving an one or more old ideas, and the best game designers are well aware of this. One of my biggest pet peeves is when someone says to me &#8220;don&#8217;t reinvent the wheel&#8221;, which they often quickly regret saying as I begin to lecture them on how if no-one ever reinvented the wheel we would never have tyres, suspension, alignments, treading, etc. All things which have made the wheel more efficient, smoother and just generally better.</p>
<div class="wp-caption aligncenter" style="width: 321px"><img src="http://cdn-static.cnet.co.uk/i/c/blg/cat/cartech/bridgestoneairlesstyre.jpg" alt="A great design for a reinvented wheel" width="311" height="198" /><p class="wp-caption-text">A great design for a reinvented wheel</p></div>
<p>But for a wheel to be reinvented, one must start with a wheel to begin with, and that is what we are always doing in the games industry. A good example is the recently successful iOS game, Jetpack Joyride, from HalfBrick studios. An excellent game, and quite obviously modelled off of those Amiga/Commodore-era &#8220;don&#8217;t touch the sides of the tunnel with your helicopter&#8221; games. They took that solid idea, and evolved it with pickups, achievements, special gear you can earn, etc, and made a great game out of it. They reinvented the wheel and it worked.</p>
<div class="wp-caption aligncenter" style="width: 341px"><img src="http://www.halfbrick.com/wordpress/wp-content/themes/halfbrick/images/game-images/screenshots/jetpack-joyride/jetpack-joyride-3.jpg" alt="An example screen from Jetpack Joyride" width="331" height="219" /><p class="wp-caption-text">An example screen from Jetpack Joyride</p></div>
<h1>
<span style="text-decoration: underline">Does it Always Work?</span></h1>
<p>No, it doesn&#8217;t always work. Some past ideas weren&#8217;t that great, let&#8217;s be honest. But some have not only been ridiculously successful, but have also done the unthinkable and withstood the test of time. Two good examples in relatively different genres are <a title="Quake 3 Arena - Wikipedia" href="http://en.wikipedia.org/wiki/Quake_3_Arena" target="_blank">Quake 3: Arena</a> (1999) and <a title="Diablo 2 - Wikipedia" href="http://en.wikipedia.org/wiki/Diablo_2" target="_blank">Diablo II</a> (2000). There are many more, of course, but these are my case studies for this particular article.</p>
<p>Well over a decade on and these two games are still being played with distinct regularity, are favourites at private LAN parties <em>and</em> have graphics which still stack up fairly well against their more modern competitors. Why is this and what can modern game developers do to make a game that withstands the test of time so well? The answer lies in how the button is pressed.</p>
<p><img class="aligncenter" src="https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ265QfYG_K479kXEwFo1tVKVOYz_rDW2cy2dMbZ9VizcR-sY9A" alt="A big, red button" width="141" height="159" /></p>
<h1><span style="text-decoration: underline">&#8230;The Button?</span></h1>
<p>I mean this metaphorically, of course. But let me explain with a story. In my day job, I am quite involved in the gambling industry, and as such am exposed to many new products before they hit the market. One such product came about which was a &#8220;re-launch&#8221; (as it were) of the old-style &#8220;one-armed bandit&#8221; poker machines of yesteryear, which fell out of use in Australia decades ago.</p>
<div class="wp-caption aligncenter" style="width: 250px"><img src="https://encrypted-tbn1.google.com/images?q=tbn:ANd9GcSSBSkemz7-aOSiSTdLIOMkI5CtG-qeVNzsNmK5o2tVBYD0JSdRQw" alt="What the pokies used to look like" width="240" height="210" /><p class="wp-caption-text">What the pokies used to look like</p></div>
<p>In an attempt to latch onto the &#8220;retro rush&#8221; that seems to be going on&#8230; Well&#8230; Everywhere, people thought that re-releasing a classic-style one-armed bandit machine would inspire people&#8217;s nostalgia and that they would be a viable new product. I was quite excited when I heard the news as I remember my grandfather having one under his house back in the 80s and I loved the feel of the flywheel revving up as I pulled down the lever. I loved seeing it kick the spinners into gear and watching all of the colourful fruits lock into place on the wheeled display.</p>
<p>Needless to say, when the first units came into the test room, I was excited to feel that little piece of nostalgia again. The machines certainly looked the same, if not a bit more modern. The digital displays had even been replaced by the classic wheels with the printed artwork on them. It was in test mode and ready to play, so I grabbed the lever and pulled. The wheels started spinning and the lights started flashing, but it was all wrong. It felt so wrong that I thought perhaps the machine was broken&#8230; It wasn&#8217;t, of course, it worked perfectly well. But the machine was no longer clockwork, obviously, and the lever arm was simply a spring-loaded arm which pressed a small button when it was fully depressed. There was no sense of &#8220;winding&#8221; the machine up. No sense of having some sort of influence over the device and no sense of being connected to its operation in any way. It was a jarring sensation of being completely disconnected. What was once &#8211; for lack of a better term &#8211; an intimate interaction experience had now become somewhat cold, clinical and disconnected.</p>
<p>I voiced my concerns at this, and was &#8211; of course &#8211; laughed off. I even went so far as to suggest they could build a small flywheel mechanism into the arm that has no functional purpose other than generating that &#8220;feel&#8221; when you pull the lever. They ignored my counsel and released the product anyway. Needless to say, it was very unpopular and never really took off. The official reasoning was that &#8220;people don&#8217;t like the &#8216;retro thing&#8217; in gambling&#8221;.</p>
<h1>
<span style="text-decoration: underline">How is it Relevant to Video Games?</span></h1>
<p>How does this relate to video games such as Quake 3 Arena and Diablo 2? Well, think of that &#8220;button&#8221; as being the interaction between the player and the game. It has to feel good, just like the poker machine arm. There are things you can do to the button to make it feel better, and be more intimate, or there are things you can do to the button to make the user feel disconnected from the machine, and they both come down to a deep level of design.</p>
<p>When beginning a game project, try to describe the game in a short, concise sentence. Once you&#8217;ve got that sentence, every single thing you add to the game which complies with that sentence will make the game &#8220;cleaner&#8221; to play, but the more you stray from that sentence, the more disjointed it will seem.</p>
<h1>
<span style="text-decoration: underline">Quake 3 Arena:</span></h1>
<p>Take Quake 3 Arena as the first example. It can easily be described as &#8220;Fast-paced, sci-fi, multiplayer deathmatching&#8221; and nothing else. The reason that game was so popular for so long, was twofold. Firstly, it was built on <a href="http://en.wikipedia.org/wiki/Id_Tech_3" target="_blank">a very beautifully made engine</a> made by John Carmack, which was powerful enough to drive MANY other games for the next decade (RTCW, Jedi Academy, Call of Duty, etc) and secondly, it followed a clean design based on a simple concept which could be summed up in that one sentence. Every aspect of the game conformed to it. There was nothing confusing, or particularly intricate about it. When you played it, you were immersed in the game. No part of it &#8220;fought&#8221; against you or detached you from the experience. You had four movement buttons, a jump button and a shoot button. A control system which could be replicated on a classic GameBoy. The player movement was swift, smooth, consistent. The game never slowed down, or became badly paced at any point, yet still gave the user enough freedom to develop their own style of play and put it into the game.</p>
<p>Conversely, a later id Software game, Doom III, was not quite as smooth. The gameplay was slower and more disjointed. It was still a great game, yes, but things such as having to stop to punch numbers into a keypad or having to put down your weapon to pull out a torch disconnected the player from an otherwise immersive, cathartic experience.</p>
<h1>
<span style="text-decoration: underline">Diablo II:</span></h1>
<p>Diablo II is another fine example of this. Fans of the series will know that it has an incredible complex control system consisting of one button&#8230; Oh, yes, you can use the number buttons on the keyboard as well if you like, but there is essentially the left-click button and a couple of others which you use occasionally. The entire game is about as non-confrontational as you can get, and anyone can pick it up. It is also paced beautifully, with the first area being almost impossible to die in, yet still giving you enough of a sense of risk to keep you engaged and on your toes.</p>
<div class="wp-caption aligncenter" style="width: 269px"><img src="https://encrypted-tbn0.google.com/images?q=tbn:ANd9GcTshXQqsYUk28y49WZFmUK5Sqo9by2Xs3y3z6Fe3Ny2x6yl6p_-6Q" alt="Diablo 2 Screenshot" width="259" height="194" /><p class="wp-caption-text">A typical scene from Diablo II</p></div>
<p>It had very simple multiplayer, a beautifully crafted procedural item and level system and enough replayability to ensure people would be able to play it for years, and indeed they did. Blizzard, in true Blizzard form, found all of the features of Diablo I that left the player feeling disconnected and removed or remodelled them, making a game which is clean, simple, elegant and extremely replayable. They followed a simple design sentence of &#8220;Explore, kill and loot while progressing character&#8221; and every aspect of the game reflects that. Nothing gets in your way, nothing slows the progress. There are no repetitive cut scenes or cloned combat encounters or scripted events, all of which can make a procedural game lag something awful. This &#8220;neatness&#8221; has ensured the game&#8217;s continuing success both in the single player and multiplayer worlds and place on game store shelves over a decade after it first was released.</p>
<h1>
<span style="text-decoration: underline">So What are you Saying?</span></h1>
<p>When designing a game, before doing anything else, describe what you want it to be in one concise sentence. After that, with every decision you make or feature you go to add, check to see if it fits neatly with that short description. If it strays too far out of that, or the description ends up being too long, you will end up with a convoluted game and the player will feel disconnected from it. Remember that games are a form of escapism, and the player should forget that there is even a keyboard or other controller between them and the game. The graphics help, yes. The story helps, yes. But it&#8217;s the FEEL of the game that will ensure a captive audience. It&#8217;s just like the one-armed bandit. The aim of the poker machine is to pull the lever and get the wheels spinning, but if you just focus on making the lever spin the wheels, people won&#8217;t play it. They need to enjoy <em><strong>the act</strong></em> of pulling the lever and pushing the button just as much as the result of that action on the screen.</p>
<p>&nbsp;</p>
<p>Anyway, thanks for listening to my little rant :) I hope it helps to inspire all of you other game developers.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/20/pushing-the-button-more-carefully/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Localization Notes</title>
		<link>http://www.altdevblogaday.com/2012/04/19/localization-notes/</link>
		<comments>http://www.altdevblogaday.com/2012/04/19/localization-notes/#comments</comments>
		<pubDate>Thu, 19 Apr 2012 12:23:17 +0000</pubDate>
		<dc:creator>Michael A. Carr-Robb-John</dc:creator>
				<category><![CDATA[Game design]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Localization]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25616</guid>
		<description><![CDATA[<p><img class="alignleft size-medium wp-image-25617" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/dreamstime_xs_18577198-300x225.jpg" alt="" width="300" height="225" />In a few days I am going to jump on a plane and move to a new country, this time I am off to Seattle. With this pending adventure it got me thinking about some of the wonderful fun I have had localizing games for foreign markets and I thought some of my notes might make an interesting post for anyone thinking of doing localization.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/19/localization-notes/" class="more-link">Read more on Localization Notes&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-medium wp-image-25617" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/dreamstime_xs_18577198-300x225.jpg" alt="" width="300" height="225" />In a few days I am going to jump on a plane and move to a new country, this time I am off to Seattle. With this pending adventure it got me thinking about some of the wonderful fun I have had localizing games for foreign markets and I thought some of my notes might make an interesting post for anyone thinking of doing localization.</p>
<p>First though, some reader interaction… dig out the schedule for your current project and look through it. Is there a task anywhere on it titled &#8220;localization&#8221;? If it is on the schedule I would put good money on it being close to the end of the project usually within five tasks of the Alpha build.</p>
<p>If you have a task titled &#8220;localization setup&#8221; in the first half of your projects development cycle then you or someone on your team has probably already been through the pain of localization and is already preparing for it.</p>
<h2><strong><img class="alignright  wp-image-25618" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/04-DesertStrike-MS-ScreenShot02.jpg" alt="" width="226" height="127" />Location, Location, Location<br />
</strong></h2>
<p>What most people focus on primarily with localization is usually the language and although it is important it is only half the equation. The “Location” is the other half and this is where things get subtle and you need to become a little culturally aware.</p>
<p>Let&#8217;s consider this post, you might initially be unaware that I have localized it for English American. I am from England and I am British which means that I learnt to spell color as colour, localization as localisation and I pronounce &#8216;Z&#8217; as &#8220;Zed&#8221; rather than &#8220;Zee&#8221;. These differences come about not because of the language but because of the differences in culture.</p>
<p>Keeping localization in mind during development means that when issues arise they can be fixed quickly rather than waiting until the end of the project and trying to fix it with a hack.</p>
<p>I do not profess to be an expert on these various countries and cultures, what follows are issues that I have experienced during the localization process. By sharing them I am hoping that you will firstly have a clearer idea of what to watch out for but also I would encourage you to share your own experiences in the comments section below.</p>
<h2><strong>Hand Gestures</strong></h2>
<p><img class="alignright size-medium wp-image-25619" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/dreamstime_xs_5112677-300x231.jpg" alt="" width="300" height="231" />Animators use hand gestures to breathe life into the characters, unfortunately there are quite a few hand gestures that can cause problems when dealing with localization. The “Okay” gesture, the “Thumbs up” gesture and the extended hand with palm outward are just three gestures that I have seen removed from various games due to how different cultures react to them.</p>
<p>You could go down the route of generating a different animation tree localized for each country but that does increase the amount of data to be maintained and also the likely hood of a bug being introduced in a specific country.</p>
<p>A quick internet search can produce some good descriptions of various gestures that can be problematic, this one even showed gestures I was unaware of before writing this post: <a title="Daily Telegraph" href="http://www.telegraph.co.uk/travel/picturegalleries/8788932/Rude-hand-gestures-of-the-world.html?image=5" target="_blank">Telegraph</a>.</p>
<h2><strong>In game visuals</strong></h2>
<p>Imagine that in your game there is a wall upon which scribbled in a marker pen is a message that is important for putting the player on the right track. Now image that Portuguese is your language, unless that texture has been translated into a different language you have just made it extremely difficult for those players to progress.</p>
<p>Apart from doing a texture swap based upon the selected language you might also consider adding a language trigger where if the player gets close to the wall it will pop up a translation.</p>
<h2><strong>The Language of Color</strong></h2>
<p>Color plays a huge part in our emotional and physiological state even though for the most part we are completely unaware of it most of the time, what is really interesting is that the specific colors actually change from one culture to another. For example in Western countries black is used to represent mourning however in South America the color to use would more appropriately be purple.</p>
<p>I am mentioning this here more for completeness since I can only remember only ever once changing a game color for localization. The specific issue was relating to the color that a map of Germany had been painted.</p>
<p>This is quite a useful and interesting chart:  <a href="http://www.informationisbeautiful.net/visualizations/colours-in-cultures/" target="_blank">informationisbeautiful</a>.</p>
<h2><strong>Violence</strong></h2>
<p><img class="alignright size-full wp-image-25620" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/r18-logo.jpg" alt="" width="196" height="161" />Germany has very strict laws about violence especially where humans are concerned, as a consequence there have been a few games where the red blood has been changed to (robot) green. Or in the case of one of my projects the characters were to be tortured for information, in the German version we simply covered the animations up hiding the offending visuals from the players in Germany.</p>
<h2><strong>Adult Content</strong></h2>
<p>Worth remembering that not every country believe that games are for adults, one such example is Australia which at present does not allow a rating of 18+ for games.</p>
<p>Have a look of this list on <a href="http://en.wikipedia.org/wiki/List_of_banned_video_games" target="_blank">wikipedia</a> of banned games in different countries, useful to know why a game was banned since it isn’t always about violence and adult content.<br />
<img class="alignleft  wp-image-25621" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/dreamstime_xs_17242624-300x300.jpg" alt="" width="240" height="240" /></p>
<h2><strong>Audio</strong></h2>
<p>Another facet of the localization process is obviously to make sure the correct spoken speech / dialog is triggered in game in the correct language. It is easy to look through an excel document and see when translation text is missing however it is a lot harder to check the audio which is why I try to encourage artists / engineers / designers on different platforms to spend time working in the different language and locations as early in a projects development as possible.<br />
Hopefully you have finished reading this and there wasn’t anything new that you didn’t know already, if anything here was surprising and new then you probably should kick localization up your schedules to do list.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/19/localization-notes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>#AltDevPanel April Update #1</title>
		<link>http://www.altdevblogaday.com/2012/04/19/altdevpanel-april-update-1/</link>
		<comments>http://www.altdevblogaday.com/2012/04/19/altdevpanel-april-update-1/#comments</comments>
		<pubDate>Thu, 19 Apr 2012 06:49:49 +0000</pubDate>
		<dc:creator>Mike Acton</dc:creator>
				<category><![CDATA[#AltDev Updates]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25608</guid>
		<description><![CDATA[<p>Two recent #AltDevPanel discussions:</p>
<h2>Why is the #ME3 ending like Javascript in the browser?</h2>
<p>With <a href="http://twitter.com/ArchAzrael">@ArchAzrael</a> and <a href="http://twitter.com/mike_acton">@mike_acton</a><br />
Check out what <a href="http://www.doublecluepon.com/">Double Cluepon</a> is doing. I&#8217;m a big fan of their open development model.<br />
<span style="text-align:center; display: block;"><a href="http://www.altdevblogaday.com/2012/04/19/altdevpanel-april-update-1/"><img src="http://img.youtube.com/vi/YQgbaEpsCbY/2.jpg" alt="" /></a></span></p>
<p><a href="http://www.altdevblogaday.com/2012/04/19/altdevpanel-april-update-1/" class="more-link">Read more on #AltDevPanel April Update #1&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Two recent #AltDevPanel discussions:</p>
<h2>Why is the #ME3 ending like Javascript in the browser?</h2>
<p>With <a href="http://twitter.com/ArchAzrael">@ArchAzrael</a> and <a href="http://twitter.com/mike_acton">@mike_acton</a><br />
Check out what <a href="http://www.doublecluepon.com/">Double Cluepon</a> is doing. I&#8217;m a big fan of their open development model. </p>
<p><iframe width="500" height="281" src="http://www.youtube.com/embed/YQgbaEpsCbY?fs=1&#038;feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<h2>Game tools</h2>
<p>With <a href="http://twitter.com/gorlak">@gorlak</a>, <a href="http://twitter.com/fuzzybinary">@fuzzybinary</a> and <a href="http://twitter.com/mike_acton">@mike_acton</a><br />
Make sure to join up with the IGDA Tools SIG (#toolsmiths) if you&#8217;re interested in a community of tools developers. And check out <a href="http://thetoolsmiths.org/">The Toolsmiths blog</a></p>
<p><iframe width="500" height="281" src="http://www.youtube.com/embed/EhZVirydTMA?fs=1&#038;feature=oembed" frameborder="0" allowfullscreen></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/19/altdevpanel-april-update-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unlocking our potential</title>
		<link>http://www.altdevblogaday.com/2012/04/18/unlocking-our-potential/</link>
		<comments>http://www.altdevblogaday.com/2012/04/18/unlocking-our-potential/#comments</comments>
		<pubDate>Wed, 18 Apr 2012 20:26:19 +0000</pubDate>
		<dc:creator>Alex Moore</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Game design]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25558</guid>
		<description><![CDATA[<p>In <a href="http://www.altdevblogaday.com/2012/04/03/the-perception-of-interactivity/" target="_blank">my last article</a> I looked at how content driven games are made, concluding that any sense of control over the story is, ultimately, an illusion. With this article I aim to open the door and look beyond our current limitations and ask instead: is it possible to make a content driven game that isn’t constrained by its creator, but instead crafted by the player?</p>
<p><a href="http://www.altdevblogaday.com/2012/04/18/unlocking-our-potential/" class="more-link">Read more on Unlocking our potential&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.altdevblogaday.com/2012/04/03/the-perception-of-interactivity/" target="_blank">my last article</a> I looked at how content driven games are made, concluding that any sense of control over the story is, ultimately, an illusion. With this article I aim to open the door and look beyond our current limitations and ask instead: is it possible to make a content driven game that isn’t constrained by its creator, but instead crafted by the player?</p>
<p>(Mini warning: this post turned from a simple idea to a fairly epic 2500 words.  Get a cuppa and a chocolate biscuit before attempting to read.)<br />
<span id="more-25558"></span><br />
To answer that, we need to look at what the current constrains actually are. There are lots of small issues but they nearly all fall into one of two categories: <strong>cost</strong> or <strong>artistic desire</strong>.</p>
<h1>Cost</h1>
<p>It&#8217;s a sad fact but <a title="Blockbuster Games" href="http://www.wired.com/gamelife/2011/02/dice-blockbuster-games/" target="_blank">the cost of making AAA games has sky rocketed</a>. On average, on the original PlayStation, a team of about 10 people could make a 60$ game in about a year. For the PS2 that went up to more like 30 &#8211; 50 people for two years. For this generation of console there is no average &#8211; it’s as many people as you can get for as long as you can get. 100 people taking 3 years is fairly normal, but it’s also common for teams made up of many more. If the price of games reflected the increased man-year development time, they’d now cost about 1800$ each.</p>
<h2>Why?</h2>
<p>As a very broad stroke: all those pretty images take a lot of developing. The quality of the art in games is far higher than ever before, and the code bases that drive everything are far larger and complex than we ever imagined they’d be.</p>
<p>The biggest single factor slowing us down, and thus costing us money, is our tools and pipelines. Turnaround for an idea has slowed to an almost archaic crawl because of the time it takes to create content in a AAA game right now. The knock on of this is that it has a detrimental effect on the quality of the games we are making, and people don’t want to pay 60$ a pop anymore, let alone 1800$. There are two ways of fixing this: as an industry we need to invest in finding a different approach to creating content or we need to develop better tools.  Or, preferably, both.</p>
<h2>Different approaches to creating content</h2>
<p>Once upon a time, coders creating everything in the game.  Art was a means to an end.  Nowadays we have teams of artists sat at desks across the globe, all beavering away on the small details.  That nice crumbly wall in Uncharted 3 probably had three different artists working on it: one for the basic collision mesh, one for the render mesh and one creating the texture and normal map in the first place.  Throw in a lighting artist or two, and a particle effects guy to make the nice clouds of dust when it gets shot.  Oh, and a guy to make the impact sound effects.  Let alone the coders required to make all these systems work together.</p>
<p>Back in 1993, a role playing game called Dungeon Hack came out. It wasn&#8217;t unique by any stretch, but I mention it partly because of how movement systems used to work. The dungeon, as with most games of the time, existed on a grid. Each move you took moved you to the adjacent square, assuming there wasn’t a wall there. The world was rendered in first person, but you had no freedom to look around at anything other than 90 degrees, and move one square at a time. (Completely unrelated to me writing this article <a href="http://youtu.be/xmSJ1iFx5zA" target="_blank">Legend of Grimrock</a>, which uses this movement system in a modern game, has just been released.)</p>
<p>From a top down view, a dungeon looked a bit like this:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/dungeon.png"><img class="aligncenter size-full wp-image-25577" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/dungeon.png" alt="" width="381" height="378" /></a></p>
<p>The main reason I mention Dungeon Hack is because of how the dungeons were actually created.  If you look again at the image above you&#8217;ll see that it&#8217;s possible to create the layout by using just four files, rotated into position:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/tiles.png"><img class="aligncenter size-full wp-image-25600" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/tiles.png" alt="" width="368" height="80" /></a></p>
<p>By using a pre-defined set of tiles and an algorithm running a randomly generated number to lay them out, a unique dungeon was created every time you started a new game.  Rules then layered on top to place items and enemies.  In theory, there were limitless combinations and once the system for creating the content was up and running new levels could be generated almost instantly.  If user control was desired, an editor allowed players to make their own layout.</p>
<p>Tile based generation still exists in games like Civilisation, but it has proved very difficult to create modern 3D games with such a system, partly because of the demands on artistic quality and partly because of the desire for unique locations to visit.</p>
<h3>Prefabs</h3>
<p>Prefabs are a more modern way of generating content, and in essence work in a similar way to tiles, except they are stand alone units rather than part of an interconnected network.  Humans are very good at spotting repetition though, which reduces the effectiveness of using this system. Houses fairly quickly get spotted as clones, and players tend to lose interest in discovering new places if they think they’ve already seen everything there is to offer.</p>
<h3>Procedural Generation</h3>
<p>This is based heavily on maths and simple data structures.  The best example of what can be achieved with this method is still the demo scene:</p>

<object width="640" height="360">
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="movie" value="http://www.youtube.com/v/ZfuierUvx1A&autoplay=0&loop=0&rel=0" />
<param name="wmode" value="transparent">
<embed src="http://www.youtube.com/v/ZfuierUvx1A&autoplay=0&loop=0&rel=0" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" allowscriptaccess="always" width="640" height="360">
</embed>
</object>


<p>As with the randomly generated dungeons there is a set of rules controlling the overall scope of the images here.  Similar methods can easily create large scale environments.  There are limitations though, the main one being creating areas that flow well into one and other.</p>
<p>On their own then, none of these approaches really gives us the flexibility or quality that we desire.  But by combining the three methods into a toolset we could help open up new ways of creating large scale content, rather than just relying on adding more artists into the equation.</p>
<h3>Character Creation</h3>
<p>Every story needs characters, and in this regard there are already tools that allow us to create a lot of unique models quickly.</p>

<object width="480" height="360">
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="movie" value="http://www.youtube.com/v/1WhOTrc5554&autoplay=0&loop=0&rel=0" />
<param name="wmode" value="transparent">
<embed src="http://www.youtube.com/v/1WhOTrc5554&autoplay=0&loop=0&rel=0" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" allowscriptaccess="always" width="480" height="360">
</embed>
</object>


<p>I&#8217;ve used this video before because it&#8217;s a great example of what can be created given the right motivation and time.  We can also do very similar for animations: with a base set we can quickly add variety by using additive animations, such as a limp, or letting physics code take control.</p>
<h3>The tools are the game</h3>
<p>Another way is to give players the ability to create content themselves.  Creating levels for Doom was the reason I got into designing videogames in the first place, more recently Minecraft created a game that was, initially, a tool where players could create their own content.  There’s a huge demand for this type of game, where the editor is effectively the game: FarmVille and DrawSomething are other examples. They are very different types of game from the Mass Effects of the world, but it feels like there should be a way of learning from their methodologies to enable us to improve our content driven games too.</p>
<p><a href="http://www.clicknothing.com/" target="_blank">Clint Hocking</a> has already done a very in-depth series of posts on convergence like this, and  in far more detail than I am here.  In his <a href="http://www.clicknothing.com/click_nothing/2010/09/convergence-culture-part-one.html" target="_blank">eight part series</a> he suggests that other gamers could provide the context for the story, a sentiment that I agree with but relies on playing online.  EVE Online does this to a degree and some of the stories of conspiracy that come out of it are great reads.  There’s a flaw with this method though: even with relatively small player numbers (compared to World of Warcraft), each player feels like a very small fish in a very large pond.  Your influence on world events is minimal.  The reason people like playing the hero is because of the feeling of power and fantasy it gives them, and single player games give you this ability.</p>
<p>So, we can no doubt create worlds and characters much faster than we currently do, but that doesn’t solve the main issue I’m trying to tackle with this post: <em>is there a way to create a story this way?</em></p>
<h2>Story as a mechanic</h2>
<p>Glance back up the page at the diagram of the dungeon for a moment.  There’s another way of showing its layout, and that is to instead show each square that requires a change in direction as a node, and the route through as connections:</p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/dungeon_nodes.png"><img class="aligncenter size-full wp-image-25578" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/dungeon_nodes.png" alt="" width="385" height="231" /></a></p>
<p>If you read <a href="http://www.altdevblogaday.com/2012/04/03/the-perception-of-interactivity/#chokepoints" target="_blank">my previous article on content</a> this should look familiar: this is, more or less, how we currently move through stories in content driven games.</p>
<p>In games today we take freedom of movement for granted: if we want to go and spend time looking at a blade of grass, we can. This is because movement systems have developed from the very simple set of rules Dungeon Hack et al had, to a complex mechanic. An almighty array of things are happening in the background to grant you that freedom of movement, from how to respond to the amount you’ve moved the analogue sticks through to how the scene behind that broken window renders.</p>
<p>Can we take the same steps with story? Can we create sets of rules that allow the player to drive the available story events at their will? Possibly even the freedom to create their own stories? It’s not going to be easy, and it’s not going to happen overnight, but I think we can.</p>
<h3>How?</h3>
<p>Firstly, take the steps required to make content creation faster and cheaper.  Then we need to understand what a story actually is. It’s well documented that all stories fall into one of seven types, which seems like a good place to start:</p>
<blockquote><p><span style="color: #3a8dc5"><strong>Overcoming the Monster</strong>: The hero learns of a great evil and goes on a journey to destroy it. Star Wars qualifies. Braveheart. Jaws. Any movie with Nazis in it. Some of the Rocky movies. (Is it obvious I am a guy?)</span></p>
<p><span style="color: #3a8dc5"><strong>Rags to Riches</strong>: A sad-sack beginning that leads to a happily ever after. A lot of Dickens’ stuff fits here. Disney princess movies. Harry Potter. Most every rom-com.</span></p>
<p><span style="color: #3a8dc5"><strong>The Quest</strong>: Everybody loves a quest where the hero goes on a journey to find something, which can be a Lost Ark (literal of figurative), a body (Stand By Me), or even something unknown and unseen, which is known in Hollywood as a MacGuffin. Sometimes the hero brings his entourage, too. A lot of epics are Quest stories. Like The Goonies. Some of my favorite biblical stories are quests, like Abram and The Wise Men.</span></p>
<p><span style="color: #3a8dc5"><strong>Voyage and Return</strong>: Like The Wizard of Oz, where Dorothy goes to a weird place with weird rules but ultimately returns home better off. I suppose I like Oz alright, but I’d rather give props to Back to the Future, because I’m of that ilk.</span></p>
<p><span style="color: #3a8dc5"><strong>Comedies</strong> get their own category, too. For some reason, two people can’t be together, which creates all sorts of antics. They eventually figure it out, though. Again, most every rom-com ever, like When Harry Met Sally, or The Money Pit. (Note: you can make anything into a comedy. For example, Monty Python is a funny Quest movie, but the category here refers to a specific kind of plot, not just anything with humour.)</span></p>
<p><span style="color: #3a8dc5"><strong>Tragedies</strong> are like riches to rags, where the villian gets it in the end. MacBeth and King Lear are classic examples. Or most slasher pictures if you go for that sort of thing.</span></p>
<p><span style="color: #3a8dc5"><strong>Rebirth</strong> is like a tragedy but where the hero realizes his error before it’s too late, like in It’s a Wonderful Life. Which makes me wonder, are there any slasher movies where the bad guy cleans up and catches a ray of sun at the end?</span></p></blockquote>
<p>(source <a href="http://lenwilson.us/seven-stories/" target="_blank">http://lenwilson.us/seven-stories/</a>)</p>
<p>The story outlines that most single player games use falls into ether <em>Overcoming the Monster</em> or <em>The Quest </em>which is something else that we ideally will address as the medium matures.  Aside from that though, these seven rules of thumb give us a great basis for the forming of a mechanic.  How so?  Well, a mechanic is really just a set of rules, and each of these seven categories has a very definable goal for each story category.  This means that we can create a fairly simple set of IF statements to set the story goal based on the category chosen.  Whether that category is chosen by the player or randomly doesn&#8217;t matter.</p>
<p>Of course, a good story requires much more than that: it also requires structure. Typically these are defined into sections called Acts. Act 1 introduces the audience to the characters and scenario, Act 2 fleshes everything out, and Act 3 has the conclusion.  More rules, which means we can add another layer of complexity to our mechanic.</p>
<p>The numbers of main characters, their traits and motivations: all these can be defined to some level either by the player or with weighted random selections (which is where you guarantee at least one of type X and so on).</p>
<p>Would a story generated in this fashion be any good? Well… probably not. The missing touch is, of course, humanity. This, then, is where the player really comes in: their decisions and actions influence the actions and motivations of the computer-controlled characters alongside them. The game would adapt on the fly, so if the player decides to be friends with the bad guy for instance, a new enemy or threat would have to emerge. But the player could have the freedom to influence the story as they move through it.</p>
<p>The thing we still can’t do very well is to create dialogue: both in the writing of it and in the audible generation of it. Computer generated voices still sound horribly robotic, and that instantly ruins any sense of immersion or belief. (Unless, of course, you’re doing a game about robots.)</p>
<p>There&#8217;s another problem as well, which is the second of the issues I mentioned at the start of this article:</p>
<h2>Artistic Desire</h2>
<p>This is the biggest problem really: what story do we want to tell? As shown above, the general structure of a good story is always the same, and Act 3 is the conclusion. Without closure you don’t really have a story in the sense that literature and film define them. As humans we like telling stories, we like crafting them and we like the warm feeling inside that we get when we, the the hero, reaches the end.</p>
<p>Unless, instead, we turn our game into something more akin to a soap opera.  They have moments of closure as story arcs come to an end, but the world in which those arcs exists continues to persist and expand.</p>
<p>Can we do the same with a game?</p>
<p>Do we want to?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/18/unlocking-our-potential/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lessons Learned from Training Interns</title>
		<link>http://www.altdevblogaday.com/2012/04/18/lessons-learned-from-training-interns/</link>
		<comments>http://www.altdevblogaday.com/2012/04/18/lessons-learned-from-training-interns/#comments</comments>
		<pubDate>Wed, 18 Apr 2012 05:19:06 +0000</pubDate>
		<dc:creator>Ted Spence</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25587</guid>
		<description><![CDATA[<p>Back in 2007, I received a referral from a friend. He knew a student at UCSD who was eager to get some practical programming experience; and I rather enjoyed the idea of helping to launch a promising candidate’s career.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/18/lessons-learned-from-training-interns/" class="more-link">Read more on Lessons Learned from Training Interns&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Back in 2007, I received a referral from a friend. He knew a student at UCSD who was eager to get some practical programming experience; and I rather enjoyed the idea of helping to launch a promising candidate’s career.</p>
<p>Well, frankly, I wasn’t any good at it at first. But through a bit of luck and a bit of perseverance, over the past few years I’ve trained and graduated a dozen interns, many of whom joined my software development team as positions opened up. It’s been an incredible experience, and I’ve been grateful to all of them for the opportunity to see them grow in talent and ability.  </p>
<p><span id="more-25587"></span>I have also heard from lots of people who have had bad internship experiences; and I’d like to pass on what I can tell you about making the experience a success for everyone.</p>
<h3>What Benefits Can You Expect?</h3>
<p>Having an internship program can really help your organization, as well as provide meaningful learning opportunities for the interns themselves. I believe the only good internship programs are ones that are mutually beneficial, providing guidance and technical skills for the intern and effective management experience for the company.</p>
<p>There’s a good reason that videogame companies attract interns: we do fun and challenging work; and we use skills that are complex and multidisciplinary. An intern in the videogame field has the potential to learn a lot in a very short time, especially if you involve them in the business and show them how their work contributes to a goal.</p>
<p>Interns know this too; and that’s why they’re willing to put up with low pay and low status in order to get started. But your company shouldn’t just take advantage of this desire – you should be prepared to provide value back to the intern.</p>
<p>Doing so helps to establish a company culture of caring rather than taking. A good internship program can provide a halo to your company: successful interns who enjoyed your program, even the ones who get fulltime positions elsewhere, will raise your company’s status as an employer. And designing this mentoring process helps to build your business’ ability to grow all employees, not just interns.</p>
<h3>Your Responsibilities</h3>
<p>Before you start, make sure you’re prepared to go through the hard work to have an intern. It isn’t all fun and games!</p>
<ul>
<li>Your staff should be able to dedicate 1-3 hours per day to mentoring each intern separately. The goal is to make the intern independent, but to still give them opportunity to learn. I find that 1-3 hours per day is a good start; try dividing it up between two senior employees, one the lead and one the secondary mentor.</li>
<li>You should have a clearly defined introductory task for the intern; ideally a side project that doesn’t require them to learn tons of processes before they can get started. Look around – there are probably a few one-off ideas lying dusty on the shelf. When the intern has succeeded at their first task, you should gradually increase the complexity and interconnectedness of their work.</li>
<li>Your intern should have a computer and enough space to get quiet work done. You want an intern to balance time between asking questions and researching their project; not all interns can shut out the distractions. If the office is noisy in general, offer headphones. Interns don’t do well with telecommuting; they need in-person supervision and reinforcement.</li>
<li>You should be prepared to pay your intern. Although the <a href="http://www.dol.gov/whd/regs/compliance/whdfs71.htm">US government has some rules that permit some internships to be unpaid</a>, the rules are tricky and you’re best off not going that route. If you read the six criteria, they’re pretty vague; and your company can be on the receiving end of a serious lawsuit. Pick a wage and offer something.</li>
<li>You must be excited about your own work before you can bring on an intern. Don’t neglect this! Interns don’t work well unless they have an opportunity to see and share in your passion for your business.</li>
</ul>
<p>When you’ve ensured that your company can support an intern, it’s time to begin searching.</p>
<h3>Acquiring your First Intern</h3>
<p>Internship ads are written differently than traditional job listings. Make it clear that the internship is for a fixed length of time; I prefer three months. This is necessary to be fair to the intern; you need them to know that, at the end of this time period, they will be successfully on their way to the fulltime career they want.</p>
<p>Focus on the rich skills you will teach, the excitement of your business, and explain how your uniquely professional work environment will best prepare the intern for a full career. Limit your “requirements” to general talents, basic knowledge, and motivation; and encourage the candidate to explain to you what sets them apart. For example:</p>
<blockquote><p><i>Mobile Developer Internship &#8211; Foo Inc, the world’s leading developer of Bars, has a three month paid internship position available to help its mobile app development team writing web services and user interface code. During your internship, you’ll learn the most advanced techniques for mobile user interface design from industry heavyweights. Requirements: Familiarity with mobile phones and HTML, a sharp mind, attention to detail, and a commitment to getting the job done.</i></p></blockquote>
<p>Next, let’s get this advertisement in the field. Try to identify five to ten targets for your job posting. Craigslist is one place to start; each advertisement costs $25 and, in my experience, generates a decent response. Don’t forget to post the internship on your website and advertise it on LinkedIn, Facebook, and Twitter. You can also contact the dean of a local university or community college and offer your internship to their students, but be prepared to have your company vetted before you can share listings directly with students.</p>
<p>With the posting in hand, it’s time to begin! Schedule all the ads to start on the same day, and keep up the momentum. Interns only have a brief moment of time when they can consider an internship, so respond quickly, ideally within 24 hours after they send their resume to you. I find it works best to speak to two or three candidates each day by phone, and interview in person about a half dozen top tier candidates.</p>
<p>When you move on to in-person interviews, the goal is to identify three things within about an hour:</p>
<ul>
<li>Does the intern have enough basic knowledge to be useful in a three month window?</li>
<li>Can the intern listen effectively and ask good questions?</li>
<li>Does the intern have the motivation and drive to succeed?</li>
</ul>
<p>When you’ve found a candidate that passes the test, make your pick fast; probably within the first week after interviews start. Let the intern know clearly that you will give them a great opportunity, and in return for their hard work you’ll give them a career.</p>
<h3>Daily Experience</h3>
<p>Once the intern starts, you should monitor them every day and provide the following:</p>
<ul>
<li><strong>A limited but useful amount of mentoring.</strong> You can’t have the intern asking questions every five minutes and sapping the team’s concentration; but neither can you have an intern firing aimlessly when a quick question would get them on target. Tell your intern to ask two really good questions about their project every day.</li>
<li><strong>Tasks that can be completed.</strong> Find simple tasks and get the intern to succeed at those before moving onto more complex and risky tasks. Many interns just need to see the fruits of their labor in use to level up. Gradually increase the task complexity, but only after a task is fully seen through to completion!</li>
<li><strong>Opportunities to shape their own unique career path.</strong> After each task completes, ask them what they liked about it and what they didn’t. Seize every chance to give the intern work they find interesting. I am reminded of Harry Truman’s phrase, “The best way to give advice to your children is to find out what they want and then advise them to do it.”</li>
</ul>
<p>In return, you need to start communicating expectations to the intern. Since many interns come straight out of college or out of a different career path, you may want to explain to them the standards required by your business, such as punctuality, professionalism, office culture, dress codes, HR rules, or adjusting to the workload. Be patient with them, and give them time to cope, but also be clear: meeting the business rules is a condition of the internship.</p>
<p>As work progresses, find opportunities to compliment your intern and gradually expose them to more and more advanced projects. I like to provide about nine compliments for each criticism I give. If you fall far south of that line, perhaps either the intern or your motivational style needs to change. Constructive criticism is your friend; honest and straightforward feedback is a critical necessity for career development. If an intern doesn’t improve after a warning, it’s best to let them move on to a place they can be more successful.</p>
<h3>Ending an Internship</h3>
<p>At the end of three months – or whatever time frame you picked &#8211; you should release your intern. During the last few weeks of the time frame, try to give them general career counseling. Set them up a few meetings where you can answer their questions about jobs in their chosen field.</p>
<p>If you are lucky enough to have a full-time position open that is suitable for the intern, encourage them to apply for the position and give them a proper hearing. Doing so professionally results in a clear transition from intern to employee.</p>
<p>If your business doesn’t have a position available, don’t fret. Hold your intern’s hand up high and celebrate their work. Give them a strong reference, and offer to hand-deliver their information to colleagues you may know at other companies. Take the intern out to lunch to celebrate the launch of a successful career – you’ve both earned it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/18/lessons-learned-from-training-interns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Game Engines for Indies</title>
		<link>http://www.altdevblogaday.com/2012/04/16/game-engines-for-indies/</link>
		<comments>http://www.altdevblogaday.com/2012/04/16/game-engines-for-indies/#comments</comments>
		<pubDate>Mon, 16 Apr 2012 20:42:05 +0000</pubDate>
		<dc:creator>Kyle-Kulyk</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Game design]]></category>
		<category><![CDATA[General Interest]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[game engines]]></category>
		<category><![CDATA[indie]]></category>
		<category><![CDATA[shiva]]></category>
		<category><![CDATA[torque]]></category>
		<category><![CDATA[udk]]></category>
		<category><![CDATA[unity]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25537</guid>
		<description><![CDATA[<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/choices7.jpg"><img class="alignright size-medium wp-image-25543" style="margin: 5px" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/choices7-300x194.jpg" alt="" width="300" height="194" /></a>There&#8217;s a lot of choices when it comes to development tools for indie developers.  As a new developer, we put a lot of thought into which commercial game engine we would license and choose to focus on going forward.  There are a number of engines available that could appeal to indie developers and I thought I’d take a look at some of the top engines out there and offer my opinion based on the research I conducted.  <a title="Itzy Interactive" href="http://itzyinteractive.com/" target="_blank">Itzy Interactive</a> formed with mobile game development in mind and multiplatform development was important to us as we set out to start our business.  We were looking for a “complete package” solution.  <span style="text-decoration: underline"><strong>Bear in mind, I haven’t had the opportunity to work on all the engines mentioned so some of my points are based off the opinions of other developers and fans</strong></span> on various forums and there are certainly other engines available depending on the type of work you&#8217;re attempting.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/16/game-engines-for-indies/" class="more-link">Read more on Game Engines for Indies&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/choices7.jpg"><img class="alignright size-medium wp-image-25543" style="margin: 5px" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/choices7-300x194.jpg" alt="" width="300" height="194" /></a>There&#8217;s a lot of choices when it comes to development tools for indie developers.  As a new developer, we put a lot of thought into which commercial game engine we would license and choose to focus on going forward.  There are a number of engines available that could appeal to indie developers and I thought I’d take a look at some of the top engines out there and offer my opinion based on the research I conducted.  <a title="Itzy Interactive" href="http://itzyinteractive.com/" target="_blank">Itzy Interactive</a> formed with mobile game development in mind and multiplatform development was important to us as we set out to start our business.  We were looking for a “complete package” solution.  <span style="text-decoration: underline"><strong>Bear in mind, I haven’t had the opportunity to work on all the engines mentioned so some of my points are based off the opinions of other developers and fans</strong></span> on various forums and there are certainly other engines available depending on the type of work you&#8217;re attempting.</p>
<p>&nbsp;</p>
<h2>UDK</h2>
<p><a href="http://udk.com/">http://udk.com/</a></p>
<p><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/theballnew4.jpg"><img class="alignright size-medium wp-image-25538" style="margin: 5px" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/theballnew4-300x187.jpg" alt="" width="300" height="187" /></a>Most are familiar with the Unreal Development Kit.  It’s a proven engine that’s been used in a tonne of AAA titles, but how does it fare for indie developers?  The first thing you’ll notice with UDK is the learning curve.  It’s steep.  Developers I’ve spoken to have all expressed this same sentiment, and my own experiences with UDK left me feeling that UDK seemed needlessly complicated.  I had taken a few courses using the UDK in the past and while practice makes perfect, even when I became more familiar with UDK I found I simply didn’t like using it compared to other alternatives.  The second strike is the need to learn Unreal Script.  It’s a fairly straight forward language in my opinion however just that you need be confined to Unreal Script can take away from valuable development time when you’re starting off.</p>
<p>UDK is capable of delivering high quality graphics out of the box but it seems geared towards First Person Shooters (much like CryEngine).  I’ve heard some complain about the difficulties involved in trying to bend UDK to other genres.  FPS games developed with UDK also have a tendency to end up feeling like Unreal Tournament clones.  UDK now supports iOS development in addition to Windows but don’t expect to port your projects over to anything else.</p>
<p>UDK is free for non-commercial use.  Plan on selling your game and you’ll need to fork over $100 with no royalties to worry about until $50,000.  After that, expect to pay a 25% royalty, which when you consider IOS development and the 30% Apple takes, can certainly add up.  UDK is a bit of a sacred cow for some in the development community, but for indie developers it’s big, unwieldy and just limited in supported platforms.  If you’re looking to add your shooter to a saturated shooter market, UDK may work for you but I wouldn’t recommend for smaller teams of developers.</p>
<p>Notable title:  The Ball</p>
<h2>Shiva3D</h2>
<p><img class="alignright size-full wp-image-25539" style="margin: 5px" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/Nesquick-race.gif" alt="" width="156" height="193" /></p>
<div><a href="http://www.stonetrip.com/">http://www.stonetrip.com/</a><br />
The problems with Shiva3d for indie developers start with its lack of a free option and continues with its smaller community size.  Shiva’s community simply isn’t there and for indies, that means few tutorials and support resources.  It may be interesting to keep an eye on Shiva3d as it evolves but indies may want to give this one a pass for now.  Shiva3d is very similar to Unity3D in terms of its available features and offers a variety of build options including Android, iOS, BlackBerry and Wii.  Some developers have commented that Shiva’s layout is unwieldy but everything a developer needs is in there.  Shiva offers good dynamic lighting (but no prebaked lighting solutions), pathfinding and a robust physics engine as well as LUA and C++ support.  It’s also been reported to have lower memory requirements than Unity and tends to be a stable and fast if you can get past its confusing layout.</div>
<div></div>
<div>Notable title:  Nesquik Race.  That’s right.  That’s about all I could find.</div>
<div>
<h2>Unity3d</h2>
<p><a href="http://unity3d.com/">http://unity3d.com/</a></p>
<p><img class="alignright size-medium wp-image-25540" style="margin: 5px" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/GSGOnline-300x156.jpg" alt="" width="300" height="156" />Unity3d is ultimately what my studio decided to go with for our development on Android and iOS platforms and <a title="Itzy3d" href="http://itzyinteractive.com/itzy3d" target="_blank">Itzy3d</a> is our first release on both platforms using the Unity engine.  To me it just seems the complete game solution for indie developers.  What helped sell us on Unity3d was the ease at which you could build your project with a one click button solution to build to different platforms.  Unity3d supports Android builds, Web, iOS, Windows and Mac.  The option for console development exists as well, however you must first jump through the hoops necessary to be recognized by the console makers and then Unity will provide a license per title (similar to UDK).  They also recently added Flash support.  Aside from specific tweaking for things like the way each mobile platform handles their Storekits, the amount of customization necessary to publish on one platform compared to the other seemed minimal.  Programming for Unity3d was also a breeze as Unity3d is able to handle C#, JavaScript and Boo.  One of my pet peeves is having to learn some obscure, scripting language to use a product.</p>
<p>Unity3D also has a robust development community with excellent support from other users sharing scripts and tutorials.  As well, the Unity Asset store has some excellent plugins that can shave weeks off development time and most are reasonably priced.</p>
<p>Although a free license is available, anyone serious about game development will want to shell out for the pro licensing to take advantage of more advanced features, from built-in pathfinding and physics to shadows, occlusion culling and for the ability to strip out all the unrequired assets when creating your builds.  No other fees required.  Unity Pro with the Android Pro and iOS Pro licences will set you back $4500, but if you keep your eyes open it’s not uncommon to see them offer the pro licenses for 20% off.  Still, this is pretty steep for an indie developer starting off, but once you have these upfront costs out-of-the-way, that’s it.  It’s free to try and there are cheaper licenses available.  I would certainly recommend giving it a spin.</p>
<p>Notable title:  Battlestar Galactica Online</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2><img class="alignright size-medium wp-image-25541" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/WorldOfSubways-300x241.jpg" alt="" width="300" height="241" />C4 Engine</h2>
<p><a href="http://www.terathon.com/c4engine/">http://www.terathon.com/c4engine/</a></p>
<p><em>Edit:  In response to comments received, I apologize for including C4 in this discussion.  As I was looking for all-in-one, game engine solutions that included mobile support, C4 was never seriously considered but thrown in to simply inform indie developers of it&#8217;s existence and provide them with a link for further research.  I&#8217;m sure it has it&#8217;s advantages, but for the purpose of this blog it should have never been included as it&#8217;s not an all-in-one type game engine.  For indies not interested in any type of mobile development, C4 may be a viable alternative.  </em></p>
<p>&nbsp;</p>
<h2>Torque</h2>
<p><a href="http://www.garagegames.com/">http://www.garagegames.com/</a></p>
<p><img class="alignright size-medium wp-image-25542" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/torque-pennyarcade-300x186.jpg" alt="" width="300" height="186" />The Torque3D engine was originally based off the Tribes 2 engine from over a decade ago and allows users access to the source code.   While many fondly remember Tribes 2, unfortunately the general consensus seems that Torque hasn’t been able to keep pace, with many complaining about an unchanged engine and broken tools.  Also, like UDK, Torque uses a non-standard scripting language – “Torquescript”.  Generally, Torque is serviceable but most of its features met with a resounding “Meh” on the indie forums.</p>
<p>What Torque has going for it is some nice networking code and a low price, although be warned that Torque3d, Torque2d and Torque2dIOS are all separate programs with separate licenses.  Also, expect to shell out for pretty much everything, from basic tool packs and editors to genre framework packs.  You can easily end up paying hundreds extra for some basic features.  Android support appears non-existent.</p>
<p>Notable title:  Penny Arcade</p>
<h3>Final Thoughts</h3>
<p>By no means is this meant as a complete list of available solutions out there.  Certainly there are other options available with a few geared towards specific types of development and developer skill level but I hope that if you’re considering becoming an independent game developer and are looking for a more complete solution, these summaries will help start you on your way.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/16/game-engines-for-indies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Software Rasterizer Part 1</title>
		<link>http://www.altdevblogaday.com/2012/04/14/software-rasterizer-part-1/</link>
		<comments>http://www.altdevblogaday.com/2012/04/14/software-rasterizer-part-1/#comments</comments>
		<pubDate>Sat, 14 Apr 2012 10:05:37 +0000</pubDate>
		<dc:creator>Simon Yeung</dc:creator>
				<category><![CDATA[Computer Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software rasterizer]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25433</guid>
		<description><![CDATA[<p><strong><span class="Apple-style-span" style="font-size: large">Introduction</span></strong><br />
Software rasterizer can be used for occlusion culling, some games such as <a href="http://www.slideshare.net/guerrillagames/practical-occlusion-culling-in-killzone-3">Killzone 3</a> use this to cull objects.  So I decided to write one by myself. The steps are first to transform vertices to homogenous coordinates, clip the triangles to the viewport and then fill the triangles with interpolated parameters.  Note that the clipping process should be done in homogenous coordinates before the perspective division, otherwise lots of the extra work are need to clip the triangles properly and this post will explain why clipping should be done before the perspective division.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/14/software-rasterizer-part-1/" class="more-link">Read more on Software Rasterizer Part 1&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><strong><span class="Apple-style-span" style="font-size: large">Introduction</span></strong><br />
Software rasterizer can be used for occlusion culling, some games such as <a href="http://www.slideshare.net/guerrillagames/practical-occlusion-culling-in-killzone-3">Killzone 3</a> use this to cull objects.  So I decided to write one by myself. The steps are first to transform vertices to homogenous coordinates, clip the triangles to the viewport and then fill the triangles with interpolated parameters.  Note that the clipping process should be done in homogenous coordinates before the perspective division, otherwise lots of the extra work are need to clip the triangles properly and this post will explain why clipping should be done before the perspective division.</p>
<p><strong><span class="Apple-style-span" style="font-size: large">Points in Homogenous coordinates</span></strong><br />
In our usual Cartesian Coordinate system, we can represent any points in 3D space in the form of (<em>X</em>, <em>Y</em>, <em>Z</em>). While in Homogenous coordinates, a redundant component <em>w</em> is added which resulting in a form of (<em>x</em>, <em>y</em>, <em>z</em>, <em>w</em>). Multiplying any constant (except zero) to that 4-components vector is still representing the same point in homogenous coordinates. To convert a homogenous point back to our usual Cartesian Coordinate, we would multiply a point in homogenous coordinates so that the <em>w</em> component is equals to one:</p>
<div style="text-align: center">(<em>x</em>, <em>y</em>, <em>z</em>, <em>w</em>) -&gt; (<em>x/</em><em>w </em>, <em>y/</em><em>w </em>, <em>z/</em><em>w, 1</em>) -&gt; (<em>X</em>, <em>Y</em>, <em>Z</em>)</div>
<p>In the following figure, we consider the <em>x</em>-<em>w</em> plane, a point (<em>x</em>, <em>y</em>, <em>z</em>, <em>w</em>) is transformed back to the usual Cartesian Coordinates (<em>X</em>, <em>Y</em>, <em>Z</em>) by projecting onto the <em>w</em>=1 plane:</p>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://2.bp.blogspot.com/-dfDLBMv6VG8/T3-_4ZA_SYI/AAAAAAAAAT0/yiY9uJC2Skw/s1600/projectTow1.png"><img src="http://2.bp.blogspot.com/-dfDLBMv6VG8/T3-_4ZA_SYI/AAAAAAAAAT0/yiY9uJC2Skw/s320/projectTow1.png" alt="" width="320" height="208" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">figure 1. projecting point to <em>w</em>=1 plane</td>
</tr>
</tbody>
</table>
<p>The interesting point comes when the <em>w</em> component is equals to zero. Imagine the <em>w</em> component is getting smaller and smaller, approaching zero, the coordinates of point (<em>x/</em><em>w </em>, <em>y/</em><em>w </em>, <em>z/</em><em>w, 1</em>) will getting larger and larger. When <em>w</em> is equals to zero, we can represent a point at infinity.</p>
<p><strong><span class="Apple-style-span" style="font-size: large">Line Segments in Homogenous coordinates</span></strong><br />
In Homogenous coordinates, we still can represent a line segment between two points P<span class="Apple-style-span" style="font-size: xx-small">0</span>= (<em>x</em><span class="Apple-style-span" style="font-size: xx-small">0</span>, <em>y</em><span class="Apple-style-span" style="font-size: xx-small">0</span>, <em>z</em><span class="Apple-style-span" style="font-size: xx-small">0</span>, <em>w</em><span class="Apple-style-span" style="font-size: xx-small">0</span>) and  P<span class="Apple-style-span" style="font-size: xx-small">1</span>= (<em>x</em><span class="Apple-style-span" style="font-size: xx-small">1</span>, <em>y</em><span class="Apple-style-span" style="font-size: xx-small">1</span>, <em>z</em><span class="Apple-style-span" style="font-size: xx-small">1</span>, <em>w</em><span class="Apple-style-span" style="font-size: xx-small">1</span>) in parametric form:</p>
<div style="text-align: center">L= P<span class="Apple-style-span" style="font-size: xx-small">0</span> + t * (P<span class="Apple-style-span" style="font-size: xx-small">1</span>-P<span class="Apple-style-span" style="font-size: xx-small">0</span>),   <span class="Apple-style-span" style="font-size: x-small">where <em>t</em> is within [0, 1]</span></div>
<p>Then we can get a line having the shape:</p>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://3.bp.blogspot.com/-hDsxTEcslcM/T3_EqJVVdXI/AAAAAAAAAT8/KmSDSPQQUYg/s1600/internalLine.png"><img src="http://3.bp.blogspot.com/-hDsxTEcslcM/T3_EqJVVdXI/AAAAAAAAAT8/KmSDSPQQUYg/s320/internalLine.png" alt="" width="320" height="208" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">figure 2. internal line segment</td>
</tr>
</tbody>
</table>
<p>The projected line on <em>w</em>=1 is called internal line segment in the above case.<br />
But what if the coordinates of P<span class="Apple-style-span" style="font-size: xx-small">0</span> and P<span class="Apple-style-span" style="font-size: xx-small">1</span> having the coordinates where <em>w</em><span class="Apple-style-span" style="font-size: xx-small">0</span> &lt; 0 and <em>w</em><span class="Apple-style-span" style="font-size: xx-small">1</span> &gt; 0 ?</p>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://4.bp.blogspot.com/-IS6paGPft8k/T3_GvjeA4uI/AAAAAAAAAUE/Ntx_8hcJ-BE/s1600/externalLine.png"><img src="http://4.bp.blogspot.com/-IS6paGPft8k/T3_GvjeA4uI/AAAAAAAAAUE/Ntx_8hcJ-BE/s320/externalLine.png" alt="" width="320" height="208" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">figure 3. external line segment</td>
</tr>
</tbody>
</table>
<p>In this case, it will result in the above figure, forming an external line segment. It is because the homogenous line segment have the form L= P<span class="Apple-style-span" style="font-size: xx-small">0</span> + t * (P<span class="Apple-style-span" style="font-size: xx-small">1</span>-P<span class="Apple-style-span" style="font-size: xx-small">0</span>), when moving the parameter from <em>t</em>=0 to <em>t</em>= 1, since <em>w</em><span class="Apple-style-span" style="font-size: xx-small">0</span> &lt; 0 and <em>w</em><span class="Apple-style-span" style="font-size: xx-small">1</span> &gt; 0, there exist a point on the homogenous line where <em>w</em>=0. This point is at infinity when projected to the <em>w</em>=1 plane, resulting the projected line segment joining P<span class="Apple-style-span" style="font-size: xx-small">0</span> and P<span class="Apple-style-span" style="font-size: xx-small">1</span> passes through the point at infinity, forming an external line segment.</p>
<p>The figure below shows how points are transformed before and after perspective projection and divided by <em>w</em>:</p>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://4.bp.blogspot.com/-g1H9j5WDenc/T3_gSsZyoII/AAAAAAAAAUU/mtunCiIXOVQ/s1600/regionMapping.png"><img src="http://4.bp.blogspot.com/-g1H9j5WDenc/T3_gSsZyoII/AAAAAAAAAUU/mtunCiIXOVQ/s400/regionMapping.png" alt="" width="400" height="153" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">figure 4. region mapping</td>
</tr>
</tbody>
</table>
<div style="margin: 0px">The blue line shows the viewing frustum, nothing unusual for the region in front of the eye. The unusual things are the points behind the eye. After perspective transformation and projected to <em>w</em>=1 plane, those points are transformed in front of the eye too. So for line segment with one point in front of the eye and the other behind the eye, it would be transformed to the external line segment after the perspective division.</div>
<div style="margin: 0px"><strong><br />
</strong></div>
<div style="margin: 0px"><strong><span class="Apple-style-span" style="font-size: large">Triangles in Homogenous coordinates</span></strong></div>
<div style="margin: 0px">In the last section, we know that there are internal and external line segments after the perspective division, we also have internal and external triangles. The internal triangles are the one that we usually sees. The external triangles must be formed by 1 internal line segment and 2 external line segments:</div>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://4.bp.blogspot.com/-T9LhG5LGq9Q/T3_T528h-TI/AAAAAAAAAUM/bNTggLtACBg/s1600/externalTri.png"><img src="http://4.bp.blogspot.com/-T9LhG5LGq9Q/T3_T528h-TI/AAAAAAAAAUM/bNTggLtACBg/s320/externalTri.png" alt="" width="320" height="208" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">figure 5. external triangle</td>
</tr>
</tbody>
</table>
<p>In the above figure, the shaded area represents the external triangle formed by the points P<span class="Apple-style-span" style="font-size: xx-small">0</span>, P<span class="Apple-style-span" style="font-size: xx-small">1</span> and P<span class="Apple-style-span" style="font-size: xx-small">2</span>. This kind of external triangles may appear after the perspective projection transform. And this happens in our real world too:</p>
<table>
<tbody>
<tr>
<td>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://1.bp.blogspot.com/-OlJYIeUl3cs/T4BbwEDiLoI/AAAAAAAAAUk/v9IdMFQoKTM/s1600/clipTriPhoto.JPG"><img src="http://1.bp.blogspot.com/-OlJYIeUl3cs/T4BbwEDiLoI/AAAAAAAAAUk/v9IdMFQoKTM/s320/clipTriPhoto.JPG" alt="" width="320" height="240" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">an external triangle in real world</td>
</tr>
</tbody>
</table>
</td>
<td>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://3.bp.blogspot.com/-S5jR7k5tLLU/T4Bb1Zp1OCI/AAAAAAAAAUs/ygOz9t773xE/s1600/clipTriPhotoFull.JPG"><img src="http://3.bp.blogspot.com/-S5jR7k5tLLU/T4Bb1Zp1OCI/AAAAAAAAAUs/ygOz9t773xE/s320/clipTriPhotoFull.JPG" alt="" width="240" height="320" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">the full triangle of the left photo</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<p>In the left photo, it shows an external triangle with one of the triangle vertex far behind the camera while the right photo shows the full view of the triangle and the cross marked the position of the camera where the left photo is taken.</p>
<p><strong><span class="Apple-style-span" style="font-size: large">Triangles clipping</span></strong><br />
To avoid the case of external triangles, lines/triangles should be clipped in homogenous coordinates before divided by the <em>w</em>-component. The homogenous point (<em>x</em>, <em>y</em>, <em>z</em>, <em>w</em>) will be tested with the following inequalities:</p>
<div style="text-align: center">(-<em>w </em>&lt;= <em>x </em>&lt;= <em>w</em>) &amp;&amp;   &#8212;&#8212; inequality. 1</div>
<div style="text-align: center">(-<em>w </em>&lt;= <em>y </em>&lt;= <em>w</em>) &amp;&amp;   &#8212;&#8212; inequality. 2</div>
<div style="text-align: center">(-<em>w </em>&lt;= <em>z </em>&lt;= <em>w</em> ) &amp;&amp;   &#8212;&#8212; inequality. 3<br />
<em>w </em>&gt; 0    &#8212;&#8212; inequality. 4</div>
<div>
<div style="text-align: center"></div>
<p>(The <em>z</em> clipping plane inequality is 0<em> </em>&lt;= <em>z </em>&lt;= <em>w</em> in the case for D3D, it depends on how the normalized device coordinates are defined.) Clipping by inequality 1,2,3 will effectively clip all points that with <em>w </em>&lt; 0 because if <em>w </em>&lt; 0, say <em>w </em>= -3:</p>
<div style="text-align: center">3 &lt;= x &lt;= -3     =&gt;     3 &lt;= -3</div>
<div style="text-align: center"></div>
<div style="text-align: left">which is impossible. But the point (0, 0, 0, 0) is still satisfy the first 3 inequalities and forming external cases, so inequality 4 is added. Consider a homogenous line with one end as (0, 0, 0, 0), it will equals to:</div>
<div style="text-align: left"></div>
<div style="text-align: center">L= (0, 0, 0, 0) + t * [ (<em>x</em>, <em>y</em>, <em>z</em>, <em>w</em>) - (0, 0, 0, 0) ] = t * (<em>x</em>, <em>y</em>, <em>z</em>, <em>w</em>)</div>
<p>which represent only a single point in homogenous coordinates. So triangle (after clipped by inequality 1, 2, 3) having one or two vertices with <em>w</em>=0 will result in either a line or a point which can be discarded. Hence, after clipping, no external triangles will be produced when dividing by <em>w-</em>component. To clip a triangle against a plane, the triangle may result in either  1 or 2 triangles depends on whether there are 1 or 2 vertex outside the clipping plane:</p>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://3.bp.blogspot.com/-C4wcagL7YSQ/T3_4q_4-PQI/AAAAAAAAAUc/x3uXbV63UFU/s1600/clipInternalTri.png"><img src="http://3.bp.blogspot.com/-C4wcagL7YSQ/T3_4q_4-PQI/AAAAAAAAAUc/x3uXbV63UFU/s320/clipInternalTri.png" alt="" width="320" height="208" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">figure 6. clipping internal triangles</td>
</tr>
</tbody>
</table>
<p>Then the clipped triangles can be passed to the next stage to be rasterized either by a <a href="http://en.wikipedia.org/wiki/Scanline_rendering">scan line</a> algorithm or by a <a href="http://devmaster.net/forums/topic/1145-advanced-rasterization/">half-space</a> algorithm.</p>
<p>Below is the clipping result of an external triangles with 1 vertex behind the camera.</p>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://1.bp.blogspot.com/-0sruXroYV4E/T4Bd8iwNoZI/AAAAAAAAAU8/N4mkoQLP6KY/s1600/sampleClipExtTri.png"><img src="http://1.bp.blogspot.com/-0sruXroYV4E/T4Bd8iwNoZI/AAAAAAAAAU8/N4mkoQLP6KY/s320/sampleClipExtTri.png" alt="" width="320" height="180" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">clipping external triangle in software rasterizer</td>
</tr>
</tbody>
</table>
<p>Below is another rasterized result:</p>
<table>
<tbody>
<tr>
<td>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://2.bp.blogspot.com/-cQ3S0rT6wI0/T4Beace2MUI/AAAAAAAAAVE/EQYVbccwg5Q/s1600/sampleDuckFill.png"><img src="http://2.bp.blogspot.com/-cQ3S0rT6wI0/T4Beace2MUI/AAAAAAAAAVE/EQYVbccwg5Q/s320/sampleDuckFill.png" alt="" width="320" height="180" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">rasterized duck model</td>
</tr>
</tbody>
</table>
</td>
<td>
<table class="tr-caption-container" style="margin-left: auto;margin-right: auto;text-align: center" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="text-align: center"><a href="http://2.bp.blogspot.com/-gfqOLmsJe1o/T4Beejh4EgI/AAAAAAAAAVM/h7a0yanEe3o/s1600/sampleDuckRef.png"><img src="http://2.bp.blogspot.com/-gfqOLmsJe1o/T4Beejh4EgI/AAAAAAAAAVM/h7a0yanEe3o/s320/sampleDuckRef.png" alt="" width="320" height="180" border="0" /></a></td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center">reference of the duck model</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<p><strong><span class="Apple-style-span" style="font-size: large">Conclusion</span></strong><br />
In this post, the maths behind the clipping of triangles are explained. Clipping should be done before projecting the homogenous point to the <em>w</em>=1 to avoid taking special cares to clip the external triangles. In the next post, I will talk about the perspective interpolation and the source code will be given in the next post (written in  javascript, drawing to html canvas).</p>
<p>And lastly special thanks to Fabian Giesen for giving feedback during the draft of this post.</p>
<p><strong>References</strong><br />
[1] <a href="http://research.microsoft.com/pubs/73937/p245-blinn.pdf">http://research.microsoft.com/pubs/73937/p245-blinn.pdf</a><br />
[2] <a href="http://medialab.di.unipi.it/web/IUM/Waterloo/node51.html">http://medialab.di.unipi.it/web/IUM/Waterloo/node51.html</a><br />
[3] <a href="http://kriscg.blogspot.com/2010/09/software-occlusion-culling.html">http://kriscg.blogspot.com/2010/09/software-occlusion-culling.html</a><br />
[4] <a href="http://www.slideshare.net/guerrillagames/practical-occlusion-culling-in-killzone-3">http://www.slideshare.net/guerrillagames/practical-occlusion-culling-in-killzone-3</a><br />
[5] <a href="http://www.slideshare.net/repii/parallel-graphics-in-frostbite-current-future-siggraph-2009-1860503">http://www.slideshare.net/repii/parallel-graphics-in-frostbite-current-future-siggraph-2009-1860503</a><br />
[6] <a href="http://fgiesen.wordpress.com/2011/07/05/a-trip-through-the-graphics-pipeline-2011-part-5/">http://fgiesen.wordpress.com/2011/07/05/a-trip-through-the-graphics-pipeline-2011-part-5/</a><br />
[7] <a href="http://devmaster.net/forums/topic/1145-advanced-rasterization/">http://devmaster.net/forums/topic/1145-advanced-rasterization/</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/14/software-rasterizer-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Technical Sound Design: An Interview with Damian Kastbauer</title>
		<link>http://www.altdevblogaday.com/2012/04/10/technical-sound-design-an-interview-with-damian-kastbauer/</link>
		<comments>http://www.altdevblogaday.com/2012/04/10/technical-sound-design-an-interview-with-damian-kastbauer/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 22:46:33 +0000</pubDate>
		<dc:creator>Ariel Gross</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Audio]]></category>
		<category><![CDATA[audio design]]></category>
		<category><![CDATA[sound design]]></category>
		<category><![CDATA[technical sound design]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25478</guid>
		<description><![CDATA[<p><em>I caught up with Damian Kastbauer, technical sound designer, in the sticky jungles of the Congo last week. He was questing for the fabled paisley hippopotamus. Legend says that when the paisley hippopotamus is kissed upon its patterned lips, the kisser is granted a treasure of immense value.</em></p>
<p><a href="http://www.altdevblogaday.com/2012/04/10/technical-sound-design-an-interview-with-damian-kastbauer/" class="more-link">Read more on Technical Sound Design: An Interview with Damian Kastbauer&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><em>I caught up with Damian Kastbauer, technical sound designer, in the sticky jungles of the Congo last week. He was questing for the fabled paisley hippopotamus. Legend says that when the paisley hippopotamus is kissed upon its patterned lips, the kisser is granted a treasure of immense value.</em></p>
<p><em>I found him hiding behind a giant leaf, wearing a giant leaf. He was pressing binoculars against his eyes, gazing towards a nearby algae-covered pool. I crouched next to him and started asking him questions.</em></p>
<p><strong>Ariel Gross:</strong> So, Damian, what is it that you do? Aside from questing after fabled beasts of yore?</p>
<p><strong>Damian Kastbauer:</strong> I&#8217;m a technical designer for games, which is a somewhat nebulous term. It&#8217;s defined pretty well by Rob Bridgett in <a title="Rob Bridgett Special - The Role of an Audio Director in Video Games" href="http://designingsound.org/2009/11/rob-bridgett-special-the-role-of-an-audio-director-in-video-games/" target="_blank">this article</a>. Essentially, I try to serve as a bridge between sound content and programming/engine-side integration in order to create systems for sound playback, or just plain getting sounds in the game working and sounding right.</p>
<p><strong>AG: </strong>Nice. My opinion is that sound design in games is only as good as its implementation. What do you think about that?</p>
<p><strong>DK:</strong> It&#8217;s often said that the best sound can end up sounding bad if it&#8217;s not implemented properly, so, a lot of the time I&#8217;m trying to let the sound do its thang&#8230; which is not always easy. Since I don&#8217;t create content, and I&#8217;m not a programmer by definition, I usually spend a lot of time either building tools, streamlining pipelines, and strategizing audio features with the help of the programming team or working with audio middleware tools to similarly create the smoothest integration possible.</p>
<p><em>Damian finally released the binoculars, which then fell and dangled around his neck, but kept his hands in place, and continued to look off towards the pool with his hand-noculars. It was an interesting technique that I had never seen used in the field before. He made a refocusing gesture and continued to peer out through his hand holes.</em></p>
<p><strong>AG:</strong> So&#8230; do you find yourself being a middle man between Team Audio and Team Programming? That could be challenging, what with all the unrequited love and/or red-hot rage between those two disciplines.</p>
<p><strong>DK:</strong> Definitely, I&#8217;m helping to bridge the gap between the two worlds. Whenever possible, I like to enable content designers to just &#8220;design in the box&#8221; all day from the DAW without having to worry about the sometimes-labyrinthine pipeline to get sound into the game. In this way, they can focus on what they&#8217;re really into and I can go to town with making sure it all works within the context of the game. It&#8217;s a balance that requires human interaction, but I&#8217;m pretty keep on that as well.</p>
<p><strong>AG:</strong> Wow, you just said labyrinthine. I&#8217;m golf clapping right now. In my head. And in my heart. I don&#8217;t want to scare off the paisley hippo. You&#8217;re welcome. So, have you found any common issues between Team Audio and Team Programming among multiple developers, and do you take measures to help both sides see eye to eye?</p>
<p><strong>DK:</strong> I think one of the missing or underdeveloped pieces of some studios is the direct communication between Team Audio and the rest of the teams. It&#8217;s common for audio to touch almost every corner of the pipeline and development process.</p>
<p>With Team Audio often sequestered within a sound-proof cave deep within the bowels of a studio, it can be hard to get the kind of happy accident or magic moment that can come from being out in the pit or lined up in a hallway.</p>
<p><strong>AG:</strong> This is painfully true.</p>
<p><strong>DK:</strong> One of the things that has always seemed right about my involvement with different game studios on-site is the necessity of being &#8220;on the floor&#8221; with the other disciplines&#8230; which has always been a positive in bridging that gap.</p>
<p>When I work remotely, I put a tremendous amount of effort into achieving a high level of communication between the different teams on a project. Whether it&#8217;s e-mail, IM, Skype, or occasion on-site visits during development, the communication between people is among the most important aspects of working on a project.</p>
<p>If I am outside the fence, having an on-site advocate for audio is a definite plus, and in most cases, it is key to making my role as a facilitator for sound actually happen.</p>
<p><em>Some foliage near the murky pool began to shake. Damian dropped his hand-noculars and placed one hand over his mouth to ensure complete silence. He placed his other hand over my mouth, too. I resisted the urge to lick his hand. A rabbit bounced from the foliage. We both sighed deeply.</em></p>
<p><strong>AG:</strong> Miv viff fuhm coffm prbflrm&#8230;</p>
<p><em>Damian removed his hand from my mouth.</em></p>
<p><strong>AG:</strong> Is this a common problem at studios you&#8217;ve worked with? That Team Audio doesn&#8217;t pop their heads up through the manhole enough to be part of the greater discussion?</p>
<p><strong>DK:</strong> Whew, well, I think that as a matter of course it is hard to have visibility across the team in the same way as being out in an open floor plan, when part of your daily work requires you to be locked away in a padded room.</p>
<p>That is, people can&#8217;t SEE you and demand your attention by rolling up to your workstation. I mean, there&#8217;s a door&#8230; you have to turn the knob&#8230; like, maybe even knock&#8230; and then get blasted in the face by high decibel explosions in order to interface. We know how averse most people are to moving in the first place, let alone opening a door.</p>
<p><em>I chuckled.</em></p>
<p><strong>DK:</strong> A little dry, mid-west sarcasm for you.</p>
<p><em>I chuckled more, leading to a whole-body belly laugh, leading to a maniacal, snorting cackle, ending finally with a very feminine giggle. Then we sat motionless for what felt like an eternity.</em></p>
<p><strong>AG:</strong> Sorry. What you say is completely true. Before tracking you down in the Congo, I hadn&#8217;t left my seat in four years. Not even to use the restroom. I held it. What you saw at the GDC was my hologram. A hologram with mass. I digress. What is the number one reason why a studio hires a technical sound designer?</p>
<p><strong>DK:</strong> The number one reason I am hired is to help ship games. Having shipped my fair share, I would like to say that I know all the tricks in the book, but this is absolutely not true.</p>
<p>What I hope that I bring to a project is an ability to work together with people to get things done, through thick and thin, regardless of the task at hand.</p>
<p>Sometimes I don&#8217;t even know what I&#8217;m going to be doing until I get involved and assess the situation&#8230; this can be true of the studios as well. They&#8217;re not sure what exactly needs to be done, but they need someone to help pull it off in the eleventh hour.</p>
<p><strong>AG:</strong> You&#8217;re basically a hero that is brought in to save the day.</p>
<p><strong>DK:</strong> If I can come in and take the burden off of content designers, help design complex playback systems for physics or procedural animations, help wrangle memory budgets or streaming look-ahead times, then that is one less thing for someone, who already has too much on their plate, to worry about.</p>
<p>For remote work, it can be at any time during the project, I work from the home studio connected to a VPN using source control while making local builds from day one.</p>
<p>When I do work on-site for an extended period of time, it&#8217;s usually toward the end of a project for a few months.</p>
<p><em>At this moment, the waters of the pool began to ripple as a large, paisley-patterned mound broke the surface of the water. Then, two paisley ears emerged, followed by blinking eyes. Damian fidgeted with </em><em>excitement, but stayed put.</em></p>
<p><strong>AG: </strong>You mentioned memory and streaming.  This is something that some people don&#8217;t realize. Someone on Team Audio is usually tasked with wrangling memory budgets and streaming bandwidth. It&#8217;s really techy work.</p>
<p>This isn&#8217;t always expertise that is considered when hiring an audio designer. I&#8217;ve found that studios tend to focus more on whether or not an applicant can make rad sounds, with less emphasis on the technical side of things.</p>
<p>There&#8217;s usually some requirement that says, &#8220;familiarity with middleware tools and implementation,&#8221; but I get the sense that the weighting at most companies is 80% creative aptitude and 20% technical prowess. Does that seem accurate to you? Or am I totally wrong? And ugly looking?</p>
<p><strong>DK: </strong>I think there are a majority of people who come to studios with a sound design background. Until recently, it has been almost non-existent to have someone come out of school with an education in the technical side of game audio.</p>
<p>It used to be that &#8220;audio implementer&#8221; was the job that someone new to the industry would take on their way to becoming a sound designer&#8230; or even a musician or composer for games&#8230; that was really the only way to learn the ropes.</p>
<p>When I got into games, it was clear to me that the technical side was the only thing that I wanted to do. Thankfully, in the past few years, it has become a niche that has benefited from a group of people whose interests are purely in the technical, which has helped to establish legitimacy for the specialization.</p>
<p><strong>AG: </strong>We used an in-game editor to place ambient audio emitters on Saints Row 2. Sometimes the frame rate would tank while I was moving an ambient emitter around, and I&#8217;d fling the emitter object 100 miles away, sometimes into a different game entirely. I think a few of those emitters landed in Red Faction: Guerrilla.</p>
<p><strong>DK:</strong> Hahaha&#8230; user interface physics lerping&#8230; TOOLS!</p>
<p><strong>AG: </strong>Do you ever find yourself caught up in the mystery of missing sounds? Like, the audio team is sure that a sound should be playing, but it&#8217;s not. Is that something you run into a lot?</p>
<p><strong>DK: </strong>Totally! Someone did a model swap but forgot to bring the audio hooks with it, or moved the entire level geometry across the level away from the audio emitters that were placed on a different layer in the editor&#8230; happens ALL the time, and the resources to figure it out are sometimes underestimated.</p>
<p>With all the different ways that people can approach game audio these days: mods, Unity, UDK, FMOD, Wwise, SDK documents, Max/MSP or pd, it&#8217;s becoming common to have fresh faces joining the team who already have a good handle on the tasks at hand and are ready for the challenge.</p>
<p><em>The fabled paisley beast began to slowly emerge from the algae-covered pool. Watching the water cascade off of it&#8217;s psychedelic hide was glorious. Swirls of color and waves of sweet smells washed over me. Granted, I had also been munching on some random red berries that I&#8217;d found on the ground.</em></p>
<p><strong>AG: </strong>I know plenty of sound designers that don&#8217;t want to do the implementation. They look at it as a boring chore. A chore-bore. A borch. Anyway, I could see some Team Audios out there wanting to hire you on full time. Do you ever get this? Have you considered an in-house gig?</p>
<p><strong>DK: </strong>I&#8217;ve worked remotely on a couple of projects for a longer duration (1-2 years) serving as a conduit for getting content in the game. I&#8217;ve worked a ton with Bay Area Sound as an outsource audio solution involving their audio and music content creation in conjunction with my management of the technical side in what has been a perfect solution for smaller developers and teams that need supplemental assistance.</p>
<p>I worked for five years in this capacity on the games for Telltale. I integrated content provided by Bay Area Sound and Harmony Machine into The Saboteur from Pandemic Studios for about a year to help augment their in-house audio team, which included building vehicle systems in Wwise to work with the simulation team who was responsible for the cars driving around in the open world.</p>
<p>Most recently I&#8217;ve been working again with Bay Area Sound to integrate content and tool the pipeline for a couple of MMOs using the Hero Engine in conjunction with FMOD.</p>
<p><strong>AG: </strong>How about documentation? I have seen with mine own eyes the lack of documentation out there. Do you find yourself having to trudge through undocumented systems a lot? Do you end up documenting them yourself as part of your services?</p>
<p><strong>DK: </strong>Documentation is always a tricky one. A lot of developers who have been iterating on in-house engines and tool sets carry with them a ton of institutional knowledge&#8230; usually within their brains. There&#8217;s usually a pretty intense time of education at the beginning of the project where I do my best to document&#8230; for my own sanity as well as anyone who might find themselves in a similar position in the future.</p>
<p>I recently worked with a company and provided an evaluation of their audio middleware integration in addition to recommendations for how to move forward with some key changes. In that case, it was documentation and justification for the different recommendations, as well as education in order to get everyone thinking about the possibilities.</p>
<p><strong>AG: </strong>Do you find that most companies that you work with have an audio programmer on stand-by to compliment you? Compliment both in terms of assisting you in a complimentary fashion, and also to tell you that your shirt looks very nice tucked in.</p>
<p><strong>DK: </strong>It&#8217;s definitely becoming more common for developers to recognize the need for audio programming support throughout the project. While I think it&#8217;s becoming, I think there is still a false expectation that you can just throw on the UI programmer for a couple of months and sew everything up.</p>
<p>The need for dedicated audio programmers is definitely growing as we continue to scale in meeting the demands in quality during the current generation.</p>
<p>So, I guess, having an audio programmer is necessary to compliment the technical side of sound design, especially a dedicated professional who is invested in sound. Their ability to bring not just programming, but a knowledge of audio to the table can only mean an increase in the quality of the audio and the quality of life for Team Audio.</p>
<p>That, and yeah&#8230; someone to tell me when my dashiki doesn&#8217;t match my socks.</p>
<p><strong>AG: </strong>Last question, and then you can get back to your quest. What do you think will change from a tech audio standpoint with the next generation of consoles?</p>
<p><strong>DK: </strong>I think the industry at large will further close the gap between pre-rendered and in-engine&#8230; across all disciplines, a continuation to move forward into real-time.</p>
<p>What this means for audio is building on the sample-based methodology that has firmly taken root in the current generation while using more procedural audio, synthesis, and DSP to modify or accent sample-based content dynamically at runtime.</p>
<p>Additionally, increased transparency and better communication in both directions between the game audio and audio engines will develop, which will in turn necessitate a further push towards enabling this functionality within usable tool sets. This accessibility will reach into every corner of the audio production pipeline, simultaneously exposing the technology while making it easier to adapt it to the interactive needs of the game.</p>
<p>Hopefully the new consoles will also make espresso.</p>
<p><strong>AG: </strong>Espresso feature would be cool. I&#8217;m hoping that someday I can feed a slice of bologna directly into the console. It would recognize the meat as bologna and procedurally create a game called Bologna Quest, where a young adventurer named Ariel, clad in the finest bologna armour, would climb the mountain of&#8230; Damian?</p>
<p><em>Damian, recognizing that I had started my typical bologna-related sign-off, was already planting a kiss upon the lips of the sleeping paisley hippopotamus. Then, a flash of light, and they both vanished, never to be seen again.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/10/technical-sound-design-an-interview-with-damian-kastbauer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C/C++ Low Level Curriculum Part 7: More Conditionals</title>
		<link>http://www.altdevblogaday.com/2012/04/10/cc-low-level-curriculum-part-7-more-conditionals/</link>
		<comments>http://www.altdevblogaday.com/2012/04/10/cc-low-level-curriculum-part-7-more-conditionals/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 15:46:57 +0000</pubDate>
		<dc:creator>Alex Darby</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[gamedev]]></category>
		<category><![CDATA[low level]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25391</guid>
		<description><![CDATA[<p>Hello humans. Welcome to the 7th part of the C/C++ Low Level Curriculum series I&#8217;ve been writing. This post covers the conditional operator, and switch statements. As per usual I will be showing snippets of C++ code and throwing the corresponding x86 assembler at you (as produced by VS2010) to show you what your high level code is actually doing at the assembler level.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/10/cc-low-level-curriculum-part-7-more-conditionals/" class="more-link">Read more on C/C++ Low Level Curriculum Part 7: More Conditionals&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Hello humans. Welcome to the 7th part of the C/C++ Low Level Curriculum series I&#8217;ve been writing. This post covers the conditional operator, and switch statements. As per usual I will be showing snippets of C++ code and throwing the corresponding x86 assembler at you (as produced by VS2010) to show you what your high level code is actually doing at the assembler level.</p>
<p>Disclaimer: in an ideal world I&#8217;d like to try to avoid assumed knowledge, but keeping up the level of detail in each post that this entails is, frankly, too much work. Consequently I will from now on point you at post 6 as a &#8220;how to&#8221; and then get on with it&#8230;</p>
<p>Here are the backlinks for preceding articles in the series (warning: it might take you a while, the first few are quite long):</p>
<ol>
<li><a href="http://www.altdevblogaday.com/2011/11/09/a-low-level-curriculum-for-c-and-c/" rel="nofollow">http://altdevblogaday.com/2011/11/09/a-low-level-curriculum-for-c-and-c/</a></li>
<li><a href="http://www.altdevblogaday.com/2011/11/24/c-c-low-level-curriculum-part-2-data-types/" rel="nofollow">http://altdevblogaday.com/2011/11/24/c-c-low-level-curriculum-part-2-data-types/</a></li>
<li><a href="http://www.altdevblogaday.com/2011/12/14/c-c-low-level-curriculum-part-3-the-stack/">http://altdevblogaday.com/2011/12/14/c-c-low-level-curriculum-part-3-the-stack/</a></li>
<li><a href="http://www.altdevblogaday.com/2011/12/24/c-c-low-level-curriculum-part-4-more-stack/">http://altdevblogaday.com/2011/12/24/c-c-low-level-curriculum-part-4-more-stack/</a></li>
<li><a href="http://www.altdevblogaday.com/2012/02/07/c-c-low-level-curriculum-part-5-even-more-stack/">http://altdevblogaday.com/2012/02/07/c-c-low-level-curriculum-part-5-even-more-stack/</a></li>
<li><a href="http://www.altdevblogaday.com/2012/03/07/c-c-low-level-curriculum-part-6-conditionals/">http://altdevblogaday.com/2012/03/07/c-c-low-level-curriculum-part-6-conditionals/</a> [see near the top of this post for details on compiling &amp; running the code snippets]</li>
</ol>
<h1>The conditional operator</h1>
<p>I assume that everyone&#8217;s familiar with the conditional operator, also known as the &#8220;question mark&#8221;, or the ternary operator (&#8220;ternary&#8221; because it&#8217;s the only C/C++ operator that takes three operands).</p>
<p>If you&#8217;re not, here&#8217;s a <a href="http://en.wikipedia.org/wiki/%3F:#C.2B.2B">link so you can catch up</a> (I predict that you will be so stoked to find out about it that you will be over-using it within the week).</p>
<p>Personally I heartily approve of the conditional operator when used judiciously, but it&#8217;s not always great for source level debugging because it&#8217;s basically a single line <em>if-else</em> and can be hard to follow in the debugger (in fact I&#8217;ve heard of it being banned under the coding standards at more than one company, but there you are we can&#8217;t all be sane can we?).</p>
<p>Anyway, let&#8217;s have a quick look at it with some code:</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="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;stdafx.h&quot;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> argv<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// the line after this comment is logically equivalent to the following line of code:</span>
    <span style="color: #666666; font-style: italic;">// int iLocal; if( argc &gt; 2 ){ iLocal = 3; }else{ iLocal = 7; }</span>
    <span style="color: #993333;">int</span> iLocal <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>argc <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">?</span> <span style="color: #0000dd;">3</span> <span style="color: #339933;">:</span> <span style="color: #0000dd;">7</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>If you remember the the assembler that a basic <em><strong>if-else</strong></em> generated <a href="http://altdevblogaday.com/2012/03/07/c-c-low-level-curriculum-part-6-conditionals/">in the last article</a>, then the assembler generated here will probably bust your mind gaskets&#8230;</p>
<p>Note:</p>
<ol>
<li>I&#8217;ve deliberately left the function prologue and epilogue out of the asm below, and just left the assembler involved with the conditonal assignment</li>
<li>if your disassembly view doesn&#8217;t show the variable names, then you need to right click the window and check &#8220;Show Symbol Names&#8221;</li>
</ol>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;">     <span style="color: #0000ff;">5</span><span style="color: #339933;">:</span>     <span style="color: #00007f; font-weight: bold;">int</span> iLocal = <span style="color: #009900; font-weight: bold;">&#40;</span>argc &gt; <span style="color: #0000ff;">2</span><span style="color: #009900; font-weight: bold;">&#41;</span> ? <span style="color: #0000ff;">3</span> <span style="color: #339933;">:</span> <span style="color: #0000ff;">7</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">01311249</span>  <span style="color: #00007f; font-weight: bold;">xor</span>         <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span><span style="color: #00007f;">eax</span>
<span style="color: #adadad; font-style: italic;">0131124B</span>  <span style="color: #00007f; font-weight: bold;">cmp</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>argc<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">2</span>
<span style="color: #adadad; font-style: italic;">0131124F</span>  <span style="color: #00007f; font-weight: bold;">setle</span>       <span style="color: #00007f;">al</span>
<span style="color: #adadad; font-style: italic;">01311252</span>  <span style="color: #00007f; font-weight: bold;">lea</span>         <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span><span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">eax</span><span style="color: #339933;">*</span><span style="color: #0000ff;">4</span><span style="color: #339933;">+</span><span style="color: #0000ff;">3</span><span style="color: #009900; font-weight: bold;">&#93;</span>
<span style="color: #adadad; font-style: italic;">01311259</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iLocal<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #00007f;">eax</span></pre></td></tr></table></div>

<p>Clearly this is not very much like the code for the simple if-else that we looked at <a href="http://altdevblogaday.com/2012/03/07/c-c-low-level-curriculum-part-6-conditionals/">previously</a>.</p>
<p>This is because there is trickery afoot and the compiler has chosen to do sneaky branchless code to implement the logic specified by the C++ code.</p>
<p>So, let&#8217;s examine it line by line:</p>
<ul>
<li><em>line 1</em> &#8211; uses the <em><strong>xor</strong></em> instruction to set <strong><em>eax</em></strong> to 0. Anything <a href="http://en.wikipedia.org/wiki/Exclusive_or">XORed </a>with itself is 0.</li>
<li><em>line 2</em> &#8211; as in the previous <strong><em>if</em></strong> examples this uses <em><strong>cmp</strong></em> to test the condition, setting flags in a special purpose CPU register based on the result of the comparison.</li>
<li><em>line 3</em> &#8211; this is a new one! The instruction <em><strong>set</strong><strong>l</strong></em>ess <em><strong>e</strong></em>qual sets its operand to 1 if the 1st operand of the preceding <em><strong>cmp</strong></em> was less than or equal to the 2nd operand, and to 0 if it was greater. We&#8217;ve not seen the operand <em><strong>al</strong></em> before, it&#8217;s a legacy (386) register name which now maps to the lowest byte of the <em><strong>eax</strong></em> register (if you&#8217;re a sensible person and are stepping through this code in your debugger with the register window open, you will see that this instruction causes the <em><strong>eax</strong></em> register to be set to 1 &#8211; also note that this only works because <em><strong>eax</strong></em> has already been set to 0).</li>
<li><em>line 4</em> &#8211; uses the <em><strong>l</strong></em>oad <em><strong>e</strong></em>ffective <em><strong>a</strong></em>ddress instruction do do some sneaky maths that relies on the value of <em><strong>eax</strong></em> set by <em><strong>setle</strong></em> in <em>line 3</em>.</li>
<li><em>line 5</em> &#8211; <em><strong>mov</strong></em>es the value from <em><strong>eax</strong></em> into the memory address storing the value of iLocal</li>
</ul>
<p>That&#8217;s all fine, but how does it work?</p>
<p>Firstly, note that at the assembler level the comparative instruction <em><strong>setle</strong></em> is (as in the previous post&#8217;s examples) testing the opposite condition to the conditonal specified in the C++ code.</p>
<p>This means that the <em><strong>eax</strong></em> register will be set to 0 in <em>line 3</em> if <em><strong>argc</strong></em> is greater than 2, which in turn means that the <em><strong>eax*4+3</strong></em> part of <em>line 4</em> will evaluate to <em><strong>(0*4)+3</strong> </em>- i.e. 3.</p>
<p>Conversely, if <em><strong>argc</strong></em> is less than or equal to 2, the <em><strong>eax</strong></em> register will be set to 1 which in turn means that <em>line 4</em> will evaluate to <em><strong>(1*4)+3</strong> </em>- i.e. 7.</p>
<p>So, as you can see, the assembler is doing the same branchless set of instructions  regardless of the condition, but using the 0 or 1 result of the conditional instruction in the maths to cancel out or include one of the terms and give what I like to call a &#8220;mathematical if&#8221;. Clever.</p>
<p>Incidentally this sort of branchless-but-still-conditional code has been a bit / lot of a hot topic over the last few years, especially on consoles  since their CPUs are particularly branch mis-prediction sensitive.</p>
<p>Judicious use of the &#8220;branchless condtional&#8221; idiom is a tool that can be used to combat branch (mis-)prediction related performance issues &#8211; for an example of this, see the use of the <em><strong>fsel</strong></em> PPU instruction in <a href="http://altdevblogaday.com/2011/11/10/optimisation_lessons/">this ADBAD post by Tony Albrecht</a>, and for brief a discussion of branch prediction issues (primarily PC related) see <a href="http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/">this article</a> by Igor Ostrovsky (who works for Microsoft).</p>
<h1>The conditional operator (part deux)</h1>
<p>So, clearly our above super-simple-sample resulted in the compiler generating clever assembler because of the constant values in it; interesting certainly, but not necessarily representative of most &#8220;real world&#8221; assembler.</p>
<p>Let&#8217;s see what happens if we use variables with the conditional operator&#8230;</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="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;stdafx.h&quot;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> argv<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> iOperandTwo <span style="color: #339933;">=</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> iOperandThree <span style="color: #339933;">=</span> <span style="color: #0000dd;">7</span><span style="color: #339933;">;</span>
    <span style="color: #993333;">int</span> iLocal <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>argc <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">?</span> iOperandTwo <span style="color: #339933;">:</span> iOperandThree<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>And, here&#8217;s the relevant disassembly:</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
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;">     <span style="color: #0000ff;">5</span><span style="color: #339933;">:</span>     <span style="color: #00007f; font-weight: bold;">int</span> iOperandTwo = <span style="color: #0000ff;">3</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00CF1619</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iOperandTwo<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">3</span>
     <span style="color: #0000ff;">6</span><span style="color: #339933;">:</span>     <span style="color: #00007f; font-weight: bold;">int</span> iOperandThree = <span style="color: #0000ff;">7</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00CF1620</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iOperandThree<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">7</span>
     <span style="color: #0000ff;">7</span><span style="color: #339933;">:</span>     <span style="color: #00007f; font-weight: bold;">int</span> iLocal = <span style="color: #009900; font-weight: bold;">&#40;</span>argc &gt; <span style="color: #0000ff;">2</span><span style="color: #009900; font-weight: bold;">&#41;</span> ? iOperandTwo <span style="color: #339933;">:</span> iOperandThree<span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00CF1627</span>  <span style="color: #00007f; font-weight: bold;">cmp</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>argc<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">2</span>
<span style="color: #adadad; font-style: italic;">00CF162B</span>  <span style="color: #00007f; font-weight: bold;">jle</span>         main<span style="color: #339933;">+</span><span style="color: #0000ff;">25h</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">0CF1635h</span><span style="color: #009900; font-weight: bold;">&#41;</span>
<span style="color: #adadad; font-style: italic;">00CF162D</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span><span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iOperandTwo<span style="color: #009900; font-weight: bold;">&#93;</span>
<span style="color: #adadad; font-style: italic;">00CF1630</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #339933;">-</span><span style="color: #0000ff;">50h</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #00007f;">eax</span>
<span style="color: #adadad; font-style: italic;">00CF1633</span>  <span style="color: #00007f; font-weight: bold;">jmp</span>         main<span style="color: #339933;">+</span><span style="color: #0000ff;">2Bh</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">0CF163Bh</span><span style="color: #009900; font-weight: bold;">&#41;</span>
<span style="color: #adadad; font-style: italic;">00CF1635</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #00007f;">ecx</span><span style="color: #339933;">,</span><span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iOperandThree<span style="color: #009900; font-weight: bold;">&#93;</span>
<span style="color: #adadad; font-style: italic;">00CF1638</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #339933;">-</span><span style="color: #0000ff;">50h</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #00007f;">ecx</span>
<span style="color: #adadad; font-style: italic;">00CF163B</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #00007f;">edx</span><span style="color: #339933;">,</span><span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #339933;">-</span><span style="color: #0000ff;">50h</span><span style="color: #009900; font-weight: bold;">&#93;</span>
<span style="color: #adadad; font-style: italic;">00CF163E</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iLocal<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #00007f;">edx</span></pre></td></tr></table></div>

<p>Since the conditional operator is now assigning from variables we&#8217;d expect it to generate something that looks more like the sort of code we saw from the basic<em><strong> if-else</strong></em> we looked at <a href="http://altdevblogaday.com/2012/03/07/c-c-low-level-curriculum-part-6-conditionals/">last time</a>, which it has.</p>
<p>We have the expected <em><strong>cmp</strong></em> followed by a conditional jump testing against the opposite of the conditional, then two blocks of assembler, the first of which (<em>lines 7 to 9</em>) unconditionally jumps over the second (<em>lines 10 and 11</em>) if it executes, so essentially it&#8217;s behaving more or less as expected; however there&#8217;s clearly some interesting stuff happening in there:</p>
<ol>
<li>the two branches use different registers to store their intermediate values; the first uses <em><strong>eax</strong></em>, the second uses <em><strong>ecx</strong></em></li>
<li>both branches store their result to the same memory address in the Stack (see <a href="http://altdevblogaday.com/2011/12/14/c-c-low-level-curriculum-part-3-the-stack/">this post if you don&#8217;t know or can&#8217;t remember about Stack Frames</a>) &#8211; i.e. <em><strong>[ebp-50h]</strong></em></li>
<li>the code that assigns the value to iLocal (<em>lines 12 and 13</em>) only exists once and is executed regardless of which branch was taken; it takes the value from<em><strong>[ebp-50h]</strong></em> and writes it into iLocal using uses a third register (<em><strong>edx</strong></em>)</li>
</ol>
<p>The use of different registers for the different branches in step 1 looks like it might be significant but (according to several expert sources) this is apparently perfectly normal compiler behaviour and not anything to read into.</p>
<p>Steps 2 and 3 show that the that generated from the conditional operator (at least with VS2010) isn&#8217;t directly equivalent to the intuitively equivalent <em><strong>if-else</strong></em> statement:</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: #666666; font-style: italic;">// intuitively equivalent if-else of</span>
<span style="color: #666666; font-style: italic;">// int iLocal = (argc &gt; 2 ) ? iOperandTwo : iOperandThree;</span>
<span style="color: #993333;">int</span> iLocal<span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> argc <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">2</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    iLocal <span style="color: #339933;">=</span> iOperandTwo<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">else</span>
<span style="color: #009900;">&#123;</span>
    iLocal <span style="color: #339933;">=</span> iOperandThree<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Rather than choosing between one of two assignments like this <em><strong>if-else</strong></em>, the assembler generated for our use of the conditional operator does exactly what we told it to: choose one of two values (store it temorarily in the Stack) and assign iLocal from it.</p>
<p>A few final notes on the ? operator:</p>
<ol>
<li>You can see that less lines of C++ code does not equate to less assembler</li>
<li>It can be nested, but don&#8217;t do it! It&#8217;s hideous and will also be very hard to follow when source-level debugging</li>
<li>Be very careful with operator precedence when using it. Use brackets to ensure it will resolve the way you intend.</li>
</ol>
<h1>Switch Statements</h1>
<p>The final type of conditional statement we&#8217;ll be looking at is the switch statement. Like the conditional operator, the switch statement is an often abused and maligned construct that you wouldn&#8217;t want to live without.</p>
<p>To be fair to the switch statement it&#8217;s not the fault of the switch statement that it&#8217;s possible for maniacs to write brittle and insane code using them.</p>
<h2>An aside about switch statements</h2>
<p>Where I have consistently found really horrific examples of switch statements is when an originally stateless synchronous system has been forced to become asyncronous and state driven under time pressure. This specific situation seems always to somehow spawn the kind of monolithic, hard to follow, difficult to change, architecturally brittle switch statements that have given the switch statement a bad rep over the years.</p>
<p>Code that has had network functionality retrofitted to it is (in my experience) an extremely common place to find problem switch statements. It&#8217;s always better to fix a system properly if it starts to look systemically broken than it is to soldier on regardless, and if it looks like you need to introduce a set of states into a system to then (in my experience) it&#8217;s architecturally more sensible to use polymorphic behaviour (e.g. a state class with one or more virtual functions) than a switch statement.</p>
<h2>Where were we?</h2>
<p>Sorry, let&#8217;s get on and take a look at a switch statement&#8230;</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
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;stdafx.h&quot;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> argv<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// n.b. no &quot;break&quot; in case 1 so we can</span>
    <span style="color: #666666; font-style: italic;">// see what &quot;fall through&quot; looks like</span>
    <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span> argc <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">:</span>
        iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">6</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">:</span>
        iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">7</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">:</span>
        iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
        iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">9</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>And here&#8217;s the disassembly&#8230;</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
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;">     <span style="color: #0000ff;">9</span><span style="color: #339933;">:</span>     switch<span style="color: #009900; font-weight: bold;">&#40;</span> argc <span style="color: #009900; font-weight: bold;">&#41;</span>
<span style="color: #adadad; font-style: italic;">00C61620</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #00007f;">eax</span><span style="color: #339933;">,</span><span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>argc<span style="color: #009900; font-weight: bold;">&#93;</span>
<span style="color: #adadad; font-style: italic;">00C61623</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #339933;">-</span><span style="color: #0000ff;">48h</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #00007f;">eax</span>
<span style="color: #adadad; font-style: italic;">00C61626</span>  <span style="color: #00007f; font-weight: bold;">cmp</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #339933;">-</span><span style="color: #0000ff;">48h</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">1</span>
<span style="color: #adadad; font-style: italic;">00C6162A</span>  <span style="color: #00007f; font-weight: bold;">je</span>          main<span style="color: #339933;">+</span><span style="color: #0000ff;">2Ah</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">0C6163Ah</span><span style="color: #009900; font-weight: bold;">&#41;</span>
<span style="color: #adadad; font-style: italic;">00C6162C</span>  <span style="color: #00007f; font-weight: bold;">cmp</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #339933;">-</span><span style="color: #0000ff;">48h</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">3</span>
<span style="color: #adadad; font-style: italic;">00C61630</span>  <span style="color: #00007f; font-weight: bold;">je</span>          main<span style="color: #339933;">+</span><span style="color: #0000ff;">31h</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">0C61641h</span><span style="color: #009900; font-weight: bold;">&#41;</span>
<span style="color: #adadad; font-style: italic;">00C61632</span>  <span style="color: #00007f; font-weight: bold;">cmp</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ebp</span><span style="color: #339933;">-</span><span style="color: #0000ff;">48h</span><span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">5</span>
<span style="color: #adadad; font-style: italic;">00C61636</span>  <span style="color: #00007f; font-weight: bold;">je</span>          main<span style="color: #339933;">+</span><span style="color: #0000ff;">3Ah</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">0C6164Ah</span><span style="color: #009900; font-weight: bold;">&#41;</span>
<span style="color: #adadad; font-style: italic;">00C61638</span>  <span style="color: #00007f; font-weight: bold;">jmp</span>         main<span style="color: #339933;">+</span><span style="color: #0000ff;">43h</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">0C61653h</span><span style="color: #009900; font-weight: bold;">&#41;</span>
    <span style="color: #0000ff;">10</span><span style="color: #339933;">:</span>     <span style="color: #009900; font-weight: bold;">&#123;</span>
    <span style="color: #0000ff;">11</span><span style="color: #339933;">:</span>     case <span style="color: #0000ff;">1</span><span style="color: #339933;">:</span>
    <span style="color: #0000ff;">12</span><span style="color: #339933;">:</span>         iLocal = <span style="color: #0000ff;">6</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00C6163A</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iLocal<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">6</span>
    <span style="color: #0000ff;">13</span><span style="color: #339933;">:</span>     case <span style="color: #0000ff;">3</span><span style="color: #339933;">:</span>
    <span style="color: #0000ff;">14</span><span style="color: #339933;">:</span>         iLocal = <span style="color: #0000ff;">7</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00C61641</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iLocal<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">7</span>
    <span style="color: #0000ff;">15</span><span style="color: #339933;">:</span>         <span style="color: #000000; font-weight: bold;">break</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00C61648</span>  <span style="color: #00007f; font-weight: bold;">jmp</span>         main<span style="color: #339933;">+</span><span style="color: #0000ff;">4Ah</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">0C6165Ah</span><span style="color: #009900; font-weight: bold;">&#41;</span>
    <span style="color: #0000ff;">16</span><span style="color: #339933;">:</span>     case <span style="color: #0000ff;">5</span><span style="color: #339933;">:</span>
    <span style="color: #0000ff;">17</span><span style="color: #339933;">:</span>         iLocal = <span style="color: #0000ff;">8</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00C6164A</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iLocal<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">8</span>
    <span style="color: #0000ff;">18</span><span style="color: #339933;">:</span>         <span style="color: #000000; font-weight: bold;">break</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00C61651</span>  <span style="color: #00007f; font-weight: bold;">jmp</span>         main<span style="color: #339933;">+</span><span style="color: #0000ff;">4Ah</span> <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">0C6165Ah</span><span style="color: #009900; font-weight: bold;">&#41;</span>
    <span style="color: #0000ff;">19</span><span style="color: #339933;">:</span>     default<span style="color: #339933;">:</span>
    <span style="color: #0000ff;">20</span><span style="color: #339933;">:</span>         iLocal = <span style="color: #0000ff;">9</span><span style="color: #666666; font-style: italic;">;</span>
<span style="color: #adadad; font-style: italic;">00C61653</span>  <span style="color: #00007f; font-weight: bold;">mov</span>         <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span> <span style="color: #009900; font-weight: bold;">&#91;</span>iLocal<span style="color: #009900; font-weight: bold;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">9</span>
    <span style="color: #0000ff;">21</span><span style="color: #339933;">:</span>         <span style="color: #000000; font-weight: bold;">break</span><span style="color: #666666; font-style: italic;">;</span>
    <span style="color: #0000ff;">22</span><span style="color: #339933;">:</span>     <span style="color: #009900; font-weight: bold;">&#125;</span></pre></td></tr></table></div>

<p>This is more or less exactly what you&#8217;d expect:</p>
<ul>
<li><em>line 1</em> stores <em><strong>argc</strong></em> into the Stack at <em><strong>[ebp-48h]</strong></em></li>
<li>then block from <em>line 2 to 9</em> implements the logic of the <em><strong>switch</strong></em> by a series of comparisons of this value against the constants specified in the <em><strong>case</strong></em> statements and associated conditional jumps to the assembler generated by the code in the corresponding <em><strong>case</strong></em> statement</li>
<li>if none of the conditional jumps are triggered, the logic causes an unconditional jump to the <em><strong>default:</strong></em> case.</li>
<li>in particular, note that:</li>
</ul>
<blockquote>
<ol>
<li>wherever the <em><strong>break</strong></em> keyword is used this causes an unconditional jump past the end of the assembler generated by the switch</li>
<li>the &#8220;drop through&#8221; from <em><strong>case 1:</strong></em> into <em><strong>case 3:</strong></em> in the high level code happens at the assembler level as a by product of the organisation of the adjacent blocks of instructions generated for the <em><strong>switch</strong></em> by the compiler, and the lack of unconditional jump at the end of the assembler for <em><strong>case 1:</strong></em></li>
</ol>
</blockquote>
<p>If you look at assembler from the sample <em><strong>if-else-if-else</strong></em> in the <a href="http://altdevblogaday.com/2012/03/07/c-c-low-level-curriculum-part-6-conditionals/">last article</a>; you should be able to see that the assembler generated for this switch is (more or less) what would happen if we had written the switch as an <em><strong>if-else-if-else</strong></em> and then re-organised the assembler so all the logic was in one place at the top, and the assembler generated for each code block was left where it was.</p>
<p>So other than the fact that the <em><strong>switch</strong></em> statement is a very useful C/C++ language convenience for managing what would often otherwise be messy looking and error prone chains of <em><strong>if-else-if-else</strong></em> statements, based on this example it doesn&#8217;t appear to be doing anything which might offer a significant advantage at the assembler level &#8211; so why would I have claimed that the compiler might generate &#8220;pretty cool assembler&#8221; for a <em><strong>switch</strong></em>?</p>
<p>Before we assume we&#8217;ve seen it all, let&#8217;s try using a contiguous range of values for the constants in the <em><strong>case</strong></em>s of the <em><strong>switch</strong></em>. You know, just for fun &#8211; and for the sake of simplicity let&#8217;s start at 0.</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
19
20
21
22
23
24
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &quot;stdafx.h&quot;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">*</span> argv<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span> argc <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">:</span>
        iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">:</span>
        iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">:</span>
        iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">6</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">3</span><span style="color: #339933;">:</span>
        iLocal <span style="color: #339933;">=</span> <span style="color: #0000dd;">7</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>And here&#8217;s the disassembly it generates&#8230;</p>
<p><em><strong><span style="color: #ff0000"><a href="http://www.altdevblogaday.com/wp-content/uploads/2012/04/CLLC_7ConditionalsTwo_ContiguousCaseSwitch.png"><img class="alignnone size-full wp-image-25447" src="http://www.altdevblogaday.com/wp-content/uploads/2012/04/CLLC_7ConditionalsTwo_ContiguousCaseSwitch.png" alt="" width="784" height="573" /></a></span></strong></em></p>
<p>Ok, so this time something more interesting is definitely going on &#8211; n.b. I&#8217;ve used a screenshot rather than just pasting the text because we need to look in a memory window to make sense of it.</p>
<p>So what exactly is it doing?</p>
<ul>
<li>it <em><strong>mov</strong></em>es <em><strong>argc</strong></em> into <em><strong>eax,</strong></em> then stores it into the Stack at <em><strong>[ebp-48h]</strong></em></li>
<li>it then <em><strong>c</strong></em>o<em><strong>mp</strong></em>ares the value stored in the address <em><strong>[ebp-48h]</strong></em> with 3 (i.e. our maximum case constant)</li>
<li>if this value is greater than 3 then<em><strong> ja</strong></em> (jump above) on the next line will cause execution to jump to <em><strong>8D1658</strong><strong>h</strong></em> &#8211; the 1st instruction after the code generated by the case blocks, skipping the switch</li>
<li>if the value is less than or equal to 3 then the value is <em><strong>mov</strong></em>ed into <em><strong>ecx</strong></em>, and we then have an unconditional <em><strong>j</strong></em>u<em><strong>mp</strong></em> to &#8230; somewhere :-/</li>
</ul>
<p>Ok, so that final unconditional jump has some syntax we&#8217;ve not yet seen for its address operand, and which clearly isn&#8217;t a constant:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="asm" style="font-family:monospace;"><span style="color: #00007f; font-weight: bold;">jmp</span>    <span style="color: #000000; font-weight: bold;">dword</span> <span style="color: #000000; font-weight: bold;">ptr</span>    <span style="color: #009900; font-weight: bold;">&#40;</span><span style="color: #0000ff;">1B1664h</span><span style="color: #009900; font-weight: bold;">&#41;</span><span style="color: #009900; font-weight: bold;">&#91;</span><span style="color: #00007f;">ecx</span><span style="color: #339933;">*</span><span style="color: #0000ff;">4</span><span style="color: #009900; font-weight: bold;">&#93;</span></pre></td></tr></table></div>

<p>This says &#8220;jump to the location stored in the memory address at an offset of 4 times the value of <em><strong>ecx</strong></em> from the memory address <em><strong>8D1664h</strong></em>&#8220;, so how is this implementing the logic of the C++ switch statement?</p>
<p>To answer this question we need to look in a memory window at the address <em><strong>8D1664h</strong></em> (n.b. to open a memory window from the menu in VS2010 when debugging go Debug -&gt; Windows -&gt; Memory -&gt; &#8230; and choose one of the memory windows. To set the address just copy and paste it from the disassembly into the &#8220;Address:&#8221; input box. You will also need to right click and choose &#8220;4-byte integer&#8221; and set the &#8220;Columns:&#8221; list box to 1 to have it look like the screenshot above).</p>
<p>So, if you cast your eyes up to the memory window on the left of the screenshot above, you will see that the top 4 rows are highlighted, these values start at address <em><strong><em><strong>8D1664h</strong></em></strong></em> and are 4 byte integers (hence the <em><strong>ecx</strong><strong>*4</strong></em> in the operand) &#8211; which specifically in this case are pointers.</p>
<p>The instruction <em><strong>jmp dword ptr (8D1664h)[ecx*4]</strong></em> will <em><strong>j</strong></em>u<em><strong>mp</strong></em> to the value stored in the address:</p>
<ul>
<li><em><strong><em><strong>8D1664h </strong></em>+ 0</strong></em> = <em><strong><em><strong>8D1664h</strong></em></strong></em> if the value in <em><strong>ecx</strong></em> is 0</li>
<li><em><strong></strong></em><em><strong>8D1664h</strong> <strong>+ 4 </strong></em> = <em><strong><em><strong>8D1668h </strong></em></strong></em>if the value of <em><strong>ecx</strong></em> is 1</li>
<li><em><strong>8D1664h</strong> <strong>+ 8 </strong></em> = <em><strong><em><strong>8D166Ch </strong></em></strong></em>if the value of <em><strong>ecx</strong></em> is 2</li>
<li><em><strong>8D1664h</strong> <strong>+ Ch </strong></em> = <em><strong><em><strong>8D1670h </strong></em></strong></em>if the value of <em><strong>ecx</strong></em> is 3</li>
</ul>
<p>So, the four highlighted rows make up a jump table &#8211; since our <em><strong>case</strong></em> constant&#8217;s range is from 0 to 3 it is an array of 4 pointers &#8211; with each element of the array pointing to the execution address of the <em><strong>case</strong></em> block matching its array index.</p>
<p>You can verify this by checking the addresses of the first instruction generated for each <em><strong>case</strong></em> against the 4 values stored in the array.</p>
<p>Maybe it&#8217;s just me, but I think this is some pretty cool assembler. It&#8217;s certainly more elegant that the assembler generated by the first <em><strong>switch</strong></em> we looked at, but what &#8211; if anything &#8211; is the advantage of this over the assembler that was generated for the previous case statement?</p>
<p>In theory this jump table form reaches the code in constant time for all <em><strong>case</strong></em>s, whereas in the <em><strong>if-else-if-else</strong></em> form the time to reach the code corresponding to each <em><strong>case</strong></em> will be proportional to the number of previous <em><strong>case</strong></em>s in the switch statement.</p>
<p>You&#8217;re pretty unlikely to find that a switch statement is a performance bottleneck in your code (unless you&#8217;ve done <a href="http://stackoverflow.com/questions/927403/overhead-of-a-switch-statement-in-c">something silly</a>) but, all things being equal, the jump table appoach uses less instructions to get to the conditional which is normally A Good Thing and &#8211; in theory &#8211; should make it faster on average.</p>
<p>One final note on <em><strong>switch</strong></em> statements; I am reliably informed that in addition to the <em><strong>if-else-if-else</strong></em> alike linear search behaviour for resolving the correct case to execute, most modern compilers are also capable of generating a <a href="http://en.wikipedia.org/wiki/Binary_search">binary search</a> for the <em><strong>case</strong></em>s of switch statements with appropriate ranges of case constant values.</p>
<p>Using a binary search rather than a linear search will improve average search time from linear to logarithmic (i.e. O(n) to O(log n)). However, in the average case a binary searched <em><strong>switch</strong></em> will still almost always take more instructions and branches to reach the correct case than a jump table switch.</p>
<p>It&#8217;s also possible that the compiler might choose to use one or more of these methods in a single switch, though this would probably require a large number of cases in the switch and ranges of case constants with very specific properties so it&#8217;s not likely you will come across these very often.</p>
<p>A couple of final things to note about switch statements:</p>
<ol>
<li>the compiler should be able to generate a jump table regardless of the order in of the constants in your code (e.g. case 2: &#8230; case 1: &#8230; case 3: &#8230; should still work fine)</li>
<li>having a range of case constants that starts at 0 makes the conditional code around a jump table simpler, as it removes the lower bounds check</li>
<li>a jump table should get created as long as the overall range of constants is large enough and/or closely packed enough for the compiler to decide it&#8217;s worthwhile even if they&#8217;re not completely contiguous. Look at the disassembly if you want to check.</li>
</ol>
<h1> Summary</h1>
<p>So, this concludes our look at conditionals, hopefully you&#8217;ve found it interesting and illuminating ;)</p>
<p>A final point to take away from our look at conditionals is that whilst the compiler <em>could</em> generate the same assembler for an <em><strong>if-else</strong></em> as for the <em><strong>conditional</strong></em> operator it doesn&#8217;t. Similarly, it could generate the same assembler from an <em><strong>if-else-if-else</strong></em> as for a  <em><strong>switch</strong></em> statement but it doesn&#8217;t do that either.</p>
<p>In part, this shows the limits of the compiler but also shows the importance of using the appropriate conditional for purpose &#8211; the benefit is that which you use makes your intent clearer to <em><strong>human</strong></em> readers of your code.</p>
<p>We&#8217;ve now covered enough ground that you should be finding that you can apply the information I&#8217;ve given you to everyday programming problems such as debugging release code, or code you don&#8217;t have debugging information for.</p>
<p>The main things I&#8217;d like you to take away from our look at conditionals are all things that will help you when debugging without symbols:</p>
<ol>
<li>anytime you see <em><strong>cmp</strong></em> followed by a <em><strong>j</strong><strong>xx</strong></em> to a nearby address in the disassembly you&#8217;re probably looking at code generated by a conditional statement in the C/C++ code</li>
<li>if the address operand to the jump instruction is lower than the current instruction&#8217;s address (i.e. it&#8217;s jumping backwards) you&#8217;re most likely looking at a loop</li>
<li>assembler generated from conditionals generally tests the opposite of the test being done in the C / C++ code</li>
</ol>
<p>By using these heuristics, looking at the values in the registers, the values in the Stack that have been written by the assembler, and by looking up your current address in the symbol file to tell you which function you&#8217;re in (if you&#8217;re not generating a symbol file for all your builds you should be &#8211; look in the documentation for your platform&#8217;s compiler toolchain to find out how) you should be able to make an educated guess at what variables in the C/C++ code are likely to be causing the current issue and this will usually tell you why it crashed, or give you a lead so you can Sherlock Holmes your way to the root of the problem &#8211; it&#8217;s certainly a lot quicker than the ubiquitous insertion of the many printf()&#8230;</p>
<p>Our next topic will be loops, which obviously also use conditional jumps (which is why we covered conditionals first&#8230;)</p>
<h1>One final thing&#8230;</h1>
<p>Thanks to Tony, Bruce, and Fabian for extra information, advice, and proof reading.</p>
<p>And, for those of you who like to go off and look for yourselves (hopefully most of you!), I&#8217;ve recently discovered this wiki book on x86 Assembler <a href="http://en.wikibooks.org/wiki/X86_Assembly">http://en.wikibooks.org/wiki/X86_Assembly</a>. It has a large overlap with this series of articles and also covers programming in x86 assembler. Highly recommended &#8211; I&#8217;ve certainly found it pretty useful.</p>
<p>A final, final nugget of wisdom from Bruce Dawson:<em><strong></strong></em></p>
<blockquote><p>Another problem I&#8217;ve seen with ?: is with people who have &#8216;cleverly&#8217; created string classes that both have a const char* constructor and a const char* conversion operator. This has potential to be exquisitely dangerous and exquisitely inefficient, by allowing lots of hidden conversions. These come to their fruition with ?:. Imagine this:</p>
<p>return bFlag ? mStringObject : &#8220;Hello world&#8221;;</p>
<p>The question is, what is the type of this expression? Does mStringObject get converted to a const char*, or does &#8220;Hello world&#8221; get converted to a string object? I have no idea, and nobody should memorize the relevant rules. Such code is too fragile and dangerous.</p>
<p>Some people might assume that the type of the ?: will depend on the return type of the function but that is not true. They are independent. Thus, it is quite possible that &#8220;Hello world&#8221; will be converted to a string object and then (if the return type of the function is const char*) this (temporary!!!) string object will be converted back to a const char*. In addition to being inefficient this leads to undefined behavior, since we are returning a pointer to memory owned by an object that is destroyed as the function exits.</p>
<p>Using the ?: operator with mismatched types is evil evil evil. String classes with a const char* conversion operator are evil evil evil. Putting them together&#8230; priceless.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/10/cc-low-level-curriculum-part-7-more-conditionals/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Past the Past Pastel Dreams</title>
		<link>http://www.altdevblogaday.com/2012/04/09/past-the-past-pastel-dreams/</link>
		<comments>http://www.altdevblogaday.com/2012/04/09/past-the-past-pastel-dreams/#comments</comments>
		<pubDate>Mon, 09 Apr 2012 14:28:07 +0000</pubDate>
		<dc:creator>Claire Blackshaw</dc:creator>
				<category><![CDATA[Game design]]></category>
		<category><![CDATA[game design]]></category>
		<category><![CDATA[old mechanics]]></category>

		<guid isPermaLink="false">http://www.altdevblogaday.com/?p=25441</guid>
		<description><![CDATA[<p>Take a moment, think back, past the nostalgia and sepia dreams so we can consider old, forgotten mechanics. The thing we love about games is that they are complex and detailed but primarily, they are games. Systems of interaction and exploration within a created framework. All creative works evolve, compete, succeed and in some cases die out.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/09/past-the-past-pastel-dreams/" class="more-link">Read more on Past the Past Pastel Dreams&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Take a moment, think back, past the nostalgia and sepia dreams so we can consider old, forgotten mechanics. The thing we love about games is that they are complex and detailed but primarily, they are games. Systems of interaction and exploration within a created framework. All creative works evolve, compete, succeed and in some cases die out.</p>
<p>Though within these sepia dreams and old memories live viable mechanics which when re-examined and explored anew provide exciting areas of creativity.</p>
<p>Among the games of my youth three digital games stand tall, in order played: <em>Hero’s Quest: So You Want to be a Hero<sup>[1]</sup></em>, <em>X-Com: Terror from the Deep </em>and <em>Shadowrun </em>on Sega Megadrive. Now some of these games have seen reboots or attempts at reboots which quite frankly angered fans and often missed the point. Thankfully through Kickstarter for <em>Shadowrun </em>and Firaxis for <em>X-Com </em>these two titles are getting a modern, caring treatment and re-examination.</p>
<h3>X-Com Squad Turns</h3>
<p>Many people passed over the unique quality of team-based turns. There have been many other games in the tactical genre but few have explored this idea of &#8220;I move all my units, then you move all your units&#8221;. This concept of moving multiple units simultaneously thus requiring a session of planning which manifests as a massive investment.</p>
<p>As control is taken away from the player, breaking a golden rule to strengthen this mechanic, a high point of tension is created as the plan unfolds.</p>
<p>Of interest to modern designers is that this investment, planning and then tension as you take away control from the player. For a modern interpretation with a different angle I suggest looking at <em>Frozen Synapse</em>. The turns are simultaneous and you plan 5 seconds increments but once again, control is taken away from the player as they watch the consequences of their plans.</p>
<blockquote><p>
Golden Rule Broken: Taking Control Away from the Player
</p></blockquote>
<h3>Shadowrun Hacking</h3>
<p>Almost a fully fledged game within the game but with deep seated roots in the core gameplay. So often “hacking” or another core ability is thrown in as a tangential mini-game. With limited or no interaction with the core-gameplay other than a binary outcome of success or failure. This follows the premise of not creating a game mode shift for the player and avoiding a development investment in what is essentially a “second game”.</p>
<p>Older games were much bolder in this. In <em>Shadowrun </em>hacking you hunted down better hacking decks with a whole subset of stats which could be upgraded. The camera shifted from isometric to third person over the shoulder with new UI and controls. You built contacts and went on missions to acquire that “better piece of software” or that “underground deck”. Your decker’s point of access, which related to hacking difficulty, is determined by their physical entry point into the system. Individual nodes on the hacking map relate to camera systems or subsystems of the physical security system. Triggering the alert system or disabling it, affect the real world alarm systems.</p>
<p>That massive investment in an alternate game mode layered on top of the primary mode added massive levels of depth to the world and further fleshed out the game. Looking for modern alternatives I was unable to find a good modern execution of this concept.</p>
<blockquote><p>
Golden Rule Broken: Avoid Gameplay Mode Shifts<br />
Alternate Expression: Focus on a consistent experience.
</p></blockquote>
<h3>Time Based Gameplay</h3>
<p>In <em>Quest for Glory</em> many moments of interaction were determined by time of day or the day of the week. This occasionally meant as a player you were running around waiting for an event to happen or cleaning out the stables to earn some coins and some time. While some modern games have integrated NPCs timetables much more complex than their predecessors, they have been made insignificant by removing their game altering potential and turning them into minor points of flavour.</p>
<p>The depth of gameplay this added to the world was significant. You had to work around a real world. As a side note the fact the game required you to grind some monsters or chores like stable sweeping to earn your coin allowed you to effectively use your downtime. In <em>Skyrim </em>I can wake up a town blacksmith and purchase armour, removing all gameplay impact of the town schedule. This mechanic lives on in many modern games but in our fear of inconveniencing the player it has been neutered. I encourage designers to look at the gameplay affecting elements this play style offers.</p>
<blockquote><p>Golden Rule Broken: Never Inconvenience the Player<br />
Alternate Expression: Never waste the players time</p></blockquote>
<h3>Mixing it Up</h3>
<p><em>Quest for Glory</em> additionally mixed combat, role playing, adventure elements while providing multiple solution paths gto many problems. Environmental storytelling, usage based levelling and many other elements which have survived into modern design lexicons.<em></em></p>
<p><em>X-Com</em> famously mixed the tactical and geoscape layer in a very complex interwoven gameplay. Though as <em>Brendon Chung</em>&#8216;s GDC talk into his trouble with <em>Atom Zombie Smashers</em> highlighted this is not a simple task. I’ve also already talked about the <em>Shadowrun</em> hacking element as another example. For modern designers still bravely exploring mixing of genre and mechanics you do have to look outside mainstream metric focused development. Though I worry that their lack of polish and budget in many cases restricts their ability to smooth out the seams and truly integrate genres.<em></em></p>
<blockquote><p>
Golden Rule Broken: Keep It Simple Stupid (KISS)
</p></blockquote>
<h3>Conclusion</h3>
<p>As many of these older mechanics show, breaking what we consider a golden rule today can sometimes be key to development of an interesting mechanic. These are just a few picked examples from these games. Many other elements exist in these older games which have been gathering dust.</p>
<p>Many of these older mechanics first came about due to technical limitation and were discarded with the limitation. Our Golden Rules were not forged by the gaming gods but discovered through trial,error and exploration. Some of them may lead to an evolutionary dead end in design, an appendix when no longer needed. I encourage you to mine old games. Not for the IP, nostalgia, or history but for the game. Uncovering the hidden machinery of the past, broken paths and discarded branches of game evolution for old and interesting ideas that can be made new again.</p>
<p>[1] Later renamed to <em>Quest for Glory: So you want to be a Hero </em>to avoid confusion with another game, <em>Hero Quest</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/09/past-the-past-pastel-dreams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TDD for legacy code, graphics code, and legacy graphics code?</title>
		<link>http://www.altdevblogaday.com/2012/04/08/tdd-for-legacy-code-graphics-code-and-legacy-graphics-code/</link>
		<comments>http://www.altdevblogaday.com/2012/04/08/tdd-for-legacy-code-graphics-code-and-legacy-graphics-code/#comments</comments>
		<pubDate>Sun, 08 Apr 2012 22:43:00 +0000</pubDate>
		<dc:creator>Rob-Galanakis</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25405</guid>
		<description><![CDATA[<p>We&#8217;re currently undergoing a push to do more &#8216;Agile testing&#8217; at work. At CCP, we &#8220;do&#8221; Agile pretty well, but I don&#8217;t think we &#8220;code&#8221; Agile really well. A large part (the largest part?) of Agile coding and Agile testing is TDD/Unit Testing, of which I&#8217;m a huge fan if not an experienced practitioner.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/08/tdd-for-legacy-code-graphics-code-and-legacy-graphics-code/" class="more-link">Read more on TDD for legacy code, graphics code, and legacy graphics code?&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re currently undergoing a push to do more &#8216;Agile testing&#8217; at work. At CCP, we &#8220;do&#8221; Agile pretty well, but I don&#8217;t think we &#8220;code&#8221; Agile really well. A large part (the largest part?) of Agile coding and Agile testing is TDD/Unit Testing, of which I&#8217;m a huge fan if not an experienced practitioner.</p>
<p>I know how to do TDD for what I do; that is, side-by-side replacement of an internal legacy codebase in a high-level language. What I don&#8217;t have experience in is TDD for expansion and maintenance of a huge, high performance, very active, legacy codebase, and specifically the graphics components and the C++ bits.</p>
<p><strong>So if you have experience in these sorts of things, I&#8217;d love to hear them.</strong></p>
<p><strong></strong>At this point I&#8217;m sticking my neck out as a TDD and unit testing advocate studio-wide, but am reluctant to evangelize too strongly outside of my areas of expertise. I don&#8217;t think it&#8217;d be fair to the very talented people in those areas, and I also don&#8217;t want to be wrong, even if I know I&#8217;m right :) So I&#8217;d really like to hear about your experiences with TDD and unit testing in the games and graphics space, and on legacy codebases, because people are coming to me with questions and I don&#8217;t have good answers. I&#8217;d love to give them places to turn, articles to read, people to contact.</p>
<p>Thanks for any help.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/08/tdd-for-legacy-code-graphics-code-and-legacy-graphics-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Oxel: A Tool for Occluder Generation</title>
		<link>http://www.altdevblogaday.com/2012/04/06/oxel-a-tool-for-occluder-generation/</link>
		<comments>http://www.altdevblogaday.com/2012/04/06/oxel-a-tool-for-occluder-generation/#comments</comments>
		<pubDate>Fri, 06 Apr 2012 23:30:27 +0000</pubDate>
		<dc:creator>Nick Darnell</dc:creator>
				<category><![CDATA[Computer Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[Hierarchical Z-Buffer]]></category>
		<category><![CDATA[Occlusion Volumes]]></category>
		<category><![CDATA[Rendering]]></category>
		<category><![CDATA[tool]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25415</guid>
		<description><![CDATA[<p>Its been awhile since I’ve done an update to my research into occluder generation.  If you need a refresher, take a look at:</p>
<ul>
<li><a href="http://www.nickdarnell.com/2011/06/hierarchical-z-buffer-occlusion-culling-generating-occlusion-volumes/" target="_blank">Hierarchical Z-Buffer Occlusion Culling – Generating Occlusion Volumes</a></li>
</ul>
<p><a href="http://www.altdevblogaday.com/2012/04/06/oxel-a-tool-for-occluder-generation/" class="more-link">Read more on Oxel: A Tool for Occluder Generation&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Its been awhile since I’ve done an update to my research into occluder generation.  If you need a refresher, take a look at:</p>
<ul>
<li><a href="http://www.nickdarnell.com/2011/06/hierarchical-z-buffer-occlusion-culling-generating-occlusion-volumes/" target="_blank">Hierarchical Z-Buffer Occlusion Culling – Generating Occlusion Volumes</a></li>
<li><a href="http://www.nickdarnell.com/2011/09/robust-inside-and-outside-solid-voxelization/" target="_blank">Robust Inside and Outside Solid Voxelization</a></li>
</ul>
<p>Lets start with the newest and most important information&#8230;</p>
<h3>Update 4/13/2012</h3>
<p>The project is now hosted on BitBucket, <a href="http://bitbucket.org/NickDarnell/oxel/overview" target="_blank">http://bitbucket.org/NickDarnell/oxel/overview</a> feel free to contribute or just follow along :)</p>
<h3>It’s a Tool Now!</h3>
<p><img style="margin: 5px;padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://altdevblogaday.com/wp-content/uploads/2012/04/oxel_v1.png" alt="oxel_v1" width="590" height="592" border="0" /></p>
<h4>Download</h4>
<p><a href="http://bitbucket.org/NickDarnell/oxel/downloads" target="_blank">Oxel 1.0.0 &#8211; Win32.zip</a></p>
<h4>Requirements</h4>
<ul>
<li><a href="http://www.microsoft.com/download/en/details.aspx?id=17718" target="_blank">.Net 4.0</a></li>
<li><a href="http://www.microsoft.com/download/en/details.aspx?id=5555" target="_blank">VS2010 C++ Runtime</a></li>
</ul>
<h4>Description</h4>
<p>Oxel is a tool for generating occluders – primarily for use with the Hierarchical Z-Buffer method of occlusion culling.  Open an .obj file then go to Build &gt; Voxelize to generate the proxy.  Try it out, let me know what you think.</p>
<p>There are some further improvements that have been made over the method that is laid out in the original <a href="http://www.nickdarnell.com/2011/06/hierarchical-z-buffer-occlusion-culling-generating-occlusion-volumes/" target="_blank">Generating Occlusion Volumes</a> post,</p>
<ul>
<li>Retriangulation</li>
<li>Evaluating Occlusion-ness</li>
<li>Filtering Polygons</li>
</ul>
<h3>Retriangulation</h3>
<p>I went back to the CSG article <a href="http://sandervanrossen.blogspot.com/">Sander van Rossen</a> and Matthew Baranowski wrote.  I noticed near the end that they recommended retriangulating the final CSG mesh because their library doesn’t handle it.</p>
<p>The easiest method I found to do the retriangulation was to just use David Eberly’s Wild Magic math library which can do it, <a href="http://www.geometrictools.com/SampleMathematics/Triangulation/Triangulation.html" target="_blank">see here</a>.  Before you perform the retriangulation you need to collect all the external/internal edge loops on each surface and then merge collinear edges before performing the retriangulation.</p>
<p>It’s was definitely worth doing, performing the retriangulation saved about 30% of the triangles.</p>
<h3>Evaluating Occlusion-ness</h3>
<p>When you’re generating occluder geometry you need to ensure that the volumes you’re adding are useful enough to pay the additional polygon tax they will incur.</p>
<p>Oxel achieves this by measuring the number of pixels written to the color buffer by rendering the original visual mesh into the stencil buffer, and then using the stencil buffer to clip a full screen quad while a “samples passed” hardware query is performed to record the number of pixels written.  This is performed from about 64 different camera angles – then when all the samples are summed together this defines the <strong>ground truth</strong> occlusion of the mesh.</p>
<p>Knowing that information we can evaluate every new box we plan to add to the final occlusion proxy geometry and ask – Does this increase the coverage enough to make it worth it?.  The default threshold is set to 3%.  If a new volume does not at least cover 3% of new silhouette pixels, we don’t include it in the final occluder mesh.</p>
<h3>Filtering Polygons</h3>
<p>Not every game needs the occluders to be visible from all angles.  For example most racing games will never have the cars jumping so high they see on top of a building.  In those circumstances you may not want to have the occluders bothering to have polygons on the top.</p>
<table width="596" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td valign="top" width="298"><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/with.png"><img style="margin: 1px;padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://altdevblogaday.com/wp-content/uploads/2012/04/with_thumb.png" alt="with" width="275" height="168" border="0" /></a></td>
<td valign="top" width="296"><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/without.png"><img style="margin: 1px;padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://altdevblogaday.com/wp-content/uploads/2012/04/without_thumb.png" alt="without" width="275" height="168" border="0" /></a></td>
</tr>
</tbody>
</table>
<p>So the tool offers the ability to remove Top and Bottom polygons from the final occluder mesh after everything has finished being processed.</p>
<p>If you decide to filter out all top polygons they’re all removed.  For bottom surfaces this has to be handled slightly differently, see below -</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/bottom_removed.png"><img style="margin: 5px;padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://altdevblogaday.com/wp-content/uploads/2012/04/bottom_removed_thumb.png" alt="bottom_removed" width="580" height="331" border="0" /></a></p>
<p>Imagine a bridge structure or a large over hang on a building.  You wouldn’t want the bottom portion of the occluder to be removed from the overhang since it would allow seeing into and through the occluder &#8211; because presumably you wouldn’t have double sided rendering enabled.  So to distinguish between bottom surfaces not meant to ever be seen by the player, and bottom surfaces that may be important to higher up potions of the structure, only bottom surfaces within 1 voxel’s height from the base of the mesh are removed.  (See picture above)</p>
<h3>Work Continues</h3>
<p>I’ve got some more ideas I need to test out but I wanted to go ahead and cut a version of where I’m at and let others take a look and give me some feedback.</p>
<p>One area I need to investigate next is a better way to generate the boxes.  Currently they are just expanded in all directions equally, but that’s not ideal.  I’m thinking about trying a parallel brute force method that would test all possible boxes at a specific origin point to find the best shaped box to generate from that point.</p>
<p><a href="http://www.nickdarnell.com/2012/04/oxel-a-tool-for-occluder-generation/" target="_blank">Oxel: A Tool for Occluder Generation @ nickdarnell.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/06/oxel-a-tool-for-occluder-generation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Floating-point complexities</title>
		<link>http://www.altdevblogaday.com/2012/04/05/floating-point-complexities/</link>
		<comments>http://www.altdevblogaday.com/2012/04/05/floating-point-complexities/#comments</comments>
		<pubDate>Thu, 05 Apr 2012 19:32:00 +0000</pubDate>
		<dc:creator>Bruce-Dawson</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[comparing]]></category>
		<category><![CDATA[denormal]]></category>
		<category><![CDATA[digits]]></category>
		<category><![CDATA[float]]></category>
		<category><![CDATA[floating point]]></category>
		<category><![CDATA[floating point precision]]></category>
		<category><![CDATA[floating point tricks]]></category>
		<category><![CDATA[precision]]></category>
		<category><![CDATA[printing]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25258</guid>
		<description><![CDATA[<p>Binary floating-point math is complex and subtle. I’ve collected here a few of my favorite oddball facts about floating-point math, based on the articles so far in my floating-point series. The focus in this list is on float but the same concepts all apply to double.</p>
<p><span id="more-25258"></span></p>
<p><a href="http://www.altdevblogaday.com/2012/04/05/floating-point-complexities/" class="more-link">Read more on Floating-point complexities&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Binary floating-point math is complex and subtle. I’ve collected here a few of my favorite oddball facts about floating-point math, based on the articles so far in my floating-point series. The focus in this list is on float but the same concepts all apply to double.</p>
<p><span id="more-25258"></span>
<p>These oddities don’t make floating-point math bad, and in many cases these oddities can be ignored. But when you try to simulate the infinite expanse of the real-number line with 32-bit or 64-bit numbers then there will inevitably be places where the abstraction breaks down, and it’s good to know about them.</p>
<p>Some of these facts are useful, and some of them are surprising. You get to decide which is which.</p>
<ul>
<li>Adjacent floats (of the same sign) <a href="http://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/">have adjacent integer representations</a>, which makes generating the next (or all) floats trivial</li>
<li>FLT_MIN is <a href="http://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/">not the smallest positive float</a> (FLT_MIN is the smallest positive <em>normalized</em> float)</li>
<li>The smallest positive float is 8,388,608 times smaller than FLT_MIN</li>
<li>FLT_MAX is not the largest positive float (it’s the largest finite float, but the special value infinity is larger)</li>
<li>0.1 <a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/">cannot be exactly represented in a float</a></li>
<li>All floats can be <a href="http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/">exactly represented in decimal</a></li>
<li>Over a <a href="http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/">hundred decimal digits</a> of mantissa are required to exactly show the value of some floats</li>
<li><a href="http://randomascii.wordpress.com/2012/02/11/they-sure-look-equal/">9 decimal digits of mantissa</a> (plus sign and exponent) are sufficient to uniquely identify any float</li>
<li>The Visual C++ debugger displays floats with 8 mantissa digits</li>
<li>The integer representation of a float is a piecewise linear approximation of the <a href="http://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/">base-2 logarithm</a> of that float</li>
<li>You can calculate the <a href="http://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/">base-2 log of an integer</a> by assigning it to a float</li>
<li>Most float math gives inexact results due to rounding</li>
<li>The basic IEEE math operations guarantee perfect rounding</li>
<li>Subtraction of floats with similar values (f2 * 0.5 &lt;= f1 &lt;= f2 * 2.0) gives an exact result, with no rounding</li>
<li>Subtraction of floats with similar values can result in a loss of virtually all significant figures (even if the result is exact)</li>
<li>Minor rearrangements in a calculation can take it from <a href="http://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/">catastrophic cancellation to 100% accurate</a></li>
<li>Storing elapsed game time in a float <a href="http://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/">is a bad idea</a></li>
<li>Comparing floats <a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/">requires care</a>, especially around zero</li>
<li>sin(float(pi)) calculates a very accurate approximation to <a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/">pi-float(pi)</a></li>
<li>From 2^24 to 2^31, an int32_t has <a href="http://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/">more precision than a float</a> – in that range an int32_t can hold every value that a float can hold, and millions more</li>
<li>pow(2.0f, -149) should calculate the smallest denormal float, but with VC++ it generates zero. pow(0.5f, 149) works.</li>
<li>IEEE float arithmetic guarantees that “if (x != y) return z / (x-y);” will never cause a divide by zero, but this guarantee only applies if denormals are supported</li>
<li>Denormals have <a href="http://www.cygnus-software.com/papers/x86andinfinity.html">horrible performance</a> on some older hardware, which leads to some developers disabling them</li>
<li>If x is a floating-point number then “x == x” may return false – if x is a NaN</li>
<li>Calculations done with <a href="http://randomascii.wordpress.com/2012/03/21/intermediate-floating-point-precision/">higher-precision intermediate values</a> sometimes give more accurate results, sometimes less accurate results, and sometimes just <a href="http://www.exploringbinary.com/when-floats-dont-behave-like-floats/">inconsistent results</a></li>
<li>Double rounding can lead to inaccurate results, even when doing something as simple as <a href="http://www.exploringbinary.com/double-rounding-errors-in-floating-point-conversions/">assigning a constant to a float</a></li>
<li>You can printf and scanf every positive float in <a href="http://randomascii.wordpress.com/2012/03/11/c-11-stdasync-for-fast-float-format-finding/">less than fifteen minutes</a></li>
</ul>
<p>Do you know of some other surprising or useful aspects of floats? Respond in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/05/floating-point-complexities/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>It&#8217;s Not Rocket Surgery&#8211;Managing Teams Across Disciplines and Under Pressure</title>
		<link>http://www.altdevblogaday.com/2012/04/04/its-not-rocket-surgerymanaging-teams-across-disciplines-and-under-pressure/</link>
		<comments>http://www.altdevblogaday.com/2012/04/04/its-not-rocket-surgerymanaging-teams-across-disciplines-and-under-pressure/#comments</comments>
		<pubDate>Wed, 04 Apr 2012 21:29:16 +0000</pubDate>
		<dc:creator>Simon Cooke</dc:creator>
				<category><![CDATA[General Interest]]></category>
		<category><![CDATA[Production]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25379</guid>
		<description><![CDATA[<p>I recently had the pleasure of presenting a talk at <strong>GDC 2012</strong> in the <strong>Producer Boot Camp </strong>tutorials track on how to be a producer in the games industry. Well, that and the kinds of issues you’ll see as teams grow and evolve over time.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/04/its-not-rocket-surgerymanaging-teams-across-disciplines-and-under-pressure/" class="more-link">Read more on It&#8217;s Not Rocket Surgery&#8211;Managing Teams Across Disciplines and Under Pressure&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I recently had the pleasure of presenting a talk at <strong>GDC 2012</strong> in the <strong>Producer Boot Camp </strong>tutorials track on how to be a producer in the games industry. Well, that and the kinds of issues you’ll see as teams grow and evolve over time.</p>
<p>I’ve got the slides up online now, so even though you can’t hear my dulcet tones, you should be able to imagine Morgan Freeman narrating for you as you read the accompanying speaker notes. Except this should be a weird English/American Morgan Freeman, who isn’t half as sexy.</p>
<p><strong>So what’s in the deck?</strong></p>
<p>Learn a variety of battle-hardened tricks and tactics for building teams, keeping them running smoothly, and how to handle your team&#8217;s worst enemy: the panic of shipping a game.</p>
<p><strong>Learn:</strong></p>
<ul>
<li>How to keep your team together under crunch</li>
<li>How to help teams not hate the producer, especially if their last one suuuuuuucked</li>
<li>Avoid crunch entirely – and justify it with research</li>
<li>Stop large teams across large companies from grinding to a halt where all your games – no matter how geographically disparate your studios are – end up shipping in lockstep</li>
<li>Why you need meetings, scooters, or both</li>
<li>Panic leads to blame, blame leads to anger, anger leads to the dark side…</li>
<li>That our brains have really buggy code/design limitations</li>
<li>What Sierra’s Carrot is, who invented it, and how amazingly well it works to ship on time, every time. (Warning: singular of data = anecdote).</li>
</ul>
<p>This slide deck (with, theoretically, <strong><em>audio!*</em></strong> and better jokes than the ones in the speaker notes that I <em>can’t remember</em> because my forebrain was wiped by the adrenaline) should be available in the <a href="http://www.gdcvault.com/" target="_blank">GDC Vault</a> soon.</p>
<p><strong>The Files</strong></p>
<p><a href="http://accidentalscientist.com/files/Final%20It's%20Not%20Rocket%20Surgery%20-%20GDC%202012.zip" target="_blank">Download a zip file containing the slide deck</a> (in PowerPoint format). Download the free PowerPoint Viewer <a href="http://www.microsoft.com/download/en/details.aspx?id=13" target="_blank">here</a>.</p>
<p>Next year? I’m thinking of going for the GDC “<a href="http://en.wikipedia.org/wiki/List_of_people_who_have_won_Academy,_Emmy,_Grammy,_and_Tony_Awards" target="_blank">EGOT</a>”, and doing a talk on game design and how your brain works. Probably called “Sticks and stickiness – Primal Game Design”.</p>
<p><span style="font-size: xx-small">*Note: Audio may have been processed and filtered by GDC staff to not actually sound like an English Morgan Freeman at all. It’s a conspiracy, I tell ya.</span></p>
<p>And time for a small apology&#8230; I’ve been meaning to write an entire series of follow up posts to my previous one on <a href="http://altdevblogaday.com/" target="_blank">#AltDevBlogADay</a> (<a href="http://altdevblogaday.com/2011/11/13/10000-is-the-magic-number/" target="_blank">$10,000 is the Magic Number</a>), but I’ve not had the time – yet. But I do intend to fix that, so stay tuned.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/04/its-not-rocket-surgerymanaging-teams-across-disciplines-and-under-pressure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simulating a Loaded Dice in a Constant Time</title>
		<link>http://www.altdevblogaday.com/2012/04/04/simulating-a-loaded-dice-in-a-constant-time/</link>
		<comments>http://www.altdevblogaday.com/2012/04/04/simulating-a-loaded-dice-in-a-constant-time/#comments</comments>
		<pubDate>Wed, 04 Apr 2012 10:45:15 +0000</pubDate>
		<dc:creator>Jaewon Jung</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[alias method]]></category>
		<category><![CDATA[loaded dice]]></category>
		<category><![CDATA[probability distribution]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25370</guid>
		<description><![CDATA[<p>A fair dice can be easily simulated with rand() function(or C++11 <a href="http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution">std::uniform_int_distribution</a>) and integer modulo arithmetic. Then how about <strong>a loaded dice</strong>(a dice with a non-uniform probability for each face)?</p>
<p>No sweat. Just partition a normalized range of 0.0 to 1.0 according to each probability and bin the result of a random function to a corresponding subrange. But the search will require O(<em>n</em>) time complexity(here, <em>n</em> is the number of dice faces). Can we do better? Sure. One can do a binary search or similar, then one can get a result of rolling a loaded dice within O(log<em>n</em>) time complexity. How about a constant time complexity? Can we achieve that?</p>
<p><a href="http://www.altdevblogaday.com/2012/04/04/simulating-a-loaded-dice-in-a-constant-time/" class="more-link">Read more on Simulating a Loaded Dice in a Constant Time&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>A fair dice can be easily simulated with rand() function(or C++11 <a href="http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution">std::uniform_int_distribution</a>) and integer modulo arithmetic. Then how about <strong>a loaded dice</strong>(a dice with a non-uniform probability for each face)?</p>
<p>No sweat. Just partition a normalized range of 0.0 to 1.0 according to each probability and bin the result of a random function to a corresponding subrange. But the search will require O(<em>n</em>) time complexity(here, <em>n</em> is the number of dice faces). Can we do better? Sure. One can do a binary search or similar, then one can get a result of rolling a loaded dice within O(log<em>n</em>) time complexity. How about a constant time complexity? Can we achieve that?</p>
<p>Suprisingly (to me, at least) it&#8217;s possible. There is an algorithm called &#8216;<strong>alias method</strong>&#8216; which guarantees O(1) generation cost once an initialization step(i.e. preprocessing) of O(<em>n</em>) has been done. This algorithm is from a paper called <a href="http://web.eecs.utk.edu/~vose/Publications/random.pdf">&#8220;A Linear Algorithm For Generating Random Numbers With a Given Distribution&#8221;</a> by Michael Vose.</p>
<div class="wp-caption aligncenter" style="width: 325px"><img src="http://i1089.photobucket.com/albums/i342/all2one/scriptogram_images/alias_method.jpg" alt="Original probability distribution and aliased one" width="315" height="553" /><p class="wp-caption-text">Original probability distribution(top) and aliased one(bottom)</p></div>
<p style="text-align: left">Let&#8217;s suppose a dice with four faces, each of which has a probability of 1/2, 1/3, 1/12 and 1/12. The probability distribution can be visualized as the top diagram above. The gist of the alias method is to transform the diagram to something like the bottom one. The essential point is that each column in the bottom diagram has at most two items. By simulating a fair dice to select a column and then flipping a biased coin, which matches to the probability distribution of in the column, to select between the two, one can get the result. A new item added to the original one in that column is called an <em>alias</em> of it, so the name of the algorithm. Quite neat, isn&#8217;t it?</p>
<p>I learned this algorithm from this excellent(though, rather long) article, <a href="http://www.keithschwarz.com/darts-dice-coins/">Darts, Dice, and Coins: Sampling from a Discrete Distribution</a>. So I highly recommend reading it for more kind &amp; thorough explanation of the matter. Especially, you can check there how the alias table can be generated in a linear time.</p>
<p>The author of the article also provides a Java implementation of it here:</p>
<p><a href="http://www.keithschwarz.com/interesting/code/?dir=alias-method">http://www.keithschwarz.com/interesting/code/?dir=alias-method</a></p>
<p>Here is my C++ implementation, which is a basic porting of the Java implementation:</p>
<p><a href="http://ideone.com/gzFzI">http://ideone.com/gzFzI</a></p>
<p>(This article has also been posted to<a href="http://scriptogr.am/jj"> my personal blog</a>.)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/04/simulating-a-loaded-dice-in-a-constant-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Launching on the AppStore in the year 2012</title>
		<link>http://www.altdevblogaday.com/2012/04/03/launching-on-the-appstore-in-the-year-2012/</link>
		<comments>http://www.altdevblogaday.com/2012/04/03/launching-on-the-appstore-in-the-year-2012/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 20:04:06 +0000</pubDate>
		<dc:creator>Charilaos Kalogirou</dc:creator>
				<category><![CDATA[General Interest]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25310</guid>
		<description><![CDATA[<p>Today is somewhat an important day, as it is exactly 60 days since the day I can officially call myself a published indie game developer! It was February 3rd when <a href="http://bit.ly/getpopcorny">Mr. Pop Corny</a> rushed (actually it crawled thanks to Apple, but I will get to that below) into the AppStore after an 8 month development time, and the dream came true. So it seems now it is a good time to share some of my experiences regarding launching on the AppStore. I will try to provide some insight that I wish I had from other projects prior to launching my own.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/03/launching-on-the-appstore-in-the-year-2012/" class="more-link">Read more on Launching on the AppStore in the year 2012&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Today is somewhat an important day, as it is exactly 60 days since the day I can officially call myself a published indie game developer! It was February 3rd when <a href="http://bit.ly/getpopcorny">Mr. Pop Corny</a> rushed (actually it crawled thanks to Apple, but I will get to that below) into the AppStore after an 8 month development time, and the dream came true. So it seems now it is a good time to share some of my experiences regarding launching on the AppStore. I will try to provide some insight that I wish I had from other projects prior to launching my own.</p>
<h2>Background</h2>
<p>Let me start with some info on <a href="http://bit.ly/getpopcorny">Pop Corny</a>. Pop Corny was <a href="http://altdevblogaday.com/2012/02/03/my-game-design-hat/">designed</a> to be a simple and fun casual game, covering the need for short game session experiences that mobile phone games require. </p>
<p>I self funded, developed, published and initially launched the game as a paid application at the $0.99 tier. Later on, it switched to free and monetizing with IAPs, but bare with me for the details of this decision. </p>
<p>Below are some more technical details of the game:</p>
<ul>
<li>Development time: 8 months</li>
<li>Number of developers: 1 </li>
<li>Outside contractors for sound and most graphics</li>
<li>Build using a fork of <a href="http://devnet.sylphis3d.com/">Sylphis3D Game Engine</a> </li>
<li>Support of all iPhone, iPod touch and iPad devices</li>
<li>Source code (gamecode + game engine code excluding third party libraries):<br />
<code><br />
-----------------------------------------<br />
Language    files    blank comment   code<br />
-----------------------------------------<br />
Lua            52     2631    1026  10415<br />
C/C++ Header   77     1209    1111   3718<br />
C++            32      731     882   2552<br />
XML             1        1       0    788<br />
Python          9      170     136    630<br />
Bourne Shell   13       70     167    284<br />
Objective C     2       14      14     25<br />
-----------------------------------------<br />
SUM:          186     4826    3336  18412<br />
-----------------------------------------<br />
</code>
</li>
<li>Game code accounted for 5983 lines of the above LUA code</li>
<li>The total source dataset reached up to 0.4 GB </li>
<li>Resulting “compiled” dataset at 10MB</li>
<li>Initial price $0.99 (50 days) then dropped to free</li>
<li>Total sales in two months: ~150000</li>
<li>IAP conversion rate: ~2.0%</li>
<li>Ratings: 4.5/5 (from 600 ratings, 70% of which are 5 star)</li>
</ul>
<h2>Promotion</h2>
<p>As I said the game was funded and published without any help from the outside. This easily translates to: <i>no money for marketing</i>. Therefore I had to find ways to make the best I could on the cheap. One of the major aids on that seemed to be the famous <b>launch day</b>.</p>
<p>Everyone developing on the AppStore will tell you that the launch day is one of the most important events in effectively publishing your game. You must do the best in your powers not to fail that day. And this is true. I had published 3 more applications on the AppStore prior to this game and the launch day will give you eye balls costing thousands of dollars for free. This is through the AppStore’s new releases list.</p>
<p>My approach was to combine that visibility with all the “social” publicity I could harvest, doing my best to leap as high as I could on the charts. Then possibly some game journalists would notice and write about it, thus keeping the fire burning. To do that I created a <a href="http://bit.ly/cornytrailer">trailer video</a> for the game and one week earlier I created an event on Facebook for the “unveiling of the video trailer”. I invited everyone I could and one week later (on January 31th) I presented the video. That day I also posted the video on every related forum I could. This caused some fuzz but mostly in Greece where most of my facebook friends live in. </p>
<p>The release day was set on February 3rd. I already had approval from Apple and I was already sending out promo codes to game journalists before that. For this I was carefully compiling a list of game review websites and journalists from early on the development cycle. I had these ordered by alexa ranking by review scores and game types. When I got the game approved by Apple, I send out all 40 promo codes I had available, and contacted 100 more without a promo code. </p>
<p>Early on the development cycle I took another big decision based on marketing. That was to support OpenFeint in addition to GameCenter. OpenFeint has its own top games, featured games and new releases, which can give some extra exposure to your new and unknown game. I decided that I needed that extra eyeballs, so I supported both social gaming networks. </p>
<p>In short what I did prior to the release day were these:</p>
<ul>
<li>Created a “coming soon” video trailer</li>
<li>Created Facebook page and Twitter page for the game</li>
<li>Organized a Facebook event for the unveiling of the game video</li>
<li>Send out all 40 promo codes to game journalists (with all media packs, bells and whistles) </li>
<li>Wrote posts in “new releases” parts of forums</li>
<li>Prepared a cross promotion among my other apps</li>
<li>Supported OpenFeint</li>
</ul>
<p>Then all I had to do was wait for the launch day and the sweet success&#8230; or not&#8230;</p>
<h2>Apple spilling the milk</h2>
<p>With everything set and the game automatically scheduled to launch at the world’s AppStores on February 3rd, an unexpected nightmare started for me on February 2nd (since we live in a globe and in New Zealand it was already “tomorrow”). Of course I was viewing the New Zealand’s AppStore waiting for Pop Corny to appear, and it did. Oh! The Joy! After all these months of hard work it was there&#8230; taking its chance! Couldn’t be happier and more stressed at the same time&#8230; however the moments of joy ended shortly after I looked closer. Fear filled my heart when I noticed next to my game’s icon a release day of “Jan 31th”. I rushed to the new releases list like a maniac looking for Pop Corny which was nowhere to be found. What happened? Had the app gone live 3 days ago and I didn’t notice? Hardly&#8230; the app was not live on any other AppStore. I manually checked every other AppStore&#8230; not released&#8230; </p>
<div class="wp-caption alignleft" style="float:left"><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/releaseday.png"><img src="http://altdevblogaday.com/wp-content/uploads/2012/04/releaseday.png" alt="Mr. Pop Corny is a popcorn loving monster" class="size-full wp-image-23798"></a>
<p class="wp-caption-text">AppStore entry showing<br /> the wrong release day</p>
</div>
<p>I was optimistic, these distributed systems are slow to update and initially things like that might happen. However, Feb 3rd started to dawn in more countries and the same story was repeating. Pop Corny was appearing as a 3 days old app. 3 days when you launch on the AppStore is an eternity. I was out of the front page, before I even got the time to get on it. I tried to contact Apple through the support system but that is easier said than done. </p>
<p>It was then I realised how small and expendable I was. There is absolutely no way to solve a situation like this with a system that works by choosing among 15 nested problem categories before you finally get a text box to write down your problem. No way to resolve it with an one day round trip for getting a reply that was canned and had nothing to do with what I described. No way when you can’t -at least- follow up on the answer you get. I tried again and again for the next days by submitting from the start my problem rephrased in the best way I would&#8230; fail. </p>
<p>It was almost 7pm US time when auto-magicaly the release day of Pop Corny rolled to the correct Feb 3rd on all AppStores. However it was too late. Some AppStores were about to go on Feb 5th by then. The icing on the cake however was the reply to my last plea at Apple that told me that they don’t see any problem with the date as it is Feb 3rd. The irony!   </p>
<p>The problem also managed to mess up OpenFeint’s releases system. OpenFeint, once you have the app approved, scans the AppStore to see when your game releases. I guess that was the reason Pop Corny didn’t got on OpenFeint’s lists. One week later I contacted them about the problem and they said that somehow the system skipped my app, and that they had to add it manually. They couldn’t find an explanation, but I could&#8230;</p>
<p>This way I had zero exposure from the AppStore new releases, resulting in next to zero sales. It was a disaster. Apple should really make up to me for this someday by featuring it for a day or two&#8230; I can wait.</p>
<h2>Getting a grip and keep walking</h2>
<p>The above disaster affected all the AppStores in the world. It resulted in Pop Corny selling 10 units on release day in the US. I know crap-ware that were released the same day and sold more (based on their top paid ranking). It was so, because no one knew of my new released game. </p>
<p>In Greece, however, it was another story. Here is most of my “social network”. People knew about Pop Corny and they were expecting it. Several major local iPhone blogs wrote about it and the game took off. In less than 24 hours Pop Corny was number one top paid application. That was among all applications, not just games. 5 stars reviews started coming and it was heaven. A few days at the top and it was also on the local TV media. </p>
<p>This contrast between Greece and all other countries was to me a great illustration of how publicity is king. You must bring your game in front of the players face. And that is hard. It is the hardest part for a small developer. No one will look at you when you are small. Getting big seems like a self fulfilling prophecy. </p>
<div style="width: 300px;float:right;font-style:italic;font-weight:bold;background: #eaeaea;margin: 10px;padding: 15px">Being the number one top paid application in Greece translates to 200 sales a day&#8230;</div>
<p>From the 150 emails I send to reviewers I only got replies from 10 people. 8 of them kindly suggested I pay some fee and the rest two just told me that they were too busy to bother. By monitoring the downloads on the media pack I could see that just two of them bothered to download it. It is clear that something is wrong here. It seems that the only way to get covered these days is through dollars. </p>
<p>Being the number one top paid application in Greece translates to 200 sales a day (yes it is a small store). This is 100 euros a day after Apple’s cut. Does not sound that bad, but given the universal decay law of the AppStore (I will talk about it next), it was not enough.  Meanwhile on all other AppStores the app was doing poorly. </p>
<p>I knew that it was out of my reach to reverse this situation, so I decided to step back, stop desperately trying to push it, and focus on fixing some bugs, implement some new features until the day the game would go free. Going free was in my mind since the development days. The game was actually designed to work as a free game from development day one but the final decision to go paid was taken a few days before the release. </p>
<p>I saw this as a second chance. My means of getting more eyeballs on the game. But I knew that going free is not easy. It is a whole different arena. Going free will give you a big sales boost mainly because of applications like <a href="http://www.appshoper.com">AppShoper</a>. These kind of apps scan the AppStore every day and report to its users which apps has gone free, resulting in many sales. However many is not enough when competing with free applications. You need LOTS more. </p>
<p>There are services out there like OpenFeint’s <a href="http://freegameoftheday.com/">“Free Game Of The Day”</a> that provide you with the extra visibility you need for the day you go free. They feature one game every day, and promote it through their website and their iPhone app. I contacted them, they liked the game and I took the first slot that was available, that happened to be Thursday, Match 22nd (yeap the day Angry Birds Space came out&#8230; no fear!). They are very well organized and the process of submitting artwork was very streamlined and efficient. I submitted the appropriate banners and texts and there was nothing more left to do but wait for the day. </p>
<p>The day came and Pop Corny became free. The effect of this promotion was overwhelming. Pop Corny started to climb the charts all over the world at incredible speeds. It was not much later that it was ranking in the top 10 of more than 20 AppStores, and being number one of its category in 10 AppStores. </p>
<p>At startup the game checks for a .plist file on my server that contains possible news to present to the user. This allowed me to measure the rate of downloads in realtime. It reached a whopping 48 downloads/min. A few hours in the promotion 148apps.com featured it and even more downloads happened. This continued for the whole day (which is actually 48 hours to cover all the globe) and I had the opportunity to correlate the spikes I saw on the news file consumption with mentions on twitter, and posts on blogs, etc. A very educative experience.  </p>
<p>With the game on so many charts it would be stupid to just turn to paid after the promotion day, switch charts, and lose the exposure. Also the revenue from the free version was already a multiple of the revenue with the paid. So I took the decision to keep it free. I believe I did the right thing. The game did 70000 downloads in the weekend following the promotion day, received very good reviews from the users and the revenue from the IAP was climbing. I was totally satisfied. </p>
<h2>The universal decay law of the AppStore</h2>
<p>One of the biggest myths busted by my experience with launching Pop Corny was that visibility on the AppStore is king. It seems like everyone believes that being on the top 10 is the way to sell. That this will translate to visibility and sales in a feedback process that will sustain enough to make a profit. You must do all you can to enter the charts as a way to make your game sell more. For me now, this is the biggest misconception about the AppStore.<br />
With the huge amount of applications in the AppStore and the new ones that enter everyday, the charts only act as a capacitor. They smooth out spikes. Most sales today start outside the AppStore and not inside. The people that will buy your application because they saw it on the charts are not enough to sustain it on its position, let alone to lift it. Therefore we witness “the universal decay law of the AppStore” as I call it. Any application that is not receiving some external to the AppStore’s charts force will follow the graph below:</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/Στιγμιότυπο-2012-04-03-7.34.10-μ.μ..png"><img src="http://altdevblogaday.com/wp-content/uploads/2012/04/Στιγμιότυπο-2012-04-03-7.34.10-μ.μ..png" alt="" width="475" height="177" class="aligncenter size-full wp-image-25340" /></a></p>
<p>Let that be paid or free. The only thing that changes is the absolute amount of downloads, which is orders of magnitude larger when free. How fast is the decay depends on the competition, how much you icon and descriptions attracts buyers and what rating you have. </p>
<p>Bottom line is that the charts cannot sustain you these days. It probably did some years ago, but not anymore. You should never think of the charts as your means to sales. Use it just as an indicator of how well you are doing. The game is played out of this field. Get reviews, tweets, mentions, and of course get featured by Apple. </p>
<h2>Conclusion</h2>
<p>The AppStore is not an easy place to publish in 2012. I was not expecting it to be easy, since Pop Corny was not my first application published there. However I would really love not to have been squashed by that bug with the release day. At least it would make me feel much better if I knew I could efficiently communicate the problem to Apple. </p>
<p>In the end however I think that Pop Corny did very well and will do better with time. I learned a lot through the process, it has almost covered its development costs and also gave me the joy of having hundred of thousands of people playing my game. With a zero marketing budget and being my first game, it certainly exceeded my expectations. It proved that you can still have a chance on the AppStore without some big dollar marketing campaign. However it is getting really hard to do so. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/03/launching-on-the-appstore-in-the-year-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The perception of interactivity</title>
		<link>http://www.altdevblogaday.com/2012/04/03/the-perception-of-interactivity/</link>
		<comments>http://www.altdevblogaday.com/2012/04/03/the-perception-of-interactivity/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 18:25:59 +0000</pubDate>
		<dc:creator>Alex Moore</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Game design]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25301</guid>
		<description><![CDATA[<p>The conclusion of the Mass Effect trilogy has spawned a great deal of chatter on forums and news sites alike, based initially on the online petition requesting extra endings and the growing responses from Bioware and others alike.  <a title="Eight million blogs" href="http://altdevblogaday.com/2012/04/01/there-are-eight-million-blogs-about-mass-effects-ending-this-is-one-of-them/" target="_blank">Kyle&#8217;s post here</a> covers one perspective, and with this post I aim to cover something slightly different one.  It is not directly about Mass Effect, but instead about how content driven games are made.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/03/the-perception-of-interactivity/" class="more-link">Read more on The perception of interactivity&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>The conclusion of the Mass Effect trilogy has spawned a great deal of chatter on forums and news sites alike, based initially on the online petition requesting extra endings and the growing responses from Bioware and others alike.  <a title="Eight million blogs" href="http://altdevblogaday.com/2012/04/01/there-are-eight-million-blogs-about-mass-effects-ending-this-is-one-of-them/" target="_blank">Kyle&#8217;s post here</a> covers one perspective, and with this post I aim to cover something slightly different one.  It is not directly about Mass Effect, but instead about how content driven games are made.</p>
<h2>Understanding</h2>
<p>It seems to me, from the way the petition is worded, that despite investing hundreds of hours in the trilogy many gamers don’t understand the logistics involved in creating a videogame.  It could be argued that they shouldn’t need to – we watch films without knowing all the intricacies involved in getting the image and sound to the screen, so why should gamers need to know about the blood, sweat and tears that go into making games?</p>
<p>While some films do spark huge reaction towards the director from fans, those fans often find other outlets for their reaction, with alternative endings turning up on youtube or comic strips or even novels.  There are rarely the tools made available for alternative endings to be made for videogames, which in turn leads to fans putting pressure on developers.  Funding issues aside, there’s a big reason why a game driven by content cannot have infinite endings: it’s simply not possible to create and test that much content.</p>
<p>To expand on that statement, the way the Mass Effect trilogy melds the experience to the player’s actions puts a phenomenal sense of power and creation into their hands, and this naturally gives the impression that the game is crafted specifically to them.  Unfortunately, it’s not.</p>
<h2>Exhibit A</h2>
<p>To give an example of how a content driven game is designed I’m going to have a quick look at Dragon’s Lair. If you haven’t played it, the premise is very simple: a beautiful animation plays out and, at a pre-defined point, something happens which the player needs to react to with a button press. This is a video of the full game being played all the way through:</p>
<span style="text-align:center; display: block;"><a href="http://www.altdevblogaday.com/2012/04/03/the-perception-of-interactivity/"><img src="http://img.youtube.com/vi/P3XNQja0H7I/2.jpg" alt="" /></a></span>
<p>The playthrough doesn&#8217;t show many of the player deaths because the player knows what they&#8217;re doing. But behind the smooth flowing animation is a system that&#8217;s waiting for a player input. If the player misses the window of opportunity the game branches, and the player dies.  If they hit the window, they progress.</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/simple_branch.png"><img class="alignleft size-full wp-image-25351" src="http://altdevblogaday.com/wp-content/uploads/2012/04/simple_branch.png" alt="" width="297" height="150" /></a></p>
<p>Different companies refer to these as different things – nodes, branches, gates.  They’re effectively all the same and, for this post, I’ll stick with the latter.  This example is the simplest gate required to create player choice.  Each and every sequence has been hand crafted, and the game planned out in intimate detail.</p>
<p>To design Dragon’s Lair and sketch out the flow it probably took a few weeks, though actually creating the content took 7 months and 1 million dollars (<a href="http://en.wikipedia.org/wiki/Dragon's_Lair" target="_blank">source</a>).  That was in 1983, so in today&#8217;s money that&#8217;s a lot more.  And all this for a game that can be completed in just over 10 minutes, as shown in the above video.</p>
<h2>Testing</h2>
<p>As well as creating the content and code, it all needs to be tested.  Test plans come later down the development line, when the framework of the game and the main mechanics are close to being locked.  Once that happens it&#8217;s possible to create a list of tests and expected results.  From here the test team can do regular checks to ensure the game is behaving as intended.</p>
<p>A test plan for the the diagram above might look something like this:</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/test_cases.png"><img class="alignnone size-full wp-image-25349" src="http://altdevblogaday.com/wp-content/uploads/2012/04/test_cases.png" alt="" width="804" height="171" /></a></p>
<p>One sequence with a single gate therefore might lead to eight tests.  Possibly even more.  For now though that’s enough to highlight why testing is one of the most difficult parts of making games.  It stands to reason therefore that in a game more complicated than Dragon’s Lair there’s going to be far more possible outcomes.  At any one point the player could have done one of a hundred things, let alone the thousands of small inputs they’ve made to get to where they are.  If a bug surfaces the developer then needs to find a way to recreate it so that they can understand what’s going wrong and then, hopefully, fix it.</p>
<p>I should note at this point that something like a shooting mechanic is very different from gated content, because that&#8217;s a system that has a set of defined rules.  When the player does certain things (such as presses the fire button) the rules determine what happens, not the content.  So the test plan doesn&#8217;t have to account for pressing the fire button at every possible position the player can get themselves into.  The sort of gates I&#8217;m describing here really only come into play at big story points, such as the &#8216;choose route&#8217; type option presented to the player in Gears of War for instance.</p>
<h2>Scaling up</h2>
<p>Now we know the level of detail required for a single gate, we should now look at how we cope with multiple gates.  In Mass Effect each conversation often has a few possible outcomes, especially when they&#8217;re with key characters.  The interaction required by the player is very different from the reaction-heavy animation window system employed by Dragon&#8217;s Lair, but the underlying system is very similar:</p>
<p style="text-align: center"> <a href="http://altdevblogaday.com/wp-content/uploads/2012/04/complicated_branch.png"><img class="size-full wp-image-25352 aligncenter" src="http://altdevblogaday.com/wp-content/uploads/2012/04/complicated_branch.png" alt="" width="247" height="225" /></a></p>
<p>Suddenly we&#8217;re facing a bit of a crisis &#8211; one conversation with three possible outcomes, each with just two more attached to them has led to six unique paths.  And the game design wants over a hundred conversations&#8230;  There&#8217;s no real way that we can create that many unique gates.  So, instead, we create paths that feed back into themselves further down the line:</p>
<p style="text-align: center"><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/branch_paths.png"><img class="size-full wp-image-25356 aligncenter" src="http://altdevblogaday.com/wp-content/uploads/2012/04/branch_paths.png" alt="" width="273" height="236" /></a></p>
<p>You&#8217;ll notice that by using this system it&#8217;s entirely possible that the player won’t have to go through every gate to get to the end – in fact it’s desirably to do this to try and encourage replays.</p>
<h2 id="chokepoints">Choke Points</h2>
<p>You can keep even more control over the number of possible outcomes by creating larger, single, gates that the player has to go through to complete the game, but where they&#8217;re free to choose whatever route they desire in between:</p>
<p style="text-align: center"><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/chokepoints.png"><img class="size-full wp-image-25358 aligncenter" src="http://altdevblogaday.com/wp-content/uploads/2012/04/chokepoints.png" alt="" width="373" height="152" /></a></p>
<p>The orange boxes in this case are choke points.</p>
<p>With a game like Mass Effect there are multiple choke points, but the entire game is constructed of so many that the player doesn&#8217;t have to go through every one to get to the end of the game.  In fact, there&#8217;s very purposefully a great deal of routes through the game.  But every single route has been planned, designed and has had content created for it.</p>
<p>This type of design method isn’t just limited to stories, but can be used for level design or ability trees too.  A good example of a game that uses this method for all of these systems is Bioshock. Several levels give you objectives that you must complete to ultimately move forward, but you can do those objectives in whatever order you desire.  Equally the story feels to develop around you, the player.  It’s up to you whether or not you delve deeper into the myth and seek out the audio diaries, and of course there’s the choice of how to deal with the little sisters.  Layered on top of that are you abilities and upgrades, all at your choice.  It works really well, all the way up until the point where you meet Ryan.  At that point all players must go through a single choke point with only one outcome.  Thus their choice is removed.  My protest with Bioshock was simply to stop playing – I still have no idea how it actually ends.</p>
<p>Mass Effect 3 has obviously created a similar reaction, though a much stronger one than my silent protest.  Throughout the trilogy players have been making what they believed were unique decisions, and the games responded accordingly.  The achievement by Bioware is staggering, and from an external perspective very inspirational.  Logistically though, there could never be enough endings to satisfy every possible outcome, and hopefully this post has gone some way to showing why not.</p>
<p><span style="color: #808080">Disclaimer: I don&#8217;t work for EA or Bioware, and wasn&#8217;t involved in the creation of Mass Effect at any point.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/03/the-perception-of-interactivity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extravagant Cheating via Direct X</title>
		<link>http://www.altdevblogaday.com/2012/04/02/extravagant-cheating-via-direct-x/</link>
		<comments>http://www.altdevblogaday.com/2012/04/02/extravagant-cheating-via-direct-x/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 00:00:41 +0000</pubDate>
		<dc:creator>Forrest Smith</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25288</guid>
		<description><![CDATA[<p>Online PC gaming is known for being full of dirty cheaters. Cheats can be implemented through many methods from simple to impressively complex. Macros, hex editing, memory inspection, memory modification, DLL injection, network manipulation, packet modification, and lord knows how many more. These various methods are then used to implement cheats such as rapid fire, no clip, aimbots, wallhacks, etc.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/02/extravagant-cheating-via-direct-x/" class="more-link">Read more on Extravagant Cheating via Direct X&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Online PC gaming is known for being full of dirty cheaters. Cheats can be implemented through many methods from simple to impressively complex. Macros, hex editing, memory inspection, memory modification, DLL injection, network manipulation, packet modification, and lord knows how many more. These various methods are then used to implement cheats such as rapid fire, no clip, aimbots, wallhacks, etc.</p>
<p>Today I want to discuss a specific form of hacking and how it’s done. I hesitate to do so, but it’s usage is already widespread amongst hack creators and users. The damage is already dealt. By sharing knowledge of its inner workings hopefully that damage can be mitigated.</p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">DirectX Interception</span></p>
<p>Direct X interception is a particularly naughty breed of hacking. It works by intercepting all calls from a game to Direct X [1]. The intermediate process can then do whatever it wants with that information. Most of the time the call will be passed directly onto the real DirectX without modification.</p>
<p>However in special cases you can do something clever. If the render call is for an enemy player then you can determine its screen position. In many cases that player may be behind world geometry and will either fail z-buffer checks or be covered by subsequent draw calls. Too late, the enemy screen location is known. At the end of the frame you can create a new draw call to DirectX to draw a box around that screen location. Boom, that’s a wallhack.</p>
<p>This type of wallhack is rampant. Even for the most popular of games. Here’s what it looks like for Battlefield 3.</p>
<p style="text-align: center"><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/battlefield_3_hax.jpg"><img class="aligncenter  wp-image-25291" src="http://altdevblogaday.com/wp-content/uploads/2012/04/battlefield_3_hax.jpg" alt="" width="533" height="300" /></a></p>
<p>This exists for every popular PC shooter you can imagine. All Battlefields, all Call of Duties, all Source engine games, all Unreal Engine games, etc.</p>
<p>The next step is to simulate mouse input by sending input messages to the app. With a known crosshair location and known screenspace enemy location this is easy. Bam, that’s an aimbot.</p>
<p>Flagrant aimbots can instantly snap from enemy to enemy. To avoid trivial detection the simulated input can be smoothed over time. Even more realistic aimbots overshoot the target intentionally before narrowing in. Other variations don’t move the crosshairs but do auto-fire when they are over an enemy target.</p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Coolest AI Ever</span></p>
<p>Wallhacks and aimbots are pretty wicked, but it’s just the beginning. What would happen if someone turned it up to 11? Matthew Fisher, a grad student at Stanford, did exactly this, and it’s the coolest thing ever.</p>
<p>Using the basic methods described above he wrote an AI that can play Starcraft 2. The camera jumps around so fast it’s impossible to keep up with. Please watch a few seconds of the video just to get an idea of what’s going on.</p>
<span style="text-align:center; display: block;"><a href="http://www.altdevblogaday.com/2012/04/02/extravagant-cheating-via-direct-x/"><img src="http://img.youtube.com/vi/FBZT2ukipkc/2.jpg" alt="" /></a></span>
<p>Let’s break it down.</p>
<ol>
<li>Intercept Direct X calls to determine exactly what units are visible and where they are.</li>
<li>With full knowledge of screen units pick an AI action to perform.</li>
<li>Send input commands to game to select units.</li>
<li>Send input commands to game to issue orders to selected units.</li>
<li>Move camera.</li>
<li>Goto 1.</li>
</ol>
<p>The automated player is driven by simulated mouse input which requires a single frame to process. This prevents it from running at ludicrous warp speed, but as the video demonstrates it can run the entire loop several times per second. Pro Starcraft gamers play the game around 300 actions per minute (APM). The automated player could theoretically hit about 3,600 APM.</p>
<p>Coolest. AI. Ever.</p>
<p>Matt wrote a large article on this player and his version of a DirectX interceptor. I highly recommend reading it <a href="http://graphics.stanford.edu/~mdfisher/GameAIs.html">here</a>.</p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Processing the Frame</span></p>
<p>Let’s go back for a moment and explain away some hand wavey magic. How exactly do you determine what a DirectX draw calls are for an enemy unit? By careful examination of what’s being rendered of course!</p>
<p>If you’ve ever used PIX, or something similar, then you’ve seen a view of the screen as it’s being rendered one call after another. By examining the vertex count, textures, shaders, etc you can figure out a lot.</p>
<p>Matt shows a breakdown of how he does this for Starcraft 2 so let’s take a look <a href="http://graphics.stanford.edu/~mdfisher/CaptureA/Capture.html">here</a>. Scroll down a bit and check out step 18. Upon visual inspection it’s obvious that a Void Ray unit is rendered. You can record what data was used in that call and use it to determine the screen location of all void rays in the future. Voila!</p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Changing Calls</span></p>
<p>I’ve discussed intercepting calls to determine unit locations. You can also add calls to render wall hacks. Finally, you can modify calls. This could be done to change textures or models.</p>
<p>For example an advantage can be gained by replacing player textures with bright red making enemies stand out. In a shooter you might as well go full wallhack so it’s more useful in other genres. [2]</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/counter_strike_model_hack.jpg"><img class="aligncenter size-medium wp-image-25292" src="http://altdevblogaday.com/wp-content/uploads/2012/04/counter_strike_model_hack-300x202.jpg" alt="" width="300" height="202" /></a></p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Cheat Prevention</span></p>
<p>So how can developers prevent this sort of cheating? Unfortunately it&#8217;s not easy and there are no silver bullets. That such cheats continue to exist for games such as Battlefield, Call of Duty, and Team Fortress 2 should indicate the complexity of the situation. There are however a variety of strategies that can help.</p>
<p>Game data can be modified to break cheating tools. If the tool relies on vertex count then modifying the data could break the tool. Hackers are of course exceptionally fast at updating their tools and can do so faster than devs. Run-time dynamic modification may help but high poly player models will always stand out. Breaking meshes into smaller pieces with random jitter could help hide them but there are both logistical and performance issues to consider.</p>
<p>It’s possible to retrieve the final frame buffer and analyze it for illegitimate additions. This is unreliable and is likely slow. I have heard tales of games doing this only for the cheating tools to detect the check and turn themselves off for a frame.</p>
<p>Anti-virus like process detection is another option. Punkbuster attempts this but it does not appear to work well. Blizzard&#8217;s proprietary Warden software performs similar functionality and seems to be effective.</p>
<p>Player data analysis is always useful. The Starcraft 2 AI is exceedingly cool but would never survive in the wild. It’s not difficult to spot and ban a 3600 apm player. Pinpointing wall hackers in a shooter is more challenging but is extremely viable. You should definitely be gathering and analyzing many data points.</p>
<p>Some companies have attempted to utilize the legal system to shut down cheat creators. This <em>may</em> work within the United States, but many cheats comes from Eastern Europe or Russia. There is no chance for lawsuits to halt their operations.</p>
<p>IP addresses change and mac addresses can be spoofed, but they can still be useful. If you have a known cheater and those addresses match up to a second account then it may be worth investigating. It’s not quite cheating, but League of Legends uses them to help detect smurf accounts. If there is a max level account followed by a level 1 account playing extremely well then you can quickly increase the matchmaking skill rating for the level 1 account to protect the real newbs.</p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Cheat Detection</span></p>
<p>The fact of the matter is that wallhacks and aimbots will always exist on PC. You can&#8217;t stop them. The cat and mouse game between developers and hackers will forever be played, but it&#8217;s not the end game.</p>
<p>Preventing players from cheating is important. Detecting when players cheat is possibly even more important. A common strategy is once cheaters are detected to let them keep playing for a few weeks. Then you drop the banhammer on thousands of players at once. From that point on players will hesitate before cheating because the player will never know if the dev knows.</p>
<p>There are companies that don’t care about preventing cheats if they are rarely used. What they care about is detecting those rarely used cheats and immediately banning the users. It&#8217;s a different and non-obvious mindset that changes how you attack the problem.</p>
<p>For example, Blizzard does not validate all player movement within World of Warcraft. There are too many players and it requires too much work to check every single position update for every single player. With some bit twiddling it’s possible to fly, run super fast, no clip, and even teleport.</p>
<p>The position update itself isn’t checked, but suspicious activity can still be detected. Entering unreachable regions, visiting multiple zones impossibly fast, positions inside geometry, player reports, etc. Once suspicious activity is detected the account can be auto-flagged and then expensive validation checks can be performed for only a handful of players.</p>
<p>Here’s an amusing video where a WoW player teleport hacks for a mere 2 minutes before getting banned. In the comments he claims the ban wasn&#8217;t due to the teleport but from the mining of ore with a bad z-axis value. The teleport itself wasn’t prevented but other more subtle behavior led to an impressively quick ban.</p>
<span style="text-align:center; display: block;"><a href="http://www.altdevblogaday.com/2012/04/02/extravagant-cheating-via-direct-x/"><img src="http://img.youtube.com/vi/wTxQV6dbbIA/2.jpg" alt="" /></a></span>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Another Approach</span></p>
<p>Do you know what one of Microsoft&#8217;s top anti-cheat measures on Xbox is? Achievements. Players are incredibly invested in their profiles and achievement scores. It takes years to build up and most players won’t dare risk losing it all by cheating.</p>
<p>How many players are willing to risk max level characters, collections of hats, and precious achievement scores just to cheat a little? Not many. At least not after the first ban wave.</p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Wizardry for Good</span></p>
<p>It’s worth noting that DirectX interception isn’t just for evil deeds. If you’ve played any games on Steam then you are likely familiar with their in-game overlay accessed via Shift-Tab. This overlay works exactly like the wallhack! Steam detects the Shift-Tab keystroke, hooks into DirectX calls, and renders the overlay on top of the actual game automagically. That’s pretty slick if you think about it.</p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Conclusion</span></p>
<p>This has been a brief summary on cheating by means of Direct X interception. It can be used in all sorts of nasty ways and if you have a popular multiplayer game it’s probably being used. It’s hard to stop and it can be hard to detect but it’s important to know about and understand. Keep fighting the good fight my friends.</p>
<p><span class="Apple-style-span" style="font-size: 20px;font-weight: bold">Footnotes</span></p>
<ol>
<li>This method works perfectly with OpenGL as well. I don’t mean to call out Direct X specifically but do so for reader clarity. Sorry Microsoft!</li>
<li>In some games, including the Counter-Strike example, this can be done more easily with a simple data file replacement.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/02/extravagant-cheating-via-direct-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>There are eight million blogs about Mass Effect’s ending. This is one of them.</title>
		<link>http://www.altdevblogaday.com/2012/04/01/there-are-eight-million-blogs-about-mass-effects-ending-this-is-one-of-them/</link>
		<comments>http://www.altdevblogaday.com/2012/04/01/there-are-eight-million-blogs-about-mass-effects-ending-this-is-one-of-them/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 22:40:40 +0000</pubDate>
		<dc:creator>Kyle-Kulyk</dc:creator>
				<category><![CDATA[#AltDev Updates]]></category>
		<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Game design]]></category>
		<category><![CDATA[General Interest]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25280</guid>
		<description><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/Our-Princess-is-in-Another-Castle.jpg"><img class="alignright  wp-image-25281" style="margin: 5px" src="http://altdevblogaday.com/wp-content/uploads/2012/04/Our-Princess-is-in-Another-Castle.jpg" alt="" width="385" height="218" /></a>When Mass Effect 3 was released earlier this month it was met with much anticipation and critical praise as the popular space epic concluded.  Immediately, however, a certain subset of fans became enraged by some of the decisions Bioware made with respect to the series.  Even before the game was announced fans expressed anger that the series was daring to go multiplatform.  At launch gamers raged at the “day one” inclusion of downloadable content, something quite common in games today but the real spectacle was the fan reaction to Mass Effect 3’s ending and the subsequent hate campaigns targeting Bioware staff, the FTC complaints of false advertising and the seemingly never-ending series of petitions to force Bioware to alter Mass Effect 3’s endings.  It was on this topic that I thought I’d weigh in and add my voice to the many who think some gamers have lost their damn minds.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/01/there-are-eight-million-blogs-about-mass-effects-ending-this-is-one-of-them/" class="more-link">Read more on There are eight million blogs about Mass Effect’s ending. This is one of them&#8230;.</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/Our-Princess-is-in-Another-Castle.jpg"><img class="alignright  wp-image-25281" style="margin: 5px" src="http://altdevblogaday.com/wp-content/uploads/2012/04/Our-Princess-is-in-Another-Castle.jpg" alt="" width="385" height="218" /></a>When Mass Effect 3 was released earlier this month it was met with much anticipation and critical praise as the popular space epic concluded.  Immediately, however, a certain subset of fans became enraged by some of the decisions Bioware made with respect to the series.  Even before the game was announced fans expressed anger that the series was daring to go multiplatform.  At launch gamers raged at the “day one” inclusion of downloadable content, something quite common in games today but the real spectacle was the fan reaction to Mass Effect 3’s ending and the subsequent hate campaigns targeting Bioware staff, the FTC complaints of false advertising and the seemingly never-ending series of petitions to force Bioware to alter Mass Effect 3’s endings.  It was on this topic that I thought I’d weigh in and add my voice to the many who think some gamers have lost their damn minds.</p>
<p>First, I’d like to say I understand some fan disappointment.  Without going into spoiler territory, Mass Effect has always been about choices and the choices the player makes throughout the game brings with it a very personal connection to the characters and events as they play out.  It’s the interactive nature of our media that differentiates the consumer experience of videogames from that of other media such as movies or television.  Bioware has never been shy about discussing and promoting the impact of the moral choices in their games, however those familiar with the series know that when it came to player decisions versus main plot points, plot points won out every time.  This should not have surprised anyone when it came down to the series conclusion.  Criticisms regarding plot holes and the lack of a satisfying ending may be warranted, but the fan reaction seems completely out of proportion.  We’ve all been disappointed by the ending of something or another and the more complicated a plot, the harder it is to wrap everything up into a neat little package.  This may come as a shock to some fans but you can’t always get what you want.</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/04/ME3ahyeschoices.jpg"><img class=" wp-image-25282 alignleft" style="margin: 5px" src="http://altdevblogaday.com/wp-content/uploads/2012/04/ME3ahyeschoices.jpg" alt="" width="369" height="217" /></a>Good stories have a beginning, middle and end.  Not “ends.”  I feel it is unrealistic to expect writers to create a strong, complex plot and then be expected to create multiple, satisfying endings.  I’m happy with one satisfying ending but many would argue that Mass Effect didn’t even give players that.  Many also think the ending was just fine.  I feel the gamers being the most vocal need to ask themselves, what would actually make you happy?  If there was an update tomorrow and when you replayed the game the ending was completely different, would that erase the memory of the original conclusion you received and leave you satisfied?   If the new endings still didn’t satisfy a certain amount of fans would you demand they do it again?  What are the rules on how many fans need to be vocally dissatisfied with an ending before you feel a company should be forced to change their artistic vision for a game?  What consideration is given, if any, to those happy with the current ending and what gives you the right to change the experience for those gamers?</p>
<p>You can&#8217;t please everyone all the time.  Whenever anything becomes popular, there will always be a subset of fans that find a reason to hate simply because they can.  There is no pleasing them.  It doesn’t matter if it’s videogames, music, movies or television you’ll always have a vocal minority that will hate what you’ve created just for the sake of hating, especially if something becomes popular.  We saw fans turn on Rockstar after their masterpiece Grand Theft Auto 4 was released; we’ve seen a backlash against Infinity Ward despite consistently shipping an excellent product.  We’re seeing it now with Bioware.  To cave into these vocal fanatics sets a dangerous precedent and takes creative control away from the artists to see their creative visions realized.  I firmly hope Bioware doesn’t touch the ending.  All it does is teach the entitled among us that if they scream and cry long enough and loud enough, they can get their way and as a parent I can attest, that’s a recipe for future disaster.  Give in and it will never end.   Bioware needs to stand by their work and continue their strong stand against those targeting their staff directly.  If gamers don’t like it, let them vote with their wallets.</p>
<p>Fans have often influenced their favorite series and if a writer wishes to remain popular it is important to listen to fans to an extent, but ultimate creative control needs to reside with creators.  Sherlock Holmes appeared to be famously killed off only to be resurrected at a later point due to fan demands.  Spock met his heroic end in Star Trek 2, only to be brought kicking and screaming back from the dead in the terrible, terrible Star Trek 3 but some Mass Effect fans are asking for a complete do-over of the ending.  Bioware has commented that they were willing to possibly have loose ends addressed in upcoming DLC (and I support this move as should fans) but imagine Star Trek 2 edited so Spock makes it out alive and pops out of his coffin at the end to yell  “Hiyoooo!” because it would be more pleasing.  Expecting Bioware to simply rewrite their ending is carpet chewing mad and Bioware shouldn’t even entertain the idea.  Already we see Hollywood taking fewer and fewer risks with story-telling trying to cater to everyone.  The end result is often bland and generic.  This happens to an extent currently in the games industry with developers and publishers erring on the side of caution in an attempt to protect the massive investment associated with developing big titles.  Gamers always rally against this effect but here the message Mass Effect gamers are sending resoundingly to the game industry is “Don’t take risks and don’t upset us or we’ll turn on you in a heartbeat.”</p>
<div id="attachment_25283" class="wp-caption alignright" style="width: 310px"><img class=" wp-image-25283" style="margin: 5px" src="http://altdevblogaday.com/wp-content/uploads/2012/04/MiseryScene.jpg" alt="" width="300" height="209" /><p class="wp-caption-text">I have your new ending to Mass Effect 3 right here.</p></div>
<p>I&#8217;ve heard others draw parallels with Stephen King’s Misery where a crazed fan holds a writer captive and submits him to numerous tortures because she’s unhappy with his recent book’s ending.  She forces him to write a follow-up novel bringing the main character back to life to continue the story.  I don’t think this is a fair comparison.  Even in her madness, Annie Wilkes never expected the author to rewrite history and change the ending as some Mass Effect fans are demanding.   For the good of games as a truly creative medium, this movement needs to be squashed.  <a href="https://twitter.com/#!/search/%23ChangeTheEnding" target="_blank">#ChangeTheEnding</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/01/there-are-eight-million-blogs-about-mass-effects-ending-this-is-one-of-them/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AltDevPanel on Optimization Video</title>
		<link>http://www.altdevblogaday.com/2012/04/01/altdevpanel-on-optimization-video/</link>
		<comments>http://www.altdevblogaday.com/2012/04/01/altdevpanel-on-optimization-video/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 20:07:19 +0000</pubDate>
		<dc:creator>Don Olmstead</dc:creator>
				<category><![CDATA[#AltDev Updates]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25275</guid>
		<description><![CDATA[<p>Here are the results of the inaugural #AltDevPanel. Featuring Mike Acton (follow him on <a href="https://twitter.com/#!/mike_acton">Twitter</a> and <a href="https://plus.google.com/u/0/105595823502776413734/posts">Google+</a>), Tony Albrecht (<a href="https://twitter.com/#!/TonyAlbrecht">Twitter</a> and <a href="https://plus.google.com/u/0/117606732344074079965/posts">Google+</a>), and John McCutchan (<a href="https://plus.google.com/u/0/106737154382790678002/posts">Google+</a>), discussing optimization.</p>
<span style="text-align:center; display: block;"><a href="http://www.altdevblogaday.com/2012/04/01/altdevpanel-on-optimization-video/"><img src="http://img.youtube.com/vi/fE25cTTSwHE/2.jpg" alt="" /></a></span>
<p>Let us know your thoughts on the results. We&#8217;re very interested in feedback on how to make #AltDevPanel better in the future.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/01/altdevpanel-on-optimization-video/" class="more-link">Read more on AltDevPanel on Optimization Video&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Here are the results of the inaugural #AltDevPanel. Featuring Mike Acton (follow him on <a href="https://twitter.com/#!/mike_acton">Twitter</a> and <a href="https://plus.google.com/u/0/105595823502776413734/posts">Google+</a>), Tony Albrecht (<a href="https://twitter.com/#!/TonyAlbrecht">Twitter</a> and <a href="https://plus.google.com/u/0/117606732344074079965/posts">Google+</a>), and John McCutchan (<a href="https://plus.google.com/u/0/106737154382790678002/posts">Google+</a>), discussing optimization.</p>
<span style="text-align:center; display: block;"><a href="http://www.altdevblogaday.com/2012/04/01/altdevpanel-on-optimization-video/"><img src="http://img.youtube.com/vi/fE25cTTSwHE/2.jpg" alt="" /></a></span>
<p>Let us know your thoughts on the results. We&#8217;re very interested in feedback on how to make #AltDevPanel better in the future.</p>
<p>Thanks again to Google for allowing us early access to On Air Hangouts!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/01/altdevpanel-on-optimization-video/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Show, Don&#8217;t Tell</title>
		<link>http://www.altdevblogaday.com/2012/04/01/show-dont-tell/</link>
		<comments>http://www.altdevblogaday.com/2012/04/01/show-dont-tell/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 19:43:24 +0000</pubDate>
		<dc:creator>Rob Braun</dc:creator>
				<category><![CDATA[Game design]]></category>
		<category><![CDATA[General Interest]]></category>
		<category><![CDATA[Visual Arts]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25269</guid>
		<description><![CDATA[<p>Anyone who has worked with storytelling in some shape or form has probably heard the phrase &#8220;Show, don&#8217;t tell&#8221; a million times. It&#8217;s such a simple concept, and yet it is one of the hardest to pull off effectively. In our everyday lives we generally tend to not go into too much detail when describing something and this easily carries into our work. It&#8217;s easy to say, &#8220;The building was huge,&#8221; but it&#8217;s far more effectively worded as &#8220;The building looked as though it was built to house the mythical Titans.&#8221; I firmly believe that the best way to learn and understand a concept is to analyze those who do it better. That being said, we&#8217;re going to look at two examples: the opening intro to Pixar&#8217;s <em><a href="http://www.youtube.com/watch?v=UHMD_EqM61I&#38;feature=related">Up</a></em>, and an animated short called <em><a href="http://vimeo.com/38591304">Ruin</a></em>. It&#8217;s advisable to watch <em>Ruin</em> and at the very least the linked intro to <em>Up</em> as I&#8217;m going to be talking about both in a fair amount of detail and it&#8217;s best if you know the materiel I&#8217;m referencing. If you haven&#8217;t seen <em>Up</em> I highly recommend going out and watching the film all the way through. It&#8217;s an amazing film and there&#8217;s no reason not to go see it. In fact, go watch it right now, the article will be here when you get back. I promise.</p>
<p><a href="http://www.altdevblogaday.com/2012/04/01/show-dont-tell/" class="more-link">Read more on Show, Don&#8217;t Tell&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Anyone who has worked with storytelling in some shape or form has probably heard the phrase &#8220;Show, don&#8217;t tell&#8221; a million times. It&#8217;s such a simple concept, and yet it is one of the hardest to pull off effectively. In our everyday lives we generally tend to not go into too much detail when describing something and this easily carries into our work. It&#8217;s easy to say, &#8220;The building was huge,&#8221; but it&#8217;s far more effectively worded as &#8220;The building looked as though it was built to house the mythical Titans.&#8221; I firmly believe that the best way to learn and understand a concept is to analyze those who do it better. That being said, we&#8217;re going to look at two examples: the opening intro to Pixar&#8217;s <em><a href="http://www.youtube.com/watch?v=UHMD_EqM61I&amp;feature=related">Up</a></em>, and an animated short called <em><a href="http://vimeo.com/38591304">Ruin</a></em>. It&#8217;s advisable to watch <em>Ruin</em> and at the very least the linked intro to <em>Up</em> as I&#8217;m going to be talking about both in a fair amount of detail and it&#8217;s best if you know the materiel I&#8217;m referencing. If you haven&#8217;t seen <em>Up</em> I highly recommend going out and watching the film all the way through. It&#8217;s an amazing film and there&#8217;s no reason not to go see it. In fact, go watch it right now, the article will be here when you get back. I promise.</p>
<p><em>*WARNING: SPOILERS*</em></p>
<p>If there&#8217;s a group of people on this planet that have mastered the art of storytelling, it&#8217;s John Lasseter and the crew at Pixar, and I firmly believe that opening to <em>Up</em> represents the pinnacle of their storytelling abilities. In the first 10 minutes of the film we learn everything we need to need to know about about Carl and Ellie&#8217;s relationship without a single word of dialogue being spoken. In a matter of minutes we see Carl and Ellie go from a young couple in love, to a couple devastated by an inability to start a family, to them overcoming their grief and moving on with their lives, and the pain Carl goes through as Ellie passes away. We know from the opening montage that despite the gruff exterior Carl displays in beginning, he is a loyal and caring man to those who are closest to him. We understand why he went to such extreme lengths to journey to Paradise Falls and what reaching his destination really means to him, and we understand the full emotional gravitas of his decision to sacrifice his journey in favor of saving Russel at the end of the film.</p>
<p>On the other end of the emotional spectrum is <em>Ruin,</em> which unlike <em>Up</em> isn&#8217;t trying to tell an emotional story, so that makes its job a little easier. Like the intro to <em>Up</em>, there isn&#8217;t a single word spoken throughout the entire course of short, but we learn everything we need to about the world the story is set in. From the opening establishing shots we see <em>Ruin</em> is set in a future where nature has begun to reclaim what was built by humans and has been at it for a t least a few decades. We&#8217;re then given a brief taste of how far humanity had progressed before its downfall with the introduction of the main character. We see him capable of creating a link with certain types of technology and controlling said technology with a mere thought. We&#8217;re shown brief hints of the possible downfall of man through quick flashes of a warning about a quarantine. Without a single word being uttered, we know everything we would need to know about this world.</p>
<p>Now, these are just two examples of the &#8220;Show, Don&#8217;t Tell&#8221; principle, and for every good example there are just as many, if not more, bad ones. I will be the first to admit that it far easier to apply this principle in a visual medium, such as animation and film, than it is in literature, but the principle still applies none-the-less. By showing your audience what you&#8217;re trying to say you help create a richer and deeper experience that will stay with with them long after they&#8217;ve finished watching, reading, or playing.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/04/01/show-dont-tell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why I hate Test Driven Development</title>
		<link>http://www.altdevblogaday.com/2012/03/30/why-i-hate-tdd/</link>
		<comments>http://www.altdevblogaday.com/2012/03/30/why-i-hate-tdd/#comments</comments>
		<pubDate>Fri, 30 Mar 2012 20:43:59 +0000</pubDate>
		<dc:creator>Rob-Galanakis</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25261</guid>
		<description><![CDATA[<p>I have no problem saying that I write good code. I place a focus on TDD and thorough unit and integration testing. I document everything I write (not just function documentation- I document classes, modules, and systems). The fact is, since I&#8217;ve been doing these two things somewhat religiously, the amount of time I have spent debugging code has gone down dramatically. There are just not many bugs to find in most of the code I write, they are easy to narrow down when I find them, and they rarely regress.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/30/why-i-hate-tdd/" class="more-link">Read more on Why I hate Test Driven Development&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I have no problem saying that I write good code. I place a focus on TDD and thorough unit and integration testing. I document everything I write (not just function documentation- I document classes, modules, and systems). The fact is, since I&#8217;ve been doing these two things somewhat religiously, the amount of time I have spent debugging code has gone down dramatically. There are just not many bugs to find in most of the code I write, they are easy to narrow down when I find them, and they rarely regress.</p>
<p>This is a good thing, isn&#8217;t it? So why do I hate TDD?</p>
<p>Because <strong>debugging is fun.</strong> There, I said it. I love debugging. I think lots of clever people like debugging. I love someone having a problem, coming to me, looking at it together, getting up to walk around, look at the ceiling, talk to myself, stand in front of a whiteboard, draw some lines that spark some idea, try it, manually test a fix out, slouch down in my chair staring at my computer lost in thought, and repeating this until I actually find and fix the problem. Not just <em>think</em> I fixed it, but really sure that I fixed it because suddenly it all makes sense. At which point I spring a terrific boner for my obviously superior brain power that was able to find this problem that plagued mere mortals.</p>
<p>So the sad fact is, since I&#8217;ve been doing TDD, I haven&#8217;t been able to go on this ego-trip a single time in our TDD-written codebase. Sure, sometimes we get a bug in the UI, but those usually manifest easily. Oh, and I&#8217;ve definitely used some frameworks and API&#8217;s improperly and caused bugs because of that. But those are the annoying types of debugging we all have to do, not the  magical mystery tour described above.</p>
<p>I didn&#8217;t realize how much I missed debugging until it was gone. Fortunately, there&#8217;s still lots of legacy code and API&#8217;s to get my fix from.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/30/why-i-hate-tdd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to build irresistible social casino games</title>
		<link>http://www.altdevblogaday.com/2012/03/29/how-to-build-irresistible-social-casino-games/</link>
		<comments>http://www.altdevblogaday.com/2012/03/29/how-to-build-irresistible-social-casino-games/#comments</comments>
		<pubDate>Thu, 29 Mar 2012 18:00:59 +0000</pubDate>
		<dc:creator>Tyler York</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Game design]]></category>
		<category><![CDATA[General Interest]]></category>
		<category><![CDATA[game design]]></category>
		<category><![CDATA[game development]]></category>
		<category><![CDATA[gamedev]]></category>
		<category><![CDATA[social casino games]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25255</guid>
		<description><![CDATA[<p>This month’s <a href="http://kaleidoscope.kontagent.com/2012/03/21/up-the-ante-stay-ahead-in-social-and-mobile-casino-games/">Kontagent analytics webinar</a> was packed yesterday, with hundreds of developers from around the world tuning in to make it their most successful webinar ever. The topic? How to build ‘irresistible’ social casino games. Clearly, the social casino games space is heating up, and game developers and casino companies alike want to learn more. Teaching them was Dave Bezahler, the CEO of <a href="http://www.blitzoo.com/">Blitzoo</a>, a 20-person social game company that experienced great success with its <a href="http://www.appdata.com/apps/facebook/171222259597821-slotspot-casino-slots-blackjack-video-poker">SlotSpot</a> Facebook slots game. He shared his knowledge of the market and went through SlotSpot as a case study for social casino games.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/29/how-to-build-irresistible-social-casino-games/" class="more-link">Read more on How to build irresistible social casino games&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>This month’s <a href="http://kaleidoscope.kontagent.com/2012/03/21/up-the-ante-stay-ahead-in-social-and-mobile-casino-games/">Kontagent analytics webinar</a> was packed yesterday, with hundreds of developers from around the world tuning in to make it their most successful webinar ever. The topic? How to build ‘irresistible’ social casino games. Clearly, the social casino games space is heating up, and game developers and casino companies alike want to learn more. Teaching them was Dave Bezahler, the CEO of <a href="http://www.blitzoo.com/">Blitzoo</a>, a 20-person social game company that experienced great success with its <a href="http://www.appdata.com/apps/facebook/171222259597821-slotspot-casino-slots-blackjack-video-poker">SlotSpot</a> Facebook slots game. He shared his knowledge of the market and went through SlotSpot as a case study for social casino games.</p>
<p><img src="https://lh5.googleusercontent.com/AshGff04IDy-LLE_eXeMpfJP-Htm6J8ujc4Hd6FctTiOs5-_Ooo6dWDtaU73CCdvREvU8UTA_26PfWFp_fo6hfpATgbjadV-1dPyUc_3neVoUugWFmE" alt="" width="592px;" height="296px;" /></p>
<p><img src="http://blog.betable.com/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /><strong>A rapidly growing market</strong><br />
It’s no secret that there’s been a ton of interest in social casino games in the past 6 months. Two social casino game companies, Playtika and DoubleDown, were <a title="DoubleDown acquired for $500m, or $100 per player" href="http://blog.betable.com/doubledown-acquisition-facebook-gambling/" target="_blank">recently purchased at massive, 9-figure valuations</a>. Everyone from <a title="EA PopCap's Lucky Gem Casino offers polished but uninspiring video slots action" href="http://www.insidesocialgames.com/2012/02/23/popcaps-lucky-gem-casino-offers-polished-but-uninspiring-video-slots-action/" target="_blank">EA</a> to <a title="Zynga teams up with Slingo to publish Bingo-slot-machine hybrid game on Facebook" href="http://venturebeat.com/2012/02/15/zynga-teams-up-with-slingo-to-publish-bingo-slot-machine-hybrid-game-on-facebook/" target="_blank">Zynga</a> are getting in on what is expected to be the next hot social game genre. Kontagent also commented that their fastest-growing customer segment has been social and mobile casino games. But what does this all mean for game developers looking to get into the space?</p>
<p>First of all, if you’re not sitting on a pile of cash, don’t bother looking at Facebook. The viral channels that made Facebook a great platform for indie game developers are dead, says Dave. While this is true for Facebook in particular, competition in the social casino games genre has driven up CPA prices on all platforms. You should expect to be <a href="http://bhorowitz.com/2011/04/15/peacetime-ceowartime-ceo/">at war from day 1</a>. Many newcomers are looking at cross-platform development solutions so they can spread their eggs across multiple baskets.</p>
<p>When being born into wartime, it’s important to pick your beachhead early. For poker, skill-based and sports-based games, Dave recommends targeting a young male audience. For slots and other chance-based games, the audience remains <a href="http://blog.betable.com/social-gamers-are-gamblers/">primarily older females</a> (typically 65% of slot players are female according to Dave) but is starting to drift closer to an even gender ratio. This drift is due to the changing nature of how slots are presented to the player: men can try the game for free, play for home, and play online. These changes make slots-type games more appealing to a broader audience.<br />
<img src="https://lh4.googleusercontent.com/Y4vdhGZdfKcovkO9_0FrV3FsTKqjIS81Fpg4975GpWtHTZ_D3U2iU-BAc3kxkcXh-28cLDh8bG3j0L8nTktiooTRW6qS-7Cz-Txon_R6blMEVT00z_0" alt="" width="618px;" height="449px;" /></p>
<p>Furthermore, these changes make casino-style games more appealing to a broader audience across the board. If you look at the difference in growth curves between FarmVille style games and social casino games, casino games show more consistent, wider growth curves. This shows that casino games keep players engaged longer and are less reliant on a huge launch for success.</p>
<p>Lastly, Dave warned social game developers that real-money gambling games are going to be launched in many if not all major platforms in the next year. Facebook is already looking into allowing real-money gambling in the UK, and the few mobile gambling apps that already inhabit the Apple and Google app stores are <a href="http://blog.betable.com/mobile-gambling-takes-off-betfairs-mobile-use/">experiencing meteoric growth</a>. Real-money gambling games are going to be tough to compete against because these companies can afford a much higher CPA than virtual currency game developers. However, real-money gambling companies come from a world where each player is a paying player, and aren’t as familiar with the freemium model. If you’re intelligent with your user acquisition and optimize your free-to-paid conversion, you can compete with these giants.. for now.</p>
<p><img src="https://lh3.googleusercontent.com/ljfr77pj5u8LsyLyYkLeT1zgxCbCwwSzteLONTpOd-M9YtRmgrN4o5HS91zeh59ZXpi2qzVk6yCh7TiNfmrDSHUfvpYsTrbtg8tbdWOo_DPzw_2nNog" alt="" width="619px;" height="397px;" /></p>
<p><strong>SlotSpot Case Study: Build, learn, iterate</strong><br />
Blitzoo built SlotSpot in just 6 weeks with a single-minded focus on a <a href="http://en.wikipedia.org/wiki/Minimum_viable_product">Minimum Viable Product</a>, or MVP. The game had no friends bar (a staple of Facebook games), no quests, no gifts, no achievements, and only 3 slot machines to play. The game did have levels and XP, but there was no reward for levelling up. Instead, Blitzoo focused on cranking out new features each week to fill in the gaps in their product. By cultivating customer feedback via their Facebook page, they were able to quickly prioritize the most important features on their product roadmap. Then, through live A/B testing of their game, they were able to test these assumptions about what features the audience was really interested in. All in all, Blitzoo used <a href="http://www.startuplessonslearned.com/">Eric Ries’ Lean Startup</a> methodology to impressive effect with their first social game (more on this in a later post).</p>
<p>When building his MVP product, Dave highlighted the importance of analytics and metrics. You need metrics for every piece of the game business:</p>
<p><span style="text-decoration: underline">User Acquisition</span>. You need to segment your inbound users and see which creative, which demographics and which countries converted most effectively.</p>
<p><span style="text-decoration: underline">Free-to-paid Conversion.</span> Which trigger got players to purchase? Which offer got that finicky player to finally buy? What creative was most effective?</p>
<p><span style="text-decoration: underline">Game Balance.</span> What is the average session length? How many spins does it take until they are out of money? How does this change as they level up?</p>
<p><span style="text-decoration: underline">Player Temperature.</span> This was Blitzoo’s own measure of positive vs. negative player feedback.</p>
<p>As you are building your game, you should always be asking yourself: what do I need to know? The answer will help you determine the metrics that are most important to your business.<br />
<img src="https://lh4.googleusercontent.com/FYJE7yolzePuEaINVWR72FP10NFizqZLkKRbkNWu6za54uVFtt3iF0YHaTVVYui79Cx4wAn0_JQ57HDNPKWMvwhQQ9u-qJDr527Wb3E9Aftx8qYidyE" alt="" width="619px;" height="352px;" /></p>
<p><strong>SlotSpot Case Study: Maximizing revenue</strong><br />
When looking to maximize your revenue, the first step you should take is to identify your high value players. For the social casino genre, there are two types of high value players: whales and evangelists. Whales are the players that spend the most, typically spending over 10x more than the typical ARPPU rate of your game. These players can spend over $1,000 per game and make up a substantial portion of your game’s revenue. Evangelists are players that love your game. They invite their friends, are active on forums, and give you valuable feedback. Catering to these two groups is of utmost importance for any social casino game.</p>
<p>To appeal to these high value customers, you should segment them internally via your analytics and present them with unique offers. You should also track their playing habits and retention so that you can optimize your game to keep these players around. When dealing with their support or feature requests, take a little more time to write a custom response. Small tweaks like these can create the best experience for these players and keep them coming back.</p>
<p><img src="https://lh3.googleusercontent.com/asA1_u3hwO313HapPfIlcEGAwbk6Pc4K2NSO2WfEST9qWSHqBgEoF9dsdkpTxSOufl7plr-LNyAioZxq7kbE5C-MZsr2erXFF7bu22ORbNOSajYyRHo" alt="" width="619px;" height="271px;" /></p>
<p>Your second step when maximizing revenue is a no brainer: maximize your revenue from all of your players. Run A/B Tests and experiments on players, using the Lean Startup as a framework. Notice how in the graph above, the revenue spikes get larger and larger. This is because the A/B tests are improving the promotions’ effectiveness over time.</p>
<p>When running these experiments, be sure to segment each test by player type, whether it’s a whale, evangelist, first-time buyer or someone who has never purchased. Dave says that 90% of players on Facebook never pay, 5% will typically pay, and 5% will maybe pay. The key to maximizing the amount of players that do pay is by running these experiments. Test different offers, such as coin bundles, sales or referral promotions, to see which copy performs better. Be sure you test one thing with each test: the copy, the collateral, or the offer itself. However, never test yourself into having only one “optimal” offer. Dave’s advice is that a variety of offers always performs better than one “best” offer. Also, be sure to vary your delivery method of the offers, whether it&#8217;s from an interstitial ad, a banner ad, or an in-game graphic.</p>
<p><strong>SlotSpot Case Study: Analytics as an immune system</strong><br />
The last key use for analytics is as an early warning system for bugs or problems with your game. Use your analytics tool to track errors, customer service requests, ARPPU, free-to-paid conversion, virality, average bet size, and anything else that is a mission-critical function of the game. If any of these numbers spike or drop dramatically, your canary is dead and it’s time to troubleshoot the coal mine. For example, Blitzoo had a problem where their overall revenue suddenly dropped. From their analytics, they could see that they had seen a significant increase in free-to-paid conversion rate, but an even larger decrease in ARPPU. It turned out that a promotion created by their marketing team was too aggressive, and undercut their price significantly. Once the error was spotted, fixing it was simple and the situation was resolved (damn it, marketing! :P).</p>
<p><img src="https://lh3.googleusercontent.com/XqoEv6QXq2GoA-EqDbZu5XZxi0yCvwshNCbnm-dzkxyhs2cp_faW8i3h0uLVLt-ZXG029KONsA8mCHHHWR-leNR1Pc6eDVE6ETnEnFDeFjvRKhxRXak" alt="" width="480px;" height="300px;" /></p>
<p><strong>Mobile: The Next Frontier</strong><br />
To conclude his presentation, Dave talked about Blitzoo’s upcoming transition to mobile and how they planned to adapt SlotSpot to the new space. He reiterated analytics’ importance on mobile because there are even more factors to a mobile player than a social player. There is no “single solution” for social sharing on mobile like there is on Facebook, so you need to incorporate and track a variety of them. Also, customer acquisition is done on a per-deal basis rather than run all through Facebook, so there’s a lot of segmentation there as well. Finally, customer onboarding is incredibly important to building a successful game on mobile and A/B tests are the key to optimizing your initial onboarding flow.</p>
<p>Dave pointed out that you simply cannot port a social network game to a mobile platform and expect the same results. For one, there’s a much shorter session length: mobile players spend 3 minutes per session on average while social players can spend up to 20 minutes. This requires a complete overhaul of game balance and the willingness to take an ax to your feature set. Offers are responded to differently on mobile, so you will need to start your in-game marketing testing all over again. Lastly, engagement is king on mobile. It’s much harder to keep players engaged with a mobile game and re-engage players that have been lost. Making all of these adjustments has been key to Blitzoo’s preparation for the mobile launch of their SlotSpots app.</p>
<p><img src="https://lh5.googleusercontent.com/31UGDjlqChMQm5kWBx_WQtstDEOW9pROWq3_Qk9UKeDJwEgUA5eNSfuOf_8pKg0OqEYMK2-5BGk-TjJug4VlzFqM8gbcv3pccZ3dZltgeTN7l_1810o" alt="" width="500px;" height="500px;" /></p>
<p><strong>Wrapping up</strong><br />
Thanks again to Blitzoo and Kontagent for throwing a great webinar. I’d recommend getting on their webinar circuit by <a href="http://kaleidoscope.kontagent.com/2012/03/21/up-the-ante-stay-ahead-in-social-and-mobile-casino-games/">signing up for their mailing list</a>, each one I attend keeps getting better.</p>
<p>The social casino space is on fire right now, and one can only expect the fire to spread to mobile. If you’re looking to get into this space, move quickly and buckle up, because it’s about to take off. And while you’re busy fending off incumbents, trying to keep distance from the newcomer nipping at your heels, and avoiding the real-money giants, you might want to look into <a href="https://developers.betable.com/developers/signin">Betable</a>. We’re the first and only platform that lets you add real-money gambling to games, and it might be the weapon you need to win in the social casino game space.<strong></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/29/how-to-build-irresistible-social-casino-games/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Put On Your Game Face</title>
		<link>http://www.altdevblogaday.com/2012/03/28/put-on-your-game-face/</link>
		<comments>http://www.altdevblogaday.com/2012/03/28/put-on-your-game-face/#comments</comments>
		<pubDate>Wed, 28 Mar 2012 18:34:21 +0000</pubDate>
		<dc:creator>David Czarnecki</dc:creator>
				<category><![CDATA[General Interest]]></category>
		<category><![CDATA[open source]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25233</guid>
		<description><![CDATA[<p><span style="text-decoration: underline"><strong>TL;DR</strong></span></p>
<p>I recently started a weekly blog series on our company blog called <a href="http://blog.agoragames.com/blog/category/game-face/">&#8220;Game Face&#8221;</a>. It is &#8220;our weekly round-up of our internal and external open source work here at Agora Games. Internal open source refers to our public projects that you can find over at our <a href="https://github.com/agoragames/">Agora Games GitHub</a> account. External open source work refers to projects that we contribute to in off-hours and may or may not have anything to do with video games because we’re swell folks like that.&#8221; This is important for our company and I think it should be for your company.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/28/put-on-your-game-face/" class="more-link">Read more on Put On Your Game Face&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><span style="text-decoration: underline"><strong>TL;DR</strong></span></p>
<p>I recently started a weekly blog series on our company blog called <a href="http://blog.agoragames.com/blog/category/game-face/">&#8220;Game Face&#8221;</a>. It is &#8220;our weekly round-up of our internal and external open source work here at Agora Games. Internal open source refers to our public projects that you can find over at our <a href="https://github.com/agoragames/">Agora Games GitHub</a> account. External open source work refers to projects that we contribute to in off-hours and may or may not have anything to do with video games because we’re swell folks like that.&#8221; This is important for our company and I think it should be for your company.</p>
<p><span style="text-decoration: underline"><strong>PUTTING ON THE GAME FACE<br />
</strong></span></p>
<p>At the beginning of 2012, I did an assessment of all the projects <a href="http://blog.agoragames.com/blog/2012/01/09/2011-open-source-projects/">we open sourced in 2011</a>. Late much? 22 projects wasn&#8217;t bad and I want to beat that number in 2012, but it got me thinking that this kind of information is timely and needs more regular attention. So, I started kicking around ideas for a blog series name. After a day, I settled on &#8220;Game Face&#8221;. &#8220;Game&#8221; obviously referred to the work we do in developing gaming-related libraries and middleware. &#8220;Face&#8221; would refer to the code-wise public face of the company and the developer(s) working on the individual libraries.</p>
<p><span style="text-decoration: underline">It will help you become a better writer</span>: If you&#8217;re a developer and you&#8217;re scared about writing a weekly blog series, you shouldn&#8217;t be. The focus of the blog is technical in nature, so you don&#8217;t need to spend a lot of time on exposition. If you&#8217;re good with your commit messages or keeping a CHANGELOG, the blog posts write themselves. For example, from an item in a recent blog post, &#8220;This releases addresses the first future idea from the README when the gem was released over a year ago to add a method allowing for bulk insert of data into a leaderboard.&#8221; Cut and paste for the most part my friends. The intrepid developer might even automate the creation of the initial blog post that can be wordsmithed by someone you deem more fluent in languages other than C++ :)</p>
<p><span style="text-decoration: underline">It will help you become a better developer</span>: We get feedback on our code each day from our co-workers. By opening up your code to the world, you get peer feedback beyond your immediate peanut gallery. You also get comments, questions and sometimes code where developers are using your code in new and interesting ways that you hadn&#8217;t thought of yet. Case-and-point: I recently integrated a patch to our leaderboard library with all the <a href="https://github.com/agoragames/leaderboard/pull/5">code and tests to allow for leaderboards in &#8220;reverse&#8221;</a> (lowest-to-highest) sorted order. I just hadn&#8217;t come across that use case in the games we&#8217;ve worked on where I needed a leaderboard appropriate for a racing game. But someone else did. And now our library is better off because of it. Beyond peer feedback, or any feedback, opening up your code and talking about it helps you to think about the ramifications of changes when there are developers other than you or your company using your code.</p>
<p><span style="text-decoration: underline">It will help you as a company</span>: By highlighting your company&#8217;s open source work, it may motivate your developers to want to take a stab at open source in the first place or to clean up a library for external publishing. You might also attract developers who put a high value on knowing their contributions will be recognized, whether they are internal or external, and that their contributions may see the light of day outside of your company&#8217;s hallowed halls. The last &#8220;Game Face&#8221; blog post I wrote highlighted a new library one of our developers had released that allowed you to parse Beersmith2 (beer brewing software) files in Ruby. I imagine many video game companies rely on open source to some degree, and so by publicly promoting your contributions to open source, it can also help you in the eyes of the open source community.</p>
<p><span style="text-decoration: underline">It will help you have awkward conversations</span>: I can&#8217;t tell you what to open source and what not to open source. You&#8217;ll have to talk as a team, as a company, and possibly with your lawyers to understand what you can and cannot open source. In 2011, there was only one instance where I went to our CEO to get a check on, &#8220;Can I open source this?&#8221; We walked around the block and our conversation went basically as follows:</p>
<p>Me: &#8220;I&#8217;d like to open source a leaderboard library. Given this is a core thing we do, is that OK?&#8221;</p>
<p>CEO: &#8220;So, someone else could do this before us using a similar method?&#8221;</p>
<p>Me: &#8220;Yes.&#8221;</p>
<p>CEO: &#8220;Ship it!&#8221;</p>
<p><span style="text-decoration: underline"><strong>FIN</strong></span></p>
<p>Hopefully I&#8217;ve made some compelling arguments that your company should highlight your internal and external open source development. Our weekly blog post series highlighting our internal and external open source work comes out on Friday and now I usually get one or two messages throughout the week in our group chat room asking, &#8220;What&#8217;s going in to Game Face this week?&#8221; It feels pretty good when I can say back, &#8220;Your face.&#8221; If your company does anything with open source, I&#8217;d love to know about it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/28/put-on-your-game-face/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asset packaging in browser-based games</title>
		<link>http://www.altdevblogaday.com/2012/03/28/asset-packaging-in-browser-based-games/</link>
		<comments>http://www.altdevblogaday.com/2012/03/28/asset-packaging-in-browser-based-games/#comments</comments>
		<pubDate>Wed, 28 Mar 2012 10:39:26 +0000</pubDate>
		<dc:creator>Rob Ashton</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25219</guid>
		<description><![CDATA[<p>I&#8217;ve written a <a href="http://altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/">couple</a> of <a href="http://altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/">posts</a> on asset management in web-based games already, and I still think they&#8217;re valid and useful on most of the points made in them.</p>
<p>However, in putting together my latest endeavour (a hack-n-slash isometric multi-player RPG in HTML5 canvas), I&#8217;ve learned a few more things and want to share them.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/28/asset-packaging-in-browser-based-games/" class="more-link">Read more on Asset packaging in browser-based games&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve written a <a href="http://altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/">couple</a> of <a href="http://altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/">posts</a> on asset management in web-based games already, and I still think they&#8217;re valid and useful on most of the points made in them.</p>
<p>However, in putting together my latest endeavour (a hack-n-slash isometric multi-player RPG in HTML5 canvas), I&#8217;ve learned a few more things and want to share them.</p>
<p><strong>TLDR;</strong> I&#8217;ve pushed the code I&#8217;m currently using to Github and it can be found here: <a title="Swallow: Resource packaging for JS games" href="https://github.com/robashton/swallow">https://github.com/robashton/swallow</a></p>
<p>Anyway &#8211; moving on we can discover some of these learnings:</p>
<h4><strong>Simply waiting for requested assets to load via HTTP on start-up isn&#8217;t always enough</strong></h4>
<p>In my <a href="http://altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/">earlier post</a>, I suggested if you had a resource caretaker which you requested resources like textures, sounds, models, shaders etc from &#8211; then it could take care of loading the data and return promises rather than the real things, this 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
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> modelOne <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'models/hovercraft.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> modelTwo <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'models/missile.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> explosionSound <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'sounds/explosion.wav'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
resources.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'fullyLoaded'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  game.<span style="color: #660066;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// use the resources</span>
  modelOne.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  modelTwo.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>And the world is a happy place to live in, we rely on those assets coming down via HTTP, rely on HTTP caching and everything else given to us and it works well.</p>
<p>However, we also rely on the initial state of the game indicating which resources it is going to need &#8211; and doesn&#8217;t account for other resources that might be requested once the game is under way (for example, explosions, other models/textures further in the world, sounds, etc).</p>
<p>This results in negative artifacts like &#8216;popping&#8217;, or sounds being played after the special effect has finished (or in bad cases, the player walking on an empty background!)</p>
<p>Therefore the answer is to pre-load, but how&#8230;?</p>
<h4><strong>The Application Cache</strong></h4>
<p>Now, I&#8217;m not going to give a full description of this, but essentially you can tell the browser &#8220;Hey, these are my resources, please download and cache them&#8221;, for example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">CACHE MANIFEST
# <span style="color: #CC0000;">2012</span><span style="color: #339933;">-</span>03<span style="color: #339933;">-</span><span style="color: #CC0000;">11</span><span style="color: #339933;">:</span>v1
&nbsp;
CACHE<span style="color: #339933;">:</span>
<span style="color: #339933;">/</span>favicon.<span style="color: #660066;">ico</span>
game.<span style="color: #660066;">html</span>
models<span style="color: #339933;">/</span>hovercraft.<span style="color: #660066;">json</span>
models<span style="color: #339933;">/</span>missile.<span style="color: #660066;">json</span>
sounds<span style="color: #339933;">/</span>explosion.<span style="color: #660066;">wav</span></pre></td></tr></table></div>

<p>We can generate this kind of application cache automatically as part of our deploy process by enumerating through the assets, and we can choose not to re-generate it if none of the files have changed.</p>
<p>When we re-generate it, we can set the timestamp (therefore indicating to the browser that because the manifest has changed it might like to go through those assets on the server and see which ones it needs to download).</p>
<p>We also have similar code to write against this, <em>&#8220;Update the resources if necessary, wait for this process to complete&#8221;</em></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">appCache.<span style="color: #660066;">addEventListener</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'updateready'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  game.<span style="color: #660066;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Ace.</p>
<p>This has its share of issues though &#8211; the biggest one is probably that it doesn&#8217;t really allow for any granularity in your app.</p>
<p>In this modern age of the internet, our users have short attention spans and a long initial load may well mean losing out on users &#8211; if you have different levels for example, you probably want to download each level and the assets for that level before you <em>play</em> that level &#8211; not at the beginning of the whole game.</p>
<p>In short, the Application Cache is great if you have a small self contained game (such as puzzle games), or if you want to fully support the game being playable offline immediately after download;  it does however come with its share of issues.</p>
<p>That brings us onto another option</p>
<h4><strong>Write your own Application Cache</strong></h4>
<p>We can easily emulate what the AppCache does for us by writing our own manifest definition and using that to pre-load files from the server. We can then rely on the browser-cache to carry on working the way it always has (so if files haven&#8217;t changed, don&#8217;t fetch them etc).</p>
<p>This is essentially like our first solution again, except we now have manifest files which describe what data needs pre-loading.</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="javascript" style="font-family:monospace;">resources.<span style="color: #660066;">preloadFromManifest</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'levels/levelOne.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> modelOne <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'models/hovercraft.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> modelTwo <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'models/missile.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> explosionSound <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'sounds/explosion.wav'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
resources.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'fullyLoaded'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  game.<span style="color: #660066;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// use the resources</span>
  modelOne.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  modelTwo.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>This still causes some issues &#8211; the browser may choose to not cache some objects, may decide that some things aren&#8217;t available offline, and weirdly give us some issues with sounds.</p>
<p>For example: One issue I discovered with sounds in my last Ludum Dare attempt was that you have to create a new Audio object every-time you play a sound &#8211; and the browser re-requests the asset from the URL you give it each time that happens!</p>
<p>Another problem with this approach is again it doesn&#8217;t scale too well &#8211; if you&#8217;ve got 500 textures, 500 HTTP requests is not really appropriate at with the current technology stack (Until SPDY or something similar is supported universally at least).</p>
<p>That brings us to where I am at the moment with my hack-n-slash multiplayer canvas RPG&#8230;</p>
<h4><strong>Bundle everything up into a single file!</strong></h4>
<p>How things come full circle &#8211; desktop game developers have been inventing and consuming package formats since time began, and now web-game developers can get in on that action too.</p>
<p>So hence writing a <a title="https://github.com/robashton/swallow" href="http://">command line utility in NodeJS</a> to scan a directory and package various files into a JSON file.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">.<span style="color: #660066;">json</span> <span style="color: #339933;">-&gt;</span> keep it <span style="color: #000066; font-weight: bold;">as</span> JSON
.<span style="color: #660066;">png</span> <span style="color: #339933;">-&gt;</span> Base64 encode it
.<span style="color: #660066;">wav</span> <span style="color: #339933;">-&gt;</span> Base64 encode it
.<span style="color: #660066;">shader</span> <span style="color: #339933;">-&gt;</span> add it <span style="color: #000066; font-weight: bold;">as</span> a string</pre></td></tr></table></div>

<p>This works well, as on the client loading these assets means writing a small amount of code like so:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> image <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Image<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
image.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;data:image/png;base64,&quot;</span> <span style="color: #339933;">+</span> imageResource.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>In actuality, what we end up doing is loading an entire asset package, say &#8216;assets.json&#8217; and writing the following code before loading the game.</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="javascript" style="font-family:monospace;">$.<span style="color: #660066;">getJSON</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'assets.json'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>rawData<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  preloadAssets<span style="color: #009900;">&#40;</span>rawData<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> preloadAssets<span style="color: #009900;">&#40;</span>rawData<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    forEachResourceInRawData<span style="color: #009900;">&#40;</span>rawData<span style="color: #339933;">,</span> preloadItem<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> preloadItem<span style="color: #009900;">&#40;</span>key<span style="color: #339933;">,</span> itemData<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> loader <span style="color: #339933;">=</span> findLoaderForFiletype<span style="color: #009900;">&#40;</span>key<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  increaseAwaitCounter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  loader<span style="color: #009900;">&#40;</span>key<span style="color: #339933;">,</span> itemData<span style="color: #339933;">,</span> decreaseAwaitcounter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
resources.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'complete'</span><span style="color: #339933;">,</span> startGame<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Where an implementation of a handler for a PNG might do 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="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> preloadPng<span style="color: #009900;">&#40;</span>key<span style="color: #339933;">,</span> itemData<span style="color: #339933;">,</span> cb<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> preloadedImage <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Image<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    preloadedImage.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;data:image/png;base64,&quot;</span> <span style="color: #339933;">+</span> itemData<span style="color: #339933;">;</span>
    preloadedAssets<span style="color: #009900;">&#91;</span>key<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> preloadedImage<span style="color: #339933;">;</span>
    preloadedImage.<span style="color: #000066;">onload</span> <span style="color: #339933;">=</span> cb<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>This means that once the assets file is loaded, the game can start and there are no delays in playing audio, displaying textures and so on and so forth.</p>
<p>Clearly this is massively simplified, because in the real world yet again what we actually do is.</p>
<h4><strong>Do the hybrid approach</strong></h4>
<ul>
<li>Load the assets for the current land</li>
<li>Request an asset</li>
<li>Is the asset in the preloaded package?</li>
<li>Yes? -&gt; Return a promise containing the asset</li>
<li>No? -&gt; Return a promise without that asset</li>
<li>-&gt; Make an HTTP request to get the asset</li>
<li>-&gt; Cache the asset</li>
</ul>
<p>For example, my little RPG pre-loads most of the textures and models used across the land, but downloads the actual tile information (where is a tile, what is on that tile) as the player walks around.</p>
<p>This is similar to the streaming that takes places in any reasonable desktop game, and offers a good compromise in a connected multiplayer game (and would work well for a disconnected one too).</p>
<p>I&#8217;ll push out the client code I&#8217;m using as a library at some point, but that&#8217;s not really a suitable candidate for &#8216;frameworking&#8217;, because homogenising something like asset management on the client side can do more harm than good.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/28/asset-packaging-in-browser-based-games/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AltDevPanel on Optimization</title>
		<link>http://www.altdevblogaday.com/2012/03/28/altdevpanel-on-optimization/</link>
		<comments>http://www.altdevblogaday.com/2012/03/28/altdevpanel-on-optimization/#comments</comments>
		<pubDate>Wed, 28 Mar 2012 01:46:05 +0000</pubDate>
		<dc:creator>Don Olmstead</dc:creator>
				<category><![CDATA[#AltDev Updates]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25201</guid>
		<description><![CDATA[<p><b>Update: Use this <a href="http://www.timeanddate.com/worldclock/meetingtime.html?iso=20120331&#38;p1=224&#38;p2=5&#38;p3=538">planner</a> to find the time for your city.</b></p>
<p>I’m happy to announce our first #AltDevPanel! Scheduled for this Saturday at 10PM PDT, we’ll be bringing together some masters of high performance programming to talk about their craft. Our scheduled panelists are <a href="http://altdevblogaday.com/author/mike-acton/">Mike Acton</a>, <a href="http://altdevblogaday.com/author/tony-albrecht/">Tony Albrecht</a>, <a href="http://altdevblogaday.com/author/john-mccutchan/">John McCutchan</a>, and <a href="http://altdevblogaday.com/author/jaymin-kessler/">Jaymin Kessler</a>.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/28/altdevpanel-on-optimization/" class="more-link">Read more on AltDevPanel on Optimization&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><b>Update: Use this <a href="http://www.timeanddate.com/worldclock/meetingtime.html?iso=20120331&amp;p1=224&amp;p2=5&amp;p3=538">planner</a> to find the time for your city.</b></p>
<p>I’m happy to announce our first #AltDevPanel! Scheduled for this Saturday at 10PM PDT, we’ll be bringing together some masters of high performance programming to talk about their craft. Our scheduled panelists are <a href="http://altdevblogaday.com/author/mike-acton/">Mike Acton</a>, <a href="http://altdevblogaday.com/author/tony-albrecht/">Tony Albrecht</a>, <a href="http://altdevblogaday.com/author/john-mccutchan/">John McCutchan</a>, and <a href="http://altdevblogaday.com/author/jaymin-kessler/">Jaymin Kessler</a>.</p>
<p>The optimization panel will focus on optimizations from a micro to a macro level, providing observations on what to do and what not to do when optimizing a code base. It will also delve into how to measure performance, and how to weigh the impact of a particular code change. And finally some discussion on how to practice optimizing so you can do it when it counts.</p>
<p>We’ll be accepting questions related to the panel’s topic prior to the panel. Questions can be posed in the comments below or via Google+ and Twitter using the hash tag #AltDevPanel.</p>
<p>The panel will be broadcast using <a href="http://support.google.com/plus/bin/answer.py?hl=en&amp;answer=1669903">Google’s On-Air</a> functionality. This requires a Google+ account to participate as an audience member. If you don’t have a Google+ account or aren’t available at the time the panel is set to occur you can still watch the talk at a later time. All talks will be posted to YouTube, and the links will appear on the site shortly after.</p>
<p>We’d like to thank Google for allowing us early access to On-Air. We’d also like to thank the people that helped us with this process, Colt McAnlis and Travis Sanchez. Without their efforts this wouldn’t be possible, so thank you guys.</p>
<h2>Panelist Bios</h2>
<table>
<tr>
<td><a href="http://altdevblogaday.com/wp-content/uploads/2012/03/Mike.jpeg"><img src="http://altdevblogaday.com/wp-content/uploads/2012/03/Mike.jpeg" alt="" width="128" height="128" class="aligncenter size-full wp-image-25210" /></a></td>
<td>
<h3>Mike Acton</h3>
<p>      Engine Director at Insomniac Games (Resistance, Ratchet and Clank for PS3.) Keeper of #AltDevBlogADay
   </td>
</tr>
<td><a href="http://altdevblogaday.com/wp-content/uploads/2012/03/Tony.jpeg"><img src="http://altdevblogaday.com/wp-content/uploads/2012/03/Tony.jpeg" alt="" width="128" height="128" class="aligncenter size-full wp-image-25211" /></a></td>
<td>
<h3>Tony Albrecht</h3>
<p>      Tony Albrecht is the founder and director of Overbyte, a company that specialises in high performance programming solutions for game companies. He&#8217;s built game engines for a range of companies over the last decade or so and now spends his time helping other studios improve their software&#8217;s performance.
   </td>
<tr>
<td><a href="http://altdevblogaday.com/wp-content/uploads/2012/03/John.jpeg"><img src="http://altdevblogaday.com/wp-content/uploads/2012/03/John.jpeg" alt="" width="128" height="128" class="aligncenter size-full wp-image-25209" /></a></td>
<td>
<h3>John McCutchan</h3>
<p>      John McCutchan is from Kitchener-Waterloo, Ontario, Canada. Wrote inotify for the Linux kernel. Got his M.Sc. in computer science from McMaster University. Lead of the Game Systems team in Developer Support, SCEA. Wrote Move.Me.
   </td>
</tr>
<tr>
<td><a href="http://altdevblogaday.com/wp-content/uploads/2012/03/jaymin.png"><img src="http://altdevblogaday.com/wp-content/uploads/2012/03/jaymin.png" alt="" width="128" height="128" class="aligncenter size-full wp-image-25208" /></a></td>
<td>
<h3>Jaymin Kessler</h3>
<p>      DoD disciple, his datas trifle. He shoot structs from his brain just like a rifle at Q-Games.
   </td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/28/altdevpanel-on-optimization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Rad Audio For Everyone</title>
		<link>http://www.altdevblogaday.com/2012/03/26/making-rad-audio-for-everyone/</link>
		<comments>http://www.altdevblogaday.com/2012/03/26/making-rad-audio-for-everyone/#comments</comments>
		<pubDate>Mon, 26 Mar 2012 22:51:28 +0000</pubDate>
		<dc:creator>Ariel Gross</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Audio]]></category>
		<category><![CDATA[game development]]></category>
		<category><![CDATA[Sound]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25189</guid>
		<description><![CDATA[<p>Team Audio is tasked with making the game sound amazing for everyone. Every single player should have an equally rad aural experience when they&#8217;re playing the game. That&#8217;s a typical goal for most Team Audios out there. But I&#8217;m starting to think that it&#8217;s not quite the right goal. Or that there&#8217;s a problem with it. Or something. Let me explain.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/26/making-rad-audio-for-everyone/" class="more-link">Read more on Making Rad Audio For Everyone&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Team Audio is tasked with making the game sound amazing for everyone. Every single player should have an equally rad aural experience when they&#8217;re playing the game. That&#8217;s a typical goal for most Team Audios out there. But I&#8217;m starting to think that it&#8217;s not quite the right goal. Or that there&#8217;s a problem with it. Or something. Let me explain.</p>
<h1>Players have all kinds of crazy crap.</h1>
<p>When it comes to audio, players be crazy. Not meant as a dis. Just an observation. One person might have a high fidelity 7.1 surround sound system with discrete speakers placed perfectly according to THX standards. The next person might have the same system, but all of the speakers are stacked on top of each other like a tower in the center of their room. And the next person is listening through their old CRT television&#8217;s stock speakers. And the next guy is listening on amazing headphones. And the next person is listening on earbuds that they got from a plastic egg after depositing a nickel in one of those vending machines.</p>
<p>We never really know what the heck our player is doing when it comes to their sound system setup. The Volition offices are a microcosm of this. Some people here use professional speakers (Team Audio). Some people use headphones (Team Design). Some people use cheap PC speakers (Team Production). Some people use earbuds (Team We Hate Team Audio).</p>
<p>Again, not meant as a dis. All of these are, of course, perfectly fine means of getting sounds into ears. However, some issues can crop up as a result.</p>
<h1>&#8220;I can&#8217;t hear Sound X. Turn it up.&#8221;</h1>
<p>Story time! Also, disclaimer time! This is a dramatization. This didn&#8217;t happen here at Volition. But I know it has happened elsewhere, and it&#8217;s not some isolated incident. Team Audios world-wide will be more than happy to regale you with some variation of this story while sullenly drinking their whiskey and/or pink-colored bismuth.</p>
<p>Once upon a time there was an Audio Designer. Our dear Audio Designer had made Sound X and had implemented it into the game. Audio Designer was happy.</p>
<p>Two weeks later, Audio Designer is called over to Project Producer&#8217;s desk. Audio Designer was scared. Nervous. Vulnerable. Naked. Okay, not naked. No, you know what? Naked. May as well make this story extra weird.</p>
<p>Project Producer was frustrated because they could not hear Sound X very well, and demonstrated this through their cheap PC speakers. Naked Audio Designer responded that the reason that Sound X couldn&#8217;t be heard very well was because of the crappy sound system that Project Producer was using.</p>
<p>Project Producer frowned. Project Producer rebutted that perhaps Naked Audio Designer shouldn&#8217;t be testing sounds on top tier studio speakers and should instead be testing sounds on crappy PC speakers, or television speakers. And why wasn&#8217;t Naked Audio Designer wearing clothes? Well, that&#8217;s another story altogether, isn&#8217;t it? It is.</p>
<p>Well, Naked Audio Designer immediately went home and wept for two weeks in their crawl space and forgot to drink any water, and therefore died, and was of course eaten by rats.</p>
<h1>So, why don&#8217;t we just test on TV speakers?</h1>
<p>I find that the easiest way to answer that question is to refer to our dear friends in Team Art. While it&#8217;s possible that Team Art might have to use whatever monitor is in front of them, they tend to want to work on the highest possible quality, perfectly color calibrated monitor. When they work on these monitors, they can assume that the visual quality will be maintained to all the different types of screens.</p>
<p>We&#8217;re in a similar situation in audio. We do our work using high end studio speakers (usually called reference monitors, but I tend to use the word speaker to avoid confusion), sometimes with especially flat frequency responses (meaning the speaker itself isn&#8217;t changing the sound), and usually in calibrated listening spaces, because that way it should translate better to all the different kinds of speakers that our players have.</p>
<p>If a colleague from production or studio management wants your Team Audio to work with low quality speakers because that&#8217;s what most players will be using, point to this article if you want. Maybe then you&#8217;ll be able to scam them into getting you nice equipment. Wait, did I just ruin that strategy? Maybe I did. But I&#8217;m too lazy to go back and change the word scam to convince. Moving on.</p>
<h1>But testing on TVs&#8230; that just seems smart.</h1>
<p>You make a good point, Blog Heading.</p>
<p>Testing on TVs still seems like a good idea. I&#8217;m not trying to make a case against testing your mix on a ridiculously wide range of audio systems. You should probably still do that. And you should still test your game audio on a system that you&#8217;re most familiar with. Test it on the system that you play games on. Then capture some audio from your game, burn it to a disc, and listen to it in your car. Test it in the conference room where you do your show n&#8217; tells. Test it on the Jumbotron in your living room. What, doesn&#8217;t everyone have a Jumbotron in their living room? Well, then do your best with what you have, I guess.</p>
<p>In my experience, the most important thing to test on a wider variety of sound systems is your mix. If you are struggling to hear the dialogue in your game on your television where you play most of your games, then that&#8217;s something that might be worth looking into. Does the music seem too loud when you listen on the headphones you&#8217;re most used to? Data point added! Just be careful. If you&#8217;re doing a final mix of the game, then you&#8217;re probably pretty close to submission. Choose your battles wisely!</p>
<p>Another trend in audio is to give our players a bunch of audio options. We give them discrete volume options to adjust sound, music, and voice, sometimes even more granular than that. We also occasionally give them overarching presets like Hi-Fi, Television, Headphones, etc, which can do things like control how much compression there is on the master mix or on sub-mixes, among other wizardry. This is awesome, but if we&#8217;re being thorough, it can put an increased burden on the audio team as well as audio QA.</p>
<h1>No time. Who care about most?</h1>
<p>Wow, Blog Heading, the way you wrote yourself is really convincing. You even deliberately left out a couple of words. Nice work.</p>
<p>I think the question that the Blog Heading is trying to ask is, when we&#8217;re low on time, which is typical in audio land, then who should we be designing audio for? Should it be for the player with the kick ass high end sound system? Or the player with the crappy earbuds?</p>
<p>Your team may have varying opinions on this. Some people or disciplines will suggest that you need to appease the lowest common denominator. Like when you make your PC game playable on an 80486SX, even though you may need to wait two years to play the same game on max settings. So, if that&#8217;s the case, then we need to design for earbuds gamer. Or at least crappy Labtec PC speakers gamer.</p>
<p>Well, my current opinion is the opposite. Go for the gamer with the higher end sound system. Why? That gamer probably gives a crap about the sound in the game.</p>
<p>I know, earbuds gamer might care, too. Maybe earbuds gamer just isn&#8217;t able to afford a nice sound system. Well, that&#8217;s okay, because fortunately for earbuds gamer, we always do our best to accommodate everyone, right? Right!</p>
<p>But the gamer with the higher end sound system is basically begging you to put that system to good use. Higher end sound system gamer probably wants you to do some serious face melting. Why else would they spend all that money? They probably want an aural experience more similar to the (good sounding) movie theaters.</p>
<p>This might be kind of controversial. I don&#8217;t really know. I haven&#8217;t tested the waters on this one, yet. I guess I should say that this is only my personal opinion, not that of any company that I work for, and it&#8217;s just an opinion, and I&#8217;m just a dude whose opinion changes, like, all the time. I&#8217;m not running for president, here. And if I was, I&#8217;d probably make a law that proclaims bologna as the official meat AND undergarment material of the country. Does the president make laws? I can&#8217;t remember, but I don&#8217;t think so. I think it&#8217;s congress, actually. Anyway, just remember, a vote for me is a vote for bologna.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/26/making-rad-audio-for-everyone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Should I Volunteer?</title>
		<link>http://www.altdevblogaday.com/2012/03/22/should-i-volunteer/</link>
		<comments>http://www.altdevblogaday.com/2012/03/22/should-i-volunteer/#comments</comments>
		<pubDate>Thu, 22 Mar 2012 22:31:37 +0000</pubDate>
		<dc:creator>Heather M Decker-Davis</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[General Interest]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25127</guid>
		<description><![CDATA[<p>I absolutely love encouraging people to volunteer within the game development community. It benefits the particular effort in question, the individual, and the game development community at large.</p>
<p>However, over the course of being heavily involved in a variety of volunteer operations, it’s come to my attention that the general understanding of what it means to volunteer may vary from person to person. It’s not just raising your hand and feeling good. These two steps are indeed part of the process, but there’s a lot more to it than that!</p>
<p><a href="http://www.altdevblogaday.com/2012/03/22/should-i-volunteer/" class="more-link">Read more on Should I Volunteer?&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I absolutely love encouraging people to volunteer within the game development community. It benefits the particular effort in question, the individual, and the game development community at large.</p>
<p>However, over the course of being heavily involved in a variety of volunteer operations, it’s come to my attention that the general understanding of what it means to volunteer may vary from person to person. It’s not just raising your hand and feeling good. These two steps are indeed part of the process, but there’s a lot more to it than that!</p>
<p>The following are general guidelines for volunteering, which I’m hoping may serve as standards to help a variety of organizations, groups, and individuals by better educating budding volunteers on how they can most effectively serve their cause.</p>
<h3> Initial Steps</h3>
<p>The first step to volunteering isn’t just saying you’ll do something. If you’re eager to get involved with an effort, please start by:</p>
<ol>
<li>identifying available opportunities</li>
<li>evaluating how realistic it is for you to contribute, based on your existing workload, schedule, and abilities</li>
</ol>
<p>You might begin by asking a professional organization like IGDA how you can help out, and in turn, receive a list of items that could currently use some attention.</p>
<p>Take a moment and actively match yourself to things you know you can accomplish. That isn’t to say you shouldn’t push yourself to grow, but you should be able to fulfill the basic need you’re stepping up for. If you volunteer for something that’s completely beyond your capabilities, the organizer is basically back to square one when this detail is discovered, which works against the overall intent of helping people.</p>
<p>Playing to your strengths and thoughtfully managing your time will overall aid you in becoming an outstanding volunteer.</p>
<h3>Following Through</h3>
<p>Similarly, it’s extremely important to finish what you’ve started. The bottom line is, someone needed help with X. Therefore, the most useful thing you can do is actually take X from a need to a finished objective.</p>
<p>Offering your time to help an organization, group, or individual should be considered a commitment. When you volunteer, people are now counting on you to pitch in with something!</p>
<p>For example, say I needed someone to make posters for an event. If no one came forward, I would be aware that I had something unasigned and I’d unconsciously operate with the understanding that I need to stretch my resources to cover it. However, if I have volunteers, my organizational thoughts change. I might start pouring more effort into my primary tasks, in the interest of making the event all that much better. Having more hands to help essentially means you can do more!</p>
<p>Unfortunately, when a volunteer bails last minute or otherwise falls short, an organizer suddenly has an unanticipated hole in their plans, and thus, must scramble to shuffle things around and make it right. Be aware that flaking out on something you committed to makes it harder for everyone else involved. Volunteers should strive to be a helpful and accountable.</p>
<p>That being said, it’s understandable that sometimes life happens and things don’t always go according to plan (emergencies, etc.) If something uncontrollable comes up, be sure to let your coordinator or organizer know as soon as possible.</p>
<h3>Doing it Well</h3>
<p>Keep in mind that volunteering generally results in some form of work&#8211;although it can often be quite enjoyable&#8211;and thus, your volunteering efforts should be held to a high quality standard. You want to be proud of your work, right? Unless the original objective stated was to “slap something rough together,” treat your task as you would a paid job. If you’re not sure what the expectation is, don’t be afraid to ask! Most coordinators are more than happy to detail out tasks and get you everything you need to accomplish the given goal.</p>
<p>Additionally, in the game development community, always demonstrating that you uphold high quality standards as a volunteer is a great way to build an awesome reputation. In all, it publicly demonstrates that you’re a hard worker. It’s no secret that this is a very close-knit industry and people talk. If they have great things to say, it’s highly beneficial to how others (including potential employers,) may regard you. In contrast, if they have nothing good to say, it can have the opposite effect.</p>
<h3>Enjoying the Benefits</h3>
<p>So it might sound like a great deal of effort, but in general, volunteering in the game development industry is great for both personal and professional growth.</p>
<ul>
<li>You get out there and meet tons of great new people in your field! This is exceptionally useful to networking efforts.</li>
<li>You often acquire new skills along the way! For example, I learned the logistics behind running an IGF booth last year.</li>
<li>You feel awesome for contributing to something larger than you could do on your own.</li>
<li>You continue to nurture the game development community, which is carried entirely by volunteers who are dedicated to their craft and the constant improvement of it.</li>
</ul>
<h3>The Big Picture</h3>
<p>My hope is that these tips will help you be the best volunteers you can be, and through teaching each other, we can continue to nurture the quality and reach of our community efforts.</p>
<p>For those of you already out there, doing all of these things and more: thank you so much! You are the amazing force that makes this field so inspiring to work in.</p>
<p>And to all aspiring super-volunteers in the making: go forth and be excellent!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/22/should-i-volunteer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Be Aspirational</title>
		<link>http://www.altdevblogaday.com/2012/03/22/be-aspirational/</link>
		<comments>http://www.altdevblogaday.com/2012/03/22/be-aspirational/#comments</comments>
		<pubDate>Thu, 22 Mar 2012 13:39:57 +0000</pubDate>
		<dc:creator>Claire Blackshaw</dc:creator>
				<category><![CDATA[General Interest]]></category>
		<category><![CDATA[off-topic]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25120</guid>
		<description><![CDATA[<p>A year ago ago I signed up to this service, TimeHop, which emails me my tweets and status updates from a year ago, and it has been strangely motivating. To see my growth, challenges and remind me of my goals, my dreams, my successes and my failures.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/22/be-aspirational/" class="more-link">Read more on Be Aspirational&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>A year ago ago I signed up to this service, TimeHop, which emails me my tweets and status updates from a year ago, and it has been strangely motivating. To see my growth, challenges and remind me of my goals, my dreams, my successes and my failures.</p>
<p>So this week a year ago I was&#8230;</p>
<ul>
<li>Listening to this classic song (<a href="http://www.youtube.com/watch?v=fzMhh8zhTiY">http://www.youtube.com/watch?v=fzMhh8zhTiY</a> ) while improving my Starcraft 2 Laddering position of course.</li>
<li>Working Hard: Quote “Stress + Overtime = Weight gain -&gt; More Stress -&gt; Stress + Overtime&#8230; (T_T)”</li>
<li>Learning to use Blender: <a href="http://e.timehop.com/wf/click?upn=-2FtU3Q-2FqLP60Svc-2BTIICjL9oCYj54griYQUQTP9iohY8nApqdxoE5Q22Y-2BfQdVnJU_jIEIFwACWSJBGsBbbSCw5to8sFHVP0NTBk9g4mvXHvrz33UPcPYyBD6nPxB-2BNamHzOcjKcrMWRJyxJnnNtdM4afzW77KdJdBGsDHOqWV8UwYPuraFZ3AwuJ4uLM3wjjrpz6w3bPvygWE4uxKhSG-2BZsA0AN768AU-2FY9HID7iCnT178jtXPFdaZoyTPSH8mE2Al5gOH5wifzeyO5IX05vI1hBnNCRfMQQarEAvzEBOHP-2FrsulHUQVH4A9W1Xjh2jF9HKYGnChFJYqY-2BGyxHbbPfF6mPpKMWVt5uvJexmNZDsr9qM24nvaWBpXY3zStapZpArGMujggXX3w1PrjA9fUVW85jfn6ILOyazJkNQ7seHvBhS-2FYNgTyX0iPyW37LlFg3ZdO-2BCZcRRPzJc-2FZ9ZXLtZQQ8vses0KTdbPzyrHGmdNZ5DYbYCgftfNBDi4qqwAzwZeOCYnTd31tHxDR9dO7r9hkMsKWR1WJaF-2BwvZhYQagraFZzqUfcy7oaRHq3YskYlT5b5QIHyXBIvXh0EK6cn4eErr4p-2FJsGWnR-2BjQ-2FCz3tuRZaouNp5shK2yY4ieCPKs-2Fn1wFwCl1dbIup-2BXeTyBIHggGHSjuCj1-2Bc7Xs9Ffso1PpWfrcBqQXZP5uM2YAlh">http://yfrog.com/h413067151p</a></li>
<li>Bitching about it’s lack of ngons, which it now has in dev branch (^_^) Great job guys!</li>
<li>Which led to this game asset: <a href="http://e.timehop.com/wf/click?upn=-2FtU3Q-2FqLP60Svc-2BTIICjL3YgzfEx-2BFrNrCt9luzznsM-3D_jIEIFwACWSJBGsBbbSCw5to8sFHVP0NTBk9g4mvXHvrz33UPcPYyBD6nPxB-2BNamHChpbvSvANb6BSjf3-2FAKf6h-2BFNmZnUx8oaFbmVwkzgFTXUs7SnVbhjDyREr1uKCsy81uCwcDcwsCmzbS6Nf2NZOs-2BLjAgP4ypMzMH9NaTUfF0EFFZCHyPQrO9-2Fc7HxGpuKAixoCzSik-2FaLaYUUNVKVAm2i0j295qUQATwImVJuDHGTCXkWSEC-2Fn3LBOMyDEcLV1cnXMIdyj-2BMtJFzxBxW0qv0dy80II43MNLzhCZwmpZcCwc2xkHpUgM8v-2BMf1qtUvohzmAfMJ9mpkxV8aI6OeDS3dEhkGUN9OyoB4lV2CZfGuod19MDBFUsrQ0lB333rRJIiv1RPVbIDZ1M29D1nYtFGScN5tWWWQTAy3RRdz7F1WnxTNkyIO-2F-2B4i2n7M5IFWTH0bujzJVVkQKNloFJD9hoFUD-2BIb8QpeHwPr6tCHEkWoTXDTOgooGNo3V7gY-2BXORoZfEw-2BqQwkRvFdlKBL7W1jD1wDR98-2B5DqjLRB2mtSK5-2Fxf4-2BvMwjD2Q-2FONbe4nVSBT5d6Lp7mZF9K4472VN21bG4jY7GpBybRkDL5eNTrisd8-2BgbKtR5bWAzquBn3jc">http://yfrog.com/h0oiyp</a>, <a href="http://e.timehop.com/wf/click?upn=-2FtU3Q-2FqLP60Svc-2BTIICjLyY5bUNYUrvVyGIATo-2FWza4-3D_jIEIFwACWSJBGsBbbSCw5to8sFHVP0NTBk9g4mvXHvrz33UPcPYyBD6nPxB-2BNamHChpbvSvANb6BSjf3-2FAKf6h-2BFNmZnUx8oaFbmVwkzgFTXUs7SnVbhjDyREr1uKCsy81uCwcDcwsCmzbS6Nf2NZOs-2BLjAgP4ypMzMH9NaTUfF0EFFZCHyPQrO9-2Fc7HxGpuKAixoCzSik-2FaLaYUUNVKVAm2i0j295qUQATwImVJuDHGTCXkWSEC-2Fn3LBOMyDEcLV1cnXMIdyj-2BMtJFzxBxW0qv0dy80II43MNLzhCZwmpZcCwc2xkHpUgM8v-2BMf1qtUvohzmAfMJ9mpkxV8aI6OeDS3dEhkGUN9OyoB4lV2CZfGuod19MDBFUsrQ0lB333rRJIiv1RPVbIDZ1M29D1nYtFGScN5tWWWQTAy3RRdz7F1WnxTNkyIO-2F-2B4i2n7M5IFWTH0bujzJVVkQKNloFJD9hoFUD-2BIb8QpeHwPr6tCHEkWoTXDTOgooGNo3V7gY-2BXOLuoOO2Rxr4JCYPkV0ZCDD3Y7PtT7axCYpbvenSCqw7UHre5cJcCvtfkTBzW2mFCp3d98OjM3YXIbJjiBR4miVgOVlPZF53MwIkXziGG5MM1R-2BgfLLrDMeU7VmUJZhT-2Fw">http://yfrog.com/h2zxzvfzj, </a><a href="http://e.timehop.com/wf/click?upn=-2FtU3Q-2FqLP60Svc-2BTIICjL20wl-2BD6kwSZpqFD2ARYpfA-3D_jIEIFwACWSJBGsBbbSCw5to8sFHVP0NTBk9g4mvXHvrz33UPcPYyBD6nPxB-2BNamHChpbvSvANb6BSjf3-2FAKf6h-2BFNmZnUx8oaFbmVwkzgFTXUs7SnVbhjDyREr1uKCsy81uCwcDcwsCmzbS6Nf2NZOs-2BLjAgP4ypMzMH9NaTUfF0EFFZCHyPQrO9-2Fc7HxGpuKAixoCzSik-2FaLaYUUNVKVAm2i0j295qUQATwImVJuDHGTCXkWSEC-2Fn3LBOMyDEcLV1cnXMIdyj-2BMtJFzxBxW0qv0dy80II43MNLzhCZwmpZcCwc2xkHpUgM8v-2BMf1qtUvohzmAfMJ9mpkxV8aI6OeDS3dEhkGUN9OyoB4lV2CZfGuod19MDBFUsrQ0lB333rRJIiv1RPVbIDZ1M29D1nYtFGScN5tWWWQTAy3RRdz7F1WnxTNkyIO-2F-2B4i2n7M5IFWTH0bujzJVVkQKNloFJD9hoFUD-2BIb8QpeHwPr6tCHEkWoTXDTOgooGNo3V7gY-2BXOiUkgrmxy6JAA3-2F69hrmRdn2QJM1DmGJAhhKXixHYhPGjEihFWSEVPojXYMgYbHvj3-2FTGkQ51RCYaGSdaNzgyp13gYnS1Dsj1ppOmA8PMykw0AR95xKWJp8GP2yis0phU">http://yfrog.com/h2og8sbj</a></li>
</ul>
<p>I was going to write another designer skill-up post regards art tools but then I wanted to  follow up the brilliant, <a href="http://altdevblogaday.com/2012/03/19/you-should-be-drawing/">“You Should be Drawing”</a> post by Mike Jungbluth, with a piece on the Flour Sack doodle. How everyone should doodle old school animation at least once to get a feel for motion and weight in animation&#8230; which led to me just wanting to shout from the roof tops.</p>
<p style="text-align: center"><strong>BE ASPIRATIONAL!</strong></p>
<p>If you&#8217;re reading AltDev, or better yet contributing, you have at least made the first steps. I encourage you to draw up a bucket list or a dream list of stuff you want to do! Try <a href="https://www.schemer.com/scheme/26ncuqfvfmb2e/3aeq8drj6mo6o">Schemer</a>!</p>
<p>Start your list with some traditional gamedev skills.</p>
<ul>
<li>Code</li>
<ul>
<li>Make “Hello World”</li>
<li>Make Pong</li>
<li>Make Particle Fountain</li>
</ul>
<li>Art</li>
<ul>
<li>Draw Flour Sack Animation</li>
<li>Draw Human Hand</li>
<li>Model Something on Your Desk</li>
</ul>
<li>Design</li>
<ul>
<li>Invent a Card Game using a normal playing deck</li>
<li>Make a Boardgame</li>
<li>Write a Roleplaying Module</li>
</ul>
</ul>
<p>Nothing is stopping you extending that list to include:</p>
<ul>
<li>Cook a Quiche</li>
<li>Crochet a Scarf</li>
<li>Model something out of clay</li>
<li>Learn to Cat Yodel</li>
</ul>
<p>There is no such thing as a useless skill! Aspire to be more, learn more, do more! Also being reminded about last year via <a href="http://timehop.com/">timehop</a> and making plans in <a href="https://www.schemer.com/home">scheme</a>r are not bad places to start.</p>
<p>Everyone I’ve ever met worth anything wanted to me worth more.</p>
<p>P.S. Sorry about the fluffy post but I got super fired up and needed to shout!<br />
P.P.S Also there are similiar services to TimeHop &amp; Schemer. They just happen to be the ones I’m using.<br />
P.P.P.S Should I think things through more and be less impulsive&#8230; maybe<br />
P.P.P.P.S I really will do a more technical, solid post next time I promise.<br />
P.P.P.P.P.S: Can you make a recursive Post Script? I wonder&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/22/be-aspirational/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 2.456 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-20 20:56:22 -->
<!-- Compression = gzip -->
