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

<channel>
	<title>#AltDevBlogADay &#187; Rob Ashton</title>
	<atom:link href="http://www.altdevblogaday.com/author/rob-ashton/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.altdevblogaday.com</link>
	<description>Each day a little more #gamedev love</description>
	<lastBuildDate>Thu, 17 May 2012 03:06:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Asset packaging in browser-based games</title>
		<link>http://www.altdevblogaday.com/2012/03/28/asset-packaging-in-browser-based-games/</link>
		<comments>http://www.altdevblogaday.com/2012/03/28/asset-packaging-in-browser-based-games/#comments</comments>
		<pubDate>Wed, 28 Mar 2012 10:39:26 +0000</pubDate>
		<dc:creator>Rob Ashton</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=25219</guid>
		<description><![CDATA[<p>I&#8217;ve written a <a href="http://altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/">couple</a> of <a href="http://altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/">posts</a> on asset management in web-based games already, and I still think they&#8217;re valid and useful on most of the points made in them.</p>
<p>However, in putting together my latest endeavour (a hack-n-slash isometric multi-player RPG in HTML5 canvas), I&#8217;ve learned a few more things and want to share them.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/28/asset-packaging-in-browser-based-games/" class="more-link">Read more on Asset packaging in browser-based games&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve written a <a href="http://altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/">couple</a> of <a href="http://altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/">posts</a> on asset management in web-based games already, and I still think they&#8217;re valid and useful on most of the points made in them.</p>
<p>However, in putting together my latest endeavour (a hack-n-slash isometric multi-player RPG in HTML5 canvas), I&#8217;ve learned a few more things and want to share them.</p>
<p><strong>TLDR;</strong> I&#8217;ve pushed the code I&#8217;m currently using to Github and it can be found here: <a title="Swallow: Resource packaging for JS games" href="https://github.com/robashton/swallow">https://github.com/robashton/swallow</a></p>
<p>Anyway &#8211; moving on we can discover some of these learnings:</p>
<h4><strong>Simply waiting for requested assets to load via HTTP on start-up isn&#8217;t always enough</strong></h4>
<p>In my <a href="http://altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/">earlier post</a>, I suggested if you had a resource caretaker which you requested resources like textures, sounds, models, shaders etc from &#8211; then it could take care of loading the data and return promises rather than the real things, this looked something like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> modelOne <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'models/hovercraft.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> modelTwo <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'models/missile.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> explosionSound <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'sounds/explosion.wav'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
resources.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'fullyLoaded'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  game.<span style="color: #660066;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// use the resources</span>
  modelOne.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  modelTwo.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

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

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

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

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

<p>Ace.</p>
<p>This has its share of issues though &#8211; the biggest one is probably that it doesn&#8217;t really allow for any granularity in your app.</p>
<p>In this modern age of the internet, our users have short attention spans and a long initial load may well mean losing out on users &#8211; if you have different levels for example, you probably want to download each level and the assets for that level before you <em>play</em> that level &#8211; not at the beginning of the whole game.</p>
<p>In short, the Application Cache is great if you have a small self contained game (such as puzzle games), or if you want to fully support the game being playable offline immediately after download;  it does however come with its share of issues.</p>
<p>That brings us onto another option</p>
<h4><strong>Write your own Application Cache</strong></h4>
<p>We can easily emulate what the AppCache does for us by writing our own manifest definition and using that to pre-load files from the server. We can then rely on the browser-cache to carry on working the way it always has (so if files haven&#8217;t changed, don&#8217;t fetch them etc).</p>
<p>This is essentially like our first solution again, except we now have manifest files which describe what data needs pre-loading.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">resources.<span style="color: #660066;">preloadFromManifest</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'levels/levelOne.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> modelOne <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'models/hovercraft.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> modelTwo <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'models/missile.json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> explosionSound <span style="color: #339933;">=</span> resources.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'sounds/explosion.wav'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
resources.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'fullyLoaded'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  game.<span style="color: #660066;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// use the resources</span>
  modelOne.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  modelTwo.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

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

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

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

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

<p>In actuality, what we end up doing is loading an entire asset package, say &#8216;assets.json&#8217; and writing the following code before loading the game.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">getJSON</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'assets.json'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>rawData<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  preloadAssets<span style="color: #009900;">&#40;</span>rawData<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> preloadAssets<span style="color: #009900;">&#40;</span>rawData<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    forEachResourceInRawData<span style="color: #009900;">&#40;</span>rawData<span style="color: #339933;">,</span> preloadItem<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> preloadItem<span style="color: #009900;">&#40;</span>key<span style="color: #339933;">,</span> itemData<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> loader <span style="color: #339933;">=</span> findLoaderForFiletype<span style="color: #009900;">&#40;</span>key<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  increaseAwaitCounter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  loader<span style="color: #009900;">&#40;</span>key<span style="color: #339933;">,</span> itemData<span style="color: #339933;">,</span> decreaseAwaitcounter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
resources.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'complete'</span><span style="color: #339933;">,</span> startGame<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Where an implementation of a handler for a PNG might do this</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> preloadPng<span style="color: #009900;">&#40;</span>key<span style="color: #339933;">,</span> itemData<span style="color: #339933;">,</span> cb<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> preloadedImage <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Image<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    preloadedImage.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;data:image/png;base64,&quot;</span> <span style="color: #339933;">+</span> itemData<span style="color: #339933;">;</span>
    preloadedAssets<span style="color: #009900;">&#91;</span>key<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> preloadedImage<span style="color: #339933;">;</span>
    preloadedImage.<span style="color: #000066;">onload</span> <span style="color: #339933;">=</span> cb<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

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

		<guid isPermaLink="false">http://altdevblogaday.com/2011/11/29/the-two-worlds-a-project-retrospective/</guid>
		<description><![CDATA[<p>I’m finally back in the world of games development after a long sojourn selling my soul for cold, hard cash in the world of active directory and corporate software. I’ve managed to pick up development of my multiplayer WebGL game and push it to some form of completion too (It’ll be up later this week at an un-specified location pending load tests).</p>
<p><a href="http://www.altdevblogaday.com/2011/11/29/the-two-worlds-a-project-retrospective/" class="more-link">Read more on The two worlds &#8211; a project retrospective&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I’m finally back in the world of games development after a long sojourn selling my soul for cold, hard cash in the world of active directory and corporate software. I’ve managed to pick up development of my multiplayer WebGL game and push it to some form of completion too (It’ll be up later this week at an un-specified location pending load tests).</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/11/image7.png"><img style="border-right-width: 0px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="image" src="http://altdevblogaday.com/wp-content/uploads/2011/11/image_thumb7.png" width="405" height="131" /></a></p>
<p>That’s the commit history for the project, starting off as an exercise in trying to do some TDD&#160; with some basic WebGL code to somehow ending up building a game of hovercraft, neon-blue grids, and explosions (I’m not good with assets, so making everything glow seems like the cheapest way to make it pretty).</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/11/image8.png"><img style="border-right-width: 0px;padding-left: 0px;padding-right: 0px;border-top-width: 0px;border-bottom-width: 0px;border-left-width: 0px;padding-top: 0px" border="0" alt="image" src="http://altdevblogaday.com/wp-content/uploads/2011/11/image_thumb8.png" width="457" height="236" /></a></p>
<p>What has been interesting throughout this project (for me) has been the at times subconscious attempts to carry on ‘doing things the way I do it in most of my day to day software’, and finding out that some of the rules don’t apply in this particular space – and some surprising ones do. (or at least, in this specific game in this specific space).</p>
<p><strong>First to go, TDD</strong></p>
<p>Ah yes, TDD – this is a principle I’m beginning to lose my love for in both worlds for a multitude of reasons, but when I started this project I thought I’d applying this way of working to this side of the fence . I created a walking skeleton of the basic technology I was to be using (JavaScript, a browser, WebGL, a server with NodeJS) and started to write tests for each feature as I I wanted to add them.</p>
<p>This started falling over pretty quickly as most of the first features required fundamental integration tasks to be carried out before writing the higher level code (manipulating the DOM, playing with WebGL, loading shaders, connecting to servers) – each of these things requiring a tiny amount of code applied in just the right order in just the right way for the particular feature. As far as feedback cycles go, it was faster to hit ctrl-f5 in a browser and watch the actual code do what it was meant to do or fail pitifully than it was to try automating the running and assertions on those problems. </p>
<p>In essence, these things could have been solved by heading off into a blank project and doing a formal spike, before coming back to the main project and laying out the tests for them to help with the design. It would have given little value however, as they were already-solved problems and the code would change little if I designed it from the perspective of testability or otherwise. I decided to treat the entire project as one giant spike into this domain and just roll with the punches.</p>
<p>Next up the behaviour itself, this is where the formal TDD approach probably would have been a bit beneficial, but I was already feeling headstrong about my initial progress and wanted to just start spitting out features – this led me down a bit of a dark alley as the code I produced wasn’t written or designed for testability and too heavily relied on there being a heap of external components being present therefore making it too expensive to automate the running of the behaviour. Funny how that happens accidentally even though I supposedly know that a de-coupled system looks like.</p>
<p>I actually sorted that out eventually, arriving at a good, clean, testable design when solving a different problem entirely – making it possible to write tests that looked like this:</p>
<pre>test(“Hovercrafts can acquire targets when only one target is around”, function() {

  var context = GivenAnEmptyScene()
    .WithAHovercraftCalled(&quot;one&quot;)
    .WithAHovercraftCalled(&quot;two&quot;)
    .WhereNotPointingAtEachOther(&quot;one&quot;, &quot;two&quot;)
    .Build();

  var targettingCraft = context.FindCraft(&quot;one&quot;);
  var targettedCraft = context.FindCraft(&quot;two&quot;);

  targettingCraft.AimAt(targettedCraft);

  ok(targettingCraft.RaisedTargetAcquiredEventForCraftWithId(&quot;two&quot;));
});</pre>
<p>Or something along those lines anyway – note how I said “made it possible” – I found that the biggest value tests I could write were the ones describing&#160; complex interactions between entities in the scene (but ignoring external components) but because the system is relatively small and because I’m the only developer and because I was changing everything all of the time to make it more fun to play that they simply weren’t worth writing. </p>
<p>If I had been part of a team or the system was larger and more complex I think it would have been worth it – and the lesson on how to arrive at this point was a valuable one, I’ll be writing tests for my next game at about this level and not worrying about the fluff. </p>
<p>The big difference here is I guess not one of games development, but of mentality and because I’m unused to working on projects where I’m the sole owner and I’m not going to have to ship it off to another developer in six months – I think apart from the core integration code there could be a lot of value in writing tests around gameplay interactions in most games dev, in this I don’t think our two worlds differ all that much.</p>
<p><strong>Messaging</strong></p>
<p>Push, don’t pull – that’s the mantra in most of the software worlds I work on – send a command, forget about it, raise an event, forget about it – deal with your own problems, maintain your own consistency, and let everybody else do the same.</p>
<p>I messed this up big time, turns out dealing with messaging in an interactive simulation across multiple clients and a server can throw up some pretty interesting issues at times, at one point I was cursing my decision to go with a push based architecture because it was becoming such a nightmare to deal with.</p>
<p>Now, other than duplication of data (and there certainly is some, memory is not my bottleneck), the biggest issue was just trying to work out which event had come from where and why it arrived in the order it had and why it had made something happen that shouldn’t have happened.</p>
<p>My mistake, was to consider this system like any other piece of business software I have worked on – when most of the software I have worked on in the business world has been of minimal behavioural complexity. Going back to my above statement on “<em>maintain your own consistency, and let everybody else do likewise</em>”, I wasn’t paying anywhere near enough attention to this and ended up with inconsistency everywhere, I was capturing events at the wrong level, I was dealing with state at the wrong level – I was … well yeah, doing it wrong.</p>
<p>I spent a few days tidying up this mess, and formalising heavily between the different types of messages – commands being external inputs to the system telling it to do something and events being things that have happened, and anything that goes over the wire or between entities are going to be one of these things. </p>
<p>I switched a lot of the code so that entities that raised events also listened to those events to update their own state, and every other unit or subsystem did likewise on receiving those events, effectively turning each event-listener into a de-normalised view around its specific area of functionality.</p>
<p>Turns out I by accident ended up with a system not unlike this: <a href="http://martinfowler.com/eaaDev/EventSourcing.html">http://martinfowler.com/eaaDev/EventSourcing.html</a> which is where my testability came from, also giving me a system that was easy to onion ring new functionality onto. </p>
<p>A retrospective however, I think in a larger system I’ll have to be a lot more careful about this if I want to run on more portable devices which are more constrained on memory usage – I don’t think I’ll move away from ‘push’ just yet though, just move it up a level so I minimise the number of de-normalised views in existence for pulling by the clients that need them.</p>
<p><strong>Client vs Server</strong></p>
<p>One of my biggest mistakes was in how I tried to at first distinguish between code that the client had permission to execute and code that only the server had permission to execute. (For example, killing a player is something that the client can witness, but it can’t take place until the server has deemed it acceptable).</p>
<p>I tried to deal with this by having different endpoints on the client and server, containing the different logic and messaging each other before proxying the relevant commands back into the scene. It looked a bit like this:</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/11/image9.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://altdevblogaday.com/wp-content/uploads/2011/11/image_thumb9.png" width="280" height="286" /></a></p>
<p>&#160;</p>
<p>I then when bootstrapping entities into the world would attach different components to them if they were in the client to if they were in the server, supposedly making it easier to control who had permissions to do what.</p>
<p><em>Computer says no.</em></p>
<p>Turns out that this was a recipe for disaster, going back to the part where I talk about “<em>maintain your own consistency, and let everybody else do likewise”, </em>this is completely counter to that goal, the receivers in between the two worlds got fatter and fatter, and pulled more of the logic out of that world and the entities that were driving the game and made it once again hard to work out what was going on. We have a name for this in our general software world, an “anaemic domain model”. </p>
<p>Going back to the messaging aspect above, it ended up being much easier to push everything into the world (including score management etc) and have them as entities that could raise events, and handle other entities events and therefore contain their logic and guard their state more appropriately. To do this in a ‘safe’ manner, I’d just have two methods on an entity</p>
<ul>
<li><em>raiseEvent</em></li>
<li><em>raiseServerEvent</em></li>
</ul>
<p>And the entity component would be responsible for determining what it considered to be a special event that only the server could raise – the rest of the logic would be completely identical. As I’ve already suggested, having entities listen to their own events to react to change is a part of this – once raiseServerEvent is called on the server and the event automatically proxied through to the client, the code on the client carries on as if it was itself that raised the event.</p>
<p>This model looks something like this:</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/11/image10.png"><img style="border-bottom: 0px;border-left: 0px;padding-left: 0px;padding-right: 0px;border-top: 0px;border-right: 0px;padding-top: 0px" border="0" alt="image" src="http://altdevblogaday.com/wp-content/uploads/2011/11/image_thumb10.png" width="169" height="248" /></a></p>
<p>And is suddenly much easier to test and maintain – not to mention that now I have the possibility of running offline games by flicking a flag that allows server events to be raised locally. Perhaps a rename of the method to “<em>raiseProtectedEvent’</em> <img style="border-bottom-style: none;border-right-style: none;border-top-style: none;border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://altdevblogaday.com/wp-content/uploads/2011/11/wlEmoticon-smile1.png" /></p>
<p><strong>Next steps</strong></p>
<p>My next steps are to go through the 10 issues written down on a pad of paper next to my desk, wait for the domain name to propagate and push it out onto the internet on its own domain name (without publicising it too much as my client code isn’t too optimal and more than 30 players will probably kill most browsers, oops). I’m pleased with the learning achieved with this project and it is a real joy to see that my time building software that isn’t games hasn’t been completely wasted (lots of principles carry across it seems, although it pays to be more mindful of your state).</p>
<p>I have some profiling to do too, I seem to spend 5% of my time in the garbage collector and 15% rendering particles and a whole lot of other things that really shouldn’t be sucking that much time. This will be fun and no doubt result in yet another blog entry about JavaScript performance.</p>
<p>And then onwards to the next game, I have some ideas about what challenges I want to set for myself in this space and a game that I want to build that will set them for me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/11/29/the-two-worlds-a-project-retrospective/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Resource management in Javascript based games</title>
		<link>http://www.altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/</link>
		<comments>http://www.altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/#comments</comments>
		<pubDate>Tue, 03 May 2011 21:34:21 +0000</pubDate>
		<dc:creator>Rob Ashton</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=5100</guid>
		<description><![CDATA[<p>So I&#8217;ve already covered how <a href="http://altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/">HTTP is great</a> and how it gives us a great way of delivering assets to our applications (even those not based in the browser), but let us actually look at how we might use it from within a browser based game.</p>
<p><a href="http://www.altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/" class="more-link">Read more on Resource management in Javascript based games&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve already covered how <a href="http://altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/">HTTP is great</a> and how it gives us a great way of delivering assets to our applications (even those not based in the browser), but let us actually look at how we might use it from within a browser based game.</p>
<p><strong>Asynchrony</strong></p>
<p>First things first, this is a really interesting cookie &#8211; what is the following code actually doing?<br />
<code><br />
var image = new Image();<br />
var texture = gl.createTexture();<br />
texture.image = image;<br />
image.onload = function(){<br />
// Set up the gl texture<br />
};<br />
image.src = "texture.gif";<br />
</code></p>
<p>And how about this code?</p>
<p><code>var model = new Model();<br />
$.get('/models/teapot.js', function(data) {<br />
model.setData(data);<br />
});<br />
</code></p>
<p>If you&#8217;re familiar with how Javascript works then you&#8217;ll know that after image.src, code is going to carry on being executed while the resource loads, and then in the callback provided you&#8217;ll get given the data which you can then do stuff with.</p>
<p>Think about that for a second, what we&#8217;re saying here is that the game can start while content streams in the background and when those resources have loaded they&#8217;ll magically start being used?</p>
<p>Well no &#8211; not really, WebGL itself is quite tolerant and while you can set null buffers and null textures all over the place with no dire consequences, it&#8217;s not really recommended and you get a truly awful user experience while this all happens.</p>
<p>Most of the WebGL games I&#8217;ve come across fall into this pit, and for a few minutes you&#8217;re sat there wondering what all the pretty colours and odd shapes on the screen are supposed to represent as the game carries on running oblivious to the fact that none of its assets are loaded yet.</p>
<p><strong>Asset Management</strong></p>
<p>So it&#8217;s obvious that you have to actually think about asset management when writing browser based games (especially with WebGL when you have large models and textures to download).</p>
<p>My strategy for this is no different to the strategy used when dealing with assets like these in an offline game, I wrap the resources in types (Model and Texture), and stick code for pulling those assets out (or pushing them in) to a resource manager of some sort which can report back to the application the number of textures/models currently waiting download, so some sort of loading screen can be presented to the user.</p>
<p>All in all, this takes about 50 lines of code for a minimal implementation, because the code for actually loading those assets, the code for actually creating the textures, dealing with the memory, dealing with the fact that they&#8217;re all being loaded in the background (potentially on different threads) has already been written for you in the engine executing the JavaScript.</p>
<p><code>var texture = resources.getTexture('texture.gif');<br />
var model = resources.getModel('teapot.js');</code></p>
<p><code> </code></p>
<p><code>resources.onAllAssetsLoaded(function(){<br />
game.Start();<br />
});<br />
</code></p>
<p><strong>Packaging your resources</strong></p>
<p>So this is an interesting one, in most games I&#8217;ve looked at, you tend to have a specialised packed file format in order to have a single handle to a single file which you can easily seek through without going through the expense of seeking multiple files, perhaps compressed &#8211; all to minimise loading time when pulling data off disk and sticking it in ram.</p>
<p>You&#8217;re limited here to a certain extent, but we can learn from some of this in that we can sensibly package our data.</p>
<p>So, here are some largely uninteresting suggestions that should be obvious to most of us :-)</p>
<ul>
<li>We can package our models up via minification/packaging scripts</li>
<li>We can package our code up similarly</li>
<li>You can do the same with textures (mega-textures in the browser, has anybody investigated the performance of this?)</li>
</ul>
<p><strong>The art of unloading your resources</strong></p>
<p>So, what happens when you download your resources What are you actually doing? And just what is a resource anyway?</p>
<p>Now we&#8217;re into vaguely interesting territory, if you&#8217;re writing a game where all your resources fit comfortably into memory then you haven&#8217;t got to worry about anything I have to say here, but if you&#8217;re planning on writing something that will be open for more than 15 minutes of casual gaming, and traverse a few miles of level then you&#8217;ll want to think about stuff like this when dealing with your resources.</p>
<p>The lifecycle of a resource looks something like this:</p>
<ol>
<li> Load the resource from the server/cache as a file <strong>[Disk space]</strong></li>
<li> Load that resource into memory as an meaningful object <strong>[Ram]</strong></li>
<li> Use that resource wherever it is needed</li>
<li> Dispose of that resource when you no longer need it</li>
<li> Go to 1 or 2 again when necessary</li>
</ol>
<p>So, 1, 2 and 3 are well covered by all the tutorials out there on the web, but what of 4 and 5? What do we have to take into consideration when working in our browser with these?</p>
<p>First up, you don&#8217;t have deterministic garbage collection in Javascript, you have methods on your WebGL context to create and destroy resources like so:</p>
<p><code> gl.createBuffer();<br />
gl.deleteBuffer();<br />
gl.createTexture();<br />
gl.deleteTexture();<br />
</code></p>
<p>Which is nice, because it gives us a way of clearing up the memory used between the device and the host, but it doesn&#8217;t actually clear up the memory used in loading those textures/buffers in the first place.</p>
<p>Consider the following:</p>
<p><code>var vertexData = new Float32Array(10000 * 3);</code></p>
<p>How do you clear that up? How do you delete it? Well it&#8217;s quite obvious really when you think about it, with a simple call to</p>
<p><code>vertexData = null;</code></p>
<p>Now, this is overly simplistic, garbage collection is up to the individual implementation of the engine concerned, and they&#8217;re hardly simple reference counting implementations &#8211; but my point is simply that you should be careful with how you&#8217;re loading your resources, and who is referencing what. (Another point towards wrapping the big pieces of data behind some nice classes and a resource manager).</p>
<p>This does however make the way we download these models somewhat important.</p>
<p>Consider the following model format that the WebGL exporter gives us (Note: I need to commit some changes to those soon, I have quite a few additions)</p>
<p><code> var BlenderExport = BlenderExport || {};<br />
BlenderExport.Cube = {};<br />
BlenderExport.Cube.Vertices = [3,3, etc]<br />
BlenderExport.Cube.Indices = [0,1,etc]<br />
</code></p>
<p>What actually happens when you include this file into the application? Well &#8211; the file is executed, and when it is excecuted, we&#8217;re given a global variable called BlenderExport which contains a variable called Cube which contains a big pile of data as arrays of primitives.</p>
<p>Will this ever get cleared up? Any code could potentially reference this at some point, so it&#8217;s unlikely, it&#8217;s in the global namespace &#8211; anything could reference it at any time, I don&#8217;t think it&#8217;s going to go out of scope (Please correct me if I&#8217;m wrong here! hah &#8211; challenge my ignorance indeed).</p>
<p>What I prefer to do is to stick my models in plain old JSON format like so:<br />
<code><br />
{<br />
Vertices: [3,4,3, etc],<br />
Indices: [3,3,4]<br />
}<br />
</code><br />
This can be pulled down via a call to $.get(&#8221;) and parsed with JSON.parse(), resulting in a local variable which can be given to my Model object containing the data it needs to hydate itself. The actual file will get cached so subsequent calls to $.get(&#8221;) will pull the data from wherever the browser stores such things, so the model can be destroyed if it isn&#8217;t used any more, but also safely re-requested whenever it is needed.</p>
<p>Textures are obviously simple enough, because we have no control over them (Remove the reference to the image, say goodbye to the memory).</p>
<p><strong>Summary</strong></p>
<p>Anyway, all I&#8217;m saying is that you need to think a tad if you&#8217;re going to create anything other than a casual throw-away game in the browser with WebGL and JavaScript, it&#8217;s not actually all magic and you should be thinking about how you load/destroy your resources over time rather than just simply loading and letting things happen and not thinking about how you&#8217;re going to keep memory usage sane.</p>
<p>If you want to read some related material on various patterns for encapsulating state/logic safely, then wander over to <a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth">http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth</a> and enjoy.</p>
<p>Any thing I&#8217;ve missed out? Feel free to educate me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/05/03/resource-management-in-javascript-based-games/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>HTTP is great</title>
		<link>http://www.altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/</link>
		<comments>http://www.altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 08:20:40 +0000</pubDate>
		<dc:creator>Rob Ashton</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=3669</guid>
		<description><![CDATA[<p>First off I&#8217;ll say hello, as that&#8217;s traditional for new guys &#8211;  I&#8217;m <a href="http://twitter.com/robashton">@robashton</a> and I hail from <a href="http://codeofrob.com/">codeofrob.com</a> where I&#8217;ve written a few posts on <a href="http://en.wikipedia.org/wiki/WebGL">WebGL</a> and<a href="http://en.wikipedia.org/wiki/Nodejs"> node.js </a>since picking up those technologies, much to the confusion of my regular readers. I have sneaked in here to write for a (hopefully) more engaged audience on those subjects, lay down a few opinions  and hopefully receive feedback from some of the minds in this space in order to further massage my brain waves.</p>
<p><a href="http://www.altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/" class="more-link">Read more on HTTP is great&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>First off I&#8217;ll say hello, as that&#8217;s traditional for new guys &#8211;  I&#8217;m <a href="http://twitter.com/robashton">@robashton</a> and I hail from <a href="http://codeofrob.com/">codeofrob.com</a> where I&#8217;ve written a few posts on <a href="http://en.wikipedia.org/wiki/WebGL">WebGL</a> and<a href="http://en.wikipedia.org/wiki/Nodejs"> node.js </a>since picking up those technologies, much to the confusion of my regular readers. I have sneaked in here to write for a (hopefully) more engaged audience on those subjects, lay down a few opinions  and hopefully receive feedback from some of the minds in this space in order to further massage my brain waves.</p>
<p>Today&#8217;s entry will be a quick introduction to HTTP in the context of content delivery in games development.</p>
<p>I am personally writing code for WebGL (which sits in the browser), but this is generic enough that it can be applied to any browser-based game &#8211; and in fact, I&#8217;d put forward that it is generic enough for most mobile games too if you lot would hold back on re-inventing the wheel once in a while ;-).</p>
<p><strong>[Insert tech here] is just yet another way of writing cross platform code that runs slower than everything else.</strong></p>
<p>Before launching off on one, let&#8217;s understand why I ended up wanting to talk about this &#8211; one of the biggest questions I get asked by people is &#8220;What new do any of these browser based technologies <em>really</em> bring to the table?&#8221; (and why are you wasting your time with hovercraft when you could be making money?)</p>
<p>And they have a point, apart from the supposedly cross-platform nature of these technologies and having content delivery sorted out for you, there really isn&#8217;t much differentiating them from say, cross platform C* with OpenGL.</p>
<p>So let&#8217;s <em>look </em>at content delivery and see why this is a (nearly) automatically solved problem in our browser-based games.</p>
<p><em>*(if you can ever call it that)</em></p>
<p><strong>Our old &#8216;new&#8217; content delivery mechanism</strong></p>
<p>HTTP is old and it was originally built to provide interaction with documents to various network clients.  It is also much more than simply &#8220;<em>GET/POST url host: example.com</em>&#8221; (Although judging by most of the awful abstractions built around it in the past decade you&#8217;d be forgiven for thinking otherwise).  It has built in support for caching, re-directs, updates, deletes and this has has been more widely realised of late &#8211; even in the largely enterprise IT world that I reside in (well, to an extent).</p>
<p>This greater realisation has brought with it a suite of fresh-faced, lightweight new web frameworks such as <a href="http://www.sinatrarb.com">Sinatra</a>, <a href="http://nodejs.org/">Node.js</a>, etc, which rather than distort HTTP beyond recognition instead seek to provide a low level abstraction over the protocol itself, and augment that with helpful libraries and supporting code.</p>
<p>We also find ourselves with more developers potentially targeting the browser for their games with emerging technologies such as WebGL and Canvas coming into fruition,  and with those games getting larger and more complex we&#8217;re entering the territory where we <em>need </em>to know about content delivery and actually think about what is going on when we include files and textures into our games.</p>
<p>These two trends are rather supportive of each other as we&#8217;ll see.</p>
<p><strong>Content delivery?</strong></p>
<p>So, in games development, I have been led to believe that unless you&#8217;re doing everything procedurally, that games require assets &#8211; and indeed without exaggerating too much, I think that most games require <em>an awful mega huge amount </em>of assets.</p>
<p>If you&#8217;re working in JavaScript these assets will take the form of big blobs of JSON which can be brought into the client-side application via either ajax calls or simple include directives at the top of the HTML file, these assets will also include textures which take the form of standard viewable jpegs/pngs/whatever else your target clients support.</p>
<p>This is interesting, because you get an awful lot for free here, as browsers support (most) of the HTTP protocol and a good server supports more than enough of it to give you all the content delivery you need.</p>
<p>Here&#8217;s the thing though, you don&#8217;t have an awful lot of control over this process (sorry guys), compressing all of your assets to a single packed and compressed proprietary format and shipping it with your game via some magically efficient wizardry is quite impractical, although not <em>entirely </em>impossible.</p>
<p>What we&#8217;re saying really, is that if you want to get content into your browser-based-game you&#8217;re going to be downloading those assets via HTTP.</p>
<p><strong>The content itself </strong></p>
<p>There are only a few types of content you can download into your browser when creating a browser based game with the current technology stack and these take the form of:</p>
<ul>
<li>The code for the game itself (JavaScript)</li>
<li>Models/data about your entities (JSON)</li>
<li>Textures (Images)</li>
<li>Sounds (WAV/whatever)</li>
</ul>
<p>There really isn&#8217;t too much outside of this &#8211; and in fact it is all but impossible to envisage anything outside of this save for perhaps a few custom text formats which you might write parsers for in JavaScript (I don&#8217;t see this being a common use case if you&#8217;re wanting speed, JSON is native to JS after all).</p>
<p><strong>Taking advantage of HTTP</strong></p>
<p>If you&#8217;re writing a mobile game for any of the various mobile devices, you&#8217;ve probably hit the size limit for whatever application store you&#8217;re deploying to and realised you&#8217;re going to have to pull content down from a server somewhere (Or start to compress, compress, compress).</p>
<p>This is quite interesting, as there are many parallels to be drawn between delivering content for those games, and delivering content for our browser-based games &#8211; except that with browser based games we haven&#8217;t got to do any of this work ourselves because the client and server protocols are not just defined but we&#8217;re running in a sandbox which natively supports them.</p>
<p>So, for example:</p>
<p><strong>I want to pull down resources I don&#8217;t have yet</strong></p>
<p>In our client&#8217;s terms, this is an HTTP GET, and our server just needs to return the data requested &#8211; nothing more elaborate than that.  This is the request the browser will make whenever you download the initial page hosting the game,  include a script, attach an image to a resource or well, anything else in fact.</p>
<p><strong>I don&#8217;t want to pull down resources I already have, but I do want new versions of those resources</strong></p>
<p>In simplest terms, the HTTP protocol supports this, you make a request for a document with a specific version/date/etag/whatever and the server returns &#8220;304 not modified&#8221; <strong>- </strong>job&#8217;s a good&#8217;n.</p>
<p><strong>I want to compress the data coming down</strong></p>
<p>Surprise surprise, HTTP supports this too, and most browsers and servers implement <em>gzip</em>, which most clients will opt in to by sending &#8220;Accept-Encoding: gzip&#8221; to the sever on initial request. This means that you can tell your content providing server to compress content as it sends it, saving band-width, time and money.</p>
<p><strong>Implications for browser based games</strong></p>
<p>In a browser based game, you can safely just ask for all the JavaScript files you want, you can safely ask for all the images you want, you can safely ask for all the sound files you want and you can leave the caching of these assets to That Which Knows Best &#8211; the client (browser) and the server (whatever that may be).</p>
<p>If you haven&#8217;t got any multi-player and you don&#8217;t need to generate anything dynamically, then you can just stick your assets behind a minimal web server, and serve a static page which downloads those static resources and allows the user to play the game at their leisure.</p>
<p>If you have multi-player, or some other need to run code server-side, then you can use something more dynamic for this &#8211; I am personally using <a href="https://github.com/felixge/node-paperboy">paperboy </a>for all my static files in node.js, and I make sure that when delivering <em>dynamic</em> content from the server  (such as world-data that gets modified over time) that caching headers are set appropriately.</p>
<p>In a more intensive deployment I&#8217;d probably separate the two out, and have static files served via a CDN (Content distribution network), and dynamic files served from the node application. The technology itself is irrelevant as it&#8217;s just an illustration.</p>
<p>You don&#8217;t need to implement any client-side <em>content </em>caching yourself (I&#8217;ve seen people suggest using Local Storage for this &#8211; no, no and no), you don&#8217;t need to implement any transfer protocols of your own and you don&#8217;t need to get all elaborate with caching and e-tags &#8211; it&#8217;s all right there for you in the way the browser talks to the web server.</p>
<p><strong>Other (non browser and specifically mobile) games</strong></p>
<p>Given all of this, is there any real reason to go and write heaps of code for content-provision in your average mobile game? I would put forth the answer &#8216;no&#8217;, because HTTP seems to do quite nicely for the rest of us and wait for the inevitable &#8220;<em>But I really needed X or Y so I wrote it all myself</em>&#8220;.</p>
<p>Given the amount of off the shelf software available for doing HTTP both on the server and the client, it surely doesn&#8217;t make financial sense to be spending any more time on this than absolutely necessary.</p>
<p>(That&#8217;s Mike&#8217;s &#8220;Challenge your ignorance&#8221; challenge undertaken then) - I genuinely would be interested to hear if there are any reasons why HTTP isn&#8217;t good enough (raw performance is a hard sell, but feel free to try), as trying to come up with answers for any of these problems in a pure browser-based-world will be a useful exercise.</p>
<p><strong>Next time&#8230;</strong></p>
<p>I am going to post the second half of this entry (I split it in two because it got too big), and talk about specific browser-based  stuff &#8211; like strategies for loading resources, unloading resources and in general being a good citizen to both your users and to your bandwidth. I might even find time to talk about constant-loading/streaming worlds and how I think that works in a purely browser + standards based world.</p>
<p>Oh, and unlike this entry, there will be some code snippets.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/04/18/in-the-land-of-content-delivery-http-is-king/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

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