Voronoi diagram generator in flash

After reading Ross Bencina’s paper : “The Metasurface – Applying Natural Neighbour Interpolation to Two to Many Mapping”, I decided to have a go at building a similar system myself and hopefully revive an earlier project for creating different ways of modulating parametric systems (for me that means audio).

The first pass is done and you can see it working right here (flash player 10 required)

The code will be up somewhere soon, at the moment its mainly a port of the code from this page (but refactored to seperate the voronoi model, the scanner and the renderer). Thats combined with an implementation of the FastClip algo from this wikipedia page to keep the lines in the bounding box.

next up is gathering the line segments into polygons and linking stuff together ready for some nearest-neighbour evaluation.

PixLib part 3. Abstract Factory

Today I found yet another good reason to test PixLib (and I still have some others in mind that are to come, like removing all my dependencies on the mx.* packages)

To give a bit of background, the application im building is a drag-and-drop based story creator for schoolkids. Theres a stage onto which they can add different types of things (aka artifacts) and move them around, scale, rotate etc.. Now most artifacts behave the same way, but some need special abilities, for example speech bubbles have text which can be edited ‘live’ (i.e. inside the bubble not in a seperate text field) and there are other types of artifact with their own peculiarities. Each of these types of artifact inherits from one base class and its this base class which most of the application deals with. It doesnt need to know about the difference between a normal artifact and a speech bubble it just wants to keep a list of them, save and restore their state etc..

To attain this goal i have decided to use a factory to create the artifacts. A factory is just a class (or often a single method) that is used to create objects. If you havent heard of these then Wikipedia has some more information: Factory Method Pattern and Abstract Factory

At creation time I know the type of the artifact I want (its a string property of an Artifact model object) and I need to create the corresponding UI object. I could code my own factory method or factory class and use a big if / else (or switch / case) construct to decide what to build depending on the artifact type but there has to be a better way. Enter PixLib’s AbstractFactory.

If you look at the API for AbstractFactory its very minimal, the only public method is push (sKey:String, classConstructor:Function). This is used to register the types of objects I want to build.
Now if you look at the source you will notice the more interesting method _buildInstance (much like the buildInstance from the HashCodeFactory from the previous post).
Because its an AbstractFactory that means I have to make my own concrete subclass which will implement my factory method. I also need to register the types I want to create by their string identifiers.

(Its worth noting at this point that the PixLib AbstractFactory class doesnt play the exact role of the AbstractFactory class in the canonical AbstractFactory Pattern. It is ‘Abstract’ because you create concrete subclasses and dont use it directly but unlike the usual AbstractFactory in the pattern it doesnt have the same interface as those subclasses, instead it provides a facility for dynamically linking identifiers to class constructors which the concrete subclasses can use to create objects.

If thats just made things even more confusing dont worry about it..)

First, I need to extend the Abstract Factory and register my types :

class EditableObjectFactory extends AbstractFactory
    // private constructor for Singleton
    private function EditableObjectFactory()
        // register artifact types



Then I can implement my factory method which looks a bit like this :

public function createEditableObject(artifact:ArtifactModel,mc:MovieClip):EditableObject
    // Create instance according to artifact type (i.e. Character.TYPE_ID, SpeechBubble.TYPE_ID etc..)
    return _buildInstance(artifact.getType(),mc);

Then the application code can just ask the EditableObjectFactory to create the appropriate item when a user requests a new artifact to be added to the stage.

Another benefit of this is that each of the 3 versions of the application can easily add their own custom artifact types. They each just register the type with EditableObjectFactory at startup and the rest happens like magic. :)

Another examples is available within PixLib. If you look at the TweenFactory class in the com.bourre.transitions package you will see that it subclasses AbstractFactory to be able to create instances of Tween objects.

If you find yourself in the situation where you are dealing with a set of if / else or switch / case statements when you are creating objects then its definitely worth considering using a factory and encapsulating the creational process into its own class.

PixLib part 2. More configuration features and a ‘hidden’ gem.

After the previous success of PixLib dealing with my configuration needs, today brought a new challenge, creating instances at runtime from string identifiers (aka Class Factories).

To complete part of the project im working on in a nice way I want to be able to create instances of UI classes at runtime, using their fully qualified package names as identifiers. e.g. com.relivethefuture.ui.Stage.

The package names will be specified in the config file, but the class constructors need to be passed parameters which can’t be declared in the config as well.

IF the instances could be created without parameters then I could have used the config type called ‘class’. This would have meant that the framework would have done the hard work for me and created me an instance of the class specified.

When you are able to use this feature you can setup your config like this (note the quotes around the package name and any string arguments)

    'com.mydomain.MyClass',23,12,'hi Mum'

The interesting thing is whilst investigating the source code to see how PixLib creates the class instance I found a handy little utility function tucked away in the HashCodeFactory class (com.bourre.core.HashCodeFactory).

This class has a static method just for building instances, it looks like this :

public static function buildInstance(sPackage:String, aArgs:Array)

Exactly what I need.

I can just specify the class name in my config file


and when the time comes I just call the buildInstance method (note the parameters are supplied as an array)

stage = HashCodeFactory.buildInstance(Config.getInstance().stage.classname,[mc.mainStage]);


Now, for those of you who are going to be creating classes from package names remember one vital thing. You *MUST* reference the class at some point in your code for the compiler to include it into the swf, otherwise you wont be able to create an instance. This is slightly unfortunate, but its easy enough to deal with, just add

static var myClass:com.mydomain.MyClass

to your main class (or in a seperate class that is just used as a placeholder to ensure the classes are imported) and you’re good to go.

Getting to know PixLib

Theres more and more frameworks available for flash developers these days and choosing between them isnt easy, mainly because they all share one feature. No documentation. At least no documentation that you could read to understand what the framework is about unless you like reading API docs.

So, in an effort to get to know more about them the only choice is to try and use them and write about what i find. Im going to start with PixLib as it does have API docs which gives a rough idea of the area it covers and its in active development.

I’ve got real world projects im working on which need some functionality which is available in PixLib. The choice is then, either code it myself or learn the PixLib way. Im going to try it with PixLib and see if it saves me time over the code-it-myself approach (which is what I normally do…I tried ARP before but didnt like the way it was structured so i coded my own micro-architecture which im happy with at the moment)

My first task for PixLib : Loading configuration files.

I need to load in a configuration file at the start of my application and have access to the configuration data throughout my app. I already have my own config file reader which I built it when i just needed a simple key => value mapping but its not good enough anymore.

A quick scan of the API docs reveals a few interesting Classes : Config, ConfigLoader and ConfigLoaderEvent.

Looks like the ConfigLoader is a good place to start and theres a method there which unsurprisingly is called ‘load’.

I’ve already downloaded the PixLib source and unzipped it into my classpath, so now its time to investigate the source :)

The constructor of the ConfigLoader takes 2 arguments, an object called config which looks like it will be used to store the config and a deserializer to convert the xml to an object representation. But, before we jump in and start to create the loader one important thing you’ll notice about PixLib is that if you dont supply arguments then it uses sensible defaults. This is great as it saves a lot of wasted time which would be spent looking into other Classes to see how to build them and pass them in etc.

The next vital part of the puzzle is how do we know when the config has been parsed?

Back to the API docs and we can see the ConfigLoader has an onLoadInitEVENT which sounds just like what I need.

So the code i think i’ll need to load the config and get notification will look like this :

configLoader = new ConfigLoader();

N.B. I have updated the above code because Francis (the creator of PixLib) kindly pointed out that PixLib automatically creates delegates when you register event listeners. So no need to use an external delegate factory. More bonus points for PixLib.

The ConfigLoader uses a url of ‘config.xml’ by default (im always happy to favour convention) so no need to supply any arguments to the load method.

I’ve added my handler (configLoaded) so now I need to find out how to access my configuration data.

Back to the API, this time to the Config class. Looks like this is a Singleton so I can access it from anywhere and know its the same instance. So just a quick call Config.getInstance() and i’ve got access to my configuration data, converted from xml to a nice round object. Great.

As I said earlier I need a bit more structure in my config than just name – value pairs. Some items need to have properties, some just need to exist.

From looking at the source earlier I saw that the ConfigLoader uses an XMLToObjectDeserializer so im going to go and investigate what happens inside the deserializer.

Right at the top theres some calls to ‘addType’ which seems to be used for mapping types to deserialization routines, but how do I specify those types in my config? (number, string, array among others)

A quick scan of the deserialize function shows

var dataType:String = node.attributes.type;

ah, so I use an attribute called ‘type’ to declare the type of the node, and im guessing that the node value represents the node value (seems reasonable)

Time to edit my config.xml and see if the data comes through how I want it. Here’s what I have so far :


Then its just a quick check with some trace statements in the config load event handler and we’re done.


Output : 477


How do I think PixLib stood up to the task overall?

It required a bit of investigation and API / source code reading to find out what I needed but it probably took a little less time than building my own AND is a lot more flexible than what I would have built in the time.
Also the PixLib source code is clear and relatively easy to understand. The use of defaults is very well done and makes using the library pretty much painless.

Definitely a thumbs up.

A quick summary for those of you who cant be bothered to read everything.

1. Create a ConfigLoader and load your data

configLoader = new ConfigLoader();

2. Get the Config instance and use your data

mc._width = Config.getInstance().artifacts.backgrounds.size.width

Ant task for Haxe compiler

For those of us who use Ant to automate builds and other tedious tasks i’ve put together a task so you can now run the Haxe compiler from Ant.

It supports all of the relevant command line arguments, but if it doesnt do something you think would be useful please get in touch and i’ll see what I can do.

You can grab a zip here :


Inside is everything you need, source, jar, samples and documentation.

MTASC and ANT : error running mtasc compiler

If you are trying to run MTASC from ant and are seeing the message ‘error running mtasc compiler’ this means that ant cant find the mtasc executable. There are 2 ways to remedy this.
The first is to add the folder with MTASC in to your system path. The second is to use the ‘mtasc’ attribute of Simon Wackers mtasc ant task to point it at mtasc.

If your mtasc executable is in D:devtools then you will need to define the task something like this :

<mtasc mtasc=”D:DevToolsmtasc.exe” …./>

I’ve written a more in depth guide to using ASDT and MTASC with ant over at osflash.org

last.fm recent tracks in flash

If you’ve been wondering when the code was going to return, well, here it is. Its a little app to show you your [tag]recently played tracks[/tag] from Last.fm. [tag]Last.fm[/tag] is a great site if you like music, and who doesnt like music? So whats it all about?

As they say ‘You get your own online music profile that you can fill up with the music you like. This information is used to create a personal [tag]radio[/tag] station and to find users who are similar to you’

One really nice feature is that a lot of the data is freely available from the audioscrobbler.net site in a variety of formats. This has prompted some people to create handy little scripts that generate sigs which show what you have just been listening to. Most of them have been made using php and GD to generate a graphic, or just plain ol html. So i thought this would be a perfect opportunity to do the same in [tag]Flash[/tag], but using only open source tools and libraries (You dont need the flash IDE installed to build it..)

You can download a zip of the code from here.

To build it you will need swfmill and MTASC, and to make your life easier i’ve included an ant build file.
The build file requires the as2 [tag]ant[/tag] tasks created by Simon Wacker which you can grab from here.

Also included in the zip is a lovely font created by the nice people at orgdot and a little php script that will cache the response from last.fm so you dont hammer their servers (they ask that you dont make more than 1 request a second..)

For now the implementation is very basic, im sure theres plenty of improvements and extras that can (and should) be added. Drop me a comment if you do something interesting with it.

and if you want to see it in action you can go here

SWT and Flash

I’ve been thinking about ways in which to use flash within eclipse and had considered using XML Sockets, but after reading the API docs for the SWT Browser I noticed that you can execute javascript functions by calling the execute method (funnily enough), and I already knew about the Flash / Javascript Integration Kit. So I knew i could send messages from java into flash, but how could i get information the other way?

Fortunately I noticed that the SWT browser allows you to listen for changes in the status text, so as a proof of concept I made a little project. Its nothing too exciting, but it shows how you communicate both ways and with a bit more work and some clever serialization I should be able to pass some rudimentary data types back and forth.

If you want to have a play you can download a zip file of the eclipse project here.

You’ll need to make sure the SWT library is on your build path to get it to compile. I’d be interested to hear if anyone has any problems using this, or if anyone makes any interesting additions to the code so we can do more complex java and flash communication within SWT.


At last I got off my arse and joined the ASDT project…well, of course I sent them an email and I stayed sitting in my chair as i do far too much, although i am making a regular habit of going outside for a walk or two every day.
I’ve just moved to Skopje (thats in Macedonia which you can find out about here) after living in London for far too long. So its also a good opportunity to learn my way around and try to remember that cars drive on the right hand side of the road, when im crossing the street.
Anyway, I think the release of FDT will spur myself and hopefully many more on to make ASDT the best option for developing flash. Dont get me wrong, im happy for them to release FDT as a commercial product and make money. We all have to eat :)

But, if you are like me and appreciate good quality open source tools and you want to see things happen with ASDT, keep bugging me and the other developers, or better yet, join up and start coding.

All flash and no bang

Flash 8 is announced, everyone is getting very excited about the new toys and tricks that are available, but, again it seems as though we are all deaf. (NOTE : I am writing this before i know for sure *exactly* what is in the new player, but from reading this it certainly looks like its all visual stuff)

Ok, so there are now 32 channels of sound in the new player (well, thats what it says here and there is a demo) BUT, oh, thats 32 mono channels, so 16 stereo channels.

Well, thats an improvement, but what can i do with those channels? anything new? theres all these fandangled bitmap filters and effects, why not the same for audio? Why do i have to be stuck with using mp3’s if i want some nice sound.
I want ogg’s and i want to access the sound buffer.
It doesnt even have to be real time, just let me write some numbers into an array, say here little sound object, eat this and loop it please. If i can update it at least some of the time, that would be cool, maybe play it back at different speeds. Im not asking for time stretching or anything.
Even some pre-defined filters would go a long way, just yer standard low pass / band pass / high pass would be great.

Oh well, maybe next time. At least i can do some motion detection with the camera and pass some data from that off via OSC (using flosc) to something nice, like plogue bidule