<?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>Games from Within &#187; Game tech</title>
	<atom:link href="http://gamesfromwithin.com/category/game-tech/feed" rel="self" type="application/rss+xml" />
	<link>http://gamesfromwithin.com</link>
	<description>Living the indie life</description>
	<lastBuildDate>Mon, 16 Jan 2012 20:37:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>iCloud Demystified</title>
		<link>http://gamesfromwithin.com/icloud-demystified</link>
		<comments>http://gamesfromwithin.com/icloud-demystified#comments</comments>
		<pubDate>Thu, 22 Dec 2011 23:34:12 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[icloud]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1592</guid>
		<description><![CDATA[Play a game on a device, put it down, pick up another device, and continue playing exactly where you left off. This is the future of games. That future is a reality today for some games and apps (Netflix, Kindle), &#8230; <a href="http://gamesfromwithin.com/icloud-demystified">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Play a game on a device, put it down, pick up another device, and continue playing exactly where you left off. This is the future of games.</p>
<p>That future is a reality today for some games and apps (Netflix, Kindle), and I&#8217;m convinced that players will expect that in most games in the next year or so. So obviously, the next bit of new iOS tech I decided to try was iCloud. I would love to turn Flower Garden into that kind of seamless experience, independently of the device you use to access it. </p>
<p>As a quick spoiler, it turns out I won&#8217;t be able to make Flower Garden quite so seamless without a lot of extra work. But I learned a lot along the way and I should be able to take a small step in that direction.<span id="more-1592"></span><br />
<h2>Design considerations</h2>
<p>iCloud promises to be the &#8220;available from everywhere&#8221; storage solution that will be a key component towards the scenario of playing on any device at any time. Unfortunately, it&#8217;s just a component of that whole scenario and still requires quite a bit of work on the part of the developer.</p>
<p>Since I&#8217;m just retrofitting Flower Garden to work with iCloud, I wanted a simple way to simply replicate the game state on iCloud. Then, whenever you play it from any device, you get the latest state and everything works as expected.</p>
<p>The big problem with that approach is that you can&#8217;t always count on having an active (or fast enough) internet connection. iPod Touches, iPads, or even iPhone in a plane or a cell tower black spot will make it so your device has no way to communicate with iCloud. So what happens if the player plays without an internet connection, then comes home, grabs another device, plays for a bit with internet connection, and finally launches the original device, this time with internet connection. You&#8217;ll end up with two conflicting game states. Not fun!</p>
<div style="text-align:center;"><img  src="http://gamesfromwithin.com/wp-content/uploads/2011/12/whatis_icloud.jpg" alt="Whatis icloud" border="0" width="382" height="295" /></div>
<p>I can think of two different strategies to deal with this situation:</p>
<ul>
<li>Require internet connection to play. Some games do this today. It can be quite frustrating not being able to play your favorite game in the plane, but it does solve the game state conflict problem because they can always communicate with iCloud, so they usually provide seamless multi-device play.</li>
<li>Detect changes on both game states and intelligently solve them. Sounds good in theory, but it&#8217;s a pain in practice. Unless you have a very simple game state (a percentage completion for example), it means not only do you have to record the state, but you have to record the events that led to that state, and be ready to examine them, compare them, and marge them in the case of a conflict. And the worst part is that even if you put lots of care into it, there will be cases where the merge is not ideal and the player will feel like he lost something in the merge.</li>
</ul>
<p>For Flower Garden, neither solution is particularly attractive. It&#8217;s the proverbial rock and a hard place. So for the moment I&#8217;ve decided to implement just a small step in that direction: Sync things that only progress in one direction, without any danger of conflict. That includes purchased IAPs and unlocked seeds. Later on, once that&#8217;s working solidly without any problems, I can consider adding counts like Fertilizer, Color Dust, or Green Thumb points. That will be a bit trickier because there&#8217;s still chance for conflict since the count can go up and down, but it&#8217;s possible to change each amount into two different values that always go up: Earned amount, and spent amount. That way I can always grab the maximum value that I find either local or on iCloud and things should work smoothly. (Update: What I wrote there about separating them in two different values is totally wrong, and any DB programmer worth his salt would be laughing at that. Separating them in two different values won&#8217;t help at all. That&#8217;s what I get for doing brain-dump posts on the fly <img src='http://gamesfromwithin.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Apple provides <a href="https://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/iCloud/iCloud.html#//apple_ref/doc/uid/TP40007072-CH5-SW1">two APIs to store data in iCloud</a>: key-value storage and file storage.</p>
<h2>Key Value storage</h2>
<p>Initially, this seems like a great way to go. It&#8217;s a <a href="https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSUbiquitousKeyValueStore_class/Reference/Reference.html#//apple_ref/occ/cl/NSUbiquitousKeyValueStore">very simple API</a>, and it&#8217;s very familiar to most iOS programmers because it&#8217;s just like <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html">NSUserDefaults</a>.</p>
<p>Don&#8217;t be fooled into thinking you need to store data in strings or one field at the time. You can stuff whatever binary chunk of data you want with NSData, so it&#8217;s quite versatile.</p>
<p>It does have three pretty big drawbacks thought:</p>
<ul>
<li><b>Size</b>. You can only store up to 64KB of data. That&#8217;s definitely a big deal if you&#8217;re planning on storing large data files. Even for Flower Garden, each pot is about 30KB, so I wouldn&#8217;t be able to save the full garden state this way.</li>
<li><b>Syncing</b>. The Apple docs say that &#8220;Keys and values are transferred to and from iCloud at periodic intervals.&#8221; Ouch! What does that mean? Clearly this is intended for non-crucial data (like settings), so the potential delay isn&#8217;t a big deal. In my tests, I found that data was often not available when starting the app, but would become available a few seconds later.</li>
<li><b>No way to check state.</b> When starting the app, there&#8217;s no way to find out if the values you&#8217;re reading are up to date. Combined with the slow syncing, it makes it less than idea for important data. On the flip side, <a href="https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSUbiquitousKeyValueStore_class/Reference/Reference.html#//apple_ref/occ/cl/NSUbiquitousKeyValueStore">you can be notified when the data changes</a>, but that means having to deal with changes while the game is running (which I was hoping not to do).</li>
</ul>
<h2>File storage</h2>
<p>File storage might be a better option then since it doesn&#8217;t have any of those drawbacks: there&#8217;s no size limit, data is synced much more aggressively, and you can check if the data is up-to-date, and wait until it is otherwise.</p>
<p>What&#8217;s not to like about file storage then? The cumbersome and intrusive API that Apple created around it. If you read the docs, they make it sound like you need to inherit from UIDocument and load all your data through that class. I like to keep things simple and portable, so I&#8217;d really rather not introduce UIDocument into the file-loading process if I don&#8217;t have to.</p>
<p>It turns out that <a href="https://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/iCloud/iCloud.html#//apple_ref/doc/uid/TP40007072-CH5-SW1">Apple&#8217;s docs on the iCloud SDK</a> are quite sparse and lacking details. I was able to put together a demo from those docs and some experimentation, so hopefully this will be useful to other devs as well.</p>
<p>The device has an iCloud storage daemon running, monitoring specific directories for changes. You get the directory assigned to your app by calling <a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/URLForUbiquityContainerIdentifier:">URLForUbiquityContainerIdentifier</a>. </p>
<p>To add a new file, the docs recommend first creating the file somewhere else, and then calling  <a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/setUbiquitous:itemAtURL:destinationURL:error:">NSFileManager:setUbiquitous:itemAtURL:destinationURL:error:</a> to move it to iCloud. Interestingly, I accidentally skipped this step and just wrote to the iCloud directory directly, and the files were stored correctly anyway. Might as well leave it just in case that behavior changes later on, or there&#8217;s some side effect I didn&#8217;t notice.</p>
<p>After that, every time you write to the file, the iCloud daemon will detect the changes and push them out to iCloud. This is an important point because a) You don&#8217;t have explicit control to say &#8220;start send it now&#8221; or even &#8220;This file is ready to be sent to iCloud&#8221; (that would be my choice), and b) I don&#8217;t know what it does with partial updates, so I would be very careful about writing to those files and make sure it&#8217;s an atomic operation (save somewhere else, and them move the file in one operation).</p>
<p>To get the latest version of the files on iCloud, you can check whether they&#8217;re fully downloaded or not by calling <a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/getResourceValue:forKey:error:">NSURL:getResourceValue:&#038;isDownloaded forKey:NSURLUbiquitousItemIsDownloadedKey error:</a>. If they are up to date, you can move on, otherwise, you can initiate a download of the files by calling <a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/startDownloadingUbiquitousItemAtURL:error:">NSFileManager:startDownloadingUbiquitousItemAtURL:error:</a>.</p>
<p>One weird thing is that the startDownloading function doesn&#8217;t have a callback (that I can see). So I had to set up a timer to check periodically if the files are synced.</p>
<p>Since all the syncing happens at startup, there&#8217;s no complexity involved with data changing while the app is running. If that&#8217;s a case you need to handle, you might be better off using UIDocument since it at least detects conflicts. If you do it this way, the latest one will overwrite any past changes.</p>
<p>Also, working this way, it seemed easier to keep the files in Application Support (or Documents), and only move them to/from iCloud when I wanted to. That has the advantage of iCloud not changing things from under you while the game is running, and the fact that, if for some reason the files in iCloud are corrupt, you always have good local files to fall back to.</p>
<h2>Demo</h2>
<p><a href="http://gamesfromwithin.com/wp-content/uploads/2011/12/iCloudTest.zip" title="iCloudTest.zip" alt="ICloudTest">iCloudTest.zip</a></p>
<p>The demo iCloudTest saves data both with the key value pair, and the file storage system directly like I described above. If you run it from different devices, you&#8217;ll see that it&#8217;s amazing how quickly file data gets propagated, but key-value data takes a few more seconds. </p>
<p>The demo project also works in the simulator (there&#8217;s no iCloud support, so it just uses local files), and it even works with iOS4 (also using local files, and it avoids using any iOS5 symbols while detecting iCloud support).</p>
<h2>Sharing Data Between Multiple Apps</h2>
<p>Once you&#8217;re at this point, sharing data between multiple apps is really straightforward. </p>
<p>First you need to make sure the app IDs of both apps start with the seam Team ID. For some unknown reason lost in the midsts of time, Flower Garden and Flower Garden Free use different prefixes, so that option is out for me. Hopefully most people having been using the Team ID only.</p>
<p>Then you need to decide which type of data you want to share. If you want to share files, you need to add the app ID of the other app to your iCloud entitlement, and then as for the correct app ID (including prefix!) when you call <a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/URLForUbiquityContainerIdentifier:">URLForUbiquityContainerIdentifier</a>. If you just want the app&#8217;s own iCloud data, you can pass NULL as the parameter.</p>
<p>As far as I can tell, each application can only have one set of key-value data. So sharing it between two apps means changing one app to use the app ID of the other app in the com.snappytouch.icloudtest field of the iCloud entitlements file. As long as both apps use the same Team ID prefix, it should work fine without having to do anything else.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/icloud-demystified/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>URL Shorteners In Under Two Minutes</title>
		<link>http://gamesfromwithin.com/url-shorteners-in-under-two-minutes</link>
		<comments>http://gamesfromwithin.com/url-shorteners-in-under-two-minutes#comments</comments>
		<pubDate>Fri, 26 Aug 2011 17:26:09 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[flower garden]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1488</guid>
		<description><![CDATA[This morning I added the goo.gl URL shortener to Flower Garden, so I thought a quick post with sample code might be helpful for other developers looking to do something similar. I use the URL shortener in Flower Garden to &#8230; <a href="http://gamesfromwithin.com/url-shorteners-in-under-two-minutes">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This morning I added the goo.gl URL shortener to Flower Garden, so I thought a quick post with sample code might be helpful for other developers looking to do something similar.</p>
<p>I use the URL shortener in Flower Garden to send bouquets through SMS. Space is limited in a text message, so the message just contains some text explaining what is it and the URL pointing to the bouquet image. (Yes, I would much rather send them through MMS, but Apple isn&#8217;t exposing that yet to developers).</p>
<div style="text-align:center;"><img  src="http://gamesfromwithin.com/wp-content/uploads/2011/08/sms.png" alt="Sms" border="0" width="280" height="231" /></div>
<p>In this case, the full URL is <a href="http://flowers.snappytouch.com/sms.php?id=949618b4b3c6f3d76e32b45446e238a0">http://flowers.snappytouch.com/sms.php?id=949618b4b3c6f3d76e32b45446e238a0</a> which gets thankfully shortened to <a href="http://goo.gl/IV5cq">http://goo.gl/IV5cq</a>.<span id="more-1488"></span>
<p>Sending bouquets through SMS has been in Flower Garden for several months, but it was using bit.ly before, which is probably the most popular URL shortener out there. I like their web interface and their super-easy to use API, but unfortunately it seems that I hit some mysterious API limit during the Mother&#8217;s Day Flower Garden promotion. That limit isn&#8217;t public anywhere, and as far as I can tell, I can&#8217;t even see it myself through the web interface or through an API query.</p>
<p>Finding out that I reached the API limit was quite shocking, because sending bouquets through SMS isn&#8217;t a particularly popular feature. Unfortunately I don&#8217;t have <a href="http://gamesfromwithin.com/analytics-for-ios-games">good analytics hooked up to that step</a>, but I can&#8217;t imagine there were more than a few thousand per day.</p>
<p>They were very nice and contacted me instead of shutting down my account since it was just a spike. They also tried to sell me their &#8220;Enterprise&#8221; account, but $995/month is a tad too expensive for me. By about $990 probably, so I had to look for other options.</p>
<p>After a very quick research, <a href="http://googlesystem.blogspot.com/2011/01/api-for-google-url-shortener.html">goo.gl</a> was the perfect alternative. Not only is it very fast (and backed up by the giant Google no less), but they have an API limit of 1,000,000 queries/day. If I ever blow that budget, I&#8217;ll be able to afford the $995/month without a problem <img src='http://gamesfromwithin.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>All URL shorteners are very easy to use. You need an API key, and figure out the exact format of the HTTP message you send and the response you get.</p>
<h3>goo.gl</h3>
<p><a href="http://goo.gl">Goo.gl</a> has a great <a href="http://code.google.com/apis/urlshortener/v1/getting_started.html">Getting Started Guide</a> that tells you everything you need to know. Get your private API key from <a href="https://code.google.com/apis/console">here</a>, and you&#8217;re ready to rock.</p>
<p>Drop this in your app and start shortening away. You&#8217;ll notice I used a synchronous HTTP request, which is usually a big no-no. Here I felt it was justified since the user is blocked waiting for the SMS to be prepared and sent. Besides, goo.gl is very, very fast, so it&#8217;s never even noticeable.</p>
<pre>
const NSString* GooGlAPIURL = @"https://www.googleapis.com/urlshortener/v1/url?key=YOUR_API_KEY_HERE";

NSString* ShortenURLWithGooGl(NSString* longURL)
{
	NSURL* apiUrl = [NSURL URLWithString:GooGlAPIURL];

	NSMutableURLRequest* req = [[NSMutableURLRequest alloc] initWithURL:apiUrl];
	[req setHTTPMethod:@"POST"];
	[req setTimeoutInterval:Timeout];
	[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

	NSString* body = [[NSString alloc] initWithFormat:@"{\"longUrl\": \"%@\"}", longURL];
	[req setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
	[body release];

	NSError* error = [[NSError alloc] init];
	NSHTTPURLResponse* urlResponse = nil;
	NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&#038;urlResponse error:&#038;error];
	[error release];
	if (data == NULL || ([urlResponse statusCode] < 200 &#038;&#038; [urlResponse statusCode] >= 300))
		return NULL;

	NSString* response = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	NSDictionary* responseDict = [response JSONValue];
	NSString* shortURL = [[responseDict objectForKey:@"id"] retain];
	[response release];
	return shortURL;
}
</pre>
<p>I&#8217;m using a <a href="https://github.com/stig/json-framework/">JSON framework</a> to parse the answer, but it&#8217;s so simple I probably wouldn&#8217;t even have to. I only used it because it&#8217;s already part of the project because of <a href="https://developers.facebook.com/docs/guides/web/">Facebook Connect</a>.</p>
<h3>bit.ly</h3>
<p>Even though it&#8217;s not my favorite shortener, I&#8217;m adding it here for completeness (and because I had the code already written).</p>
<p>The one thing that bit.ly has going for it is that it&#8217;s even easier to use than goo.gl. No JSON involved, and you don&#8217;t even need to send a body with your request. As usual, get your API key by <a href="http://bitly.com/a/sign_up">signing up with bit.ly</a>.</p>
<pre>
const NSString* BITLYAPIURL = @"http://api.bit.ly/v3/shorten?login=%@&#038;apiKey=%@&#038;format=txt&#038;";

NSString* ShortenURLWithBitLy(NSString* longURL)
{
	NSString* urlWithoutParams = [NSString stringWithFormat:BITLYAPIURL, LoginName, APIKey];
	CFStringRef encodedParamCF = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
															 (CFStringRef) longURL,
															 nil, (CFStringRef) @"&#038;+", kCFStringEncodingUTF8);
	NSString* encodedURL = (NSString*)encodedParamCF;
	NSString* parameters = [NSString stringWithFormat:@"longUrl=%@", [encodedURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
	NSString* finalURL = [urlWithoutParams stringByAppendingString:parameters];

	NSURL* url = [NSURL URLWithString:finalURL];

	NSMutableURLRequest* req = [[NSMutableURLRequest alloc] initWithURL:url];
	[req setTimeoutInterval:Timeout];

	NSHTTPURLResponse* urlResponse = nil;
	NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&#038;urlResponse error:NULL];
	if (data == NULL || ([urlResponse statusCode] < 200 &#038;&#038; [urlResponse statusCode] >= 300))
		return NULL;

	NSString* response = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	return response;
}
</pre>
<p><br/></p>
<p>That&#8217;s it. You should be able to drop in either one of those snippets in your project and spend your time working on the things that really matter in your games.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/url-shorteners-in-under-two-minutes/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Analytics For iOS Games</title>
		<link>http://gamesfromwithin.com/analytics-for-ios-games</link>
		<comments>http://gamesfromwithin.com/analytics-for-ios-games#comments</comments>
		<pubDate>Thu, 25 Aug 2011 19:08:56 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iDevBlogADay]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1481</guid>
		<description><![CDATA[Unlike a lot of console and PC games, most mobile and web games keep evolving over time [1]. It&#8217;s up to a game&#8217;s designers to ultimately decide how to change and improve the game, but the more data about players&#8217; &#8230; <a href="http://gamesfromwithin.com/analytics-for-ios-games">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Unlike a lot of console and PC games, most mobile and web games keep evolving over time <a href="#1">[1]</a>. It&#8217;s up to a game&#8217;s designers to ultimately decide how to change and improve the game, but the more data about players&#8217; habits they have, the more informed a decision they&#8217;ll be able to make. Having good analytics on iOS games is simply essential these days.<span id="more-1481"></span>Recording particular events as part of the analytics is only part of it. The most important part is how that data is presented to the developer. Having tables with millions of entries does me no good, and as a busy indie developer, I can&#8217;t afford to spend hours writing scripts to analyze it. I want something that allows me to easily visualize the data and makes sense out of it at a glance.</p>
<p>One possible snagging point about analytics is that Apple was cracking down on some applications with analytics enabled a while back. Specifically, the <a href="https://developer.apple.com/programs/terms/ios/standard/ios_standard_agreement_20110215.pdf">iOS developer agreement</a> states:</p>
<blockquote><p>
3.3.9	You and Your Applications may not collect user or device data without prior user consent, and then only to provide a service or function that is directly relevant to the use of the Application, or to serve advertising. You may not use analytics software in Your Application to collect and send device data to a third party.
</p></blockquote>
<p>Where does that leave us? Reading it carefully, it seems that the restrictions are limited to &#8220;user or device data&#8221;. I&#8217;m interpreting that to mean things like UDIDs and emails, not anonymous player usage data (how long did it take to reach level 5, how long are play sessions, etc), so I think we&#8217;re clear there. </p>
<p>The puzzling thing is that a lot (all?) of the third party analytics libraries do report device information, like what kind of hardware or iOS version is running. That is extremely important information that developers really benefit from knowing, but it seems to go against point 3.3.9. Maybe &#8220;device data&#8221; only applies to information about that specific device? (as in, <a href="http://venturebeat.com/2011/08/23/ios-5-udid-privacy/">the UDID that is now going away</a>). I hope so.</p>
<p>Not having analytics isn&#8217;t really an option. Unless you make a game that you plan to throw on the App Store, never touch again, and hope for the best, you&#8217;re flying blind without analytics. </p>
<p>What are some of the options we have then?</p>
<h3>Home brewed</h3>
<p>If you read this blog regularly, you probably know that I&#8217;m a <a href="http://gamesfromwithin.com/360idev-cranking-up-floating-point-performance-to-11">low-level</a>, do-it-myself kind of guy, with <a href="http://gamesfromwithin.com/my-fear-of-middleware">a deep mistrust and suspicion of middleware</a>. So you would think that I would want to write my own analytics package. After all, how hard can it be? Collect the data you want and ping your server with it. If you get fancy, you can even use a scalable server back end like <a href="http://aws.amazon.com/">AWS</a> or <a href="http://code.google.com/appengine/">GAE</a>. Done.</p>
<p>Not so fast. To do that well, it&#8217;s a lot more involved than that. You want to batch when you send out the information, and you might want to distinguish between WiFi and 3G connection (to avoid causing extra data usage for players on a limited data plan).</p>
<p>That in itself is not even that bad. The real pain comes in visualizing that data, and that&#8217;s where you can easily sink in days or weeks, and you would still not have something as good as some of the other alternatives. </p>
<p>The other drawback is that if you have some successful applications, you may be generating Terabytes of data per day. Think about the storage and bandwidth costs for that. Yes, I know that sounds insane, but Playfish reported generating that much analytics data at a <a href="http://www.gdcvault.com/play/1014544/Scaling-Social-Games-What-Game">GDC 2011 talk</a> (<a href="http://www.gdcvault.com/play/1014543/Scaling-Social-Games-What-Game">video for paid GDC Vault members</a>).</p>
<h3>Flurry</h3>
<p><a href="http://www.flurry.com/product/analytics/index.html">Flurry Analytics</a> appears to be the most common analytics package out there among my indie iOS dev friends. It&#8217;s free and it&#8217;s easy to integrate. The visualization page is pretty good, and it even offers some fancy features beyond session length and events, such as flow through the application.</p>
<p>So what&#8217;s not to like? I was never able to make heads or tails of the application flow. When you get at that level, you start needing to spend some serious time making sense of data, which is what I don&#8217;t have as an indie. <s>The web page to visualize the data is written in Flash, so for those of you using an iPad to check it, it&#8217;s not a good option.</s> <b>Update:</b> Flurry apparently added a Flash-free web page since I last looked at it a few months back. Thanks Charilaos Kalogirou for the tip.</p>
<p>The killer deal for me was bloat. Adding the Flurry analytics library to an app increased the executable size by 500KB. I&#8217;m sorry, but that&#8217;s completely unacceptable for me. Memory is tight, and half a MB is very significant. I would rather add another large texture or another music track. And if you think about it, why does it need 500KB to buffer and send some events? That&#8217;s simply ridiculous.</p>
<h3>Google Analytics</h3>
<p>I never actually tried out <a href="http://code.google.com/mobile/analytics/docs/iphone/">Google Analytics</a>. They have an iOS SDK and it integrates quite well into the web page Google Analytics environment. The main drawback I heard from other developers is that it&#8217;s designed more for web pages rather than for apps and games, so it wasn&#8217;t a perfect fit.</p>
<p>Anyone who used it want to expand on this in the comments?</p>
<h3>Localytics</h3>
<p><a href="http://www.localytics.com/app-analytics/">Localytics</a> is a relative newcomer to the iOS analytics field, but it was love at first sight for me.</p>
<p>It has the same ease of integration of Flurry, and it provides very similar functionality. Localytics, however, is completely open source, so instead of a black box library, you get the source code and you can add it directly to your game. How much does it increase executable size? 4KB! You have to wonder what the other 496KB were for in the Flurry library.</p>
<p>As a bonus, their visualization web page works great on an iPad, although it can be a bit slow for very large data sets sometimes.</p>
<p>One of their biggest selling points is that they report the analytics in real time, but I really don&#8217;t care one way or another. Waiting 12 or 24 hours to see the analytics doesn&#8217;t bother me one bit.</p>
<p>Unlike Flurry, you can only add strings as parameters to events. That works fine if I have a set of discrete options. For example, when someone sends a bouquet in Flower Garden, I can send a &#8220;bouquet sent&#8221; event with a parameters that is &#8220;email&#8221;, &#8220;facebook&#8221;, or &#8220;sms&#8221;. As a result, I can see a nice pie chart with the breakdown of how people are sending bouquets. Very useful stuff!</p>
<p>But how about things that don&#8217;t have discrete options? For example, in Casey&#8217;s Contraptions, we wanted to see how long players take to solve each level. It turns out you can&#8217;t have a number as a parameter, but you can easily get around that by discretizing it yourself, which in the end, is easier to visualize. So when we send the LevelXXFinished event, we look at how long the player took to finish it, and we break it down into ranges: under 30s, 30s-1min, 1min-2min, etc.</p>
<p>This is what the report looks like for one of Casey&#8217;s Contraptions levels:</p>
<div style="text-align:center;"><img  src="http://gamesfromwithin.com/wp-content/uploads/2011/08/piechart.png" alt="Piechart" border="0" width="380" height="317" /></div>
<p>It looks like a fairly balanced level with the majority of the people spending under 3 minutes to solve it.</p>
<p><br/></p>
<h3>Random tips</h3>
<p>A couple random things we learned along the way about analytics:</p>
<ul>
<li>Less is more. Start with just a few events and go from there. If you have tons of data, you might never have the time to look at it.</li>
<li>Use analytics during playtesting. One thing is what people tell you, and another thing is what they really do. Since most of our playtesting is done remotely and we can&#8217;t observe as people play (which is invaluable), we can at least gather some hard data about it.</li>
<li>Turn off analytics reporting in debug mode. Trust me on that one.</li>
</ul>
<p><br/></p>
<p>How about you? What&#8217;s your favorite analytics package and why?</p>
<p><br/></p>
<p><a name="1"></a>[1] For example, Flower Garden has been on the App Store for almost two and a half years, and it has changed radically in that time!</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/analytics-for-ios-games/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Writing Reusable Code</title>
		<link>http://gamesfromwithin.com/writing-reusable-code</link>
		<comments>http://gamesfromwithin.com/writing-reusable-code#comments</comments>
		<pubDate>Tue, 21 Jun 2011 16:12:32 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[inner product]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1398</guid>
		<description><![CDATA[Some people asked what I meant by a &#8220;toolkit architecture&#8221; in the previous post about my middleware fears. It turns out I wrote about that in a previous Inner Product column that for some reason I never reposted here. I &#8230; <a href="http://gamesfromwithin.com/writing-reusable-code">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Some people asked what I meant by a &#8220;toolkit architecture&#8221; in <a href="http://gamesfromwithin.com/my-fear-of-middleware">the previous post about my middleware fears</a>. It turns out I wrote about that in a previous Inner Product column that for some reason I never reposted here. I think at the time I wrote this (late 2008), I already wasn&#8217;t very concerned about writing reusable code, and I was focusing it mostly with respect to using other people&#8217;s code and how I wanted it to be architected.<br />
</em></p>
<p><span id="more-1398"></span></p>
<p>As programmers, we&#8217;re constantly reusing code. Sometimes it&#8217;s in the form of low-level OS function calls, or game middleware, and sometimes code that our teammates wrote. At the same time, unless you&#8217;re writing top-level game script code, chances are that the code you&#8217;re writing will be used by people as well.</p>
<p>I&#8217;m purposefully avoiding labeling reusable code as &#8220;libraries&#8221; or &#8220;middleware&#8221;. Those are just two of the many forms in which we end up reusing code. Copying some source files onto your project, calling an API function, or instantiating a class written by someone else in your team, are all different forms of code reuse.</p>
<h2>Getting Started</h2>
<p>Without a doubt, the most difficult job writing reusable code, is making sure it solves a problem correctly and meets everybody&#8217;s needs. That&#8217;s not a easy task when we&#8217;re writing code for ourselves, but it&#8217;s much more difficult when we&#8217;re targeting other programmers. Too many libraries get it only half right, and they solve some problems at the expense of introducing a bunch of new ones. Or they force the user to jump through all sorts of hoops to get the desired result in the end. We need a clear understand of the exact problem we&#8217;re trying to solve with our code.</p>
<p>Libraries often fall in the trap of presenting an implementation-centric interface. That is, their interface is based on the implementation details of the library, rather than how the users are going to use it in their programs.</p>
<p>The best way I&#8217;ve found to address both those shortcomings is to start by implementing code that solves the problem for one person. Just one. Forget about multiple users and code reusability for now. If you don&#8217;t have immediate and constant access to that one person, then you need to play that role and create a game or application that is as close as possible to what one of your users is going to be developing. By using this approach, I find that the interface to the reused code is much more natural, and it&#8217;s based on the experience of having solved the problem at least once. Otherwise, you run the risk of creating an interface that is not a good fit and forcing everything to conform to it in unnatural ways.</p>
<p>Once you have implemented a solution, take a moment to think before you dive into doing any more work. Many times you&#8217;ll find there is no reason to abstract it any further since your code is only going to be used in one place. If that&#8217;s the case, step away from the code and go do something more productive. You can always come back later whenever there is a real need to reuse it later in the project or in a future game.</p>
<p>There are exceptions to this approach of implementing a solution first, and abstracting it later. Some problems are very simple, or very well understood, so we might be able to jump in and implement the reusable solution directly (an optimized search algorithm, or a compression function for example). It&#8217;s also possible that you&#8217;ve implemented a similar system several times before, and you know exactly at what kind of level to expose the interface and how things should look like. In that case, it&#8217;s perfectly valid to draw on your past experience. Just try to avoid the second-system effect: The tendency to follow up a successful, simple first system, by an overly-complex system with all the ideas that didn&#8217;t make it into the first one.<br />
Setting Goals</p>
<p>Most successful reusable code was created with specific goals about how it was meant to be used. Sometimes those goals are explicitly stated, most of the time they are implied in the code design.</p>
<p>Some of the most common goals are flexibility, protection, simplicity, robustness, or performance. You can obviously not meet all those goals at once, and even if you could, you probably shouldn&#8217;t try. That would be a tremendous waste of time and resources. Stop thinking in the abstract and think about your one user. What does he or she need? What is the most important goal for them?</p>
<p>Many APIs and middleware packages are designed with protection as one of the primary goals: They don&#8217;t want the user to accidentally do anything wrong. In itself is not a bad goal, and it can often be implemented by having clean, unambiguous interfaces, clearly-named types and functions, and strongly-typed data types. Unfortunately, a design with protection as a main goal can often result in encumbered interfaces, verbose code, slow performance, and inflexible code. There is nothing more frustrating than wanting to do something that is explicitly being protected against, and having to work around the interface.</p>
<p>If your target users are professional game developers, give them the benefit of the doubt and don&#8217;t try to overprotect all your code. Save that for the scripting API exposed to junior designers and released to the customers with the game. If you&#8217;re concerned about programmers using your code correctly and not making mistakes, provide good sample code, tests, and documentation. If that&#8217;s not enough, and you feel that everybody would benefit from some level of protection, try to keep it to a minimum and maybe even provide lower-level functions that bypass it for power users.</p>
<p>Whatever the primary goal, the libraries and APIs I prefer to work with, help me get whatever I need done, while getting out of the way as much as possible.</p>
<h2>Architecture</h2>
<p>There are many different ways to architect code that is intended for reuse. The best approach will depend on the particular code: How complex is it? How much of it is there? What are its goals?</p>
<p>Unless your goals are to make quick, throwaway applications, I strongly recommend against a framework type of architecture (see Figure 1.) A framework is a system in which you add a few bits of functionality to customize your program into an existing system. They may sound like a clean and easy way to use complex code, but they&#8217;re inevitably very restrictive, and they make it very difficult, if not impossible, to do things with them beyond what they were intended to.</p>
<div style="text-align: center;"><img src="http://gamesfromwithin.com/wp-content/uploads/2011/06/framework.png" alt="Framework" width="398" height="248" border="0" /></div>
<p>A more flexible approach is a layered architecture (see Figure 2.) Each layer is relatively simple and provides a well-defined set of functionality. Higher-level layers build on top of lower-level layers to create more complex or more specific functionality.</p>
<div style="text-align: center;"><img src="http://gamesfromwithin.com/wp-content/uploads/2011/06/layered.png" alt="Layered" width="395" height="250" border="0" /></div>
<p>Keep in mind that it is not necessary, or even desirable, to have higher-level layers completely abstract out and hide the lower-level ones. By letting layers be fully transparent, they allow you to mix and match at what level you want to access the code. This can be very important, especially towards the end of a game when fixing some bugs or trying to squeeze some more performance out of the engine.</p>
<p>For example, one layer can expose functionality to create and manipulate pathfinding networks and nodes, another one can implement searches and other queries on those networks, while a third, higher-level layer, can expose functions to reason on the state of the network.</p>
<p>A toolkit architecture (see Figure 3), is the most flexible of all. It provides small, well-defined modules or functions with very few dependencies on other modules. This allows users to pull in whatever modules they need into their game to meet their needs and nothing else. Users can also start by reusing some modules, and but replace them down the line when they want to go beyond the existing functionality. Because of this, toolkit architectures are particularly well suited to game development.</p>
<div style="text-align: center;"><img src="http://gamesfromwithin.com/wp-content/uploads/2011/06/toolkit.png" alt="Toolkit" width="524" height="337" border="0" /></div>
<h2>Object Oriented</h2>
<p>I tend to avoid complex class hierarchies in most of my code, but that&#8217;s especially important in the case of reusable code. Class hierarchies are very rigid, and impose a particular structure on their users.</p>
<p>If you want to remain object-oriented, a better approach is to emphasize composition of objects instead of inheritance. That allows users to much more easily pull in the functionality they need, and create their own objects based on their own constraints.</p>
<p>You can even go a step further and provide purely procedural interfaces. Plain static functions that operate on data types. Interfaces based on static functions are often much easier to understand and grasp than interfaces that involve classes and inheritance. They are also much more convenient for users to wrap and use in many different ways.</p>
<p>Remember what you learned about object-oriented design and having private data? Forget about it, and keep everything accessible. You may think you&#8217;re doing the user a favor by making some variables private and reducing the complexity of the interface. That&#8217;s partly true, but eventually, your users will want to have access to some of those variables that you took pains to hide. And if they really want to, they will get to them, even if it means direct addressing into an object or vtable.</p>
<p>It&#8217;s true that large codebases can be intimidating, and exposing all the internal details along with the regular interface would make it unwieldy for new users. An effective approach is to separate the public interface from what is intended for internal use only, but still make it available through some other means. For example, private data and functions could be wrapped in a different namespace, or simply in a different set of headers. Anything that clearly sets them apart, and doesn&#8217;t clutter the initial look at the interface, but that allows experienced developers to get to them and get their hands dirty.<br />
Extensibility</p>
<p>As soon as you make your code available to a wide range of developers, you&#8217;ll find that people want to use it in progressively more complex and bizarre situations. Your code might have completely solved the case of your first couple of users, and since it&#8217;s layered and modular, it can meet a lot of different requirements. But eventually, some people will start taking it to extremes you hadn&#8217;t imagined and it falls short for them. What to do?</p>
<p>You could start adding more options and more modules and more callbacks to your code. That way programmers can hook up into almost any part of the code and replace it with their own. The problem with that approach is that you&#8217;ve taken something that was relatively simple and made it into an large, ugly, fully-customizable, behemoth that tries to keep everybody happy. That sounds like a lot of common APIs we know and hate. Most successful products try to completely meet the need of some people rather than meet everybody&#8217;s needs part way. Otherwise you inconvenience 95% of your users for the benefit of 5% of them.</p>
<p>A better approach is to let those 5% users fend for themselves, but give them the means to do it. How so? With source code. Without source code, developers feel caged and constrained. They know they can&#8217;t look behind the interfaces, let alone modify anything in case something goes wrong (and we all know something will go wrong). The more code there is, and the more a project relies on it, the more important it is to have access to the full source code. Many teams will refuse to use some libraries or middleware unless the full source code is available. As soon as you make source code available to your users, you immediately put them more at ease because they feel more in control, and you allow those with special requirements to make whatever modifications they need to do.</p>
<p>Even those developers without a need to modify the code, they will be able to browse the code and see how certain functions are implemented. Not only will it make people much more likely to use your code, but they will probably also fix your bugs and suggest performance improvements, so it&#8217;s a win-win situation for everybody.</p>
<p>For extra bonus points, the source code should be accompanied by a set of tests. The more comprehensive the better (unit tests, functional tests, etc). Hopefully you created all those tests while you were developing the code, so distributing it along with the source code shouldn&#8217;t be any extra effort, but it will make a huge difference to your users. It will give them much more confidence modifying the code to suit their needs and still see that all the tests are passing.</p>
<h2>Upgrades</h2>
<p>As soon as you release some code and you have your first user, the question comes up of how to deal with new versions. There are many ways you can go about it, depending on how often you&#8217;ll release new versions, and how important it is to maintain backwards compatibility.</p>
<p>On one extreme, you can change the code and the interface to fit new features, changes in architecture, or any other reason. Whenever you release a new version, users will have to choose to remain with their current version or upgrade to the latest and make whatever changes are necessary. This is a common approach in open source projects and internal company code.</p>
<p>On the other extreme, once you release a version, you stick to that interface whether it&#8217;s a good idea or not. This can be good for users because they can get new versions without any extra work on their part, but it can be very constraining. It can make new features impossible to add, and it can prevent performance optimizations. This approach is more common on code that will become the foundation of many programs, like OS libraries and low-level APIs.</p>
<p>A good compromise is to keep interfaces the same during minor versions, and only change them whenever a major version is released. That way other developers only have to put in the time to upgrade to a major release if they really need the new features at that time.</p>
<p>Another approach is not to change existing functions or classes, but to introduce new ones and slowly deprecate the old ones over time. That way code continues to work, but users can take advantage of the new functions. After a few versions, you can completely drop off deprecated functionality, at which point most people will have upgraded already. If you do this, make sure to label deprecated functions with a #pragma warning or some other way. That way, developers know it will be phased out and they can start thinking about upgrading to the new interface.</p>
<p>The easier you make the transition to the new version, the better for your users, and the more likely they will be continue using your code. For example, you can provide scripts that parse their source code and upgrade it to match the new interfaces. That can be a bit risky, but it can be really worthwhile if you have a lot of required changes that are relatively mechanical (renamed functions, changed parameter order, etc).</p>
<p>Is there any point to all this talk of interfaces if you made your source code available? Yes, very much so. Most developers will look at the source code to know how things work under the hood, but they probably won&#8217;t modify it. Even if they do, they know that&#8217;s something they do at their own risk, so they&#8217;ll be more than willing to make a few changes whenever a new version is released. Everybody else will still definitely benefit from a relatively stable interface.</p>
<h2>Conclusion</h2>
<p>Writing reusable code starts with solving a problem and solving it well. The rest should all fall from there, and you can pick whichever method is more appropriate for your particular code and how you want to share it.</p>
<p>&nbsp;</p>
<p>This article was originally printed in the March 2009 issue of <a href="http://gdmag.com">Game Developer</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/writing-reusable-code/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>My Fear of Middleware</title>
		<link>http://gamesfromwithin.com/my-fear-of-middleware</link>
		<comments>http://gamesfromwithin.com/my-fear-of-middleware#comments</comments>
		<pubDate>Fri, 17 Jun 2011 20:30:27 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1391</guid>
		<description><![CDATA[Once upon a time, the idea of using some kind of middleware or major external library in my projects was out of the question. Writing all my code was the one and true way! I had a bad case of &#8230; <a href="http://gamesfromwithin.com/my-fear-of-middleware">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Once upon a time, the idea of using some kind of middleware or major external library in my projects was out of the question. Writing all my code was the one and true way! I had a bad case of <a href="http://en.wikipedia.org/wiki/Not_Invented_Here">NIH syndrome</a>.</p>
<p>Over the years I&#8217;ve mellowed out quite a bit. Now I recognize my obsession with writing endless tools and technology was more of an escape from doing the really hard part of game development. In comparison to making all the decisions involved in the design and implementation of the game itself, writing the perfect resource streaming system sounds like a really good time. It&#8217;s amazing how early it started too: I still remember spending weeks writing a Basic-to-assembly translator in 1986, before I had even heard the word &#8220;compiler&#8221;.</p>
<p>Now I just want to make games.</p>
<p><span id="more-1391"></span>I&#8217;ll gladly use code other people have written as long as they fit my needs. For example, I&#8217;m very happy with <a href="http://www.box2d.org/">Box2d</a> in <a href="http://www.box2d.org/">Casey&#8217;s Contraptions</a>. Was Box2d perfect? Far from it, but it was good enough and I&#8217;m very happy with the tradeoff.</p>
<p>So how come that Casey&#8217;s Contraptions, apart from Box2d, is all custom code, written in C and OpenGL? Why didn&#8217;t I use some of the great tools and libraries available like <a href="http://www.cocos2d-iphone.org/">Cocos2d</a> or <a href="http://unity3d.com/">Unity</a>?</p>
<p>In the land of AAA console games, developers routinely pull off the performance card: Only our code will allow us to make something that is so tailored to the hardware that it will make the game stand out above all other games. But for Casey&#8217;s Contraptions that&#8217;s not much of an issue: Any of the middleware options would be able to handle that amount of performance on an iPad just fine.</p>
<p>It wasn&#8217;t a lack of features either. We&#8217;re not doing anything particularly fancy, and I&#8217;m sure it would be possible to implement it in almost any other framework.</p>
<p>So if it&#8217;s not performance of features, why not?</p>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2011/06/2373515952_8dbda5be74_m.jpg" alt="2373515952 8dbda5be74 m" width="240" height="180" border="0" />Creating a game is a craft. It&#8217;s a mix of art and technique, and the craftsman or artisan has a vision and slowly probes, guides, and implements the final product. As with most crafts, the tools you use are extremely important and will directly affect the final product. If I&#8217;m going to change my tools and my techniques, the payoff I get needs to be huge to make up for the change. It&#8217;s as if I give up a set of hand woodworking tools for a power tool. Maybe it will be faster when I&#8217;m cutting in a straight line, but it will be very different and will completely change what I create.</p>
<p>As a game developer, my main tool is the language I use (C with a dash of C++). Things like editors or IDEs are secondary, and I can easily adapt to different ones without much of a problem (like when going from Visual Studio to Xcode). The way I like to work involves fast iterations, unit tests, very explicit memory layout, and processing data at a global, rather than local (entity) level.</p>
<p>I feel that by going to Unity or Cocos2d, I would have to completely give that up. A lot of middleware are frameworks instead of toolkits. That means I&#8217;m restricted to implementing bits of code that are embedded in a larger system and called by the rest of the framework. I give up the ability to architect the game in the way I want. Maybe it wouldn&#8217;t be a big deal if I liked a component or inheritance-based, entity-centered approach like a lot of frameworks, but I don&#8217;t.</p>
<p>Will I get enough benefits from using one of those frameworks to make up for the loss of productivity and techniques I like to use? Doubtful. All of a sudden I can&#8217;t just use fwrite on a memory block for serialization, I have to parse data files to load game state, undo/redo isn&#8217;t as simple as copying a block of memory, rendering becomes much more generic and less tied to the game, I can&#8217;t easily do test-driven development, iterate quickly, etc.</p>
<p><img style="float: left;" src="http://gamesfromwithin.com/wp-content/uploads/2011/06/Wood_Router.jpg" alt="Wood Router" width="180" height="196" border="0" />Sometimes, shifting workflows and techniques is inevitable. You may be used to solving collisions in a particular way, but when you move to a full physics engine, you need to process things differently. The payoff you get from using a pre-made physics engine is huge, so it&#8217;s worth it in my book.</p>
<p>For 2D games, there isn&#8217;t that much that I need: cross-platform support, simple math functions, ways to load textures, play sounds, and render simple things. Throw in some kind of simple UI display and layout tool, and that&#8217;s it. The rest I can handle. Actually, that&#8217;s not true, let me rephrase that: The rest I <strong>prefer</strong> to do myself, because it&#8217;s always highly dependent on the game.</p>
<p>What I really want is a toolkit-based middleware that does exactly those things without imposing any workflow or architecture on me. It saves me from doing the boring bits, gets out of the way as much as possible, and lets me work the way I want to. That&#8217;s already what I have with my current code, minus the UI library/tool part, which I&#8217;m still stuck using mostly UIKit. The idea of using Unity just so I can have cross-platform UI seems total overkill.</p>
<p>Even in the case of middleware that fits my style, I still need to be weary of the quality of the code. The last thing I want to do is trade time implementing my own code for time debugging someone else&#8217;s crappy code. Also, having learned my lesson years ago, I&#8217;ve sworn that I will never use a middleware/library that I don&#8217;t have source code access to. Nothing more frustrating than having to reverse-engineer UIKit classes to work around their bugs just because I don&#8217;t have the source code.</p>
<p>I&#8217;m not even going to go in the debate about middleware lock-in, future portability, building tech vs. relying on it, and financial aspects. All those are important, but secondary to how using some middleware will affect my everyday development.</p>
<p>If my next game were a networked, 3D game involving moving some kind of character or vehicle around a world, and I had nothing to start from, then the pain of adopting a foreign workflow and architecture might be worth it. Might. Even though it might be a wash on the code side, the tools and pipeline might be the thing that sways me over to adopt it.</p>
<p>In the end, as an indie developer, I chose to make games because it&#8217;s something I enjoy doing. I get up every morning excited about it, and I enjoy the development process. Whichever <a href="http://fairyengine.blogspot.com/2011/05/android-experiment-porting-my-xna-game.html">platform</a>, tool, middleware or process I end up choosing, it needs to be enjoyable. The day I&#8217;m not having fun making my own games, I shouldn&#8217;t be an indie anymore.</p>
<p>What do you think? Am I being overly paranoid? Is there a good solution out there that&#8217;s multiplatform and will double my productivity once I get used to it? Has anyone written their own code for a 2D game and later switched to Cocos2d/Unity and liked it?</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/my-fear-of-middleware/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>The Curious Case of Casey and The Clearly Deterministic Contraptions</title>
		<link>http://gamesfromwithin.com/casey-and-the-clearly-deterministic-contraptions</link>
		<comments>http://gamesfromwithin.com/casey-and-the-clearly-deterministic-contraptions#comments</comments>
		<pubDate>Fri, 13 May 2011 19:22:57 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[casey's contraptions]]></category>
		<category><![CDATA[physics]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1346</guid>
		<description><![CDATA[As we gear up for Casey&#8217;s Contraptions launch on May 19th, this is the first post in a series dealing with different aspects of the game. I&#8217;m planning on covering technical aspects like today, but also design and other parts &#8230; <a href="http://gamesfromwithin.com/casey-and-the-clearly-deterministic-contraptions">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As we gear up for <a href="http://www.caseyscontraptions.com/">Casey&#8217;s Contraptions</a> launch on May 19th, this is the first post in a series dealing with different aspects of the game. I&#8217;m planning on covering technical aspects like today, but also design and other parts of development.</p>
<div style="text-align: center;"><img src="http://gamesfromwithin.com/wp-content/uploads/2011/05/Casey-640x100.jpg" alt="Casey 640x100" width="640" height="100" border="0" /></div>
<p>For those of you who have been living under a rock and haven&#8217;t seen the Casey&#8217;s Contraptions video, go watch it now. I&#8217;ll wait. Or even better, here it is. You don&#8217;t even have to leave this page:</p>
<div style="text-align: center;"><iframe src="http://www.youtube.com/embed/JlqNa9mEqNE" frameborder="0" width="640" height="390"></iframe></div>
<p><span id="more-1346"></span>The core interaction loop of Casey&#8217;s Contraptions gameplay is placing some items, pressing the Play button, seeing the simulation, and repeating based on what you learned from seeing the simulation. We designed this loop to be very tight and without any penalty: Running/stopping the simulation is instant, there&#8217;s no limit on the number of times you run it, and you can even stop the simulation by tapping anywhere on the screen. Even if you painted yourself in a wall by creating a solution that needs a very specific placement of items on the screen, making small changes is very quick and painless.</p>
<p>There&#8217;s a very important, underlaying assumption in that loop: Running the same simulation multiple times will result in the same behavior. Imagine how frustrating it would be to create a complex chain reaction, just to find out it only works every other time you run it. That would truly deserve a ONE STAR WANT MY MONEY BACK!!</p>
<h3>Determinism</h3>
<p>That&#8217;s referred to as the game being deterministic: Given the same inputs, it produces the same outputs. It&#8217;s not the first time I&#8217;ve had to deal with that. Actually, it seems that I&#8217;ve had to deal with that in <a href="http://gamesfromwithin.com/back-to-the-future-part-1">one form</a> <a href="http://gamesfromwithin.com/back-to-the-future-part-2">or another</a> for all my games in the last 10 years (except for Flower Garden). Most recently, it was a key component of gameplay for the <a href="http://kotaku.com/259968/prototyping-for-fun-and-profit">unreleased game we were working on at Power of Two Games</a>.</p>
<p>To make a game deterministic, you need to remove the obvious sources of &#8220;accidentally different&#8221; inputs. That&#8217;s usually random number generators, and making sure the initial state is truly the same. It&#8217;s too easy to have some leftover state from the previous simulation that throws things off a little bit.</p>
<p>Another potential source of problems are uninitialized variables. If at some point the simulation depends on an uninitialized variable, different runs will cause different results based on whatever value happened to be in memory at that time.</p>
<p>Once you fix all of those little things, that should be it, right? Same input should create the same output. Not really. We&#8217;re missing the most crucial input: The timer.</p>
<p>Casey&#8217;s Contraptions runs at 60 fps on an iPad one, but the timestep isn&#8217;t set to a fixed 16.667ms. Instead, I use a high-resolution timer to measure how much time has really elapsed since last frame, and I advance the simulation by that much.</p>
<p>The problem is that the timer doesn&#8217;t always return the exact same amount. It&#8217;s not super-precise, and it can be slightly affected by other things going on in the device. It won&#8217;t be off by more than 1/10th of a ms, but that&#8217;s enough to cause different results and start diverging the simulation.</p>
<h3>Fixed timestep</h3>
<p>One way to get around this problem is to hardcode the timestep to always be 16.667ms, independently of what it really was. That would fix the determinism problem, but it would add its own drawbacks. If the simulation can&#8217;t keep up with 60 fps, the game will appear to slow down, which is not the effect we want. Casey&#8217;s Contraptions includes a level editor to make your own free-form contraptions, and even though we have a cap in the maximum number of items you can add, it&#8217;s probably possible to add enough of them to start slowing down an iPad 1.</p>
<div style="text-align: center;"><img src="http://gamesfromwithin.com/wp-content/uploads/2011/05/CaseyDollTruck.jpg" alt="CaseyDollTruck" width="474" height="231" border="0" /></div>
<h3>Recording timesteps</h3>
<p>A tempting solution (and one I&#8217;m ashamed I even briefly tried), is to record the exact timestep during the first run of the simulation. Then, in subsequent runs when nothing has changed, we use the initially recorded stream of timesteps instead of the real ones from the clock.</p>
<p>Apart from being a clumsy-looking solution (I hate having two modes for doing the same thing), the solution only works in the case of replaying the exact same input. This approach falls apart if you make a change to an item that doesn&#8217;t affect the simulation until after several seconds have passed. At that point, you&#8217;re running a new simulation with new timesteps and everything can diverge before the affected object is changed. Bad, idea. Bad.</p>
<h3>Fixed simulation timesteps</h3>
<p>This is the correct solution and it&#8217;s what we&#8217;re doing in Casey&#8217;s Contraptions.</p>
<p>You probably already know that physics simulations are a lot more stable if you take small steps, always of the same size. So you really never want to advance your physics simulation by your frame time. Instead, you want to have a small and fixed simulation step (we&#8217;re running at 120Hz, but 200 or even 300 are not unheard of). Then, you run the physics simulation as many times as you can fit into your larger timestep. It&#8217;s also important to keep around the amount of leftover time you haven&#8217;t simulated, to apply it to the next frame.</p>
<p>The simulation loop code looks something like this:</p>
<pre>	const float timestep = 1.0f/120.0f;
	accumulator += dt;
	while (accumulator &gt;= timestep)
	{
		// Do physics simulation by timestep
		accumulator -= timestep;
	}</pre>
<p>Once we have this loop in place, our real frame time doesn&#8217;t matter anymore. The physics simulation will either run for a full step (or multiple steps), or it won&#8217;t. There&#8217;s no half-way states. So it doesn&#8217;t matter if in the first run of the simulation the loop gets executed 3 times in the first frame and 2 times in the second, and in the next simulation is 2 times in the first and 3 in the second. The state of the world will be the same.</p>
<p><a href="http://gafferongames.com/">Glenn Fiedler</a> writes about this kind of simulation loop in much more detail in <a href="http://gafferongames.com/game-physics/fix-your-timestep/">this excellent article</a>.</p>
<h3>Jitterbug</h3>
<p>There&#8217;s still a slight problem with the above loop. Nothing horrible; the simulation is deterministic at this point (assuming everything else is taken care of correctly). But you might notice some annoying jittering as things move around.</p>
<div style="text-align: center;"><img src="http://gamesfromwithin.com/wp-content/uploads/2011/05/CaseysDollKick1.jpg" alt="CaseysDollKick" width="431" height="221" border="0" /></div>
<p>That&#8217;s because how we&#8217;re sampling the simulation. We might render a frame after 3 steps of the physics simulation, but another one after 2. So movement isn&#8217;t going to be very smooth.</p>
<p>To get around it, we need to interpolate the state of the world to match the time at which the frame is rendered. To do that, we need to simulate one timestep in the future, and then interpolate between the previous one and the future one by the percentage amount left in the accumulator.</p>
<p>Something like this:</p>
<pre>	const float timestep = 1.0f/120.0f;
	accumulator += dt;
	while (accumulator &gt;= timestep)
	{
		GameState lastState = gameState;
		// Do physics simulation by timestep
		accumulator -= timestep;
	}

	const float t = accumulator/timestep;
	GamePhysicsUtils::LerpState(interpolatedState, prevState, gameState, t);</pre>
<p><em></em><br />
The interpolation is just the positions and rotations of every item in the world. That&#8217;s only used for rendering, so no need to worry about velocities or forces (unless those are affecting rendering in a very obvious way too).</p>
<p>This is when it comes really handy to have the game state as a contiguous, relocatable block of memory. You can really easily copy states around without having to worry about allocating any memory or fixing any pointers. Yes, I really like my <a href="http://gamesfromwithin.com/start-pre-allocating-and-stop-worrying">simple, pre-allocated data</a>.</p>
<p>One added benefit of this approach: If you do it right, you can have extreme slow-motion in your game and everything will be right. Even if you only run one physics simulation loop every 10 rendering frames, the interpolation will take care of making sure everything is super smooth.</p>
<h3>Odds and ends</h3>
<p>A couple gotchas to watch out for (that&#8217;s code speak for &#8220;I didn&#8217;t think of this and it bit me hard&#8221;).</p>
<p>If you have any game logic that affects the physical state of your game objects, it needs to be executed in the inner, simulation loop. Anything that deals with visual or audio stuff can go in the regular update loop and only be executed once per frame.</p>
<p>A good example of this was the balloon code. Every frame, I iterate through all existing balloons, and apply some upward force based on buoyancy and other factors. Initially that was done once per frame, after the physics simulation, but that&#8217;s obviously wrong because it will leave balloons (and everything else) in a different state depending on your frame delta time. I moved it to the inner simulation loop and everything became deterministic again.</p>
<div style="text-align: center;"><img src="http://gamesfromwithin.com/wp-content/uploads/2011/05/CaseyBalloons.png" alt="CaseyBalloons" width="500" height="260" border="0" /></div>
<p>This second gotcha sounds silly, but it was a big deal: Make sure you deal with the situation where you have different numbers of items in the previous game state than in the next game state. For example, if a balloon is destroyed, between the two states, the item count will be different. In my case I don&#8217;t free any memory, but I was initially making the assumption that I could interpolate based on the index of the items on both states. But since I removed the balloon and pushed all the items behind it forward, the interpolation was totally wrong.</p>
<p>I solved that problem by marking items as invalid, and removing them only after the inner simulation loop was complete. That allowed me to still interpolate in a very straightforward way and not have to worry about missing items.</p>
<h3>Taking it further</h3>
<p>Not only are we relying on this determinism while you play a level of Casey&#8217;s Contraptions, but also to let you replay solutions from your friends. We simply load their initial layout and run the simulation locally.</p>
<p>[Pause]</p>
<p>Ah, yes, astute reader, you&#8217;re right to be puzzled about that. How do we make the simulation deterministic across platforms and versions? Good question. Stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/casey-and-the-clearly-deterministic-contraptions/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Start Pre-allocating And Stop Worrying</title>
		<link>http://gamesfromwithin.com/start-pre-allocating-and-stop-worrying</link>
		<comments>http://gamesfromwithin.com/start-pre-allocating-and-stop-worrying#comments</comments>
		<pubDate>Mon, 25 Oct 2010 20:31:57 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Game tech]]></category>
		<category><![CDATA[inner product]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1203</guid>
		<description><![CDATA[One of the more frequent questions I receive is what kind of memory allocation strategy I use in my games. The quick answer is none (at least frame to frame, I do some allocation at the beginning of each level &#8230; <a href="http://gamesfromwithin.com/start-pre-allocating-and-stop-worrying">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><i>One of the more frequent questions I receive is what kind of memory allocation strategy I use in my games. The quick answer is none (at least frame to frame, I do some allocation at the beginning of each level on a stack-based allocator). This reprint of one of my Inner Product column covers quite well how I feel about memory allocation.</i></p>
<p><br/></p>
<p>We&#8217;ve all had things nagging us in the back of our minds. They&#8217;re nothing we have to worry about this very instant, just something we need to do sometime in the future. Maybe that&#8217;s changing those worn tires in the car, or making an appointment with the dentist about that tooth that has been bugging you on and off.</p>
<p>Dynamic memory allocation is something that falls in that category for most programmers. We all know we can&#8217;t just go on allocating memory willy-nilly whenever we need it, yet we put off dealing with it until the end of the project. By that time, deadlines are piling on the pressure and it&#8217;s usually too late to make significant changes. With a little bit of forethought and pre-planning, we can avoid those problems and be confident our game is not going to run out of memory in the most inopportune moment.</p>
<h3>On-Demand Dynamic Memory Allocation</h3>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/10/memory-all-ranks.jpg" alt="memory-all-ranks.jpg" border="0" width="295" height="181" />The easiest way to get started with memory management is to allocate memory dynamically whenever you need it. This is the approach many software engineering books consider as ideal and it&#8217;s often encouraged in Computer Science classes.</p>
<p>It&#8217;s certainly an easy approach to use. Need a new animation instance when the player is landing on a ledge? Allocate it. Need a new sound when we reach the goal? Just allocate another one! </p>
<p>On-demand dynamic memory allocation can help to keep memory usage to a minimum, because, you only allocate the memory that you need and no more. In practice it&#8217;s not quite as neat and tidy because there can be a surprisingly large amount of overhead per allocation, which adds up if programmers become really allocation-happy.</p>
<p>It&#8217;s also a good way to shoot yourself in the foot.</p>
<p>Games don&#8217;t live inside a Computer Science textbook, so we have to deal with real world limitations, which make this approach cumbersome, clunky, and potentially disastrous. What can go wrong with on-demand dynamic memory allocation? Almost everything!</p>
<h4>Limited Memory</h4>
<p>Games, or any software for that matter, run on machines with limited amounts of memory. As long as you know what that limit is, and you keep extremely careful track of your memory usage, you can remain under the limit. However, since the game is allocating memory any time it needs it, there will most likely come a time when the game tries to allocate a new block but there is no memory left. What can you do then? Nothing easy I&#8217;m afraid. You can try to free an older memory block and allocate the new one there, or you can try to make your game tolerant to running out of memory. Both those solutions are very complex and difficult to implement correctly.</p>
<p>Even setting memory budgets and sticking to them can be very difficult. How can a designer know that a given particle system isn&#8217;t going to run out of memory? Are these AI units going to create too many pathfinding objects and crash the game? Hard to say until we run the game in all possible combinations. And even then, how do you know it isn&#8217;t going to crash five minutes later? Or ten? It&#8217;s almost impossible to know for certain.</p>
<p>If you insist in using this approach, at the very least, you should tag all memory allocations, so you have an idea of how memory is being used. You can either tag each allocation based on what system initiated it (physics, textures, animation, sound, AI, etc) or even on the filename where it originated, which has the advantage that it can be automated and should still give you a good picture of the overall memory usage.</p>
<h4>Memory Fragmentation</h4>
<p>Even if you take lots of pain not to go over your the available memory, you might still run into trouble because of memory fragmentation. You might have enough memory for a new allocation, but in the form of many small memory blocks instead of a large contiguous one. Unless you provide your own memory allocation mechanism, fragmentation is something that is very hard to track on your own, so you can&#8217;t even be ready for it until the allocation fails.</p>
<h4>Virtual Memory</h4>
<p>Virtual memory could solve all those problems. In theory, if you run out of real memory, the operating system swaps out some older, unused pages to disk and makes room for the new memory you requested. In practice, it&#8217;s just a bad caching scheme because it can be triggered at the worst possible moment, and it doesn&#8217;t know about what data it&#8217;s swapping out or how your game uses it.</p>
<p>Games, unlike most other software, have a &#8220;soft realtime&#8221; requirement: The game needs to keep updating at an acceptable interactive rate, which is somewhere around 15 or more frames per second. That means that gamers are going to make a trip to the store to return your game if it pauses for a couple of seconds every few minutes to &#8220;make some room&#8221; for new memory. So relying on virtual memory isn&#8217;t a particularly attractive solution.</p>
<p>Additionally, lots of games run in platforms with fixed amounts of RAM and no virtual memory. So when memory runs out, things won&#8217;t get slow and chuggy, they&#8217;ll crash hard. When the memory is gone, it&#8217;s really gone.</p>
<h4>Performance Problems</h4>
<p>There are some performance issues that are relatively easy to track down and fix. Usually ones that occur every frame and are happening in a single spot: some expensive operation, a O(n3) algorithm, etc. Then there are performance problems introduced by dynamic memory allocations, which can be really hard to track down.</p>
<p>Standard malloc returns memory pretty quickly, and usually doesn&#8217;t ever register on the the profiler. Every so often though, whenever the game has been running for a while and memory is pretty fragmented, it can spike up and cause a significant delay for just a frame. Trying to track down those spikes has caused more than one programmer to age prematurely. You can avoid some of those problems by using your own memory manager, but don&#8217;t attempt to write a generic one yourself from scratch. Instead start with some of the ones listed in the references. </p>
<p>Malloc spikes are not the only source of performance problems. Allocating many small blocks of memory can lead to bad cache coherence when the game code access them sequentially. This problem usually manifests itself as a general slowdown that can&#8217;t be narrowed down in the profiler. With today&#8217;s hardware of slow memory systems and deep caches, good memory access patterns are more important than ever.</p>
<h4>Keeping Track Of Memory</h4>
<p>Another source of problems with dynamic memory allocation are bugs in the logic that keeps track of the allocated memory blocks. If we forget to free some of them, our program will have memory leaks and has the potential to run out of memory. </p>
<p>The flip side of memory leaks are invalid memory access. If we free a memory block and later we access it as if it were allocated, we&#8217;ll either get a memory access exception, or we&#8217;ll manage to corrupt our own game.</p>
<p>Some techniques, such as reference counting and garbage collection can help keep track of memory allocations, but introduce their own complexities and overhead.</p>
<h3>Introducing Pre-allocation</h3>
<p>On the opposite corner of the boxing ring is the purely pre-allocated game. It excels at everything that the dynamically-allocated game is weak at, but it has a few weaknesses of its own. All in all, it&#8217;s probably a much safer approach for most games though.</p>
<p>The idea behind a pre-allocation memory strategy is to allocate everything once and never have to do any dynamic allocations in the middle of the game. Usually you grab as big a block of memory as you can, and then you carve it out to suit your game&#8217;s needs.</p>
<p>Some advantages are very clear: no performance penalties, knowing exactly how your memory is used, never running out of memory, and no memory fragmentation to worry about. There are some other more subtle advantages, such as being able to put data in contiguous areas of memory to get best cache coherency, or having blazingly-fast load times by loading a baked image of a level directly into memory.</p>
<p>The main drawback of pre-allocation is that is more complex to implement than the dynamic allocation approach and it takes some planning ahead.</p>
<h4>Know Your Data</h4>
<p>For preallocation to work, you need to know ahead of time how much of every type of data you will need in the game. That can be a daunting proposition, especially to those used to a more dynamic approach. However, with a good data baking system (see last month&#8217;s Inner Product column), you can get a global view of each level and figure out how big things need to be.</p>
<p>There is one important design philosophy that needs to be adopted for preallocation to work: Everything in the game has to be bounded. That shouldn&#8217;t feel too restrictive; after all, the memory in your target platform is bounded, as well as every single resource. That means that everything that can create new objects, including high-level game constructs, should operate on a fixed number of them. This might seem like an implementation detail, but it often bubbles up to what&#8217;s exposed to game designers. A common example is an enemy spawner. Instead of designing a spawner with an emission rate, it should have a fixed number of enemies it can spawn (and potentially reuse them after they&#8217;re dead).</p>
<h4>Potentially Wasted Space</h4>
<p>If you allocate enough data for the worst case in your game, that can lead to a lot of unused data most of the time. That&#8217;s only an issue if that unused data is preventing you from adding more content to the game. We might initially balk at the idea of having 2000 preallocated enemies when we&#8217;re only going to see 10 of them at once. But when you realize that each of those enemies is only taking 256 bytes and the total overhead is 500 KB, which can be easily accommodated in most modern platforms today.</p>
<p>Preallocation doesn&#8217;t have to be as draconian as it sounds though. You could relax this approach and commit to having each level preallocated and never having dynamic memory allocations while the game is running. That still allows you to dynamically allocate the memory needed for each level and keep wasted space to a minimum. Or you can take it even further and preallocate the contents of memory blocks that are streamed in memory. That way each block can be divided in the best way for that content and wasted space is kept to a minimum.</p>
<h4>Reuse, RecycleM</h4>
<p>If you don&#8217;t want to preallocate every single object you&#8217;ll ever use, then you can create a smaller set, and reuse them as needed. This can be a bit tricky though. First of all, it needs to be very much specific to the type of object that is reused. So particles are easy to reuse (just drop the oldest one, or the ones not in view), but might be harder with enemy units or active projectiles. It&#8217;s going to take some game knowledge of those objects to decide which ones to reuse and how to do it.</p>
<p>It also means that systems need to be prepared to either fail an allocation (if your current set of objects is full and you don&#8217;t want to reuse an existing one), or they need to cope with an object disappearing from one frame to another. That&#8217;s a relatively easy problem to solve by using handles or other weak references instead of direct pointers.</p>
<p>Then there&#8217;s the issue that reusing an object isn&#8217;t as simple as constructing a new one. You really need to make sure that when you reuse it, there&#8217;s nothing left from the object it replaced. This is easy when your objects are just plain data in a table, but can be more complicated when they&#8217;re complex C++ classes tied together with pointers. In any case, you can&#8217;t apply the Resource Acquisition Is Initialization (RAII) pattern, but it doesn&#8217;t seem to be a pattern very well suited for games, and it&#8217;s a small price to pay for the simplicity that preallocation provides.</p>
<h3>Specialized Heaps</h3>
<p>Truth be told, a pure pre-allocated approach can be hard to pull off, especially with highly dynamic environments or games with user-created content. Specialized heaps is a combination of dynamic memory allocation and pre-allocation  that takes the best of both worlds.</p>
<p>The idea behind specialized heaps is that the heaps themselves are pre-allocated, but they allow some form of specialized dynamic allocation within them. That way you avoid the problems of running out of memory, or memory fragmentation globally, but you still can perform some sort of dynamic allocation when needed. </p>
<p>One type of specialized heaps is based on the object type. If you can guarantee that all objects allocated in that heap are going to be of the same size, or at least a multiple of a certain size, memory management becomes much easier and less error prone, and removes a lot of the complexity of a general memory manager.</p>
<p>My favorite approach for games is to create specialized heaps based on the lifetime of the objects allocated in them. These heaps use sequential allocators, always allocating memory from the beginning of a memory block. When the lifetime of the objects is up, the heap is reset and allocations can start from the beginning again. The use of a simple sequential allocator bypasses all the insidious problems of general memory management: fragmentation, compaction, leaks, etc. See the code in http://gdmag.com/resources/code.htm for an implementation of a SequentialAllocator class.</p>
<p>The heap types most often used in games are:</p>
<ul>
<li>Level heap. Here you allocate all the assets and data for the level at load time. When the level is unloaded, all objects are destroyed at once. If your game makes heavy use of streaming, this can be a streaming block instead of a full level.</li>
<li>Frame heap. Any temporary objects that only need to last a frame or less get allocated here, and destroyed at the end of the frame.</li>
<li>Stack heap. This one is a bit different from the others. Like the other heaps, it uses a sequential allocator and objects are allocated from the beginning, but instead of destroying all objects at once, it only destroys objects up to the marker that is popped fro the stack.</li>
</ul>
<h3>What About Tools?</h3>
<p>You can take everything I&#8217;ve written here, and (almost) completely ignore it for tools. I fall in the camp of the programmers who consider the runtime as a totally separate beast from the tools. That means that the runtime can be lean and mean and minimalistic, but I can relax and use whatever technique makes me more productive when writing tools. That means you can allocate memory any time you want, you can use complex libraries like STL and Boost, etc. Most tools are going to run on a beefy PC and a few extra allocations here and there won&#8217;t make any difference.</p>
<p>Be careful with performance-sensitive tools though. Tools that build assets or compute complex lighting calculations might be a bottleneck in the build process. In that case, performance becomes crucial again and you might want to be a bit more careful about memory layout and cache coherency.</p>
<p>On the other hand, if the tool you&#8217;re writing is not performance sensitive, you should ask yourself if it really needs to be written in C++. Maybe C# or Python are better languages if all you&#8217;re doing is transforming XML files or verifying that a file format is correct. Trading performance for ease of development is almost always a win with development tools.</p>
<p><br/></p>
<p>Next time you reach out for a malloc inside your main loop, think about how it can fail. Maybe you can pre-allocate that memory and stop worrying about what&#8217;s going to happen the day you prepare the release candidate.</p>
<p><br/></p>
<p><em>This article was originally printed in the February 2009 issue of <a href="http://gdmag.com">Game Developer</a>.<br />
</em></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/start-pre-allocating-and-stop-worrying/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Life In The Top 100 And The Google App Engine</title>
		<link>http://gamesfromwithin.com/life-in-the-top-100-and-the-google-app-engine</link>
		<comments>http://gamesfromwithin.com/life-in-the-top-100-and-the-google-app-engine#comments</comments>
		<pubDate>Thu, 07 Oct 2010 20:44:21 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iDevBlogADay]]></category>
		<category><![CDATA[flower garden]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1179</guid>
		<description><![CDATA[A few weeks ago I wrote about using the Google App Engine as a back end for Flower Garden. One of the comments I heard from several people is that the Google App Engine pricing scheme is &#8220;scary&#8221; due to &#8230; <a href="http://gamesfromwithin.com/life-in-the-top-100-and-the-google-app-engine">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago I wrote about <a href="http://gamesfromwithin.com/google-app-engine-as-back-end-for-iphone-apps">using the Google App Engine as a back end for Flower Garden</a>. One of the comments I heard from several people is that the Google App Engine pricing scheme is &#8220;scary&#8221; due to its unpredictability. What if your server gets very busy and you find yourself with a huge bill?</p>
<h3>Google App Engine Costs</h3>
<p>At the time I wrote that post, the bandwidth of Flower Garden (and Flower Garden Free) was just under the free bandwidth allowance, so I didn&#8217;t have to pay anything. However, this last week, after <a href="http://gamesfromwithin.com/communicating-with-players">riding the Pocket Frogs rocket</a>, Flower Garden Free shot up to the #56 overall app in the US. And boy, did that make a difference in server usage!</p>
<p><center><img src="http://gamesfromwithin.com/wp-content/uploads/2010/10/serverload.jpg" alt="serverload.jpg" border="0" width="500" height="264" /></center></p>
<p>That screenshot shows the Google App Engine dashboard with the number of requests per second for a 4 day period. Can you guess when the Pocket Frogs cross-promotion started? It went from an average of 1.5 requests per second, to a peak of about 16. That&#8217;s a factor of 10 right there.</p>
<p>Let&#8217;s see what that means in terms of cost. With the Google App Engine, you get charged for different resources you consume: CPU usage, incoming bandwidth, outgoing bandwidth, data storage, and recipients emailed. Of those, the only one that Flower Garden makes any dent on is outgoing bandwidth (mostly the HTML pages and images in the Flower Shop).</p>
<p>For each of those resources, you get a free amount every day. In the case of outgoing bandwidth, we get 1GB before we have to start paying anything. Afterwards, it&#8217;s $0.12 per GB. The peak day for Flower Garden Free, when it was all the way at #56, it consumed 7.8 GB. Now that it&#8217;s back down, it&#8217;s using up at around 2-3 GB of outgoing data every day.</p>
<p>That means, that the busiest day I was charged $0.82 in bandwidth, but the profits for that day were over $1500! I can only hope for days just as busy!</p>
<p><center><img src="http://gamesfromwithin.com/wp-content/uploads/2010/10/charges.png" alt="charges.png" border="0" width="600" height="121" /></center></p>
<p>As a reference, these are my Google App Engine charges for the busy week during the promotion. $3.28 for the week? Bring it on! <img src='http://gamesfromwithin.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Minimizing Bandwidth</h3>
<p>When I first saw the first day&#8217;s bandwidth, I was pretty surprised it was taking up that much. I hadn&#8217;t tried to minimize it first, but 8 GB seemed like a significant amount.</p>
<p>The first thing I did was to forward any requests to the <a href="http://st-flowershop.appspot.com/moregames/index.html">&#8220;More Games&#8221;</a> and &#8220;News&#8221; section back to the Dreamhost account. After all, if that server goes down, it doesn&#8217;t really matter, and they can take up significant bandwidth with all the images.</p>
<p>To forward something, I couldn&#8217;t just do it from the configuration file. Instead, I set a handler for the moregames directory like this:</p>
<pre>
- url: /moregames/.*
  script: redirect.py
</pre>
<p>And the redirect script is very simple:</p>
<pre>
import os
import sys
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class RedirectMoreGames(webapp.RequestHandler):
	def get(self, params):
		url = "http://flowers.snappytouch.com/moregames/Snappy_Touch_More_Games/More_Games.html"
		self.redirect(url, permanent=True)

application = webapp.WSGIApplication(
							[(r'/(.*)', RedirectMoreGames),
							 ],
							debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
</pre>
<p>Another thing you can do is to turn on <a href="http://code.google.com/appengine/docs/python/config/appconfig.html#Static_File_Handlers">explicit caching of files in the app.yaml</a> file for your Google App Engine app. I don&#8217;t know how much that helps with data requested from within an iPhone app, but it can&#8217;t hurt.</p>
<p>Finally, I made some changes to Flower Garden. I never had bandwidth minimization in mind, so for example, I was happily requesting updated news and other data at the beginning of every session. I wised up a bit and now it only requests that data at most once every few hours or days.</p>
<p>In case you&#8217;re ever getting close to using up your quotas, I learned that you can <a href="http://code.google.com/appengine/docs/quotas.html">query them at runtime</a>. I haven&#8217;t done anything about it yet, but I suppose I could start forwarding image fetches to a backup server whenever I get close to the limit. But for that, I&#8217;ll have to sell many more units of Flower Garden!</p>
<h3>Google App Engine Shortcomings</h3>
<p>Overall, I&#8217;m very happy with the Google App Engine. But it&#8217;s not all a bed of roses over here. I think the Google App Engine excels at scaling under heavy load, but surprisingly, it doesn&#8217;t have anything close to 100% uptime. I&#8217;m going to say it probably doesn&#8217;t even have 95% uptime! With such a massive system and all the redundancy underneath, I&#8217;m surprised they can&#8217;t have better uptime. Supposedly <a href="http://code.google.com/status/appengine">their status page</a> makes you think everything is perfect, but it&#8217;s really far from it.</p>
<p>Apart from downtime, people are also reporting <a href="http://groups.google.com/group/google-appengine/browse_frm/thread/f8dd1f332ab32909#">severe latency issues sometimes</a>, and I&#8217;ve seen some errors like that in my log every so often. Chalk it up to being a beta I suppose. I imagine it&#8217;s only going to get better with time.</p>
<p>I would still use the Google App Engine for any new game I&#8217;ll release in the future, whether it has big or small backend needs. If nothing else, the ease of development and testing beats every alternative for me.</p>
<p><br/></p>
<p><i>This post is part of <a href="http://idevblogaday.com/">iDevBlogADay</a>, a group of indie iPhone development blogs featuring two posts per day. You can keep up with iDevBlogADay through the <a href="http://idevblogaday.com/">web site</a>, <a href="http://feeds.feedburner.com/idevblogaday">RSS feed</a>, or <a href="http://twitter.com/#search?q=%23idevblogaday">Twitter</a>.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/life-in-the-top-100-and-the-google-app-engine/feed</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Lag: The Bane Of Touch Screens</title>
		<link>http://gamesfromwithin.com/lag-the-bane-of-touch-screens</link>
		<comments>http://gamesfromwithin.com/lag-the-bane-of-touch-screens#comments</comments>
		<pubDate>Thu, 16 Sep 2010 18:53:17 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iDevBlogADay]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1152</guid>
		<description><![CDATA[Lag in games is as inevitable as taxes. It&#8217;s something we can try to minimize, but we always need to live with it. Earlier this week, I noticed that input for my new iPad game was very laggy. Excessively so, &#8230; <a href="http://gamesfromwithin.com/lag-the-bane-of-touch-screens">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Lag in games is as inevitable as taxes. It&#8217;s something we can try to minimize, but we always need to live with it. Earlier this week, I noticed that input for my new iPad game was very laggy. Excessively so, to the point it was really detracting from the game, so I decided I had to look into it a bit more.</p>
<h3>Lag In Games</h3>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/09/got_lag.png" alt="got_lag.png" border="0" width="229" height="300" />I&#8217;m defining lag as the time elapsed between the moment the player performs an input action (press a button, touch the screen, move his finger), until the game provides some feedback for that input (movement, flash behind a button, sound effect).</p>
<p>Mick West wrote <a href="http://cowboyprogramming.com/2008/05/27/programming-responsiveness/">a great article on the causes of lag in games</a>, followed up by <a href="http://cowboyprogramming.com/2008/05/30/measuring-responsiveness-in-video-games/">another one in how to measure it</a>. I&#8217;m going to apply some of that to the lag I was experiencing in my game.</p>
<p>Lag can be introduced in games by many different factors:</p>
<ul>
<li>Delay between gathering input and delivering it to the game.</li>
<p><il>Delay updating the simulation to reflect new inputs.</li>
<li>Delay rendering simulation state.</li>
<li>Delay displaying the latest rendered state on screen.</li>
</ul>
<p>The new game runs on the iPad and involves moving objects around the screen with your finger. To make sure it wasn&#8217;t anything weird with the rest of the game code, I wrote <a href="http://gamesfromwithin.com/wp-content/uploads/2010/09/LagTest.zip">a quick (and ugly!) program</a> that draws a square with OpenGL that follows your finger on the screen. When you run the sample, the same lag becomes immediately obvious. </p>
<p>The iPad is a much larger device than the iPhone, and it encourages a physical metaphor even more. As soon as you attempt to move an &#8220;object&#8221; on screen, the lag kills that sense of physicality. Instead of moving an object around with your finger, you&#8217;re dragging it around with a rubber band. It moved the player from applying direct action on screen, to being removed and disassociated with the actions on screen.</p>
<h3>Loop Structure</h3>
<p>The place to start looking for lag is in my main loop. The main loop looks something like this:</p>
<pre>
	ProcessInput();
	UpdateSimulation();
	RenderWorld();
	PresentRenderBuffer();
</pre>
<p>So I was reading the input correctly before the simulation. Nothing weird there.</p>
<p>Touch input is delivered to the code as events from the OS. Whenever I received those events (outside of the main loop), I queue them, and then process them all whenever the main loop starts in ProcessInput().</p>
<p>The loop runs at 60Hz, so the lag here is at most 16.7 ms (if you&#8217;re running at 30Hz, then you&#8217;re looking at a delay up to 33.3ms). Unfortunately, the lag I was seeing in the game was way more than one frame, so there was to be something else.</p>
<h3>Rendering</h3>
<p>For some reason, I thought that iDevices were triple buffered. I ran some tests and fortunately it looks like it&#8217;s regular double buffering. That means that if I render a frame and call presentRenderBuffer(), the results of that render will be visible on screen at the next vertical sync interval. I&#8217;m sure there&#8217;s a slight lag with the iPad screen, but I&#8217;m willing to be is close to negligible when we&#8217;re talking about milliseconds, so we&#8217;ll call that zero.</p>
<h3>Main Loop Calls</h3>
<p>The game uses CADisplayLink with interval of 1, so the main loop is called once every 16.7 ms (give or take a fraction of ms). I thought that perhaps CADisplayLink wasn&#8217;t playing well with touch events, so I tried switching to NSTimer, and even to <a href="http://gamesfromwithin.com/gdc-austin-2009-squeezing-every-drop-of-performance-out-of-the-iphone">my old thread-driven main loop</a>, but none of it seemed to make any difference. Lag was alive and well as always.</p>
<p>That the simulation and rendering in the game are very fast, probably just a few ms. That means the rest of the system has plenty of time to process events. If I had a full main loop, maybe one of the two other approaches would have made a difference.</p>
<p>It looks like the lag source had to be further upstream.</p>
<h3>Input Processing</h3>
<p>On the dashboard, press and hold on an icon, now move it around the screen. That&#8217;s the same kind of lag we have in the sample program! That&#8217;s not encouraging.</p>
<p>A touch screen works as a big matrix of touch sensors. The Apple OS processes that input grid and tries to make sense out of it by figuring out where the touches are. The iOS functions eventually process that grid, and send our programs the familiar touchesBegan, touchesMoved, etc events. That&#8217;s not easy task by any means. It&#8217;s certainly not like processing mouse input, which is discrete and very clearly defined. For example, you can put your whole palm down on the screen. Where are the touches exactly?</p>
<p>TouchesBegan is actually a reasonably easy one. That&#8217;s why you see very little lag associated with that one. Sensors go from having no touch values, to going over a certain threshold. I&#8217;m sure that as soon as one or two of them cross that threshold, the OS identifies that as a touch and sends up the began event.</p>
<p>TouchesMoved is a lot more problematic. What constitutes a touch moving? You need to detect the area in the sensor grid that is activated, and you need to detect a pattern of movement and find out a new center for it. In order to do that, you&#8217;ll need several samples and a fair amount of CPU cycles to perform some kind of signal processing on the inputs. That extra CPU usage is probably the reason why some games get choppier as soon as you touch the screen.</p>
<h3>Measuring Lag</h3>
<p>Measuring lag in a game is tricky. You usually can&#8217;t measure it from within the code, so you need to resort to external means like <a href="http://cowboyprogramming.com/2008/05/30/measuring-responsiveness-in-video-games/">Mick did in his tests</a>.</p>
<p>I decided to do something similar. I pulled out my digital video camera, and started recording my finger moving on the screen. The quality leaves much to be desired, but it&#8217;s good enough for the job. I can see how far my finger gets from the center of the square, but that&#8217;s not enough information to quantify the lag. How fast is my finger moving exactly? Fortunately, that&#8217;s something I can answer in code, so I added that information to the screen <a href="#1">[1]</a>. Now, for a given frame, I can see both how far the finger is from the center of the square and how fast it&#8217;s going.</p>
<p><center><img src="http://gamesfromwithin.com/wp-content/uploads/2010/09/lag_test.jpg" alt="lag_test.jpg" border="0" width="496" height="516" /></center></p>
<p>The square is 100 pixels wide. When I move my finger at about 500 pixels per second, the center of my finger is on the edge of the square. That makes a rough 100 ms total delay from input until it&#8217;s rendered. That&#8217;s a whopping 6 full frames at 60 fps! </p>
<h3>What Can We Do About It</h3>
<p>As iOS developers, there isn&#8217;t much we can do. Make sure your loops are set up correctly to avoid an extra frame delay. Make sure you provide feedback as soon as you can and don&#8217;t delay it any longer than you have to. Other than that, there&#8217;s nothing much we can do.</p>
<p>I&#8217;ve been saying this for a while, but I&#8217;m a big fan of layers as long as you can get to the underlying layers when you need to. Here&#8217;s a perfect case where it would be fantastic if Apple gave us raw access to the touch matrix input. Apart from being able to process the input faster (because I know what kind of input to expect for the game), can you imagine the possibilities that would open up? Input wouldn&#8217;t be limited to touch events, and we could even sense how &#8220;hard&#8221; the user is pushing, or the shape of the push.</p>
<p>At the very least, it would be very useful if we had the option to allocate extra CPU cycles to input recognition. I&#8217;m not doing much in my game while this is going on, so I&#8217;d happily give the input recognition code 95% of the frame time if it means it can give me those events in half the time.</p>
<p>I&#8217;m hoping that in a not very far distant, iDevices come with multiple cores, and maybe one of those cores is dedicated to the OS and to do input recognition without affecting the game. Or maybe, since that&#8217;s such a specialized, data-intensive task, some custom hardware could do the job much faster.</p>
<p>Until then, we&#8217;ll just have to deal with massive input lag.</p>
<p><strong>How about you? Do you have some technique that can reduce the touch event lag?</strong></p>
<p><br/></p>
<p><a href="http://gamesfromwithin.com/wp-content/uploads/2010/09/LagTest.zip">LagTest source code</a>. Released under the MIT License, yadda, yadda, yadda&#8230;</p>
<p><br/></p>
<p><a name="1"></a>[1] I actually shrank the OpenGL view to make sure the label wasn&#8217;t on top if it because I was getting choppier input than usual. Even moving it there caused some choppiness. This is exactly what I saw last year  with OpenGL performance dropping when a label is updated every frame!</p>
<p><br/></p>
<p><i>This post is part of <a href="http://idevblogaday.com/">iDevBlogADay</a>, a group of indie iPhone development blogs featuring two posts per day. You can keep up with iDevBlogADay through the <a href="http://idevblogaday.com/">web site</a>, <a href="http://feeds.feedburner.com/idevblogaday">RSS feed</a>, or <a href="http://twitter.com/#search?q=%23idevblogaday">Twitter</a>.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/lag-the-bane-of-touch-screens/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Google App Engine As Back End For iPhone Apps</title>
		<link>http://gamesfromwithin.com/google-app-engine-as-back-end-for-iphone-apps</link>
		<comments>http://gamesfromwithin.com/google-app-engine-as-back-end-for-iphone-apps#comments</comments>
		<pubDate>Thu, 09 Sep 2010 19:59:04 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iDevBlogADay]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1145</guid>
		<description><![CDATA[As soon as a game involves servers, there&#8217;s no such a thing anymore as &#8220;ship and forget&#8221;. Flower Garden put this in evidence about a month ago when I started getting complaints from users that the Flower Shop kept going &#8230; <a href="http://gamesfromwithin.com/google-app-engine-as-back-end-for-iphone-apps">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As soon as a game involves servers, there&#8217;s no such a thing anymore as &#8220;ship and forget&#8221;. Flower Garden put this in evidence about a month ago when I started getting complaints from users that the Flower Shop kept going down. Sometimes they weren&#8217;t even getting the items they were purchasing! (fortunately they can always do a free re-download, but they don&#8217;t always know that).</p>
<p>Flower Garden was using a shared Dreamhost server to upload bouquets, host in-game news, and, most importantly, to serve the Flower Shop (which involves hosting the static shop files, redeeming promo codes, recording transactions, verifying receipts with Apple&#8217;s server, and delivering purchased content). All the Flower Shop functionality was implement in PHP and using a mySQL database. </p>
<p>After some stressful sorting through the logs, it looked like the server was running out of memory and killing PHP processes. Dreamhost&#8217;s technical support didn&#8217;t help much and just claimed that I was simply something that happened and they would be happy to sell me a virtual private server. I was surprised to hear it was using up a lot of memory, and certainly nothing I could see with the tools available to me showed that. I certainly hadn&#8217;t done any changes in a while and traffic was constant. Doing some Googling at the time brought up lots of other angry Dreamhost users in a similar situation, so I suspected server configuration problems.</p>
<p>Whatever the case, I couldn&#8217;t let it be that way and I had to fix it somehow. I briefly considered a virtual private server, or even a dedicated host in some highly <a href="http://www.slicehost.com/">recommended</a> <a href="http://www.linode.com/">providers</a>. But in the end, the simplicity, scalability, and affordability of the Google App Engine won me over.</p>
<p>Now that Flower Garden has been using the Google App Engine for several weeks, I still think it&#8217;s fantastic. I wish someone had whacked me on the head when I started writing server code and forced me to use it. Hopefully this post will be more pleasant than a hit to the head and will still have a similar (good) effect.</p>
<h3>Google App Engine Overview</h3>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/09/appengine_lowres.gif" alt="appengine_lowres.gif" border="0" width="142" height="109" />Even though I was pretty much completely new to the Google App Engine (I had looked into it briefly before the launch of Flower Garden but dismissed it because they couldn&#8217;t support the amount of email traffic I needed), it took me two days to port over everything. Actually flipping the switch from the old system to the new one took a while longer, but that required more courage than work. More on that later.</p>
<p>This is not a Google App Engine tutorial. Instead, it&#8217;s going to be an overview of what it can do and why you should consider it as a backend for your iPhone app instead of using a shared or even dedicated server.</p>
<p>The first shock (at least for me) when looking into the Google App Engine is that you can&#8217;t run PHP. You&#8217;re limited to Java or Python. It turns out Python is my go-to scripting language, so I was thrilled at the idea. PHP is fine, but Python is a whole class above.</p>
<p>Next, it took a bit of adjusting to the fact that the environment to run anything on the Google App Engine has to be carefully controlled. You need to create a configuration file indicating the entry points and their handlers. Fortunately, all of that is well covered in the <a href="http://code.google.com/appengine/docs/python/overview.html">extensive online documentation</a>. </p>
<p>This is what the Flower Garden config file looks like, indicating both static files and several execution entry points:</p>
<pre>
application: st-flowershop
version: 1
runtime: python
api_version: 1

handlers:
- url: /catalog
  static_dir: catalog

- url: /emailassets
  static_dir: emailassets

- url: /news
  static_dir: news

- url: /moregames
  static_dir: moregames

- url: /.*
  script: purchase.py
</pre>
<p>If you hit one of the URLs listed as static_dir, you get those files directly (like the <a href="http://st-flowershop.appspot.com/news/news.html">in-game news</a>). Anything else is handled by the Python script purchase.py. Google even provides the <a href="http://code.google.com/appengine/docs/python/tools/webapp/">webapp framework</a> that easily allows you to connect different parts of the script to handle different requests and easily get to the input parameters.</p>
<p>Once you&#8217;re past that and you have the requisite &#8220;Hello World&#8221; up and running, then it&#8217;s all fun and games.</p>
<p>One of the great features of the Google App Engine is that it comes with a fully-featured, local environment. This environment is installed automatically with the Google App Engine SDK, and there&#8217;s nothing to configure. It&#8217;s certainly nothing like setting up Apache + mySQL + PHP in your dev station! That way,  you can do all your work locally, and only update the servers when you&#8217;re confident everything is working. </p>
<p>Beyond this, the only other thing that is different from what you may be used to is the datastore. They provide a query language called <a href="http://code.google.com/appengine/docs/python/datastore/">GQL</a>, which is not exactly SQL, but it&#8217;s very similar. Close enough that I had no trouble porting over my very simple queries anyway.</p>
<p>Adding data to a data store couldn&#8217;t be simpler. For example, to add a promo code, I need the following class definition:</p>
<pre>
class PromoCode(db.Model):
	code = db.StringProperty()
	productid = db.StringProperty()
	amount = db.IntegerProperty(default=1)
	singleuse = db.BooleanProperty(default=True)
	enabled = db.BooleanProperty(default=True)
</pre>
<p>And then I can add it this way:</p>
<pre>
	promocode = PromoCode()
	# fill it up here
	promocode.put()
</pre>
<p>How do I check if a promocode is valid? I can use the SQL-like syntax, or something even simpler:</p>
<pre>
	q = PromoCode.all()
	q.filter("code =", code)
	return q.get()
</pre>
<p>Once you know that, you can go to town with your Python programs.</p>
<h3>Google App Engine Advantages</h3>
<p><b>Scalability</b><br />
This was the big reason that forced me to move away from Dreamhost. I have no way of testing how scalable it really is, but I&#8217;m going to take Google&#8217;s word for it. They know a tiny little bit about scalability. And besides, Flower Garden is nothing compared to other apps (it serves about 1.5 requests per second on average).</p>
<p>Since I don&#8217;t know how things are implemented under the hood in the Google App Engine, I don&#8217;t have a good feel for performance best practices. So I&#8217;m hoping that my very simple queries (add to the end of a table, or see if a record is present) are just fine. If not, I can do some tuning down the line (and I won&#8217;t have to wait for any approval to make the code go live!).</p>
<p><b>Local environment</b><br />
The local environment is simply great. It makes developing a pleasure. You can add any test data you want to the local datastore through a web interface without affecting the live server. Probably my favorite feature is the console: Since the server is running locally, you can print out any debug info in the server code and you can see it live as you perform some action. That saved me hours of debugging compared to doing it on a remote server with php!</p>
<p><b>Server synching</b><br />
In the past, I&#8217;ve synced my server scripts through ftp and I kept meaning to write an automated script to do that. In this case, Google provides a script (and a GUI tool) to do the actual synching with the servers, which is great. It even waits a few seconds until it can verify that the new version is live on the server.</p>
<p><b>Python</b><br />
I&#8217;m not a big Java fan (although I used it a bit way back in the day when it first came out), but I do love Python. For a program with some complexity like this, it&#8217;s definitely a much better choice than PHP.</p>
<p><b>Real-time stats</b><br />
The Google App Engine web console displays real-time stats of access to your site. You see it expressed in requests per second and you can visualize it in the past few hours, days, or even month. You also have access to all the logs, and you can filter by type of log message (debug, info, warning, error). </p>
<p><b>Price</b><br />
This is one category where the Google App Engine definitely shines. Every day you&#8217;re given a free quota of bandwidth, disk usage, and CPU usage. If you stay under that quota you don&#8217;t pay anything. If you go over, you pay per unit as you go (at very reasonable prices). You can even set a maximum cap on daily spending so you don&#8217;t encounter any nasty surprises at the end of the month.</p>
<p>So far, Flower Garden has been hovering right at the edge of the outgoing bandwidth free quota (the rest of the metrics it doesn&#8217;t even come close). So even if traffic were to double, expenses would be very reasonable.</p>
<h3>Development Tricks</h3>
<p>Along the way, I figured out a couple of interesting tricks that helped me during development.</p>
<p><b>Bypass the App store for testing</b><br />
For me, few things are more annoying than doing development in the actual device. Iteration is slow and stepping with the debugger is mostly impossible (seems to depend on the mood of the debugger that day). So I try to do the bulk of the development on the simulator and just test on the device when things are ready. </p>
<p>Unfortunately, the device can&#8217;t access the App Store, which makes testing all the server functionality dealing with the App Store painful. What I did was to add a define that, when present, the program bypasses the App Store but still functions as usual.</p>
<p><b>Local server</b><br />
During development, you want to be using your local server. In my case, I set it up so that Debug versions of the code access the local server, but Release and Distribution ones access the live one.</p>
<p>There is one problem: The Google App Engine server, by default, binds itself to localhost, not to the IP address of your network card. That meant I was able to hit it from the simulator just fine accessing http://localhost:8080, but not from the device. In order to access the development server from the device, I had to explicitly tell the server to bind itself to another address like this:</p>
<pre>dev_appserver.py --address 192.168.1.150 FlowerShop</pre>
<p>Now I can access the server at 192.168.1.150:8080 from both the simulator and any device.</p>
<p><b>Switching servers</b><br />
Porting the code took just a couple of days. Making the switch on the live server was a lot scarier though. I couldn&#8217;t wait for a new update to be released because that seems to take over a week these days, so I forwarded requests from the old server to the new one.</p>
<p>I did it one system every day, avoiding weekends which is when there&#8217;s the most traffic. News was easy, and so was the web view with more games. But I ran into a snag with promo codes and Flower Shop purchases. </p>
<p>Initially, I was just redirecting requests in .htaccess this way:</p>
<pre>
Redirect permanent /Shop/catalog http://st-flowershop.appspot.com/catalog
Redirect 301 /Shop/catalog http://st-flowershop.appspot.com/catalog
</pre>
<p>As I learned the hard way, POST variables aren&#8217;t preserved in a redirect of that kind (I guess to avoid state being changed in multiple servers). I tried a bunch of things, but in the end, I wrote a quick php script that gathered all POST variables and re-posted them to the new request. A bit ugly, but it did the trick:</p>
<pre>
&lt;?php
function PostRequest($url, $_data) {

    $data = array();
    while(list($n,$v) = each($_data)){
        $data[] = "$n=" . urlencode($v);
    }
    $data = implode('&#038;', $data);
    // format --> test1=a&#038;test2=b etc.

    $url = parse_url($url);
    if ($url['scheme'] != 'http') {
        die('Only HTTP request are supported !');
    }

    $host = $url['host'];
    $path = $url['path'];

    $fp = fsockopen($host, 80);

    fputs($fp, "POST $path HTTP/1.1\r\n");
    fputs($fp, "Host: $host\r\n");
    fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
    fputs($fp, "Content-length: ". strlen($data) ."\r\n");
    fputs($fp, "Connection: close\r\n\r\n");
    fputs($fp, $data);

    $result = '';
    while(!feof($fp)) {
        $result .= fgets($fp, 128);
    }
    fclose($fp);

    $result = explode("\r\n\r\n", $result, 2);
    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';
    return $content;
}

print PostRequest("http://st-flowershop.appspot.com/purchase", $_POST);
?&gt;
</pre>
<h3>Conclusion</h3>
<p>I hope this post is enough to at least make you interested in checking out the Google App Engine and help you get over a couple of the initial hurdles. I&#8217;ll definitely be using it in any future projects.</p>
<p><br/>
<p><i>This post is part of <a href="http://idevblogaday.com/">iDevBlogADay</a>, a group of indie iPhone development blogs featuring two posts per day. You can keep up with iDevBlogADay through the <a href="http://idevblogaday.com/">web site</a>, <a href="http://feeds.feedburner.com/idevblogaday">RSS feed</a>, or <a href="http://twitter.com/#search?q=%23idevblogaday">Twitter</a>.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/google-app-engine-as-back-end-for-iphone-apps/feed</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
		<item>
		<title>Prototyping: You&#8217;re (Probably) Doing It Wrong</title>
		<link>http://gamesfromwithin.com/prototyping-youre-probably-doing-it-wrong</link>
		<comments>http://gamesfromwithin.com/prototyping-youre-probably-doing-it-wrong#comments</comments>
		<pubDate>Thu, 12 Aug 2010 18:30:12 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iDevBlogADay]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1085</guid>
		<description><![CDATA[You&#8217;re not alone, I was also doing prototyping wrong until a few years ago. There are probably many different ways of prototyping games correctly, and maybe your way works great for you. In that case, a more accurate title for &#8230; <a href="http://gamesfromwithin.com/prototyping-youre-probably-doing-it-wrong">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>You&#8217;re not alone, I was also doing prototyping wrong until a few years ago. There are probably many different ways of prototyping games correctly, and maybe your way works great for you. In that case, a more accurate title for this post could have been &#8220;Prototyping: I Was Doing It Wrong&#8221;.</p>
<p>A good game prototype is something fast/cheap that allows you to answer a specific question about your game. The key points there are <em>fast/cheap</em> and <em>specific question</em>. It&#8217;s not a level of a game, it&#8217;s not a &#8220;vertical slice&#8221;, and it&#8217;s certainly not an engine for the game. </p>
<p><a href="http://chrishecker.com/Homepage">Chris Hecker</a> and <a href="http://www.slackworks.com/%7Ecog/">Chaim Gingold</a> gave one of the <a href="http://www.d6.com/users/checker/gdc06-AdvancedPrototyping.ppt">best presentations on the subject of rapid prototyping</a>. It was hugely influential for me, and it made me re-think the way I do prototypes. If you get a chance, find the audio for the presentation, it&#8217;s definitely worth it.</p>
<h3>Mistake #1: Going With The First Idea</h3>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/08/proto_2.jpg" alt="proto_2.jpg" border="0" width="200" height="302" />Every company I&#8217;ve ever worked at has done this mistake. The team hashes out a bunch of ideas, and somehow they pick one (or create it by committee). Maybe they&#8217;ll create a prototype to show something about the game, or maybe they&#8217;ll dive straight and start writing a design document and developing technology. If you&#8217;re lucky, or you have an extremely talented game director, the game that comes out of the other end might be fantastic. In most cases, it&#8217;s just a so-so idea and the team only realizes it when the first level comes together, years later, at around alpha time. At this point the choice is canning a project after spending millions of dollars, or patching it up to try to salvage something. Neither idea is particularly appealing.</p>
<p>Creating a prototype for a game you know you&#8217;ve already committed to is pointless. It&#8217;s nothing more than an exercise to keep management happy. Frankly, I even made that same mistake at Power of Two, when <a href="http://gamesfromwithin.com/prototyping-for-fun-and-profit">we prototyped the game idea we had in mind</a> and immediately moved on into pre-production (and yes, later we realized we had to change things to make it more interesting).</p>
<p>What I do now is to force myself to prototype several of my top ideas before committing to any one project. I have a page (actually, a <a href="http://trac.edgewall.org/">wiki</a> page) with every game idea or thought I have. That page has way over a hundred entries, and every so often I cull and reorganize it, bringing up the most promising ideas towards the top. Whenever I&#8217;m in prototyping mode, I start grabbing them from the top and prototype them.</p>
<p><img src="http://gamesfromwithin.com/wp-content/uploads/2010/08/proto_1.jpg" alt="proto_1.jpg" border="0" width="270" height="180" style="float:left;" />With a good prototype it&#8217;s easy to see if an idea is worthwhile. If it&#8217;s not, I discard it and move on to the next one. If it has potential but it&#8217;s just so-so, I either choose to continue just a bit longer (to ask another, better question) or I shelve it back in the list of potential game ideas. Maybe at some later time, things might click in or I might have a new inspiration and the game idea might become a lot stronger.</p>
<p>Also, often times, after doing one prototype and deciding against it, a new idea will come up. Usually a variation on the original prototype or something directly sparked from it, so I&#8217;ll find myself jumping to that idea instead of one of the ones I had saved in my list.</p>
<p>Eventually, one idea will click and you&#8217;ll know that&#8217;s &#8220;the one&#8221;. If you&#8217;re lucky (or unlucky) enough to have that happen with the first one you try, I still recommend doing a few more prototypes. If nothing else, you might be prototyping future projects, so it&#8217;s certainly not wasted time. For my current project, I went through eight prototypes before finding &#8220;the one&#8221; (several of them were a collaboration with <a href="http://twitter.com/mysterycoconut">Miguel</a>). Eight to ten prototypes per project is roughly what I&#8217;m hearing from other indies with this approach.</p>
<h3>Mistake #2: Not having a good question</h3>
<p>A good prototype attempts to answer a question about the game. But not all questions are created equal. First of all, a question needs to be relevant and crucial to the project. &#8220;Can I have a pretty settings screen?&#8221; isn&#8217;t a particularly difficult question to answer, so it doesn&#8217;t deserve its own prototype. &#8220;Can I control little planes by drawing smooth lines on the screen?&#8221; is a much bigger unknown (before Flight Control anyway, today you can just download the game and immediately answer yes).</p>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/08/proto_3.jpg" alt="proto_3.jpg" border="0" width="270" height="180" />Also, a good question is concise and can be answered in a fairly unambiguous way. &#8220;Is this game awesome?&#8221; isn&#8217;t a good question because &#8220;awesome&#8221; is very vague. A better question might be &#8220;Can I come up with a tilt control scheme that is responsive and feels good?&#8221;. Feels good is a very subjective question, but it&#8217;s concrete enough that people can answer that pretty easily after playing your prototype for a bit.</p>
<p>Even though most questions are about game design, they can also be about any other aspect of the game. Maybe you&#8217;re doing something tricky with technology and you want to make sure it&#8217;s feasible. If not, there&#8217;s no point in even starting. It&#8217;s more uncommon to think of prototyping art, but it&#8217;s also a very valid approach: &#8220;Will this art style allow foreground objects to stand out enough?&#8221; &#8220;Will the lighting approach allow the player to see important features in enough detail?&#8221;. Often you can do these art &#8220;prototypes&#8221; directly in Photoshop or a 3D modeling package.</p>
<p>In the case of Flower Garden, the main unknown was the technology behind the procedural flowers. So I created a prototype to answer the question &#8220;Can I create compelling procedural flowers that grow in real-time and the user can interact with them?&#8221;. The prototype had several parts to answer that question: the geometry generation, the animation, the simulation, and the rendering. There isn&#8217;t anything else particularly ground-breaking in the rest of the Flower Garden code, so as soon as I was able to answer &#8220;yes&#8221; to that question, I green-lighted the project and started production on it.</p>
<p>For larger projects, you might have several major, outstanding questions, so you&#8217;ll need to do multiple prototypes. Unless they&#8217;re very closely related, I find it easier to keep them separate instead of building on top of the same prototype.</p>
<p>Without a good question, it&#8217;s too easy for a prototype to go on for a long time. You feel you&#8217;re making progress because new things are added, but you have no real sense of when to stop or when it&#8217;s done. You really have to focus on the question, ignore everything else, and be merciless in your approach.</p>
<h3>Mistake #3: Taking too long</h3>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/08/proto_41.jpg" alt="proto_4.jpg" border="0" width="271" height="180" />One of the key concepts in the definition of a prototype was that it has to be fast/cheap (which are two sides of the same coin). What&#8217;s fast enough? It depends on the length of the project itself. It&#8217;s not the same thing to do a prototype for a two-month iPhone game, than for a three-year console game. Also, a larger, more expensive project probably has more complex questions to answer with a prototype than a simple iPhone game.</p>
<p>In my case, I shoot for one-day prototypes. If you already have the tech to create games with, one day allows you to focus 100% on answering the question. By the end of the day, or even before, I have a pretty good idea how the game is going to work out. My shortest prototype ever was a 2-hour one. I thought it was going to be longer, but I managed to complete everything to answer the question in two hours (for the record, I didn&#8217;t can that idea, but I shelved it for a possible future project).</p>
<p><a href="http://iphonegamejam.com/index.php?title=Main_Page">Game</a> <a href="http://indiegamejam.com/">jams</a> are a great way to get over the mental block of doing quick prototypes. There you are focused on making the game on a very short time, surrounded by people trying to do the same thing. I can&#8217;t think of a more fun way to prototype than that!</p>
<p>Also, think beyond programming. Is there a faster way you can answer the prototype question? Maybe you can use the modding capabilities of an existing game, or even do a mockup with paper moving pieces around. Don&#8217;t fall in the trap of thinking you have to code a prototype if something simpler and faster will do.</p>
<p>If you find that a day is not enough, take a step back and really ask yourself why you need more time. Were you getting side-tracked on things that were irrelevant to the prototype (menus, tech, art, etc)? Are you asking a question that the prototype can&#8217;t answer? Do you have the game idea clearly defined in your head?</p>
<h3>Mistake #4: Building a system, not a game</h3>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/08/proto_5.jpg" alt="proto_5.jpg" border="0" width="270" height="180" />When you&#8217;re making a prototype, if you ever find yourself working on something that isn&#8217;t directly moving your forward, stop right there. As programmers, we have a tendency to try to generalize our code, and make it elegant and be able to handle every situation. We find that an itch terribly hard not scratch, but we need to learn how. It took me many years to realize that it&#8217;s not about the code, it&#8217;s about the game you ship in the end.</p>
<p>Don&#8217;t write an elegant game component system, skip the editor completely and hardwire the state in code, avoid the data-driven, self-parsing, XML craziness, and just code the damned thing.</p>
<p>When you&#8217;re prototyping, it&#8217;s a race to answer the main prototype question. Everything is expendable. Don&#8217;t even worry about memory leaks, hardwired numbers, or how you load resources. Just get stuff on the screen as quickly as you can.</p>
<p>And don&#8217;t ever, ever, use the argument &#8220;if we take some extra time and do this the <em>right</em> way, we can reuse it in the game&#8221;. EVER.</p>
<p><br/></p>
<p><i>This post is part of <a href="http://idevblogaday.com/">iDevBlogADay</a>, a group of indie iPhone development blogs featuring two posts per day. You can keep up with iDevBlogADay through the <a href="http://idevblogaday.com/">web site</a>, <a href="http://feeds.feedburner.com/idevblogaday">RSS feed</a>, or <a href="http://twitter.com/#search?q=%23idevblogaday">Twitter</a>.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/prototyping-youre-probably-doing-it-wrong/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Remote Game Editing</title>
		<link>http://gamesfromwithin.com/remote-game-editing</link>
		<comments>http://gamesfromwithin.com/remote-game-editing#comments</comments>
		<pubDate>Thu, 22 Jul 2010 18:00:22 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Game tech]]></category>
		<category><![CDATA[iDevBlogADay]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[flower garden]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=1053</guid>
		<description><![CDATA[I&#8217;ve long been a fan of minimal game runtimes. Anything that can be done offline or in a separate tool, should be out of the runtime. That leaves the game architecture and code very lean and simple. One of the &#8230; <a href="http://gamesfromwithin.com/remote-game-editing">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve long been a fan of minimal game runtimes. Anything that can be done offline or in a separate tool, should be out of the runtime. That leaves the game architecture and code very lean and <a href="http://gamesfromwithin.com/simple-is-beautiful">simple</a>.</p>
<p>One of the things you potentially give up by keeping the game runtime to a minimum is an <a href="http://www.unrealtechnology.com/features.php?ref=editor">editor built in the game itself</a>. But that&#8217;s one of those things that sounds a lot better than it really is. From a technical point of view, having an editor in the game usually complicates the code a huge amount. All of a sudden you need to deal with objects being created and destroyed randomly (instead of through clearly defined events in the game), and you have to deal with all sorts of crazy inputs and configurations.</p>
<p>The worse part though, is having to implement some sort of GUI editing system in every platform. Creating the GUI to run on top of the game is not easy, requiring that you create custom GUI code or try to use some of the OpenGL/DirectX libraries available. And even then, a complex in-game GUI might not be a big deal on a PC, but wait and try to use that interface on a PS3 or iPhone. After all, making games is already complicated and time-consuming enough to waste more time reinventing the widget wheel.</p>
<p>Remote game editing manages to keep a minimal runtime and allow you to quickly create native GUIs that run on a PC. It&#8217;s the best of both worlds, and although it&#8217;s not quite a perfect solution, it&#8217;s the best approach I know.</p>
<h3>Debug Server</h3>
<p><a href="http://twitter.com/mysterycoconut">Miguel Ángel Friginal</a> <a href="http://mysterycoconut.com/blog/2010/07/tweak-away/">already covered the basics of the debug server</a>, so I&#8217;m not going to get in details there.</p>
<p>The idea is that you run a very simple socket server on the game, listening in a particular port. This server implements the basic <a href="http://www.faqs.org/rfcs/rfc854.html">telnet protocol</a>, which pretty much means that it&#8217;s a line-based, plain-text communication.</p>
<p>The main difference between my debug server and Miguel&#8217;s (other than mine is written in cross-platform C/C++ instead of ObjC), is that I&#8217;m not using Lua to execute commands. Using Lua for that purpose is a pretty great idea, but goes against the philosophy of keeping the runtime as lean and mean as possible.</p>
<p>Instead, I register variables with the server by hand. For each variable, I specify its memory address, it&#8217;s type, any restrictions (such as minimum and maximum values), and a &#8220;pretty name&#8221; to display in the client. Sounds like a lot of work, but it&#8217;s just one line with the help of a template:</p>
<pre>
registry.Add(Tweak(&#038;plantOptions.renderGloss, "render/gloss", "Render gloss"));
registry.Add(Tweak(&#038;BouquetParams::FovY, "bouquet/fov", "FOV", Pi/32, Pi/3))
</pre>
<p>And yes, if I were to implement this today, I would probably get rid of the templates and make it all explicit instead (ah, the follies of youth <img src='http://gamesfromwithin.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<pre>
TweakUtils::AddBool(registry, &#038;plantOptions.renderGloss, "render/gloss", "Render gloss");
TweakUtils::AddFloat(registry, &#038;BouquetParams::FovY, "bouquet/fov", "FOV", Pi/32, Pi/3);
</pre>
<p>The debug server itself responds to three simple commands:</p>
<ul>
<li><strong>list</strong>. Lists all the variables registered in the server.</li>
<li><strong>set varname value</strong>. Sets a value.</li>
<li><strong>print varname</strong>. Gets the value for that variable.</li>
</ul>
<p>For example, whenever the server receives a set command, it parses the value, verifies that it&#8217;s within the acceptable range, and applies it to the variable at the given memory location.</p>
<h3>Telnet Clients</h3>
<p><img class="alignright size-full wp-image-673" src="http://gamesfromwithin.com/wp-content/uploads/2010/07/telnet.png" alt="telnet.png" border="0" width="236" height="174" />Because we used the standard telnet protocol, we can start playing with it right away. Launch the game, telnet into the right port, and you can start typing away.</p>
<p>However, most telnet clients leave much to be desired for this. They all rely on the history and cursor manipulation being handled by the shell they assume you&#8217;re connected to. Here we aren&#8217;t connected to much of anything, but I&#8217;d like to be able to push up arrow and get my last command, and be able to move to the beginning of the line or the previous word like I would do in any text editor. The easiest solution I found for that was to use a telnet client prepared for that kind of thing: A MUD client! Just about any will do, but one that works well for me is <a href="http://www.riverdark.net/atlantis/">Atlantis</a>.</p>
<p>So far, we&#8217;ve implemented the equivalent of a FPS console, but working remotely. And because the code is fully portable, our game can be in just about any platform and we can always access it from our PC. Not just that, but we can even open multiple simultaneous connections to various development devices if you need to run them all at once.</p>
<h3>Custom Clients</h3>
<p>Game parameter tweaking is something that is OK through a text-based console, but really comes into its own when you add a GUI. That&#8217;s exactly what we did at <a href="http://gamesfromwithin.com/tag/power-of-two">Power of Two Games</a>. We created a generic GUI tool (based on WinForms since we were on Windows at the time), that would connect to the server, ask for a list of variables, and generate a GUI on the fly to represent those variables. Since we knew type and name of each variable, it was really easy to construct the GUI elements on the fly: A slider with a text field for floats and ints, a checkbox for bools, four text fields for vectors, and even a color picker for variables of the type color.</p>
<p>It worked beautifully, and adjusting different values by moving sliders around was fantastic. We quickly ran into two problems through.</p>
<p>The first one is that we added so many different tweaks to the game, that it quickly became unmanageable to find each one we wanted to tweak. So, in the spirit of keeping things as simple as possible (and pushing the complexity onto the client), we decided that the / symbol in a name would separate group name and variable name. That way we could group all related variables together and make everything usable again.</p>
<p>The second problem was realizing that some variables were changing on the runtime without us knowing it on the client. That created weird situations when moving sliders around. We decided that any time a registed variable changes on the server, it should notify any connected clients. That worked fine, but, as you can imagine, it became prohibitively expensive very quickly. To get around that, we added a fourth command: <strong>monitor varname</strong>. This way clients need to explicitly register themselves to receive notifications whenever a variable changes, and the GUI client only did it for the variables currently displayed on the screen.</p>
<p><center><img src="http://gamesfromwithin.com/wp-content/uploads/2010/07/tweaker.png" alt="tweaker.png" border="0" width="542" height="591" /></center></p>
<p>During this process, it was extremely useful to be able to display a log console to see what kind of traffic there was going back and forth. It helped me track down a few instances of bugs where changing a variable in the client would update it in the server, sending an update back to the client, which would send it again back to the server, getting stuck in an infinite loop.</p>
<p>You don&#8217;t need to stop at a totally generic tool like this either. You could create a more custom tool, like a level editor, that still communicates with the runtime through this channel.</p>
<h3>Flower Garden Example</h3>
<p>For Flower Garden, I knew I was going to need a lot of knobs to tweak all those plant DNA parameters, so I initially looked into more traditional GUI libraries that worked on OpenGL. The sad truth is that they all fell way short, even for development purposes. So I decided to grab what I had at hand: My trusty tweaking system from Power of Two Games.</p>
<p>I&#8217;m glad I did. It saved a lot of time and scaled pretty well to deal with the hundreds of parameters in an individual flower, as well as the miscellaneous tweaks for the game itself (rendering settings, infinite fertilizer, fast-forwarding time, etc).</p>
<p>Unfortunately, there was one very annoying thing: The tweaker GUI was written in .Net. Sure, it would take me a couple of days to re-write it in Cocoa (faster if I actually knew any Cocoa), but as an indie, I never feel I can take two days to do something tangential like that. So instead, I just launched it from VMWare Fusion running Windows XP and&#8230; it worked. Amazingly enough, I&#8217;m able to connect from the tweaker running in VMWare Fusion to the iPhone running in the simulator. Kind of mind boggling when you stop and think about it. It also connects directly to the iPhone hardware without a problem.</p>
<p>VMWare Fusion uses up a lot of memory, so I briefly looked into running the tweaker client in Mono. Unfortunately Mono for the Mac didn&#8217;t seem mature enough to handle it, and not only was the rendering of the GUI not refreshing correctly, but events were triggered in a slightly different order than in Windows, causing even more chaos with the variable updates.</p>
<p>Here&#8217;s a time-lapse video of the creation of a Flower Garden seed from the tweaker:</p>
<p><object width="640" height="505"><param name="movie" value="http://www.youtube.com/v/j_j9nIQO_B8&amp;hl=en_US&amp;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/j_j9nIQO_B8&amp;hl=en_US&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="505"></embed></object></p>
<h3>Drawbacks</h3>
<p>As I mentioned earlier, I love this system and it&#8217;s better than anything else I&#8217;ve tried, but it&#8217;s not without its share of problems.</p>
<p>Tweaking data is great, but once you find that set of values that balances the level to perfection&#8230; then what? You write those numbers down and enter them in code or in the level data file? That gets old fast. Ideally you want a way to automatically write those values back. That&#8217;s easy if the tool itself is the editor, but if it&#8217;s just a generic tweaker, it&#8217;s a bit more difficult.</p>
<p>One thing that helped was adding a Save/Load feature to the tweaker GUI. It would simply write out a large text-based file with all the variables and their current values. Whenever you load one of those, it would attempt to apply those same values to the current registered variables. In the end, I ended up making the Flower Garden offline seed file format match with what the tweaker saved out, so that process went pretty smoothly.</p>
<p>Another problem is if you want lots of real-time (or close to real time) updates from the server. For example, you might want to monitor a bunch of data points and plot them on the client (fps, memory usage, number of collisions per frame, etc). Since those values change every frame, it can quickly overwhelm the simple text channel. For those cases, I created side binary socket channels that can simply send real-time data without any overhead.</p>
<p>Finally, the last drawback is that this tweaking system makes editing variables very easy, but calling functions is not quite as simple. For the most part, I&#8217;ve learned to live without function calls, but sometimes you really want to do it. You can extend the server to register function pointers and map those to buttons in the client GUI, but that will only work for functions without any parameters. What if you wanted to call any arbitrary function? At that point you might be better off integrating Lua in your server.</p>
<h3>Future Directions</h3>
<p>This is a topic I&#8217;ve been interested in for a long time, but the current implementation of the system I&#8217;m using was written 3-4 years ago. As you all know by now, <a href="http://gamesfromwithin.com/the-always-evolving-coding-style">my coding style and programming philosophy changes quite a bit over time</a>. If I were to implement a system like this today, I would do it quite differently.</p>
<p>For all I said about keeping the server lean and minimal, it could be even more minimal. Right now the server is receiving text commands, parsing them, validating them, and interpreting them. Instead, I would push all that work on the client, and all the server would receive would be a memory address, and some data to blast at that location. All of that information would be sent in binary (not text) format over a socket channel, so it would be much more efficient too. The only drawback is that we would lose the ability to connect with a simple telnet client, but it would probably be worth it in the long run.</p>
<p><br/></p>
<p><i>This post is part of <a href="http://idevblogaday.com/">iDevBlogADay</a>, a group of indie iPhone development blogs featuring two posts per day. You can keep up with iDevBlogADay through the <a href="http://idevblogaday.com/">web site</a>, <a href="http://feeds.feedburner.com/idevblogaday">RSS feed</a>, or <a href="http://twitter.com/#search?q=%23idevblogaday">Twitter</a>.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/remote-game-editing/feed</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Managing Data Relationships</title>
		<link>http://gamesfromwithin.com/managing-data-relationships</link>
		<comments>http://gamesfromwithin.com/managing-data-relationships#comments</comments>
		<pubDate>Sun, 27 Jun 2010 21:54:49 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[Data-oriented design]]></category>
		<category><![CDATA[Game tech]]></category>
		<category><![CDATA[game developer magazine]]></category>
		<category><![CDATA[inner product]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=942</guid>
		<description><![CDATA[I&#8217;ve been meaning to put up the rest of the Inner Product columns I wrote for Game Developer Magazine, but I wasn&#8217;t finding the time. With all the recent discussion on data-oriented design, I figured it was time to dust &#8230; <a href="http://gamesfromwithin.com/managing-data-relationships">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>I&#8217;ve been meaning to put up the rest of the <a href="http://gamesfromwithin.com/tag/inner-product">Inner Product columns</a> I wrote for <a href="http://gdmag.com">Game Developer Magazine</a>, but I wasn&#8217;t finding the time. With all the <a href="http://gamesfromwithin.com/the-always-evolving-coding-style">recent discussion on data-oriented design</a>, I figured it was time to dust some of them off.</p>
<p>This was one of the first columns I wrote. At first glance it might seem a completely introductory topic, not worth spending that much time on it. After all, all experience programmers know about pointers and indices, right? True, but I don&#8217;t think all programmers really take the time to think about the advantages and disadvantages of each approach, and how it affects architecture decisions, data organization, and memory traversal.</p>
<p>It should provide a good background for this coming Thursday&#8217;s <a href="http://twitter.com/#search?q=%23idevblogaday">#iDevBlogADay</a> post on how to deal with heterogeneous objects in a data-oriented way.</em></p>
<p><br/></p>
<p>From a 10,000-Foot view, all video games are just a sequence of bytes. Those bytes can be divided into code and data. Code is executed by the hardware and it performs operations on the data. This code is generated by the compiler and linker from the source code in our favorite computer language. Data is just about everything else. <a href="#1">[1]</a></p>
<p>As programmers, we’re obsessed with code: beautiful algorithms, clean logic, and efficient execution. We spend most of our time thinking about it and make most decisions based on a code-centric view of the game.</p>
<p>Modern hardware architectures have turned things around. A data-centric approach can make much better use of hardware resources, and can produce code that is much simpler to implement, easier to test, and easier to understand. In the next few months, we’ll be looking at different aspects of game data and how everything affects the game. This month we start by looking at how to manage data relationships.</p>
<h2>Data Relationships</h2>
<p>Data is everything that is not code: meshes and textures, animations and skeletons, game entities and pathfinding networks, sounds and text, cut scene descriptions and dialog trees. Our lives would be made simpler if data simply lived in memory, each bit totally isolated from the rest, but that’s not the case. In a game, just about all the data is intertwined in some way. A model refers to the meshes it contains, a character needs to know about its skeleton and its animations, and a special effect points to textures and sounds.</p>
<p>How are those relationships between different parts of data described? There are many approaches we can use, each with its own set of advantages and drawbacks. There isn’t a one-size-fits-all solution. What’s important is choosing the right tool for the job.</p>
<h2>Pointing The Way</h2>
<p>In C++, regular pointers (as opposed to “smart pointers” which we’ll discuss later on) are the easiest and most straightforward way to refer to other data. Following a pointer is a very fast operation, and pointers are strongly typed, so it’s always clear what type of data they’re pointing to.</p>
<p>However, they have their share of shortcomings. The biggest drawback is that a pointer is just the memory address where the data happens to be located. We often have no control over that location, so pointer values usually change from run to run. This means if we attempt to save a game checkpoint which contains a pointer to other parts of the data, the pointer value will be incorrect when we restore it.</p>
<p>Pointers represent a many-to-one relationship. You can only follow a pointer one way, and it is possible to have many pointers pointing to the same piece of data (for example, many models pointing to the same texture). All of this means that it is not easy to relocate a piece of data that is referred to by pointers. Unless we do some extra bookkeeping, we have no way of knowing what pointers are pointing to the data we want to relocate. And if we move or delete that data, all those pointers won’t just be invalid, they’ll be <i>dangling pointers</i>. They will point to a place in memory that contains something else, but the program will still think it has the original data in it, causing horrible bugs that are no fun to debug.</p>
<p>One last drawback of pointers is that even though they’re easy to use, somewhere, somehow, they need to be set. Because the actual memory location addresses change from run to run, they can’t be computed offline as part of the data build. So we need to have some extra step in the runtime to set the pointers after loading the data so the code can use them. This is usually done either by explicit creation and linking of objects at runtime, by using other methods of identifying data, such as resource UIDs created from hashes, or through pointer fixup tables converting data offsets into real memory addresses. All of it adds some work and complexity to using pointers.</p>
<p>Given those characteristics, pointers are a good fit to model relationships to data that is never deleted or relocated, from data that does not need to be serialized. For example, a character loaded from disk can safely contain pointers to its meshes, skeletons, and animations if we know we’re never going to be moving them around.</p>
<h2>Indexing</h2>
<p>One way to get around the limitation of not being able to save and restore pointer values is to use offsets into a block of data. The problem with plain offsets is that the memory location pointed to by the offset then needs to be cast to the correct data type, which is cumbersome and prone to error.</p>
<p>The more common approach is to use indices into an array of data. Indices, in addition to being safe to save and restore, have the same advantage as pointers in that they’re very fast, with no extra indirections or possible cache misses.</p>
<p>Unfortunately, they still suffer from the same problem as pointers of being strictly a many-to-one relationship and making it difficult to relocate or delete the data pointed to by the index. Additionally, arrays can only be used to store data of the same type (or different types but of the same size with some extra trickery on our part), which might be too restrictive for some uses.</p>
<p>A good use of indices into an array are particle system descriptions. The game can create instances of particle systems by referring to their description by index into that array. On the other hand, the particle system instances themselves would not be a good candidate to refer to with indices because their lifetimes vary considerably and they will be constantly created and destroyed.</p>
<p>It’s tempting to try and extend this approach to holding pointers in the array instead of the actual data values. That way, we would be able to deal with different types of data. Unfortunately, storing pointers means that we have to go through an extra indirection to reach our data, which incurs a small performance hit. Although this performance hit is something that we&#8217;re going to have to live with for any system that allows us to relocate data, the important thing is to keep the performance hit as small as possible.</p>
<p>An even bigger problem is that, if the data is truly heterogeneous, we still need to cast it to the correct type before we use it. Unless all data referred to by the pointers inherits from a common base class that we can use to query for its derived type, we have no easy way to find out what type the data really is.<br />
On the positive side, now that we’ve added an indirection (index to pointer, pointer to data), we could relocate the data, update the pointer in the array, and all the indices would still be valid. We could even delete the data and null the pointer out to indicate it is gone. Unfortunately, what we can’t do is reuse a slot in the array since we don’t know if there’s any data out there using that particular index still referring to the old data.</p>
<p>Because of these drawbacks, indices into an array of pointers is usually not an effective way to keep references to data. It’s usually better to stick with indices into an array of data, or extend the idea a bit further into a handle system, which is much safer and more versatile.</p>
<h2>Handle-Ing The Problem</h2>
<p>Handles are small units of data (32 bits typically) that uniquely identify some other part of data. Unlike pointers, however, handles can be safely serialized and remain valid after they’re restored. They also have the advantages of being updatable to refer to data that has been relocated or deleted, and can be implemented with minimal performance overhead.</p>
<p>The handle is used as a key into a handle manager, which associates handles with their data. The simplest possible implementation of a handle manager is a list of handle-pointer pairs and every lookup simply traverses the list looking for the handle. This would work but it’s clearly very inefficient. Even sorting the handles and doing a binary search is slow and we can do much better than that.</p>
<p><a href="http://gamesfromwithin.com/wp-content/uploads/2010/06/HandleManager.zip">Here&#8217;s an efficient implementation of a handle manager</a> (released under the usual <a href="http://www.opensource.org/licenses/mit-license.php">MIT license</a>, so go to town with it). The handle manager is implemented as an array of pointers, and handles are indices into that array. However, to get around the drawbacks of plain indices, handles are enhanced in a couple of ways.</p>
<p>In order to make handles more useful than pointers, we’re going to use up different bits for different purposes. We have a full 32 bits to play with, so this is how we’re going to carve them out:</p>
<p><center><img src="http://gamesfromwithin.com/wp-content/uploads/2010/06/Handle.png" alt="Handle.png" border="0" width="492" height="104" /></center></p>
<ul>
<li><strong>The index field</strong>. These bits will make up the actual index into the handle manager, so going from a handle to the pointer is a very fast operation. We should make this field as large as we need to, depending on how many handles we plan on having active at once. 14 bits give us over 16,000 handles, which seems plenty for most applications. But if you really need more, you can always use up a couple more bits and get up to 65,000 handles.</li>
<li><strong>The counter field</strong>. This is the key to making this type of handle implementation work. We want to make sure we can delete handles and reuse their indices when we need to. But if some part of the game is holding on to a handle that gets deleted—and eventually that slot gets reused with a new handle—how can we detect that the old handle is invalid? The counter field is the answer. This field contains a number that goes up every time the index slot is reused. Whenever the handle manager tries to convert a handle into a pointer, it first checks that the counter field matches with the stored entry. Otherwise, it knows the handle is expired and returns null.
<li><strong>The type field</strong>. This field indicates what type of data the pointer is pointing to. There are usually not that many different data types in the same handle manager, so 6–8 bits are usually enough. If you’re storing homogeneous data, or all your data inherits from a common base class, then you might not need a type field at all.</li>
</ul>
<pre>
struct Handle
{
    Handle() : m_index(0), m_counter(0), m_type(0)
    {}

    Handle(uint32 index, uint32 counter, uint32 type)
        : m_index(index), m_counter(counter), m_type(type)
    {}

    inline operator uint32() const;

    uint32 m_index : 12;
    uint32 m_counter : 15;
    uint32 m_type : 5;
};

Handle::operator uint32() const
{
    return m_type << 27 | m_counter << 12 | m_index;
}
</pre>
<p>The workings of the handle manager itself are pretty simple. It contains an array of HandleEntry types, and  each HandleEntry has a pointer to the data and a few other bookkeeping fields: freelist indices for efficient addition to the array, the counter field corresponding to each entry, and some flags indicating whether an entry is in use or it’s the end of the freelist.</p>
<pre>
struct HandleEntry
{
	HandleEntry();
	explicit HandleEntry(uint32 nextFreeIndex);

	uint32 m_nextFreeIndex : 12;
	uint32 m_counter : 15;
	uint32 m_active : 1;
	uint32 m_endOfList : 1;
	void* m_entry;
};
</pre>
<p>Accessing data from a handle is just a matter of getting the index from the handle, verifying that the counters in the handle and the handle manager entry are the same, and accessing the pointer. Just one level of indirection and very fast performance.</p>
<p>We can also easily relocate or invalidate existing handles just by updating the entry in the handle manager to point to a new location or to flag it as removed.</p>
<p>Handles are the perfect reference to data that can change locations or even be removed, from data that needs to be serialized. Game entities are usually very dynamic, and are created and destroyed frequently (such as enemies spawning and being destroyed, or projectiles). So any references to game entities would be a good fit for handles, especially if this reference is held from another game entity and its state needs to be saved and restored. Examples of these types of relationships are the object a player is currently holding, or the target an enemy AI has locked onto.</p>
<h2>Getting Smarter</h2>
<p>The term smart pointers encompasses many different classes that give pointer-like syntax to reference data, but offer some extra features on top of “raw” pointers.</p>
<p>A common type of smart pointer deals with object lifetime. Smart pointers keep track of how many references there are to a particular piece of data, and free it when nobody is using it. For the runtime of games, I prefer to have very explicit object lifetime management, so I’m not a big fan of this kind of pointers. They can be of great help in development for tools written in C++ though.</p>
<p>Another kind of smart pointers insert an indirection between the data holding the pointer and the data being pointed. This allows data to be relocated, like we could do with handles. However, implementations of these pointers are often non- serializable, so they can be quite limiting.</p>
<p>If you consider using smart pointers from some of the popular libraries (STL, Boost) in your game, you should be very careful about the impact they can have on your build times. Including a single header file from one of those libraries will often pull in numerous other header files. Additionally, smart pointers are often templated, so the compiler will do some extra work generating code for each data type you instantiated templates on. All in all, templated smart pointers can have a significant impact in build times unless they are managed very carefully.</p>
<p>It’s possible to implement a smart pointer that wraps handles, provides a syntax like a regular pointer, and it still consists of a handle underneath, which can be serialized without any problem. But is the extra complexity of that layer worth the syntax benefits it provides? It will depend on your team and what you’re used to, but it’s always an option if the team is more comfortable dealing with pointers instead of handles.</p>
<h2>Conclusion</h2>
<p>There are many different approaches to expressing data relationships. It’s important to remember that different data types are better suited to some approaches than others. Pick the right method for your data and make sure it’s clear which one you’re using.</p>
<p>In the next few months, we’ll continue talking about data, and maybe even convince you that putting some love into your data can pay off big time with your code and the game as a whole.</p>
<p><br/></p>
<p><em>This article was originally printed in the September 2008 issue of <a href="http://gdmag.com">Game Developer</a>.<br />
</em></p>
<p><br/></p>
<p><a name="1"></a>[1] I'm not too happy about the strong distinction I was making between code and data. Really, data is any byte in memory, and that includes code. Most of the time programs are going to be managing references to non-code data, but sometimes to other code as well: function pointers, compiled shaders, compiled scripts, etc. So just ignore that distinction and think of data in a more generic way.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/managing-data-relationships/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Great Presentation on Data-Oriented Design</title>
		<link>http://gamesfromwithin.com/great-presentation-on-data-oriented-design</link>
		<comments>http://gamesfromwithin.com/great-presentation-on-data-oriented-design#comments</comments>
		<pubDate>Sun, 20 Dec 2009 22:07:56 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Data-oriented design]]></category>
		<category><![CDATA[Game tech]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=764</guid>
		<description><![CDATA[A few days ago, Tony Albrecht posted the slides of his presentation titled &#8220;Pitfalls of Object-Oriented Design&#8221; [1]. Even though the title is really broad and could easily be misinterpreted, it&#8217;s not just a general bash on OOD. Instead, it&#8217;s &#8230; <a href="http://gamesfromwithin.com/great-presentation-on-data-oriented-design">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-773" title="Memory CPU gap" src="http://gamesfromwithin.com/wp-content/uploads/2009/12/mem_cpu_gap.jpg" alt="Memory CPU gap" width="300" height="164" />A few days ago, <a href="http://twitter.com/TonyAlbrecht">Tony Albrecht</a> posted the slides of his presentation titled <a href="http://research.scee.net/files/presentations/gcapaustralia09/Pitfalls_of_Object_Oriented_Programming_GCAP_09.pdf">&#8220;Pitfalls of Object-Oriented Design&#8221;</a> <a href="#1">[1]</a>. Even though the title is really broad and could easily be <a href="http://www.reddit.com/r/programming/comments/ag43j/pitfalls_of_object_oriented_programming_pdf/">misinterpreted</a>, it&#8217;s not just a general bash on OOD. Instead, it&#8217;s very much focused on how object-oriented design is not a good match for high-performance apps (games) on modern hardware architectures with slow memory access and deep memory hierarchies. His proposed solution: Data-oriented design. Spot on!</p>
<p>If you haven&#8217;t seen the presentation, go download it right now. It&#8217;s really well put together and he has some great detailed examples on how caches are affected with traditional object-oriented design vs. a more data-oriented approach.</p>
<p><br/></p>
<p><a name="1"></a>[1] Thanks to <a href="http://twitter.com/ChristerEricson/status/6783005918">Christer Ericson</a> for pointing that out.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/great-presentation-on-data-oriented-design/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Data-Oriented Design (Or Why You Might Be Shooting Yourself in The Foot With OOP)</title>
		<link>http://gamesfromwithin.com/data-oriented-design</link>
		<comments>http://gamesfromwithin.com/data-oriented-design#comments</comments>
		<pubDate>Fri, 04 Dec 2009 19:40:20 +0000</pubDate>
		<dc:creator>Noel</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Data-oriented design]]></category>
		<category><![CDATA[Game tech]]></category>
		<category><![CDATA[game developer magazine]]></category>
		<category><![CDATA[inner product]]></category>

		<guid isPermaLink="false">http://gamesfromwithin.com/?p=723</guid>
		<description><![CDATA[Picture this: Toward the end of the development cycle, your game crawls, but you don’t see any obvious hotspots in the profiler. The culprit? Random memory access patterns and constant cache misses. In an attempt to improve performance, you try &#8230; <a href="http://gamesfromwithin.com/data-oriented-design">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Picture this: Toward the end of the development cycle, your game crawls, but you don’t see any obvious hotspots in the profiler. The culprit? Random memory access patterns and constant cache misses. In an attempt to improve performance, you try to parallelize parts of the code, but it takes heroic efforts, and, in the end, you barely get much of a speed-up due to all the synchronization you had to add. To top it off, the code is so complex that fixing bugs creates more problems, and the thought of adding new features is discarded right away. Sound familiar?</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">That scenario pretty accurately describes almost every game I’ve been involved with for the last 10 years. The reasons aren’t the programming languages we’re using, nor the development tools, nor even a lack of discipline. In my experience, it’s object- oriented programming (OOP) and the culture that surrounds it that is in large part to blame for those problems. OOP could be hindering your project rather than helping it!</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">It&#8217;s All About Data</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">OOP is so ingrained in the current game development culture that it’s hard to think beyond objects when thinking about a game. After all, we’ve been creating classes representing vehicles, players, and state machines for many years. What are the alternatives? Procedural programming? Functional languages? Exotic programming languages?</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Data-oriented design is a different way to approach program design that addresses all these problems. Procedural programming focuses on procedure calls as its main element, and OOP deals primarily with objects. Notice that the main focus of both approaches is code: plain procedures (or functions) in one case, and grouped code associated with some internal state in the other. Data-oriented design shifts the perspective of programming from objects to the data itself: The type of the data, how it is laid out in memory, and how it will be read and processed in the game.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Programming, by definition, is about transforming data: It’s the act of creating a sequence of machine instructions describing how to process the input data and create some specific output data. A game is nothing more than a program that works at interactive rates, so wouldn’t it make sense for us to concentrate primarily on that data instead of on the code that manipulates it?</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">I’d like to clear up potential confusion and stress that data-oriented design does not imply that something is data- driven. A data-driven game is usually a game that exposes a large amount of functionality outside of code and lets the data determine the behavior of the game. That is an orthogonal concept to data-oriented design, and can be used with any type of programming approach.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Ideal Data</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">If we look at a program from the data point of view, what does the ideal data look like? It depends on the data and how it’s used. In general, the ideal data is in a format that we can use with the least amount of effort. In the best case, the format will be the same we expect as an output, so the processing is limited to just copying that data. Very often, our ideal data layout will be large blocks of contiguous, homogeneous data that we can process sequentially. In any case, the goal is to minimize the amount of transformations, and whenever possible, you should bake your data into this ideal format offline, during your asset-building process.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Because data-oriented design puts data first and foremost, we can architect our whole program around the ideal data format. We won’t always be able to make it exactly ideal (the same way that code is hardly ever by-the-book OOP), but it’s the primary goal to keep in mind. Once we achieve that, most of the problems I mentioned at the beginning of the column tend to melt away (more about that in the next section).</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">When we think about objects, we immediately think of trees— inheritance trees, containment trees, or message-passing trees, and our data is naturally arranged that way. As a result, when we perform an operation on an object, it will usually result in that object in turn accessing other objects further down in the tree. Iterating over a set of objects performing the same operation generates cascading, totally different operations at each object (see Figure 1a).</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">To achieve the best possible data layout, it’s helpful to break down each object into the different components, and group components of the same type together in memory, regardless of what object they came from. This organization results in large blocks of homogeneous data, which allow us to process the data sequentially (see Figure 1b). A key reason why data-oriented design is so powerful is because it works very well on large groups of objects. OOP, by definition, works on a single object. Step back for a minute and think of the last game you worked on: How many places in the code did you have only one of something? One enemy? One vehicle? One pathfinding node? One bullet? One particle? Never! Where there’s one, there are many. OOP ignores that and deals with each object in isolation. Instead, we can make things easy for us and for the hardware and organize our data to deal with the common case of having many items of the same type.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Does this sound like a strange approach? Guess what? You’re probably already doing this in some parts of your code: The particle system! Data-oriented design is turning our whole codebase into a gigantic particle system. Perhaps a name for this approach that would be more familiar to game programmers would have been particle-driven programming.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Advantages of Data-Oriented Design</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">hinking about data first and architecting the program based on that brings along lots of advantages.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Parallelization.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">These days, there’s no way around the fact that we need to deal with multiple cores. Anyone who has tried taking some OOP code and parallelizing it can attest how difficult, error prone, and possibly not very efficient that is. Often you end up adding lots of synchronization primitives to prevent concurrent access to data from multiple threads, and usually a lot of the threads end up idling for quite a while waiting for other threads to complete. As a result, the performance improvement can be quite underwhelming.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">When we apply data-oriented design, parallelization becomes a lot simpler: We have the input data, a small function to process it, and some output data. We can easily take something like that and split it among multiple threads with minimal synchronization between them. We can even take it further and run that code on processors with local memory (like the SPUs on the Cell processor) without having to do anything differently.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Cache utilization.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">In addition to using multiple cores, one of the keys to achieving great performance in modern hardware, with its deep instruction pipelines and slow memory systems with multiple levels of caches, is having cache-friendly memory access. Data-oriented design results in very efficient use of the instruction cache because the same code is executed over and over. Also, if we lay out the data in large, contiguous blocks, we can process the data sequentially, getting nearly perfect data cache usage and great performance. Possible optimizations. When we think of objects or functions, we tend to get stuck optimizing at the function or even the algorithm level; Reordering some function calls, changing the sort method, or even re-writing some C code with assembly.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">That kind of optimization is certainly beneficial, but by thinking about the data first we can step further back and make larger, more important optimizations. Remember that all a game does is transform some data (assets, inputs, state) into some other data (graphics commands, new game states). By keeping in mind that flow of data, we can make higher-level, more intelligent decisions based on how the data is transformed, and how it is used. That kind of optimization can be extremely difficult and time- consuming to implement with more traditional OOP methods.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Modularity.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">So far, all the advantages of data-oriented design have been based around performance: cache utilization, optimizations, and parallelization. There is no doubt that as game programmers, performance is an extremely important goal for us. There is often a conflict between techniques that improve performance and techniques that help readability and ease of development. For example, re-writing some code in assembly language can result in a performance boost, but usually makes the code harder to read and maintain.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Fortunately, data-oriented design is beneficial to both performance and ease of development. When you write code specifically to transform data, you end up with small functions, with very few dependencies on other parts of the code. The codebase ends up being very “flat,” with lots of leaf functions without many dependencies. This level of modularity and lack of dependences makes understanding, replacing, and updating the code much easier.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Testing.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">The last major advantage of data-oriented design is ease of testing. As we saw in the June and August Inner Product columns, writing unit tests to check object interactions is not trivial. You need to set up mocks and test things indirectly. Frankly, it’s a bit of a pain. On the other hand, when dealing directly with data, it couldn’t be easier to write unit tests: Create some input data, call the transform function, and check that the output data is what we expect. There’s nothing else to it. This is actually a huge advantage and makes code extremely easy to test, whether you’re doing test-driven development or just writing unit tests after the code.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Drawbacks of Data-Oriented Design</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Data-oriented design is not the silver bullet to all the problems in game development. It does help tremendously writing high-performance code and making programs more readable and easier to maintain, but it does come with a few drawbacks of its own.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">The main problem with data-oriented design is that it’s different from what most programmers are used to or learned in school. It requires turning our mental model of the program ninety degrees and changing how we think about it. It takes some practice before it becomes second-nature.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Also, because it’s a different approach, it can be challenging to interface with existing code, written in a more OOP or procedural way. It’s hard to write a single function in isolation, but as long as you can apply data-oriented design to a whole subsystem you should be able to reap a lot of the benefits.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Applying Data-Oriented Design</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Enough of the theory and overview. How do you actually get started with data-oriented design? To start with, just pick a specific area in your code: navigation, animations, collisions, or something else. Later on, when most of your game engine is centered around the data, you can worry about data flow all the way from the start of a frame until the end.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">The next step is to clearly identify the data inputs required by the system, and what kind of data it needs to generate. It’s OK to think about it in OOP terms for now, just to help us identify the data. For example, in an animation system, some of the input data is skeletons, base poses, animation data, and current state. The result is not “the code plays animations,” but the data generated by the animations that are currently playing. In this case, our outputs would be a new set of poses and an updated state.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">It’s important to take a step further and classify the input data based on how it is used. Is it read- only, read-write, or write-only? That classification will help guide design decisions about where to store it, and when to process it depending on dependencies with other parts of the program.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">At this point, stop thinking of the data required for a single operation, and think in terms of applying it to dozens or hundreds of entries. We no longer have one skeleton, one base pose, and a current state, and instead we have a block of each of those types with many instances in each of the blocks.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Think very carefully how the data is used during the transformation process from input to output. You might realize that you need to scan a particular field in a structure to perform a pass on the data, and then you need to use the results to do another pass. In that case, it might make more sense to split that initial field into a separate block of memory that can be processed independently, allowing for better cache utilization and potential parallelization. Or maybe you need to vectorize some part of the code, which requires fetching data from different locations to put it in the same vector register. In that case, that data can be stored contiguously so vector operations can be applied directly, without any extra transformations.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Now you should have a very good understanding of your data. Writing the code to transform it is going to be much simpler. It’s like writing code by filling in the blanks. You’ll even be pleasantly surprised to realize that the code is much simpler and smaller than you thought in the first place, compared to what the equivalent OOP code would have been.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">If you think back about most of the topics we’ve covered in this column over the last year, you’ll see that they were all leading toward this type of design. Now it’s the time to be careful about how the data is aligned (Dec 2008 and Jan 2009), to bake data directly into an input format that you can use efficiently (Oct and Nov 2008), or to use non- pointer references between data blocks so they can be easily relocated (Sept 2009).</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Is Thre Room For OOP?</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Does this mean that OOP is useless and you should never apply it in your programs? I’m not quite ready to say that. Thinking in terms of objects is not detrimental when there is only one of each object (a graphics device, a log manager, etc) although in that case you might as well write it with simpler C-style functions and file-level static data. Even in that situation, it’s still important that those objects are designed around transforming data.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Another situation where I still find myself using OOP is GUI systems. Maybe it’s because you’re working with a system that is already designed in an object-oriented way, or maybe it’s because performance and complexity are not crucial factors with GUI code. In any case, I much prefer GUI APIs that are light on inheritance and use containment as much as possible (Cocoa and CocoaTouch are good examples of this). It’s very possible that a data-oriented GUI system could be written for games that would be a pleasure to work with, but I haven’t seen one yet.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Finally, there’s nothing stopping you from still having a mental picture of objects if that’s the way you like to think about the game. It’s just that the enemy entity won’t be all in the same physical location in memory. Instead, it will be split up into smaller subcomponents, each one forming part of a larger data table of similar components.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Data-oriented design is a bit of a departure from traditional programming approaches, but by always thinking about the data and how it needs to be transformed, you’ll be able to reap huge benefits both in terms of performance and ease of development.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">Thanks to Mike Acton and Jim Tilander for challenging my ideas over the years and for their feedback on this article.</div>
<p>Picture this: Toward the end of the development cycle, your game crawls, but you don’t see any obvious hotspots in the profiler. The culprit? Random memory access patterns and constant cache misses. In an attempt to improve performance, you try to parallelize parts of the code, but it takes heroic efforts, and, in the end, you barely get much of a speed-up due to all the synchronization you had to add. To top it off, the code is so complex that fixing bugs creates more problems, and the thought of adding new features is discarded right away. Sound familiar?</p>
<p>That scenario pretty accurately describes almost every game I’ve been involved with for the last 10 years. The reasons aren’t the programming languages we’re using, nor the development tools, nor even a lack of discipline. In my experience, it’s object- oriented programming (OOP) and the culture that surrounds it that is in large part to blame for those problems. OOP could be hindering your project rather than helping it!</p>
<h2>It&#8217;s All About Data</h2>
<p>OOP is so ingrained in the current game development culture that it’s hard to think beyond objects when thinking about a game. After all, we’ve been creating classes representing vehicles, players, and state machines for many years. What are the alternatives? Procedural programming? Functional languages? Exotic programming languages?</p>
<p>Data-oriented design is a different way to approach program design that addresses all these problems. Procedural programming focuses on procedure calls as its main element, and OOP deals primarily with objects. Notice that the main focus of both approaches is code: plain procedures (or functions) in one case, and grouped code associated with some internal state in the other. Data-oriented design shifts the perspective of programming from objects to the data itself: The type of the data, how it is laid out in memory, and how it will be read and processed in the game.</p>
<p>Programming, by definition, is about transforming data: It’s the act of creating a sequence of machine instructions describing how to process the input data and create some specific output data. A game is nothing more than a program that works at interactive rates, so wouldn’t it make sense for us to concentrate primarily on that data instead of on the code that manipulates it?</p>
<p>I’d like to clear up potential confusion and stress that data-oriented design does not imply that something is data- driven. A data-driven game is usually a game that exposes a large amount of functionality outside of code and lets the data determine the behavior of the game. That is an orthogonal concept to data-oriented design, and can be used with any type of programming approach.</p>
<h2>Ideal Data</h2>
<div id="attachment_726" class="wp-caption alignright" style="width: 239px"><img class="size-full wp-image-726 " title="oo_design" src="http://gamesfromwithin.com/wp-content/uploads/2009/12/oo_design.png" alt="Call sequence with an object-oriented approach" width="229" height="247" /><p class="wp-caption-text">Figure 1a. Call sequence with an object-oriented approach</p></div>
<p>If we look at a program from the data point of view, what does the ideal data look like? It depends on the data and how it’s used. In general, the ideal data is in a format that we can use with the least amount of effort. In the best case, the format will be the same we expect as an output, so the processing is limited to just copying that data. Very often, our ideal data layout will be large blocks of contiguous, homogeneous data that we can process sequentially. In any case, the goal is to minimize the amount of transformations, and whenever possible, you should bake your data into this ideal format offline, during your asset-building process.</p>
<p>Because data-oriented design puts data first and foremost, we can architect our whole program around the ideal data format. We won’t always be able to make it exactly ideal (the same way that code is hardly ever by-the-book OOP), but it’s the primary goal to keep in mind. Once we achieve that, most of the problems I mentioned at the beginning of the column tend to melt away (more about that in the next section).</p>
<p>When we think about objects, we immediately think of trees— inheritance trees, containment trees, or message-passing trees, and our data is naturally arranged that way. As a result, when we perform an operation on an object, it will usually result in that object in turn accessing other objects further down in the tree. Iterating over a set of objects performing the same operation generates cascading, totally different operations at each object (see Figure 1a).</p>
<div id="attachment_728" class="wp-caption alignright" style="width: 243px"><img class="size-full wp-image-728 " title="do_design" src="http://gamesfromwithin.com/wp-content/uploads/2009/12/do_design1.png" alt="Call sequence with a data-oriented approach" width="233" height="297" /><p class="wp-caption-text">Figure 1b. Call sequence with a data-oriented approach</p></div>
<p>To achieve the best possible data layout, it’s helpful to break down each object into the different components, and group components of the same type together in memory, regardless of what object they came from. This organization results in large blocks of homogeneous data, which allow us to process the data sequentially (see Figure 1b). A key reason why data-oriented design is so powerful is because it works very well on large groups of objects. OOP, by definition, works on a single object. Step back for a minute and think of the last game you worked on: How many places in the code did you have only one of something? One enemy? One vehicle? One pathfinding node? One bullet? One particle? Never! Where there’s one, there are many. OOP ignores that and deals with each object in isolation. Instead, we can make things easy for us and for the hardware and organize our data to deal with the common case of having many items of the same type.</p>
<p>Does this sound like a strange approach? Guess what? You’re probably already doing this in some parts of your code: The particle system! Data-oriented design is turning our whole codebase into a gigantic particle system. Perhaps a name for this approach that would be more familiar to game programmers would have been particle-driven programming.</p>
<h2>Advantages of Data-Oriented Design</h2>
<p>Thinking about data first and architecting the program based on that brings along lots of advantages.</p>
<h3>Parallelization.</h3>
<p>These days, there’s no way around the fact that we need to deal with multiple cores. Anyone who has tried taking some OOP code and parallelizing it can attest how difficult, error prone, and possibly not very efficient that is. Often you end up adding lots of synchronization primitives to prevent concurrent access to data from multiple threads, and usually a lot of the threads end up idling for quite a while waiting for other threads to complete. As a result, the performance improvement can be quite underwhelming.</p>
<p>When we apply data-oriented design, parallelization becomes a lot simpler: We have the input data, a small function to process it, and some output data. We can easily take something like that and split it among multiple threads with minimal synchronization between them. We can even take it further and run that code on processors with local memory (like the SPUs on the Cell processor) without having to do anything differently.</p>
<h3>Cache utilization.</h3>
<p>In addition to using multiple cores, one of the keys to achieving great performance in modern hardware, with its deep instruction pipelines and slow memory systems with multiple levels of caches, is having cache-friendly memory access. Data-oriented design results in very efficient use of the instruction cache because the same code is executed over and over. Also, if we lay out the data in large, contiguous blocks, we can process the data sequentially, getting nearly perfect data cache usage and great performance. Possible optimizations. When we think of objects or functions, we tend to get stuck optimizing at the function or even the algorithm level; Reordering some function calls, changing the sort method, or even re-writing some C code with assembly.</p>
<p>That kind of optimization is certainly beneficial, but by thinking about the data first we can step further back and make larger, more important optimizations. Remember that all a game does is transform some data (assets, inputs, state) into some other data (graphics commands, new game states). By keeping in mind that flow of data, we can make higher-level, more intelligent decisions based on how the data is transformed, and how it is used. That kind of optimization can be extremely difficult and time- consuming to implement with more traditional OOP methods.</p>
<h3>Modularity.</h3>
<p>So far, all the advantages of data-oriented design have been based around performance: cache utilization, optimizations, and parallelization. There is no doubt that as game programmers, performance is an extremely important goal for us. There is often a conflict between techniques that improve performance and techniques that help readability and ease of development. For example, re-writing some code in assembly language can result in a performance boost, but usually makes the code harder to read and maintain.</p>
<p>Fortunately, data-oriented design is beneficial to both performance and ease of development. When you write code specifically to transform data, you end up with small functions, with very few dependencies on other parts of the code. The codebase ends up being very “flat,” with lots of leaf functions without many dependencies. This level of modularity and lack of dependences makes understanding, replacing, and updating the code much easier.</p>
<h3>Testing.</h3>
<p>The last major advantage of data-oriented design is ease of testing. As we saw in the June and August Inner Product columns, writing unit tests to check object interactions is not trivial. You need to set up mocks and test things indirectly. Frankly, it’s a bit of a pain. On the other hand, when dealing directly with data, it couldn’t be easier to write unit tests: Create some input data, call the transform function, and check that the output data is what we expect. There’s nothing else to it. This is actually a huge advantage and makes code extremely easy to test, whether you’re doing test-driven development or just writing unit tests after the code.</p>
<h2>Drawbacks of Data-Oriented Design</h2>
<p>Data-oriented design is not the silver bullet to all the problems in game development. It does help tremendously writing high-performance code and making programs more readable and easier to maintain, but it does come with a few drawbacks of its own.</p>
<p>The main problem with data-oriented design is that it’s different from what most programmers are used to or learned in school. It requires turning our mental model of the program ninety degrees and changing how we think about it. It takes some practice before it becomes second-nature.</p>
<p>Also, because it’s a different approach, it can be challenging to interface with existing code, written in a more OOP or procedural way. It’s hard to write a single function in isolation, but as long as you can apply data-oriented design to a whole subsystem you should be able to reap a lot of the benefits.</p>
<h2>Applying Data-Oriented Design</h2>
<p>Enough of the theory and overview. How do you actually get started with data-oriented design? To start with, just pick a specific area in your code: navigation, animations, collisions, or something else. Later on, when most of your game engine is centered around the data, you can worry about data flow all the way from the start of a frame until the end.</p>
<p>The next step is to clearly identify the data inputs required by the system, and what kind of data it needs to generate. It’s OK to think about it in OOP terms for now, just to help us identify the data. For example, in an animation system, some of the input data is skeletons, base poses, animation data, and current state. The result is not “the code plays animations,” but the data generated by the animations that are currently playing. In this case, our outputs would be a new set of poses and an updated state.</p>
<p>It’s important to take a step further and classify the input data based on how it is used. Is it read- only, read-write, or write-only? That classification will help guide design decisions about where to store it, and when to process it depending on dependencies with other parts of the program.</p>
<p>At this point, stop thinking of the data required for a single operation, and think in terms of applying it to dozens or hundreds of entries. We no longer have one skeleton, one base pose, and a current state, and instead we have a block of each of those types with many instances in each of the blocks.</p>
<p>Think very carefully how the data is used during the transformation process from input to output. You might realize that you need to scan a particular field in a structure to perform a pass on the data, and then you need to use the results to do another pass. In that case, it might make more sense to split that initial field into a separate block of memory that can be processed independently, allowing for better cache utilization and potential parallelization. Or maybe you need to vectorize some part of the code, which requires fetching data from different locations to put it in the same vector register. In that case, that data can be stored contiguously so vector operations can be applied directly, without any extra transformations.</p>
<p>Now you should have a very good understanding of your data. Writing the code to transform it is going to be much simpler. It’s like writing code by filling in the blanks. You’ll even be pleasantly surprised to realize that the code is much simpler and smaller than you thought in the first place, compared to what the equivalent OOP code would have been.</p>
<p>If you think back about most of the topics we’ve covered in this column over the last year, you’ll see that they were all leading toward this type of design. Now it’s the time to be careful about how the data is aligned (Dec 2008 and Jan 2009), to bake data directly into an input format that you can use efficiently (Oct and Nov 2008), or to use non- pointer references between data blocks so they can be easily relocated (Sept 2009).</p>
<h2>Is There Room For OOP?</h2>
<p>Does this mean that OOP is useless and you should never apply it in your programs? I’m not quite ready to say that. Thinking in terms of objects is not detrimental when there is only one of each object (a graphics device, a log manager, etc) although in that case you might as well write it with simpler C-style functions and file-level static data. Even in that situation, it’s still important that those objects are designed around transforming data.</p>
<p>Another situation where I still find myself using OOP is GUI systems. Maybe it’s because you’re working with a system that is already designed in an object-oriented way, or maybe it’s because performance and complexity are not crucial factors with GUI code. In any case, I much prefer GUI APIs that are light on inheritance and use containment as much as possible (Cocoa and CocoaTouch are good examples of this). It’s very possible that a data-oriented GUI system could be written for games that would be a pleasure to work with, but I haven’t seen one yet.</p>
<p>Finally, there’s nothing stopping you from still having a mental picture of objects if that’s the way you like to think about the game. It’s just that the enemy entity won’t be all in the same physical location in memory. Instead, it will be split up into smaller subcomponents, each one forming part of a larger data table of similar components.</p>
<p>Data-oriented design is a bit of a departure from traditional programming approaches, but by always thinking about the data and how it needs to be transformed, you’ll be able to reap huge benefits both in terms of performance and ease of development.</p>
<p><br/></p>
<p>Thanks to <a href="http://www.cellperformance.com/mike_acton">Mike Acton</a> and <a href="http://www.tilander.org/aurora/">Jim Tilander</a> for challenging my ideas over the years and for their feedback on this article.</p>
<p>This article was originally printed in the September 2009 issue of <a href="http://gdmag.com">Game Developer</a>.</p>
<p><br/></p>
<p><a href="http://www.lameproof.com/zboard/zboard.php?id=bbs2&amp;no=790">Here&#8217;s a Korean translation of this article</a> by Hakkyu Kim.</p>
]]></content:encoded>
			<wfw:commentRss>http://gamesfromwithin.com/data-oriented-design/feed</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
	</channel>
</rss>

