Hi! My name is Jan Jorissen. Check out some of my experiments:

WebGL Music Visualizer

A lot of sound visualizers are popping up all over the web using the Google Chrome Audiocontext API so I decided to have a go at it. This experiment was inspired by Diego Pintos FireBall experiment.

I started off by drawing a grid of vertices creating a plane, and then used a custom vertex shader and fragment shader to animate the vertices. Every frame the attributes of the verts get updated using the data from the AudioContext to distort them along the xy plane. For extra awesome I also added Perlin noise distortion along the yz plane using the processing API.

You can drag and drop any sound file to start playing and analyzing that one. Use the spacebar to toggle between the two visualizations, and use the options in the upper right for more fun!

technologies used: THREE.js,Tween.js, Chrome AudioContext API,Processing.js

visualiser

Playing with Particles

I finally got around to using the Particle class in THREE.js! ParticleSystems really allow you to go crazy with your experiments without worrying too much about performance. I came across a lot of cool shapes while making this, and you can find two of my favorites in this experiment! When you click your mouse, shape 1 will transform into shape 2. The transformation is done with the excellent tween.js class, moving around the 32k particles on your screen without as much as a hiccup!

To easily plot all my particles on a sphere-like shape, I used the THREE.SphereGeometry class, looped through all the faces and used their normals as a starting point for my transformations. You can make some awesome shapes doing this! Take a look at the code for more information -from line 131 tot line 169 you can find variations on the current shapes- :)

libraries used: THREE.js,Tween.js

particless

Experimenting with the Vertex shader in WebGL

Ever since I found out about WebGL and more specifically mr.doob’s THREE.js, I haven’t been able to stop experimenting with it. The examples that come with the 3D library provide an excellent reference for anybody interested in playing around with it, but it’s the tutorials by Paul Lewis that really got me going!

In this specific experiment I set out to construct a tunnel vertex by vertex, which allows me to move them around later on using a vertex shader. Afterwards I felt I could make things more interesting by adding a Sphere that moves through the tunnel, pushing away the vertices as it passes.. Feel free to check out the source code to get a better idea how this experiment was done!

libraries used: THREE.js

vertex

Animated 3D Perlin noise field

This experiment was my first succesful attempt at creating a vertex shader. A vertex shader is a program that runs on your graphics card, which allows you to do an insane amount of calculations on the vertices that make up your 3D model. In this case the 3D model is a plane, and every vertex is shifted along the Y-axis. This distortion is not really random but pseudo-random, more specifically it’s distorted using Perlin noise, which makes the transition between the random values really smooth.

You can see an early version of this experiment (without the animation) here!

libraries used: THREE.js & processing.js

perlinfield

Having fun with the curveTo() function

This is the experiment that led me to write the blogpost “Drawing a perfect circle using the curveTo() function“. Once I figured out how to draw circles, I started playing around and added a couple of parameters that define the shape of my circle. Afterwards I connected all the points with their neighbours using a LinkedList, wich allowed me to animate all of the points consecutively by just “launching” one point. Go ahead and try it out ! Make sure you click debug mode so you can see what is going on behind the scenes :)

curveto

Or take a look at some of my blogposts:

Blitting a Particle transition between two images

Sometimes when you are experimenting around with flash, you’ll notice that things can get a little laggy when you put too many things on the stage and try to move them around at the same time. The Display List is a very fast and easy way to handle the way things are displayed on the screen, but to you have to sacrifice some performance.

So why does the framerate in flash drop when you want to move +1000 MovieClips around at the same time? If you go and take a look at the livedocs for the MovieClip class, you’ll see that not only does MovieClip extend a handfull of classes ( Sprite Inheritance DisplayObjectContainer Inheritance InteractiveObject Inheritance DisplayObject Inheritance EventDispatcher Inheritance Object), it also has loads of properties like .currentFrame and methods like gotoAndPlay(). These are all very welcome when you want to make use of them, but when you just want to display basic things,  this is not the way to go.

One solution is using a Sprite (losing the timeline functionalites) or even a DisplayObject, the most basic class that Flash can display on its DisplayList. Another solution is using a technique called Blitting. There is an excellent article over at Adobe Developer Connection explaining the basics behind this technique.

In short, the reason why this technique is so fast, is that it skips the DisplayList entirely. When you draw something on-screen using the blitting technique, you copy a rectangular part of a bitmap straight to another bitmap. The first bitmap being offscreen, the second one on your stage.

For example, you tell flash to copy a rectangle with width=100 and height=100 at position x=0 and y=0, to your stage at position x=20 and y=20. This will now display a square with sides of 100pixels, containing whatever was in the upper-left corner of your off-screen bitmap, on your stage at position (20,20). Take a look at the following example to get a better idea:

Blitting

Blitting is really powerful when implemented in games. When you are animating a character, blitting the animation can easily give you a performance increase by factor 10. Check out the example below where I use blitting to move 2000 instances of the same character around on the screen. If these were animations playing on a timeline in flash, the framerate would drop drastically (click to focus & use your arrow keys to move the characters).

I did an intro a couple of years ago for the Interational Centre for Art & New Technologies, and in an early version of the current intro there was a transition between 2 logos using pre-sliced particles. I always wanted to do this again without the need of slicing the logos and with more particles, but I realised that performance would be an issue. A few years later I learned about blitting and familiarized myself with BitmapData & friends and the Synergy class was born in the process.

The Synergy class is initialized with the stage property of your Document class, and has a method called loadItems() that accepts 2 DisplayObjects – one sourceObject and one targetObject. What happens next is that after calling the Synergy.explode() method, the sourceObject dissolves in all the pixels that make up the object, fly away and then join together in the targetObject. Check out the example below. Make a drawing, click the ‘Switch’ button to switch to the other drawing board, and when you are happy with both of your drawings, click the ‘Start’ button! Press clear if you want to reset the current drawing.

Now let’s take a look at what is happening behind the screens. There were a couple of challenges that I encountered and things I learned while working on this project, so read on for some highlights or just dive into the source code.

  • A closer look at the drawing technique, inspired by blitting.
  • A small class I wrote for easier color analyzing
  • Some random optimizations

A closer look at the drawing technique

The first thing that happens in the loadItems() method, is parsing of the DisplayObjects. By parsing I mean analyzing every pixel, checking it for alpha value (when the alpha value is 0, you don’t need to move it around because, well, it’s transparent). for every pixel that is worth moving around, an object from the ‘Particle’ class is created. This class contains some essential info about the pixel:

- Its original position (“sourceX,sourceY” >> we will need these later on, when we are blitting FROM the offscreen object)
- Its current position (“x,y” >> indicates the position on the stage where we will copy TO.
- Its target position (“targetX,targetY” >> which will indicate the position where the pixel will have to move to)
- A reference to the DisplayObject where the pixel came from. (a variable called “copyBitmapData”)

All these particles get placed in a list, and are drawn on the screen 31 times per second, on the ENTER_FRAME event. Let’s take a look at the function that draws our pixels on the screen:

private function drawStuff(e:Event):void
{
	canvasData.fillRect(canvasData.rect, 0xFFFFFF) // clear the canvas before drawing
	var lli : ILinkedListIterator = sourceList.iterator() as ILinkedListIterator;
	var item:Particle;
	while (lli.hasNext())
	{
		lli.next();
		item = lli.current;
		if(item.update()) getNewTarget(item);
		copyP.x = item.x; copyP.y = item.y;
		copyR.width = copyR.height = particleSize;
		copyR.x = item.sourceX; copyR.y = item.sourceY;
		canvasData.copyPixels(item.copyBitmapData, copyR, copyP);
	}
}

“copyP”  is a Point object and “copyR” is a Rectangle object. These two objects are essential parameters for the copyPixels method. the “copyR” rectangle defines the area that will be copied to the stage (see examples above) and the “copyP” point defines the position that this rectangle will get on the stage. item.copyBitmapData is the reference to the DisplayObject where the pixels will be copied from.

the item.update() method returns a Boolean, which is false when the particle is still swarming around randomly. Yet when this function returns true, it means that the particle has come to a standstill, and that it needs a destination. The method getNewTarget will give this particle a destination to Tween to. Notice that in this case we are not tweening a DisplayObject -which is usually the case- but we will be tweening the X and the Y properties of the Particle object.

the Pixel32 class

When you extract pixel information from a bitmap, you can do so using the BitmapData.getPixel32() method. This returns an unsigned integer, ranging from 0  (0×00000000) to 4294967295 (0xFFFFFFFF).  To make my life a little bit easier I created the Pixel32 class. You can create a new Pixel32 object by instantiating it with the color value and then reading the public properties alpha,red,green or blue, or you can make use of the static functions. These include:

  • toString():  this will return a string, for example “OxFFOOFFOO – Alpha: FF – Red:  0 – Green:  FF- Blue:  0″;
  • isWhite(): this will return a Boolean that tells you wether or not the pixel is white.
  • isTransparent(): this will return a Boolean that tells you wether or not the pixel is 100% transparent.
  • getAlpha(), getRed(), getGreen(), getBlue()

 

Some random optimizations

  • Declare your variables outside of for/while loops. You will noticed a huge increase in performance when doing this. If you take a look at the code above,  you’ll see that I declare “var item:Particle” just once, before the loop, and then re-use this variable, instead of declaring it over and over again inside of the while loop.
  • Using a LinkedList instead of an Array is a great way to increase performance, when iterating through the list is the most important thing and random access of items in the list is not necessary.

I hope you had as much fun reading this blogpost as I had making it! If you have any questions about this post, or if you have tips to improve my code or the application performance, please use the comments section below.

Like this post ? Follow me on Twitter !

particles

Prototyping: ActionScript’s best kept secret

As a developer, once in a while  you discover something new that makes you go  ”How come nobody ever told me about this and why do I only find this out NOW ? ”  Last year, when I discovered that a Function in AS3 is also a class and can be used as a a variable/property, was one of those moments.  I remember getting all fuzzy and warm inside and seeing all the ways that it could improve my coding skills, flashing before my eyes.

Today I experienced something similar. While playing around with the amazing “Three.js” JavaScript library (originally developed by the equally amazing mr.doob), I noticed that the “prototype” property kept popping up in my code completion. After googling around for a bit, I came to the conclusion that I used this technique in jQuery before without realizing  it.  So what is this prototyping that I speak of ? Let’s take a look at the following situation where you want to randomize an Array.

var myArr:Array = [1,2,3,4,5,6];
 
// Normally you would do something like this
myArr = randomizeMyArray(myArr);
 
// Thanks to prototyping, you can type
myArr.randomize();

As you probably know, the Array class doesn’t have a public method called “randomize”. This is what prototyping allows you to do: Add properties and methods to classes, without extending them. Let’s take a look at another example. In Flash Player 10.3, the method “removeChildren” was introduced. If you want to use this functionality without worrying about the Flash player version, you can add this public method to the DisplayObjectContainer class using prototyping. Let’s take a look at how to implement this:

DisplayObjectContainer.prototype.removeAllChildren = function ():void
{
	while (this.numChildren > 0)
	{
		this.removeChildAt(0);
	}
}

Using this code, the public method “removeAllChildren()” will be available for all DisplayObjectContainers (including MovieClips, Sprites,…) in your project. Inside the anonymous function, you can use the “this” keyword to address the instance that called the method. I created a small class called “Prototyper” with a couple of static methods.

If you want to add the .randomize() method to the Array class in your project, just call the method Prototyper.randomize() once to do the prototyping. Also included is the .removeAllChildren() method. Take a look at the class and feel free to add new functionalities! What about a new “addToCenter()” method for the Stage object? If you come up with some really cool prototyping, make sure to share them in the comment section below!

*Update* If you take a look at the comments section, you’ll find a few reasons why you should refrain from using Prototyping (including performance issues & debug problems). For the brave souls that would like to venture further in the prototyping underworld, I suggest you take a look at this website with loads and loads of snippets!

Like this post ? Follow me on Twitter !

bwas3

More fun with Azoth: “Sierpinski Yourself”

You need a webcam to enjoy this blogpost to the fullest

This post is a brief addendum of my previous post about Azoth. I was so excited about Azoth’s performance in my previous post that I didn’t take enough time to come up with a more practical example. Like I said last time, ByteArray operations is what Azoth does best, and this time I’m going to use the BitmapData of a webcam feed and manipulate those pixels in some fun ways. Also, you will be able to look like a complete fool in front of your PC. If you follow all the steps in this tutorial (or download the Source code), you should end up with a Sierpinski-ish photo like this:

Sierpinski Image

To set up your webcam, you can use the following code:

cam = Camera.getCamera();	// Initialize the webcam
cam.setMode(320,240,30);	// Set the dimensions and FPS
cam.setQuality(0, 100);		// Set the quality
 
video = new Video(_w,_h);	// the video object will display the stream
video.attachCamera(cam);

As you can see I’m using pretty low quality settings, this is because we’ll be doing quite some heavy calculations later on, 76800 (320×240) times per frame, at 30 frames per second (a whopping 2,304,000 pixels that are analysed, displaced and displayed every second). We won’t be adding the video object to our display list, since we only want to display the video-data after it has been manipulated. Remember that any object that implements an IDrawable object (MovieClip, Video, ..) can be drawn to a BitmapData using the .draw() method, even when it’s not in the display list. Next up, we are going to extract the pixel information out of our webcam feed:

canvasBitmapData.draw(video);  // draw the bitmap data from the videofeed to a BitmapData object
byteArray = canvasBitmapData.getPixels(new Rectangle(0, 0, _w, _h)); // extract the pixel data as an array of Bytes
doFastMem()

this block of code will be executed every frame, and the doFastMem() method will do all of the hard work. Let’s take a look at this method:

byteArray.position = 0;			// set your ByteArray at memory position 0, ready to be read.
fastmem.fastSelectMem(byteArray); 	// load the ByteArray in our fastmem class
 
for (var i:int = 0; i < numBytes; i += 4)	// loop through all the pixels			
{	
	fastmem.fastSetI32(fastmem.fastGetI32((i * 2) % (numBytes/2)), i);	// do the Sierpinski magic
	// get the pixel at memory position i*2 (with modulo of all the bytes divided by 2)
	// and set them at memory position i 
}	
 
// return the information from the fastmem class back to the byteArray object  
fastmem.fastDeselectMem();
// return the modified pixels back to the canvasBitmapdata object				
canvasBitmapData.setPixels(new Rectangle(0,0,_w,_h), byteArray);

In the example below I made things 4 times bigger by using ‘canvas.scaleX = canvas.scaleY = 2′. If you open the context menu and hit ‘Show Profiler’, you will see that the demo runs at a solid 31fps. Press the button in the upper left corner to take a picture your Sierpinski-self – You’ve got 5 seconds to strike a pose! (I’ve thrown in some extra effects for good measure).

Gallery of sierpinskied people:

Like this post ? Follow me on Twitter !

MySierpinski

Supercharge your ByteArray operations using Azoth

(edit: take a look at my next blogpost for more fun with Azoth !)

I recently came across an interesting use of Adobe’s Alchemy technology. Basically what Alchemy allows you to do is run compiled c/c++ code inside of the ActionScript Virtual Machine. This in turn allows you to implement low-level optimizations that can lead to huge performance gains. Since I don’t know any c++ I’m not going to cover how to create your own libraries, but I’ll share a really cool executable called ‘Azoth’ that offers the power of Alchemy using a simple drag & drop or command line interface.

Azoth simulates direct access to system memory addresses -while coding in AS3, you use the provided fastmem.as class to read and write values. Afterwards, you re-compile the SWF file using the Azoth executable, which then replaces the fastmem.as class with optimized Alchemy code. Where Azoth really shines, is ByteArray operations. When you are working with BitmapData and the getPixels/setPixels methods, you are dealing with an array of 32 bit (or 4 byte) unsigned integer values. Every pixel has the following 4 bytes of information stored in this array:

(from left to right)

  • byte 1: Blue Channel (8 bits = 1 byte = 255 possible values)
  • byte 2: Green Channel (8 bits = 1 byte = 255 possible values)
  • byte 3: Red Channel (8 bits = 1 byte = 255 possible values)
  • byte 4: Alpha Channel (8 bits = 1 byte = 255 possible values)

for example, the unsigned integer 0x00FF0088 represents a green color with a 50% alpha value. (quite an unsettlingly ugly color to be fair)
Since it’s always fun to get visual feedback when trying new things, and fastmem.as has a method called fastSetI32, we’ll manipulate the data of these pixels. Take a look at this short code excerpt to see the class at work. You can find the full source code here.

private function frameHandler(e:Event) :void
{
 
	byteArray.position = 0; 		// prepare your ByteArray to be read from the start.
	fastmem.fastSelectMem(byteArray); 	// select your ByteArray with the fastmem.as class
	getColor(); 				// change the color 
 
	for (var i:int = 0; i &lt; numBytes; i += 4)       // loop through all the memory addresses.
							// steps of 4 since every address holds 1 byte of data and
							// our pixel has 4 bytes of data.
	{
		fastmem.fastSetI32(color, i );		// write the 32bit unsigned int holding the colour information
	}
 
	fastmem.fastDeselectMem(); 			// deselect the memory
	bData.setPixels(rect, byteArray);		// fill the Bitmap with the net BitmapData
}

So, exactly how big is this increase in performance thanks to Azoth ? When running really abstract read/write tests, there was a staggering increase of about 1500%. In the example I will be showing, the performance increase depends on the machine that is running the SWF’s, but overall the frame rate increased from 18 FPS to 120 FPS (the framerate limit set by the flashplayer). All I had to do was:

  1. use the fastmem.as class when dealing with  ByteArray objects.
  2. drag ‘n drop my SWF on Azoth.exe.

Like magic, a new file appears called yourswfname_azoth.swf, and you can enjoy your turbocharged SWF file! Take a look at the optimized SWF below and then take a look at the original here. (For reasons -to me- unknown, both SWF’s drop to the lowest framerate when they are displayed on the same page.)

Also, don’t forget to take a look at the website of the guys that created Azoth for some more (technical) information. Thanks to SWFProfiler for the free & awesome performance measuring tool.

Like this post ? Follow me on Twitter !

bytearray

Flash packager for iPhone: Using the Geolocation class

Prerequisites:
- an iOS device.
- Flash professional CS5
- an iPhone dev. license/certificate that allows you to package flash and deploy on iOs.

After playing around with the flash packager for iPhone that ships with Flash CS5, I thought I’d share some information about one of the most interesting aspects of mobile development: Location based services. If you want to access information about the whereabouts of a mobile device, the Geolocation class is your friend.

Since I’ve been living in Gent for more than a year now, making an application that calculates the distance (in a straight line) between my location and the city center of 9000 seemed like a good start. The Geolocation class uses latitude and longitude values, so the first thing I had to do was find out what the Lat/Long values of the city center were. Apparantely there is no immediate way to extract these values from Google Maps, so I found this neat little trick -Go to Google Maps, make sure the location you want Lat/Long information about is centered, and then copy/paste the following code in your address bar and hit enter:

 javascript:void(prompt('',gApplication.getMap().getCenter()));

A pop-up should appear with the latitude and longitude values of the current marker position.
The next thing we need is the coordinates of the mobile device. Since a mobile device is per definition capable of moving around, its location can change every second. This is why the Geolocation class acts as an EventDispatcher, with a definable interval. So, If you would like to check on the location of the device every second, this is what your code would look like:

if (Geolocation.isSupported)
{
     geo = new Geolocation();
     geo.setRequestedUpdateInterval(1000); // 1000 milliseconds = 1 second.
     geo.addEventListener(GeolocationEvent.UPDATE, geolocationUpdateHandler);
}

Make sure that you have a private class member called “geo” of the type Geolocation. What happens next is pretty straightforward: you create an event handler called “geolocationUpdateHandler”, with a GeolocationEvent as single parameter. You can then extract the latitude / longitude from this GeolocationEvent – object, along with some other properties such as altitude, speed, etc.

Finally, you have to calculate the distance between your current coordinates and those of Gent. I used the following code:

private function geolocationUpdateHandler(event:GeolocationEvent):void
{
          var myLat:Number =  51.05563894; // Gent Latitude
          var myLong:Number = 3.7216186523; // Gent Longitude
	  distance_txt.text = "Distance from Gent: " + getLatLongDistance(myLat, myLong, event.latitude, event.longitude) + " km.";
}
 
private function getLatLongDistance(lat1:Number, lng1:Number, lat2:Number, lng2:Number):Number
{
	var pi80:Number = Math.PI/180;
	lat1 *= pi80;
     	lng1 *= pi80;
      	lat2 *= pi80;
      	lng2 *= pi80;
      	var earthRadius:Number = 6372.797; // Omtrek van de aarde in km.
      	var dlat:Number = lat2-lat1;
      	var dlng:Number = lng2-lng1;
      	var a:Number = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dlng / 2) * Math.sin(dlng / 2);
      	var c:Number = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      	var km:Number = earthRadius*c;
	return km;
}

And there you have it: If you ever wonder how far it would be to fly to Gent from your current location in a supersonic jet, now you know!

Distance from gent
Like this post ? Follow me on Twitter !

gps

drawing a perfect circle with the curveTo() function

I’m guessing most of you already know what the graphics.curveTo function is. As the name suggests, it allows you to draw a curved line that starts at a certain point, bends towards a control point, and ends in an anchor point. The starting point of the curve can be defined in three ways:

  • undefined: the default starting point will be (0,0)
  • the last anchor point: this will be the default starting point when you’ve already drawn a curve. this overrides the default point above.
  • using the moveTo method: you set the starting point by using graphics.moveTo(x,y). this method overrides all of the above.

After leaving the starting point, the curve will work its way to the Control point, and then curve to the Anchor point. That’s basically what curveTo() does.

So why would you draw a circle with the curveTo function when you can just use drawCircle ? One answer to this question is that it’s just fun to experiment with these things in flash, another answer is that when you dynamically draw a circle using this method, you can animate the different points that make up the circle and create even weirder shapes.

First thing we have to do is define all our Anchor points. Since we are drawing a circle, it would be helpful if the anchor points were nicely aligned in a circular fashion. One way to align pretty much everything in a circular order is working with sine and cosine, but right now I would like to try this another way, namely using the Point.polar() method. (no worries, we’ll be needing our trigonometric friends later on).

The polar() function works with polar coordinates, as opposed to cartesian coordinates that are standard in flash. The main idea behind the Polar coordinate system is that instead of working with an X and Y position to define a point, you work with an angle and a distance. The distance tells you how far this point is removed from the Pole (the fixed point in the system) and the angle tells you the angle of the point relative to a horizontal line going through the Pole.

So, if you want to draw a 100 points that are all on the edge of a perfect circle with radius 10, the polar coordinates for the first five points will be:

Circles

the Point.polar() method has 2 parameters, the first being the distance to the Pole, the second being the angle (in radians). The method then returns a Point object with the corresponding cartesian coordinates, and this allows you to draw this point on the screen in Flash. so, drawing all of our points (in this case a circle with radius 1) will go as follows:

this.graphics.beginFill(0);
for (var i:int = 0; i &lt; numberOfPoints; i++)
{
    var p:Point = Point.polar(10,2*Math.PI * i/numberOfPoints);
    this.graphics.drawCircle(p.x,p.y,1);
}
this.graphics.endFill();

Now that I’ve made it clear how to draw the Anchor points in a circular method, all that is left is drawing the Control points. The Control Points will make sure that the curves between the anchor points form a nice circle. We’ll use some trigonometry from back in the high school days to find their coordinates. Because we will also use the Point.polar() method, all we need to do to find the coordinates, is the distance from the Control Points to the center. We can then re-use the for-loop above, with the adjusted distance to the Pole.

Circles

We can establish that the COS(delta/2) = r / |AB|. Thanks to this, we can calculate |AB|. the line AB is the angle bisector of Delta (meaning AB splits the angle Delta in 2 evenly divided parts). Point B is where the 2 Perpendicular lines meet with each other AND with the bisector -We are not going into specifics as to why this is, but feel free to prove this yourself :) .

This leaves us with |AB|, the distance from the center of our circle to every Control Point. All that we need to do now is plot these points next to each other and draw Curves through them. Take a look at the following code to see what you need to draw a Circle with 10 Control Points and be amazed when you see how fluid the circle appears.

public class APC extends MovieClip {
 
	private var ControlPoints:Array = [];
	private var AttachPoints:Array = [];
	private var diameter:int = 100;
	private var Points:int = 10;
 
	public function APC() {
		var xx:int = stage.stageWidth/2;
		var yy:int = stage.stageHeight / 2;
			var outerDiameter:Number = diameter / Math.cos(Math.PI / Points);
 
		for (var i:int = 0; i &lt; Points; i++)
			{
				var Ap:Point = Point.polar(diameter, i * 2 * Math.PI / Points);
				var Cp:Point = Point.polar(outerDiameter, i * 2 * Math.PI / Points + (Math.PI / Points ));
				Ap.x += xx;
				Ap.y += yy;
				Cp.x += xx;
				Cp.y += yy;
				AttachPoints.push(Ap);
				ControlPoints.push(Cp);
			}
 
		drawStuff();
	}
 
	private function drawStuff():void
	{
		this.graphics.beginFill(0);
		this.graphics.moveTo(AttachPoints[0].x, AttachPoints[0].y);
		for (var i:int = 0; i &lt; Points-1; i++)
		{
			this.graphics.curveTo(ControlPoints[i].x, ControlPoints[i].y, AttachPoints[i+1].x, AttachPoints[i+1].y);
		}
		this.graphics.curveTo(ControlPoints[Points-1].x, ControlPoints[Points-1].y, AttachPoints[0].x, AttachPoints[0].y);
		this.graphics.endFill();
	}
}

And to wrap things up, have a look at all the cool stuff you can do once you start tweening these points… Go forth and experiment !

Like this post ? Follow me on Twitter !

perfectcircle

the Monty Hall problem: A programmer’s approach

I’ve always enjoyed mindgames, but there was always one riddle that I just couldn’t wrap my head around. You may or may not have heard about the Monty Hall problem:

Suppose you’re on a game show, and you’re given the choice of three doors: Behind one door is a sportscar; behind the others, goats. You pick a door, say No. 1, and the host, who knows what’s behind the doors, opens another door, say No. 3, which has a goat. He then says to you, “Do you want to pick door No. 2?Is it to your advantage to switch your choice?

The answers is: Yes. switching to another door will double your chances of winning the sportscar (from 33% to 66%). Now this may strike you as very peculiar, because after all, if there are only 2 options left (in this case door No.1 & door No. 2), then the chances to win the car are 50% right ?
If you are already outraged by now, it might bring a little solace to know that you are not alone. Nobel prize winners and Professors around the world alike have made the same mistake. I concluded there was only one way to find out who was right, and using my weapon of choice (AS3), I recreated the setting of the gameshow and simulated 1.000.000 games.

The results were pretty convincing: Staying with your original door yielded a favorable result 33% of the time, whilst switching doors won you the car 66% of the time. And it was only when I was coding this little simulation, that I understood how exactly this is possible. Let’s have a look at some the code involved.

[edit: Now with even shorter code notation, thanks to Pascal]

private function startLongGame(doSwitch:Boolean):Boolean
{
	doors = [0, 1, 2];
	var winningDoor = randomRange(0, 2);
	var doorChosen:int = randomRange(0, 2);
        if(doorChosen == winningDoor && doSwitch) return false;
 
	var doorGiven:int = giveDoor(doorChosen, winningDoor);
 
	if (doSwitch) {
		doors.splice(doors.indexOf(doorChosen), 1);
		doors.splice(doors.indexOf(doorGiven), 1);
		doorChosen = doors[0];
	}
 
	if (winningDoor == doorChosen) return true;
	return false;
}
 
private function giveDoor(chosen:int,winner:int):int
{
	var tempDoors:Array = [0, 1, 2];
	tempDoors.splice(tempDoors.indexOf(chosen), 1);
	tempDoors.splice(tempDoors.indexOf(winner), 1);
	return tempDoors[randomRange(0,tempDoors.length-1)]; // if there are two doors left, choose one random door.
}

This is a very long but readable way of simulating the problem. There is a random ‘winningDoor’, I choose a random door ‘doorChosen’ , and according to these variables, the method ‘giveDoor’ returns a door that the host will open. Depending on my boolean ‘doSwitch’, I change my mind or stay with my original choice. Pretty straightforward, and the results are correct: switching wins the car 66% of the time, not switching only 33%.

But when you think about this a little more, you’ll see that there is a much shorter way of coding all this. You can skip the whole giveDoor part, because the matter of fact is, it doesn’t matter which door the host gives you, because it will always be a goat. If you chose a winning door, and you switch, you always lose. if you chose a goat, and you switch, you always win. Since you choose a goat 66% of the time, switching gives you a car 66% of the time ;-)

private function startShortGame(doSwitch:Boolean):Boolean
{
	var doYouGetACar:Boolean;
	var winningDoor = randomRange(0, 2);
	var doorChosen:int = randomRange(0, 2);
 
	if(winningDoor != doorChosen){ // this happens 66% of the time
             doYouGetACar = (doSwitch)? true:false;
        }
 
	if(winningDoor == doorChosen){ // this happens 33% of the time
             doYouGetACar = (doSwitch)? true:false;
        } 
 
	return doYouGetACar;
}

If you don’t take my word for it, take a look at the simulation below, or download the AS Class and check it out!

Like this post ? Follow me on Twitter !

monty

estimating the duration of a Sound Object while loading

In case you never used the Sound class before, let me give you a brief introduction.
The Sound class is found in the flash.media package and is used (hard not to be obvious here) for playing sounds. The constructor for the Sound class has 2 optional parameters:

  • stream:URLRequest = new URLRequest(“url:String“);
  • context:SoundLoaderContext = new SoundLoaderContext(“buffertime:Number” , “checkPolicyFile:Boolean” )

The SoundLoaderContext is crucial if you are loading sounds from another website (needed to prevent security errors). This class also allows you to determine the amount of milliseconds that flash will buffer before playing your file.

var $path:String = "assets/sounds/theme.mp3";
var $buffer:Number = 5000;
var $checkPolicyFile:Boolean = false
var s:Sound = new Sound(new URLRequest($path), new SoundLoaderContext($buffer, $checkPolicyFile));

So far, so good. We created a Sound object that is currently loading and will be ready to play when 5 seconds of audio have been buffered.
Now lets take a look at the Sound objects public properties. The ones that we are interested in are the following:

  • length:Number = the number of milliseconds that have already been loaded and are ready to play
  • bytesLoaded:uint = the number of bytes that are already loaded from the audio file
  • bytesTotal:uint = the fileSize in bytes of the audio file

As you can see, one property that would be very useful is missing. Namely, the duration of the entire audio file in milliseconds (when fully loaded). Imagine that you would like to create an online music player, and you need to display a scrollbar to show the user to which part of the song he is currently listening (*) . If the file is still loading, you will be unable to use the length property, because it only shows the number of milliseconds that have already been loaded, not the entire length of the song ! Now have a look at this method:

private function guessDuration(s:Sound):Number 
{
    return Math.floor( s.length / (s.bytesLoaded / s.bytesTotal) );
}

This function will calculate a value for the total duration, based on the correlation that exists between bytesLoaded / bytesTotal and s.length / [s.length when downloading is finished] Please realize that this value remains an estimate, but for my applications, it has proven to be amazingly accurate. Happy Coding !

* Extra: getting the current position (in milliseconds) of a Sound when it’s playing.

So, now you know how to find an estimated value for the total playback time of your file. But if you are still planning on making the online music player with a scrollbar, you will also need to know at which point in the song you are when its playing. The Sound class doesn’t have a property called “position” or “currentPosition”, but luckily for us, the SoundChannel class does.
What’s important here, is that when you call the Sound.play() method, it returns a SoundChannel. If you keep this SoundChannel stored in a variable, you can later access its position:Number property, which returns the current position (in milliseconds) of you original Sound object.

...
var sound:Sound = new Sound(new URLRequest("01.mp3"));
var channel:SoundChannel = sound.play();
 
// now you can get the current position and the estimated length (both in milliseconds)
 
var position:Number = channel.position;
var duration:Number = guessDuration(sound);

Like this post ? Follow me and multimediacollege on Twitter !

sound

Optimizing the floodFill() method.

If you ever used the floodFill() method that is provided in the AS3 BitmapData class, you know that it doesn’t always act like it’s supposed to. For those of you unfamiliar with it, the The floodFill() method is similar to the paint bucket tool in various paint programs. The signature of the method looks like this:

   public function floodFill(x:int, y:int, color:uint):void

You provide the method with an X and Y coordinate (the pixel at this location will define the color of the area that will be flooded with a color of your choice). Then you provide the method with an unsigned integer (ARGB value) , ranging from 0 (0×00000000) to 4294967295 (0xffffffff).

What is important to realize here, is that only neighboring pixels with the exact same color value will be flooded. So the floodFill() method does his job flawlessly, only sometimes we would like to flood pixels that are slightly similar as well.

For example, when we take a closer look at most rounded shapes on a pixel level, we will see that there is some anti-aliasing going on to give the picture a more smooth look. The anti-aliasing will create a range of colors between the fill color and the border color. These colors will be skipped by the floodFill() method, since they do not have the exact same ARGB value as the color that has to be flooded. You can try this out for yourself in the flash movie below.

To bypass this ‘shortcoming’ of the floodFill() method, we will be adding a filter on top of the floodFill. And what better filter to add some subtle extra color to edges than the GradientGlowFilter ? So, what we will actually be doing is this:

  1. take a snapshot of the original image
  2. take another snapshot of the original image and apply the floodFill
  3. compare the two snapshots using the BitmapData.compare() method and save this shot. (only the fill will be left in this 3rd shot)
  4. add a GradientGlowFilter to shot #3 and save it.
  5. copy the BitmapData of this third shot (with only the fill in it) to a new Bitmap.
  6. add this Bitmap to the original image !

here are some code snippets used in this example:

 [1] var snapshot1:BitmapData =  new BitmapData(target_mc.width, target_mc.height, false, 0xFFFFFFFF);
 
 snapshot1.draw(target_mc);
 
 var snapshot2:BitmapData =  BitmapData(snapshot1.clone());
 
 [2] snapshot1.floodFill(point.x, point.y, color);
 
 [3] var compareResult:Object = snapshot1.compare(snapshot2);
 if (compareResult) {
 
    var comp:BitmapData = BitmapData(compareResult);
 
    var alphaValue:uint = color >> 24 & 0x000000FF; // we would like to use the same Alpha as in our original image
 
    [4] comp.applyFilter(comp, comp.rect, new Point(0, 0), new GradientGlowFilter(0, 90, [color, color], [0, alphaValue], [0, 255], 2, 2, 5, BitmapFilterQuality.HIGH, BitmapFilterType.FULL, true));
 
    var bmp:BitmapData = new BitmapData(target_mc.width, target_mc.height);
 
    [5] bmp.copyPixels(comp, comp.rect, new Point(0, 0));
 
    [6] target_mc.addChild(b);
 
 }

Like this post ? Follow me on Twitter !

floodfill

Use the menu in the upper right corner to play with the background!

Hi there.

My name is Jan Jorissen and I'm a web developer from Belgium, currently living in Perth, Australia.

I studied New Media & Communications technology with a major in Multimedia, concentrating mostly on the Actionscript 3 language. I then did a 4 months internship at the International Centre for Arts and New Technologies in Prague, Europe.

Afterwards I worked at Multimediacollege for 2 years as an all-round webdev and a consultant/instructor for Flash and a variety of other Adobe products.

I've always been interested in making visualizations and experiments, and with the rise of new web technologies like WebGL, my interests have shifted from 2D visuals to 3D visuals. On this website you can find a selection of my works in the Labs section, and some more technical articles on my Blog.

So please, take a look around and if you like what you see or have any questions, send me a tweet or drop me an email at info [at] janjorissen.be!

__blob