Getting hooked up with Starling

Files with a working solution is available here

One of the more promising aspects of the new Flash Player and AIR runtime is the Stage3D object. The obvious and breathtaking improvements is seen in experiments like http://www.unrealengine.com/flash/ where you are moving around in a 3D landscape in realtime, with reflections, light and all the Unreal Engine can throw at you. Another great example is Unity, that exports to the Flash Player. Take a look at the video on http://blogs.unity3d.com/2011/09/01/unity-and-flash-a-sneak-peek/ to see how it raises the bar for what is possible in a browser.

My project with Mouse Wood calls for a simpler solution, though. Fortunately Stage3D is not only for 3D content. There are several initiatives like ND2D, M2D and Citrus Engine, that I find very interesting because of it’s buit-in level editor and side scrolling ability (and I am in desperate need of inside knowledge on how to make side scrolling games). My love falls on the Starling Framework. First of all, it looks simple and straight forward – and have a lot of similarities to the traditional display list approach. Secondly, I hear it mentioned quite a few places, performing some nice results on both desktop as well as mobile. I may look into the other as well, but this article dives into Starling.

Get the packages

Starling originates from the gaming framework called Sparrow, that targets iOS game development. Both frameworks resides at the site http://gamua.com/ and provides easy access to packages and tutorials. You get access to the framework by doing the following:

  1. Go to http://gamua.com/starling/download/ and hit the Download Starling button (currently 1.0)
  2. Unzip the package

Inside you will find a few folders and a read me-, change log- and license file.

Folders in Starling

There is a folder with some samples, and a folder to Flex Unit Tests. I will not discuss these files, but solely focus on the starling folder. Inside the Starling folder you will see a few folders. You are interested in the bin folder and the src folder – actually, you are only interested in the bin folder. Looking into the source folder, you will find all the ActionScript classes, that makes up the framework. The same files, are the one compiled into one handy swc-file (ShockWave Component, Small Web Component – or something like that. Nobody seems to know .. or care) located in the bin folder for you to keep.

Copy the starling.swc from the bin folder to where you keep you class-files. I have made a folder in my dropbox folder, so everytime I update a package on one of my machines, i automatically gets updated on the other machines.

Link to the framework

In my experiments I will primarily use Flash Builder for the development. So fire up Flash Builder and:

1. Create a new ActionScript project (File > New > ActionScript Project)
2. Call it StarlingTest (or similar) as the project name.
3. Click Next to go to the Build Paths.


4. In the dialog, click on the Add SWC button. Navigate to the startling.swc and add that to the list.
5. Click on finish, to create the project.

NB: If you are following along in Flash Professional, you can add the swc’s so they are always available in the programs preferences (under ActionScript settings) or per project (in it’s publish settings)

Making a stage3D object

With the project in place. You will now make a Stage3D object. The Stage3D object i placed in the Display List just like any other display object. In fact it is placed behind the stage. You can have many stage3D object on top of each other, but they all have to be behind the normal stage and it’s contained objects – so no stage3D floating around a traditional animation in Flash, only the other way around.

With StarlingTest.as open – enter the following code. The highlighted areas is where you should enter text, if you follow along:

package
{
  import flash.display.Sprite;
  import starling.core.Starling;

  [SWF(frameRate="60", width="800", height="600", backgroundColor="0xFFFFFF")]
  public class StarlingTest extends Sprite
  {
    private var starl:Starling;

    public function StarlingTest()
    {
      starl = new Starling(StarlStage, stage);
 starl.start();
    }
  }
}

First is the SWF-meta tag, that allows you to set specific parameters that is used at compile time. This one simply sets the frame rate to 60fps, width and hight and finally a white background.

Then you declare an object of the type Starling. This object is the main motor. It translates everything that goes into it into the native Stage3D framework underneath. Inside the constructor, it is initialized. The signature has a lot of parameters, but in general i believe you will use the first two in most cases. The first one, is the name of the Class that is supposed to be inserted on stage and the other one is just a reference to the stage object. This example references the StarlStage class that isn’t defined yet, so you will get an error – don’t worry. You will create it in a moment.

The Starling object itself has a few methods and properties, that can be used to control the behaviour of the object. The one you will use everytime is the start() method, that starts up the engines.

Create the Starling sprite class

Right click in the default package and choose New > ActionScript Class. In the dialog box enter “StarlStage” in the name field (the same name you refered to in the main class). In the input field called Superclass, begin typing the word “sprite” to see the code completion kick in. Select the option called Sprite – starling.display to make sure that the sprite inherits from the right superclass.

Showing a background with the Quad class

One of the more interesting classes I found in the Starling framework is the Quad. Maybe I just haven’t looked around, but I haven’t seen other objects, that made it so easy to manipulate rectangles, and their colors. The Quad is basically a rectangle that is able to present a uniform color or a gradient. Not a normal gradient, but a gradient that radiates from every vertex in the rectangle.

Quad Vertices

The individual vertex is stores in an array, going from top-left, over top-right and down to bottom-left and finally bottom-right

The signature of the class is:

Quad(width:Number, height:Number, color:uint = 0xffffff, premultipliedAlpha:Boolean = true)

You simply set width and height. If you leave all other parameters, you will get a white box. You can set the third and fourth parameter to change the color or the default alpha method, premultiplied alpha. (read more about it here)

With the StarlStage.as active enter the following code. The text in bold is the one you should add:

package
{
  import starling.display.Quad;
  import starling.display.Sprite;
  import starling.events.Event;
 
  public class StarlStage extends Sprite
  {
    <strong>private var q:Quad; </strong>
    public function StarlStage()
    {
     <strong> addEventListener(Event.ADDED_TO_STAGE, onAdded); </strong>    }
 
<strong> private function onAdded(e:Event):void { q = new Quad(800, 600, 0x880000); addChild(q); } </strong>  }
}

First it declares the Quad as the variable q. Then the class listens for the event that is triggered, when the object is added to the stage. It is a good habit to make sure the stage is available before adding content to it. In this case, you could do it all in the constructor, but you may end up in a situation later on, where you need to be sure that the stage is reachable – this way, you are on the safe side.

Finally in the onAdded() listener, you instatiate it with a width, a height and a dark red color. Because the similarity between traditional display objects and Starlings display objects, it’s just a matter of calling addChild() to place it in the display list.

Test it

Now, would be a great time to see if everything is working as expected. If you try to run the code, you will see that it shows an error on the screen that says: “This application is not correctly embedded (wrong wmode value)”

This is a default message, that Starling displays if you haven’t enabled the the players the right access to the GPU. To do that, open the file called StarlingTest-app.xml that is located in the root of your source folder. This file contains all relevant information about the project, and this is where you will find the node called RenderMode (around line 104). Uncomment that node and correct it to:

<renderMode>direct</renderMode>

This way you tell the application, that although you will render vectors through the software renderer they will blit through the GPU. It is also possible to enter “gpu” and make all the calculations in the GPU, but for the most part, I believe that direct gives the best performance … but you can fiddle with that.

Save all the documents and try again. You should see a dark, red colored window. If not, review your code, and look for errors. You might download and look at the accompanying files to look for things that might have gone wrong.

Placing an image

OK, with a Quad in place, it is time to step up a level – let’s introduce images. You can’t go around showing colored rectangles all day, at a point you have to bring in some detailed pixels. Update your code, so it looks like this:

package
{
  import flash.display.Bitmap;

  import starling.display.Image;
  import starling.display.Quad;
  import starling.display.Sprite;
  import starling.events.Event;
  import starling.textures.Texture;

  public class StarlStage extends Sprite
  {
    private var q:Quad;

 [Embed(source="assets/mouse.png")]
 private var mouseBMP:Class; 
    public function StarlStage()
    {
      addEventListener(Event.ADDED_TO_STAGE, onAdded);
    }

    private function onAdded(e:Event):void
    {
      q = new Quad(800, 600, 0x880000);
      addChild(q);
 var mouseBMP:Bitmap = new mouseBMP();
 var mouseTEX:Texture = Texture.fromBitmap(mouseBMP);
 var mouse:Image = new Image(mouseTEX);
 addChild(mouse);
    }
  }
}

That was a lot for a little result, you may think. Well, some of it is the way Flash Builder is used to embed images, and some of it is because of Starlings way to treat content inside images as textures – actually Image works like Flash’s own Bitmap class. In the references it is told like this:

An Image is a quad with a texture mapped onto it.

The Image class is the Starling equivalent of Flash’s Bitmap class. Instead of BitmapData, Starling uses textures to represent the pixels of an image. To display a texture, you have to map it onto a quad – and that’s what the Image class is for.

Let’s take the code in chunks

 [Embed(source="assets/mouse.png")]
 private var mouseBMP:Class;

This is the normal way to embed images in Flash Builder. By using the Embed meta tag you are making the image available from the beginning, instead of loading it in at runtime. You can read more about the embed meta tag at http://www.adobe.com/devnet/flash/articles/embed_metadata.html

You are capturing the path to the source and immediately assign it to a class object. This is because you have to assign the image info to an object in order to reference it later on in the code. The second part of the code is executed when the stage is ready, and looks like this:

var mouseTEX:Texture = Texture.fromBitmap(new mouseBMP());
var mouse:Image = new Image(mouseTEX);
addChild(mouse);

First you make a texture, to place on your image. You are using the static methods in the Texture class to tell, what will be the foundation for the texture. This example use Texture.fromBitmap() to indicate that a bitmap info is used for the texture. As argument, you just enter “new mouseBMP()” so a new instance of the image is passed on to the texture.

The next line declares Starlings Image object, that is similar to the Flash Bitmap class. Instead of passing bitmap data to a bitmap object, you are passing the texture data to an image object in Starling – similar proces, different names. Finally it is added to the stage with addChild()

Now what?

This is the absolute fundamentals of presenting images and Quads. In the next tutorial, I will add some movement, but use this tutorial as a reference to get things out on the stage in Starling – Other articles I do will take it for granted and refer to this one for explanation.

Feel free to comment and ask quations in the forum

 

 



Leave a Comment