<?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>Game Closure</title>
	<atom:link href="http://www.gameclosure.com/blog/feed" rel="self" type="application/rss+xml" />
	<link>http://www.gameclosure.com/blog</link>
	<description>HTML5-Powered Mobile Gaming</description>
	<lastBuildDate>Fri, 24 May 2013 23:26:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Cow Defense System &#8211; A Shooter</title>
		<link>http://www.gameclosure.com/blog/2013/05/cow-defense-system-a-shooter</link>
		<comments>http://www.gameclosure.com/blog/2013/05/cow-defense-system-a-shooter#comments</comments>
		<pubDate>Fri, 24 May 2013 23:26:48 +0000</pubDate>
		<dc:creator>Arno van der Vegt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=465</guid>
		<description><![CDATA[One of the most classic types of games is a space invader style game. Cow Defense System is just that: aliens are coming down from the top of the screen to kidnap your livestock. The game uses a lot of components which can be re-used for other games. The engine also allows modifications for different [...]]]></description>
				<content:encoded><![CDATA[<p>One of the most classic types of games is a space invader style game. Cow Defense System is just that: aliens are coming down from the top of the screen to kidnap your livestock.</p>
<p>The game uses a lot of components which can be re-used for other games. The engine also allows modifications for different games in the same genre.</p>
<p><a href="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/cds_screenshot1.png"><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/cds_screenshot1-200x300.png" alt="cds_screenshot1" width="200" height="300" class="alignnone size-medium wp-image-468" /></a></p>
<h2>Model View Controller</h2>
<p>There&#8217;s a clear distinction between the visual representation and the data of the game. The <code>Game</code> class is the core of the game logic. This is the place where all models and views are hooked up. The <code>WorldView</code> contains all views of the game mainly in the form of <code>ViewPool</code> instances.</p>
<h2>View Pools</h2>
<p>This game uses the <code>ViewPool</code> system: all views necessary are created at the start of the game in a hidden state and are obtained when something has to be displayed.</p>
<p>There are a couple of reasons for using view pools. The first is that we try to create as little garbage as possible. The second might be a little less obvious. When running the game on a mobile device the views are actually implemented in native code. When a view is created it is registered in a data structure. This takes some time when it&#8217;s done a lot. To make everything run as smoothly as possible the view pool does this once and then keeps re-using the data which was initially created.</p>
<p>There are a number of view pools used and they are structured in layers.</p>
<h2>Model Pools</h2>
<p>This game also uses model pools. A model pool is a class which contains a list of models. The model pool calls the tick function on the active part of the list. In a shooter type game a lot of items have a short lifetime. For example, bullets or enemies are on screen only a limited amount of time. To prevent a lot of creating and destroying of objects the objects are grouped into pools which allows the objects to be recycled. The code in this library also handles the linking and unlinking of views and models.</p>
<h3>The type value</h3>
<p>A model pool can contain different types of models. The facilitate this, the <code>ModelPool</code> constructor takes an optional <code>type</code> parameter.</p>
<p></p><pre class="crayon-plain-tag">this._allocItem = function (ctor, type) {
        // implentation...
    };</pre><p></p>
<p>So why use a type when the type is already implicitly provided in the <code>ctor</code> (constructor) parameter?</p>
<p>Let&#8217;s create a class which we could put in a model pool:</p>
<p></p><pre class="crayon-plain-tag">var Model1 = Class(function () {});</pre><p></p>
<p>And another one which we base on the first one:</p>
<p></p><pre class="crayon-plain-tag">var Model2 = Class(Model1, function (supr) {});</pre><p></p>
<p>Ok, we have two models. Let&#8217;s subclass the <code>ModelPool</code>. In this subclass the <code>_allocItem</code> function will be called:</p>
<p></p><pre class="crayon-plain-tag">this.getSomeModel = function () {
        var model = this._allocItem(someCondition ? Model1 : Model2);
        ...
    };</pre><p></p>
<p>Well that looks fine but after running it a couple of times weird stuff is happening. What&#8217;s going on? Unfortunately it turns out that using the <code>instanceof</code> keyword to figure out if an item can be used gives us correct values which are wrong&#8230;!?</p>
<p>The following code shows how the model pool breaks when using <code>instanceof</code> instead of a type value:</p>
<p></p><pre class="crayon-plain-tag">var test1 = new Model1();
var test2 = new Model2();

// All these values are true...
console.log(test1 instanceof Test1);
console.log(test2 instanceof Test1);
console.log(test2 instanceof Test2);</pre><p></p>
<p><code>test2</code> is an instance of <code>Test1</code> but we only want instances of <code>Test1</code> object which are not subclassed!</p>
<p>The model pool introduces a public property <code>type</code> to all models in the pool which allows the model to identify which type of model it is.</p>
<p><a href="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/cds_twins.png"><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/cds_twins.png" alt="cds_twins" width="250" height="125" class="alignnone size-full wp-image-470" /></a></p>
<h2>Optimizations</h2>
<p>After making sure the game produces as little garbage as possible &#8211; through the use of <code>ViewPool</code> and <code>ModelPool</code>- there is another step taken which makes this game perform very well: the structure of the layers and sprite sheets.</p>
<h3>How does the DevKit render stuff?</h3>
<p>All visible instances of <code>ImageView</code> are stored in a queue. The only thing which influences the order of the items in the queue is the zIndex.</p>
<p>When the scene is rendered the application executes a number of render calls. To get the best performance the number of render calls should be as few as possible.</p>
<p>How can we reduce the number of render calls? For a series of <code>ImageView</code>s to be grouped into a single render call, these properties have to be the same:</p>
<ul>
<li>Sprite sheet</li>
<li>Opacity</li>
<li>Filter</li>
</ul>
<p>If all <code>ImageView</code> instances are siblings and the listed properties are the same then they can be rendered with a single render call.</p>
<h3>Events</h3>
<p>Whenever a touch event is handled the view tree is traversed to find the actual view in which the coordinates of the touch fall. Usually there are a lot of views which are completely irrelevant for touch events, for example the views in a particle system.</p>
<p>To make sure that the system does not do a lot of redundant checking there&#8217;s a distinction made between display views and input views. The display views have the value <code>blockEvents</code> as true passed to the constructor. These views and all their children will not be checked when a touch event occurs.</p>
<h2>The Engine</h2>
<p>The Cow Defense demo game uses a number of classes which are based on the principles described above. But when you want to build your own game like this it&#8217;s not very convenient to start with a completely implemented game.</p>
<p>The <a href="https://github.com/gameclosure/shooter">shooter library</a> on which this code is based contains a sample <code>Application.js</code> file. This file is a barebones engine demonstrating views dropping, a player which can be moved, projectiles and basic collision detection, all this in less than 250 lines of code!</p>
<p><a href="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/cds_screenshot2.png"><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/cds_screenshot2-200x300.png" alt="cds_screenshot2" width="200" height="300" class="alignnone size-medium wp-image-469" /></a></p>
<p>All classes in the <code>shooter</code> library are documented. The documentation can be found here:</p>
<ul>
<li><a href="https://github.com/gameclosure/shooter/blob/master/models/readme.md">Model classes</a></li>
<li><a href="https://github.com/gameclosure/shooter/blob/master/views/readme.md">View classes</a></li>
<li><a href="https://github.com/gameclosure/shooter/tree/master/particle">ParticleSystem class</a></li>
</ul>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/05/cow-defense-system-a-shooter/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Generic Menu system</title>
		<link>http://www.gameclosure.com/blog/2013/05/a-generic-menu-system</link>
		<comments>http://www.gameclosure.com/blog/2013/05/a-generic-menu-system#comments</comments>
		<pubDate>Sat, 18 May 2013 01:17:37 +0000</pubDate>
		<dc:creator>Arno van der Vegt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=423</guid>
		<description><![CDATA[Since pretty much any game needs some kind of menu system this project will feature just that: a generic menu system which you can style as you please. The code of this menu system can be found here: https://github.com/gameclosure/menus. We&#8217;ve made this demo part of the default installation of the DevKit. If you&#8217;ve already installed [...]]]></description>
				<content:encoded><![CDATA[<p>Since pretty much any game needs some kind of menu system this project will feature just that: a generic menu system which you can style as you please.</p>
<p>The code of this menu system can be found here:  <a href="https://github.com/gameclosure/menus">https://github.com/gameclosure/menus</a>. We&#8217;ve made this demo part of the default installation of the <code>DevKit</code>. If you&#8217;ve already installed the <code>DevKit</code> then you can just run <code>./install.sh</code> again to update and get the new application.</p>
<p>All dialogs in this demo use the same images in a consistent way which makes it easy to customize them. There are also settings to select the font family, stroke color and stroke style. Another option which you can change is the way the dialogs appear like sliding and fading in and out.</p>
<p>There&#8217;s a single file in this package which controls the default behaviour and style for all views. That file is called <code>menuConstants</code> and has the option to accept a custom configuration through a <code>set</code> method.</p>
<p>This demo provides the most common menus which keep popping up again and again. The first one is a basic menu with a number of items. Usually this type of menu is used as a main menu.</p>
<p>The background of this demo is a blue gradient which is just there to add some contrast when you use these menus. You can choose any background you like or just show the menu on top of the game screen.</p>
<h2>Styling</h2>
<p>The paths to the resources used by the menu system are defined in the file <code>menus/constants/menuConstants.js</code>. The default location for all graphics is <code>resources/images/ui/</code>. It is recomended that you use the same location. However, if you do want to change the paths you can use the <code>menuConstants.set</code> method to change the configuration of the menus which includes the image locations.</p>
<h2>MenuView: A basic item menu</h2>
<p>First let&#8217;s import the <strong>MenuView</strong>. Note that the <strong>demoMenu</strong> resources have been copied into this local demo project.</p>
<p></p><pre class="crayon-plain-tag">import menus.views.MenuView as MenuView;</pre><p></p>
<p>After importing this class we can create an instance. This is usually done in the <strong>initUI</strong> function in <strong>Application.js</strong>.</p>
<p></p><pre class="crayon-plain-tag">this._mainMenu = new MenuView({
    superview: this,
    title: 'Main menu',
    items: [
        {item: 'This is an option', action: bind(this, 'onOption')},
        {item: 'Emit Second', action: 'Second'},
    ]
});</pre><p></p>
<p>This <strong>MenuView</strong> instance has a <strong>show</strong> function that causes the menu to appear. In this case, it uses the default <strong>slide</strong> transition.</p>
<p></p><pre class="crayon-plain-tag">this._mainMenu.show();</pre><p></p>
<p>Calling the <strong>show</strong> function results in the following screen: <br /><a href="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/mainMenu.png"><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/mainMenu-300x200.png" alt="mainMenu" width="300" height="200" class="alignnone size-medium wp-image-427" /></a> </p>
<p>When the first option in the menu is clicked, the <strong>onOption</strong> function in the <strong>Application</strong> is called.</p>
<p>When the second option is clicked, the instance emits a <strong>Second</strong> event which can be used as follows:</p>
<p></p><pre class="crayon-plain-tag">this._mainMenu.on('Second', bind(this, 'onSecond'));</pre><p></p>
<p>One advantage of the event emission approach is that a single event can trigger multiple functions.</p>
<p></p><pre class="crayon-plain-tag">this._mainMenu.on('Second', bind(this, 'onSecond')).on('Second', bind(this, 'doThisToo'));</pre><p></p>
<h2>TextDialogView: A dialog view</h2>
<p>The <strong>TextDialogView</strong> satisfies another common use case: the alert or confirm dialog. The following example shows how to use the <strong>TextDialogView</strong> class as an alert dialog.</p>
<p>First let&#8217;s import the class:</p>
<p></p><pre class="crayon-plain-tag">import menus.views.TextDialogView as TextDialogView;</pre><p></p>
<p>After importing the class we can create an instance:</p>
<p></p><pre class="crayon-plain-tag">this._alertModalDialog = new TextDialogView({
    superview: this,
    title: 'Alert modal',
    text: 'This menu is displayed on top of the dialogs menu',
    width: 500,
    modal: true,
    buttons: [
        {
            title: 'Ok',
            width: 160,
            style: 'GREEN'
        }
    ]
});</pre><p></p>
<p>One of the constructor parameters is a button array which must contain one or more button definitions. The <strong>modal</strong> option is used to darken the background behind the dialog.</p>
<p></p><pre class="crayon-plain-tag">this._alertModalDialog.show();</pre><p></p>
<p>When the <strong>show</strong> method on the instance is called the dialog appears which should look like this:</p>
<p><a href="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/alertModal.png"><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/alertModal-300x200.png" alt="alertModal" width="300" height="200" class="alignnone size-medium wp-image-429" /></a> </p>
<h2>DocumentView: A dialog to display simple documents.</h2>
<p>To display one or more pages of text you can use the <code>DocumentView</code>. The JSON format allows you to select the color, size and font family of the font. Other options to create nice looking pages are: images, background colors and background images.</p>
<p>A demo game which we are working on will use this window to show information about pickup items: </p>
<p><a href="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/documentBonus.png"><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/documentBonus-200x300.png" alt="documentBonus" width="200" height="300" class="alignnone size-medium wp-image-426" /></a> </p>
<p>The style options are basic but sufficient to create great looking dialogs. You can <a href="https://github.com/gameclosure/menus">read the api documentation</a> for more information on how to use this dialog.</p>
<h2>TutorialView: A tutorial dialog view</h2>
<p>You can use the <strong>TutorialView</strong> to teach users about your game. This is a dialog which contains an animation. Usually this dialog is only shown once for each option in the game. After showing it, simply set a value in <strong>localStorage</strong> to indicate that it should not be shown again.</p>
<p>To create a tutorial dialog, first import the class:</p>
<p></p><pre class="crayon-plain-tag">import menus.views.TutorialView as TutorialView;</pre><p></p>
<p>Then create an instance:</p>
<p></p><pre class="crayon-plain-tag">this._tutorialView = new TutorialView({
    superview: this,
    title: 'Tutorial',
    url: 'resources/images/tutorial/tutorial',
    animation: 'swipe'
});</pre><p></p>
<p>The animation displayed on the dialog is implemented using the <a href="http://docs.gameclosure.com/api/ui-spriteview.html">SpriteView</a> class.</p>
<p></p><pre class="crayon-plain-tag">this._tutorialView.show();</pre><p></p>
<p>When <strong>show</strong> is called the dialog should look like this:</p>
<p><a href="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/tutorial.png"><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/tutorial-200x300.png" alt="tutorial" width="200" height="300" class="alignnone size-medium wp-image-428" /></a> </p>
<h2>Building your own dialogs</h2>
<p>The easiest way to build your own dialog is to subclass the <strong>TextDialogView</strong> and clear the <strong>text</strong> option. The <strong>TextDialogView</strong> has a content area which can be used for custom content.</p>
<p></p><pre class="crayon-plain-tag">var CustomMenuView = Class(TextDialogView, function (supr) {
    this.init = function (opts) {
        delete opts.text; // Clear the text

        supr(this, 'init', [opts]);

        // Get the content from the superview and use it as a parent for a new view...
        var content = this._dialogView.content;
        this._view = new View({
            superview: content,
            x: 10,
            y: 10,
            width: 10,
            height: content.style.height - 20,
            backgroundColor: 'red'
        });
        // The new view is a red rectangle, start animating it:
        this._startAnimation();
    };

    this._startAnimation = function () {
        var content = this._dialogView.content;
        // The red rectangle moves to the right of the content and back again...
        animate(this._view).
            then({x: content.style.width - 20}, 1000).
            then({x: 10}, 1000).
            then(bind(this, '_startAnimation'), 10);
    };
});</pre><p></p>
<p>Since the <strong>TextDialogView</strong> can show buttons these have to be passed to the constructor.</p>
<p></p><pre class="crayon-plain-tag">this._customMenuView = new CustomMenuView({
    superview: this,
    title: 'Custom menu',
    buttons: [
        {
            title: 'Ok',
            width: 160,
            style: 'GREEN',
            cb: bind(this, 'showMenu', '_mainMenu')
        }
    ],
    closeCB: bind(this, 'showMenu', '_mainMenu')
});</pre><p></p>
<p>After calling the <strong>show</strong> method on this menu a dialog like this screenshot should appear:</p>
<p><a href="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/custom.png"><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/custom-300x200.png" alt="custom" width="300" height="200" class="alignnone size-medium wp-image-425" /></a> </p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/05/a-generic-menu-system/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ship an awesome, polished Android &amp; iOS game in a few hours using JavaScript</title>
		<link>http://www.gameclosure.com/blog/2013/05/ship-an-awesome-polished-android-ios-game-in-a-few-hours-using-javascript</link>
		<comments>http://www.gameclosure.com/blog/2013/05/ship-an-awesome-polished-android-ios-game-in-a-few-hours-using-javascript#comments</comments>
		<pubDate>Fri, 10 May 2013 22:16:43 +0000</pubDate>
		<dc:creator>Marcus Cavanaugh</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=409</guid>
		<description><![CDATA[The GC DevKit provides a solid, performant foundation for many different types of games. You can already build cross-platform games of any genre incredibly quickly using DevKit. At Game Closure, we regularly build new games in a day or less. We wanted to see if we could take it even further: What if we narrowed [...]]]></description>
				<content:encoded><![CDATA[<p>The GC DevKit provides a solid, performant foundation for many different types of games. You can already build cross-platform games of any genre incredibly quickly using DevKit. At Game Closure, we regularly build new games in a day or less.</p>
<p>We wanted to see if we could take it even further: What if we narrowed our constraints a bit and built a framework on top of DevKit, designed for a specific game genre? Could we reduce the cycle from idea to implementation even more, so that developers can not only prototype a game in the span of a few hours, but build a fully-polished, shippable game in an afternoon?</p>
<p>We wanted to choose a genre that includes a couple interesting technical challenges for game developers. For this first experiment, we decided to build a framework for side-scrolling games. This is a classic genre, filled with greats like the original Mario and Sonic franchises, as well as modern variants like <a href="https://itunes.apple.com/us/app/doodle-jump/id307727765?mt=8">Doodle Jump</a>, <a href="https://play.google.com/store/apps/details?id=jp.naver.SJLGWR">Wind Runner</a>, and <a href="https://itunes.apple.com/us/app/tiny-wings/id417817520?mt=8">Tiny Wings</a>. I can&#8217;t begin to count the number of hours I spent ignoring my coworkers and responsibilities because I was engrossed in Tiny Wings.</p>
<p>How can we abstract away some of the hard work in building those games? All of them have a few constraints in common:</p>
<ul>
<li>The game scrolls in one direction, always forward.</li>
<li>They employ parallax scrolling to provide a sense of depth.</li>
<li>The level is potentially infinitely long, computed on the fly.</li>
<li>They have a simple physics engine.</li>
</ul>
<p>Let&#8217;s build a framework that makes it easy to build games with those constraints. We&#8217;ll build a platform game to test the framework too.</p>
<h2>Infinite Levels</h2>
<p>To build a game with a never-ending level, we can&#8217;t just compute the level at the beginning. We&#8217;ll need to generate it as we go.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/platform256.png" alt="platform256" width="256" height="75" class="aligncenter size-full wp-image-417" /></p>
<p>For now, assume we have a <code>LevelLayer</code> class of some sort which we expect developers to subclass.</p>
<p>At the very beginning of the level, we need to generate a chunk <em>at least</em> as long as the screen width. But as the level scrolls forward, we don&#8217;t want to build new sections of the level at every frame; instead, let&#8217;s generate the level in chunks.</p>
<p></p><pre class="crayon-plain-tag">// in our framework:
while (needsMoreLevelData()) {
    populate(currentX, CHUNK_SIZE);
}</pre><p></p>
<p>Since we&#8217;re building a framework, we should think about this problem from the viewpoint of the framework. If we need data about the game, we need to ask the game developer. We could ask the developer to fill out a specific area of the level, perhaps one screen width at a time:</p>
<p></p><pre class="crayon-plain-tag">function populate(currentX, chunkSize) {
    // populate the level here
}</pre><p></p>
<p>That seems reasonable at first glance, but what happens if we&#8217;re building a platform game that has platforms wider than one screen? A fixed-width chunk wouldn&#8217;t be flexible enough.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/platform512.png" alt="platform512" width="512" height="124" class="aligncenter size-full wp-image-418" /></p>
<p>Instead, let&#8217;s just give the game developer the <code>x</code> coordinate where we need to start populating the level, and we&#8217;ll keep asking them for more data if they don&#8217;t provide enough. We need to know how far ahead they&#8217;ve prepopulated the level, so let&#8217;s have them return the width of the chunk they populated:</p>
<p></p><pre class="crayon-plain-tag">function populate(currentX) {
    var platform = new View(...);
    var spaceBetweenPlatforms = 100;
    return platform.width + spaceBetweenPlatforms;
}</pre><p></p>
<p>Cool! Now we have a generic way for the developer to specify chunks of the level as we scroll forward. As the screen scrolls forward, we&#8217;ll just call their <code>populate()</code> function and prepopulate enough level to ensure the screen is always filled.</p>
<p>But wait, we&#8217;re not quite done! As the screen scrolls forward, old level data falls off the left of the screen. If we leave it there, we&#8217;ll eventually run out of memory. One of the constraints we chose when selecting this genre was that we only scroll forward, so we know we don&#8217;t need the old level data once it leaves the screen. We don&#8217;t want the game developer to have to manually remove old level chunks, so let&#8217;s make that part of our framework too:</p>
<p></p><pre class="crayon-plain-tag">for (var i = 0; i &amp;lt; subviews.length; i++) {
    var subview = subviews[i];
    if (subview.x + subview.width &amp;lt; level.x) {
        subview.removeFromSuperview();
    }
}</pre><p></p>
<h2>Performance Optimization</h2>
<p>While we have avoided running out of memory, we need to address a couple common causes of performance problems in scrolling games.</p>
<p>If we&#8217;re going to generate the level on the fly, the <code>populate()</code> function needs to run quickly, otherwise we&#8217;ll notice hiccups in our game every time we generate a new chunk of a level. Additionally, when we allocate and destroy new views, they need to be garbage collected by the JavaScript runtime, which can cause noticeable lag spikes at arbitrary times. To write a performant game, we need to avoid allocating new memory whenever possible, so that we can reduce the need for garbage collection.</p>
<p>The GC DevKit provides a <code>ui.ViewPool</code> class, which we use in our games to preallocate a pool of views. When we need a new view, we obtain one from the pool; when we&#8217;re done with it, we release it. This pattern comes up often in game development, but it&#8217;s especially important in scrolling games where we&#8217;re constantly generating new views.</p>
<p>It needs to be drop-dead simple and intuitive for developers to use a ViewPool, and it should be as unobtrusive as possible. In our framework, the only place developers will be creating new views is within the <code>LevelLayer.populate()</code> function. They already create views like so:</p>
<p></p><pre class="crayon-plain-tag">var view = new ImageView({x: startX, ...});</pre><p></p>
<p>Assuming we have a <code>ViewPool</code> in our <code>LevelLayer</code>, let&#8217;s create a function on the LevelLayer to make it easy to fetch a pooled view. We have a few requirements, though: we need to be able to instantiate <em>any</em> class for the view pool (like an ImageView or EnemyView), and we may want to be able to generate different types of the same object (like an ImageView representing a coin, and another ImageView representing a heart). A <code>ui.ViewPool</code> can only hold one class of object. In other words, our level may need several different pools, depending on the class and group of the given object.</p>
<p>Putting that all together:</p>
<p></p><pre class="crayon-plain-tag">LevelLayer.obtainView = function(viewClass, viewOpts, group) {
    var group = viewClass + group;
    var pool = this.pools[group];
    if (!pool) {
        pool = this.pools[group] = new ui.ViewPool({
            ctor: viewClass,
            initOpts: viewOpts
        });
    }
    return pool.obtainView(viewOpts);
}</pre><p></p>
<p>If you&#8217;re confused, the <a href="http://docs.gameclosure.com/api/ui-viewpool.html">ui.ViewPool docs</a> may help.</p>
<p>Now we obtain our views from a pool, but we need to <em>release</em> them. Otherwise we&#8217;re right back where we started, running out of memory and all that.</p>
<p>Again, views might disappear for a couple reasons:</p>
<ul>
<li>The developer removed them from the screen</li>
<li>The view fell off the left of the screen</li>
</ul>
<p>Fortunately, the DevKit provides an event that we can handle to detect when a view gets removed from the screen, and we can release the view there:</p>
<p></p><pre class="crayon-plain-tag">view.on(&amp;quot;ViewRemoved&amp;quot;, function () {
    pool.releaseView(view);
});</pre><p></p>
<p>Now, the developer simply needs to use <code>obtainView(ViewClass)</code> rather than <code>new ViewClass()</code>. Views automatically come from a pool, and they are released back into the pool when the view gets removed from the screen. This avoids excess garbage collection and makes the game perform more smoothly.</p>
<h2>Parallax Scrolling</h2>
<p>All sorts of games use parallax scrolling to provide a sense of depth. Fortunately, most of the hard work has already been included in our framework through the view recycling code above. A parallax game is really just a bunch of infinitely-scrolling views stacked on top of each other, with each one scrolling proportionally to the others. Layers designed to seem far away will scroll more slowly; layers close to the camera will scroll faster.</p>
<p>At this point, it&#8217;s just a bit of math and API design to end up with something like this:</p>
<p></p><pre class="crayon-plain-tag">var ParallaxView = Class(ui.View, function () {

    this.addLayer = function (opts) {
        this.addSubview(new Layer({
            superview: this,
            populate: opts.populate,
            distance: opts.distance
        });
    }

    this.scrollTo = function(x, y) {
        // scroll each layer independently
    }
});

var Layer = Class(ui.View, function () {
    this.scrollTo = function(x, y) {
        // scroll the view
        // then populate, if necessary
    }
});</pre><p></p>
<p>Using that view becomes pretty simple:</p>
<p></p><pre class="crayon-plain-tag">var parallaxView = new ParallaxView({ superview: this.view });
parallaxView.addLayer({
    distance: 10,
    populate: function (layer, x) {
        var platform = new ImageView(...);
        layer.addSubview();
        return platform.style.width;
    }
});</pre><p></p>
<p>And with that, we have a view that supports many layers of an infinitely-scrolling level!</p>
<h2>Physics</h2>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/kiwiAce_blink_0006.png" alt="kiwiAce_blink_0006" width="100" height="100" class="alignright size-full wp-image-415" /></p>
<p>The DevKit doesn&#8217;t yet ship with a dedicated physics engine, but we&#8217;ve created games using JavaScript ports of Box2D. In this case, though, Box2D would be overkill. We just need some simple collision detection and movement. Something simple and flexible. Just enough physics to make game development easy without burdening the developer with the harsh mechanics of physical reality.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/kiwiAce_jump_0004.png" alt="kiwiAce_jump_0004" width="100" height="100" class="alignleft size-full wp-image-416" /></p>
<p>I won&#8217;t go into great detail about the implementation of the physics engine I built for this framework (the source is well-commented), but I&#8217;ll describe its API. I built this engine in one day, so if you think you can contribute improvements, let&#8217;s join forces!</p>
<p>To be intuitive, our physics needs to hook directly into the existing view system. So we should be able to either subclass a <code>Physics</code> component, or add physics to an existing view like a mixin. This framework allows both options, for convenience.</p>
<p>In a nutshell:</p>
<p></p><pre class="crayon-plain-tag">var player = new SpriteView(...);

Physics.addToView(player);

player.position.x = 100; // same as player.style.x
player.velocity.x = 200; 
player.acceleration.y = 400;

var collisions = player.getCollisions(&amp;quot;ground&amp;quot;);</pre><p></p>
<p>DevKit&#8217;s <code>ui.View</code> contains a number of useful properties, but as I was developing this framework, I found that resulting game code was clearer with a few helper accessors: <code>.getBottom()</code>, <code>.getRight()</code>, <code>.getCenter()</code>, and the like. In other words, any view that has <code>Physics</code> added automatically becomes enriched with these methods.</p>
<h2>Bonus Goodies</h2>
<p>There are a couple other pain points I found while developing this test game:</p>
<h3>Displaying a Score Efficiently</h3>
<p>The DevKit&#8217;s <code>TextView</code> isn&#8217;t optimal for displaying a high score counter. Internally, it buffers strings of text for display, and a score counter changes constantly, perhaps every frame. Additionally, most score counters display the score in a monospace font for a cleaner look, and most fonts are variable-width.</p>
<p>I&#8217;ve included a <code>ScoreView</code> class that we&#8217;ve used internally, which takes in a set of bitmaps representing individual digits in a score. At runtime, <code>ScoreView</code> will render a bitmap of each character, a fixed-width apart, and cache each digit individually. This allows the engine to render a new score every frame without degrading performance. Other than performance, a <code>ScoreView</code> is used just like a regular <code>TextView</code>: call <code>.setText(score)</code>.</p>
<h3>Aspect Ratios</h3>
<p>Every day, a new Android phone appears with a different screen resolution. By default, DevKit renders your game in a one-to-one mapping, with your main view sized equal to the screen resolution. In most games, you don&#8217;t want that kind of pixel-precision: you want to be able to write your game with a specific size in mind, and have it automatically scale to fit the screen size. Included in the <code>platformer.util</code> module in this framework is a function called <code>scaleRootView(app, width, height)</code>; it resizes your main view to fit within the screen, letterboxing it if necessary. Then you can write your game layout logic with a fixed size in mind, without making changes for different screen sizes.</p>
<h2>Results &amp; Demo</h2>
<p>Working in JavaScript, and with the DevKit, game development is already incredibly quick. I wrote both this framework and the sample game in only a couple days. Now that we&#8217;ve taken the time to abstract away some of the core concepts from a platformer-style game, we can all create a game like this even more quickly, with less code.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/05/platformer.png" alt="platformer" width="480" height="320" class="aligncenter size-full wp-image-419" /></p>
<p>This is nothing magic. Looking at the platformer framework, you&#8217;ll see that it isn&#8217;t a massive, all-encompassing project: It&#8217;s pretty simple and easy to follow. But it&#8217;s powerful enough that it makes developing platform games incredibly easy. Designing a framework is always a balancing act: If you abstract away too much, you end up with an inflexible monstrosity that&#8217;s hard to understand and maintain. But if you abstract away too little, you have a lot of extra code for little gain.</p>
<p>Take a look at this framework, <a href="http://github.com/gameclosure/platformer">fork it on GitHub</a>, and see if you can improve it.</p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/05/ship-an-awesome-polished-android-ios-game-in-a-few-hours-using-javascript/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiplayer Word Game</title>
		<link>http://www.gameclosure.com/blog/2013/04/multiplayer-word-game</link>
		<comments>http://www.gameclosure.com/blog/2013/04/multiplayer-word-game#comments</comments>
		<pubDate>Fri, 12 Apr 2013 23:08:10 +0000</pubDate>
		<dc:creator>Mario Balibrera</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=391</guid>
		<description><![CDATA[There&#8217;s been a lot of talk about building real-time multiplayer games on the DevKit. This makes sense, because everyone knows that multiplayer games are way more fun. Even these kids from the 50s have figured it out: Multiplayer games have a natural edge over single player games. Would you rather play solitaire or poker? It&#8217;s [...]]]></description>
				<content:encoded><![CDATA[<p>There&#8217;s been a lot of talk about building real-time multiplayer games on the DevKit. This makes sense, because everyone knows that multiplayer games are way more fun. Even these kids from the 50s have figured it out:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/04/parlourgames.jpg" alt="parlourgames" width="260" height="333" class="aligncenter size-full wp-image-396" /></p>
<p>Multiplayer games have a natural edge over single player games. Would you rather play solitaire or poker? It&#8217;s a matter of taste, but your buddies will never ask you to play solitaire with them. All other things being equal, we tend to do what our friends are doing. Thanks to peer pressure, multiplayer games have the potential to spread faster and retain better than single player games.</p>
<p>They&#8217;re also a lot of fun to make. Here&#8217;s an example of a simple client for a fast-paced real-time multiplayer word game.</p>
<h2>The Original</h2>
<p><a href="http://mariobalibrera.com/wordrace.html">Wordrace</a> is an extremely minimal multiplayer word game I made about five years ago. The backend is a <a href="https://github.com/gameclosure/wordrace/blob/master/race.py">dead-simple Python server</a> written atop <a href="http://code.google.com/p/dez/">dez</a> and <a href="https://code.google.com/p/registeredeventlistener/">rel</a>.</p>
<p>Basically, you&#8217;re competing against everyone else who happens to be playing. Everyone shares a pool of seven letters. The point is to use those letters to make words. When someone makes a word, the word&#8217;s letters are replaced in the shared letter pool, which is a little jarring. So if you make smaller words, you mix up the shared letter pool more often, thus screwing with your opponents. On the other hand, bigger words get you more points. What a dilemma! Does any of this make sense? <a href="http://mariobalibrera.com/wordrace.html">Play for a second to get the idea</a>. Here&#8217;s what the original browser version looks like:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/04/web.png" alt="web" width="505" height="221" class="aligncenter size-full wp-image-398" /></p>
<p>The protocol is a little silly. The server sends down 2-element arrays that look like this: <strong>[MESSAGE&#95;TYPE, MESSAGE&#95;DATA]</strong>. <strong>MESSAGE_TYPE</strong> is a string and <strong>MESSAGE_DATA</strong> varies, depending on <strong>MESSAGE_TYPE</strong>.</p>
<p>The client sends up frames delimited by <strong>:</strong>. For example, when a player tries to submit the word <strong>dog</strong>, the client sends <strong>dog:</strong> to the server. Besides sending a word, the user can also reset the current letters (if they&#8217;re bad) by sending <strong>!</strong>.</p>
<p>This reminds me of stories I&#8217;ve heard about Mexican sports writers interviewing Brazilian soccer players, with one side speaking Spanish and the other side speaking Portuguese, and both sides more or less understanding each other. Or <a href="http://www.youtube.com/watch?v=hVfQcP15-qg">this cat talking to a robot</a>.</p>
<p>That&#8217;s pretty much it. There&#8217;s a bit more built into the protocol for scoring, but we&#8217;re about to implement a client so minimal that it mostly ignores scores, which would take us too far off topic, anyway, unlike cat videos.</p>
<p>So let&#8217;s make a mobile version of this game. First let&#8217;s slap together some views.</p>
<h2>How It Looks</h2>
<p>Make a fresh game with <strong>basil init</strong> and open up your shiny new <strong>Application.js</strong>. Delete <strong>launchUI</strong> and empty out <strong>initUI</strong>. Your imports at the top should look like this:</p>
<p></p><pre class="crayon-plain-tag">import device;
import ui.View as View;
import ui.TextView as TextView;</pre><p></p>
<p>Now to build our game screen. Here&#8217;s your new <strong>initUI</strong>:</p>
<p></p><pre class="crayon-plain-tag">this.initUI = function () {
    // start button
    this.startBtn = new TextView({
        superview: this,
        layout: 'box',
        color: 'white',
        text: 'start',
        size: 50
    });
    this.startBtn.on('InputStart', bind(this, 'connect'));

    /*
     * game stuff
     */
    this.game = new View({
        superview: this,
        layout: 'box',
        canHandleEvents: false,
        visible: false
    });

    // TOP ROW: 7 letters to choose from
    this.letters = [];
    var w = device.width / 7;
    var letterBox = bind(this, function(num) {
        var tv = new TextView({
            superview: this.game,
            backgroundColor: 'red',
            size: 50,
            x: 5 + num * w,
            y: 5,
            width: w - 10,
            height: w - 10
        });
        tv.on('InputStart', bind(this, 'tapLetter', num));
        return tv;
    });
    for (var i = 0; i &amp;lt; 7; i++) {
        this.letters.push(letterBox(i));
    }

    // MIDDLE ROW: log view
    this.logView = new TextView({
        superview: this.game,
        layout: &amp;#039;box&amp;#039;,
        backgroundColor: &amp;#039;white&amp;#039;,
        color: &amp;#039;black&amp;#039;,
        size: 50,
        height: w,
        centerY: true
    });

    // BOTTOM ROW: 3 buttons
    // skip (new letters)
    this.skipBtn = new TextView({
        superview: this.game,
        layout: &amp;#039;box&amp;#039;,
        backgroundColor: &amp;#039;green&amp;#039;,
        text: &amp;#039;SKIP&amp;#039;,
        size: 50,
        height: w,
        width: w * 2,
        left: 0,
        bottom: 0
    });
    this.skipBtn.on(&amp;#039;InputStart&amp;#039;, bind(this, &amp;#039;skip&amp;#039;));

    // word being built (tap to send)
    this.word = new TextView({
        superview: this.game,
        layout: &amp;#039;box&amp;#039;,
        backgroundColor: &amp;#039;pink&amp;#039;,
        text: &amp;#039;&amp;#039;,
        size: 50,
        height: w,
        width: w * 3,
        bottom: 0,
        centerX: true
    });
    this.word.on(&amp;#039;InputStart&amp;#039;, bind(this, &amp;#039;submit&amp;#039;));

    // clear word in progress
    this.clearBtn = new TextView({
        superview: this.game,
        layout: &amp;#039;box&amp;#039;,
        backgroundColor: &amp;#039;blue&amp;#039;,
        text: &amp;#039;CLEAR&amp;#039;,
        size: 50,
        height: w,
        width: w * 2,
        right: 0,
        bottom: 0
    });
    this.clearBtn.on(&amp;#039;InputStart&amp;#039;, bind(this, &amp;#039;clear&amp;#039;));
};</pre><p></p>
<p>This creates a start button and a game screen with a row of letters at the top, a <strong>TextView</strong> for displaying game events in the middle, and a row of buttons at the bottom.</p>
<h2>What It Does</h2>
<p>So now we&#8217;ve got a bunch of views bound to nonexistent input handlers. Here are the handlers:</p>
<p></p><pre class="crayon-plain-tag">/*
 * input event callbacks
 */
this.skip = function() {
    this.send(&quot;!&quot;);
};

this.clear = function() {
    for (var i = 0; i  2) {
        this.clear();
        this.send(w);
    }
};

this.tapLetter = function(num) {
    this.word.setText(this.word.getText() + this.letters[num].getText());
    this.letters[num].setText(&quot;&quot;);
};

this.connect = function() {
    this.log(&quot;connect&quot;);
    import gc.native.socketTransport as socketTransport;
    this.sock = new socketTransport.Socket('mariobalibrera.com', 9999);
    this.sock.reader.setMode('json');
    this.sock.onError = bind(this, 'onError');
    this.sock.onClose = bind(this, 'onClose');
    this.sock.onConnect = bind(this, 'onConnect');
    this.sock.onRead = bind(this, 'onRead');
};</pre><p></p>
<p>These handlers invoke a couple utility functions, <strong>this.log</strong> and <strong>this.send</strong>. They look like this:</p>
<p></p><pre class="crayon-plain-tag">this.log = function(data) {
    logger.log(data);
    this.logView.setText(data);
};

this.send = function(data) {
    this.log('sending: ' + data);
    this.sock.send(data + &quot;:&quot;);
};</pre><p></p>
<p>The last handler, <strong>this.connect</strong>, binds several network events to callbacks. Here are those callbacks:</p>
<p></p><pre class="crayon-plain-tag">/*
 * socket event callbacks
 */
this.onError = function(e) {
    this.log(&quot;error: &quot; + e);
};

this.onClose = function() {
    this.log(&quot;close&quot;);
};

this.onConnect = function() {
    this.log(&quot;connected&quot;);
    this.send('player' + ~~(Math.random() * 1000));
};

// event router
this.onRead = function(data) {
    switch(data[0]) {
        case &quot;SCORE&quot;: this.score(data[1]); break;
        case &quot;WORD&quot;: this.newLetters(data[1]); break;
        case &quot;ALERT&quot;: this.log(data[1]); break;
        case &quot;JOIN&quot;: this.join(data[1]); break;
        case &quot;LEAVE&quot;: this.leave(data[1]); break;
        case &quot;WELCOME&quot;: this.welcome(data[1]); break;
        case &quot;SIGNEDIN&quot;: this.signedin(); break;
    }
};</pre><p></p>
<p>And here are the individual read events triggered by <strong>this.onRead</strong>:</p>
<p></p><pre class="crayon-plain-tag">/*
 * read event handlers
 */
this.newLetters = function(data) {
    for (var i = 0; i &amp;lt; 7; i++) {
        this.letters[i].__letter = data[i];
        this.letters[i].setText(data[i]);
    }
};

this.score = function(data) {
    this.log(data[0] + &quot; has &quot; + data[1] + &quot; points!&quot;);
};

this.join = function(data) {
    this.log(data[0] + &quot; joined!&quot;);
};

this.leave = function(data) {
    this.log(data + &quot; left!&quot;);
};

this.welcome = function(data) {
    this.log(&amp;#039;welcome: &amp;#039; + data);
    this.newLetters(data[0]);
};

this.signedin = function() {
    this.startBtn.removeFromSuperview();
    this.game.canHandleEvents(true);
    this.game.show();
};</pre><p></p>
<p>And it works!</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/04/debugger.png" alt="debugger" width="643" height="420" class="aligncenter size-full wp-image-394" /></p>
<p>Woohoo!</p>
<h2>The Whole Shebang</h2>
<p>That&#8217;s the whole game. Done.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/04/game.png" alt="game" width="400" height="225" class="aligncenter size-full wp-image-395" /></p>
<p>The project lives at <a href="https://github.com/gameclosure/wordrace">this github repo</a>. If you feel so inclined, install <a href="https://github.com/gameclosure/wordrace/blob/master/wordrace.apk">this APK</a> on your phone and play against your friends and <a href="http://mariobalibrera.com/wordrace.html">others on the site</a>. Trust me, it&#8217;s somewhat fun.</p>
<h2>The Point</h2>
<p>What I&#8217;m trying to get across here is that multiplayer games aren&#8217;t rocket science. All you have to do is come up with a protocol &#8212; even a dumb, asymmetrical protocol &#8212; and stick to it. The vast majority of your code doesn&#8217;t even have to know about it.</p>
<h3>Upstream</h3>
<p>No one on the client side has any idea what upstream communication looks like, except for one magical function. Check out <strong>this.send</strong>:</p>
<p></p><pre class="crayon-plain-tag">this.send = function(data) {
    this.log('sending: ' + data);
    this.sock.send(data + &quot;:&quot;);
};</pre><p></p>
<p>There it is: <strong>this.sock.send(data + &#8220;:&#8221;);</strong>. That&#8217;s all it takes to define a colon-delimited upstream protocol. Here&#8217;s the matching line in the Python server code:</p>
<p></p><pre class="crayon-plain-tag">self.conn.set_rmode_delimiter(DELIM, self.__parse_input)</pre><p></p>
<p><strong>DELIM</strong> is a colon, and <strong>self._&#95;parse&#95;input</strong> is the input handler. Thus, the server knows that incoming frames are separated by colons. Simple, right?</p>
<h3>Downstream</h3>
<p>Jumping back to our <strong>Application.js</strong>, behold <strong>this.connect</strong>:</p>
<p></p><pre class="crayon-plain-tag">this.connect = function() {
    this.log(&quot;connect&quot;);
    import gc.native.socketTransport as socketTransport;
    this.sock = new socketTransport.Socket('mariobalibrera.com', 9999);
    this.sock.reader.setMode('json');
    this.sock.onError = bind(this, 'onError');
    this.sock.onClose = bind(this, 'onClose');
    this.sock.onConnect = bind(this, 'onConnect');
    this.sock.onRead = bind(this, 'onRead');
};</pre><p></p>
<p>Every DevKit socket comes with a reader. It has three read modes:</p>
<ul>
<li><strong>stream</strong>: pass all data along to <strong>onRead</strong> handler (default)</li>
<li><strong>json</strong>: buffer until you see a JSON object and forward to <strong>onRead</strong> handler</li>
<li><strong>delimiter</strong>: read until you see some string and forward to <strong>onRead</strong> handler</li>
</ul>
<p>The reader essentially eats a stream of characters and expels frames consistent with the read mode. It sits between the native socket&#8217;s read stream and the JavaScript socket&#8217;s <strong>onRead</strong> callback. By default, it forwards every new chunk of data immediately. This is called <strong>stream</strong> mode.</p>
<p>Here, we want <strong>json</strong> mode. Thanks to <a href="https://github.com/gameclosure/gcapi/blob/master/src/native/reader.js">reader.js</a>, a mere <strong>this.sock.reader.setMode(&#8216;json&#8217;);</strong> clearly instructs the client-side socket to deliver you JSON objects as they arrive. All the server needs to do is write stringified JSON.</p>
<h2>Final Words</h2>
<p>Our socket works great on phones, but not at all in the browser, because browsers and real-deal sockets don&#8217;t mix. If this makes you sad, simply use a WebSocket in the browser and a real socket on the phone. You can either write a server that speaks WebSocket <em>and</em> regular stream-speak, or point your browser version at a WebSocket proxy (examples: <a href="https://github.com/mcolyer/em-websocket-proxy">1</a>, <a href="https://code.google.com/p/dez/source/browse/trunk/dez/network/websocket.py">2</a>).</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/04/socket.png" alt="socket" width="200" height="200" class="aligncenter size-full wp-image-397" /></p>
<p>If you don&#8217;t feel like doing that, build your game using the GC Test App (<a href="http://doc.gameclosure.com/native/android-test-app.html">Android</a>, <a href="http://doc.gameclosure.com/native/ios-test-app.html">iOS</a>), which is pretty much just as fast as developing in the browser. Now go forth and craft the finest multiplayer games the world has ever seen!</p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/04/multiplayer-word-game/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Add Offline Documentation in 15 Minutes</title>
		<link>http://www.gameclosure.com/blog/2013/03/add-offline-documentation-in-15-minutes</link>
		<comments>http://www.gameclosure.com/blog/2013/03/add-offline-documentation-in-15-minutes#comments</comments>
		<pubDate>Fri, 29 Mar 2013 03:51:23 +0000</pubDate>
		<dc:creator>Chris Taylor</dc:creator>
				<category><![CDATA[GC DevKit]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[docs]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[offline]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=366</guid>
		<description><![CDATA[Your customers want offline documentation. They want to be able to use your product on an airplane and look at the docs. They want to be anywhere and everywhere and they want to take you with them. Too bad it&#8217;s unmaintainable, risky, and complicated. Or.. Is it really? You developed the best application in your [...]]]></description>
				<content:encoded><![CDATA[<p>Your customers want offline documentation. They want to be able to use your product on an airplane and look at the docs. They want to be anywhere and everywhere and they want to take you with them. <strong>Too bad it&#8217;s unmaintainable, risky, and complicated.</strong></p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/unplug-me-fb-small.jpg" alt="unplug-me-fb-small" width="480" height="325" class="aligncenter size-full wp-image-368" /></p>
<h2>Or.. Is it really?</h2>
<p>You developed the best application in your space and now you&#8217;re looking at how to make it accessible. &#8212; <em>That means documentation!</em> If you&#8217;re like us, you found <a href="http://johnmacfarlane.net/pandoc/">pandoc</a>, did your documentation in markdown, and wrote a build script to compile it to static HTML.</p>
<p>Then, like us, you probably sat down and scratched your head for a bit and decided it was too much work to bake your HTML for each release, or decided it&#8217;s not worth <strong>bloating</strong> the download.</p>
<p>We found a great solution for implementing offline docs using HTML5 that is:</p>
<ul>
<li>Easy to do (took us 30 minutes)</li>
<li>Makes minimal changes</li>
<li>Safe to deploy</li>
</ul>
<h2>The Magic Formula</h2>
<p>There are only three easy steps to adding this useful feature to your docs:</p>
<ul>
<li>Create an index-offline.html from your index.html file.</li>
<li>Add a cache.manifest file generator to your docs build script.</li>
<li>Configure your web server.</li>
</ul>
<p>Use an <a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5 cache manifest</a> attached to an index-offline.html file. This is like your normal index.html except that your leading <code>&lt;html&gt;</code> tag looks like this: <code>&lt;html manifest="cache.manifest"&gt;</code>. Then have your doc build script create a cache manifest. Here&#8217;s how we did it in bash:</p>
<p></p><pre class="crayon-plain-tag">echo &quot;CACHE MANIFEST&quot; &gt; $OUT_ROOT/cache.manifest
        echo &quot;# Revision `date +%s`&quot; &gt;&gt; $OUT_ROOT/cache.manifest
        echo &quot;CACHE:&quot; &gt;&gt; $OUT_ROOT/cache.manifest
        cd $OUT_ROOT &amp;&amp; find . -type f \( -iname &quot;*.htm*&quot; -o -iname &quot;*.js&quot; -o -iname &quot;*.css&quot; \) -print &gt;&gt; ./cache.manifest &amp;&amp; cd $DOC_ROOT
        echo &quot;NETWORK:&quot; &gt;&gt; $OUT_ROOT/cache.manifest
        echo &quot;*&quot; &gt;&gt; $OUT_ROOT/cache.manifest</pre><p></p>
<p>The resulting <code>cache.manifest</code> looks like this:</p>
<p></p><pre class="crayon-plain-tag">CACHE MANIFEST
        # Revision 1362454455
        CACHE:
        ./api/animate.html
        ./api/appengine.html
        &hellip;
        NETWORK:
        *</pre><p></p>
<p>The <code>NETWORK</code> tag above is needed so that jquery, Google Analytics, and other off-site resources still work!</p>
<p>And the <code>Revision</code> counter is important to keep the file fresh each time you build.</p>
<h2>Configuring nginx (for example)</h2>
<h4>Add MIME Type: text/cache-manifest</h4>
<p>We modified <code>/usr/local/etc/nginx/mime.types</code> to include:</p>
<p></p><pre class="crayon-plain-tag">text/cache-manifest                   manifest;</pre><p></p>
<h4>Add Cache-Control: no-cache</h4>
<p>We modified <code>/usr/local/etc/nginx/nginx.conf</code> to look like this example:</p>
<p></p><pre class="crayon-plain-tag">location / {
                    root   /Users/cat/cleanroom/doc/html;
                    index  index.html index.htm;
    
                    location ~* \.(manifest)$ {
                        expires -1;
                    }
                }</pre><p></p>
<p>If you get a 404 from curl testing it&#8217;s because you put the location outside of /. It&#8217;s important to nest location tags as in the above example.</p>
<h4>Test it: curl</h4>
<p>The <code>expires -1;</code> tells nginx to add a <code>Cache-Control: no-cache</code> to the response, as shown below. Also note that the <code>Content-Type</code> has been set to <code>text/cache-manifest</code>.</p>
<p></p><pre class="crayon-plain-tag">$ curl http://localhost:8080/cache.manifest -I
    
        HTTP/1.1 200 OK
        Server: nginx/1.2.6
        Date: Tue, 05 Mar 2013 06:39:23 GMT
        Content-Type: **text/cache-manifest**
        Content-Length: 5112
        Last-Modified: Tue, 05 Mar 2013 03:34:15 GMT
        Connection: keep-alive
        Expires: Tue, 05 Mar 2013 06:39:22 GMT
        Cache-Control: **no-cache**
        Accept-Ranges: bytes</pre><p></p>
<p>The <code>curl -I</code> command was perfect for testing.</p>
<h2>Ship it!</h2>
<p>Testing it was pretty easy on Mac with <em>brew</em>. We ran <code>brew install nginx</code> and made the above changes, and tested with <code>curl</code>. Then we deployed it to our website. We deployed with confidence because we had already tested the changes (which are minor), and the changes only affect <code>index-offline.html</code>.</p>
<p>To hook it up, point the webkit view in your app towards <code>http://docs.mysite.com/index-offline.html</code> instead of <code>http://docs.mysite.com/</code> and you&#8217;re all set.</p>
<p>Users that install your app will hit <code>index-offline.html</code>, the attached manifest will have their browser cache the whole documentation site in the background, and then they can unplug and go anywhere with it. Whenever your documentation is rebuilt, the <code>cache.manifest</code> file revision rolls, and their browser will download the changes as normal. Great!</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/html5.png" alt="html5" width="256" height="256" class="aligncenter size-full wp-image-367" /></p>
<p>It was <strong>eye opening</strong> to us that such a wonderful feature like offline documentation can be had for free thanks to HTML5. We have found a bunch of other great ways to exploit HTML5 features to simplify our release process for the <a href="http://www.gameclosure.com/">Game Closure DevKit</a> and are looking forward to sharing them. As we have time we&#8217;ll write up some of the better ones over the next few weeks.</p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/03/add-offline-documentation-in-15-minutes/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Space Blaster Meets Mobile</title>
		<link>http://www.gameclosure.com/blog/2013/03/space-blaster-meets-mobile</link>
		<comments>http://www.gameclosure.com/blog/2013/03/space-blaster-meets-mobile#comments</comments>
		<pubDate>Sat, 23 Mar 2013 00:41:13 +0000</pubDate>
		<dc:creator>Mario Balibrera</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=289</guid>
		<description><![CDATA[I recently discovered a sort of unbelievable game development platform by Scirra called Construct 2. Using this tool you can basically create an entire game without any programming whatsoever. It&#8217;s pretty darn neat. Space Blaster is one of their demo games. You can find it on the Chrome Web Store, as well as Facebook. After [...]]]></description>
				<content:encoded><![CDATA[<p>I recently discovered a sort of unbelievable game development platform by <a href="https://www.scirra.com/">Scirra</a> called <a href="http://www.scirra.com/construct2">Construct 2</a>. Using this tool you can basically create an entire game without any programming whatsoever. It&#8217;s pretty darn neat.</p>
<p><a href="http://www.scirra.com/construct2/demos/space-blaster">Space Blaster</a> is one of their demo games. You can find it on the <a href="https://chrome.google.com/webstore/detail/space-blaster/lgaehcefpgklgofcgfamgnfpnmcfbfmp?hl=en">Chrome Web Store</a>, as well as <a href="http://apps.facebook.com/197624256970598/">Facebook</a>. After playing a few rounds, I wanted to try it out on my Nexus 4. I downloaded Construct 2, opened up Space Blaster (which ships with Construct 2 as an example), and exported an HTML5 app. It looked like this:</p>
<p></p><pre class="crayon-plain-tag">SpaceBlaster
|-- c2runtime.js
|-- index.html
|-- jquery-1.7.1.min.js
|-- logo.png
|-- offline.appcache
|-- images
|-- media</pre><p></p>
<p>I ran:</p>
<p></p><pre class="crayon-plain-tag">$ python -m SimpleHTTPServer</pre><p></p>
<p>This is where my troubles began.</p>
<h2>Mobile Browsers are for Reading Email</h2>
<p>I opened Space Blaster in a browser on my phone and almost immediately started crying. The first thing I noticed was how laggy it was. The frame rate was so low that my bullets were passing right through enemy ships. The second thing I noticed was the absence of sound. Then it crashed.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/flip.jpg" alt="flip" width="163" height="200" class="alignleft size-full wp-image-311" /></p>
<p>This bummed me out a little bit because the actual game is super fun. It&#8217;s got great sound effects, and the animations are very impressive when they actually play smoothly. Then I got a little mad, because I should know better. Playing a game in a modern mobile browser is like reading the news on a flip phone or sending an email with a beeper.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/beep.jpg" alt="beep" width="180" height="117" class="alignright size-full wp-image-307" /></p>
<p>Any of these can be attempted, but why? The basic reason, I suppose, is that folks insist on doing everything on the go, which means working with the materials at hand, no matter how terrible they are. I find myself in a similar situation, the bearer of an HTML5 canvas game that I yearn to play on my phone. Luckily, I work at a company that makes a native-accelerated OpenGL canvas for running HTML5 games on mobile.</p>
<h2>Why Would Anyone Do This?</h2>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/enemies.png" alt="enemies" width="300" height="300" class="alignright size-full wp-image-308" /></p>
<p>Let&#8217;s step back for a second and really appreciate what Construct 2 has to offer. It enables someone with <em>zero coding experience</em> to create a complete HTML5 game. Is your mind blown yet? It really should be. Think of all the sweet game ideas that at this very moment are bouncing around in people&#8217;s heads, and how many of those people aren&#8217;t programmers. Five years ago, these ideas would never see the light of day. Nowadays, thanks to frameworks like Construct 2, they really can become games. That&#8217;s truly awesome.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/mines.png" alt="mines" width="300" height="300" class="alignleft size-full wp-image-313" /></p>
<p>So where does Game Closure fit in? It&#8217;s quite simple. Essentially, lots of people (including Construct 2 users) are creating HTML5 games that run awesomely in real browsers and terribly in mobile browsers. We&#8217;ve <em>already solved this problem</em> with a custom native implementation of the HTML5 canvas. If we can leverage our technology to help bridge this gap, we can bring these games to a much wider audience. If we can streamline the process, folks will be able to make HTML5 games using any framework out there and deploy them to smart phones with ease. This degree of compatibility, after all, is the point of HTML5 and open standards in general.</p>
<p>Step one is porting Space Blaster.</p>
<h2>Getting Something on the Screen</h2>
<h3>Basic Setup</h3>
<p>I made a fresh game with basil in <code>devkit/projects</code>, and pulled in the JavaScript and images I figured we&#8217;d need from Space Blaster:</p>
<p></p><pre class="crayon-plain-tag">$ basil init scblaster
Created a new empty project at scblaster
  [register]    adding scblaster
$ cp ~/SpaceBlaster/*js scblaster/src/
$ cp ~/SpaceBlaster/images/* scblaster/resources/images</pre><p></p>
<p>My src folder now contained 3 files: the <code>Application.js</code> generated by <code>basil init</code>; <code>c2runtime.js</code>, where the Space Blaster game lived; and <code>jquery-1.7.1.min.js</code>, which Space Blaster seemed to require (and which I renamed to <code>jq.js</code> for ease of importing). I opened up <code>Application.js</code> and <code>manifest.json</code> and started tinkering.</p>
<p>Step one was to get something running in the browser. First I changed the game&#8217;s orientation from landscape to portrait. This simply entailed replacing the string <code>landscape</code> with <code>portrait</code> in the <code>supportedOrientations</code> array in <code>manifest.json</code>. Easy peasy.</p>
<p>Next I turned to <code>Application.js</code>, which looked like this:</p>
<p></p><pre class="crayon-plain-tag">import ui.TextView as TextView;

exports = Class(GC.Application, function () {

    this.initUI = function () {
        var textview = new TextView({
            superview: this.view,
            layout: &quot;box&quot;,
            text: &quot;Hello, world!&quot;,
            color: &quot;white&quot;
        });
    };
    
    this.launchUI = function () {};
});</pre><p></p>
<p>Great. I deleted <code>initUI</code> and replaced the <code>TextView</code> import at the top with a couple imports of our own:</p>
<p></p><pre class="crayon-plain-tag">import src.jq;
import src.c2runtime;

exports = Class(GC.Application, function () {

    this.launchUI = function () {
        // do something here!
    };
});</pre><p></p>
<p>At this point it ran with no errors and transitioned from a GC splash to a black screen. What fun! Now we just need the actual game.</p>
<h3>Digging, Lying, and Cheating</h3>
<p>So how do you start this thing? A quick scan of the <code>index.html</code> generated by Construct 2 reveals the magic line to get the show on the road:</p>
<p></p><pre class="crayon-plain-tag">cr_createRuntime(&quot;c2canvas&quot;);</pre><p></p>
<p>A search for this function in <code>c2runtime.js</code> takes us to this code:</p>
<p></p><pre class="crayon-plain-tag">cr.createRuntime = function (canvasid)
{
    return new Runtime(document.getElementById(canvasid));
};
cr.createDCRuntime = function (w, h)
{
    return new Runtime({ &quot;dc&quot;: true, &quot;width&quot;: w, &quot;height&quot;: h });
};
window[&quot;cr_createRuntime&quot;] = cr.createRuntime;
window[&quot;cr_createDCRuntime&quot;] = cr.createDCRuntime;</pre><p></p>
<p>Seems straightforward enough. They&#8217;ve got this <code>cr.createRuntime</code> thing, and they attach it to the window object as <code>cr_createRuntime</code>. Fantastic. The only problem is that they expect to pull a canvas out of the DOM using an ID. There&#8217;s no DOM on the phone, so this approach won&#8217;t work. But wait! There&#8217;s that other function, <code>createDCRuntime</code> (attached to window as <code>cr_createDCRuntime</code>), which just takes a <code>width</code> and <code>height</code>. Worth a shot! I added</p>
<p></p><pre class="crayon-plain-tag">cr_createDCRuntime();</pre><p></p>
<p>to my previously-empty <code>launchUI</code>, leaving <code>width</code> and <code>height</code> undefined because the constructor resizes the canvas to the max dimensions available, which is what we want. I ran it again and immediately got an error:</p>
<p></p><pre class="crayon-plain-tag">Cannot call method 'addEventListener' of undefined</pre><p></p>
<p>Fair enough. Construct 2 barfed while trying to route input events to their handlers. You guys didn&#8217;t expect this to work right off the bat, did you? Anyhow, it seemed that the undefined variable was being set a few lines up, in this code chunk:</p>
<p></p><pre class="crayon-plain-tag">var elem = (this.runtime.fullscreen_mode &amp;gt; 0) ? document : this.runtime.canvas;
var elem2 = document;
if (this.runtime.isDirectCanvas)
    elem2 = elem = window[&quot;Canvas&quot;];
else if (this.runtime.isCocoonJs)
    elem2 = elem = window;</pre><p></p>
<p>So what&#8217;s <code>this.runtime.isDirectCanvas</code>? It gets set in the Runtime constructor, like so:</p>
<p></p><pre class="crayon-plain-tag">this.isDirectCanvas = !!canvas[&quot;dc&quot;];</pre><p></p>
<p>And what&#8217;s <code>canvas</code>? That&#8217;s just the object that gets passed in by <code>cr_createDCRuntime</code> (see above), and all it has on it are <code>width</code>, <code>height</code>, and <code>dc</code> (which equals <code>true</code>). So since we&#8217;re using <code>cr_createDCRuntime</code>, <code>isDirectCanvas</code> is definitely <code>true</code>, which means that <code>elem</code> and <code>elem2</code> get set to <code>window["Canvas"]</code>, which, according to the Chrome debugger, isn&#8217;t anything. So let&#8217;s make it something, and while we&#8217;re at it we can map our input events to Construct 2&#8242;s handlers.</p>
<p></p><pre class="crayon-plain-tag">// map our input events to Construct 2 handlers
var inputMap = {
    touchstart: &quot;onInputStart&quot;,
    touchmove: &quot;onInputMove&quot;,
    touchend: &quot;onInputSelect&quot;
};
window.Canvas = {
    addEventListener: bind(this, function(name, handler) {
        this[inputMap[name]] = function(e) {
            e.changedTouches = [{ pageX: e.pt[1].x, pageY: e.pt[1].y, identifier: 0 }];
            handler(e);
        };
    })
};</pre><p></p>
<p>Construct 2 will now add its event listeners directly to what it thinks is a &#8220;direct canvas&#8221; (which we know to be our shim object). Our shim in turn will create input callbacks that modify our input events (Construct 2 expects a &#8220;changedTouches&#8221; array) and pass them along to Construct 2&#8242;s handlers. Simple dimple!</p>
<p>Run it again and we get a different error, which means we&#8217;re making progress. This time, <code>AppMobi</code> is not defined, which makes sense because we&#8217;re not AppMobi. The error happens here:</p>
<p></p><pre class="crayon-plain-tag">this.ctx = AppMobi[&quot;canvas&quot;][&quot;getContext&quot;](&quot;2d&quot;);</pre><p></p>
<p>Construct 2 is trying to get a canvas from AppMobi. Time to lie:</p>
<p></p><pre class="crayon-plain-tag">// pretend to be AppMobi
window.AppMobi = {
    canvas: GC.app.engine.getCanvas()
};</pre><p></p>
<p>We&#8217;ve given them our canvas instead. The guilt will fade with time.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/pinoccio.jpg" alt="pinoccio" width="640" height="449" class="aligncenter size-full wp-image-316" /></p>
<p>Refresh for the next error. Now that Space Blaster has successfully gotten its hooks into our Context2D, it expects to find a function called <code>present</code>. Here&#8217;s where the game tries to call it:</p>
<p></p><pre class="crayon-plain-tag">Runtime.prototype.draw = function ()
{
    this.running_layout.draw(this.ctx);
    if (this.isDirectCanvas)
        this.ctx[&quot;present&quot;]();
};</pre><p></p>
<p>At this point I&#8217;m pretty happy that we&#8217;ve made it to the <code>draw</code> function. This just might work! So what&#8217;s <code>present</code>? Turns out it&#8217;s an AppMobi/DirectCanvas thing that gets called every tick to trigger a render. Our canvas knows how to render without this. Let&#8217;s cheat!</p>
<p></p><pre class="crayon-plain-tag">// pretend to be AppMobi (lie)
// pretend to support context.present (cheat)
var canvas = GC.app.engine.getCanvas();
var ctx = canvas.getContext('2d');
ctx.present = function() {};
window.AppMobi = {
    canvas: canvas
};</pre><p></p>
<p>Great! Refresh, next error here:</p>
<p></p><pre class="crayon-plain-tag">if (this.isDirectCanvas)
    AppMobi[&quot;webview&quot;][&quot;execute&quot;](&quot;onGameReady();&quot;);</pre><p></p>
<p>Oh man, this direct canvas is so demanding! Let&#8217;s just cheat again:</p>
<p></p><pre class="crayon-plain-tag">window.AppMobi = {
    canvas: canvas,
    webview: {
        execute: function() {}
    }
};</pre><p></p>
<p>This is fun.</p>
<h3>I Still Can&#8217;t See Anything</h3>
<p>Ok, now we&#8217;re getting an error in <code>ctx.drawImage</code>. This is because we haven&#8217;t told Construct 2 where the graphics are hiding. Let&#8217;s do it!</p>
<p>As it turns out, the whole game is defined in a JSON object at the bottom of <code>c2runtime.js</code>. In this case, the object is over ten thousand lines long. Anywho, the most recent error indicates that it&#8217;s trying to find an image at <code>images/background3-default-000.jpg</code>. The DevKit serves image assets in <code>resources/images</code>, so this is an easy fix. We just have to override <code>cr.getProjectModel</code>, which generates the game definition object. I added this to <code>launchUI</code>:</p>
<p></p><pre class="crayon-plain-tag">// import game and modify project model
jsio(&quot;external src.c2runtime import cr&quot;);
var oldGetProjModel = cr.getProjectModel;
function deepReplace (obj, search, replace) {
    if (isArray(obj)) {
        return obj.map(function (item) { return deepReplace(item, search, replace); });
    } else if (typeof obj == 'string') {
        return obj.replace(search, replace);
    } else {
        return obj;
    }
}
cr.getProjectModel = function() {
    var data = oldGetProjModel();
    
    // overwrite image asset paths
    data = deepReplace(data, /^images\//, &quot;resources/images/&quot;);
    
    return data;
};</pre><p></p>
<p>That <code>jsio</code> line at the top is some black magic for grabbing a local variable out of a JavaScript file. Since we&#8217;re importing <code>c2runtime</code> here, we can remove the import from the top of our <code>Application.js</code>. The rest basically remaps Space Blaster&#8217;s image sources to their new home in <code>resources/images</code>. When I run it again I get the same error:</p>
<p></p><pre class="crayon-plain-tag">Uncaught Error: IndexSizeError: DOM Exception 1</pre><p></p>
<p>This basically means it still can&#8217;t find the image it&#8217;s looking for. Let&#8217;s tell the DevKit not to build spritesheets for these assets, as they&#8217;ve already been sprited. Create a new file in <code>resources/images/</code> called <code>metadata.json</code>, and paste in this:</p>
<p></p><pre class="crayon-plain-tag">{ &quot;sprite&quot;: false }</pre><p></p>
<p>And it works!</p>
<h3>I Still Can&#8217;t Hear Anything</h3>
<p>Right, the original had sound, and lots of it. Let&#8217;s grab the audio assets we need.</p>
<p></p><pre class="crayon-plain-tag">$ cp -r ~/SpaceBlaster/media/ scblaster/resources/media</pre><p></p>
<p>Now we just need the game to look in the proper place. We&#8217;ll solve this the same way we handled image asset paths, by overwriting the project model.</p>
<p></p><pre class="crayon-plain-tag">cr.getProjectModel = function() {
    var data = oldGetProjModel();
    
    // overwrite asset paths
    data = deepReplace(data, /^images\//, &quot;resources/images/&quot;);
    data = deepReplace(data, /^media\//, &quot;resources/media/&quot;);
    
    return data;
};</pre><p></p>
<p>Refresh, and we&#8217;ve got sound!</p>
<h2>Wait, What About the Phone?</h2>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/phone.jpg" alt="phone" width="470" height="362" class="aligncenter size-full wp-image-315" /></p>
<p>Remember a million years ago when the whole point of this was to run Space Blaster on a phone? Let&#8217;s give it a shot. Plug an android phone into your computer and start typing in a terminal:</p>
<p></p><pre class="crayon-plain-tag">$ basil debug native-android --install</pre><p></p>
<p>Great!</p>
<h3>A Few More Fibs</h3>
<p>You just installed the game on your phone. If you try to run it, you&#8217;ll get a gross jQuery error:</p>
<p></p><pre class="crayon-plain-tag">{js} Reporting exception
./src/jq.js line: 2
,g,h,i,j,k,l,m,n,o,p,q=c.createElement(&quot;div&quot;),r=c.documentElement;q.setAttribu
TypeError: Cannot call method 'setAttribute' of undefined
at ./src/jq.js:2:17334
at ./src/jq.js:2:20984</pre><p></p>
<p>Man, I&#8217;ve heard enough out of you, jQuery. You worked fine in the browser, but now you expect a full DOM on the phone, and that&#8217;s just not going to happen. What exactly is this game doing with jQuery? I removed the jq import at the top of <code>Application.js</code> to find out.</p>
<p>It turns out that everything runs fine without jQuery, for the most part. The only thing missing is window size detection, which only happens if jQuery is present:</p>
<p></p><pre class="crayon-plain-tag">if (typeof jQuery !== &quot;undefined&quot; &amp;amp;&amp;amp; this.fullscreen_mode &amp;gt; 0)
    this[&quot;setSize&quot;](jQuery(window).width(), jQuery(window).height());</pre><p></p>
<p>So let&#8217;s fake it. Add this to <code>launchUI</code>:</p>
<p></p><pre class="crayon-plain-tag">window.jQuery = function(w) {
    return {
        width: function() {
            return w.innerWidth || w.screen.width;
        },
        height: function() {
            return w.innerHeight || w.screen.height;
        }
    };
};</pre><p></p>
<p>Looks good in the browser. After rebuilding and reinstalling on the phone, you&#8217;ll see this:</p>
<p></p><pre class="crayon-plain-tag">TypeError: Object # has no method 'getElementById', from ./src/c2runtime.js:1861</pre><p></p>
<p>Yup, there&#8217;s no DOM, so there&#8217;s no <code>document.getElementById</code>. Time for more lies!</p>
<p></p><pre class="crayon-plain-tag">document.getElementById = document.getElementById || function() { return null; };</pre><p></p>
<p>Don&#8217;t worry, no one ever has to know. Rebuild, reinstall, and see the next error:</p>
<p></p><pre class="crayon-plain-tag">TypeError: Cannot call method 'loadSound' of undefined, from ./src/c2runtime.js:9760</pre><p></p>
<p>Looks like we&#8217;ve got more shimming to do. Update <code>window.AppMobi</code> to look like this:</p>
<p></p><pre class="crayon-plain-tag">window.AppMobi = {
    canvas: canvas,
    context: {
        loadSound: function(src) {},
        playSound: function(src) {}
    },
    webview: {
        execute: function() {}
    }
};</pre><p></p>
<p>That&#8217;ll do it. Our <code>loadSound</code> doesn&#8217;t actually need to do anything, because our <code>AudioManager</code> can load everything we need up front. You&#8217;ll see.</p>
<h3>But Where&#8217;s the Game?</h3>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/waldo.jpg" alt="waldo" width="400" height="285" class="aligncenter size-full wp-image-318" /></p>
<p>Rebuild, reinstall, and run. The first and last thing you&#8217;ll notice after the GC splash is a black screen. This is because <code>alwaysRepaint</code> defaults to <code>true</code> on the GC engine. When <code>alwaysRepaint</code> is <code>true</code>, the engine draws every tick. Since we&#8217;re not doing any of the drawing, this just clears the canvas every tick, obliterating whatever Space Blaster just tried to draw. Let&#8217;s turn that off:</p>
<p></p><pre class="crayon-plain-tag">// turn off screen clearing
this.engine._opts.alwaysRepaint = false;</pre><p></p>
<p>Next thing you know you&#8217;re looking at the Space Blaster main menu on your phone. Yay! Before you pop the champaign, tap for the next error.</p>
<h3>Creating createPattern</h3>
<p>The problem:</p>
<p></p><pre class="crayon-plain-tag">TypeError: Object # has no method 'createPattern', from ./src/c2runtime.js:12059</pre><p></p>
<p><a href="https://developer.mozilla.org/samples/canvas-tutorial/4_11_canvas_createpattern.html">This example</a> demonstrates the basic usage of <code>createPattern</code>:</p>
<p></p><pre class="crayon-plain-tag">var ptrn = ctx.createPattern(img, 'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, 150, 150);</pre><p></p>
<p>It&#8217;s basically an image tiler with a funny API. Very doable. Here&#8217;s our 2D Context&#8217;s implementation of <code>fillRect</code>:</p>
<p></p><pre class="crayon-plain-tag">this.fillRect = function(x, y, width, height) {
    this._ctx.fillRect(x, y, width, height, this.fillStyle, this.getCompositeOperationID());
};</pre><p></p>
<p>Great, all we need is a <code>createPattern</code> that returns some kind of object, and a <code>this.fillStyle</code> test of some sort in <code>fillRect</code>, and we&#8217;re good to go. This <code>createPattern</code> should do the trick:</p>
<p></p><pre class="crayon-plain-tag">this.createPattern = function(img, repeatPattern) {
    return {
        img: img,
        repeatPattern: repeatPattern
    };
};</pre><p></p>
<p>Now let&#8217;s just handle this case in <code>fillRect</code>:</p>
<p></p><pre class="crayon-plain-tag">this.fillRect = function(x, y, width, height) {
    if (typeof this.fillStyle == 'object') {
        var img = this.fillStyle.img,
            w = img.width, h = img.height,
            wMax, hMax, xx, yy,
            op = this.getCompositeOperationID();
        switch (this.fillStyle.repeatPattern) {
            case 'repeat':
                for (xx = 0; xx &amp;lt; width; xx += w) {
                    wMax = Math.min(w, width - xx);
                    for (yy = y; yy &amp;lt; height; yy += h) {
                        hMax = Math.min(h, height - yy);
                        this._ctx.drawImage(img.__gl_name, img._src, 0, 0, wMax, hMax, x + xx, y + yy, wMax, hMax, op);
                    }
                }
                break;
            case &amp;#039;repeat-x&amp;#039;:
                for (xx = 0; xx &amp;lt; width; xx += w) {
                    wMax = Math.min(w, width - xx);
                    this._ctx.drawImage(img.__gl_name, img._src, 0, 0, wMax, hMax, x + xx, y, wMax, hMax, op);
                }
                break;
            case &amp;#039;repeat-y&amp;#039;:
                for (yy = 0; yy &amp;lt; height; yy += h) {
                    hMax = Math.min(h, height - yy);
                    this._ctx.drawImage(img.__gl_name, img._src, 0, 0, wMax, hMax, x, y + yy, wMax, hMax, op);
                }
                break;
            case &amp;#039;no-repeat&amp;#039;:
            default:
                wMax = Math.min(w, width);
                hMax = Math.min(h, height);
                this._ctx.drawImage(img.__gl_name, img._src, 0, 0, wMax, hMax, x, y, wMax, hMax, op);
                break;
        }
    } else {
        this._ctx.fillRect(x, y, width, height, this.fillStyle, this.getCompositeOperationID());
    }
};</pre><p></p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/red1-180x300.png" alt="red" width="180" height="300" class="alignleft size-medium wp-image-317" /><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/missiles-180x300.png" alt="missiles" width="180" height="300" class="alignright size-medium wp-image-314" /></p>
<p>That&#8217;s all it takes! Now the DevKit supports <code>createPattern</code> invocations of various kinds: &#8216;repeat&#8217;, &#8216;repeat-x&#8217;, &#8216;repeat-y&#8217;, and the pointless &#8216;no-repeat&#8217;. Here&#8217;s a before and after. The <code>createPattern</code> on the left returns the string &#8220;red&#8221;. The <code>createPattern</code> on the right returns the object discussed above. Just look at all those missiles! Nice work, <code>createPattern</code>.</p>
<p>And now we&#8217;ve got a game! Wooo! Unfortunately, our game has the following problems:</p>
<ul>
<li>the screen goes black when you touch it</li>
<li>there&#8217;s no sound</li>
<li>some of the images are having transparency issues</li>
</ul>
<p>These are hard core dealbreakers. Luckily, they&#8217;re easy to fix.</p>
<h3>Black Screen on Touch?</h3>
<p>This is due to another flag on the GC engine. Remember <code>alwaysRepaint</code>? There&#8217;s another engine flag that defaults to <code>true</code> called <code>repaintOnEvent</code>. The idea with this flag is that in cases when you&#8217;re <em>not</em> repainting every tick (<code>alwaysRepaint</code> == <code>false</code>), you&#8217;ll probably want to repaint when the user taps the screen (which generally results in some visual difference). Since we&#8217;re not doing any of the drawing, this behavior will simply result in a black screen whenever the user taps. So let&#8217;s turn it off. Add</p>
<p></p><pre class="crayon-plain-tag">this.engine._opts.repaintOnEvent = false;</pre><p></p>
<p>to <code>launchUI</code>, and you&#8217;re in business! Now take a break to play a few rounds. Yes, this is JavaScript, and yes, it actually works. Let that sink in before moving on to the next issue.</p>
<h3>Sound?</h3>
<p>Ok, so we copied over the Space Blaster audio assets to our new project. They&#8217;re running fine in the browser, but we&#8217;ll have to roll our own sound support to get a peep out of the phone. Luckily, the DevKit already did this for us.</p>
<p>We&#8217;ve got two copies of each sound: an <code>m4a</code>, which is played in the browser; and an <code>ogg</code>, which is played on the phone. We want file names without any spaces or weird punctuation, because this simplifies our <a href="http://doc.gameclosure.com/api/audio.html"><code>AudioManager</code> configuration</a>. So I made a simple Python script that looks like this:</p>
<p></p><pre class="crayon-plain-tag">from subprocess import call

print 'replacing dashes with underscores and sanitizing'
call('rename -s - _ resources/media/*ogg -z', shell=True)</pre><p></p>
<p>And ran it like this:</p>
<p></p><pre class="crayon-plain-tag">$ python fixAudio.py 
replacing dashes with underscores and sanitizing</pre><p></p>
<p>Great! Now we can just drop in our <code>AudioManager</code>, which looks like this:</p>
<p></p><pre class="crayon-plain-tag">// set up our sound manager
var sound = new AudioManager({
    path: 'resources/media',
    preload: true,
    files: {
        epicarpg: {
            background: true
        },
        explosion_1: {},
        explosion_2: {},
        explosion_3: {},
        explosion_4: {},
        jetloop1: {},
        lazer_fire_1: {},
        lazer_ricochet: {},
        mattoglseby___3: {
            background: true
        },
        retrolaser1: {},
        retrolaser2: {},
        squaremotif1: {},
        tronblast1: {},
        upgrade1: {}
    }
});</pre><p></p>
<p>Remember when we shimmed <code>loadSound</code> with a function that didn&#8217;t do anything? That&#8217;s ok because of the <code>preload: true</code> here, which loads up all the sound effects for us. Also, I flagged the music files (<code>epicarpg</code> and <code>mattoglseby___3</code>) with <code>background: true</code>. This guarantees two things:</p>
<ul>
<li>these songs won&#8217;t preload (this would take up memory and time, and is unnecessary, as music files are streamed)</li>
<li>these songs won&#8217;t play at the same time (playing one stops the other)</li>
</ul>
<p>Don&#8217;t forget to import <code>AudioManager</code> at the top of <code>Application.js</code>:</p>
<p></p><pre class="crayon-plain-tag">import AudioManager;</pre><p></p>
<p>Cool. Now let&#8217;s hook up our <code>AudioManager</code> to the AppMobi shim:</p>
<p></p><pre class="crayon-plain-tag">// pretend to be AppMobi
window.AppMobi = {
    canvas: canvas,
    context: {
        loadSound: function(src) {},
        playSound: function(src) {
            sound.play(src.slice(16).replace(/ /g, '_').replace(/-/g, '_').replace('.ogg', ''));
        }
    },
    webview: {
        execute: function() {}
    }
};</pre><p></p>
<p>And it&#8217;s a game! With sound! Woohoo!</p>
<h3>What&#8217;s with the Black Boxes?</h3>
<p>Here&#8217;s a funny one. As it turns out, some of Space Blaster&#8217;s graphic assets use regular transparency, and others just have a black background. Silly game developers! Here are two explosion spritesheets from the game:</p>
<p>exlosion1-sheet0.png, exlosion2-sheet0.png:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/explosion1-sheet0.png" alt="explosion1-sheet0" width="187" height="187" class="alignleft size-full wp-image-309" /><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/explosion2-sheet0.png" alt="explosion2-sheet0" width="187" height="175" class="alignleft size-full wp-image-310" /></p>
<p>See what I mean? The quickest fix here is an <code>ImageMagick</code> batch conversion, a la this script:</p>
<p></p><pre class="crayon-plain-tag">import os
from subprocess import call

def process(targets, dirname, fnames):
    print &quot;replacing black backgrounds with transparency&quot;
    for target in targets:
        hits = [os.path.join(dirname, fname) for fname in fnames if fname.startswith(target)]
        for fpath in hits:
            print ' - converting', fpath
            call('convert -transparent black -fuzz 10%% %s png32:%s'%(fpath, fpath), shell=True)

os.path.walk('resources/images', process, ['explosion1', 'explosion3', 'playerthrust'])</pre><p></p>
<p>It finds all the graphics with names that start with &#8220;explosion1&#8243;, &#8220;explosion3&#8243;, and &#8220;playerthrust&#8221; (the other images use regular transparency), and uses <code>convert</code> (<code>ImageMagick</code>&#8216;s command-line utility) to replace black with transparency. Run it:</p>
<p></p><pre class="crayon-plain-tag">$ python fixImages.py 
replacing black backgrounds with transparency
 - converting resources/images/explosion1-sheet0.png
 - converting resources/images/explosion1-sheet1.png
 - converting resources/images/explosion1-sheet2.png
 - converting resources/images/explosion1-sheet3.png
 - converting resources/images/explosion1-sheet4.png
 - converting resources/images/explosion3-sheet0.png
 - converting resources/images/explosion3-sheet1.png
 - converting resources/images/explosion3-sheet10.png
 - converting resources/images/explosion3-sheet11.png
 - converting resources/images/explosion3-sheet12.png
 - converting resources/images/explosion3-sheet13.png
 - converting resources/images/explosion3-sheet14.png
 - converting resources/images/explosion3-sheet15.png
 - converting resources/images/explosion3-sheet2.png
 - converting resources/images/explosion3-sheet3.png
 - converting resources/images/explosion3-sheet4.png
 - converting resources/images/explosion3-sheet5.png
 - converting resources/images/explosion3-sheet6.png
 - converting resources/images/explosion3-sheet7.png
 - converting resources/images/explosion3-sheet8.png
 - converting resources/images/explosion3-sheet9.png
 - converting resources/images/playerthrust-sheet0.png</pre><p></p>
<p>Great!</p>
<h2>Spit and Polish</h2>
<p>What&#8217;s left?</p>
<h3>Icon</h3>
<p>I used <a href="http://www.gimp.org/">the GIMP</a> to steal this image from one of the enemy spritesheets and resize as necessary:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/ios144.png" alt="ios144" width="144" height="144" class="aligncenter size-full wp-image-312" /></p>
<p>Setting the icon in <code>manifest.json</code> is easy:</p>
<p></p><pre class="crayon-plain-tag">&quot;icon&quot;: &quot;resources/icons/icon512.png&quot;,</pre><p></p>
<h3>Splash Screen</h3>
<p>This game asset seems sufficiently spaceish:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/background3-default-0001.jpg" alt="background3-default-000" width="400" height="400" class="aligncenter size-full wp-image-306" /></p>
<p>We can make this the splash screen with a few simple lines in <code>manifest.json</code>:</p>
<p></p><pre class="crayon-plain-tag">&quot;splash&quot;: {
    &quot;autoHide&quot;: true,
    &quot;universal&quot;: &quot;resources/images/background3-default-000.jpg&quot;
},</pre><p></p>
<h2>Retrospective</h2>
<p>We did it!</p>
<h3>What We Accomplished</h3>
<p>Here&#8217;s the <code>Application.js</code> we ended up with:</p>
<p></p><pre class="crayon-plain-tag">import AudioManager;

exports = Class(GC.Application, function () {

    this.launchUI = function () {
        // turn off screen clearing
        this.engine._opts.alwaysRepaint = false;
        this.engine._opts.repaintOnEvent = false;
        
        // map our input events to Construct 2 handlers
        var inputMap = {
            touchstart: &quot;onInputStart&quot;,
            touchmove: &quot;onInputMove&quot;,
            touchend: &quot;onInputSelect&quot;
        };
        window.Canvas = {
            addEventListener: bind(this, function(name, handler) {
                this[inputMap[name]] = function(e) {
                    e.changedTouches = [{ pageX: e.pt[1].x, pageY: e.pt[1].y, identifier: 0 }];
                    handler(e);
                };
            })
        };
        
        // set up our sound manager
        var sound = new AudioManager({
            path: 'resources/media',
            preload: true,
            files: {
                epicarpg: {
                    background: true
                },
                explosion_1: {},
                explosion_2: {},
                explosion_3: {},
                explosion_4: {},
                jetloop1: {},
                lazer_fire_1: {},
                lazer_ricochet: {},
                mattoglseby___3: {
                    background: true
                },
                retrolaser1: {},
                retrolaser2: {},
                squaremotif1: {},
                tronblast1: {},
                upgrade1: {}
            }
        });
        
        // pretend to support context.present
        var canvas = GC.app.engine.getCanvas();
        var ctx = canvas.getContext('2d');
        ctx.present = function() {};
        
        // pretend to be AppMobi
        window.AppMobi = {
            canvas: canvas,
            context: {
                loadSound: function(src) {},
                playSound: function(src) {
                    sound.play(src.slice(16).replace(/ /g, '_').replace(/-/g, '_').replace('.ogg', ''));
                }
            },
            webview: {
                execute: function() {}
            }
        };
        
        // import game and modify project model
        jsio(&quot;external src.c2runtime import cr&quot;);
        var oldGetProjModel = cr.getProjectModel;
        function deepReplace (obj, search, replace) {
            if (isArray(obj)) {
                return obj.map(function (item) { return deepReplace(item, search, replace); });
            } else if (typeof obj == 'string') {
                return obj.replace(search, replace);
            } else {
                return obj;
            }
        }
        cr.getProjectModel = function() {
            var data = oldGetProjModel();
            
            // overwrite asset paths
            data = deepReplace(data, /^images\//, &quot;resources/images/&quot;);
            data = deepReplace(data, /^media\//, &quot;resources/media/&quot;);
            
            return data;
        };
        
        // humor Construct 2 on native
        //  - fake getElementById
        //  - fake jQuery
        document.getElementById = document.getElementById || function() { return null; };
        window.jQuery = function(w) {
            return {
                width: function() {
                    return w.innerWidth || w.screen.width;
                },
                height: function() {
                    return w.innerHeight || w.screen.height;
                }
            };
        };
        
        cr_createDCRuntime();
    };
});</pre><p></p>
<p>And here&#8217;s the APK we ended up with: <a href="https://github.com/bubbleboy14/scblaster/blob/master/scblaster.apk">Space Blaster APK</a>.</p>
<p>The project lives at <a href="https://github.com/bubbleboy14/scblaster/">this github repo</a>. As it stands, you should be able to run any Construct 2 game on a phone by simply:</p>
<ul>
<li>1) exporting your Construct 2 game as an HTML5 app</li>
<li>2) cloning <a href="https://github.com/bubbleboy14/scblaster/">this github repo</a></li>
<li>3) replacing <code>src/c2runtime.js</code> with the <code>c2runtime.js</code> generated by Construct 2 for your game</li>
<li>4) replacing everything in <code>resources/images/</code> with the image assets from your game</li>
<li>5) replacing everything in <code>resources/media/</code> with the audio assets from your game
<ul>
<li>update the <code>AudioManager</code> in <code>Application.js</code> accordingly</li>
</ul>
</li>
<li>6) running <code>fixAudio.py</code> and/or <code>fixImages.py</code> if necessary
<ul>
<li>if you have to run <code>fixImages.py</code>, replace the target prefix array on line 12 with whatever prefixes correspond to images with a black background that should actually be transparent</li>
</ul>
</li>
</ul>
<p>I know that&#8217;s six whole steps. I want to simplify this process and probably turn this into some sort of plugin. I&#8217;ll keep you guys posted.</p>
<h3>Why It Matters</h3>
<p>To put this in perspective, consider the general case of porting a game from one platform to another. In fact, look at what <a href="http://www.bit-tech.net/gaming/2009/08/18/the-problem-with-porting-games/1">this guy</a> has to say about it:</p>
<blockquote><p>You don&#8217;t need to be a 1970s stand-up comedian to know that there&#8217;s a large lexicon of monosyllabic, four-letter words for describing something you don&#8217;t like – but only PC gamers use the word “port” with such a fervent degree of repulsion.</p></blockquote>
<p>Basically, he hates it, and so does everyone else, because it&#8217;s hard and it usually involves a rewrite. Now, we just took a game that only runs in a desktop browser, wrote about 100 lines of JavaScript, and came out the other end with a game that runs smoothly on Android and iOS. Did we rewrite the entire thing in Java and Objective-C? Did we hire a team of developers and set aside months of dev time? No dude, not even close. It took one developer a couple days to figure this one out, and the next Construct 2 port will take a matter of minutes.</p>
<p>The big takeaway here is that when we use open standards, we get to pool resources. I didn&#8217;t write Space Blaster, and Scirra didn&#8217;t write the DevKit, but they play nice together because we both bought in to the &#8220;HTML5&#8243; idea. And so have lots of other game engines. This means that you should continue to develop your HTML5 games using any framework that tickles your fancy, because when the time comes, you can easily deploy to mobile using our native canvas. Isn&#8217;t that great? I think so.</p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/03/space-blaster-meets-mobile/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unravelling Nested Callbacks with FF</title>
		<link>http://www.gameclosure.com/blog/2013/03/unravelling-nested-callbacks-with-ff</link>
		<comments>http://www.gameclosure.com/blog/2013/03/unravelling-nested-callbacks-with-ff#comments</comments>
		<pubDate>Thu, 21 Mar 2013 21:00:50 +0000</pubDate>
		<dc:creator>Michael Henretty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=263</guid>
		<description><![CDATA[If you&#8217;re a javascript developer, then callback functions are your bread-and-butter. You know all about the so-called &#8220;pyramid of doom&#8221;, and you know all kinds of ways to defeat it. If you&#8217;re a javascript developer, you might regularly use a promise library like Q, or perhaps something more sequential like node async. Maybe you even [...]]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;re a javascript developer, then callback functions are your bread-and-butter. You know all about the so-called &#8220;pyramid of doom&#8221;, and you know all kinds of ways to defeat it. If you&#8217;re a javascript developer, you might regularly use a promise library like <a href="https://github.com/kriskowal/q">Q</a>, or perhaps something more sequential like <a href="https://github.com/caolan/async">node async</a>. Maybe you even get excited or angry when someone mentions co-routines. But if you&#8217;re a javascript developer, the last thing you ever wanted in life was another asynchronous flow control library. Well, it might be time to take another look.</p>
<h3>The Problem</h3>
<p>Let&#8217;s start with what we all know, callback hell:</p>
<p></p><pre class="crayon-plain-tag">db.authenticate(request, function (err, user) {
    analytics.trackVisit(user, function (err) {
        graph.addFriend(user, friend, function (err) {
            cache.cacheUser(user, function (err) {
                response.send(&quot;so many callbacks!!&quot;, user);
            });
        });
    });
});</pre><p></p>
<p>The problem with this is twofold. First, unless you have a really wide screen it is hard to read. But more importantly, as the logic grows more and more complex, code like this becomes difficult to reason about. For instance, what do we do when an important method like <code>addFriend</code> returns an error (can we still cache the userData)? What happens if an uncaught exception is thrown inside/outside the callback chain? How do we schedule multiple asynchronous operations at once and wait for them all to complete before continuing?</p>
<h3>The Workarounds</h3>
<p>There are a variety of ways to deal with the callback problem. One technique is to use a <a href="http://wiki.commonjs.org/wiki/Promises">promise</a> library. In a nutshell, promises ditch the callback paradigm in favor of an event based system. Using a method like <code>then</code>, you can register onSuccess and onError (and sometimes onProgress) handlers for your asynchronous operations. What makes this especially useful in terms of the &#8220;pyramid of doom&#8221; is that promises can be chained together. Let&#8217;s rewrite the nested callbacks above using the <a href="https://github.com/kriskowal/q">Q</a> library to see promises in action:</p>
<p></p><pre class="crayon-plain-tag">var user;

Q.nfcall(db.authenticate, request)
.then(function (userData) {
    user = userData; // make userData available to all success handlers
    return Q.nfcall(analytics.trackVisit, user);
})
.then(function () {
    return Q.nfcall(graph.addFriend, user, friend);
})
.then(function () {
    return Q.nfcall(cache.cacheUser, user);
})
.fin(function (err) {
    response.send(&quot;ahh, much better&quot;, user);
});</pre><p></p>
<p>In the above example, we used the <code>Q.nfcall</code> method to turn our asynchronous operations into promises. Then, in the onSuccess handlers, we return new promises representing the next async operation. In this way we are able to &#8220;schedule&#8221; a series of handlers for our asynchronous operations rather than simply nesting the callback functions. It is also important to note that in order to use <code>userData</code> across these handlers, we must declare the <code>user</code> variable in the enclosing scope, and set it in the <code>authenticate</code> success handler. Even still, the result is noticeably cleaner code than nested callbacks.</p>
<p>Another method for unravelling the pyramid is to use a generalized flow control library like <a href="https://github.com/caolan/async">async</a>. Let&#8217;s rewrite the above example using this library instead:</p>
<p></p><pre class="crayon-plain-tag">var user;

async.waterfall([
    function (next) {
        db.authenticate(request, next);
    },
    function (userData, next) {
        user = userData;
        graph.addFriend(user, friend, next);
    },
    function (next) {
        cache.cacheUser(user);
    }
], function (err) {
    response.send(&quot;feeling fine&quot;, user);
});</pre><p></p>
<p>Here we used the <code>async.waterfall</code> method to specify an array of functions that we want to run in order, and one at a time. Each function is given a <code>next</code> parameter, which we use to forward the results of the asynchronous operations to the proceeding function. Once again, we have to declare a <code>user</code> variable in the enclosing scope in order to use it throughout the handlers. In any case, a nice feature of <code>async.waterfall</code> is that all errors are forwarded to the final callback so you can deal with them all in one place. And again, the resulting code is much cleaner than using nested callbacks.</p>
<p>While both of these options are great, life-savers even, what happens when I want to intermingle series AND parallel operations? The logic using the aforementioned libraries can again become <a href="https://github.com/basicallydan/q-examples/blob/master/wait-for-multiple-promises.js">complex</a> and hard to read.</p>
<p>Luckily, there are other libraries out there that are specifically designed for this situation. Let&#8217;s have a look at <a href="http://github.com/creationix/step">Step</a>:</p>
<p></p><pre class="crayon-plain-tag">Step(
    function () {
        db.authenticate(request, this);
    },
    function (err, userData) {
        graph.addFriend(userData, friend, this.parallel());
        cache.cacheUser(userData, this.parallel());
        return userData;
    },
    function (err, userData) {
        response.send(&quot;like butter&quot;, userData);
    }
);</pre><p></p>
<p>Like <code>async.waterfall</code>, we are specifying a list of functions to be executed in serial order. But instead of invoking <code>next</code> to move on the proceeding function, we use the <code>this.parallel</code> method to tell the Step library to wait for the results from the current operations before moving on. When we want to pass data to the next function immediately, we simply return the variable and it will get passed as a parameter to the proceeding function. This way we do not have to declare a <code>user</code> variable in the enclosing scope, we can directly pass it to the following functions.</p>
<h3>FF</h3>
<p>Unfortunately, there are some drawbacks to the Step library. First, the <code>"this"</code> keyword is reserved by Step, so you cannot bind your functions to any specific context. This makes code hard to read and write when following OOP practices. Second, if you want to forward local data from one function to the next you need to return it, which means you are limited to passing one object at a time. Third, you have to manually handle errors in each function rather then being able to handle errors in one place (like we did with <a href="https://github.com/caolan/async">async</a>).</p>
<p><a href="https://twitter.com/creationix">Tim Caswell</a>, the original creator of Step, realized these limitations and created a <a href="https://gist.github.com/creationix/1524578">vision</a> of what Step would be like if he could rewrite it from scratch. The <a href="http://github.com/gameclosure/ff">ff library</a> is our extrapolation of this vision. Let&#8217;s see the above example rewritten in ff:</p>
<p></p><pre class="crayon-plain-tag">var f = ff(
    function () {
        db.authenticate(request, f.slot());
    },
    function (userData){
        graph.addFriend(userData, friend, f.wait());
        cache.cacheUser(userData, f.wait());
        f.pass(userData);
    },
    function (userData) {
        response.send(&quot;we did it!&quot;, userData);
    }
)

.onError(function (err) {
    console.log(&quot;Houston, we have an error&quot;, err);
});</pre><p></p>
<p>You&#8217;ll notice that ff does not rely on the <code>this</code> object, so you are free to run your code using any context you want. Also, using the <code>ff.pass</code> method we can forward as many variables as we want to the next function. This is more dynamic and flexible than relying on the <code>return</code> statement. Finally, if there are any errors returned in the callbacks (or even thrown during execution), we can deal with them all in one place by attaching an <code>.onError</code> handler.</p>
<p>Another interesting feature of ff is that it is entirely <a href="http://promises-aplus.github.com/promises-spec/">Promises/A+</a> compliant. This means if you have an existing framework that relies on the promise api, or if you just love the promise spec itself, you can still write your code that way:</p>
<p></p><pre class="crayon-plain-tag">var f = ff(
    function () {
        db.authenticate(request, f.slot());
    },
    function (userData) {
        ... // etc
    }
)

.then(
    function onSuccess(userData) {
        response.send(&quot;we did it!&quot;, userData);
    },
    function onError(err) {
        console.log(&quot;Houston, we have an error&quot;, err);
    }
);</pre><p></p>
<p>In the above code, we used the <code>then</code> method to specify how we wanted to handle our ff operation when it finished running of all its functions (or produced an error). For more information about promises, check out <a href="https://twitter.com/nathan_stott">Nathan Stott</a>&#8216;s excellent <a href="http://howtonode.org/promises">HowToNode Article</a>.</p>
<p>In any case, FF was designed to be a poweful, concise, and easy to read way of handling your asynchronous operations. If you&#8217;re interested in learning more about how FF works, check out the <a href="https://github.com/gameclosure/ff/blob/master/README.md">documentation</a>. Also, be sure to fork us on <a href="http://github.com/gameclosure/ff">github</a>, and come find us on <a href="http://twitter.com/gameclosure">twitter</a>.</p>
<p>Happy coding!</p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/03/unravelling-nested-callbacks-with-ff/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A Quick Look at PVRTC</title>
		<link>http://www.gameclosure.com/blog/2013/03/a-quick-look-at-pvrtc</link>
		<comments>http://www.gameclosure.com/blog/2013/03/a-quick-look-at-pvrtc#comments</comments>
		<pubDate>Sat, 16 Mar 2013 05:27:04 +0000</pubDate>
		<dc:creator>Chris Taylor</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[PNG]]></category>
		<category><![CDATA[PVRTC]]></category>
		<category><![CDATA[sprites]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=240</guid>
		<description><![CDATA[PVRTC is the image compression (like JPEG) that is built into PowerVR chips on iPhone and iPad devices. And, like JPEG, it should not be used for situations where you want lossless quality. It&#8217;s lossy. The current state of PVRTC is not suitable for beautiful, hand-drawn artwork. I decided to investigate the best that you [...]]]></description>
				<content:encoded><![CDATA[<p>PVRTC is the image compression (like JPEG) that is built into PowerVR chips on iPhone and iPad devices. And, like JPEG, it should not be used for situations where you want lossless quality. It&#8217;s lossy.</p>
<blockquote>
<p>The current state of PVRTC is not suitable for beautiful, hand-drawn artwork. I decided to investigate the best that you can do in case there was some utility for it.</p>
</blockquote>
<p>Let&#8217;s keep this simple and just compare some beautiful game art with the PVRTC compression output. I used a part of a spritesheet from one of our games.</p>
<h2>The Original Image</h2>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/original.png" alt="original" width="474" height="461" class="aligncenter size-full wp-image-241" /></p>
<p>Gorgeous! Now let&#8217;s crush it with PVRTC:</p>
<h2>&#8211;bits-per-pixel4 &#8211;channel-weighting-perceptual</h2>
<p>Here&#8217;s the best result you can get from the PVRTC compressor:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/bitsperpixel4-perceptual.png" alt="bitsperpixel4-perceptual" width="478" height="466" class="aligncenter size-full wp-image-242" /></p>
<p>Notice that the color has been distorted lighter, and there are now a bunch of light-grey tick marks spotting the tree, and the spiderwebs look thicker and messier.</p>
<p>Imagine these sorts of obvious image distortions across every one of your textures.</p>
<h2>&#8211;bits-per-pixel4 &#8211;channel-weighting-linear</h2>
<p>This one demonstrates something terrible about PVRTC when it comes to graphics stored in spritesheets (texture atlases). Note there are jaggy artifacts at the top that leak between parts of the spritesheet. This would cause awful visible animation glitches.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/bitsperpixel4-linear.png" alt="bitsperpixel4-linear" width="478" height="465" class="aligncenter size-full wp-image-243" /></p>
<h2>&#8211;bits-per-pixel2</h2>
<p>Just out of curiosity I decided to try out the 2 bits per pixel mode to see how much worse it was.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/bitsperpixel2.png" alt="bitsperpixel2" width="477" height="464" class="aligncenter size-full wp-image-244" /></p>
<p>It has the same types of errors in the other PVRTC encoding modes but more exaggerated.</p>
<h2>Further Reading</h2>
<p>As a result of seeing these problems we decided not to use PVRTC for mobile games. Instead we use PNG graphics in the DevKit, since it provides an alpha channel and reasonable compression.</p>
<p>By the way, to generate these images I used the preview mode of <code>texturetool</code>, invoked as follows:</p>
<p></p><pre class="crayon-plain-tag">/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/texturetool -e PVRTC --bits-per-pixel-4 --channel-weighting-perceptual -p bitsperpixel4-perceptual.png -o test.pvrtc ./original.png</pre><p></p>
<p>There is documentation for this tool available in the <a href="http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/TextureTool/TextureTool.html">OpenGL ES Programming Guide for iOS</a>.</p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/03/a-quick-look-at-pvrtc/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Overcoming iOS Game Memory Limits</title>
		<link>http://www.gameclosure.com/blog/2013/03/ios-game-memory-limits</link>
		<comments>http://www.gameclosure.com/blog/2013/03/ios-game-memory-limits#comments</comments>
		<pubDate>Sat, 16 Mar 2013 01:56:32 +0000</pubDate>
		<dc:creator>Chris Taylor</dc:creator>
				<category><![CDATA[GC DevKit]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[devkt]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[memory]]></category>

		<guid isPermaLink="false">http://www.gameclosure.com/blog/?p=199</guid>
		<description><![CDATA[If you don&#8217;t know how to deal with memory properly on iOS, you will have a game with bad retention and poor reviews. Unless you know what to expect up front, memory issues will not come up on your just-unboxed test devices &#8212; because available memory varies by what is installed! You will see it [...]]]></description>
				<content:encoded><![CDATA[<p>If you don&#8217;t know how to deal with <em>memory</em> properly on iOS, you will have a game with <strong>bad retention</strong> and <strong>poor reviews</strong>. Unless you know what to expect up front, memory issues will not come up on your just-unboxed test devices &#8212; because available memory varies by what is installed! You will see it <strong>first in user reviews</strong>. Confused? We got it handled, and you can too!</p>
<blockquote>
<p>Roll back the clock to a year ago ~ We wanted our games to be beautiful, high-quality and engaging. These goals were in direct conflict with memory limits, which constrained how much we can present to the player.</p>
</blockquote>
<p>For the iOS platform, we found that there were <strong>unique considerations</strong> to make the most of the memory space that the operating system <em>allowed</em> us to use.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/memory-splode.jpg" alt="Memory Limits" width="300" height="299" class="aligncenter size-full wp-image-204" /></p>
<p><strong>Heads up</strong>: We are focused mainly on beautiful 2D games, which are ironically more difficult from a memory-management perspective than 3D games. Some discussion of 3D-related memory management found its way in here too!</p>
<h2>The Skinny</h2>
<ul>
<li>
<p>iOS restricts our apps to about <strong>10% of the total memory</strong> available on the device. So we use that as a guide for an <em>initial</em> memory limit.</p>
</li>
<li>
<p>iOS provides <strong>low memory warnings</strong> that we had to write code to immediately handle. If our code failed to release memory fast enough, then iOS <strong>killed our app</strong> and the Xcode Organizer device log viewer indicated that the app was closed due to memory usage. We saw these &#8220;app crashes&#8221; without an exception trace log, and the reason was memory usage.</p>
</li>
</ul>
<p>It was time to clean up our act&#8230;</p>
<h2>The Game Plan</h2>
<p>Memory usage for games falls into a number of basic categories:</p>
<ul>
<li><strong>Code</strong> (C, C++, Objective-C, Objective-C++)</li>
<li><strong>Configuration</strong> (JSON, config.plist, NSData blobs, 3D models)</li>
<li><strong>Sounds</strong> (.MP3 files)</li>
<li><strong>Graphics</strong> (.PNG(2D), PVRTC(3D))</li>
</ul>
<h3>Reducing Code Size</h3>
<p>We found that the following <strong>Xcode Compilation Options</strong> had a <em>real</em> impact on app size:</p>
<ul>
<li>Linking : <code>Dead Code Stripping</code> = <em>Yes</em></li>
<li>Deployment : <code>Strip Linked Product</code> = <em>Yes</em></li>
<li>Apple LLVM compiler &#8211; Code Generation : <code>Generate Debug Symbols</code> = <em>No</em></li>
<li>Apple LLVM compiler &#8211; Code Generation : <code>Generate Position-Independent Code</code> = <em>No</em></li>
</ul>
<h5>Thumb-Mode Compilation</h5>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/like.png" alt="Like Thumb" width="398" height="300" class="aligncenter size-full wp-image-220" /></p>
<p>The iPhone processor is based on the ARM instruction set, which has a compact <strong>&#8220;Thumb&#8221;</strong> mode that should reduce compiled code size to about <strong>half</strong> its original size. In addition this switch often <strong>improves performance</strong> on newer iPhone devices at the same time! To turn this option on for GCC 4.2 or newer we used the <em>&#8220;Compile for Thumb&#8221;</em> option:</p>
<ul>
<li>GCC &#8211; Code Generation : <code>Compile for Thumb</code> = <em>Yes</em></li>
</ul>
<p>For LLVM and support for more platforms, we added a new User-Defined option to do the same thing:</p>
<ul>
<li>User-Defined : <code>GCC_THUMB_SUPPORT</code> = <em>YES</em></li>
</ul>
<h5>C++ Language Options to Simplify Compilation</h5>
<p>Since we were not using C++ RTTI (Run-Time Type Information) nor C++ Exceptions, turning those options off was a win for performance, size, and compile time:</p>
<ul>
<li>Apple LLVM compiler &#8211; Language : <code>Enable C++ Exceptions</code> = <em>No</em></li>
<li>Apple LLVM compiler &#8211; Language : <code>Enable C++ Runtime Types</code> = <em>No</em></li>
</ul>
<h5>Optimization Trade-Offs</h5>
<p>Telling the compiler to optimize for size may be a good idea, through the space saved will be minimal. We decided to go for full optimization (-O3) though these other options could be useful for someone:</p>
<ul>
<li>Apple LLVM compiler &#8211; Code Generation : <code>Optimization Level</code> = <em>Fastest, Smallest [-Os]</em></li>
<li>Apple LLVM compiler &#8211; Code Generation : <code>Unroll Loops</code> = <em>No</em></li>
</ul>
<p><em>References:</em></p>
<p><a href="https://developer.apple.com/library/mac/#documentation/performance/Conceptual/CodeFootprint/Articles/CompilerOptions.html">1</a> Mac Developer Library: <a href="https://developer.apple.com/library/mac/#documentation/performance/Conceptual/CodeFootprint/Articles/CompilerOptions.html">Code Size Performance Guidelines</a></p>
<h2>MP3 Sounds</h2>
<p>We switched to compressed MP3-format sounds.</p>
<p>We used <a href="http://kstenerud.github.com/ObjectAL-for-iPhone/">ObjectAL</a> as an OpenAL wrapper to play compressed sounds directly to keep memory usage at a minimum. Encoding audio at a lower MP3 bitrate, especially for the music, afforded another few MB of active textures, which made the difference between good performance and bad performance on lower-end phones on some games. Smaller files meant faster loading too, <strong>always</strong> nice!</p>
<h2>Squeezing Graphics</h2>
<p>After reducing code, configuration, and sound size as much as we could afford, it was time to move onto the biggest resource: Graphics.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/squeeze-lemon.jpg" alt="Squeeze Graphics" width="300" height="263" class="aligncenter size-full wp-image-221" /></p>
<h4>Choosing a File Format: PNG</h4>
<p>For 2D games like ours, the visual quality loss of JPG or <a href="http://en.wikipedia.org/wiki/PVRTC">PVRTC</a> is too high to ignore. Beautiful pixel-perfect hand-drawn artwork gets crushed by these lossy formats even at the highest possible quality. See our <a href="http://www.gameclosure.com/blog/?p=240">article on PVRTC quality</a>.</p>
<h4>Alternative Formats</h4>
<p>Alternative formats to consider are <a href="http://www.researchandtechnology.net/bcif/">BCIF</a> and <a href="https://developers.google.com/speed/webp/">WebP</a>.</p>
<p>BCIF has Java and C versions, which are faster and better than WebP for lossless compression ratio. WebP supports a slightly lossy+alpha mode suitable for sprites that is an attractive option, though the encoder is only available as C code.</p>
<p>We decided to go with PNG for the first cut, though a modified BCIF <em>looks</em> like an exciting prospect for a home-grown solution. In a few tests it saves about 30% more space than PNG!</p>
<h4>PNGCRUSH</h4>
<p><a href="http://pmt.sourceforge.net/pngcrush/">PNGCRUSH</a> is free open-source software (FOSS) that allowed us to get more compression ratio out of PNG image files by spending more time brute-forcing all the options. Sure- it takes a while to compress. But we only had to do it once a week for each public release!</p>
<p>In three of our resource-heavy games, the advantages of running PNGCRUSH are clear:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/pngcrush1.png" alt="PNGCRUSH Performance" width="511" height="374" class="aligncenter size-full wp-image-222" /></p>
<p>PNG images that &#8220;crush&#8221; well tend to be user-interface elements with fewer colors and sharp edges (~30% reduction), text (~50% reduction), and spritesheets with empty space.</p>
<blockquote>
<p>Somewhat counter-intuitively, a more tightly compressed PNG image will also load faster. The main reason is that read time is shorter and the decompression code has less data to process so it can finish sooner!</p>
</blockquote>
<h4>Texture Atlases / Spritesheets</h4>
<p>Since our game is designed for the high performance of OpenGL, textures must be <em>power-of-two</em> in size. So to use memory efficiently, texture atlases (also called spritesheets) were already a part of our game engine.</p>
<p>This is what a <strong>texture atlas</strong> looks like:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/whackthatatlas1.png" alt="Whack-that-Mole Atlas" width="512" height="512" class="aligncenter size-full wp-image-223" /></p>
<p>If each graphic in our game had been a separate image file, then they each would be increased in size to be a power-of-two in dimension at runtime, wasting a <strong>ton of memory</strong> just to satisfy that requirement. Instead&#8211; Sprites are combined into a single spritesheet and will use much less memory and will render much faster!</p>
<h4>3D Games: PVRTC and Memory-Mapping</h4>
<p>Images can be loaded as textures without decompressing into memory if they are stored in PVRTC format. This is a huge win for load times because as soon as the image file is read, the texture is done loading. This is great for 3D games because the quality loss due to the lossy PVRTC format is negligible.</p>
<p>A further exciting benefit of PVRTC is that the image files can be memory-mapped. This allows the operating system to do most of the texture memory management. Meaning that images outside of the active set may be unloaded automatically by the operating system without having to write more code.</p>
<p>For even less overhead it would be best to pack all of the PVRTC files into one large file that is memory-mapped at runtime. This saves memory because each memory-mapped file needs to be mapped at a memory address number that is an even multiple of the disk sector size. Since file sizes are rarely evenly divisible this would waste memory and would require more code and startup time to load each file. Offsets inside the blob for each file can be compiled into the app code with a pre-build script, or they can be read in through a separate configuration file.</p>
<p>3D games can still do some simple texture memory management and react to memory warnings by dynamically reducing the number of textures used in each frame. The OS will automatically unload the unused textures.</p>
<p><em>References:</em></p>
<p><a href="https://developer.apple.com/library/mac/#documentation/performance/Conceptual/CodeFootprint/Articles/CompilerOptions.html">1</a> iOS Developer Library: <a href="http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/TextureTool/TextureTool.html#//apple_ref/doc/uid/TP40008793-CH108-SW1">Using texturetool to Compress Textures</a></p>
<h2>2D Games: Texture Memory Management</h2>
<p>Once we started getting serious with iOS game development, very quickly our games started having more textures overall than we could have loaded at one time. Since we use OpenGL for graphics, this means that we needed a <strong>texture manager</strong> to control which images are in the &#8220;working set&#8221; of images that are being rendered to the screen, and which images should be unloaded when no longer needed.</p>
<p>A good texture manager makes full use of memory and keeps loaded as many textures as it can in a &#8220;cache&#8221; &#8212; so that the <em>next</em> time a texture is displayed, it is already available and does not need to be reloaded from disk.</p>
<p>Here&#8217;s an example ramp-up for game memory on startup:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/instruments1.png" alt="Instruments Memory" width="1014" height="492" class="aligncenter size-full wp-image-224" /></p>
<p>And here&#8217;s a reaction to a memory warning:</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/instrufree1.png" alt="Instruments Free Memory" width="1014" height="492" class="aligncenter size-full wp-image-225" /></p>
<p>Only the most recently-used textures would need to be kept in memory. So if we have some hint as to which images are going to be needed soon (sometimes called preloading), then those textures are <strong>&#8220;touched&#8221;</strong> to keep them <strong>&#8220;alive&#8221;</strong> in the texture manager cache of textures even though they are not being rendered in the current frame.</p>
<blockquote>
<p>It is up to the texture manager to keep the game within its memory limits, since at runtime graphics memory is the only part of the game that can shrink further in reaction to memory warnings from iOS.</p>
</blockquote>
<p>The texture manager for the Game Closure DevKit is in the native-core <a href="https://github.com/gameclosure/native-core/blob/master/texture_manager.c">texture_manager.c code</a>.</p>
<h4>Reacting to Memory Warnings</h4>
<p>We react to memory warnings by implementing the <code>applicationDidReceiveMemoryWarning</code> method in our Objective-C Application Delegate:</p>
<p></p><pre class="crayon-plain-tag">- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application{
        // Handle warning here
    }</pre><p></p>
<p>These warnings have four levels of severity {0..3}. The private API function OSMemoryNotificationCurrentLevel() can provide the severity level. The reported severity level will increase at each warning until your app is killed. However, failing to respond to any of these <strong>will</strong> cause your app to <em>die</em>.</p>
<blockquote>
<p>Whenever a memory warning is received, we treat it as severe.</p>
</blockquote>
<p>Our texture memory manager constantly analyzes how much memory is being used actively by the game. When a memory warning occurs it subtracts off about 10 MB from the used memory (a somewhat heuristic value that works in our experience) to come up with a new texture memory limit.</p>
<h4>2D Games: Half-Sizing</h4>
<p>On lower-end cellphones, the screens are smaller and can display less detail than higher-end cellphones that have much more memory. Since the same app must work on both classes of cellphones, it is a good idea to support texture <strong>half-sizing</strong>. This is an efficient operation that can be done during loading, and adds very little additional time to loading.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/johnny-doubler1.jpg" alt="Johnny Mnemonic Doubler" width="440" height="233" class="aligncenter size-full wp-image-226" /></p>
<p><strong>Why half-size and not quarter-size or 60% size?</strong> Half-sizing is efficient to implement in C code by averaging blocks of <strong>4 pixels into one</strong>. Efficiency is essential for lower-end iPhone 3GS devices where this is applied. Half-sizing reduces the memory footprint of images by a factor of <em>four</em> so will be good enough to fix memory problems, and quality does not need to suffer any more than this to be effective.</p>
<blockquote>
<p>We do half-sizing on the iPhone 3GS, but it can also happen if our engine detects extreme memory limitations: It will smash that half-size button in an emergency attempt to stay under the limit.</p>
</blockquote>
<p>A fully unrolled implementation of half-sizing decompressed and resizing to power-of-two (for OpenGL) may be found in the Game Closure Dev Kit <a href="https://github.com/gameclosure/native-core/blob/master/texture_2d.c">texture_2d.c</a> code; see the <code>texture_2d_load_texture_raw</code> function.</p>
<h2>Appendix: Fast PNG Loading</h2>
<p>Demonstrably faster load times and less memory usage can be achieved by using memory-mapped files on iOS. Normal file loading first allocates a buffer in memory to receive the file contents, and then reads the file from disk into the buffer. Memory-mapped files, on the other hand, make the file contents immediately available without the read step. This leads to about 30% better load times for PNG images in our testing.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/mmap1.gif" alt="MMap Virtual Memory" width="367" height="155" class="aligncenter size-full wp-image-227" /></p>
<p>Files placed in the resources section in Xcode for your app will be available on the device. Verify that the files are present in the Build Phases tab of your target under Copy Bundle Resources if you have problems loading them on the device.</p>
<p>The first step to loading a resource is to get its path. This short code snippet demonstrates how to do that:</p>
<p></p><pre class="crayon-plain-tag">NSString *path = &quot;texture.png&quot;;
    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
    NSURL *resourceURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@&quot;%@/%@&quot;, self.appBundle, path]];</pre><p></p>
<p>To quickly load this URL into a UIImage in Objective C:</p>
<p></p><pre class="crayon-plain-tag">NSData *data = [NSData dataWithContentsOfURL:resourceURL];
    UIImage *image = [UIImage imageWithData:data];</pre><p></p>
<p>Now, our improved memory-mapped file loader as C code:</p>
<p></p><pre class="crayon-plain-tag">#include &lt;sys/mman.h&gt;
    #include &lt;sys/fcntl.h&gt;

    ...

    // Result will be in success, data, sz
    bool success = false;
    unsigned char *data;
    unsigned long sz;

    int fd = open(path, O_RDONLY);

    if (fd != -1) {
        unsigned long len = lseek(fd, 0, SEEK_END);

        fcntl(fd, F_NOCACHE, 1);
        fcntl(fd, F_RDAHEAD, 1);

        if (len &amp;gt; 0) {
            void *raw = mmap(0, len, PROT_READ, MAP_PRIVATE, fd, 0);

            if (raw != MAP_FAILED) {
                data = (unsigned char*)raw;
                sz = len;
                success = true;
            }
        }

        close(fd);
    }

    if (success) {

        ... // Use the data,sz here

        munmap(data, sz);
    }</pre><p></p>
<p>The data would be passed to OpenGL&#8217;s <code>glTexImage2D</code>.</p>
<p>Note that <code>F_NOCACHE</code> and <code>F_RDAHEAD</code> are toggled to further streamline the loading.</p>
<p><code>F_NOCACHE</code> prevents the OS from caching data during file reads, which would waste time since the data will <em>not be requested twice</em>.</p>
<p>And <code>F_RDAHEAD</code> gives a hint to the OS that each page of file data request will soon be <em>followed by another request for the next page</em>, so it should go ahead and start paging in the next page ahead of time.</p>
<p>These options are respected on iOS and measureably help to reduce load times.</p>
<h2>Appendix: More Words on Sprite Packing</h2>
<p>Sprite packing can pack game graphics into images up to 1024&#215;1024 pixels that can be loaded by OpenGL at runtime. Note that 1024&#215;1024 is a limit on some cellphones.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/binpack1.gif" alt="Bin-packing" width="200" height="200" class="aligncenter size-full wp-image-228" /></p>
<p>Sprite packing is an interesting NP-complete problem also known as bin-packing. There has been a lot of work done on this problem in a lot of different domains including game sprites and several commercial solutions exist.</p>
<p>Spending a lot of extra processing time to pack tighter typically gains only about 3% better packing that is often lost anyway due to the power-of-two limitation on OpenGL textures.</p>
<blockquote>
<p>In general, sprite packing algorithms should be optimized for performance once you have a reasonable approach.</p>
</blockquote>
<p>It is also a good idea to store consecutive images in animations on the same spritesheet if possible. This gives better in-game performance since switching between textures can be minimized up front during spriting. Images that are going to be used together should be sprited together for the same reason.</p>
<h2>Appendix: Initial Memory Limits</h2>
<p>The initial memory limit of 10% total memory is straight-forward to calculate in C code:</p>
<p></p><pre class="crayon-plain-tag">#import &lt;mach/mach.h&gt;
#import &lt;mach/mach_host.h&gt;

int get_platform_memory_limit()
{
    mach_port_t host_port;
    mach_msg_type_number_t host_size;
    vm_size_t pagesize;

    host_port = mach_host_self();
    host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
    host_page_size(host_port, &amp;pagesize);

    vm_statistics_data_t vm_stat;

    if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&amp;vm_stat, &amp;host_size) != KERN_SUCCESS) {
        return 50000000; // Default: 50 MB (This is a fairly safe value across current iOS devices)
    } else {
        natural_t mem_used = (vm_stat.active_count +
                              vm_stat.inactive_count +
                              vm_stat.wire_count) * pagesize;
        natural_t mem_free = vm_stat.free_count * pagesize;
        natural_t mem_total = mem_used + mem_free;

        // Return 10% of total memory (bytes)
        return (int)mem_total / 10;
    }
}</pre><p></p>
<h2>Victory!</h2>
<p>With all of these techniques brought to bear on the iOS memory problem, our general-purpose game engine now successfully navigates the entire iPhone and iPad landscape, from low-end phones to high-end tablets.</p>
<p><img src="http://www.gameclosure.com/blog/wp-content/uploads/2013/03/kiwirun-active.png" alt="Kiwirun Active" width="572" height="295" class="aligncenter size-full wp-image-230" /></p>
<p>Thanks to the techniques we developed, we can deliver <em>pixel-perfect</em> image clarity with <em>short</em> load times.</p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/03/ios-game-memory-limits/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Game Closure &#8220;DevKit&#8221; for Mobile HTML5 Games is Open Source!</title>
		<link>http://www.gameclosure.com/blog/2013/02/game-closure-devkit-for-mobile-html5-games-is-open-source</link>
		<comments>http://www.gameclosure.com/blog/2013/02/game-closure-devkit-for-mobile-html5-games-is-open-source#comments</comments>
		<pubDate>Thu, 14 Feb 2013 17:59:40 +0000</pubDate>
		<dc:creator>Michael Carter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://gameclosure.com:8081/blog/?p=177</guid>
		<description><![CDATA[We founded Game Closure around the idea that HTML5 is the right technology choice for building successful iOS and Android games, and for the past two years we&#8217;ve been working to make that a reality. Today I&#8217;m proud to announce our public release of Game Closure “DevKit”, for mobile game development with Javascript. It is [...]]]></description>
				<content:encoded><![CDATA[<p>We founded Game Closure around the idea that HTML5 is the right technology choice for building successful iOS and Android games, and for the past two years we&#8217;ve been working to make that a reality. Today I&#8217;m proud to announce our public release of Game Closure “DevKit”, for mobile game development with Javascript. It is 100% Free and Open Source, and we intend for it to stay that way.</p>
<p>This is a technology that already powers dozens of games, and has been battle tested against literally hundreds of mobile devices by millions of players around the world. This is not a science project, or “pretty good for an HTML5 game engine” &#8212; the GC DevKit is a damn good mobile game engine that you can compare alongside the best of them. It is the only truly production-ready mobile game engine with such strong roots in JavaScript.</p>
<p><center><br />
<iframe style="background:#000000;" src="http://player.vimeo.com/video/59646792?title=1&amp;byline=1&amp;portrait=1&amp;color=00adef&amp;autoplay=0&amp;loop=0" width="500" height="375" frameborder="0"></iframe><br />
</center></p>
<p>If you&#8217;re ready to dive right in, please check out the <a href="https://github.com/gameclosure/devkit">github repository</a>, and <a href="http://docs.gameclosure.com/">the documentation</a>!</p>
<p>Also, <a href="http://www.icepopbeat.com/">check out Kiwi Run</a>, an early GC DevKit launch title. You can go ahead and play the game directly on the web, or just <a href="https://itunes.apple.com/US/app/id568975017">download it on your iOS (iTunes store)</a> or <a href="https://play.google.com/store/apps/details?id=com.popsiclebeat.kiwirunkr&amp;hl=en">Android device (Play Store)</a>. Kiwi Run is a fantastic game with nearly a million players since release two months ago, and I hope it will make the potential and possibilities of DevKit real to you!</p>
<h2>Ethos</h2>
<ol>
<li><span style="line-height: 1.714285714; font-size: 1rem;"><strong>GC DevKit is the best 2D mobile game engine in the world.</strong> If we find a weakness or this turns out not to be true, we&#8217;ll fix it.</span></li>
<li><span style="line-height: 1.714285714; font-size: 1rem;"><strong>Web Technology is Great.</strong> We want to piggyback off of the fantastic technology created every day at Apple, Google, Facebook, Adobe, Joyent, Microsoft, and other innovative companies in the Javascript and Web space. We don&#8217;t want to re-invent our own debugger, profiler, editor, version control, art software/pipeline, so we didn&#8217;t.</span></li>
<li><strong>GC DevKit is always production ready.</strong> It is incredibly stable; check out Kiwi Run&#8217;s rating, it&#8217;s a 4.7 across many thousands of reviews. We made sure that the core engine is fast, 8000-sprites-on-the-screen fast. We created a UI system that can handle every aspect ratio, size, and type of device, and tooling to go with it. We made the process of distributing games on the App Store and Play store easy.</li>
</ol>
<h2>Licensing</h2>
<p>We chose a dual-licensing strategy with the <a href="http://www.gnu.org/licenses/gpl-3.0.html">GPLv3</a> and the <a href="http://www.gameclosure.com/GCFL-1.0.pdf">Game Closure Free License (GCFL)</a> (you can read more about both on our <a href="http://www.gameclosure.com/license.html">licensing page</a>). We tried very hard to make the core of the GCFL fit on a single page; it does, and it&#8217;s incredibly easy to read and understand. The idea here is to make sure that everyone who is benefiting from our ecosystem is also contributing back their modifications and improvements to DevKit. But we also want to allow studios and developers to create proprietary, closed-source, and for-profit games, completely free of charge.</p>
<h2>Contributors</h2>
<p>Our primary goal here is to get this technology in the hands of many, many developers, and along the way we&#8217;d also like to build a strong community of collaboration and participation. We have a guide for Contributors that outlines our Contributor License Agreement (CLA) which is very similar to the agreements you see in most open source projects, like nodejs, dojo, and Apache. The goal is for us to retain ownership of the code base so that we can protect users under both the GPL and the GCFL. The CLA and the licensing is designed so that users under either license will need to contribute code back for the good of the entire community.</p>
<p>Other than our required CLA, we intend to run the github project similarly to other Open Source github projects out there, complete with branches, pull requests, a mailing list&#8230; the works.</p>
<h2>Join us!</h2>
<p>Game Closure is hiring javascript hackers and (mobile) engineers. If you are interested in working here, either full-time or as an internship, please check out our <a href="http://www.gameclosure.com/careers.html">jobs page.</a> Thanks!</p>
<!-- Start Shareaholic Recommendations Automatic --><!-- End Shareaholic Recommendations Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.gameclosure.com/blog/2013/02/game-closure-devkit-for-mobile-html5-games-is-open-source/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Database Caching 10/30 queries in 0.011 seconds using disk: basic
Object Caching 573/654 objects using disk: basic

 Served from: www.gameclosure.com @ 2013-05-25 06:05:43 by W3 Total Cache -->