• About
  • Contact
  • Work
  • RSS
  • Canvas Rendering bug in default browser of older Samsung devices.

    Over the past few weeks I’ve been working on a mobile game project which required the dynamic creation/insertion/manipulation of dom elements, each containing a child canvas element.

    <div>
       <canvas></canvas>
    </div>
    

    Everything worked well on the Samsung S4, but earlier devices like the S3, Galaxy Tab 8, and Note 2 revealed a nasty rendering bug when using the default browser only (no problems in chrome).

    Turns out that if you render a canvas *before* adding it to the DOM, the resulting canvas quality is pretty shabby. It seems to render at a much lower resolution. If you perform any operations on the canvas *after* it has been successfully added to the DOM, that forces a re-render and all is magical again.

    If you subsequently remove & re-append the div containing the canvas, the render quality bottoms out again, and you’ll need to perform another drawing operation on the canvas to normalize things.

    At the moment I’m resorting to a really horrible single pixel clearRect() on the affected canvases, but ultimately the answer would seem to be to steer clear of DOM manipulation of canvas elements on these devices, and to move everything into a single canvas because there are subtle but noticeable artefacts present for a very short period between the time that the element is added and re-rendered, so it’s not an entirely unnoticeable hack.


    Cake Flour

    Flour is a set of simple build tools that makes compilation, minification & bundling of your coffee, less & js files a breeze.  Adding additional compilers is also very simple.

    Make sure all your dependencies are installed. We’ll add jade compilation to our build in a bit, so hit it up on npm.

    npm install -g coffee-script flour jade
    

    Create a text file called ‘Cakefile’. No file extension. Task creation is as simple as specifying compiler, source & output files.

    task 'build:coffee', ->
       compile 'dev/core.coffee', 'deploy/core.js'
    

    To add an additional compiler like jade, to your build:

    flour.compilers['jade'] = (file, cb) ->
      jade = require 'jade'
      file.read (code) ->
         fn = jade.compile code
         cb fn()
    
    task 'build:jade', -> compile 'test.jade', 'index.html'
    
    task 'build', -> invoke 'build:jade'
    

    Run ‘cake build’ from the command line and magical things happen.

    Command line tools are great, but sometimes it’s also handy to be able to perform a build directly from your IDE.  If you use webstorm/phpstorm, here’s a simple method to add a menu command that will perform a build from the cakefile of an active project.

    Go to Open File>Settings>External Tools and add a tool (+)

    On my windows work machine, the cake command path is:

    C:\Users\SAFindIt\AppData\Roaming\npm\cake.cmd

    Hit ‘ insert macro’ for working directory & select ‘$ProjectFileDir$’  which will perform a build from the cakefile in the active project directory.

    Tools>Build>Bake Cake.   Yum.


    Node socket app with zappa.

    I’ve spent much time recently working with node, and one of the coolest packages I’ve discovered is zappa! It’s a streamlined wrapper for express & socket.io, with a whole bunch of awesome added conveniences…and it’s in coffeescript. Cool!

    Ultimately I want to try creating a socket-ized 2 player pong game controlled by mobile device, but this post will concentrate on building a simple app that log’s the mouse movements for 2 connected clients.

    1) Install node.
    2) Open command prompt/terminal & install zappa with npm:

    npm install zappa

    3) Create a new coffeescript file called, ‘app.coffee’. We’ll configure our app so that zappa serves jquery and static assets (like css and js files). By default, static assets are served from a ‘public’ folder.

    @configure =>
          @enable 'serve jquery'
          @use 'static' #serves static assets from public folder

    4) Next we’ll define a route.

     @get '/control' : ->
          @render 'control' : layout: no

    By default your app will use port 3000. Whenever a client requests ‘http://localhost:3000/control’, a template called ‘control’ will be rendered, and here it is:

    @view control: ->
          doctype 5
          html ->
             head ->
                link rel: 'stylesheet', href: '/css/style.css'
                script src: '/socket.io/socket.io.js'
                script src: '/zappa/jquery.js'
                script src: '/zappa/zappa.js' #necessary for @client socket
                script src: '/client.js'
             body ->
                canvas id: 'canvas', width : '500', height: '500'

    Zappa uses the coffeekup template engine, allowing you to define your html template in coffeescript. You can also use other template engines like Jade, which is my preferred template engine.

    5) Last thing to do on the server side is handle socket data. We want to be notified when a player connects or drags their mouse:

    @on connection: ->
          if playerCount < 2
                 @client.name = "Player #{playerCount}"
                 @emit player:  @client.name
                 playerCount++
    @on move: ->
          console.log("#{@client.name} moved to #{@data}")

    6) In order for the socket magic to happen, there needs to be some client side javascript too. Again, zappa makes things all magical and rainbow-ish by letting you write inline coffee which is deployed as javascript (‘client.js’). In order for it to work, the client needs a reference to zappa -> ‘zappa.js’ in your in your html

    @client '/client.js': ->
          @connect()
          @on player: ->
             console.log @data
    
             $ =>
                isMouseDown = false
                canvas = $('#canvas')
    
                canvas.mousedown (e) =>
                   @emit move : e.pageY
                   isMouseDown = true
    
                canvas.mouseup -> isMouseDown = false
    
                canvas.mousemove (e) =>
                   if isMouseDown
                      @emit move : e.pageY

    7) Start your app. Open a terminal window/command prompt.

    coffee app.coffee

    8 ) Open 2 brower windows, and click & drag in each. You should see something like, ‘player 0 moved to 150′ in the console.

    The final code:

    playerCount = 0
    
    require('zappa') ->
    
       @configure =>
          @enable 'serve jquery'
          @use 'static'
    
       #routes
       @get '/control' : ->
          @render 'control' : layout: no
    
       #inline view templates
       @view control: ->
          doctype 5
          html ->
             head ->
                link rel: 'stylesheet', href: '/css/style.css'
                script src: '/socket.io/socket.io.js'
                script src: '/zappa/jquery.js'
                script src: '/zappa/zappa.js'
                script src: '/client.js'
             body ->
                canvas id: 'canvas', width : '500', height: '500'
    
       @on connection: ->
          if playerCount < 2
             @client.name = "Player #{playerCount}"
             @emit player:  @client.name
             playerCount++
    
       @on move: ->
          console.log("#{@client.name} moved to #{@data}")
    
       @client '/client.js': ->
          @connect()
          @on player: ->
             console.log @data
    
             $ =>
                isMouseDown = false
                canvas = $('#canvas')
    
                canvas.mousedown (e) =>
                   @emit move : e.pageY
                   isMouseDown = true
    
                canvas.mouseup -> isMouseDown = false
    
                canvas.mousemove (e) =>
                   if isMouseDown
                      @emit move : e.pageY
    

    Download files.


    Asteroids & The Singleton

    I’ve been doing quite a bit of reading on design patterns & recently came across a post over at photonstorm which talks of a ‘registry pattern’, which essentially just looks like a lazy singleton approach.

    The idea behind a singleton is that you can only ever have a single instance of a singleton class & that the instance is globally accessible (meaning that the same instance is easily reached by any object in your program). This is really useful for storing game data, so I decided to test the registry pattern with a game of asteroids. The game will play full browser so it’s not very challenging on large monitors. To be fair, it’s not particularly challenging at any size. ha.

    Play asteroids!

    The registry pattern mentioned at photonstorm serves the same purpose as a traditional singleton, but the class is populated with static (class) variables, and the data accessed through the class itself (rather than through an instance of the class, as is the case with the normal singleton). It’s really simple to work with. The downside is that the registry class is tightly coupled to the program, but for a small project like this, it’s not really a major concern.

    Usage:

    All program data was stored in a class called AsteroidsModel.

    package model
    {
          public class AsteroidsModel extends EventDispatcher
    	{
    		//vars
            public static var numLives:int = 4;
    		public static var player:Player;
    		public static var asteroids:Vector.<Asteroid> = new Vector.<Asteroid>();
                    ....
    

    So to trace out the number of lives (from anywhere in my program), I’d simply use:

    trace(AsteroidsModel.numLives);
    

    I used this approach for the asteroids game, and it worked really nicely but I’d read somewhere that static variables aren’t the best option for performance optimization so I decided to do some tests to compare static vs instance variables. The first test was to compare speed of static vs instance variables when they were in the same class as the calling code:

    public class Main extends Sprite
    	{
    		//private static var myString:String;
    		private var myString:String;
    
    		public function Main():void
    		{
    			var startTime:Number = getTimer();
    			for (var i:int = 0; i < 1000000; i++)
    			{
    				myString = "brad";
    			}
    			var endTime:Number = getTimer();
    			trace(endTime - startTime);
    		}	
    
    	}
    

    Both returned similar results of around 110ms (My machine is an old girl).

    The second test was designed to see if there were any performance benefits to be had by working with an object vs the class itself.

    Object Instantiation method:

    public class Main extends Sprite
    	{
    		public function Main():void
    		{
    			var staticDemo:StaticDemo = new StaticDemo();
    
    			var startTime:Number = getTimer();
    			for (var i:int = 0; i < 1000000; i++)
    			{
    				staticDemo.myString = "brad";
    			}
    
    			var endTime:Number = getTimer();
    			trace(endTime - startTime); //output average :110ms
    		}	
    
    	}
    

    Class & Static Variable method:

    public class Main extends Sprite
    	{
    		public function Main():void
    		{
    			var startTime:Number = getTimer();
    			for (var i:int = 0; i < 1000000; i++)
    			{
    				StaticDemo.myString = "brad";
    			}
    			var endTime:Number = getTimer();
    			trace(endTime - startTime);  //output average :125ms
    		}	
    
    	}
    

    So variable access appears to be marginally faster when working with an instance of a class as opposed to accessing static variables from a class directly, but all in all I like the looser coupling that the traditional singleton approach creates between the model and the rest of the program.

    Download code (which implements the ‘registry pattern’ technique discussed above).


    Asteroids 2:Creating the visual assets

    Since this game has such simple artwork, we can easily create the game assets, 1) using flash’s drawing tools, or 2) programmatically with actionscript. I created the assets for this project using flash and the remainder of the posts for this game will be making use these assets which you can download here, but I’ll give a brief overview of both options.

    If you’ve downloaded the assets file above, you already have all the necessary artwork in the .swc file so all you need to is to 1) drop that file into the lib folder of your asteroids project and, 2) right click and choose ‘Add to library’. If you’d prefer to create your own assets, read on..

    Creating the artwork in flash

    In order to be able to use flash assets in a flashdevelop AS3 project we need to convert each object in flash into a movieclip (or sprite), export for actionscript & publish a SWC file.

    a) Draw the object in flash and convert it into a symbol (F8).

    b) Choose Movieclip from the type dropdown & select “Export for Actionscript”.

    c) Enter a class name. It’s good practice to use common naming conventions, so use upper case for the first letter of your class. This helps distinguish it from a variable which typically has a lower case first letter, eg. I’ve used “Ship” for my starship class. The library item name (at the top of the dialogue box) is of no importance when coding, it’s the class name which significant from a programmatic point of view. Hit OK.

    Export for actionscript

    If want to optimize your program, you can change the Base class from Movieclip to Sprite for any symbols that have only a single frame on their timeline, so the base class will read ‘flash.display.Sprite’. Whats the difference? Well Movieclips and Sprite are very similar but movieclips have additional methods for moving around their timeline (think dvd player type functionality with the ability to play, stop and jump to various points in the movie). If you open the assets.fla file you’ll see that I’ve used Sprite as the super/base class for the spaceship, while the flame and asteroid have Movieclip as there base class, and that’s because the ship is a simple visual asset with only 1 frame, while the asteroid and flame clips have multiple frames on each of their timelines.

    e) Save the .fla to the .src folder of your project.

    f) Open File>Publish settings and look for ‘SWC’ or ‘Export SWC’ option depending on which version you’re using. In CS4 you’ll need to navigate across to the flash tab to find this setting. Change the publish directory to “../lib/assets.swc” so that the swc file get’s created in the lib folder of your asteroids project. (If you’re working with an older version of flash you may need to also publish a swf which you can later delete because we only need the .swc file). Publish the project.

    g) Open flashdevelop, expand your lib folder. Right click on the SWC file and choose add to library. DONE!

    Add swc to library

    Drawing the visual assets programmatically

    I’m not going to go into much detail here, other than to say that display objects like movieclips and sprites have a graphics property that allow you to draw to the display object. The diagram below shows a possible sequence for drawing the ship graphics. lineStyle() sets the line colour and thickness. lineTo() draws from the current position to a new location and moveTo() picks up the ‘pen’ and moves it to new position without drawing.

    Drawing ship procedure

    with(graphics)
    {
    	lineStyle(1, 0xFFFFFF); //stroke thickness:1 colour: white
    	moveTo(-4,-8); //picks up pen and moves it to pt1
    	lineTo(20,0); //draws a line to pt2
    	lineTo(-4, 8); //draws a line to pt3
    	moveTo(0,-7); //picks up pen and moves it to pt4
    	lineTo(0,7); //draws a line to pt5
    }

    Asteroids 1: Setting Up The Project

    This is the first in a series of posts that will run through the creation of a simple game of asteroids using flash & flashdevelop. These entries are based on some actionscript classes that I teach, and the finished product will be a simplified, single level version of the original arcade classic. I’ve kept it simple in an effort to make the posts easy to follow. At the end of these articles, I’m going to do some posts on building this game using the MVC (Model View Controller) design framework, where we might add some additional functionality that’s closer to the original game.

    Asteroids

    Setting up the Project

    All of the scripting will be done in Flashdevelop which is a fantastic, free & open source actionscript editor that is far nicer to work with, than Flash’s own script editor. In addition, flashdevelop can compile or publish a .swf file using the free open source adobe flex sdk, which means that you can work through these tutorials and publish a .swf file, using only free open source software. Sweet! (I’ve created the graphics for the game using flash, but you can also create all of the necessary assets entirely by code. I’ll walk through both approaches, and you can also download the project assets here.
    .

    You’ll find easy installation instructions for flashdevelop on their website, but in short, you’ll need the java runtime 1.6, & the flex 4 sdk along with flashdevelop. FD4 Beta has recently been released which also has some goodies for android development so grab that! It’ll automatically download and configure the flex sdk. If you need to manually configure the flex sdk location for whatever reason though, you’ll find the settings in Tools>Program Settings>AS3Context. Scroll down to language setting and enter the flex sdk location.

    Flashdevelop Setup

    The last thing to do is to set up a new project. Navigate to Project>New Project. Select AS3 project from the list, and choose the folder where you want your files project to be created.

    AS3 Project

    In the project explorer on the right, you’ll notice that flashdevelop has created 3 folders for you:

    - a bin folder where your compiled swf will be created
    - a lib folder which we’ll use to store some assets in later
    - an src folder where your actionscript classes will go.

    Everything is prepped and ready to go, and in the next post we’ll start planning our game.


    Processing, Android & Pong

    The new stable release of processing (v.1.5) has an android mode that allows you to create android apps with ridiculous ease. I gave it a quick test drive with my accelerometer controlled version of pong.

    Pong

    Download sketch

    Majority of the code in the game is straightforward processing code, with the main differences revolving around sketch size, orientation & the accelerometer code which I’ll talk about shortly. To get started with android & processing in next to no time, you’ll need to:

    1) download the android sdk – detailed instructions on exactly what files you need can be found on the processing wiki

    2) launch processing 1.5 and switch to android mode:

    android mode

    2) create a processing sketch & run it!

    The simplest way to run your sketch is to connect an android device to your computer by usb, enable usb debugging on the phone (Menu>Settings>Applications>Development>USB Debugging), and use Sketch>Run On Device to launch the app on your phone.

    You can also test in the software android emulator, but the compiled processing sketch will launch far more quickly on an android device, perform much better, and be way more fun to play with, than using an emulator.

    Back to display size, orientation and accelerometer:

    The sketch will, by default, be set to the full display size. To get the dimensions of your sketch, use screenWidth & screenHeight.

    The orientation of you sketch will automatically be updated as you roll your phone between portrait and landscape positions, but orientation can be locked. For pong I wanted the sketch to be locked in landscape mode:

    orientation(LANDSCAPE);

    To access the accelerometer, I borrowed heavily from Erik Pavey’s very helpful article on hardware detection in processing. I’ve subsequently come across a super library called ketai which makes it even easier to capture sensor data.


    Loading cross domain xml into processing.js

    At some point you’ll probably want to load xml from another domain into a sketch but because of javascript cross-domain restrictions, you can’t simply add the url to your processing sketch if you want it to work with processing.js. You need to create a proxy. Simply put, a proxy allows you to request resources from another domain. The php proxy I used to request one of my last.fm feeds is extremely basic, but it does the job.

    <?php
       header('Content-type: application/xml');
       echo file_get_contents('http://www.site.co.za/data.xml');
    ?>
    

    I was having some trouble getting the data back to my processing sketch because I had been trying to handle the data as xml, but found that it needed to be passed to processing as a string, ie. the return datatype for my jquery request needed to be ‘html’ and not ‘xml’, and the data then needed to be passed back to a function that was expecting a string, rather than an XMLElement.

    $.ajax({
        type: "GET",
        url: "getXML.php",
        dataType: "html",
        success: sendXMLToProcessing
    });
    
    function sendXMLToProcessing(data)
    {
        var pjs = Processing.getInstanceById('dataViz');
        pjs.parseXML(data);
    }
    

    To communicate with the sketch, the canvas container needs to be assigned an id. Now to call a function inside the sketch, we simply create a variable to hold a reference to that canvas, and from there, it’s plain sailing.

    <canvas id="dataViz" data-processing-sources="sketch.pde"></canvas> 

    last fm data visualization

    Download files


    Processing.js

    Processing.js allows you to load a processing sketch into a web page, have it converted to javascript & rendered on the fly, with no plugins required!!

    All you need is a browser that supports the HTML5 <canvas> tag, your processing sketch(.pde) and the processing.js library.

    Loading a sketch requires just 2 lines of code:

    <script src="processing-1.1.0.min.js"> </script>
    <canvas data-processing-sources="mySketch.pde"></canvas>
    

    The sketch below is a a simple example put together for my processing class at UCT.



    Source code

    Google chrome doesn’t allow access of local files, so if you’re using chrome, you’ll probably want to install a local server like wamp or xampp and test from there. Another option is to launch chrome from the command line with a switch to allow loading of local files:

    chrome.exe --allow-file-access-from-files

    Processing has an impressive collection of 3rd party libraries, and it’s great to see developers porting some of these across to javascript. Toxiclibs.js is a great example, and while toxiclibs.js doesn’t have all the functionality of it’s processing counterpart, it’s great to see libraries like this making their way across to processing.js.You don’t import these libraries as you would in a processing sketch, but instead, simply load in the necessary javascript files using the script tag. The example below uses the toxiclibs.js library to calculate line intersection point. The necessary js files are loaded with:

    <script type="text/javascript" src="processing-1.1.0.min.js"></script>
    <script type="text/javascript" src="core/geom/Line2D.js"></script>
    <script type="text/javascript" src="core/geom/Vec2D.js"></script>

    Click & drag anywhere inside the sketch to cross sticks.


    Source code

    NOTE: pmouseX & pmouseY, which hold previous mouse X & Y coordinates, don’t appear to work in Processing.js, but it’s a simple enough task to create your own variables to hold these values.