<?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>Richard Lord</title>
	<atom:link href="http://www.richardlord.net/feed" rel="self" type="application/rss+xml" />
	<link>http://www.richardlord.net</link>
	<description>Game Developer</description>
	<lastBuildDate>Wed, 15 May 2013 12:50:28 +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>Teaching Game Design</title>
		<link>http://www.richardlord.net/blog/teaching-game-design</link>
		<comments>http://www.richardlord.net/blog/teaching-game-design#comments</comments>
		<pubDate>Wed, 15 May 2013 12:50:28 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Choreography]]></category>
		<category><![CDATA[Game Design]]></category>
		<category><![CDATA[Learning]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=1099</guid>
		<description><![CDATA[It&#8217;s a little known fact that before I became involved in game development I was a choreographer. Yes, I have a degree in Maths, and I started programming computers when I was 12, but after getting that degree I went to dance school in London and got another degree, this time in contemporary dance and [...]]]></description>
				<content:encoded><![CDATA[<p>It&#8217;s a little known fact that before I became involved in game development I was a choreographer. Yes, I have a degree in Maths, and I started programming computers when I was 12, but after getting that degree I went to dance school in London and got another degree, this time in contemporary dance and choreography. I followed this by forming my own dance company and spent the next ten years choreographing dances.</p>

<p>Which begs the question of how I got into game development. Most choreographers do something else to supplement their choreography income, it comes with the low-pay high-satisfaction territory. Some teach dance or do other dance related work, others wait tables in restaurants. I wrote code &#8211; it paid better and I enjoyed it. Eventually, a few years back, I stopped choreographing and focused entirely on game development.</p>

<p>Which is all background to what I want to talk about. Reading Daniel Cook&#8217;s recent article, <a href="http://www.gamasutra.com/blogs/DanielCook/20130414/190462/A_Case_Study_in_how_Revolutionaries_become_The_Man.php">How Revolutionaries become The Man</a>, and particularly the section on game design teaching, caused me to remember, and dwell on, how I was taught choreography.</p>

<h2>Teaching choreography</h2>

<p>The first thing to note about my choreography learning is that it all took place in dance studios.  I was never required to read books or analyze other choreographers&#8217; work, although I did so by choice. I was encouraged to watch lots of dance, and my teachers made time to discuss what I&#8217;d seen if I asked them to, but choreography teaching was based around one activity &#8211; choreographing. The thinking, in essence, was the more you choreograph the more you learn. So, during my three years at dance school I choreographed 14 dances of varying length.</p>

<p>And while at dance school there were three choreography teachers from whom I learnt a lot.</p>

<p>Jane Dudley was a legend in the contemporary dance world. She was a dancer in Martha Graham&#8217;s original company and had over 50 years experience as a choreographer. Jane taught a class of her own devising, in which she choreographed a dance on us, the students, while asking us for ideas that she might use in the dance. Through this she encouraged our creativity, allowing us to express all sorts of crazy ideas, some of which she used and some she didn&#8217;t. Through this we also saw first hand, from the best vantage, how she built a dance piece, overlaying ideas, providing counterpoints, and discarding content without regret if it didn&#8217;t quite work. The result was a dance work that we all had a hand in creating.</p>

<p>I also asked Jane to watch and feedback on my work, which she seemed to enjoy doing. She was unreserved in both praise and criticism. Above all Jane emphasised the importance of creating something interesting. It wasn&#8217;t enough to craft with skill if what you were crafting was not unique in some small way. Jane helped me to understand and pay attention to the ideas that drove my work, to know what would make each dance special.</p>

<p>Ingegerd Lönnroth was quiet, unassuming and could dissect a dance with precision and present the truth with kindness. She sometimes struggled with a class full of students, but she was brilliant with individuals or small groups. On one occasion I showed her a piece I was working on. Inge watched the piece through once, then asked the dancers to perform one specific section again. Half way through she pointed and said &#8220;There&#8221;, and as she said it I realised how, with one careless move, I had broken the purpose and flow of the dance, and Inge had spotted it on a single viewing of the dance. Through her I learnt to pay attention to the details, to care about every moment. I also started to learn one of the most difficult skills of a creator, how to view my work with the dispassionate eye of a neutral observer. To see the dance as it was, not as I wanted it to be.</p>

<p>Kim Brandstrup was brilliant at telling stories with dance. But what I learnt from him was not about stories, it was about craft. He taught me how to shape a phrase of dance, to give it highs and lows, to make it deliberate and to give it purpose. In his choreography classes he would present us with simple, short exercises &#8211; a rhythm, a theme, a message &#8211; and ask us to create a phrase of dance, mere seconds in length, and refine it to convey the goal he&#8217;d presented. Then we&#8217;d watch each other&#8217;s work and discuss what succeeded and didn&#8217;t, and why. Kim taught me craft.</p>

<p>So, I learnt to choreograph by choreographing. I was only required to choreograph one work per year but I was encouraged to do much more. I used other dancers at the school in my dances. Most of the time I used prerecorded music, or on a couple of occasions no music at all, and there were no specific costumes or lighting because learning to craft the dance was what mattered.<p>

<p>In my final year I was lucky to work with a couple of composers from nearby music schools, a brilliant design student from a theatre school, and a friend of a friend who was a lighting designer. By then I was showing my work to the public and the addition of these other skills, and learning to work with those who had these skills, was important.</p>

<p>Choreography was an important part of my degree. I was assessed and marked by experts who watched what I&#8217;d choreographed, discussed it with me, and decided how many marks it deserved. There was no written exam, no testing my understanding of choreographic theory. To test my choreography, I choreographed and the examiners assessed the result.</p>

<h2>What if game design was taught like I was taught choreography?</h2>

<p>I don&#8217;t presume to know how game design is taught at universities around the world. I have heard stories, and if those stories are correct then it has little in common with how I was taught choreography. If game design was taught how I was taught choreography then I guess it would look something like this.</p>

<p>Students are encouraged to create games, working with fellow students as artists and programmers. They create multiple games every year, in various genres, exploring ideas, pushing boundaries, discovering for themselves, with guidance and help from experts who work or have worked in the industry. They learn craft from small exercises, designing solutions to specific problems or designing a critical few seconds of a game.</p>

<p>They are encouraged to read, to play, and to discuss what they read and play. But there is no right and wrong for them to be taught, instead there is opinion to be formed and skill to be acquired.</p>

<p>Each year they also work with a professional game designer, as assistant designers and level designers, to create a complete game for release to the world (their colleagues studying programming, art and music build this game that they design, also under the guidance of professionals from the industry).</p>

<p>Every year, they present their best work for assessment by experienced game designers and the marks from this are their assessment. And at the end of their course, after designing 14 games or so, they will have started to form their own vision of what games they want to design and to gain the skills with which to design them.</p>

<p>If I went back to school, that&#8217;s the game design course I&#8217;d like to learn from.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/teaching-game-design/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Finite State Machines with Ash entity system framework</title>
		<link>http://www.richardlord.net/blog/finite-state-machines-with-ash</link>
		<comments>http://www.richardlord.net/blog/finite-state-machines-with-ash#comments</comments>
		<pubDate>Wed, 05 Dec 2012 21:26:50 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Ash]]></category>
		<category><![CDATA[Entity systems]]></category>
		<category><![CDATA[Finite State Machine]]></category>
		<category><![CDATA[Game development]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=1064</guid>
		<description><![CDATA[Finite state machines are one of the staple constructs in game development. During the course of a game, game objects may pass through many states and managing those states effectively is important. The difficulty with finite state machines in an entity system framework like Ash can be summed up in one sentence &#8211; the state [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Finite-state_machine">Finite state machines</a> are one of the staple constructs in game development. During the course of a game, game objects may pass through many states and managing those states effectively is important.</p>

<p>The difficulty with finite state machines in an entity system framework like <a href="http://www.ashframework.org/">Ash</a> can be summed up in one sentence &#8211; the state pattern doesn’t work with an entity system framework. Entity system frameworks use a data-oriented paradigm in which game objects are not self-contained OOP objects. So you can’t use the <a href="http://en.wikipedia.org/wiki/State_pattern">state pattern</a>, or any <a href="http://www.richardlord.net/blog/finite-state-machines-for-ai-in-actionscript">variation</a> of it. All the data is in the components, all the logic is in the systems.</p>

<p>If your states are few and simple it is possible to use a good old fashioned switch statement inside a system, with the data for all the states in one or more components that are used by that system, but I wouldn’t usually recommend that.</p>

<p>When creating <a href="http://www.sticksports.com/mobile/stick-tennis.php">Stick Tennis</a> I was faced with the problem of how to manage states as the two main entities in the game are the two players, and they go through a number of states as they&#8230;</p>

<ul>
<li>prepare to serve</li>
<li>swing arm to toss the ball</li>
<li>release the ball</li>
<li>swing the racquet</li>
<li>hit the ball</li>
<li>follow through</li>
<li>run to a good position</li>
<li>react to the opponent hitting the ball</li>
<li>run to intercept the ball</li>
<li>swing the racquet</li>
<li>hit the ball</li>
<li>follow through</li>
<li>run to a good position</li>
<li>react to winning the point</li>
<li>&#8230;etc</li>
</ul>

<p>Stick Tennis is a complex example, and I can’t show you the source code, so instead I’ll use something a little simpler, with source code.</p>

<h2>An example</h2>

<p>Lets consider a guard character in a game. This character patrols along a path, keeping watch. If they spot an enemy, they attack him/her.</p>

<p>In a traditional object-oriented state machine we might have a class for each state</p>

<pre class="code">public class PatrolState
{
    private var guard : Character;
    private var path : Vector.&lt;Point&gt;;

    public function PatrolState( guard : Character, path : Vector.&lt;Point&gt; )
    {
        this.guard = guard;
        this.path = path;
    }

    public function update( time : Number ) : void
    {
        moveAlongPath( time );
        var enemy : Character = lookForEnemies();
        if( enemy )
        {
            guard.changeState( new AttackState( guard, enemy ) );
        }
    }
}</pre>

<pre class="code">public class AttackState
{
    private var guard : Character;
    private var enemy : Character;

    public function AttackState( guard : Character, enemy : Character )
    {
        this.guard = guard;
        this.enemy = enemy;
    }

    public function update( time : Number ) : void
    {
        guard.attack( enemy );
        if( enemy.isDead )
        {
            guard.changeState( new PatrolState( guard, PatrolPathFactory.getPath( guard.id ) );
        }
    }
}</pre>

<p>In a entity system architecture we have to take a slightly different approach, but the core principle of the state pattern, to split the state machine across multiple classes, one for each state, can still be applied. To implement the state machine in an entity framework we will use one System per state.</p>

<pre class="code">public class PatrolSystem extends ListIteratingSystem
{
    public function PatrolSystem()
    {
        super( PatrolNode, updateNode );
    }

    private function updateNode( node : PatrolNode, time : Number ) : void
    {
        moveAlongPath( node );
        var enemy : Enemy = lookForEnemies( node );
        if( enemy )
        {
            node.entity.remove( Patrol );
            var attack : Attack = new Attack();
            attack.enemy = enemy;
            node.entity.add( attack );
        }
    }
}</pre>

<pre class="code">public class AttackSystem extends ListIteratingSystem
{
    public function AttackSystem()
    {
        super( AttackNode, updateNode );
    }

    private function updateNode( node : PatrolNode, time : Number ) : void
    {
        attack( node.entity, node.attack.enemy );
        if( node.attack.enemy.get( Health ).energy == 0 )
        {
            node.entity.remove( Attack );
            var patrol : Patrol = new Patrol();
            patrol.path = PatrolPathFactory.getPath( node.entity.name );
            node.entity.add( patrol );
        }
    }
}</pre>

<p>The guard will be processed by the PatrolSystem if he has a Patrol component, and he will be processed by the AttackSystem if he has an Attack component. By adding/removing these components from the guard we change his state.</p>

<p>The components and nodes look like this&#8230;</p>

<pre class="code">public class Patrol
{
    public var path : Vector.&lt;Point&gt;;
}</pre>

<pre class="code">public class Attack
{
    public var enemy : Entity;
}</pre>

<pre class="code">public class Position
{
    public var point : Point;
}</pre>

<pre class="code">public class Health
{
    public var energy : Number;
}</pre>

<pre class="code">public class PatrolNode extends Node
{
    public var patrol : Patrol;
    public var position : Position;
}</pre>

<pre class="code">public class AttackNode extends Node
{
    public var attack : Attack;
}</pre>

<p>So, by changing the components of the entity, we change the entities state and thus change the systems that process the entity.</p>

<h2>Another example</h2>

<p>Here’s another, more complex example using the <a href="https://github.com/richardlord/Asteroids">Asteroids example game</a> that I use to illustrate how Ash works. I’ve add an additional state to the spaceship for when it’s shot. Rather than simply removing the spaceship when it is shot, I show a short animation of it breaking up. While doing this, the user won’t be able to move it and the spaceship won’t react to collisions with other objects.</p>

<p>The two states require the following</p>

<p>While the ship is alive -</p>
<ul>
<li>It looks like a spaceship</li>
<li>The user can move it</li>
<li>The user can fire its gun</li>
<li>It collides with asteroids</li>
</ul>

<p>When the ship is dead -</p>
<ul>
<li>It looks like bits of a spaceship floating in space</li>
<li>The user cannot move it</li>
<li>The user cannot fire its gun</li>
<li>It doesn’t collide with asteroids</li>
<li>After a fixed time it is removed from the game</li>
</ul>

<p>The relevant piece of code, where the spaceship dies, is in the CollisionSystem. Without the second state it would look like this</p>

<pre class="code">for ( spaceship = spaceships.head; spaceship; spaceship = spaceship.next )
{
    for ( asteroid = asteroids.head; asteroid; asteroid = asteroid.next )
    {
        if ( Point.distance( asteroid.position.position, spaceship.position.position )
            <= asteroid.position.collisionRadius + spaceship.position.collisionRadius )
        {
            creator.destroyEntity( spaceship.entity );
            break;
        }
    }
}</pre>

<p>The code tests whether the ship is colliding with an asteroid, and if it is it removes the ship. Elsewhere, the <a href="https://github.com/richardlord/Asteroids/blob/master/src/no-dependencies/net/richardlord/asteroids/systems/GameManager.as">GameManager</a> system handles the situation where there is no spaceship and creates another one, if any are left, or ends the game. Instead of destroying the spaceship, we need to change its state. So, lets try this...</p>

<p>We can prevent the user controlling the spaceship by simply removing the <a href="https://github.com/richardlord/Asteroids/blob/master/src/no-dependencies/net/richardlord/asteroids/components/MotionControls.as">MotionControls</a> and <a href="https://github.com/richardlord/Asteroids/blob/master/src/no-dependencies/net/richardlord/asteroids/components/GunControls.as">GunControls</a> components. We might as well remove the <a href="https://github.com/richardlord/Asteroids/blob/master/src/no-dependencies/net/richardlord/asteroids/components/Motion.as">Motion</a> and <a href="https://github.com/richardlord/Asteroids/blob/master/src/no-dependencies/net/richardlord/asteroids/components/Gun.as">Gun</a> components while we’re at it since they're of no use without the controls. So we replace the code above with</p>

<pre class="code">for ( spaceship = spaceships.head; spaceship; spaceship = spaceship.next )
{
    for ( asteroid = asteroids.head; asteroid; asteroid = asteroid.next )
    {
        if ( Point.distance( asteroid.position.position, spaceship.position.position )
            <= asteroid.position.collisionRadius + spaceship.position.collisionRadius )
        {
            spaceship.entity.remove( MotionControls );
            spaceship.entity.remove( Motion );
            spaceship.entity.remove( GunControls );
            spaceship.entity.remove( Gun );
            break;
        }
    }
}</pre>

<p>Next, we need to change how the ship looks and remove the collision behaviour</p>

<pre class="code">for ( spaceship = spaceships.head; spaceship; spaceship = spaceship.next )
{
    for ( asteroid = asteroids.head; asteroid; asteroid = asteroid.next )
    {
        if ( Point.distance( asteroid.position.position, spaceship.position.position )
            <= asteroid.position.collisionRadius + spaceship.position.collisionRadius )
        {
            spaceship.entity.remove( MotionControls );
            spaceship.entity.remove( Motion );
            spaceship.entity.remove( GunControls );
            spaceship.entity.remove( Gun );
            spaceship.entity.remove( Collision );
            spaceship.entity.remove( Display );
            spaceship.entity.add( new Display( new SpaceshipDeathView() ) );
            break;
        }
    }
}</pre>

<p>And finally, we need to ensure that the spaceship is removed after a short period of time. To do this, we’ll need a new system and component like this</p>

<pre class="code">public class DeathThroes
{
    public var countdown : Number;
        
    public function DeathThroes( duration : Number )
    {
        countdown = duration;
    }
}</pre>

<pre class="code">public class DeathThroesNode extends Node
{
    public var death : DeathThroes;
}</pre>

<pre class="code">public class DeathThroesSystem extends ListIteratingSystem
{
    private var creator : EntityCreator;
    
    public function DeathThroesSystem( creator : EntityCreator )
    {
        super( DeathThroesNode, updateNode );
        this.creator = creator;
    }

    private function updateNode( node : DeathThroesNode, time : Number ) : void
    {
        node.death.countdown -= time;
        if ( node.death.countdown <= 0 )
        {
            creator.destroyEntity( node.entity );
        }
    }
}</pre>

<p>We add the DeathThroesSystem to the game at the start, so it will handle the drawn-out death of any entity. Then we add the DeathThroes component to the spaceship when it dies.</p>

<pre class="code">for ( spaceship = spaceships.head; spaceship; spaceship = spaceship.next )
{
    for ( asteroid = asteroids.head; asteroid; asteroid = asteroid.next )
    {
        if ( Point.distance( asteroid.position.position, spaceship.position.position )
            <= asteroid.position.collisionRadius + spaceship.position.collisionRadius )
        {
            spaceship.entity.remove( MotionControls );
            spaceship.entity.remove( Motion );
            spaceship.entity.remove( GunControls );
            spaceship.entity.remove( Gun );
            spaceship.entity.remove( Collision );
            spaceship.entity.remove( Display );
            spaceship.entity.add( new Display( new SpaceshiopDeathView() ) );
            spaceship.entity.add( new DeathThroes( 5 ) );
            break;
        }
    }
}</pre>

<p>And that is our state transition. The transition is achieved by altering which components the entity has.</p>

<h2>The state is encapsulated in its components</h2>

<p>This is the general rule of the entity system architecture - the state of an entity is encapsulated in its components. If you want to change how an entity is processed, you should change its components. That will alter which systems operate on it and that changes how the entity is processed.</p>

<h2>Standardised state machine code</h2>

<p>To help with state machines I’ve added some <a href="https://github.com/richardlord/Ash/tree/master/src/ash/fsm">standard state machine classes</a> to Ash. These classes help you manage states by defining states based on the components they contain, and then changing state simply by specifying the new state you want.</p>

<p>A finite state machine is an instance of the <a href="https://github.com/richardlord/Ash/blob/master/src/ash/fsm/EntityStateMachine.as">EntityStateMachine</a> class. You pass it a reference to the entity it will manage when constructing it. You will usually store the state machine in a component on the entity so it can be recovered from within any system that is operating on the entity.</p>

<pre class="code">var stateMachine : EntityStateMachine = new EntityStateMachine( guard );</pre>

<p>A state machine is configured with states, and the state can be changed by calling the state machine's changeState() method. States are identified by a string, which is assigned when the state is created and used to identify the state when calling the changeState() method.</p>

<p>States are instances of the <a href="https://github.com/richardlord/Ash/blob/master/src/ash/fsm/EntityState.as">EntityState</a> class. They may be added to the EntityStateMachine using the EntityStateMachine.addState() method, or they may be created and added in one call using the EntityStateMachine.createState() method.</p>
    
<pre class="code">var patrolState : EntityState = stateMachine.createState( "patrol" );
var attackState : EntityState = stateMachine.createState( "attack" );</pre>

<p>A state is a set of components that should be added to the entity when that state is entered, and removed when that state exits (unless they are also required for the next state). The add method of the EntityState specifies the type of component required for the state and is followed by a rule specifying how to create that component.</p>

<pre class="code">var patrol : Patrol = new Patrol();
patrol.path = PatrolPathFactory.getPath( node.entity.name );
patrolState.add( Patrol ).withInstance( patrol );
attackState.add( Attack );</pre>

<p>The four standard rules for components are</p>

<pre class="code">entityState.add( type : Class );</pre>

<p>Without a rule, the state machine will create a new instance of the given type to provide the component every time the state is entered.</p>

<pre class="code">entityState.add( type : Class ).withType( otherType : Class );</pre>

<p>This rule will create a new instance of the otherType every time the state is entered. otherType should be the same as or extend the specified component type. You only need this rule if you create component classes that extend other component classes and should be treated as the base class by the engine, which is rare.</p>

<pre class="code">entityState.add( type : Class ).withInstance( instance : * );</pre>

<p>This method will use the provided instance for the component every time the state is entered.</p>

<p>Finally</p>

<pre class="code">entityState.add( type : Class ).withSingleton();</pre>

<p>or</p>

<pre class="code">entityState.add( type : Class ).withSingleton( otherType : Class );</pre>

<p>will create a single instance and use that one instance every time the state is entered. This is similar to using the withInstance method, but the withSingleton method will not create the instance until it is needed. If otherType is omitted, then the singleton with be an instance of type, if included it will be of otherType and otherType must be the same as or extend type.</p>

<p>Finally, you can use custom code to provide the component by implementing the <a href="https://github.com/richardlord/Ash/blob/master/src/ash/fsm/IComponentProvider.as">IComponentProvider</a> interface and then using your custom provider with</p>

<pre class="code">entityState.add( type : Class ).withProvider( provider : IComponentProvider );</pre>

<p>The IComponentProvider interface is defined as</p>

<pre class="code">public interface IComponentProvider
{
    function getComponent() : *;
    function get identifier() : *;
}</pre>

<p>The getComponent method returns a component instance. The identifier in the IComponentProvider is used to compare two component providers to see if they will effectively return the same component. This is used to avoid replacing a component unnecessarily if two successive states use the same component.</p>

<p>The methods are designed to be chained together, to create a fluid interface, as you’ll see in the next example.</p>

<h2>Back to the examples</h2>

<p>If we apply these new tools to the spaceship example, the states are set-up when the spaceship entity is created, as follows</p>

<pre class="code">var fsm : EntityStateMachine = new EntityStateMachine( spaceshipEntity );

fsm.createState( "playing" )
   .add( Motion ).withInstance( new Motion( 0, 0, 0, 15 ) )
   .add( MotionControls )
       .withInstance( new MotionControls( Keyboard.LEFT, Keyboard.RIGHT, Keyboard.UP, 100, 3 ) )
   .add( Gun ).withInstance( new Gun( 8, 0, 0.3, 2 ) )
   .add( GunControls ).withInstance( new GunControls( Keyboard.SPACE ) )
   .add( Collision ).withInstance( new Collision( 9 ) )
   .add( Display ).withInstance( new Display( new SpaceshipView() ) );

fsm.createState( "destroyed" )
   .add( DeathThroes ).withInstance( new DeathThroes( 5 ) )
   .add( Display ).withInstance( new Display( new SpaceshipDeathView() ) );

var spaceshipComponent : Spaceship = new Spaceship();
spaceshipComponent.fsm = fsm;
spaceshipEntity.add( spaceshipComponent );
fsm.changeState( "playing" );</pre>

<p>and the state change is simplified to</p>

<pre class="code">for ( spaceship = spaceships.head; spaceship; spaceship = spaceship.next )
{
    for ( asteroid = asteroids.head; asteroid; asteroid = asteroid.next )
    {
        if ( Point.distance( asteroid.position.position, spaceship.position.position )
            <= asteroid.position.collisionRadius + spaceship.position.collisionRadius )
        {
            spaceship.spaceship.fsm.changeState( "destroyed" );
            break;
        }
    }
}</pre>

<h2>To do</h2>

<p>There will be further refinement and additions to the state machine tools based on feedback so please do let me know how you get on with them. Use <a href="http://groups.google.com/group/ash-framework?hl=en">the mailing list for Ash</a> to get in touch.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/finite-state-machines-with-ash/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Using the iPad retina display with Adobe Air</title>
		<link>http://www.richardlord.net/blog/using-the-ipad-retina-display-with-adobe-air</link>
		<comments>http://www.richardlord.net/blog/using-the-ipad-retina-display-with-adobe-air#comments</comments>
		<pubDate>Mon, 19 Mar 2012 09:51:26 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Air]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=1033</guid>
		<description><![CDATA[Last Friday, the new iPad was launched by Apple, with its new retina display. I did a few tests to try to use the high-resolution retina screen at its maximum resolution from Adobe Air. Here are the results. The simple option doesn&#8217;t work The first thing to note is that Apple deliberately limited the new [...]]]></description>
				<content:encoded><![CDATA[<p>Last Friday, the new iPad was launched by Apple, with its new retina display. I did a few tests to try to use the high-resolution retina screen at its maximum resolution from Adobe Air. Here are the results.</p>

<h3>The simple option doesn&#8217;t work</h3>

<p>The first thing to note is that Apple deliberately limited the new retina resolution to Apps built with the iOS 5.1 SDK. This is to avoid incompatibility issues with Apps that were released before the new iPad was available. So apps built with earlier versions of the iOS SDK use pixel doubling and have an effective resolution of 1024&#215;768 pixels, like the iPad 2.</p>

<p>By default, Adobe Air compiles with iOS 4.0. I don&#8217;t know what&#8217;s special about iOS 4.0 that Adobe can distribute this version with Air but not later versions, but that&#8217;s the way it is. So, if you compile your Air app the normal way, you will not get retina resolution on the new iPad. Everything will still work fine, but it will use pixel doubling to get the same results as on the iPad 2.</p>

<h3>Compiling with iOS 5.1</h3>

<p>If you have a Mac, there is a solution. Adobe Air (since Air 3.1) includes a build setting to specify the version of the iOS SDK to use. The setting is the platformsdk and you can read more about it on <a href="http://blogs.adobe.com/rajorshi/2011/11/16/ios5-support-for-airusing-external-sdks-to-package-apps/">this Adobe blog</a>. If you read through the comments in that post you&#8217;ll see that this is only supported when compiling on OSX, at the moment, but Adobe hope to bring it to Windows sometime in the future.</p>

<p>So, if you have a Mac, download and install XCode. In the new XCode, the SDK is inside the application package &#8211; the filepath is /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/. Now use the playformsdk setting to build against iOS 5.1.</p>

<h3>The test</h3>

<p>To test this I built a little app, with just a few lines of code &#8211; </p>

<pre class="code">package com.sticksports.test
{
  import flash.display.Sprite;
  import flash.display.StageAlign;
  import flash.display.StageScaleMode;
  import flash.events.Event;
  import flash.system.Capabilities;
  import flash.text.TextField;

  public class RetinaTest extends Sprite
  {
    public function RetinaTest()
    {
      stage.scaleMode = StageScaleMode.NO_SCALE;
      stage.align = StageAlign.TOP_LEFT;
      addEventListener( Event.ENTER_FRAME, getStats );
    }
    
    private function getStats( event : Event ) : void
    {
      removeEventListener( Event.ENTER_FRAME, getStats );
      
      var textField : TextField = new TextField();
      textField.width = stage.stageWidth - 40;
      textField.height = stage.stageHeight - 40;
      textField.x = 20;
      textField.y = 20;
      textField.border = true;
      textField.multiline = true;
      addChild( textField );
      
      textField.appendText( "Capabilities.screenResolutionX : " + Capabilities.screenResolutionX + "\n" );
      textField.appendText( "Capabilities.screenResolutionY : " + Capabilities.screenResolutionY + "\n" );
      textField.appendText( "Capabilities.screenDPI : " + Capabilities.screenDPI + "\n" );
      textField.appendText( "stage.stageWidth : " + stage.stageWidth + "\n" );
      textField.appendText( "stage.stageHeight : " + stage.stageHeight + "\n" );
      textField.appendText( "stage.fullScreenWidth : " + stage.fullScreenWidth + "\n" );
      textField.appendText( "stage.fullScreenHeight : " + stage.fullScreenHeight + "\n" );    }
  }
}</pre>

<p>I didn&#8217;t use Flash Builder for my tests because I&#8217;m an FDT user, so the apps were built from Ant scripts. First I built the swf in the standard way.</p>

<pre class="code">&lt;exec executable="${sdk.home}/bin/amxmlc" failonerror="true" dir="../package"&gt;
  &lt;arg line='-source-path ../src'/&gt;
  &lt;arg line='-default-size=960,640'/&gt;
  &lt;arg line='-default-background-color 0xFFFFFF'/&gt;
  &lt;arg line='-default-frame-rate 60'/&gt;
  &lt;arg line='-debug=false'/&gt;
  &lt;arg line='-optimize=true'/&gt;
  &lt;arg line='-swf-version=13'/&gt;
  &lt;arg line='-output RetinaTest.swf'/&gt;
  &lt;arg line='../src/com/sticksports/test/RetinaTest.as'/&gt;
&lt;/exec&gt;</pre>

<p>I gave the swf a default size to match the iPhone, just to see what Air gave me as the stage size as a result.</p>

<p>The application descriptor file requests the high resolution display, as for the iPhone retina screen.</p>

<pre class="code">&lt;?xml version="1.0" encoding="utf-8" standalone="no"?&gt;
&lt;application xmlns="http://ns.adobe.com/air/application/3.0"&gt;

  &lt;id&gt;com.sticksports.RetinaTest&lt;/id&gt;
  &lt;filename&gt;RetinaTest&lt;/filename&gt;
  &lt;name&gt;Retina Test&lt;/name&gt;
  &lt;versionNumber&gt;0.0.1&lt;/versionNumber&gt;
  &lt;versionLabel&gt;v0.0.1&lt;/versionLabel&gt;
  &lt;copyright&gt;Stick Sports Ltd.&lt;/copyright&gt;

  &lt;initialWindow&gt;
    &lt;content&gt;RetinaTest.swf&lt;/content&gt;
    &lt;aspectRatio&gt;portrait&lt;/aspectRatio&gt;
    &lt;autoOrients&gt;true&lt;/autoOrients&gt;
    &lt;fullScreen&gt;true&lt;/fullScreen&gt;
    &lt;renderMode&gt;cpu&lt;/renderMode&gt;
    &lt;softKeyboardBehavior&gt;none&lt;/softKeyboardBehavior&gt;
    &lt;/initialWindow&gt;

  &lt;icon&gt;
    &lt;image29x29&gt;icons/icon_29.png&lt;/image29x29&gt;
    &lt;image57x57&gt;icons/icon_57.png&lt;/image57x57&gt; 
    &lt;image72x72&gt;icons/icon_72.png&lt;/image72x72&gt; 
    &lt;image114x114&gt;icons/icon_114.png&lt;/image114x114&gt; 
  &lt;/icon&gt;
  
  &lt;iPhone&gt;
    &lt;InfoAdditions&gt;
      &lt;![CDATA[
        &lt;key&gt;UIDeviceFamily&lt;/key&gt;
        &lt;array&gt;
          &lt;string&gt;1&lt;/string&gt;
          &lt;string&gt;2&lt;/string&gt;
        &lt;/array&gt;
        &lt;key&gt;UIStatusBarStyle&lt;/key&gt;
        &lt;string&gt;UIStatusBarStyleBlackOpaque&lt;/string&gt;
      ]]&gt;
    &lt;/InfoAdditions&gt;
    &lt;requestedDisplayResolution&gt;high&lt;/requestedDisplayResolution&gt;
  &lt;/iPhone&gt;

&lt;/application&gt;</pre>

<p>I built the ipa twice, using the <a href="http://labs.adobe.com/downloads/air3-2.html">Air 3.2 release candidate from Adobe Labs</a>. I built it once using the default version of the iPhone SDK (version 4.0) that is bundled with Air.</p>

<pre class="code">&lt;exec executable="${sdk.home}/bin/adt" failonerror="true" dir="../package"&gt;
  &lt;arg value="-package"/&gt;
  &lt;arg value="-target"/&gt;
  &lt;arg value="ipa-ad-hoc"/&gt;
  &lt;arg value="-provisioning-profile"/&gt;
  &lt;arg value="${ios.provisioning.profile}"/&gt;
  &lt;arg value="-storetype"/&gt;
  &lt;arg value="pkcs12"/&gt;
  &lt;arg value="-keystore"/&gt;
  &lt;arg value="${ios.keystore.file}"/&gt;
  &lt;arg value="-storepass"/&gt;
  &lt;arg value="${ios.keystore.password}"/&gt;
  &lt;arg value="../publish/default/RetinaTest.ipa"/&gt;
  &lt;arg value="../build/RetinaTest-app.xml"/&gt;
  &lt;arg value="RetinaTest.swf"/&gt;
  &lt;arg value="Default.png"/&gt;
  &lt;arg value="icons"/&gt;
&lt;/exec&gt;</pre>

<p>And once with the iOS 5.1 SDK</p>

<pre class="code">&lt;exec executable="${sdk.home}/bin/adt" failonerror="true" dir="../package"&gt;
  &lt;arg value="-package"/&gt;
  &lt;arg value="-target"/&gt;
  &lt;arg value="ipa-ad-hoc"/&gt;
  &lt;arg value="-provisioning-profile"/&gt;
  &lt;arg value="${ios.provisioning.profile}"/&gt;
  &lt;arg value="-storetype"/&gt;
  &lt;arg value="pkcs12"/&gt;
  &lt;arg value="-keystore"/&gt;
  &lt;arg value="${ios.keystore.file}"/&gt;
  &lt;arg value="-storepass"/&gt;
  &lt;arg value="${ios.keystore.password}"/&gt;
  &lt;arg value="../publish/5.1/RetinaTest.ipa"/&gt;
  &lt;arg value="../build/RetinaTest-app.xml"/&gt;
  &lt;arg value="RetinaTest.swf"/&gt;
  &lt;arg value="Default.png"/&gt;
  &lt;arg value="icons"/&gt;
  &lt;arg line="-platformsdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/"/&gt;
&lt;/exec&gt;</pre>

<p>The equivalent command-line script is</p>

<p><code>adt -package -target ipa-ad-hoc -provisioning-profile YOUR_PROVISIONING_PROFILE -storetype pkcs12 -keystore YOUR_KEYSTORE_FILE -storepass YOUR_KEYSTORE_PASSWORD RetinaTest.ipa RetinaTest-app.xml RetinaTest.swf Default.png icons -platformsdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/</code></p>

<h3>The results</h3>

<p>With the default SDK the results are</p>

<pre class="code">Capabilities.screenResolutionX : 768
Capabilities.screenResolutionY : 1024
Capabilities.screenDPI : 132
stage.stageWidth : 960
stage.stageHeight : 640
stage.fullScreenWidth : 768
stage.fullScreenHeight : 1024</pre>

<p>I was surprised the stageWidth and stageHeight don&#8217;t match the screenResolutionX and screenResolutionY, which is why I use the latter in my projects. As Florian mentioned in the comments, you can also use fullScreenWidth and fullScreenHeight, which I added after reading his comment. Aside from that, there&#8217;s no surprises here. The results are the same as on the iPad2.</p>

<p>With iOS 5.1 SDK, the results are</p>

<pre class="code">Capabilities.screenResolutionX : 1536
Capabilities.screenResolutionY : 2048
Capabilities.screenDPI : 132
stage.stageWidth : 1536
stage.stageHeight : 2048
stage.fullScreenWidth : 1536
stage.fullScreenHeight : 2048</pre>

<p>This version uses the full resolution of the retina screen. The text is half the size on screen because the pixel resolution is doubled and the screenResolutionX and screenResolutionY and fullScreenWidth and fullScreenHeight are the correct size for the retina display. This time, surprisingly, the stageWidth and stageHeight did match the screen resolution &#8211; all the more reason not to trust them. Also, the screenDPI is incorrect, showing the same value as the iPad 2.</p>

<p>But, most importantly, the project has access to the full retina screen resolution. Hurrah!</p>

<h3>Building with Air 3.1</h3>

<p>As I said above, I initially used the public beta of Air 3.2 for this test. I reran the test using Air 3.1 and the results were the same, except building with Air 3.1 and iOS 5.1 gave the stageWidth as 1920px and stageHeight as 1280px. All other results were the same as for Air 3.2.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/using-the-ipad-retina-display-with-adobe-air/feed</wfw:commentRss>
		<slash:comments>46</slash:comments>
		</item>
		<item>
		<title>20 tips for creating Air Native Extensions for iOS</title>
		<link>http://www.richardlord.net/blog/20-tips-for-creating-air-native-extensions-for-ios</link>
		<comments>http://www.richardlord.net/blog/20-tips-for-creating-air-native-extensions-for-ios#comments</comments>
		<pubDate>Thu, 01 Mar 2012 14:03:53 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Air]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Native Extension]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=1022</guid>
		<description><![CDATA[Over the past three months I&#8217;ve created three Air Native Extensions for iOS (available on Github), which were all used in our game Stick Cricket Super Sixes, and have discovered a lot along the way. I&#8217;ve forgotten some of it, but here&#8217;s a few of the tips I can remember for anyone else approaching this [...]]]></description>
				<content:encoded><![CDATA[<p>Over the past three months I&#8217;ve created three Air Native Extensions for iOS (<a href="https://github.com/StickSports">available on Github</a>), which were all used in our game <a href="http://itunes.apple.com/app/id483135193?ls=1&#038;mt=8">Stick Cricket Super Sixes</a>, and have discovered a lot along the way. I&#8217;ve forgotten some of it, but here&#8217;s a few of the tips I can remember for anyone else approaching this task.</p>

<h3>Documentation</h3>

<h4>1. Getting Started</h4>

<p>Here&#8217;s a couple of useful getting started guides. If you don&#8217;t know what you&#8217;re doing, this is a good place to start. There are more on the web, just ask Google.</p>

<ul>
<li><a href="http://www.adobe.com/devnet/air/articles/extending-air.html">Extending Adobe Air</a></li>
<li><a href="http://custardbelly.com/blog/2011/09/21/air-native-extension-example-ibattery-for-ios/">AIR Native Extension Example: iBattery for iOS</a></li>
</ul>

<h4>2. Read Adobe&#8217;s documentation.</h4>

<p>For the most part <a href="http://help.adobe.com/en_US/air/extensions/index.html">Adobe&#8217;s documentation</a> is comprehensive and detailed. <a href="http://help.adobe.com/en_US/air/extensions/index.html">Use it</a>.</p>

<h3>Writing the Actionscript code</h3>

<h4>3. Pay attention to the Actionscript API</h4>

<p>Make an Actionscript API that suits the functionality you&#8217;re implementing. Don&#8217;t get pulled into copying Apple&#8217;s iOS API in Actionscript if there&#8217;s a better, more Actionscript like, way to do it.</p>

<p>Remember, changing the implementation later only affects the extension, but changing this API breaks all projects that use the extension so make it as good as you can.</p>

<h4>4. Maximise the error checking in your Actionscript code</h4>

<p>You need to check the input to your extension methods to avoid errors. You could do this in the native code, but it&#8217;s a lot easier to do it in the Actionscript code. If you know you&#8217;ll always call the native code with the correct number of parameters, and that those parameters will always be valid values, you can avoid a lot of error checking in the native code.</p>

<p>Of course, if you enjoy writing error checking code in C, go right ahead. Personally, I prefer to do this in Actionscript.</p>

<h4>5. Always create a default implementation</h4>

<p>Even if you&#8217;re only planning to use your extension on iOS, create a default implementation anyway. You build this default implementation in pure Actionscript, so it works on all platforms. It implements the same API as the iOS version, but using only Actionscript. That means it may throw errors or returns null values, but it will be valid Actionscript code that you can compile against for platforms other than iOS.</p>

<p>Without a default implementation, you can only ever test your app on an iOS device. This makes testing your app during development very tiresome. Being able to compile your app for desktop Air to test a new feature that&#8217;s unrelated to your native extension is very useful.</p>

<h3>Writing the native code</h3>

<h4>6. Use Objective-C to interface to Apple&#8217;s APIs.</h4>

<p>You don&#8217;t have to use Objective-C, but if you&#8217;re interfacing with any of Apple&#8217;s APIs it&#8217;s easier if you do. Otherwise, you can use C or C++.</p>

<h4>7. Place the C code for the Air-Native interface in a .m file.</h4>

<p>The interface between the native code and Air is via C, so your native code will include one file of C code to provide this interface. If you place this code inside a .c file, you can&#8217;t use any Objective-C functionality in there (e.g. you can&#8217;t use objective-c style code to call objective-c APIs), but if you place it inside a .m file you can. So life is easier if you use a .m extension.</p>

<h4>8. The .m file containing the Air-Native interface doesn&#8217;t need a .h header file.</h4>

<p>But you&#8217;ll want to disable the error messages so turn off warnings for &#8220;missing function prototypes&#8221; in your XCode project settings.</p>

<h4>9. Use unique names for your extension initializer and finalizer functions.</h4>

<p>A number of example extensions use generic names like &#8220;extInitializer&#8221; and &#8220;extFinalizer&#8221; for the initializer and finalizer functions. No two extensions in your project may have the same names for these functions, so use names that are appropriate to your project.</p>

<h4>10. Use macros in your source code</h4>

<p>How many times can you type</p>

<pre class="code">FREObject someFunction(FREContext context, void* functionData, uint32_t argc, FREObject argv[])</pre>

<p>before you want to poke yourself in the eye with a blunt stick? Create a macro for this, and any other repetitive tasks for implementing the Air-Native interface. You can see a few of my macros in <a href="https://github.com/StickSports/ANE-Game-Center/blob/master/ios/GameCenterIosExtension/GameCenterIosExtension.m">this source file</a>. (Thank you to <a href="https://github.com/mnem/box2d_ane">David Wagner</a> for some of these.)</p>

<h4>11. Set &#8220;Enable linking with shared libraries&#8221; to yes</h4>

<p>There&#8217;s a lot of noise around the web about this XCode project setting, with some saying use &#8220;no&#8221; and some saying use &#8220;yes&#8221;. Basically, setting this to yes means your extension will be linked with the required libraries later when you compile your app. This is what you want. But it means when you compile your Air app that uses your native extension, you&#8217;ll need to direct the compiler to the iOS SDK so it can link to the libraries. See item 18 below.</p>

<p>N.B. If you get a build error</p>

<pre class="code">ld warning: unexpected srelocation type 9</pre>

<p>then you probably either have this setting as no or you haven&#8217;t specified the location of the iOS SDK when building your app.</p>

<h4>12. Be careful with threads</h4>

<p>Your native extension can&#8217;t create Actionscript objects in any but the main thread from which it is called, and must do so during a call from Air. This makes using blocks in your objective-c code problematic. However, there is one thing you can do from another thread, and that is dispatch an event to the Actionscript ExtensionContext. This offers a solution</p>

<ol>
<li>In your block or other threaded code, store your data into a native object.</li>
<li>Dispatch an event to your ExtensionContext with whatever details it needs for step 3.</li>
<li>In response to the event, call a native method to fetch the object.</li>
<li>In this native method, create the Actionscript object from the native object created in step 1 and return it.</li>
</ol>

<h4>13. Creating native views</h4>

<p>Your Air application runs inside a standard native window. You can get a reference to this window as</p>

<pre class="code">[UIApplication sharedApplication].keyWindow</pre>

<p>Once you have this window reference you can add subviews to it to display native views.</p>

<h3>Compiling the Extension</h3>

<h4>14. Automate the compiling and testing of your extension</h4>

<p>When building my Game Center extension I created a simple air app for testing the extension.</p>

<p>I created an ant build script to compile the whole extension (build the native C/obj-C library, build the native AS3 library, build the default AS3 library, wrap them all as an Air native extension) and to build the test project.</p>

<p>The result, one click in Eclipse and I had the extension built and the test project built against it, ready to drop on my phone (and using the Organiser in XCode makes this last step easy too). The result &#8211; it took about 10 seconds to go from writing code to having the test project with the latest extension on my phone. That&#8217;s still 9 seconds too long but it&#8217;s a lot better than most workflows I&#8217;ve seen.</p>

<p>Maybe there&#8217;s a better way if you use Flash Builder (I use <a href="http://fdt.powerflasher.com/">FDT</a>), and you certainly don&#8217;t have to use Ant &#8211; any build tool will do. But streamline the build and test process as much as you can. My ant scripts are in my <a href="https://github.com/StickSports/ANE-Game-Center/blob/master/build/build.xml">Game Center extension project</a> if you want them.</p>

<h4>15. Using a third party library</h4>

<p>If you&#8217;re using a third party library in your extension (e.g. the Flurry analytics library in my <a href="https://github.com/StickSports/ANE-Flurry-Analytics">Flurry extension</a>), include that library along with your compiled native library in the &#8220;-platform iPhone-ARM&#8221; argument when compiling the extension.</p>

<h4>16. You may need a platform.xml file.</h4>

<p>If using any but the most common libraries in the iOS SDK, create a <a href="https://github.com/StickSports/ANE-Game-Center/blob/master/build/platform.xml">platform.xml</a> file to specify the libraries you&#8217;re using and the minimum iOS version to build against.</p>

<p>I create a platform.xml file for all my extensions &#8211; it hides the warning about unknown minimum iOS version that Air 3.1 will display if you don&#8217;t.</p>

<h3>Building your mobile application</h3>

<h4>17. If your IDE doesn&#8217;t know about native extensions, use the .swc from the default implementation.</h4>

<p>This swc contains the full Actionscript API of the native extension in a pure Actionscript implementation, so you can code against it, and compile with it for testing on your dev computer.</p>

<p>Of course, an IDE that doesn&#8217;t know about native extensions won&#8217;t build your mobile app correctly, but you&#8217;re using a build script for that aren&#8217;t you.</p>

<h4>18. Specify the location of the iOS SDK when compiling your Air mobile app.</h4>

<p>By default, the Air compiler compiles against version 4.0 of the iOS SDK. If your native extension uses features that don&#8217;t exist in this version it will fail to compile because the required libraries can&#8217;t be found. Specify the location of a later version of the iOS SDK to enable this linking. See <a href="http://blogs.adobe.com/rajorshi/2011/11/16/ios5-support-for-airusing-external-sdks-to-package-apps/">this blog post</a> for more details.</p>

<p>In Flash Builder, there is a setting for this somewhere in the various screens for configuring the native extensions your project uses. If you&#8217;re using the command line compiler, use the -platformsdk compiler flag to specify the path to the iOS SDK.</p>

<p>Unfortunately, this is only possible if you&#8217;re compiling your app on Mac OS X. Adobe are, apparently, working to get this working on Windows too. If you try to use a native extension that requires you to link to the SDK and don&#8217;t link to it, you will get a compile error like this (the second line may or may not be present).</p>

<pre class="code">Compilation failed while executing : ld64
ld: unknown option: -ios_version_min</pre>

<p>Unfortunately, this means that for the time being some native extensions can only be used if you compile on a Mac.</p>

<h4>19. ld: warning: ARM function not 4-byte aligned</h4>

<p>When compiling your app, you may get a number of warnings of the form</p>

<pre class="code">ld: warning: ARM function not 4-byte aligned</pre>

<p>These are just warnings and nothing to worry about. 4-byte alignment is an optimisation rather than a requirement.</p>

<h3>When it&#8217;s all done</h3>

<h4>20. Make your native extension available to others.</h4>

<p>Having completed your extension, you have three choices</p>

<ol>
<li>Keep it to yourself</li>
<li>Open-source it for other developers</li>
<li>Sell it to other developers</li>
</ol>

<p>Ask yourself what makes your app unique and special. If it&#8217;s not your native extension (and it very rarely is) then choosing option 2 or 3 may have many benefits for you like code contributions from others or additional income.</p>

<p>Further, by making your extension available to other developers you strengthen the ecosystem around Adobe Air as a tool for mobile development. This encourages other developers to use Air and encourages Adobe to continue to develop and improve it. This is in your interests.</p>

<p>At <a href="http://www.sticksports.com/mobile/">Stick Sports</a> we favour option 2 because we&#8217;d rather spend time marketing and supporting our games than marketing and supporting our extensions as commercial products.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/20-tips-for-creating-air-native-extensions-for-ios/feed</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>try{harder} level-up</title>
		<link>http://www.richardlord.net/blog/tryharder-level-up</link>
		<comments>http://www.richardlord.net/blog/tryharder-level-up#comments</comments>
		<pubDate>Mon, 27 Feb 2012 13:17:50 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[try{harder}]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=1015</guid>
		<description><![CDATA[The first try{harder} took place last October and I was lucky enough to be one of the 16 attendee/speakers. The four-day conference was residential &#8211; we lived together in four &#8220;executive cabins&#8221; at Center Parcs in Sherwood Forest. That means everyone had a double bedroom, an en-suite bathroom, and three new developer friends to have [...]]]></description>
				<content:encoded><![CDATA[<p>The first <a href="http://www.tryharder.org.uk/">try{harder}</a> took place last October and I was lucky enough to be one of the 16 attendee/speakers. The four-day conference was residential &#8211; we lived together in four &#8220;executive cabins&#8221; at <a href="http://www.centerparcs.co.uk/villages/sherwood">Center Parcs in Sherwood Forest</a>. That means everyone had a double bedroom, an en-suite bathroom, and three new developer friends to have breakfast with.</p>

<p>If you ask people who attend conferences why they do it, most of them will tell you it&#8217;s for the networking. Some of the presentations will be good, but it&#8217;s the conversations, over coffee, over beer, and over dinner, that make the conference worthwhile. Because the best thing you get from a conference is the opportunity to share experiences with other developers, to talk about code, to learn from each other.</p>

<p>try{harder} has that in spades. try{harder} is about sixteen experienced developers teaching and learning. Seminars, code jams, pair programming, and of course conversations. Not shallow chats, but important debates, with depth and breadth, explored over a four day period. Sometimes lubricated with fine scotch whisky (thank you <a href="http://noiseandheat.com/">David</a>). The experience is intense, exhausting, exhilirating, and absolutely wonderful.</p>

<p>October&#8217;s try{harder} was the first. After it I&#8217;d learnt more about TDD than I&#8217;d learnt in the previous two years of (sometimes) unit testing my code. I&#8217;d learnt enough to kickstart my development of <a href="https://github.com/StickSports">Air native extensions</a>. I&#8217;d learnt about build tools, debugging tools, and promises. I&#8217;d learnt about the inner workings of the Flash player, and about <a href="https://github.com/robotlegs/robotlegs-framework">Robotlegs 2</a> and <a href="https://github.com/tschneidereit/SwiftSuspenders">SwiftSuspenders 2</a>. I&#8217;d learnt about myself. And I&#8217;d been inspired enough to dig deeper into <a href="/blog/what-is-an-entity-framework">Entity frameworks</a> and to write <a href="/blog/introducing-ash">Ash</a>.</p>

<p>And more than all that, I&#8217;d gained sixteen new friends. That&#8217;s fifteen great developers and <a href="http://www.xxcoder.net/">Stray</a>&#8216;s lovely wife Helen. These are friends who know and understand what I do for a living. Friends I can turn to for advice and help, as I did recently when wondering which cloud platform would suit a particular need.</p>

<p>This spring will see another try{harder} born. This one is subtitled &#8216;level-up&#8217; because it&#8217;s all about the alumni from the previous try{harder} sharing their experience and their knowledge with eight other, less experienced developers. It&#8217;s about helping those mid-to-senior developers realise their potential.</p>

<p>It will feature the same mix of <a href="http://www.tryharder.org.uk/level-up-2012/timetable/">seminars, programming and conversations</a>. The same intense learning experience. But in addition, to help the newcommers they will each be mentored by an alumni.</p>

<p>I am very disappointed that I can&#8217;t be a mentor at try{harder} level-up. Unfortunately I have work commitments that can&#8217;t be moved. But <a href="http://www.tryharder.org.uk/level-up-2012/mentors/">the mentors</a> who will be there are fantastic.</p>

<p>If you&#8217;re looking to improve your developer skills, <a href="http://www.tryharder.org.uk/level-up-2012/">try{harder} level-up</a> is an opportunity to learn from the best. I highly recommend it.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/tryharder-level-up/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why use an entity system framework for game development?</title>
		<link>http://www.richardlord.net/blog/why-use-an-entity-framework</link>
		<comments>http://www.richardlord.net/blog/why-use-an-entity-framework#comments</comments>
		<pubDate>Thu, 16 Feb 2012 13:29:40 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Ash]]></category>
		<category><![CDATA[Entity systems]]></category>
		<category><![CDATA[Game development]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=998</guid>
		<description><![CDATA[Following my previous post on entity systems for game development I received a number of good questions from developers. I answered many of them in the comments on that post, but one question stands out. It&#8217;s all very well explaining what an entity system framework is, and even building one, but why would you want [...]]]></description>
				<content:encoded><![CDATA[<p>Following my <a href="/blog/what-is-an-entity-framework">previous post</a> on entity systems for game development I received a number of good questions from developers. I answered many of them in the <a href="/blog/what-is-an-entity-framework#comments">comments on that post</a>, but one question stands out. It&#8217;s all very well explaining what an entity system framework is, and even <a href="/blog/introducing-ash">building one</a>, but why would you want to use one? In particular, why use the later component/system architecture I described and that I implement in <a href="http://www.ashframework.org/">Ash</a> rather than the earlier object-oriented entity architecture as used, for example, in <a href="http://pushbuttonengine.com/">PushButton Engine</a>.</p>

<p>So, in this post I will look more at what the final architecture is, what it gives us that other architectures don&#8217;t, and why I personally prefer this architecture.</p>

<h3>The core of the architecture</h3>

<img src="/images/blog/entity5.png" alt="" width="459" height="251" />

<p>First, it&#8217;s worth noting that the core of this architecture is the components and the systems. Components are value-objects that contain the state of the game, and systems are the logic that operates on that state, changing it as the game progresses. The other elements of the architecture are purely incidental, designed to make life easier.</p>

<p>The entity object is present to collect related components together. The relation between components is encapsulated by the concept of an entity and that is vital to the architecture, but it isn&#8217;t necessary to use an explicit Entity object for this. There are some frameworks that simply use an id to represent the entity, adding the entity id to every component to indicate which entity it belongs to. In this scenario there is no requirement for an entity object at all and entity based operations are performed through an entity manager, using the id to indicate which entity they are operating on.</p>

<p>As a concept, the entity is vital to the architecture. But as a code construct it is entirely optional. I include it because, when using an object-oriented language, the entity object makes life easier. In particular, it enables us to create the methods that operate on the entity as methods of an entity object and to track and manage the entity through this object, removing the need to track ids throughout the code.</p>

<p>While the concept of an entity is vital to the architecture, the concept of node objects is entirely incidental. The nodes are used as the objects in the collections of components supplied to the systems. We could instead provide each system with a collection of the relevant entities and let the systems pull the components they want to operate on out of the entities, using the get() method of the entity.</p>

<p>In Ash, the nodes serve two purposes. First they enable us to use a more efficient data structure in which the node objects that the systems receive are nodes in a linked list. This improves the execution speed of the framework.</p>

<p>Second, using the node objects enables us to apply strong, static typing throughout our code. The method to fetch a component from an entity necessarily returns an untyped object, which must then be cast to the correct component type for use in the game code. The properties on the node are already statically typed to the components&#8217; data types, so no casting is necessary.</p>

<p>So, fundamentally, the entity architecture is about components and systems.</p>

<h3>This is not object-oriented programming</h3>

<p>We can build our entity architecture using an object-oriented language but, on a fundamental level, this is not object-oriented programming. The architecture is not about objects, it&#8217;s about data (components) and sub-routines that operate on that data (systems).</p>

<p>For many object-oriented programmers this is the hardest part of working with an entity system framework. Our tendency is to fall back to what we know and as an object-oriented programmer using an object-oriented language that means encapsulating data and operations together into objects. If you do this with a framework like Ash you will fail.</p>

<h3>Data-Oriented Programming</h3>

<p>Games tend to be about lots of fast changing state, with players, non-player characters, game objects like bullets and lasers, bats and balls, tables and chairs, and levels, scores, lives and more all having state that might include position, rotation, speed, acceleration, weight, colour, intention, goals, desires, friendships, enemies and more.</p>

<p>The state of the game can be encapsulated in this large mass of constantly changing data, and on a technical level the game is entirely about what this data is and how this data changes.</p>

<p>In a game a single little piece of this data may have many operations acting on it. Take, for example, a player character that has a position property that represents the character&#8217;s position in the game world. This single piece of data may be used by</p>

<ul>
<li>The render system, to draw the player in the world.</li>
<li>The camera system, to position the camera relative to the player.</li>
<li>The AI systems of all non-player characters, to decide how they should react to the player.</li>
<li>The input system, which alters the player&#8217;s position based on user input.</li>
<li>The physics system, which alters the player&#8217;s position based on the physics of the game world.</li>
<li>The collision system, which tests whether the player is colliding with other objects and resolves those collisions.</li>
</ul>

<p>and probably many more systems besides. If we try to build our game using objects that encapsulate data with the operations that act on that data, then we will build dependencies between all these different systems as they all want to be encapsulated with the player&#8217;s position data. This can&#8217;t be done unless we code the game as one single, massive class, so inevitably we break some parts of the game into separate systems and provide data to those systems &#8211; the physics system, the graphics system &#8211; while including other elements of the game logic within the entity objects themselves.</p>

<p>An entity architecture based on components and systems takes the idea of discrete systems to its logical conclusion. All operations are programmed as independent systems, and all game state is stored separately in a set of data components, which are provided to the systems according to their need.</p>

<p>The systems are decoupled form each other. Each system knows only about itself and the data it operates on. It knows and cares nothing at all about the other systems and how they may have affected by or used the data before or after this system gets to work with it.</p>

<p>Also, by embracing the system as the core logic of the architecture, we are encouraged to make many smaller and simpler systems rather than a few large complex ones, which again leads to simpler code and looser coupling.</p>

<p>This decoupling makes building your game much easier. It is why I enjoy working with this form of entity system so much, and why I built Ash.</p>

<h3>Storing the game state</h3>

<p>Another benefit of the component/system architecture is apparent when you want to save and restore the game state. Because the game state is contained entirely in the components, and because these are simple value objects, saving the game state is a relatively simple matter of serialising out the components, and restoring the game state involves just deserialising the data back in again.</p>

<p>In most cases, serialising a value-object is straightforward, and one could simply json-encode each component, with additional data to indicate its entity owner (an id) and its component type (a string), to save the game state.</p>

<p><a href="http://t-machine.org/">Adam Martin</a> wrote about <a href="http://t-machine.org/index.php/2011/08/22/entity-system-rdbms-beta-a-new-example-with-source/">comparing components in an entity system framework to data in a relational database</a> (there&#8217;s lots of interesting entity related stuff on <a href="http://t-machine.org/">Adam&#8217;s blog</a>), and emphasising that conversion between a relational database for long-term storage and components for game play doesn&#8217;t require any object/relational mapping, because components are simple copies of the relational database&#8217;s data structure rather than complex objects.</p>

<p>This leads further to the conclusion that a component/system architecture is ideal for an MMO game, since state will be stored in a relational database on the game servers, and much of the processing of that state will occur on the servers, where using a set of discrete, independent systems to process the data as the game unfolds is an excellent fit to both the data storage requirements of the state and the parallelism available on the servers.</p>

<h3>Concurrency</h3>

<p>Indeed, a component/system architecture is well suited to applying concurrency to a game. In most games, some of the systems are entirely independent of each other, including being independent of the order in which they are applied. This makes it easy to run these systems in parallel.</p>

<p>Further, most systems consist of a loop in which all nodes are processed sequentially. In many cases, the loop can be parallelised since the nodes can be updated independently of each other.</p>

<p>This gives us two places in the code where concurrency can be applied without altering the core logic of the game, which is inside the loop in the systems, or the core state of the game, which is in the components.</p>

<p>This makes adding concurrency to the game relatively simple.</p>

<h3>We don&#8217;t need object-orientation</h3>

<p>Finally, because the component/system architecture is not object-oriented, it lends itself to other programming languages that implement different programming paradigms like functional programming and procedural programming. While I created Ash as an Actionscript framework, this architecture would be well suited to Javascript for client side development or any of the many functional languages used for highly concurrent server side development.</p>

<h3>Update: In-game editors</h3>

<p><a href="http://www.tomseysdavies.com/">Tom Davies</a> has pointed out that a very valuable benefit to him is how easy it is to create an in-game level editor when developing with an entity system framework like <a href="https://github.com/tdavies/Ember2">Ember</a> or <a href="http://www.ashframework.org/">Ash</a>. You can see <a href="http://www.tomseysdavies.com/2012/02/07/samphire/">his example here</a>.</p>

<p>I agree with Tom, this is a very useful benefit of these frameworks. The complete separation of the game state and the game logic in an entity system framework makes it easy to create an editor that lets you alter the state (configuration, level design, AI, etc.) while playing the game. Add to this the easier saving and loading of state and you have a framework that is very well suited to in-game editing.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/why-use-an-entity-framework/feed</wfw:commentRss>
		<slash:comments>54</slash:comments>
		</item>
		<item>
		<title>Game architecture is different</title>
		<link>http://www.richardlord.net/presentations/game-architecture-is-different</link>
		<comments>http://www.richardlord.net/presentations/game-architecture-is-different#comments</comments>
		<pubDate>Thu, 19 Jan 2012 14:49:03 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
		
		<guid isPermaLink="false">http://www.richardlord.net/?page_id=976</guid>
		<description><![CDATA[Presented at try{harder}, 6 October 2011 In this session, I compared building a game (Asteroids) using an entity framework (Ember) and an MVC framework (Robotlegs) and concluded that the entity framework was more suited to this task. I then attempted to explain why. I also wrote a blog post that covers much of the material [...]]]></description>
				<content:encoded><![CDATA[<p>Presented at</p>
<ul>
<li><a href="http://www.tryharder.org.uk/">try{harder}</a>, 6 October 2011</li>
</ul>
<p>In this session, I compared building a game (Asteroids) using an entity framework (<a href="https://github.com/tdavies/Ember">Ember</a>) and an MVC framework (<a href="https://github.com/robotlegs/robotlegs-framework">Robotlegs</a>) and concluded that the entity framework was more suited to this task. I then attempted to explain why.</p>

<p>I also <a href="/blog/what-is-an-entity-framework">wrote a blog post</a> that covers much of the material in this presentation.</p>

<p>These are the slides from the presentation at try{harder} on Thursday, 6 October 2011.</p>

<div class="spaced" style="text-align:center"><div id="swf5197bc688915b">
<p><b>Flash required:</b> You need version 10 or later of the free Flash player from Adobe to use this content. To download and install the free player from Adobe's web site <a href="http://get.adobe.com/flashplayer/">click here</a>.</p>
</div>
<script type="text/javascript">
var params = {loop:"false",quality:"high",allowfullscreen:"true",allowscriptaccess:"always"};
var flashvars = {};
swfobject.embedSWF("http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=try-harder-120119082446-phpapp01&#038;stripped_title=game-architecture-is-different", "swf5197bc688915b", "595", "380", "10.0.0", "/swf/expressInstall.swf", flashvars, params, {} );
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/presentations/game-architecture-is-different/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is an entity system framework for game development?</title>
		<link>http://www.richardlord.net/blog/what-is-an-entity-framework</link>
		<comments>http://www.richardlord.net/blog/what-is-an-entity-framework#comments</comments>
		<pubDate>Thu, 19 Jan 2012 13:28:57 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Ash]]></category>
		<category><![CDATA[Entity systems]]></category>
		<category><![CDATA[Game development]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=961</guid>
		<description><![CDATA[Last week I released Ash, an entity system framework for Actionscript game development, and a number of people have asked me the question &#8220;What is an entity system framework?&#8221;. This is my rather long answer. Entity systems are growing in popularity, with well-known examples like Unity, and lesser known frameworks like Actionscript frameworks Ember2, Xember [...]]]></description>
				<content:encoded><![CDATA[<p>Last week I released <a href="http://www.ashframework.org/">Ash</a>, an entity system framework for Actionscript game development, and a number of people have asked me the question &#8220;What is an entity system framework?&#8221;. This is my rather long answer.</p>

<p>Entity systems are growing in popularity, with well-known examples like <a href="http://unity3d.com/">Unity</a>, and lesser known frameworks like Actionscript frameworks <a href="https://github.com/tdavies/Ember2">Ember2</a>, <a href="https://github.com/alecmce/xember">Xember</a> and my own <a href="http://www.ashframework.org/">Ash</a>. There&#8217;s a very good reason for this; they simplify game architecture, encourage clean separation of responsibilities in your code, and are fun to use.</p>

<p>In this post I will walk you through how an entity based architecture evolves from the old fashioned game loop. This may take a while. The examples will be in Actionscript because that happens to be what I&#8217;m using at the moment, but the architecture applies to all programming language.</p>

<p>This is based on <a href="/presentations/game-architecture-is-different">a presentation</a> I gave at <a href="http://www.tryharder.org.uk/">try{harder}</a> in 2011.</p>

<h3>The examples</h3>

<p>Throughout this post, I&#8217;ll be using a simple <a href="http://en.wikipedia.org/wiki/Asteroids_(video_game)">Asteroids</a> game as an example. I like to use Asteroids as an example because it involves simplified versions of many of the systems required in larger games &#8211; rendering, physics, ai, user control of a character, non-player characters.</p>

<h3>The game loop</h3>

<p>To understand why we use entity systems, you really need to understand the old-fashioned <a href="http://en.wikipedia.org/wiki/Game_programming#Game_structure">game loop</a>. A game loop for Asteroids might look something like this</p>

<pre class="code">function update( time:Number ):void
{
  game.update( time );
  spaceship.updateInputs( time );
  for each( var flyingSaucer:FlyingSaucer in flyingSaucers )
  {
    flyingSaucer.updateAI( time );
  }
  spaceship.update( time );
  for each( var flyingSaucer:FlyingSaucer in flyingSaucers )
  {
    flyingSaucer.update( time );
  }
  for each( var asteroid:Asteroid in asteroids )
  {
    asteroid.update( time );
  }
  for each( var bullet:Bullet in bullets )
  {
    bullet.update( time );
  }
  collisionManager.update( time );
  spaceship.render();
  for each( var flyingSaucer:FlyingSaucer in flyingSaucers )
  {
    flyingSaucer.render();
  }
  for each( var asteroid:Asteroid in asteroids )
  {
    asteroid.render();
  }
  for each( var bullet:Bullet in bullets )
  {
    bullet.render();
  }
}</pre>

<p>This game loop is called on a regular interval, usually every 60th of a second or every 30th of a second, to update the game. The order of operations in the loop is important as we update various game objects, check for collisions between them, and then draw them all. Every frame.</p>

<p>This is a very simple game loop. It&#8217;s simple because</p>

<ol>
<li>The game is simple</li>
<li>The game has only one state</li>
</ol>

<p>In the past, I have worked on console games where the game loop, a single function, was over 3,000 lines of code. It wasn&#8217;t pretty, and it wasn&#8217;t clever. That&#8217;s the way games were built and we had to live with it.</p>

<p>Entity system architecture derives from an attempt to resolve the problems with the game loop. It addresses the game loop as the core of the game, and pre-supposes that simplifying the game loop is more important than anything else in modern game architecture. More important than separation of the view from the controller, for example.</p>

<h3>Processes</h3>

<p>The first step in this evolution is to think about objects called processes. These are objects that can be initialised, updated on a regular basis, and destroyed. The interface for a process looks something like this.</p>

<pre class="code">interface IProcess
{
  function start():Boolean;
  function update( time:Number ):void;
  function end():void;
}</pre>

<p>We can simplify our game loop if we break it into a number of processes to handle, for example, rendering, movement, collision resolution. To manage those processes we create a process manager.</p>

<pre class="code">class ProcessManager
{
  private var processes:PrioritisedList;

  public function addProcess( process:IProcess, priority:int ):Boolean
  {
    if( process.start() )
    {
      processes.add( process, priority );
      return true;
    }
    return false;
  }

  public function update( time:Number ):void
  {
    for each( var process:IProcess in processes )
    {
      process.update( time );
    }
  }

  public function removeProcess( process:IProcess ):void
  {
    process.end();
    processes.remove( process );
  }
}</pre>

<p>This is a somewhat simplified version of a process manager. In particular, we should ensure we update the processes in the correct order (identified by the priority parameter in the add method) and we should handle the situation where a process is removed during the update loop. But you get the idea. If our game loop is broken into multiple processes, then the update method of our process manager is our new game loop and the processes become the core of the game.</p>

<h3>The render process</h3>

<p>Lets look at the render process as an example. We could just pull the render code out of the original game loop and place it in a process, giving us something like this</p>

<pre class ="code">class RenderProcess implements IProcess
{
  public function start() : Boolean
  {
    // initialise render system
    return true;
  }

  public function update( time:Number ):void
  {
    spaceship.render();
    for each( var flyingSaucer:FlyingSaucer in flyingSaucers )
    {
      flyingSaucer.render();
    }
    for each( var asteroid:Asteroid in asteroids )
    {
      asteroid.render();
    }
    for each( var bullet:Bullet in bullets )
    {
      bullet.render();
    }
  }
  
  public function end() : void
  {
    // clean-up render system
  }
}</pre>

<h3>Using an interface</h3>

<p>But this isn&#8217;t very efficient. We still have to manually render all the different types of game object. If we have a common interface for all renderable objects, we can simplify matters a lot.</p>

<pre class="code">interface IRenderable
{
  function render();
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.&lt;IRenderable&gt;;

  public function start() : Boolean
  {
    // initialise render system
    return true;
  }

  public function update( time:Number ):void
  {
    for each( var target:IRenderable in targets )
    {
      target.render();
    }
  }
  
  public function end() : void
  {
    // clean-up render system
  }
}</pre>

<p>Then our spaceship class might contain some code like this</p>

<pre class="code">class Spaceship implements IRenderable
{
  public var view:DisplayObject;
  public var position:Point;
  public var rotation:Number;

  public function render():void
  {
    view.x = position.x;
    view.y = position.y;
    view.rotation = rotation;
  }
}</pre>

<p>This code is based on the flash display list. If we were blitting, or using stage3d, it would be different, but the principles would be the same. We need the image to be rendered, and the position and rotation for rendering it. And the render function does the rendering.</p>

<h3>Using a base class and inheritance</h3>

<p>In fact, there&#8217;s nothing in this code that makes it unique to a spaceship. All the code could be shared by all renderable objects. The only thing that makes them different is which display object is assigned to the view property, and what the position and rotation are. So lets wrap this in a base class and use <a href="http://en.wikipedia.org/wiki/Inheritance_(computer_science)">inheritance</a>.</p>

<pre class="code">class Renderable implements IRenderable
{
  public var view:DisplayObject;
  public var position:Point;
  public var rotation:Number;

  public function render():void
  {
    view.x = position.x;
    view.y = position.y;
    view.rotation = rotation;
  }
}</pre>

<pre class="code">class Spaceship extends Renderable
{
}</pre>

<p>Of course, all renderable items will extend the renderable class, so we get a simple class heirarchy like this</p>

<img src="/images/blog/entity1.png" alt="" width="439" height="234" />

<h3>The move process</h3>

<p>To understand the next step, we first need to look at another process and the class it works on. So lets try the move process, which updates the position of the objects.</p>

<pre class="code">interface IMoveable
{
  function move( time:Number );
}</pre>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.&lt;IMoveable&gt;;
  
  public function start():Boolean
  {
    return true;
  }

  public function update( time:Number ):void
  {
    for each( var target:IMoveable in targets )
    {
      target.move( time );
    }
  }
  
  public function end():void
  {
  }
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  public var position:Point;
  public var rotation:Number;
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<pre class="code">class Spaceship extends Moveable
{
}</pre>

<h3>Multiple inheritance</h3>

<p>That&#8217;s almost good, but unfortunately we want our spaceship to be both moveable and renderable, and many modern programming languages don&#8217;t allow <a href="http://en.wikipedia.org/wiki/Multiple_inheritance">multiple inheritance</a>.</p>

<p>Even in those languages that do permit multiple inheritance, we have the problem that the position and rotation in the Moveable class should be the same as the position and rotation in the Renderable class.</p>

<p>One common solution is to use an inheritance chain, so that Moveable extends Renderable.</p>

<pre class="code">class Moveable extends Renderable implements IMoveable
{
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<pre class="code">class Spaceship extends Moveable
{
}</pre>

<p>Now the spaceship is both moveable and renderable. We can apply the same principles to the other game objects to get this class hierarchy.</p>

<img src="/images/blog/entity2.png" alt="" width="439" height="331" />

<p>We can even have static objects that just extend Renderable.</p>

<img src="/images/blog/entity2a.png" alt="" width="439" height="343" />

<h3>Moveable but not Renderable</h3>

<p>But what if we want a Moveable object that isn&#8217;t Renderable? An invisible game object, for example? Now our class hierarchy breaks down and we need an alternative implementation of the Moveable interface that doesn&#8217;t extend Renderable.<p>

<pre class="code">class InvisibleMoveable implements IMoveable
{
  public var position:Point;
  public var rotation:Number;
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<img src="/images/blog/entity3.png" alt="" width="439" height="343" />

<p>In a simple game, this is clumsy but manageable, but in a complex game using inheritance to apply the processes to objects rapidly becomes unmanageable as you&#8217;ll soon discover items in your game that don&#8217;t fit into a simple linear inheritance tree, as with the force-field above.</p>

<h3>Favour composition over inheritance</h3>

<p>It&#8217;s long been a sound principle of object-oriented programming to <a href="http://en.wikipedia.org/wiki/Composition_over_inheritance">favour composition over inheritance</a>. Applying that principle here can rescue us from this potential inheritance mess.</p>

<p>We&#8217;ll still need Renderable and Moveable classes, but rather than extending these classes to create the spaceship class, we will create a spaceship class that contains an instance of each of these classes.</p>

<pre class="code">class Renderable implements IRenderable
{
  public var view:DisplayObject;
  public var position:Point;
  public var rotation:Number;

  public function render():void
  {
    view.x = position.x;
    view.y = position.y;
    view.rotation = rotation;
  }
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  public var position:Point;
  public var rotation:Number;
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<pre class="code">class Spaceship
{
  public var renderData:IRenderable;
  public var moveData:IMoveable;
}</pre>

<p>This way, we can combine the various behaviours in any way we like without running into inheritance problems.</p>

<img src="/images/blog/entity4.png" alt="" width="645" height="234" />

<p>The objects made by this composition, the Static Object, Spaceship, Flying Saucer, Asteroid, Bullet and Force Field, are collectively called entities.

<p>Our processes remain unchanged.</p>

<pre class="code">interface IRenderable
{
  function render();
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.&lt;IRenderable&gt;;

  public function update(time:Number):void
  {
    for each(var target:IRenderable in targets)
    {
      target.render();
    }
  }
}</pre>

<pre class="code">interface IMoveable
{
  function move();
}</pre>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.&lt;IMoveable&gt;;

  public function update(time:Number):void
  {
    for each(var target:IMoveable in targets)
    {
      target.move( time );
    }
  }
}</pre>

<p>But we don&#8217;t add the spaceship entity to each process, we add it&#8217;s components. So when we create the spaceship we do something like this</p>

<pre class="code">public function createSpaceship():Spaceship
{
  var spaceship:Spaceship = new Spaceship();
  ...
  renderProcess.addItem( spaceship.renderData );
  moveProcess.addItem( spaceship.moveData );
  ...
  return spaceship;
}</pre>

<p>This approach looks good. It gives us the freedom to mix and match process support between different game objects without getting into spagetti inheritance chains or repeating ourselves. But there&#8217;s one problem.</p>

<h3>What about the shared data?</h3>

<p>The position and rotation properties in the Renderable class instance need to have the same values as the position and rotation properties in the Moveable class instance, since the Move process will change the values in the Moveable instance and the Render process will use the values in the Renderable instance.</p>

<pre class="code">class Renderable implements IRenderable
{
  public var view:DisplayObject;
  <b>public var position:Point;</b>
  <b>public var rotation:Number;</b>

  public function render():void
  {
    view.x = position.x;
    view.y = position.y;
    view.rotation = rotation;
  }
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  <b>public var position:Point;</b>
  <b>public var rotation:Number;</b>
  public var velocity:Point;
  public var angularVelocity:Number;

  public function move( time:Number ):void
  {
    position.x += velocity.x * time;
    position.y += velocity.y * time;
    rotation += angularVelocity * time;
  }
}</pre>

<pre class="code">class Spaceship
{
  public var renderData:IRenderable;
  public var moveData:IMoveable;
}</pre>

<p>To solve this, we need to ensure that both class instances reference the same instances of these properties. In Actionscript that means these properties must be objects, because objects can be passed by reference while primitives are passed by value.</p>

<p>So we introduce another set of classes, which we&#8217;ll call components. These components are just value objects that wrap properties into objects for sharing between processes.</p>

<pre class="code">class PositionComponent
{
  public var x:Number;
  public var y:Number;
  public var rotation:Number;
}</pre>

<pre class="code">class VelocityComponent
{
  public var velocityX:Number;
  public var velocityY:Number;
  public var angularVelocity:Number;
}</pre>

<pre class="code">class DisplayComponent
{
  public var view:DisplayObject;
}</pre>

<pre class="code">class Renderable implements IRenderable
{
  public var display:DisplayComponent;
  public var position:PositionComponent;

  public function render():void
  {
    display.view.x = position.x;
    display.view.y = position.y;
    display.view.rotation = position.rotation;
  }
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;

  public function move( time:Number ):void
  {
    position.x += velocity.velocityX * time;
    position.y += velocity.velocityY * time;
    position.rotation += velocity.angularVelocity * time;
  }
}</pre>

<p>When we create the spaceship we ensure the Moveable and Renderable instances share the same instance of the PositionComponent.</p>

<pre class="code">class Spaceship
{
  public function Spaceship()
  {
    moveData = new Moveable();
    renderData = new Renderable();
    moveData.position = new PositionComponent();
    moveData.velocity = new VelocityComponent();
    renderData.position = moveData.position;
    renderData.display = new DisplayComponent();
  }
}</pre>

<p>The processes remain unaffected by this change.</p>

<h3>A good place to pause</h3>

<p>At this point we have a neat separation of tasks. The game loop cycles through the processes, calling the update method on each one. Each process contains a collection of objects that implement the interface it operates on, and will call the appropriate method of those objects. Those objects each do a single important task on their data. Through the system of components, those objects are able to share data and thus the combination of multiple processes can produce complex updates in the game entities, while keeping each process relatively simple.</p>

<p>This architecture is similar to a number of entity systems in game development. The architecture follows good object-oriented principles and it works. But there&#8217;s more to come, starting with a moment of madness.</p>

<h3>Abandoning good object-oriented practice</h3>

<p>The current architecture uses good object-oriented practices like <a href="http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)">encapsulation</a> and <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibility</a> &#8211; the IRenderable and IMoveable implementations encapsulate the data and logic for single responsibilities in the updating of game entities every frame &#8211; and <a href="http://en.wikipedia.org/wiki/Composition_over_inheritance">composition</a> &#8211; the Spaceship entity is created by combining implementations of the IRenderable and IMoveable interfaces. Through the system of components we ensured that, where appropriate, data is shared between the different data classes of the entities.</p>

<p>The next step in this evolution of entity systems is somewhat counter-intuitive, breaking one of the core tenets of object-oriented programming. We break the encapsulation of the data and logic in the Renderable and Moveable implementations. Specifically, we remove the logic from these classes and place it in the processes instead.</p>

<p>So this</p>

<pre class="code">interface IRenderable
{
  function render();
}</pre>

<pre class="code">class Renderable implements IRenderable
{
  public var display:DisplayComponent;
  public var position:PositionComponent;

  public function render():void
  {
    display.view.x = position.x;
    display.view.y = position.y;
    display.view.rotation = position.rotation;
  }
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.&lt;IRenderable&gt;;

  public function update( time:Number ):void
  {
    for each( var target:IRenderable in targets )
    {
      target.render();
    }
  }
}</pre>

<p>Becomes this</p>

<pre class="code">class RenderData
{
  public var display:DisplayComponent;
  public var position:PositionComponent;
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.&lt;RenderData&gt;;

  public function update( time:Number ):void
  {
    for each( var target:RenderData in targets )
    {
      target.display.view.x = target.position.x;
      target.display.view.y = target.position.y;
      target.display.view.rotation = target.position.rotation;
    }
  }
}</pre>

<p>And this</p>

<pre class="code">interface IMoveable
{
  function move( time:Number );
}</pre>

<pre class="code">class Moveable implements IMoveable
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;

  public function move( time:Number ):void
  {
    position.x += velocity.velocityX * time;
    position.y += velocity.velocityY * time;
    position.rotation += velocity.angularVelocity * time;
  }
}</pre>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.&lt;IMoveable&gt;;

  public function move( time:Number ):void
  {
    for each( var target:Moveable in targets )
    {
      target.move( time );
    }
  }
}</pre>

<p>Becomes this</p>

<pre class="code">class MoveData
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;
}</pre>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.&lt;MoveData&gt;;

  public function move( time:Number ):void
  {
    for each( var target:MoveData in targets )
    {
      target.position.x += target.velocity.velocityX * time;
      target.position.y += target.velocity.velocityY * time;
      target.position.rotation += target.velocity.angularVelocity * time;
    }
  }
}</pre>

<p>It&#8217;s not immediately clear why we&#8217;d do this, but bear with me. On the surface, we&#8217;ve removed the need for the interface, and we&#8217;ve given the process something more important to do &#8211; rather than simply delegate its work to the IRenderable or IMoveable implementations, it does the work itself.</p>

<p>The first apparent consequence of this is that all entities must use the same rendering method, since the render code is now in the RenderProcess. But that&#8217;s not actually the case. We could, for example, have two processes, RenderMovieClip and RenderBitmap for example, and they could operate on different sets of entities. So we haven&#8217;t lost any flexibility.</p>

<p>What we gain is the ability to refactor our entities significantly to produce an architecture with clearer separation and simpler configuration. The refactoring starts with a question.</p>

<h3>Do we need the data classes?</h3>

<p>Currently, our entity</p>

<pre class="code">class Spaceship
{
  public var moveData:MoveData;
  public var renderData:RenderData;
}</pre>

<p>Contains two data classes</p>

<pre class="code">class MoveData
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;
}</pre>

<pre class="code">class RenderData
{
  public var display:DisplayComponent;
  public var position:PositionComponent;
}</pre>

<p>These data classes in turn contain three components</p>

<pre class="code">class PositionComponent
{
  public var x:Number;
  public var y:Number;
  public var rotation:Number;
}</pre>

<pre class="code">class VelocityComponent
{
  public var velocityX:Number;
  public var velocityY:Number;
  public var angularVelocity:Number;
}</pre>

<pre class="code">class DisplayComponent
{
  public var view:DisplayObject;
}</pre>

<p>And the data classes are used by the two processes</p>

<pre class="code">class MoveProcess implements IProcess
{
  private var targets:Vector.&lt;MoveData&gt;;

  public function move( time:Number ):void
  {
    for each( var target:MoveData in targets )
    {
      target.position.x += target.velocity.velocityX * time;
      target.position.y += target.velocity.velocityY * time;
      target.position.rotation += target.velocity.angularVelocity * time;
    }
  }
}</pre>

<pre class="code">class RenderProcess implements IProcess
{
  private var targets:Vector.&lt;RenderData&gt;;

  public function update( time:Number ):void
  {
    for each( var target:RenderData in targets )
    {
      target.display.view.x = target.position.x;
      target.display.view.y = target.position.y;
      target.display.view.rotation = target.position.rotation;
    }
  }
}</pre>

<p>But the entity shouldn&#8217;t care about the data classes. The components collectively contain the state of the entity. The data classes exist for the convenience of the processes. So we refactor the code so the spaceship entity contains the components rather than the data classes.</p>

<pre class="code">class Spaceship
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;
  public var display:DisplayComponent;
}</pre>

<pre class="code">class PositionComponent
{
  public var x:Number;
  public var y:Number;
  public var rotation:Number;
}</pre>

<pre class="code">class VelocityComponent
{
  public var velocityX:Number;
  public var velocityY:Number;
  public var angularVelocity:Number;
}</pre>

<pre class="code">class DisplayComponent
{
  public var view:DisplayObject;
}</pre>

<p>By removing the data classes, and using the constituent components instead to define the spaceship, we have removed any need for the spaceship entity to know what processes may act on it. The spaceship now contains the components that define its state. Any requirement to combine these components into other data classes for the processes is some other class&#8217;s responsibility.</p>

<h3>Systems and Nodes</h3>

<p>Some core code within the entity system framework (which we&#8217;ll get to in a minute) will dynamically create these data objects as they are required by the processes. In this reduced context, the data classes will be mere nodes in the collections (arrays, linked-lists, or otherwise, depending on the implementation) used by the processes. So to clarify this we&#8217;ll rename them as nodes.</p>

<pre class="code">class MoveNode
{
  public var position:PositionComponent;
  public var velocity:VelocityComponent;
}</pre>

<pre class="code">class RenderNode
{
  public var display:DisplayComponent;
  public var position:PositionComponent;
}</pre>

<p>The processes are unchanged, but in keeping with the more common naming I&#8217;ll also change their name and call them systems.</p>

<pre class="code">class MoveSystem implements ISystem
{
  private var targets:Vector.&lt;MoveNode&gt;;

  public function update( time:Number ):void
  {
    for each( var target:MoveNode in targets )
    {
      target.position.x += target.velocity.velocityX * time;
      target.position.y += target.velocity.velocityY * time;
      target.position.rotation += target.velocity.angularVelocity * time;
    }
  }
}</pre>

<pre class="code">class RenderSystem implements ISystem
{
  private var targets:Vector.&lt;RenderNode&gt;;

  public function update( time:Number ):void
  {
    for each( var target:RenderNode in targets )
    {
      target.display.view.x = target.position.x;
      target.display.view.y = target.position.y;
      target.display.view.rotation = target.position.rotation;
    }
  }
}</pre>

<pre class="code">interface ISystem
{
  function update( time:Number ):void;
}</pre>

<h3>And what is an entity?</h3>

<p>One last change &#8211; there&#8217;s nothing special about the Spaceship class. It&#8217;s just a container for components. So we&#8217;ll just call it Entity and give it a collection of components. We&#8217;ll access those components based on their class type.</p>

<pre class="code">class Entity
{
  private var components : Dictionary;
  
  public function add( component:Object ):void
  {
    var componentClass : Class = component.constructor;
    components[ componentClass ] = component'
  }
  
  public function remove( componentClass:Class ):void
  {
    delete components[ componentClass ];
  }
  
  public function get( componentClass:Class ):Object
  {
    return components[ componentClass ];
  }
}</pre>

<p>So we&#8217;ll create our spaceship like this</p>

<pre class="code">public function createSpaceship():void
{
  var spaceship:Entity = new Entity();
  var position:PositionComponent = new PositionComponent();
  position.x = Stage.stageWidth / 2;
  position.y = Stage.stageHeight / 2;
  position.rotation = 0;
  spaceship.add( position );
  var display:DisplayComponent = new DisplayComponent();
  display.view = new SpaceshipImage();
  spaceship.add( display );
  engine.add( spaceship );
}</pre>

<h3>The core Engine class</h3>

<p>We mustn&#8217;t forget the system manager, formerly called the process manager.</p>

<pre class="code">class SystemManager
{
  private var systems:PrioritisedList;

  public function addSystem( system:ISystem, priority:int ):void
  {
    systems.add( system, priority );
    system.start();
  }

  public function update( time:Number ):void
  {
    for each( var system:ISystem in systemes )
    {
      system.update( time );
    }
  }

  public function removeSystem( system:ISystem ):void
  {
    system.end();
    systems.remove( system );
  }
}</pre>

<p>This will be enhanced and will sit at the heart of our entity system framework. We&#8217;ll add to it the functionality mentioned above to dynamically create nodes for the systems.</p>

<p>The entities only care about components, and the systems only care about nodes. So to complete the entity system framework, we need code to watch the entities and, as they change, add and remove their components to the node collections used by the systems. Because this is the one bit of code that knows about both entities and systems, we might consider it central to the game. In Ash, I call this the Engine class, and it is an enhanced version of the system manager.</p>

<p>Every entity and every system is added to and removed from the Engine class when you start using it and stop using it. The Engine class keeps track of the components on the entities and creates and destroys nodes as necessary, adding those nodes to the node collections. The Engine class also provides a way for the systems to get the collections they require.</p>

<pre class="code">public class Engine
{
  private var entities:EntityList;
  private var systems:SystemList;
  private var nodeLists:Dictionary;

  public function addEntity( entity:Entity ):void
  {
    entities.add( entity );
    // create nodes from this entity's components and add them to node lists
    // also watch for later addition and removal of components from the entity so
    // you can adjust its derived nodes accordingly
  }

  public function removeEntity( entity:Entity ):void
  {
    // destroy nodes containing this entity's components
    // and remove them from the node lists
    entities.remove( entity );
  }

  public function addSystem( system:System, priority:int ):void
  {
    systems.add( system, priority );
    system.start();
  }

  public function removeSystem( system:System ):void
  {
    system.end();
    systems.remove( system );
  }

  public function getNodeList( nodeClass:Class ):NodeList
  {
    var nodes:NodeList = new NodeList();
    nodeLists[ nodeClass ] = nodes;
    // create the nodes from the current set of entities
    // and populate the node list
    return nodes;
  }

  public function update( time:Number ):void
  {
    for each( var system:ISystem in systemes )
    {
      system.update( time );
    }
  }
}</pre>

<img src="/images/blog/entity5.png" alt="" width="459" height="251" />

<p>To see one implementation of this architecture, <a href="http://www.ashframework.org/">checkout the Ash entity system framework</a>, and see <a href="https://github.com/richardlord/Ash/tree/master/examples/no-dependencies">the example Asteroids implementation there</a> too.</p>

<h3>Conclusion</h3>

<p>So, to summarise, entity systems originate from a desire to simplify the game loop. From that comes an architecture of entities, which represent the state of the game, and systems, which operate on the state of the game. Systems are updated every frame &#8211; this is the game loop. Entities are made up of components, and systems operate on the entities that have the components they are interested in. The engine monitors the systems and the entities and ensures each system has access to a collection of all the entities that have the appropriate components.</p>

<p>However, systems don&#8217;t generally care about the entity as a whole, just the specific components they require. So, to optimise the architecture and provide additional clarity, the systems operate on statically typed node objects that contain the appropriate components, where those components all belong to the same entity.</p>

<p>An <b>entity system framework</b> provides the basic scaffolding and core management for this architecture, without providing any actual entity or system classes. You create your game by creating the appropriate entities and systems.</p>

<p>An <b>entity based game engine</b> will provide many standard systems and entities on top of the basic framework.</p>

<p>Three entity system frameworks for Actionscript are my own <a href="http://www.ashframework.org/">Ash</a>, <a href="https://github.com/tdavies/Ember2">Ember2</a> by <a href="http://www.tomseysdavies.com/">Tom Davies</a> and <a href="https://github.com/alecmce/xember">Xember</a> by <a href="http://alecmce.com/">Alec McEachran</a>. <a href="http://www.gamadu.com/artemis/">Artemis</a> is an entity system framework for Java, that has also been ported to <a href="https://github.com/thelinuxlich/artemis_CSharp">C#</a>.</p>

<p>My <a href="/blog/why-use-an-entity-framework">next post</a> covers some of the reasons why I like using an entity system framework for my game development projects.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/what-is-an-entity-framework/feed</wfw:commentRss>
		<slash:comments>75</slash:comments>
		</item>
		<item>
		<title>Mobile Apps</title>
		<link>http://www.richardlord.net/apps</link>
		<comments>http://www.richardlord.net/apps#comments</comments>
		<pubDate>Sat, 14 Jan 2012 19:31:58 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
		
		<guid isPermaLink="false">http://www.richardlord.net/?page_id=925</guid>
		<description><![CDATA[Stick Sports I am CTO at Stick Sports where I am involved in the development of these apps. Stick Tennis Free Easy to play yet difficult to master, Stick Tennis &#8211; the number one sports game in 102 countries &#8211; offers fast and fluid gameplay with realistic court surfaces and a huge range of unique [...]]]></description>
				<content:encoded><![CDATA[<table class="layout">
<tr><td colspan="2"><h2>Stick Sports</h2>

<p>I am CTO at <a href="http://www.sticksports.com">Stick Sports</a> where I am involved in the development of these apps.</p></td></tr>

<tr><td colspan="2"><h3>Stick Tennis</h3></td></tr>

<tr><td><p><img src="/images/sticksports/sticktennis.gif" width="72" height="72" style="padding:0 20px 10px 0" /><br />
Free</p></td>

<td><p>Easy to play yet difficult to master, Stick Tennis &#8211; the number one sports game in 102 countries &#8211; offers fast and fluid gameplay with realistic court surfaces and a huge range of unique player styles and characteristics.</p>
<p>With just a simple one-fingered swipe you’ll soon be thumping crosscourt winners, yet at the core of Stick Tennis is a highly sophisticated physics engine that rewards tactical play.</p>

<p><a href="http://itunes.apple.com/app/id507086545?ls=1&#038;mt=8"><img src="/images/stores/AppleAppStore.png" width="135" height="40" style="padding:0 20px 10px 0" /></a>
<a href="https://play.google.com/store/apps/details?id=air.com.sticksports.sticktennis"><img src="/images/stores/GooglePlay.png" width="126" height="44" style="padding:0 20px 10px 0" /></a>
<a href="http://appworld.blackberry.com/webstore/content/133242/"><img src="/images/stores/BlackberryAppWorld.png" width="141" height="39" style="padding:0 20px 10px 0" /></a>
<a href="http://www.amazon.com/Stick-Tennis/dp/B008YW5RH2/"><img src="/images/stores/AmazonAppStore.png" width="126" height="43" style="padding:0 20px 10px 0" /></a></p></td>
</tr>

<tr><td colspan="2"><h3>Stick Cricket</h3></td></tr>

<tr><td><p><img src="/images/sticksports/stickcricketicon.gif" width="72" height="72" style="padding:0 20px 10px 0" /><br />
Free</p></td>

<td><p>Chart-topping… Award-winning… GDP-reducing… Need we say more? Stick Cricket, the world&#8217;s most popular cricket game, is available for iOS and Android. Whether you&#8217;re on the job or &#8216;on the john&#8217;, you can still hit out or get out!</p>

<p><a href="http://itunes.apple.com/app/id406781620?ls=1&#038;mt=8"><img src="/images/stores/AppleAppStore.png" width="135" height="40" style="padding:0 20px 10px 0" /></a>
<a href="https://play.google.com/store/apps/details?id=com.sticksports.stickcricket"><img src="/images/stores/GooglePlay.png" width="126" height="44" style="padding:0 20px 10px 0" /></a>
<a href="http://www.amazon.com/Stick-Cricket/dp/B009M5BE1S/"><img src="/images/stores/AmazonAppStore.png" width="126" height="43" style="padding:0 20px 10px 0" /></a></p></td>
</tr>

<tr><td colspan="2"><h3>Stick Cricket Super Sixes</h3></td></tr>

<tr><td><p><img src="/images/sticksports/supersixes.gif" width="72" height="72" style="padding:0 20px 10px 0" /><br />
Free</p></td>

<td><p>It&#8217;s man vs machine in the ultimate test of your cricket skills! Instead of facing mere mortals, your opponent is the state-of-the-art Bowlomatic 3000: a sadistic bowling machine that is hell bent on wiping you out.</p>
<p>Smash as many boundaries as you can but be wary, as the Bowlomatic 3000 has plenty of tricks up his sleeve to ensure a harrowing time at the crease.</p>

<p><a href="http://itunes.apple.com/app/id483135193?ls=1&#038;mt=8"><img src="/images/stores/AppleAppStore.png" width="135" height="40" style="padding:0 20px 10px 0" /></a>
<a href="https://play.google.com/store/apps/details?id=air.com.sticksports.supersixes"><img src="/images/stores/GooglePlay.png" width="126" height="44" style="padding:0 20px 10px 0" /></a>
<a href="http://appworld.blackberry.com/webstore/content/18560801/"><img src="/images/stores/BlackberryAppWorld.png" width="141" height="39" style="padding:0 20px 10px 0" /></a>
<a href="http://www.amazon.com/Super-Sixes/dp/B00A6D5I6M/"><img src="/images/stores/AmazonAppStore.png" width="126" height="43" style="padding:0 20px 10px 0" /></a></p></td>
</tr>

</table>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/apps/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ash &#8211; a new entity system framework for Actionscript games</title>
		<link>http://www.richardlord.net/blog/introducing-ash</link>
		<comments>http://www.richardlord.net/blog/introducing-ash#comments</comments>
		<pubDate>Wed, 11 Jan 2012 20:31:00 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Ash]]></category>
		<category><![CDATA[Entity systems]]></category>
		<category><![CDATA[Game development]]></category>

		<guid isPermaLink="false">http://www.richardlord.net/?p=910</guid>
		<description><![CDATA[I&#8217;ve been doing a lot of stuff with entity systems recently. At try{harder} I gave a presentation about entity systems, which was warmly received and led to many interesting conversations. I also created example projects with the Ember and Xember frameworks and had fruitful conversations with Tom and Alec about their projects, even contributing a [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been doing a lot of stuff with entity systems recently. At <a href="http://www.tryharder.org.uk/">try{harder}</a> I gave <a href="/presentations/game-architecture-is-different">a presentation about entity systems</a>, which was warmly received and led to many interesting conversations. I also created example projects with the <a href="https://github.com/tdavies/Ember">Ember</a> and <a href="https://github.com/alecmce/xember">Xember</a> frameworks and had fruitful conversations with <a href="http://www.tomseysdavies.com/">Tom</a> and <a href="http://alecmce.com/">Alec</a> about their projects, even contributing a few minor bits of code to them.</p>

<p>But now I&#8217;ve written an entity system framework of my own. It&#8217;s called <a href="https://github.com/richardlord/Ash">Ash</a> and you can <a href="https://github.com/richardlord/Ash">find it on Github</a>.</p>

<p>A few of the features of Ash are</p>

<ul>
<li>Uses the most performant linked list format <a href="/blog/linked-list-performance-test">from my tests here</a>.</li>
<li>Optional, but not required, integration with <a href="https://github.com/tschneidereit/SwiftSuspenders">SwiftSuspenders</a> and <a href="http://www.robotlegs.org/">Robotlegs</a>.</li>
<li>The process manager is a core part of the framework.</li>
</ul>

<p>I plan to build a game with Ash, so more features will come as I need them, and more posts on this blog. Meanwhile, if you&#8217;re building an actionscript game why not <a href="https://github.com/richardlord/Ash">take Ash for a spin</a>. And for comparison, check out <a href="https://github.com/tdavies/Ember2">Ember2</a> and <a href="https://github.com/alecmce/xember">Xember</a>.</p>

<p><a href="http://www.tomseysdavies.com/">Tom</a> in particular has done a lot of work to develop the ideas behind entity systems on the Flash platform. Without that work to feed my ideas machine I wouldn&#8217;t have built Ash, so thank you Tom.</p>

<p>And thank you to <a href="http://www.tillschneidereit.de/">Till</a> who added a feature to <a href="https://github.com/tschneidereit/SwiftSuspenders">SwiftSuspenders</a> to enable me to inject linked lists based on their content type.</p>

<h3>Update</h3>

<p>Here is <a href="/blog/introducing-ash">a follow-up post</a> explaining entity system frameworks and <a href="/blog/why-use-an-entity-framework">a further post</a> explaining some of the reasons why I like using an entity system framework for my game development projects.</p>

<h3>Update 2</h2>

<p>Ash now has a website, at <a href="http://www.ashframework.org/">www.ashframework.org</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/introducing-ash/feed</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
	</channel>
</rss>
