<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Soulwire &#187; Flash</title>
	<atom:link href="http://blog.soulwire.co.uk/category/laboratory/flash/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.soulwire.co.uk</link>
	<description>Art + Technology</description>
	<lastBuildDate>Fri, 12 Feb 2010 00:29:59 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Smack My Glitch Up</title>
		<link>http://blog.soulwire.co.uk/laboratory/flash/as3-bitmapdata-glitch-generator</link>
		<comments>http://blog.soulwire.co.uk/laboratory/flash/as3-bitmapdata-glitch-generator#comments</comments>
		<pubDate>Wed, 03 Feb 2010 21:37:51 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Generative]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Transmissions]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Colour]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Glitch]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=1003</guid>
		<description><![CDATA[
Sometimes it&#8217;s good to break things&#8230;
During a recent project I needed to find a way of simulating digital interference on an image / video stream. At first, it seemed the best approach might be to use the graphics API or Bitmap effects, but why imitate when you can have the real thing.
The principle is incredibly [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/art-design/generative/webcam-glitch-art' rel='bookmark' title='Permanent Link: Webcam Glitch Art'>Webcam Glitch Art</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette' rel='bookmark' title='Permanent Link: BitmapData Colour Palette'>BitmapData Colour Palette</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/glitchmap.swf" title="AS3 Glitch Generator" rel="lightbox;width=900;height=650;" ><img class="alignnone size-full wp-image-1006" title="Glitchmap - AS3 Glitch Generator" src="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/glitch-generator.jpg" alt="Glitchmap - AS3 Glitch Generator" width="710" height="360" /></a></p>
<p><em>Sometimes it&#8217;s good to break things&#8230;</em></p>
<p>During a recent project I needed to find a way of simulating digital interference on an image / video stream. At first, it seemed the best approach might be to use the graphics API or Bitmap effects, but why imitate when you can have the real thing.<span id="more-1003"></span></p>
<p>The principle is incredibly simple. Corrupt / alter a byte (or several bytes) in the ByteArray of a JPEG and then load this back into a DisplayObject using <em>Loader.loadBytes()</em>. Because of the way in which <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure" >JPEGs work</a>, the image will still display but the corrupt bytes will mangle the output to varying degrees, depending on how many bytes have been corrupted. The result is an interesting glitch pattern, a bit like those which were accidentally created <a href="http://blog.soulwire.co.uk/art-design/generative/webcam-glitch-art" title="Webcam glitch images" >when my webcam drivers lost the plot</a>.</p>
<p>It is also possible to corrupt other image formats (png, gif etc) in the same way, by first passing the image ByteArray through a <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://code.google.com/p/as3corelib/source/browse/trunk/src/com/adobe/images/JPGEncoder.as" >JPEGEncoder</a>.</p>
<p>I&#8217;ve implemented this technique in the <strong>Glitchmap</strong> class, which you can download and play with at the bottom of this post. I hope that it will provide a few moments of fun, if not a practical use <em>(I&#8217;m thinking image gallery transitions or <a href="http://blog.soulwire.co.uk/laboratory/flash/actionscript3-dynamic-sound-visualisation" >music </a><a href="http://blog.soulwire.co.uk/art-design/portfolio/more-bandcamp-music-visualisations" >visualisations</a>)</em>.</p>
<p>The small gottcha is that it isn&#8217;t desirable to mess with the JPEG headers, so when the clean ByteArray is passed to the <em>Glitchmap</em> class, it will determine the length of the header by reading through the bytes until it finds the <em>SOS (start of scan)</em> declaration <em>(0xFFDA)</em>. The next two bytes represent the length of the <em>SOS</em>, so it skips forward by this amount &#8211; the resulting position in the ByteArray should be the end of the header, and so between this point and the <em>EOI (end of image)</em> the data corruption takes place. I&#8217;m not sure whether this is the best way of determining the JPEG header size; <em>perhaps any CS graduates / students out there can help me out?</em></p>
<p>After I posted the <a href="http://blog.soulwire.co.uk/art-design/generative/webcam-glitch-art" >webcam glitch images</a>, Jon used them in his title sequences for the <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.youtube.com/watch?v=k5scRdXr7wU"  rel="shadowbox[post-1003];player=swf;width=640;height=385;">48 hour film gala</a>. If you find a similar creative use for this script or the <a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/glitchmap.swf" title="AS3 Glitch Generator" rel="lightbox;width=900;height=650;" >glitch generator</a> then please let us all know.</p>
<p>I think the next step is to experiment with merging the bytes of multiple glitched images in order to create transition effects. I may also build an AIR app and see what the best way of outputting video might be (using NativeProcess for screen capture perhaps?).</p>
<a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=Glitchmap.zip" class="download" title="AS3 BitmapData Glitch Generator (Glitchmap): Glitchmap is a class for generating glitch imagery from AS3 BitmapData"  rel="nofollow"><strong>Download:</strong> AS3 BitmapData Glitch Generator (Glitchmap)</a>
<p><em>You can also download the Glitchmap Class and the <a href="http://blog.soulwire.co.uk/wp-content/uploads/2010/02/glitchmap.swf" title="AS3 Glitch Generator" rel="lightbox;width=900;height=650;" >Glitch Generator</a> source code from the <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://code.google.com/p/soulwire/" title="Soulwire code repository" >soulwire code repository</a>.</em></p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/art-design/generative/webcam-glitch-art' rel='bookmark' title='Permanent Link: Webcam Glitch Art'>Webcam Glitch Art</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette' rel='bookmark' title='Permanent Link: BitmapData Colour Palette'>BitmapData Colour Palette</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/laboratory/flash/as3-bitmapdata-glitch-generator/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Technical Tentacles</title>
		<link>http://blog.soulwire.co.uk/laboratory/flash/pixel-bender-growing-tentacles</link>
		<comments>http://blog.soulwire.co.uk/laboratory/flash/pixel-bender-growing-tentacles#comments</comments>
		<pubDate>Tue, 26 May 2009 19:08:17 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Generative]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Flash Player 10]]></category>
		<category><![CDATA[Pixel Bender]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=360</guid>
		<description><![CDATA[
I’ve been revisiting one of my favourite topics lately &#8211; recursion &#8211; and have been getting together a bunch of sketches for a big personal project I’m working on (more on that another time). Anyway, I inadvertently stumbled across quite a nice way of making things grow in a convincing manner, and whilst this script [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/perlin-noise-flow-field' rel='bookmark' title='Permanent Link: Perlin Noise Flow Field'>Perlin Noise Flow Field</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata' rel='bookmark' title='Permanent Link: 2D Cellular Automata'>2D Cellular Automata</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2009/05/tenticles.swf" rel="lightbox;width=900;height=760" title="Pixel Bender Generative Tentacles" ><img src="http://blog.soulwire.co.uk/wp-content/uploads/2009/05/tentacles-cropped-710x326.jpg" alt="Generative Tentacles" title="Generative Tentacles" width="710" height="326" class="alignnone size-medium wp-image-509" /></a></p>
<p>I’ve been revisiting one of my favourite topics lately &#8211; <strong><a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://en.wikipedia.org/wiki/Recursion"  target="_blank">recursion</a></strong> &#8211; and have been getting together a bunch of sketches for a big personal project I’m working on <em>(more on that another time)</em>. Anyway, I inadvertently stumbled across quite a nice way of making things grow in a convincing manner, and whilst this script doesn’t actually use recursion ‘per se’, I thought it was kind of cool so I ran with it.<span id="more-360"></span></p>
<p>It also presented a good opportunity to try out another Flash Player 10 feature that I’ve been eager to try, which is using <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://labs.adobe.com/technologies/pixelbender/"  target="_blank"><strong>Pixel Bender</strong></a> and <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://livedocs.adobe.com/flex/3/langref/flash/display/ShaderJob.html"  target="_blank"><strong>ShaderJob</strong></a>. Although I’ve used Pixel Bender before, I’ve never used it in this way.</p>
<p>Basically, the idea is to exploit Pixel Bender’s performance and ask it to do some of the heavier number crunching for you &#8211; a concept that is currently being used by the Papervision3D team to give some juice to the next release. The other great thing about this approach is that these computations can run in another thread, leaving you more resources for other tasks (like rendering a fishing boat load of tentacles)</p>
<p>So, although this isn’t the best example of using Pixel Bender’s capabilities, it was a nice opportunity to exercise the idea. Each Tentacle starts a new ShaderJob and Pixel Bender whips up some tasty trigonometry for me, before passing it back inside a <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://livedocs.adobe.com/flex/3/langref/Vector.html"  target="_blank">Vector</a> object (typed Array). From there it’s just a question of making those numbers look nice&#8230; Kind of reminds me of the illustrative style used for the <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://oreilly.com/"  target="_blank">O&#8217;Reilly</a> book covers&#8230;</p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/perlin-noise-flow-field' rel='bookmark' title='Permanent Link: Perlin Noise Flow Field'>Perlin Noise Flow Field</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata' rel='bookmark' title='Permanent Link: 2D Cellular Automata'>2D Cellular Automata</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/laboratory/flash/pixel-bender-growing-tentacles/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Fit DisplayObject into Rectangle</title>
		<link>http://blog.soulwire.co.uk/code/actionscript-3/fit-a-displayobject-into-a-rectangle</link>
		<comments>http://blog.soulwire.co.uk/code/actionscript-3/fit-a-displayobject-into-a-rectangle#comments</comments>
		<pubDate>Mon, 25 May 2009 17:20:20 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=362</guid>
		<description><![CDATA[
We’ve all been there. You’re building an image gallery and you need to create consistently sized thumbnails from a set of images, of various sizes and orientations and with differing aspect ratios &#8211; or you need a fullscreen background which always fills the stage, regardless of a user’s screen resolution and browser window size &#8211; [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors' rel='bookmark' title='Permanent Link: Flipping you the Boid'>Flipping you the Boid</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2009/05/displayutils.swf" rel="lightbox;width=800;height=550" title="DisplayUtils Demonstration" ><img title="DisplayUtils" src="http://blog.soulwire.co.uk/wp-content/uploads/2009/05/displayutils.jpg" alt="DisplayUtils" /></a></p>
<p>We’ve all been there. You’re building an image gallery and you need to create consistently sized thumbnails from a set of images, of various sizes and orientations and with differing aspect ratios &#8211; or you need a fullscreen background which always fills the stage, regardless of a user’s screen resolution and browser window size &#8211; or maybe you just need to fit a DisplayObject into a rectangular area whilst maintaining the correct proportions of the original image.<span id="more-362"></span></p>
<h3>Introducing DisplayUtils</h3>
<p>Since this is a common task, one that I find myself coding over and over, I&#8217;ve whipped up a little class called <strong>DisplayUtils</strong> which will help with the scenarios mentioned above and more.</p>
<p>The main method in <em>DisplayUtils</em> is <strong>FitIntoRect</strong>. <em>FitIntoRect</em> can work in several ways. You can use it to resize a DisplayObject to fit inside a rectangle, or you can use it to generate a <em>transformation matrix</em>, which can be applied to an object or used with the <em>BitmapData.draw</em> method to create thumbnail previews, or both. There is also another method called <strong>createThumb</strong>, which uses <em>fitIntoRect</em> to quickly and easily create nicely cropped and scaled thumbnails from a source image with any aspect ratio.</p>
<p>Have a play with the demo above to see what you can do with these methods.</p>
<h3>Using DisplayUtils and fitIntoRect</h3>
<p>There are several parameters to control how fitIntoRect works. Here’s what you can pass to the method:</p>
<ul>
<li><strong>displayObject</strong> : The DisplayObject to resize</li>
<li><strong>rectangle</strong> : A Rectangle object representing the space the DisplayObject should fit into.</li>
<li><strong>fillRect</strong> : Whether the DisplayObject should be transformed to fill the entire  rectangle, or whether it should fit completely within it.</li>
<li><strong>align</strong> : The alignment of the DisplayObject within the rectangle, for example Top Left or Middle.</li>
<li><strong>applyTransform</strong> : Whether the calculated transformation matrix should be applied to the DisplayObject within the fitIntoRect method. If false, the DisplayObject will not be modified, but the Matrix returned by the fitIntoRect method can be used to transform objects or modify the draw command on a BitmapData object.</li>
</ul>
<p>The download includes all necessary classes as well as several examples of how to use the <strong>fitIntoRect</strong> method. Here are some code snippets for getting started with&#8230;</p>
<h3>Example Usage</h3>
<p><strong>Fit a DisplayObject into a Rectangle</strong></p>
<pre lang="actionscript">var area:Rectangle = new Rectangle( 0, 0, 200, 100 );
DisplayUtils.fitIntoRect( myDisplayObject, area, true, Alignment.MIDDLE );</pre>
<p><strong>Create a fullscreen background image</strong></p>
<pre lang="actionscript">stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;

function onStageResized( event:Event = null ):void
{
	var area:Rectangle = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight );
	DisplayUtils.fitIntoRect( myDisplayObject, area, true, Alignment.MIDDLE );
}

stage.addEventListener( Event.RESIZE, onStageResized );
onStageResized();</pre>
<p><strong>Create a thumbnail</strong></p>
<pre lang="actionscript">var thumb:Bitmap = DisplayUtils.createThumb( myBitmap.bitmapData, 100, 100, Alignment.MIDDLE, true );
addChild( thumb );</pre>
<h3 id="download">Download</h3>
<p>You can download the <strong>DisplayUtils</strong> class, as well as the <strong>Alignment</strong> class, which simply contains enumeration for the various alignment options when using <em>fitIntoRect</em> and <em>createThumb</em>.</p>
<p>A example of some of the uses discussed above is also available in the zip.</p>
<a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=displayutils.zip" class="download" title="DisplayUtils: Utilities for Creating Thumbnails & Resizing DisplayObjects"  rel="nofollow"><strong>Download:</strong> DisplayUtils</a>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors' rel='bookmark' title='Permanent Link: Flipping you the Boid'>Flipping you the Boid</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/code/actionscript-3/fit-a-displayobject-into-a-rectangle/feed</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>Flipping you the Boid</title>
		<link>http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors</link>
		<comments>http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors#comments</comments>
		<pubDate>Tue, 05 May 2009 15:12:45 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Autonomous]]></category>
		<category><![CDATA[Emergence]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=320</guid>
		<description><![CDATA[
I’ve uploaded the Boid source code. Sorry for the delay. I’ve also included some basic examples of how you can create nice behaviors using the Boid class. If you set Main.as as your document class then you’ll see that within that you can specify the demo to run when you compile.
The basic demos included are:

Chase [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/perlin-noise-flow-field' rel='bookmark' title='Permanent Link: Perlin Noise Flow Field'>Perlin Noise Flow Field</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/as3-drag-drop-shuffle-grid-menu' rel='bookmark' title='Permanent Link: AS3 Shuffle Grid Class'>AS3 Shuffle Grid Class</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2009/05/boids.swf" title="AS3 Steering Behaviors" rel="lightbox;width=800;height=760" ><img class="alignnone size-full wp-image-519" title="Boids AS3 Demo" src="http://blog.soulwire.co.uk/wp-content/uploads/2009/05/boids.jpg" alt="Boids AS3 Demo" width="710" height="326" /></a></p>
<p>I’ve uploaded the Boid source code. Sorry for the delay. I’ve also included some basic examples of how you can create nice behaviors using the Boid class. If you set <em>Main.as</em> as your document class then you’ll see that within that you can specify the demo to run when you compile.</p>
<p>The basic demos included are:</p>
<ul>
<li><strong>Chase</strong> &#8211; Boids chase each other</li>
<li><strong>Flock</strong> &#8211; Boids flock together with some wander</li>
<li><strong>Graphics</strong> &#8211; How to use custom graphics with a Boid instance</li>
<li><strong>Seek</strong> &#8211; Boids seek the mouse position</li>
<li><strong>Wander</strong> &#8211; You guessed it, they wander</li>
</ul>
<p>I’ve commented all of the methods and properties and there is also documentation (open <strong><em>index.html</em></strong> in the docs folder) to get you started. Before you mention it, yes, there is some redundant code ;) (such as the <em>constrainToRect</em> method which doesn&#8217;t really work) but I need to do some optimisations anyway so I just left it as is for now, rough and ready.</p>
<p><a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=boids.zip" class="download" title="AS3 Boid Class & Demos: AS3 Boid class for creating flocking behavior, with a variety of steering behaviors and examples of how to use the Boid class."  rel="nofollow"><strong>Download:</strong> AS3 Boid Class & Demos</a><span id="more-320"></span></p>
<p>It’s been a little while since I posted! I’m in the process of moving house and office, plus I’ve been repeatedly slammed at work. Apologies to those of you who’ve left comments and haven’t got much by way of reply. I’ll hopefully be visible again over the next few weeks.</p>
<p>I actually coded this experiment back in November, but only recently decided that enough was enough and hijacked an evening so I could tidy up the code and build a UI for the demo.</p>
<p>Since coming across Craig Reynold’s paper; “<a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.red3d.com/cwr/steer/gdc99/"  target="_blank">Steering Behaviors for Autonomous Characters</a>” whilst I was researching complexity theory for a university project (it wasn’t as academic as it sounds!), I’ve found myself becoming fascinated by flocking and swarm beahviors and the notion that you can create complex systems from relatively simple components. Much like the <a href="http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata" title="2D Cellular Automata"  target="_blank">Cellular Automata</a>, you can program an agent to have only a limited set of abilities and awareness, define a set rules for it to follow, and then create a multitude of instances of the agent to see what patterns begin to emerge through their interactions.</p>
<p><a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.red3d.com/cwr/boids/" title="Flocking"  target="_blank">Flocking</a> is a great example of this, as Reynolds demonstrated. His agents, or “<a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://en.wikipedia.org/wiki/Boids" title="Boids"  target="_blank">Boids</a>”, could perform certain maneuvers, such as <em>seeking</em> a target, <em>fleeing</em> from a predator, <em>avoiding obstacles</em> or <em>wandering</em> randomly. Combine these behaviors though, and allow each Boid to consider it’s neighbors when deciding on its locomotion, and complex behaviors begin to emerge.</p>
<p>The most infamous of these combinations is that of <em>separation</em>, <em>cohesion</em> and <em>alignment</em>, as it can produce a swarm behavior reminiscent of flocking birds or shoals of fish.</p>
<p><strong>Separation</strong> means that each Boid attempts to maintain a certain distance from its immediate neighbors, <strong>Cohesion</strong> ensures that each Boid attempts to stay close to the centre of the immediate flock and <strong>Alignment</strong> will calculate the average heading of the flock and steer towards this vector.</p>
<p>Each of these behaviors is fairly simple in isolation, but the results can give the impression that some significant AI is at work, when all that’s really going on is some simple vector math.</p>
<p><a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.flight404.com/blog/" title="Flight 404"  target="_blank">Robert Hodgin</a> has done some <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.flight404.com/blog/?p=99"  target="_blank">amazing work with flocking behaviors</a>, so too has <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.psyop.tv/o.php?id=51|0"  target="_blank">Psyop</a>, and of course <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.red3d.com/cwr/"  target="_blank">Reynolds</a> is the daddy of all this stuff. There are some good libraries out there too, such as <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://opensteer.sourceforge.net/"  target="_blank">OpenSteer</a>, and <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.bit-101.com/blog/"  target="_blank">Keith Peters</a> talks about this too in <em>Advanced Actionscript Animation</em>.</p>
<p>I’ve been trying to sharpen up my mathematical skills lately though, and was eager to play around with the new (new when I created this experiment anyway!) Flash Player 10 API &#8211; the 3D aspects in particular. So at the core of the Boid class are the native <em>Vector3D</em>, <em>Matrix3D</em> and <em>PerspectiveProjection</em> classes. Ok, so we’ve all got our own Vector3D and Matrix3D class in our library, but I thought it’d be good to use Adobe’s, especially seeing you can then apply the Matrix3D <em>directly to a DisplayObject’s transform property</em>.</p>
<p>Another cool feature I came across was the <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://livedocs.adobe.com/flex/3/langref/flash/geom/Matrix3D.html#pointAt()"  target="_blank">Matrix3D.pointAt()</a> method, which will rotate a Matrix around a given axis and in this case can be used to orientate the Boid to it’s heading vector… Nice!</p>
<p>I’ve had a lot of fun putting together the Boid demo anyway &#8211; tweaking various settings on the individual Boids as well as the group behaviors (my personal favorite is ‘<em>Chase</em>’ mode with ‘<em>Number of Boids</em>’ cranked right up!).</p>
<p>If you have a play with the settings though, you’ll quickly see what I mean about the plethora of different effects that can be accomplished, even by simply adjusting the locomotive abilities of the Boids.</p>
<p>Due to said lack of free time as of late, I haven’t documented the code fully, though I have started and so if anyone is interested in the source code <em>then please say so</em> in the comments and I’ll try and finish the job (after a mere 6 months!) and put it up for download.</p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/perlin-noise-flow-field' rel='bookmark' title='Permanent Link: Perlin Noise Flow Field'>Perlin Noise Flow Field</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/as3-drag-drop-shuffle-grid-menu' rel='bookmark' title='Permanent Link: AS3 Shuffle Grid Class'>AS3 Shuffle Grid Class</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors/feed</wfw:commentRss>
		<slash:comments>47</slash:comments>
		</item>
		<item>
		<title>More Music Visualisations</title>
		<link>http://blog.soulwire.co.uk/art-design/portfolio/more-bandcamp-music-visualisations</link>
		<comments>http://blog.soulwire.co.uk/art-design/portfolio/more-bandcamp-music-visualisations#comments</comments>
		<pubDate>Tue, 17 Mar 2009 14:07:44 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Animation]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Generative]]></category>
		<category><![CDATA[Illustration]]></category>
		<category><![CDATA[Portfolio]]></category>
		<category><![CDATA[Transmissions]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Audio]]></category>
		<category><![CDATA[Visualisation]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=322</guid>
		<description><![CDATA[
Just a quick (and slightly belated) announcement.
The distinguished Bandcamp has recently been regaled with another round of audio-visual snacks. I&#8217;ve had a lot of fun working on them, and there will be even more in the not too distant future.
The whole Bandcamp site in fact is bursting with more and more tasty new features which [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/art-design/portfolio/bandcamp-music-visualisations' rel='bookmark' title='Permanent Link: Bandcamp Music Visualisations'>Bandcamp Music Visualisations</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/actionscript3-dynamic-sound-visualisation' rel='bookmark' title='Permanent Link: AS3 Music Visualisation'>AS3 Music Visualisation</a></li>
<li><a href='http://blog.soulwire.co.uk/art-design/portfolio/disabed-algebra' rel='bookmark' title='Permanent Link: Disabed Algebra'>Disabed Algebra</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-525" title="Bandcamp Music Visualisations" src="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/bandcamp.jpg" alt="Bandcamp Music Visualisations" width="710" height="352" /></p>
<p><strong>Just a quick</strong> (and slightly belated) <strong>announcement</strong>.</p>
<p>The distinguished <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://bandcamp.com/" title="Bandcamp"  target="_blank">Bandcamp</a> has recently been regaled with another round of audio-visual snacks. I&#8217;ve had a lot of fun working on them, and there will be even more in the not too distant future.</p>
<p>The whole Bandcamp site in fact is bursting with more and more <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://bandcamp.com/features"  target="_blank">tasty new features</a> which you should check out. In terms of my little contribution on the music visualistions front, there are currently four new full fat flavors to feast on…<span id="more-322"></span></p>
<p><strong>Ribbons</strong> » which uses my <a href="http://blog.soulwire.co.uk/code/actionscript-3/papervision3d-ribbons" title="Papervision3D Ribbon Class" >Papervision3D Ribbons Class</a> and is designed for crunching riffs and hard beats.</p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/ribbons-big.jpg" rel="lightbox[bandcamp]" ><img class="alignnone size-medium wp-image-528" title="Ribbons Visualisation" src="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/ribbons-big-710x177.jpg" alt="Ribbons Visualisation" width="710" height="177" /></a></p>
<p><strong>Strata</strong> » which was inspired by stream-graphs and rock formations, and flows like a charred pizza in a log-flume along an imaginary Teflon oven dish.</p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/strata-big.jpg" rel="lightbox[bandcamp]" ><img class="alignnone size-medium wp-image-529" title="Strata Visualisation" src="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/strata-big-710x177.jpg" alt="Strata Visualisation" width="710" height="177" /></a></p>
<p><strong>Plughole</strong> » which comprises of disembodied appendages and iconography encapsulating the zeitgeist of generation stupid &#8211; mashes the aforementioned archetypes up into crumbs before offering them to the esophagus of oblivion.</p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/plughole-big.jpg" rel="lightbox[bandcamp]" ><img class="alignnone size-medium wp-image-527" title="Plughole Visualisation" src="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/plughole-big-710x177.jpg" alt="Plughole Visualisation" width="710" height="177" /></a></p>
<p><strong>Hypno</strong> » which was designed to bring about universal harmony and spiritual equilibrium but accidentally caused the credit crunch.</p>
<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/hypno-big.jpg" rel="lightbox[bandcamp]" ><img class="alignnone size-medium wp-image-526" title="Hypno Visualisation" src="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/hypno-big-710x177.jpg" alt="Hypno Visualisation" width="710" height="177" /></a></p>
<p>You can see them in action by visiting an <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://bandcamp.com/artists" title="Artists on Bandcamp"  target="_blank">artist&#8217;s</a> page (such as <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://hotbitcharsenal.bandcamp.com/" title="Hot Bitch Arsenal on Bandcamp"  target="_blank">Hot Bitch Arsenal</a> or <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://patttten.bandcamp.com/" title="Patterns on Bandcamp"  target="_blank">Pattern</a>), hitting play and selecting a visualisation from the pop-out menu underneath the cover art.</p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/art-design/portfolio/bandcamp-music-visualisations' rel='bookmark' title='Permanent Link: Bandcamp Music Visualisations'>Bandcamp Music Visualisations</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/actionscript3-dynamic-sound-visualisation' rel='bookmark' title='Permanent Link: AS3 Music Visualisation'>AS3 Music Visualisation</a></li>
<li><a href='http://blog.soulwire.co.uk/art-design/portfolio/disabed-algebra' rel='bookmark' title='Permanent Link: Disabed Algebra'>Disabed Algebra</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/art-design/portfolio/more-bandcamp-music-visualisations/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>AS3 Shuffle Grid Class</title>
		<link>http://blog.soulwire.co.uk/code/open-source/as3-drag-drop-shuffle-grid-menu</link>
		<comments>http://blog.soulwire.co.uk/code/open-source/as3-drag-drop-shuffle-grid-menu#comments</comments>
		<pubDate>Wed, 04 Mar 2009 00:50:47 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Interactive]]></category>
		<category><![CDATA[Interface]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=311</guid>
		<description><![CDATA[
Drag &#38; Drop the images to shuffle them around&#8230;
A friend of mine, Dale Sattler over at No Ponies recently posted a grid sorting class. He said it was based on my old dynamic stacking menu; but that was pure modesty as his script is based on a 2D grid and much more sophisticated.
Anyway &#8211; it [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata' rel='bookmark' title='Permanent Link: 2D Cellular Automata'>2D Cellular Automata</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/shuffle-grid.swf" title="Drag the images to shuffle grid" rel="lightbox;width=800;height=500" ><img class="alignnone size-full wp-image-534" title="Shuffle Grid Demo" src="http://blog.soulwire.co.uk/wp-content/uploads/2009/03/shuffle-grid.jpg" alt="Shuffle Grid Demo" width="710" height="325" /></a></p>
<p><strong><em>Drag &amp; Drop</em></strong><em> the images to shuffle them around&#8230;</em><span id="more-311"></span></p>
<p>A friend of mine, <strong>Dale Sattler</strong> over at <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.blog.noponies.com/"  target="_blank">No Ponies</a> recently posted a <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.blog.noponies.com/archives/246"  target="_blank">grid sorting class</a>. He said it was based on my old <a href="http://blog.soulwire.co.uk/code/open-source/dynamic-stacking" title="Dynamic Stacking Menu" >dynamic stacking menu</a>; but that was pure modesty as his script is based on a 2D grid and much more sophisticated.</p>
<p>Anyway &#8211; it inspired me to create a <strong>grid sorting / shuffling algorithm</strong> of my own. It behaves differently to Dales but I think it works pretty well.</p>
<p>The basic logic of the algorithm works by determining how far a dragged item travels along the grid (rows and columns) and then shuffling the surrounding items in the opposite direction by these values, therefore creating space for the dragged item to slot into when released.</p>
<p>It currently only works for grids which are fully populated, but adding more flexibility for incomplete grids will only be a matter of adding a few conditions &#8211; functionality which I’ll add when I get a moment.</p>
<p>You can extend the <strong>ShuffleGridItem</strong> class to add the functionality you need. In the demo I’ve made a simple image class which grabs a photo from <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.flickr.com/"  target="_blank">Flickr</a>.</p>
<p>Creating a <strong>ShuffleGrid</strong> is very simple, and can be done like so:</p>
<pre lang="actionscript">var grid:ShuffleGrid = new ShuffleGrid(4,7,40,40,1);

for (var i : int = 0; i &lt; grid.numCells; i++)
{
	grid.addItem (new ShuffleGridItem());
}

addChild (grid);</pre>
<p>The constructor takes the following arguments:</p>
<pre lang="actionscript">new ShuffleGrid(rows, cols, cellWidth, cellHeight, spacing);</pre>
<p>Feel free to download the class and a simple demo and have a play around. I can imagine many uses for it, so hopefully it will come in handy.</p>
<a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=shuffle-grid-demo.zip" class="download" title="Shuffle Grid Class & Demo: The source code and example implementation of a grid interface with drag & drop functionality and an intelligent shuffling algorithm."  rel="nofollow"><strong>Download:</strong> Shuffle Grid Class & Demo</a>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata' rel='bookmark' title='Permanent Link: 2D Cellular Automata'>2D Cellular Automata</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/code/open-source/as3-drag-drop-shuffle-grid-menu/feed</wfw:commentRss>
		<slash:comments>47</slash:comments>
		</item>
		<item>
		<title>Double Sided 3D Plane in FP10</title>
		<link>http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10</link>
		<comments>http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10#comments</comments>
		<pubDate>Tue, 30 Dec 2008 14:15:10 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Flash Player 10]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=273</guid>
		<description><![CDATA[Easily create two sided 3D DisplayObjects and flip card effects using Flash Player 10 and the new 3D API


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/fit-a-displayobject-into-a-rectangle' rel='bookmark' title='Permanent Link: Fit DisplayObject into Rectangle'>Fit DisplayObject into Rectangle</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors' rel='bookmark' title='Permanent Link: Flipping you the Boid'>Flipping you the Boid</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2008/12/papersprite.swf" rel="lightbox;width=800;height=550;" title="Double Sided DisplayObject in Flash Player 10" ><img title="PaperSprite Demo" src="http://blog.soulwire.co.uk/wp-content/uploads/2008/12/papersprite-710x352.jpg" alt="PaperSprite Demo" width="710" height="352" /></a></p>
<p>I’ve made a couple of small improvements to the PaperSprite class:</p>
<ol>
<li>The visible face of the plane is updated automatically only when required. This saves on processing load and also means you can just set up the PaperSprite and not have to worry about anything else, just tween the crap out of all its properties and it won’t mind one bit. (Thanks to Jesse for the pointers re. using stage.invalidate for this process)</li>
<li>The back face is now automatically flipped horizontally, so text and graphics are no longer mirrored and will display correctly</li>
<li>I’ve changed the logic which sets the dynamic registration point for the pivot. This should now correctly line up the front and back faces of the 3D plane, regardless of where their individual registration points are.</li>
</ol>
<p>Also, some people have asked how to use it, so here is a really quick example to get you up and running with PaperSprite if you are not familiar with using classes and are using the Flash IDE to compile your movie:</p>
<ol>
<li>First, <a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=papersprite.zip" title="Download the PaperSprite class for creating two sided planes using FP10" >download the PaperSprite class</a> and put the <strong>soulwire </strong>folder in the same directory as your FLA or source code.</li>
<li>Then paste this code into the main timeline of your FLA:</li>
</ol>
<p><span id="more-273"></span></p>
<pre lang="actionscript">// Import the PaperSprite class

import soulwire.display.PaperSprite;

/*
Create a new PaperSprite:

If your front and back faces already exist, you can pass them straight
into the constructor, like so:

myPaperSprite = new PaperSprite( myFrontMc, myBackMc );
*/

var myPaperSprite:PaperSprite = new PaperSprite();

/*
Optionally specify a pivot point, in this example the centre is used
(this is also the default so there is no need to set this normally).

To pivot around the top left use:
myPaperSprite.pivot = new Point(0,0);

or for bottom right:
myPaperSprite.pivot = new Point(1,1);

and so on...
*/

myPaperSprite.pivot = new Point(0.5,0.5);

// Centre it on the stage

myPaperSprite.x = stage.stageWidth / 2;
myPaperSprite.y = stage.stageHeight / 2;

/*
Set the front and back faces:

These can be any type of DisplayObject, for example, to use a MovieClip
from your library use:

myPaperSprite.front = new MyLibraryClip();
*/

myPaperSprite.front = createSprite(0x66FF00);
myPaperSprite.back = createSprite(0xFF3399);

// Add the PaperSprite to the display list

addChild ( myPaperSprite );

// This method just creates coloured boxes for the demo

function createSprite (colour:uint):Sprite
{
	var mySprite:Sprite = new Sprite();
	mySprite.graphics.beginFill ( colour );
	mySprite.graphics.drawRect (0,0,100,100);
	mySprite.graphics.endFill ();
	return mySprite;
}

// Listen for the enterFrame event

addEventListener ( Event.ENTER_FRAME, spin );

/*
Move and rotate your PaperSprite in any way you want - it will
update it's visible face automatically!
*/

function spin ( event:Event ):void
{
	var mX:Number = ((mouseX / stage.stageWidth) - 0.5) * 360;
	var mY:Number = ((mouseY / stage.stageHeight) - 0.5) * 360;

	myPaperSprite.rotationY += (mX - myPaperSprite.rotationY) / 40;
	myPaperSprite.rotationX += (mY - myPaperSprite.rotationX) / 40;
}</pre>
<p>Publish the movie and you’re all done!</p>
<h2>Background</h2>
<p>Flash Player 10’s new 3D capabilities are a much welcomed and exiting addition, and although their implementation at first seemed a little obtuse after using libraries such as Papervision3D, Adobe’s implementation is beginning to make a lot more sense to me. Rather than being handed a complete 3D library, developer’s have been given the necessary building blocks to use 3D, or 2.5D with less ‘hacks’ and arguably better performance where it matters.</p>
<p>Time will tell, but I personally think this will be a positive development for existing frameworks like Papervision and Sandy, because whilst Flash can now natively handle certain tasks like triangle drawing, 3D matrices etc &#8211; implementing cameras and shaders, loading and building meshes and so on is something which developers will still require. If this can plug neatly into Flash Player’s capabilities and possibly yield increased performance then all the better.</p>
<p>In more basic situations though, the ability to rotate a DisplayObject around its X, Y and Z axis, as well as finally having a Z property, is useful for adding basic 3D effects, even if your project doesn’t require anything more sophisticated than that.</p>
<p>But this is where some gaps begin to arise. Z sorting, for example, will be required, and <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.unitzeroone.com/" >Ralph Hauwert</a> (a member of the Papervision3D team) has already written a <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://theflashblog.com/?p=470" >useful script</a> for this.</p>
<h2>Two Sided DisplayObjects</h2>
<p>Another common use for Flash Player 10’s 3D capabilities is to create <strong>double sided sprites</strong> or planes, than can be rotated to reveal alternate content on either side. Again, I would have expected this to be a new property of DisplayObjectContainer, so that <strong><em>front </em></strong>and <strong><em>back </em></strong>could be passed to it as DisplayObjects. This isn’t the case though, so it requires some minimal work around.</p>
<p><a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://theflashblog.com/" >Lee Brimelow</a> demonstrated <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.gotoandlearn.com/play?id=91"  target="_blank">one approach</a> to this, which was to monitor the rotation of a DisplayObject, and swap the visible faces accordingly (<a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://flashartofwar.com/2008/11/16/two-sided-plane-fp-10/"  target="_blank">Jesse Freeman</a> also used this technique). This works great in many cases, however it doesn’t give the desired results when the parent DisplayObject is off centre and therefore subject to the perspective of the 3D environment. It also means that if you are rotating the DisplayObject around multiple axis then the calculations required get slightly more complex.</p>
<h2>The Solution</h2>
<p>As ever, the wise and prolific <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.senocular.com/" >Senocular</a> came to the rescue. He described a technique whereby 3 points are placed on the surface of the DisplayObject, and by determining the winding direction of these points when translated from 3D to 2D space; one is able to determine which way the DisplayObject is facing. Because this is relative to the perspective used to produce this transformation, the result is true to the point of view of the user.</p>
<p>Senocular published his helper class which will return a Boolean value indicating whether a given DisplayObject is front facing or not, and so I wish to stress that all credit is his for <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.senocular.com/?id=2.57"  target="_blank">his solution</a> and wonderfully clear <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.kirupa.com/forum/showthread.php?t=315821"  target="_blank">explanation of the process</a>.</p>
<p>I did feel that it might be beneficial though to wrap this up, along with other functionality, into a class which solved the double sided DisplayObject issue, and so I introduce the <strong>PaperSprite </strong>class (I chose to call it <em>PaperSprite </em>so that it isn’t confused with <em>Sprite3D</em> if you use another 3D library).</p>
<h2>How to use PaperSprite</h2>
<p>Creating a two sided Plane using PaperSprite is simple:</p>
<pre lang="actionscript">import soulwire.display.PaperSprite;

var mySprite:PaperSprite = new PaperSprite();

// Any type of DisplayObject can be used for each face
mySprite.front = new Sprite();
mySprite.back = new Bitmap( myImage );</pre>
<p>So you can use any DisplayObject for the front and reverse sides; MovieClips, Sprites, Bitmaps, Shapes, Loaders etc. <strong>These can also be set via the constructor</strong>&#8230;</p>
<p><del datetime="2009-01-02T12:53:05+00:00">Another property of PaperSprite is <strong>whether is updates it’s display automatically</strong>. If <em>true</em>, once the PaperSprite is added to the stage it will update its visible face autonomously, however if you have a more general render loop where you’re controlling your 3D scene from, you can set this to <em>false </em>and then call the <strong>update </strong>method when calculating the visible face is required:</del></p>
<blockquote><p>Thanks to <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://flashartofwar.com/"  target="_blank">Jesse Freeman</a> for suggesting a method to limit unnecessary calls to the <em>update </em>method. By overriding the setters for the position and rotation properties and using <strong>stage.invalidate()</strong>, then listening for the render event (Event.RENDER), the calculations needed to determine the visible face of the PaperSprite need only be made if one or more properties have been changed and if the PaperSprite needs to be rendered. Therefore there is no longer a need for autoUpdate, everything is handled internally by the PaperSprite class. Cheers Jesse! :)</p></blockquote>
<p>&#8230;The other useful feature is the <strong>pivot </strong>property. By default, a PaperSprite will pivot (rotate around) its <strong>centre point</strong>, which will be automatically calculated for each face depending on its respective dimensions. Alternatively, if you want the PaperSprite to rotate around the <em>top left</em> corner, <em>bottom right</em>, or indeed any point on its surface, you can set the pivot property, which is a Point object and requires 2 normalised values, representing the fraction of the width and height of the PaperSprite at which you want to place the pivot.</p>
<p>So to set the PaperSprite to rotate around its centre (this is set by default) you can use:</p>
<pre lang="actionscript">mySprite.pivot = new Point( 0.5, 0.5 );</pre>
<p>And its Top Left corner:</p>
<pre lang="actionscript">mySprite.pivot = new Point( 0.0, 0.0 );</pre>
<p>And its top centre:</p>
<pre lang="actionscript">mySprite.pivot = new Point( 0.5, 0.0 );</pre>
<p>And so on!</p>
<p>You can also access its <strong>isFrontFacing </strong>property at any time:</p>
<pre lang="actionscript">if ( mySprite.isFrontFacing )
{
	doSomethingGood();
}</pre>
<p>An finally, removing the front or back face from its display list (or indeed not defining one at all) will cause the PaperSprite to <em>display the available face at all times</em>, essentially giving it the default behaviour of a one sided Sprite.</p>
<h2>Download the PaperSprite class</h2>
<p>Again, this is really just a glorified augmentation of Senocular’s solution to finding the front facing side of a DisplayObject in 3D. All credit should go to him for creating such an elegant solution. I built this class in order to simplify its use and provide the extra functionality needed to quickly start working with a two-sided DisplayObject.</p>
<a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=papersprite.zip" class="download" title="PaperSprite Class & Demo: The PaperSprite class is a double sided DisplayObject, allowing for custom front and reverse side DisplayObjects which will appear as a 3D card when rotated in 3D space."  rel="nofollow"><strong>Download:</strong> PaperSprite Class & Demo</a>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/fit-a-displayobject-into-a-rectangle' rel='bookmark' title='Permanent Link: Fit DisplayObject into Rectangle'>Fit DisplayObject into Rectangle</a></li>
<li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors' rel='bookmark' title='Permanent Link: Flipping you the Boid'>Flipping you the Boid</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10/feed</wfw:commentRss>
		<slash:comments>83</slash:comments>
		</item>
		<item>
		<title>Perlin Noise Flow Field</title>
		<link>http://blog.soulwire.co.uk/laboratory/flash/perlin-noise-flow-field</link>
		<comments>http://blog.soulwire.co.uk/laboratory/flash/perlin-noise-flow-field#comments</comments>
		<pubDate>Sun, 14 Dec 2008 23:11:59 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Autonomous]]></category>
		<category><![CDATA[Emergence]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=263</guid>
		<description><![CDATA[
It was a rainy Sunday and I found myself playing around with perlin noise for a couple of hours.
The idea was to create a simple flow field using the BitmapData perlinNoise method, and use this to influence the movement of autonomous agents. There is no complex vector math or steering behaviours, just some simple logic [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors' rel='bookmark' title='Permanent Link: Flipping you the Boid'>Flipping you the Boid</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2008/12/flow-field.swf" rel="lightbox:width=780;height=450;" title="Perlin Noise Flow Field" ><img src="http://blog.soulwire.co.uk/wp-content/uploads/2008/12/flow-field-710x352.jpg" alt="Flow Field with Perlin Noise" title="Flow Field with Perlin Noise" width="710" height="352" class="alignnone size-medium wp-image-563" /></a></p>
<p>It was a rainy Sunday and I found myself playing around with <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://en.wikipedia.org/wiki/Perlin_noise"  target="_blank">perlin noise</a> for a couple of hours.</p>
<p>The idea was to create a simple flow field using the BitmapData perlinNoise method, and use this to influence the movement of autonomous agents. There is no complex vector math or steering behaviours, just some simple logic for how a particle or agent reacts to the current pixel it is positioned over.<span id="more-263"></span></p>
<p>Despite its simplicity, by changing parameters such as the level of offset per frame or the x and y frequency, it is possible to create some interesting effects which resemble the movement of flocking birds, shoals of fish or indeed more fittingly for this time of year; panicking Christmas shoppers desperately hunting for gifts.</p>
<p>At each update step, an agent will grab the value of the pixel it is on top of and alter its trajectory based on the brightness of the pixel. Throw in some variance relating to how strongly an individual agent will react to this value and some interesting patterns begin to emerge.</p>
<p>The basic logic I’m using in this demo is as follows:</p>
<pre lang="actionscript">// Get the pixel the agent is over
var pixel:uint = noiseBitmap.getPixel( agent.x, agent.y );

// Find the brightness of the pixel
var brightness:Number = pixel / 0xFFFFFF;

// Set the angle and the speed according to brightness
var speed:Number = brightness * agent.speed;
var angle:Number = brightness * 360 * Math.PI / 180;

// Update the agent's position / rotation
agent.x += Math.cos( angle ) * speed;
agent.y += Math.sin( angle ) * speed;
agent.rotation = brightness * 360;</pre>
<p>Feel free to download the source code and start tweaking the many variables. Adding further life to the agents by introducing collision or allowing additional individual traits beyond simply speed and wander might be one option worth exploring.</p>
<a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=perlin-flow-field.zip" class="download" title="Perlin Noise Flow Field: An example of how to use the Perlin noise algorithm to simulate flocking behaviors."  rel="nofollow"><strong>Download:</strong> Perlin Noise Flow Field</a>
<p>Have fun!&#8230;</p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors' rel='bookmark' title='Permanent Link: Flipping you the Boid'>Flipping you the Boid</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/two-sided-planes-in-flash-player-10' rel='bookmark' title='Permanent Link: Double Sided 3D Plane in FP10'>Double Sided 3D Plane in FP10</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/laboratory/flash/perlin-noise-flow-field/feed</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>BitmapData Colour Palette</title>
		<link>http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette</link>
		<comments>http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette#comments</comments>
		<pubDate>Sat, 11 Oct 2008 19:52:35 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Colour]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=195</guid>
		<description><![CDATA[
My previous post explained and provided a very simple method for extracting colours from a BitmapData image, by averaging the colours in specific areas. This can have several applications, for example it features in a large amount of prototypes for the update to my Motion Tracking engine. However, if you want to create an accurate and [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata' rel='bookmark' title='Permanent Link: BitmapData Average Colours'>BitmapData Average Colours</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/fit-a-displayobject-into-a-rectangle' rel='bookmark' title='Permanent Link: Fit DisplayObject into Rectangle'>Fit DisplayObject into Rectangle</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2008/10/colour-palette.swf" title="Extracting the Colour Palette from an Image" rel="lightbox;width=800;height=450;" ><img class="alignnone size-medium wp-image-582" title="Bitmapdata Colour Palette" src="http://blog.soulwire.co.uk/wp-content/uploads/2008/10/bitmapdata-colour-palette-710x399.jpg" alt="Bitmapdata Colour Palette" width="710" height="399" /></a></p>
<p>My <a href="http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata" title="BitmapData average colour" >previous post</a> explained and provided a very simple method for <a href="http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata" title="Extracting the average colour from a BitmapData image" >extracting colours from a BitmapData image</a>, by averaging the colours in specific areas. This can have several applications, for example it features in a large amount of prototypes for the update to my <a href="http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking" title="AS3 Webcam Motion Tracking engine" >Motion Tracking engine</a>. However, if you want to create an accurate and representative colour palette from an image it has several flaws, the most obvious being that by averaging colours, you are actually removing or diluting the striking but perhaps less frequent colours in the image – the very colours which often make an image’s colour palette so exiting!</p>
<p>So, if we’re to extract an exciting and more representative palette from an image, we need a more intelligent algorithm; one which takes into account what makes a colour palette interesting – the contrasts and juxtapositions of colours within the image.<span id="more-195"></span></p>
<p>After some experimentation I arrived at the following solution. <a href="#getcode">I have posted the code bellow</a>, but I think it’s important to understand how it works and why each step is taken, so without further ado, here be my approach to calculating the colour palette of a BitmapData image&#8230;</p>
<h2>Reducing the colours</h2>
<p>We’re going to be performing quite a few operations on the colours in our input image, so for the sake of performance it’s wise to reduce the colours in the image as much as possible without losing the overall look and feel of the palette.</p>
<p><a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://en.nicoptere.net/" title="Nicolas Barradeau's blog"  target="_blank">Nicolas Barradeau</a> has done some really cool things with this, and his <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://en.nicoptere.net/?p=8" title="Colour Depth Change"  target="_blank">Color Depth Change</a> script is really worth checking out. We can actually enhance this technique slightly by omitting the two loops which cycle through every pixel in the image and use <strong>paletteMap</strong>. The result is good enough for our needs and substantially quicker. I’m also glad I could use the BitmapData paletteMap method, because up until now I hadn’t ever had a use for it :)</p>
<p>I’ve found that reducing the image’s colour palette to 64 colours works well performance wise and still looks great, but you might want to use anything up to 256.</p>
<p>I won’t go into how paletteMap works, and <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://livedocs.adobe.com/flex/201/langref/flash/display/BitmapData.html#paletteMap()"  target="_blank">the docs</a> aren’t very helpful on this matter so I suggest you check out Google if you want a bit more information. In short, we create a new index of colours for the image by creating three arrays, one for each channel (red, green and blue) and pass these values to the paletteMap method, which takes care of the rest at blisteringly fast speeds. What we are left with is a dithered version of our original image, allowing us to analyse it’s pixels in a much speedier manner.</p>
<pre lang="actionscript">public static function reduceColours( source:BitmapData, colours:int = 16 ):void
{
	var Ra:Array = new Array(256);
	var Ga:Array = new Array(256);
	var Ba:Array = new Array(256);

	var n:Number = 256 / ( colours / 3 );

	for (var i:int = 0; i < 256; i++)
	{
		Ba[i] = Math.floor(i / n) * n;
		Ga[i] = Ba[i] << 8;
		Ra[i] = Ga[i] << 8;
	}

	source.paletteMap( source, source.rect, new Point(), Ra, Ga, Ba );
}</pre>
<p>Note: at this stage, if you’re working with a very large image, it’s advisable to draw the image to a smaller BitmapData using a scaled Matrix, as we will be looping over its pixels and so a 2000 x 2000 image is likely to make your CPU rather pissed off at you!</p>
<h2>Indexing the colours</h2>
<p>The next step is to build an index of the colours in the image. By index, I mean that we want a list of unique colours and a tally for each telling us how many times they occur in the image. We can do this by using an Object or a Dictionary, which uses the colour values as a key and a counter as the value.</p>
<pre lang="actionscript">public static function indexColours( source:BitmapData, sort:Boolean = true ):Array
{

	var n:Object = {};
	var a:Array = [];
	var p:int;

	for (var x:int = 0; x < source.width; x++)
	{
		for (var y:int = 0; y < source.height; y++)
		{
			p = source.getPixel(x, y);
			n[p] ? n[p]++ : n[p] = 1;
		}
	}

	for (var c:String in n)
	{
		a.push ( { colour:c, count:n[c] } );
	}

	function byCount( a:Object, b:Object ):int
	{
		if ( a.count > b.count ) return 1;
		if ( a.count < b.count ) return -1;
		return 0;
	}

	return a.sort( byCount, Array.DESCENDING );
}</pre>
<p>We are left with an Object containing all the colours in the image, grouped by their colour value and with a reference to how frequently they appear. We can then use a <em>for in</em> loop to create an array from the Objects properties.</p>
<p>Finally, we need to sort the resulting Array, essentially by popularity, so that the colours which appear most frequently within the image are at the start of the Array. We can do this using the Array’s sort method, and passing a custom function which compares each colour’s count or frequency to that of the other colours. Now we can discard the count value, and what we are left with is a correctly ordered array of unsigned integers representing our entire spectrum of colours.</p>
<h2>Finding unique, contrasting colours</h2>
<p>At this point, we could simply take the first values from the array and call this our palette, after all if we wanted, say, a 16 colour palette then we know that the first 16 colours in our Array are the most frequently occurring colours in our source image. The problem with this is that, as with most things in life, just because something is popular doesn’t necessarily make it good! Take a landscape photograph for example; there may be a beautiful collection of flowers with striking colours in the foreground, and a burning orange and pink sunset descending over the horizon, yet the first group of colours in our Array will likely be a host of different shades of green from the hills and fields – not exactly what we were hoping for!</p>
<p>So we need an algorithm which can discern between colours and tell us which of our colours have a sufficient variance, therefore producing a palette which fairly represents the broader spectrum of colours in our image.</p>
<p>The best solution that I found was to add up the square of the red, green and blue components of two colours and compare their results. If they are sufficiently different (as determined by a variable tolerance) then we have a match.</p>
<pre lang="actionscript">public static function similar( colour1:uint, colour2:uint, tolerance:Number = 0.01 ):Boolean
{
	var RGB1:Object = Hex24ToRGB( colour1 );
	var RGB2:Object = Hex24ToRGB( colour2 );

	tolerance = tolerance * ( 255 * 255 * 3 ) << 0;

	var distance:Number = 0;

	distance += Math.pow( RGB1.red - RGB2.red, 2 );
	distance += Math.pow( RGB1.green - RGB2.green, 2 );
	distance += Math.pow( RGB1.blue - RGB2.blue, 2 );

	return distance <= tolerance;
}</pre>
<p>To apply this idea, we need to create an empty Array which will eventually become our results. We then begin to loop through our colours, taking the first and comparing it to subsequent colours until we find one which is sufficiently different. We then push this colour into our results Array, and then continue searching, this time comparing each colour in our initial Array to each colour in our growing Array of unique colours. Once we have reached our predefined quota of colours, or the end of the Array, we have our beautiful colour palette!</p>
<pre lang="actionscript">public static function different( colour:uint, colours:Array, tolerance:Number = 0.01 ):Boolean
{
	for (var i:int = 0; i < colours.length; i++)
	{
		if ( similar( colour, colours[i], tolerance ) )
		{
			return false;
		}
	}
	return true;
}

public static function uniqueColours( colours:Array, maximum:int, tolerance:Number = 0.01 ):Array
{
	var unique:Array = [];

	for (var i:int = 0; i < colours.length &#038;&#038; unique.length < maximum; i++)
	{
		if ( different( colours[i], unique, tolerance ) )
		{
			unique.push( colours[i] );
		}
	}

	return unique;
}</pre>
<h2 name="getcode" id="getcode">Putting it all together</h2>
<p>I’ve packaged the above technique, as well as the <strong>averageColour </strong>and <strong>averageColours </strong>methods from my last post into a <strong>ColourUtils</strong> class. Most of the methods detailed above, despite being necessary steps in finding an image’s colour palette, are useful in their own right and so I have separated them out into a documented collection of static methods.</p>
<p>You can download the <strong>ColourUtils </strong>class and also some examples of how to use it:</p>
<a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=ColourUtils.zip" class="download" title="ColourUtils: A useful class for extracting colour palettes from images and BitmapData objects based on an interestingness algorithm, ensuring contrasting colours are selected."  rel="nofollow"><strong>Download:</strong> ColourUtils</a> <a href="http://blog.soulwire.co.uk/wp-content/plugins/download-monitor/download.php?id=ColourUtils-Demo.zip" class="download" title="ColourUtils Demo: An example of how to use the ColourUtils class to extract a colour palette from an image or BitmapData."  rel="nofollow"><strong>Download:</strong> ColourUtils Demo</a>
<h2>Possible Enhancements</h2>
<p>I have a few ideas for possible enhancements to the algorithm, and <strong>would like to hear yours</strong> if you have any. Currently, these are my intentions for the next revision:</p>
<ul>
<li>Integration of the <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.colourlovers.com/blog/2007/09/02/the-muller-formula-or-predictable-color-preferences/" >Müller formula</a> so that a single colour from a group of similar colours is chosen not by its frequency but by its suitability for the extracted palette – i.e. a colour with greater tonal variation is preferred by the algorithm much the same way as it would be by the eye.</li>
<li>Palette colour sorting by hue, saturation or brightness.</li>
<li>A faster way of discarding unwanted colours, preferably before looping through the colour index, resulting in much better performance.</li>
</ul>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata' rel='bookmark' title='Permanent Link: BitmapData Average Colours'>BitmapData Average Colours</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/fit-a-displayobject-into-a-rectangle' rel='bookmark' title='Permanent Link: Fit DisplayObject into Rectangle'>Fit DisplayObject into Rectangle</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette/feed</wfw:commentRss>
		<slash:comments>46</slash:comments>
		</item>
		<item>
		<title>BitmapData Average Colours</title>
		<link>http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata</link>
		<comments>http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata#comments</comments>
		<pubDate>Fri, 10 Oct 2008 18:21:46 +0000</pubDate>
		<dc:creator>Soulwire</dc:creator>
				<category><![CDATA[Actionscript 3.0]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Colour]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://blog.soulwire.co.uk/?p=165</guid>
		<description><![CDATA[
If you want a very simple way of extracting a colour palette from an image, one technique would be to average the colour values within specific areas. Averaging colour values is almost identical to averaging numbers, except with the added initial step of finding the red, green and blue components of the colour. To do [...]


Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette' rel='bookmark' title='Permanent Link: BitmapData Colour Palette'>BitmapData Colour Palette</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/as3-drag-drop-shuffle-grid-menu' rel='bookmark' title='Permanent Link: AS3 Shuffle Grid Class'>AS3 Shuffle Grid Class</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.soulwire.co.uk/wp-content/uploads/2008/10/average-colour.swf" rel="lightbox;width=800;height=450;" title="Finding the average colours in an image" ><img src="http://blog.soulwire.co.uk/wp-content/uploads/2008/10/average-colours-710x399.jpg" alt="BitmapData Average Colours" title="BitmapData Average Colours" width="710" height="399" class="alignnone size-medium wp-image-618" /></a></p>
<p>If you want a very simple way of extracting a colour palette from an image, one technique would be to average the colour values within specific areas. Averaging colour values is almost identical to averaging numbers, except with the added initial step of finding the red, green and blue components of the colour. To do this we can use <strong>bitwise operators</strong>, in this case <strong>bitwise shift</strong>, to perform fast operations on each <em>bit </em>inside the unsigned integer returned by <em>getPixel</em> or <em>getPixel32</em>.  If you want to know more about bitwise operators, <strong>Moock </strong>has written a detailed and, as ever, very clear article on where, when and why to use bitewise operations. You can read it <a rel="nofollow" href="http://blog.soulwire.co.uk/goto/http://www.moock.org/asdg/technotes/bitwise/"  target="_blank">here</a>.</p>
<p>So once you’re familiar with how to shift the bits of an integer, you can easily get the RGB values from a 24 bit hexadecimal by moving the bits to the right by a certain amount using the <strong>bitwise right </strong><strong>shift </strong> operator (<strong>&gt;&gt;</strong>).<span id="more-165"></span></p>
<p>For example, getting the red, green and blue values from a 24 bit integer would look like:</p>
<pre lang="actionscript">var colour:uint = 0x33CC99;

var R:Number = colour &gt;&gt; 16 &amp; 0xFF;
var G:Number = colour &gt;&gt; 8  &amp; 0xFF;
var B:Number = colour &amp; 0xFF;</pre>
<p>And finding the alpha, red, green and blue values of a 32 bit integer:</p>
<pre lang="actionscript">var colour:uint = 0xFF33CC99;

var A:Number = colour &gt;&gt; 24 &amp; 0xFF;
var R:Number = colour &gt;&gt; 16 &amp; 0xFF;
var G:Number = colour &gt;&gt; 8 &amp; 0xFF;
var B:Number = colour &amp; 0xFF;</pre>
<p>So we know that by shifting the bits to the right, we can effectively break an unsigned integer representing a colour into its specific components, but what about changing these components back into an RGB or ARGB value? Well, it’s simply a matter of shifting the bits in the other direction, using the <strong>bitwise left shift </strong>operator, which looks like this <strong>&lt;&lt;</strong> (two less than operators next to each other).</p>
<p>So using this bitwise shift left operator, you can take your RGB or ARGB values and cram the little buggers back into a usable format, with a little help from <em>bitwise OR</em>:</p>
<pre lang="actionscript">// RGB
var colourRBG:uint = (R &lt;&lt; 16 | G &lt;&lt; 8 | B);

// ARGB
var colourARBG:uint = (A &lt;&lt; 24 | R &lt;&lt; 16 | G &lt;&lt; 8 | B);</pre>
<p>Right, so we know how to take an unsigned integer, for example one that’s been returned from <strong>getPixel </strong>or <strong>getPixel32 </strong>and break it down into its <strong>RGB </strong>or <strong>ARGB </strong>components &#8211; and then for the sake of universal harmony, put it back together again and release it back into its 24 or 32bit world with all its binary friends.</p>
<p>So now, finding the average colour within a set of colours is simply a question of averaging the red, green and blue values of all the colours, and then turning these averages into a new colour.</p>
<p>The method bellow does just this, by looping through the pixels in a BitmapData object, adding up all of the red, green and blue values, dividing them by the total number of pixels and then creating a new colour from the results.</p>
<pre lang="actionscript">public static function averageColour( source:BitmapData ):uint
{
	var red:Number = 0;
	var green:Number = 0;
	var blue:Number = 0;

	var count:Number = 0;
	var pixel:Number;

	for (var x:int = 0; x &lt; source.width; x++)
	{
		for (var y:int = 0; y &lt; source.height; y++)
		{
			pixel = source.getPixel(x, y);

			red += pixel &gt;&gt; 16 &amp; 0xFF;
			green += pixel &gt;&gt; 8 &amp; 0xFF;
			blue += pixel &amp; 0xFF;

			count++
		}
	}

	red /= count;
	green /= count;
	blue /= count;

	return red &lt;&lt; 16 | green &lt;&lt; 8 | blue;
}</pre>
<p>So taking this a step further; say we want an array of 64 colours from an image, we can break the input image down into 64 chunks and find the averages of each. The easiest way of doing this is to build a grid, copy the pixels in each cell and use the averageColour function to return the average colour value of that cell.</p>
<pre lang="actionscript">public static function averageColours( source:BitmapData, colours:int ):Array
{
	var averages:Array = new Array();
	var columns:int = Math.round( Math.sqrt( colours ) );

	var row:int = 0;
	var col:int = 0;

	var x:int = 0;
	var y:int = 0;

	var w:int = Math.round( source.width / columns );
	var h:int = Math.round( source.height / columns );

	for (var i:int = 0; i &lt; colours; i++)
	{
		var rect:Rectangle = new Rectangle( x, y, w, h );

		var box:BitmapData = new BitmapData( w, h, false );
		box.copyPixels( source, rect, new Point() );

		averages.push( averageColour( box ) );
		box.dispose();

		col = i % columns;

		x = w * col;
		y = h * row;

		if ( col == columns - 1 ) row++;
	}

	return averages;
}</pre>
<p>In terms of building an accurate colour palette from an image, this isn’t a great method, mainly because averaging the colours doesn’t give you a fair representation of the <em>range</em> of colours in the image. The palette returned can often be somewhat muddy; however it is still a technique that I’ve found a use for on a surprisingly regular basis and so thought it worth sharing. Becoming familiar with bitwise operators is also a useful exercise and so, if they aren’t already part of your life, I suggest you begin to woo them with your nerdy charm.</p>


<p>Related posts:<ol><li><a href='http://blog.soulwire.co.uk/code/actionscript-3/colourutils-bitmapdata-extract-colour-palette' rel='bookmark' title='Permanent Link: BitmapData Colour Palette'>BitmapData Colour Palette</a></li>
<li><a href='http://blog.soulwire.co.uk/code/actionscript-3/webcam-motion-detection-tracking' rel='bookmark' title='Permanent Link: AS3 Webcam Motion Tracking'>AS3 Webcam Motion Tracking</a></li>
<li><a href='http://blog.soulwire.co.uk/code/open-source/as3-drag-drop-shuffle-grid-menu' rel='bookmark' title='Permanent Link: AS3 Shuffle Grid Class'>AS3 Shuffle Grid Class</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
	</channel>
</rss>
