<?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>UnitZeroOne &#187; Examples</title>
	<atom:link href="http://unitzeroone.com/blog/category/technology/examples/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitzeroone.com/blog</link>
	<description>by Ralph Hauwert, Creative Developer, Consultant</description>
	<lastBuildDate>Mon, 21 Nov 2011 09:31:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>The Particle Sessions : Part One, Is this it ?</title>
		<link>http://unitzeroone.com/blog/2011/01/16/the-particle-sessions-part-one-is-this-it/</link>
		<comments>http://unitzeroone.com/blog/2011/01/16/the-particle-sessions-part-one-is-this-it/#comments</comments>
		<pubDate>Sun, 16 Jan 2011 21:03:03 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[particles]]></category>
		<category><![CDATA[pixelbender]]></category>

		<guid isPermaLink="false">http://unitzeroone.com/blog/?p=437</guid>
		<description><![CDATA[Part One of the Particle Session kicks off with looking at a system similar, but simpler then this Bloom particle experiment (music made for it by the fantastic artist Rich Bologna, thank you again for it, Rich!). We&#8217;ll be taking slow steps &#8230; <a href="http://unitzeroone.com/blog/2011/01/16/the-particle-sessions-part-one-is-this-it/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://unitzeroone.com/blog/wp-content/uploads/thestrokes.jpg"><img class="alignnone size-full wp-image-442" title="The Strokes - Is This It" src="http://unitzeroone.com/blog/wp-content/uploads/thestrokes.jpg" alt="" width="640" height="379" /></a></p>
<p>Part One of the Particle Session kicks off with looking at a system similar, but simpler then <a href="http://unitzeroone.com/labs/bloom/">this Bloom particle experiment</a> (music made for it by the fantastic artist <a href="http://www.richbologna.com/">Rich Bologna</a>, thank you again for it, Rich!). We&#8217;ll be taking slow steps of optimizations and at the end have a get prepared for the next level. To be able to get up to speed with the working of the <a href="http://unitzeroone.com/labs/particleVideo/" target="_blank">video particles</a>, we&#8217;ll start from the beginning and work our way up. For that reason, we&#8217;ll start very simple and look at a basic unoptimized particle system with next to zero functionality, and modify the code for performance.</p>
<p><span id="more-437"></span></p>
<p><strong>Basis : The Particle</strong></p>
<p>The opening picture of this post is the album cover of <a href="http://www.youtube.com/watch?v=f1vvUec71v8" target="_blank">The Strokes &#8211; Is This It</a>. It being one of my favorite albums, I have listened to it many times, but never noticed what the <a href="http://www.google.com/images?q=particle+collision&amp;um=1&amp;ie=UTF-8&amp;source=og&amp;sa=N&amp;hl=en&amp;tab=wi&amp;biw=1267&amp;bih=1103">cover really was</a>. It&#8217;s amazing &amp; inspiring what imagery one can get from science. Now put on your headphones and listen to that album while reading this post.</p>
<p>Over the last years I&#8217;ve more and more started enjoying introductory books about theoretical physics. In complete honesty, it wasn&#8217;t even that long ago that I didn&#8217;t know that the <a href="http://en.wikipedia.org/wiki/Boson">Boson</a> in the <a href="http://en.wikipedia.org/wiki/Higgs_boson">Higgs Boson</a> wasn&#8217;t the other guy discovering it, next to <a href="http://en.wikipedia.org/wiki/Peter_Higgs">Mr.Higgs</a>. You know, like the <a href="http://en.wikipedia.org/wiki/Comet_Hale-Bopp">Hale-Bopp comet</a> was discovered by <a href="http://en.wikipedia.org/wiki/Alan_Hale_(astronomer)">Hale</a> &amp; <a href="http://en.wikipedia.org/wiki/Thomas_Bopp">Bopp</a>.</p>
<p>Luckily for us and this post, we don&#8217;t need to deal with <a href="http://en.wikipedia.org/wiki/Wave%E2%80%93particle_duality">wave particle duality</a> and <a href="http://en.wikipedia.org/wiki/Quantum_entanglement">quantum entanglement</a>, but we can achieve seeming complexity by using simplicity.</p>
<p><strong>Getting started : Simplicity &amp; Complexity</strong></p>
<p>The simple core particle we will be using in this session get its complexity from its display of large numbers of them, not from per instance properties. To illustrate that, let&#8217;s start off with a simple particle object in AS3</p>
<pre class="brush: as3; title: ; notranslate">
package com.unitzeroone.particlesessions
{
	import flash.display.BitmapData;

	public class Particle {
		public var x:Number;
		public var y:Number;
		public var velX:Number;
		public var velY:Number;

		public function Particle(x:Number, y:Number, velX:Number, velY:Number) {
			this.x = x;
			this.y = y;
			this.velX = velX;
			this.velY = velY;
		}
	}
}
</pre>
<p>As you can see, this particle object is pretty simple, and it contains the core properties we really need to make them move. Its position stored in x and y, and its velocity stored in velX and velY. For the case of this post it&#8217;s more then enough to do what we want.</p>
<p>I do want to point out two things about the simplicity of this. First of all, we express all values in absolute x and y. For the positions, this would be called a <a href="http://en.wikipedia.org/wiki/Cartesian_coordinate_system">cartesian system</a>. In some cases it might be handier to express velocity as a <a href="http://en.wikipedia.org/wiki/Polar_coordinate_system">polar coordinates</a>, but performance reasons we&#8217;ll keep them like this.</p>
<p><strong>OOP (s)</strong></p>
<p>It&#8217;s very common within the AS3 industry to &#8220;objectify&#8221; everything in nicely wrapped classes first and think about performance later. In the case of our particle and a classic &#8220;update&#8221; loop as seen in game engines, the most natural feeling way to implement the particle&#8217;s moving behaviour for the particle is as follows.</p>
<pre class="brush: as3; title: ; notranslate">
package com.unitzeroone.particlesessions
{
	import flash.display.BitmapData;

	public class Particle {
		public var x:Number;
		public var y:Number;
		public var velX:Number;
		public var velY:Number;

		public function Particle(x:Number, y:Number, velX:Number, velY:Number) {
			this.x = x;
			this.y = y;
			this.velX = velX;
			this.velY = velY;
		}

		public function updateAndDraw(toBitmapData:BitmapData):void
		{
			this.x += velX;
			this.y += velY;
			toBitmapData.setPixel(this.x,this.y,0xFFFFFF);
		}
	}
}
</pre>
<p>This is a very logical thing to do and is suitable for most things, especially in larger code bases, it certainly helps in readability. It also matches many things you&#8217;ll see in OOP and AS3 books. Like car.drive() or lasership.shoot() or avatar.updatePosition(). From a pure OO perspective, it makes sense. From a performance perspective, this isn&#8217;t as good though. We&#8217;ll tackle that in a bit.</p>
<p><strong>Main</strong></p>
<p>Now, let&#8217;s say we&#8217;d have a very simple Main class to run this system, as such :</p>
<pre class="brush: as3; title: ; notranslate">
package {

import flash.display.StageScaleMode;
import flash.display.StageAlign;
import com.unitzeroone.particlesessions.Particle;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;

	public class MainOne extends Sprite {
		private var bitmap : Bitmap;
		private var bitmapData : BitmapData;
		private var particles:Array;

		public function MainOne(){
			init();
		}

		private function init():void
		{

			//Create a canvas to draw too
			bitmapData = new BitmapData(500,400,false,0x000000);
			bitmap = new Bitmap(bitmapData);
			addChild(bitmap);

			//Create a set of random particles with a random velocity
			particles = new Array();
			for(var i:int = 0; i&lt;=1000; i++){
				particles.push(new Particle(Math.random()*500,Math.random()*400,Math.random()*2-1,Math.random()*2-1));
			}
			//Wait to be added to stage
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}

		private function onEnterFrame(event : Event) : void
		{
			//Clear the stage
			bitmapData.fillRect(bitmapData.rect,0x000000);

			//Lock the bitmapdata, while we are updating it.
			bitmapData.lock();

			//Draw particles
			var p:Particle;
			var l : int = particles.length;
			for(var i:int = 0; i&lt;l; i++){
				p = particles[i];
				p.updateAndDraw(bitmapData);
			}

			//We are done updating, unlock the bitmapdata
			bitmapData.unlock();
		}

		private function onAddedToStage(event : Event) : void
		{
			//If added to stage, set stage properties and start listening to the global enterframe.
			stage.frameRate = 30;
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
	}
}
</pre>
<p>For clarity sake I&#8217;ve omitted a couple of things, but this code runs. If you run it, you&#8217;ll see bunch of particles moving at a constant speed, moving offscreen. Our simplest of simple particle system works, so now we can start looking at performance and why we need to change the structure for performance.</p>
<p><strong>Performance, the small issues</strong></p>
<p>If you aware of performance caveats within Flash, you&#8217;ll immediately notice a couple of things, amongst which the lesser problems like for instance;</p>
<pre class="brush: as3; title: ; notranslate">bitmapData.fillRect(bitmapData.rect,0x000000);</pre>
<p>A lesser known fact about this piece of code is that the property rect of the bitmapdata is not a static read-only rect, but that every time you query this property a new rect is instantiated. Instantiation is rather expensive in the AVM2, but in this case, it&#8217;s called once per frame, thus not a major issue. Still it&#8217;s unneeded. Keep this in mind when you do many things per frame with bitmapdata.rect. In general, keep in mind that instantiation &amp; allocation is expensive.</p>
<p>If you ever had one of those swf&#8217;s which seemed to hickup every now and then, chances are that it is the garbage collector kicking in. It doesn&#8217;t have to be one specific place where you are instancing to many objects, it might be more then one. So keep things clean from the beginning. Also keep in mind that many small performance losses will result in one big one.</p>
<p><strong>The larger performance costs</strong></p>
<p>There&#8217;s multiple things we can optimize in this piece of code. For now let&#8217;s keep it a bit simple and look at the larger issues, where we get the most gain. One of the main issues is how we store and access the individual particles.</p>
<pre class="brush: as3; title: ; notranslate">particles = new Array();</pre>
<p>We currently store them in an (as always in ActionScript) untyped array. If we&#8217;d like to keep the &#8220;storage&#8221; an array like structure, we would be better off using a Vector for storage, but we can get it even a bit faster by using a <a href="http://en.wikipedia.org/wiki/Linked_list">linked list</a> instead. For the purposes of this simple particle system, that data structure is enough, as we are only going to linearly iterate over the particle set in one direction. This is called a singly linked list.</p>
<p>Let&#8217;s have a look at how that works.</p>
<p><strong>Linked List</strong></p>
<p>First, we modify our Particle class, to contain a link to the next particle in the list, by adding this to its properties.</p>
<pre class="brush: as3; title: ; notranslate">public var next:Particle;</pre>
<p>Then we modify the Main class to instanciated the particles like this :</p>
<pre class="brush: as3; title: ; notranslate">
var particle:Particle;
var previousParticle:Particle;
for(var i:int = 0; i&lt;=1000;i++){
	particle = new Particle(Math.random() * 550, Math.random() * 400, Math.random() * 2 - 1, Math.random() * 2 - 1);
	particle.next = previousParticle;
	previousParticle = particle;
}
firstParticle = particle;
</pre>
<p>For every particle we create we store a reference to the previous particle in that particle. Then when we are done with the loop we keep a reference to the last created particle. That particle refers to the particle created before that, and so on, until we reach the first particle which has no reference to any particle.</p>
<p>We now update the drawloop to do the following;</p>
<pre class="brush: as3; title: ; notranslate">
var p : Particle = firstParticle;
while (p) {
	p.updateAndDraw(bitmapData);
	p = p.next;
}
</pre>
<p><strong>Final(ly) ?</strong><br />
Using a linked list instead of an Array helped, but we can even more performance for free, by adding the “final” keyword to the particle class.</p>
<pre class="brush: as3; title: ; notranslate">final public class Particle {</pre>
<p>You would use the final keyword normally to prevent classes from being subclassed, but there is an interesting piece about final in <a href="http://onflex.org/ACDS/AS3TuningInsideAVM2JIT.pdf">Flash AS3 and AVM2 performance tuning</a>, which by now is an aged document. In this case it indicates that sealing classes using the final keyword helps the AVM because the properties are already resolved and bound.</p>
<p>I find that in Flash Player 10.1 the advantage is less noticable then 10 and before, but it still has a slight performance gain on my machine, although I&#8217;ve heard it been debated more then one time. It seems to me also that some platforms/architectures benefit more then others. My naive way of thinking about it is that if you&#8217;re not going to subclass it anyway, you might as well finalize it. Simplicity.</p>
<p><strong>Function calling</strong><br />
It may seem obvious to call a method of an object (like with car.drive()), but if you want maximum performance you should avoid function calls. With this in mind, let’s take another look at our draw loop :</p>
<pre class="brush: as3; title: ; notranslate">
var p : Particle = firstParticle;
while (p) {
	p.updateAndDraw(bitmapData);
	p = p.next;
}
</pre>
<p>The updateAndDraw call here is the costliest thing in the main loop. Not because what it does, but because it is a function. In general, function calling is always going to have some form of overhead, but in the case of Flash / AVM2 / AS3, the cost is exceptionally high. Although this situation has improved with Flash 10.1, the overall hit of just calling a function inside the loop is way to high to be acceptable if we want to achieve high numbers of particles.</p>
<p><strong>Inlining</strong></p>
<p><a href="http://en.wikipedia.org/wiki/Inline_expansion">Inlining</a> is something a compiler does for for you to replace a method call with the actual functionality in place of the function call.</p>
<p>AS3 does not have an inline keyword natively, and the compiler wouldn&#8217;t know what to do with it. <a href="http://blog.joa-ebert.com/">Joa Ebert&#8217;s</a> <a href="http://code.google.com/p/apparat/">Apparat tool suite</a>, written in <a href="http://www.scala-lang.org/">Scala</a>,provides amongst other incredibly handy things a way <a href="http://blog.joa-ebert.com/2010/05/26/new-apparat-example/">to do inlining in AS3</a>. I highly recommend using it for larger projects where code style and performance are important. I actually also would highly recommend it for any project where performance is a priority. For this instance though, let&#8217;s go to a simpler solution first.</p>
<p>We&#8217;ll remove the updateAndDraw method from the particle class and make our main loop look like this.</p>
<pre class="brush: as3; title: ; notranslate">
var p : Particle = firstParticle;
while (p) {
	p.x += p.velX;
	p.y += p.velY;
	bitmapData.setPixel(p.x,p.y,0xFFFFFF);
	p = p.next;
}
</pre>
<p>Yay. For now you&#8217;ll have to take my word for it, but this is faster. (later on in this series will prove this with benchmark tests, I wanted to avoid this post just being a bunch of charts and performance graphs).</p>
<p><strong>Yet another function call.</strong></p>
<p>While looking at this new snippet, immediately you&#8217;ll notice another function call in our mainloop.</p>
<pre class="brush: as3; title: ; notranslate">bitmapData.setPixel(p.x,p.y,0xFFFFFF);</pre>
<p>The bitmapData.setPixel is yet another function call being called as many times as there are particles. What&#8217;s important to note though is that Flash native API calls are faster then calls to methods in non &#8220;api&#8221; classes. So although the bitmapdata.setpixel call is costing us more then it should, it still not costs as much as calling a method on one of your objects.</p>
<p>Still, there is cost associated to this function call, and we can avoid it by inlining the method again. setPixel() is an incredibly handy utility function though, so we need to replace its functionality by a piece of code which mimicks its behaviour. Also, we need to write to the bitmapdata&#8217;s data by hand.</p>
<p>I&#8217;m not going to jump into using Alchemy / FastMemory just yet, so for now we&#8217;re going to use the next fastest accessible type that is available in AS3. Vector.</p>
<p><strong>Drawing to a Vector instead</strong></p>
<p>One can avoid drawing to a bitmap using setPixel and use a faster way to do so using a Vector object. While certainly not the fastest way to write to a bitmapdata, it&#8217;s probably the fastest way to do it in pure actionscript without any external tools. In comparison to using setPixel in our main loop, it should be a very good performance improvement.</p>
<p>One of the things setPixel did for us was bounds checking. Since we won&#8217;t use it anymore, we need to do it ourselves, so that we don&#8217;t write to a position in the vector that is outside of the bounds of the vector. At the same time, we&#8217;ll use this to resolve another issue. The particles were randomly flying offscreen. Instead of that we&#8217;ll respawn them at their starting position. We&#8217;ll add these properties to the particle class.</p>
<pre class="brush: as3; title: ; notranslate">
final public class Particle  {

		public var x:Number;
		public var y:Number;
		public var velX:Number;
		public var velY:Number;
		public var spawnX:Number;
		public var spawnY:Number;
		public var next:Particle;

		public function Particle(x:Number, y:Number, velX:Number, velY:Number) {
			this.spawnX = this.x = x;
			this.spawnY = this.y = y;
			this.velX = velX;
			this.velY = velY;
		}
}
</pre>
<p>And here is our main renderloop :</p>
<pre class="brush: as3; title: ; notranslate">
private function onEnterFrame(event : Event) : void
		{
			// Clear the stage
			bitmapData.lock();
			bitmapData.fillRect(bitmapRect, 0x000000);
			var vec:Vector.&lt;uint&gt; = bitmapData.getVector(bitmapRect);

			var w : int = bitmapRect.width;
			var h : int = bitmapRect.height;
			// Access particles and draw them
			var p : Particle = firstParticle;
			while (p) {
				p.x += p.velX;
				p.y += p.velY;
				if(p.x &gt; w || p.x &lt; 0){
					p.x = p.spawnX;
				}
				if (p.y &gt; h || p.y &lt; 0) {
					p.y = p.spawnY;
				}
				vec[int(w*int(p.y) + int(p.x))] = 0xFFFFFFFF;
				p = p.next;
			}
			bitmapData.setVector(bitmapRect, vec);
			bitmapData.unlock();
		}
</pre>
<p>While this setup is still far from optimal from a performance perspective, we&#8217;ve got a reasonably fast way to render 10 to 20k particles to screen.</p>
<p>One note here is the bitmapData.getVector and setVector.<br />
This still isn’t that optimized &#8211; the function call “BitmapData.getVector” creates a new Vector object every time we call it, and as you know, creating objects takes CPU and memory allocation. Ideally the function should allow us to pass it a pre-existing vector object for it to populate with data. There are a couple of examples of this throughout the Flash API&#8217;s, and I truly hope Adobe will address these in future versions of the Flash Player. The benefit here of using getVector is that we can quickly clear the entire vector. Or if you would play around with this, you could not fillrect the bitmapdata and blur it slightly every frame.</p>
<p>For reference, what we have now looks like this, and can be download as source here: <a class="downloadlink" href="http://unitzeroone.com/blog/wp-content/plugins/download-monitor/download.php?id=1" title="Version1 downloaded 576 times" >MainOneVersionOne (576)</a></p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="MainOne" width="640" height="400" align="center" name="MainOne">
      <param name="movie" value="http://unitzeroone.com/blog/wp-content/uploads/MainOne1.swf" />
      <param name="align" value="center" />
      <param name="name" value="MainOne" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://unitzeroone.com/blog/wp-content/uploads/MainOne1.swf" width="640" height="400" align="center" name="MainOne">
      <!--<![endif]-->
        </p>
<p>What, you don\&#8217;t have Flash ? And you are still reading my blog ? Kudos to you!</p>
<p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p><strong>So far, simple enough, right ?</strong></p>
<p><span style="color: #000000;">I&#8217;ve kept everything quite simple so far to illustrate a couple of mostly obvious performance hints, and to set a frame of reference for the follow up article, part two. Technically this solution is far from the optimal solution to run particles. But for experimenting with moving the particles in a more interesting fashion, its good enough for Part One of this series. The benefit is that we can still express all the code in ActionScript. We&#8217;ll add a little bit of PixelBender in the mix to get comfortable with it and use it as an example of manipulating data with PixelBender.</span></p>
<p><span style="color: #000000;"><strong>Velocity Field ?</strong></span></p>
<p><span style="color: #000000;">Visually this example is completely boring, so let&#8217;s make it a bit more interesting. We&#8217;ll start by making the particles move to a background pattern. We&#8217;ll use some perlin noise and pixelbender to generate a <a href="http://en.wikipedia.org/wiki/Vector_field" target="_blank">vector field</a> for the particles to read from.</span></p>
<p><span style="color: #000000;">We&#8217;ll use a vector similar to the vector we are using to draw to the bitmapdata we did earlier, and mix in some perlin noise to convert grayscale perlin noise to velocities to be quickly looked up by the particles. We start by adding some code to the Main class, let&#8217;s start with the init method.</span></p>
<p><span style="color: #000000;"> </span></p>
<pre class="brush: as3; title: ; notranslate">
private function init():void
{
	//Get some perlin noise in grayscale to read in our pixelbender filter.
	var perlinMap:BitmapData = new BitmapData(WIDTH, HEIGHT, false, 0x000000);
	perlinMap.perlinNoise(128, 128, 6, 123456, true, false,7,true);

	//Load the embedded shader bytearray into a new shader.
	var velocityConverterShader : Shader = new Shader(new VelocityConverter() as ByteArray);
	var velocityConverterFilter : ShaderFilter = new ShaderFilter(velocityConverterShader);

	//Create a new temporary bitmapdata to write the filter result too.
	var perlinVelocityMap : BitmapData = perlinMap.clone();
	perlinVelocityMap.applyFilter(perlinMap, perlinMap.rect, perlinMap.rect.topLeft, velocityConverterFilter);

	// And get the result into a fastly readable vector
	velocityVector = perlinVelocityMap.getVector(perlinVelocityMap.rect);

	//Nicely dispose of the memory used by the two bitmapdata's.
	perlinVelocityMap.dispose();
	perlinMap.dispose();

	//Create a canvas to draw too
	bitmapData = new BitmapData(WIDTH, HEIGHT, false, 0x000000);
	bitmapRect = bitmapData.rect;
	bitmap = new Bitmap(bitmapData);
	addChild(bitmap);

	//Initialize the particles and keep them as a linked list.
	var particle:Particle;
	var previousParticle:Particle;
	for(var i:int = 0; i&lt;=1000;i++){
		particle = new Particle(Math.random() * WIDTH, Math.random() * HEIGHT, Math.random() * 2 - 1, Math.random() * 2 - 1);
		particle.next = previousParticle;
		previousParticle = particle;
	}
	firstParticle = particle;

	//Wait to be added to stage
	addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
</pre>
<p><span style="color: #000000;">As you can see we added some code and a new property to our mainclass, to hold a reference to a &#8220;velocity vector&#8221;. This Vector will contain values much like colors. There&#8217;s many ways to get pixelbender to output data. To be able to read the data quickly in our mainloop, we need a vector again. So the easiest way to get a vector with uint&#8217;s from a pixelbender is to actually let it render to a bitmapdata. </span></p>
<p><span style="color: #000000;">The reason we are using 2 bitmapdata&#8217;s is that it&#8217;s significantly cheaper to instanciate them yourself and pass them, then to pass 1 bitmapdata for pixelbender to use as input and output, as it will allocate a block of memory for the output in any case. This way it&#8217;s faster and we have more control.</span></p>
<p>After the pixelbender filter has done it processing, we simple do a getVector on the bitmapdata to get the result into a Vector.&lt;uint&gt;.</p>
<p><strong>A tiny bit of pixelbending</strong></p>
<p>To get familiar with pixelbender kernels, we&#8217;re going to use one to calculate the data in our velocity field with. The pixelbender filter is one of a very simple kind, let&#8217;s have a look at it. It only has one input and it samples four pixels for every pixel it evaluates. Sampling from data within the Pixelbender is quite heavy, but for now we will only run this filter during the initialization of our swf. It might be fast enough to run every frame even.</p>
<pre class="brush: plain; title: ; notranslate">
&lt;languageVersion : 1.0;&gt;

kernel VelocityConverter
&lt;   namespace : &quot;com.unitzeroone&quot;;
    vendor : &quot;UnitZeroOne&quot;;
    version : 1;
&gt;
{
    input image4 src;
    output pixel4 dst;

    void
    evaluatePixel()
    {
        const float halve = 0.5;
        const float3 offsets = float3(0.0,1.0,-1.0);//We'll swizzle these around in our sampling.
        float4 left = sampleNearest(src,outCoord()-offsets.zx);
        float4 right = sampleNearest(src,outCoord()-offsets.yx);
        float4 top = sampleNearest(src,outCoord()-offsets.xz);
        float4 bottom  = sampleNearest(src,outCoord()-offsets.xy);

        //We'll store the slopes in green and blue, the two lower bytes in the vector.
        dst.r = 0.0;// We don't need to set r, but on some older flash players this caused bugs.
        dst.g = ((left.b-right.b)*halve)+halve;//Get the slope value between left and right, and normalize to 0-1
        dst.b = ((top.b - bottom.b)*halve)+halve;//Get the slope value between top and bottom and normalize to 0-1
        dst.a = 1.0;//We're using four channels, because we use shaderfilter.

    }
}
</pre>
<p>What this filter does is that it calculates the so called <a href="http://en.wikipedia.org/wiki/Finite_difference" target="_blank">central difference</a> for every pixel, using its connecting neighbours and store them back into the color channels. Let&#8217;s look at its input and output to have a visual reference before discussing it further.</p>
<p>The input &amp; output.</p>
<p><a href="http://unitzeroone.com/blog/wp-content/uploads/input.jpg"><img class="aligncenter size-full wp-image-517" title="Perlin Noise Input" src="http://unitzeroone.com/blog/wp-content/uploads/input.jpg" alt="" width="640" height="480" /></a><a href="http://unitzeroone.com/blog/wp-content/uploads/output.jpg"></a></p>
<p><a href="http://unitzeroone.com/blog/wp-content/uploads/output.jpg"><img class="aligncenter size-full wp-image-518" title="output" src="http://unitzeroone.com/blog/wp-content/uploads/output.jpg" alt="" width="640" height="480" /></a></p>
<p><span style="color: #000000;">Although that wikipedia page about the central difference might have scared you off, all in all what it does is very simple. For every pixel you look at the connecting neighbours in both directions and you look at the difference between that and store that. Note that we are normalizing the value, so that the maximum negative value of -1 and the maximum value of +1 fit in a range 0 to 1. This way we can read these values later on in our mainloop. We store the result for the difference on the horizontal axis in the green channel and the result for the vertical axis in the blue channel, hence the blue green teint of the image.</span></p>
<p><span style="color: #000000;">It&#8217;s good to note that PixelBender really makes these types of image calculations fast and simple. Long before PixelBender we had to do this using combinations of filters and copy channels to do this quickly enough. <a href="http://unitzeroone.com/flashexamples/bumpMapping/" target="_blank">My first experiment with fast bumpmapping</a> from a <a href="http://unitzeroone.com/blog/2006/03/28/flash-8-example-3d-bumpmapping-using-filters-source-included/" target="_blank">long, long time ago</a> used that way of doing it. When I started working on Papervision3D it resulted in <a href="http://unitzeroone.com/papervision/paperPlanet/Main.html" target="_blank">this experiment</a>.</span></p>
<p><span style="color: #000000;"><strong>Making things move</strong></span></p>
<p><span style="color: #000000;">Now that we have this new set of data, how do we make our particles dance to it ? The reason we wrote too a vector uint is so that we can read from it quickly. But we store the data in two different channels, being blue and green. Let&#8217;s take that data out and manipulate our particles velocities using it.</span></p>
<p><span style="color: #000000;">Our main loop will look something like this;</span></p>
<pre class="brush: as3; title: ; notranslate">
while (p) {
	//Add the current velocity to the particle position
	p.x += p.velX;
	p.y += p.velY;

	//Keep the particles in bounds
	if(p.x &gt; w || p.x &lt; 0){
		p.x = p.spawnX;
	}
	if (p.y &gt; h || p.y &lt; 0) {
		p.y = p.spawnY;
	}

	//Calculate the new position index;
	pos = (w*int(p.y) + int(p.x));

	//Draw the pixel
	vec[pos] = 0xFFFFFFFF;

	// Read the velocityfield at the new particles position
	var velocities : int = velocityVector[pos];
	var velXU : int = ((velocities&gt;&gt;8)&amp;0xFF)-127.5;
	var velYU : int = ((velocities)&amp;0xFF)-127.5;

	//Add a fraction of the position velocity to the current velocity
	p.velX += velXU*.073;
	p.velY += velYU*.073;

	// Dampen the current particle velocity
	p.velX = p.velX*.99;
	p.velY = p.velY*.99;

	p = p.next;
}
</pre>
<p>This bit of actionscript :</p>
<pre class="brush: as3; title: ; notranslate">
var velXU : int = ((velocities&gt;&gt;8)&amp;0xFF)-127.5;
var velYU : int = ((velocities)&amp;0xFF)-127.5;
</pre>
<p>If your unfamilar with <a href="http://en.wikipedia.org/wiki/Mask_(computing)" target="_blank">masking</a> and <a href="http://en.wikipedia.org/wiki/Bitwise_operation" target="_blank">bitwise operations</a>, this might look slightly strange. But if you have worked with colors using setPixel before, you might be familiar with the pattern here. Basically we extract the &#8220;color&#8221; as output by PixelBender from the green and blue channel. I put color in quotes there, because it&#8217;s not what we use it for. We simple use the byte packing into uint&#8217;s as a way to quickly access one value in a vector (which is the heaviest), and then unpack it into two of its components. A uint in Flash is 32 bit, so it contains 4 bytes. In theory we have 2 bytes left for storing other data. More on that in part two.</p>
<p>And it does almost exactly the opposite of what this did in the pixelbender loop :</p>
<pre class="brush: plain; title: ; notranslate">
dst.g = ((left.b-right.b)*0.5)+0.5;
dst.b = ((top.b - bottom.b)*0.5)+0.5;
</pre>
<p>The only difference is that pixelbender treats the color value as a range between 0-1 and that our actionscript values will now be filled with a value between -127.5 and 127.5. We handle putting the particle velocities to reasonable values by multiplying them by a rather small value. Play around with the values if you like.</p>
<p>To assure that the particles don&#8217;t pick up an infinite speed we dampen it by multiplying by a value near to one, as to only slightly lower it every loop.</p>
<pre class="brush: as3; title: ; notranslate">
p.velX = p.velX*.99;
p.velY = p.velY*.99;
</pre>
<p><strong>So is it magical yet ? </strong></p>
<p>If we look at what it looks like now with a thousand particles, we see this:</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="MainOneTwo" width="640" height="480" name="MainOneTwo">
      <param name="movie" value="http://unitzeroone.com/blog/wp-content/uploads/MainOne2.swf" />
      <param name="name" value="MainOneTwo" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://unitzeroone.com/blog/wp-content/uploads/MainOne2.swf" width="640" height="480" name="MainOneTwo">
      <!--<![endif]-->
        Still here without Flash huh ? You\&#8217;re persistent ! 
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p>So, no it&#8217;s still rather uninteresting. Although our particles do seem to have to taken up a life on their own.</p>
<p><strong>Adding complexity by adding the numbers</strong></p>
<p>The particles seem to settle in areas, and the randomness of their movement and location is worsened by the fact that they are moving over perlin noise, where the noise part of that implies it&#8217;s somewhat random.</p>
<p>As I said at the beginning of this post, part of the percieved complexity of a particle system is in its numbers. What happens if we replace the perlin noise by a picture and add a lot more particles, let&#8217;s say 20.000 ? And then tweak the values a bit ?</p>
<p><a href="http://www.unitzeroone.com/particlesessions/pSessionsOne/" target="_blank">Click here</a> to see what that looks like.</p>
<p>Get the source here : <a class="downloadlink" href="http://unitzeroone.com/blog/wp-content/plugins/download-monitor/download.php?id=3" title=" downloaded 665 times" >Session One Final Source (665)</a></p>
<p><strong>Closing and what will follow</strong></p>
<p><span style="color: #000000;">The length of this simple introductory Session One already got way out of hand, so it&#8217;s time to close for this session, which means that unfortunately Alchemy is saved for next week. We&#8217;ve covered the basics of a reasonably performant particle system in pure, directly compilable AS3.</span></p>
<p><span style="color: #000000;">To continue this series and make the example code do a lot more then it does now, we need to start diving much deeper in PixelBender and the Alchemy-memory within Flash Player. We&#8217;ll be able to increase the number of particles to a much higher count then 20.000 of them using these techniques and hopefully be able to fully understand why and how. Along the way we&#8217;ll be able to look at how these technologies function inside the Flash Player.</span></p>
<p><span style="color: #000000;">Hopefully, we&#8217;ll polish up this example to a point where it&#8217;s starting to become interesting to look at. You&#8217;d be surprised to see how close we are to achieving something like the <a href="http://unitzeroone.com/labs/particlehd/" target="_blank">Particle Reactor</a> with the current source code. But to be able to fully explain ways of using PixelBender and Alchemy, we need about another time the length of this post. </span></p>
<p><span style="color: #000000;">Until then, I would love to see your experiments based upon the source code above. If you do happen to do anything with it, please send it over and if there is enough response, maybe we&#8217;ll add it to next the post. I&#8217;ll give you some hints; dynamic vector fields, colors, trails.</span></p>
<p>I would like to thank <a href="http://sebleedelisle.com/" target="_blank">Seb Lee-Delisle</a> for reviewing this post and helping me to get it cleaner, better and more to the point. Another big thank you to <a href="http://techblog.floorplanner.com/" target="_blank">Tim Knip</a> for reading and pointing out the missing explanations.</p>
<p>I would also greatly appreciate any feedback on this article from you. I&#8217;m new to writing large articles / tutorials like this, and would love to hear what you think and what you would like to see.</p>
<p><span style="color: #000000;"><br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2011/01/16/the-particle-sessions-part-one-is-this-it/feed/</wfw:commentRss>
		<slash:comments>53</slash:comments>
		</item>
		<item>
		<title>Flash Player 10.1 pre-release on Nexus One</title>
		<link>http://unitzeroone.com/blog/2010/05/12/flash-player-10-1-pre-release-on-nexus-one/</link>
		<comments>http://unitzeroone.com/blog/2010/05/12/flash-player-10-1-pre-release-on-nexus-one/#comments</comments>
		<pubDate>Wed, 12 May 2010 22:35:55 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[3d]]></category>
		<category><![CDATA[Examples]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[10.1]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[flash3d]]></category>
		<category><![CDATA[flashmodplug]]></category>
		<category><![CDATA[libmodplug]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[nexus one]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/?p=352</guid>
		<description><![CDATA[Nexus One running Flash Player 10.1 from Ralph Hauwert on Vimeo. This is a video of the Nexus One with a pre-release version of Adobe Flash Player 10.1. It does not represent the final quality of the Flash Player on &#8230; <a href="http://unitzeroone.com/blog/2010/05/12/flash-player-10-1-pre-release-on-nexus-one/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="400" height="300" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://vimeo.com/moogaloop.swf?clip_id=11695816&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed type="application/x-shockwave-flash" width="400" height="300" src="http://vimeo.com/moogaloop.swf?clip_id=11695816&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p><strong><a href="http://vimeo.com/11695816">Nexus One running Flash Player 10.1</a></strong> from <strong><a href="http://vimeo.com/unitzeroone">Ralph Hauwert</a></strong> on <strong><a href="http://vimeo.com">Vimeo</a></strong>.</p>
<p>This is a video of the <a href="http://www.google.com/phone/?hl=en&amp;s7e=" target="_blank"><strong>Nexus One</strong></a> with a pre-release version of <strong><a href="http://labs.adobe.com/technologies/flashplayer10/" target="_blank">Adobe  Flash Player 10.1</a></strong>. It does not represent the final quality of the Flash  Player on this specific device. But it&#8217;s pretty good as is!</p>
<p>This is the Nexus One running 2 demos. First a Nexus one specific  version of the &#8220;<strong><a title="Milkyball" href="http://www.unitzeroone.com/labs/vertexmap/" target="_blank">Milkyball</a></strong>&#8220;, which is adjusted in resolution and  screensize.</p>
<p>Second a non-adjusted version of <a href="http://unitzeroone.com/labs/flashModPlug/#Mortimer%20Twang-Burning%20chrome%20end.mod" target="_blank"><strong>FlashModPlug</strong></a>, an experimental project I&#8217;m currently  working on. It&#8217;s a port and wrapper of <strong><a href="http://modplug-xmms.sourceforge.net/">LibModPlug</a></strong>, running inside the  Flash Player through <a href="http://labs.adobe.com/technologies/alchemy/" target="_blank"><strong>Adobe Alchemy</strong></a>.</p>
<p>Conclusion 10.1 on the Nexus is really, really fast!</p>
<p>(go to <a href="http://vimeo.com/11695816" target="_blank"><strong>vimeo</strong></a> for the full resolution version). (<a href="http://unitzeroone.com/labs/vertexMapNexus/" target="_blank"><strong>link to nexus demo</strong></a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2010/05/12/flash-player-10-1-pre-release-on-nexus-one/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Help me test! Flash VSync and Screen Tearing.</title>
		<link>http://unitzeroone.com/blog/2009/11/30/help-me-test-flash-vsync-and-screen-tearing/</link>
		<comments>http://unitzeroone.com/blog/2009/11/30/help-me-test-flash-vsync-and-screen-tearing/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 13:55:40 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Random Thoughts]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[tearing]]></category>
		<category><![CDATA[vsync]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/?p=311</guid>
		<description><![CDATA[So, here&#8217;s a post where I am asking you, the Flash community, for a hand. Any of it is truly appreciated and will hopefully get some attention and maybe even a solution to a problem which has been in around &#8230; <a href="http://unitzeroone.com/blog/2009/11/30/help-me-test-flash-vsync-and-screen-tearing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone" src="http://www.unitzeroone.com/images/tearing.jpg" alt="" width="430" height="294" /></p>
<p>So, here&#8217;s a post where I am asking you, the Flash community, for a hand. Any of it is truly appreciated and will hopefully get some attention and maybe even a solution to a problem which has been in around in Flash since as long as I can remember; screen tearing.</p>
<p>First, what does tearing mean in this context ? <a href="http://en.wikipedia.org/wiki/Screen_tearing" target="_blank"><strong>Read this wikipedia article</strong></a>. In this case, it&#8217;s a visual split along a vertical line in a Flash movie. It&#8217;s been a known issue with Flash since quite some time (always as far as I know), with improvements over several Flash player versions, but I haven&#8217;t had to deal with it much lately&#8230;.until now. I&#8217;m in a project where this visual artefact is a major distraction from the content and the experience.</p>
<p>All in all, this seems to be the cause (at least, my analysis of it) of tearing in this case; Flash internally rasterizes a screen, and pushes it to the screen buffer. Internally, this should be synced to your display refresh (60hz or 72hz, for instance), so that the buffer doesn&#8217;t get updated halfway through the videocard building up the frame. But on some browsers and platforms it does update during the video card frame refresh, resulting in two rendered frames being displayed at once (or better; 1 frame being updated to the next while drawing to screen), with an optically visible vertical split visible between the two frames. This problem has been around for a long time. It&#8217;s more prone to show up in content with &#8220;tall&#8221; items in it, fast frame rates with large portions of the screen moving, and during horizontal scrolling of displayobjects.</p>
<p>The picture above shows the problem in action. It&#8217;s a picture taken using a regular camera pointed at the screen, as this problem doesn&#8217;t show up in screencapture software. It shows two different frames of the testing movie; both a black and white square, updated halfway through the screen. While the position of where the slicing happens changes, in many single frames, 2 frames will be displayed at the same time.</p>
<p>I&#8217;m seeing problems with the latest 10 Player on Windows XP (Firefox), Mac OS X (Firefox, safari doesn&#8217;t but &#8220;stutters), and Windows 7. All in all, this is a graphical issue which has been around for a long time and should be solved. It&#8217;s definitely a Flash Player bug and with FlashPlayer 10.1 around the corner, I would really love to see this fixed. As well as being hopeful for finding a solution for current player/browser configurations. But testing results are varying and that&#8217;s where I am asking you for help, by running 2 flash movies and posting the results to my comments.</p>
<p>Over the last days I&#8217;ve been frantically testing several configurations and options, I would hope force vsync with the flash screen buffer, amongst which the following :</p>
<ul>
<li>Adding a video at 30fps to the stage (no result)</li>
<li>Adding system text to the display list (seems to work on windows xp)</li>
<li>Several configurations of stage.invalidate() and Event.RENDER (no result)</li>
<li>Different drawing / caching methods.</li>
<li>Wmode=&#8221;direct&#8221; for flash player embed options. (result across the board!)</li>
</ul>
<p>The last option is the only thing which seems to work on all testing configurations, but comes at a cost. Switching to wmode=&#8221;direct&#8221; seems to force vsyncing and this would adhere to what has been said about direct wmode:</p>
<p><strong><em>&#8220;This mode tries to use the fastest path to screen, or direct path if you will. In most cases it will ignore whatever the browser would want to do to have things like overlapping HTML menus or such work. A typical use case for this mode is video playback. On Windows this mode is using DirectDraw or Direct3D on Vista, on OSX and Linux we are using OpenGL. Fidelity should not be affected when you use this mode.&#8221; </em><a href="http://www.kaourantin.net/2008/05/what-does-gpu-acceleration-mean.html" target="_blank"><em>[Link to Tinics blog]</em></a></strong></p>
<p><em><strong>&#8220;Hardware offscreen buffer<br />
Software renderer, perfect fidelity&#8221; <a href="http://web.me.com/jeroendendunnen/downloads/max2008/documents/develop/Flash_Player_Internals-Jim_Corbett-final_v2.ppt" target="_blank">[link to Jim Corbett's presentation (ppt)]</a></strong></em></p>
<p>As opposed to the wmode=&#8221;gpu&#8221; flag, which moves rasterization to the videocard (at a hight cost in most content cases, also altering the appearance of your content depending on the videocard), this option still uses the Flash Software Rasterizer to build up content for the screen. But on both my Mac and PC testing this comes at a performance cost of several frames per second, up to about 15fps on larger screens (1280&#215;768). Also, I&#8217;m not sure about the results of this on machines with no gpu. (mostly, cheap on board graphic chipsets, which share system memory). While most of the time, your content type might vary in terms of results with either GPU enabled wmodes, in this test that shouldn&#8217;t be an issue.</p>
<p>Obviously, abusing wmode=&#8221;direct&#8221; to force vsyncing on the Flash Player isn&#8217;t ideal, but it seems to work. In an effort to survey the results of this, I&#8217;ve built a very simple test swf. What I&#8217;d like you to do is run both swfs and copy the text field of both and paste them in my comments. Although I&#8217;m already in contact with Tinic about this, there&#8217;s currently no JIRA bug describing the problem. With the results you have, I&#8217;d like to put up an official bug there, and use your results to describe what systems are impacted.</p>
<p>Firefox seems to be the main culprit. Since FF 3 there have been a number of big issues with Flash and Firefox; for instance, in some cases a right click on the flash player will cause the updated areas in the Flash movie to render as an opaque rectangle with the background color. In another case, Flash doesn&#8217;t respond to rollover events and doesn&#8217;t even render without a mouse click occuring.</p>
<p>Please help me and hopefully Adobe identify and fix this problem, by running these tests. Here&#8217;s what you should do :</p>
<ul>
<li>Run both movies</li>
<li>Look for tearing. Typically, in these test, instead of steady flickering, you&#8217;ll see a moving vertical tear between the black and white area. It is essentiall you identify tearing correctly, so make sure you know what it looks like (picture above is a still). The effect of tearing shows even better on my mac, when you move the firefox window so that the flash movie intersects your screenborder, halfway splitting vertically through the flash movie).</li>
<li>Copy and paste the textfield contents when the test is done, on both tests to my comments. Fill in the required 2 fields, and if you can, what type of graphics hardware your machine has.</li>
<li>Send this link to other people who are willing to test (and be part of the solution, making Flash a better place!).</li>
</ul>
<p><a href="http://unitzeroone.com/labs/tearing/opaque/FlashTearing.html" target="_blank"><strong>Test with wmode opaque</strong></a></p>
<p><a href="http://unitzeroone.com/labs/tearing/direct/FlashTearing.html" target="_blank"><strong>Test with wmode direct</strong></a></p>
<p><strong>[WARNING : if you are prone to visually induced epileptic fits, this might induce one. Don't run it then]</strong></p>
<p>(don&#8217;t forget to post to the comments).</p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2009/11/30/help-me-test-flash-vsync-and-screen-tearing/feed/</wfw:commentRss>
		<slash:comments>249</slash:comments>
		</item>
		<item>
		<title>Triangle3D : Small Flash 10 3D demo.</title>
		<link>http://unitzeroone.com/blog/2009/11/17/triangle3d-small-flash-10-3d-demo/</link>
		<comments>http://unitzeroone.com/blog/2009/11/17/triangle3d-small-flash-10-3d-demo/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 17:23:10 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[User Groups]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[flash3d]]></category>
		<category><![CDATA[triangle3d]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/?p=298</guid>
		<description><![CDATA[Over the last days I&#8217;ve spent some time twittering back and forth with Eugene. His supershape demo is very cool and we spent some time &#8216;tweeting&#8217; about shaders. This lead me to upload and twitter one of my experiments which &#8230; <a href="http://unitzeroone.com/blog/2009/11/17/triangle3d-small-flash-10-3d-demo/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="mceTemp">
<dl class="wp-caption alignnone" style="width: 440px;">
<dt class="wp-caption-dt"><a href="http://www.unitzeroone.com/labs/Triangle3DOld/Alt.html"><img title="Triangle3DMorph" src="http://www.unitzeroone.com/images/Triangle3DMorph.jpg" alt="Screenshot from the realtime Flash3D demo." width="430" height="234" /></a></dt>
</dl>
</div>
<p><a href="http://www.unitzeroone.com/labs/Triangle3DOld/"><img class="alignnone" src="http://www.unitzeroone.com/images/Triangle3DMorphOriginal.jpg" alt="" width="430" height="195" /></a></p>
<p>Over the last days I&#8217;ve spent some time <a href="http://www.twitter.com/UnitZeroOne" target="_blank"><strong>twittering</strong></a> back and forth with <a href="http://blog.inspirit.ru" target="_blank"><strong>Eugene</strong></a>. His <strong><a href="http://blog.inspirit.ru/?p=364" target="_blank">supershape demo</a></strong> is very cool and we spent some time &#8216;tweeting&#8217; about shaders. This lead me to upload and twitter one of my experiments which I used as part of my FOTB / MAX presentation. Judging by the huge number of retweets it seems people enjoyed it a lot, so I figured that it was worth a blog post. I started working on this experiment a while back after toying around with OpenGL, OpenFrameworks and audio reactive shapes and that inspired me to do something similar in Flash. This is an unfinished demo as it lead me to pursue something else, at which point I stopped working on it.</p>
<p>In the session where this came from, specifically this part, I shared information about the path of yet another demo, where this experiment led me too. Some of you who attended Flash on the Beach, might recall it from the Adobe keynote, where it was aptly named &#8220;milky ball&#8221;.  I&#8217;ll present on it one more time on the 3rd of December at the <strong><a href="http://www.adobeusergroupxl.nl" target="_blank">AUG XL event</a></strong>, in Amsterdam. I&#8217;ll post more of the session&#8217;s demos with explanation, when I have the time.</p>
<p>I do want to clarify that the code base I&#8217;ve created for this, which I currently call Triangle3D, is not to be a new Papervision3D, Away3D, Alternativa3D, Infinity3D, Sandy3D, Null3D or Yogurt3D (I&#8217;m probably missing a couple, sorry, have your way in the comments). It&#8217;s my experimental playground of classes to play around, with no care for architecture restrictions or a generalized API. It&#8217;s all about me playing and enjoying. Pure experimentation of what can be achieved with Flash 3D and hoping to find something beautiful in it.</p>
<p><a href="http://www.unitzeroone.com/labs/Triangle3DOld/" target="_blank"><strong>Orignal unfinished demo</strong></a></p>
<p><a href="http://www.unitzeroone.com/labs/Triangle3DOld/Alt.html" target="_blank"><strong>Demo with adjusted lightmaps from my new mirrorball.</strong></a></p>
<p><a href="http://www.flickr.com/photos/unitzeroone/4102372725/" target="_blank"><strong>(here&#8217;s the shot of the mirrorball, on flickr).</strong></a></p>
<p>The music track is Sixtyten by Boards of Canada.</p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2009/11/17/triangle3d-small-flash-10-3d-demo/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>More play with Alchemy : Lookup table effects.</title>
		<link>http://unitzeroone.com/blog/2009/04/06/more-play-with-alchemy-lookup-table-effects/</link>
		<comments>http://unitzeroone.com/blog/2009/04/06/more-play-with-alchemy-lookup-table-effects/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 09:11:04 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[FITC]]></category>
		<category><![CDATA[Flash]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/?p=212</guid>
		<description><![CDATA[After the overwhelming response of posting the sources of 300.000 pixels with Alchemy and Pixelbender, I thought it would be nice to post some more from my session at FITC Amsterdam. First let&#8217;s take a look at what people have &#8230; <a href="http://unitzeroone.com/blog/2009/04/06/more-play-with-alchemy-lookup-table-effects/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.unitzeroone.com/labs/alchemyLookupTable/"><img class="alignnone" src="http://www.unitzeroone.com/images/lutEffect.jpg" alt="" width="430" height="140" /></a></p>
<p>After the overwhelming response of posting the sources of 300.000 pixels with Alchemy and Pixelbender, I thought it would be nice to post some more from my session at FITC Amsterdam.</p>
<p>First let&#8217;s take a look at what people have done in response of the previous sources.</p>
<p><a href="http://www.zozuar.org/pub/sierpinski-pusher/Main.swf" target="_blank"><strong>Yonatan Offek &#8211; Sierpinski Particles</strong></a></p>
<p><a href="http://www.peternitsch.net/blog/?p=166" target="_blank"><strong>Peter Nitsch &#8211; Alchemy Particles</strong></a></p>
<p><a href="http://www.derschmale.com/2009/03/23/experimenting-with-alchemy-of-smoke-milk-and-ink/"><strong>David Lenaerts &#8211; Smoke, Milk and Ink</strong></a></p>
<p><a href="http://www.rozengain.com/blog/2009/04/02/alchemy-experiment-incredibly-fast-plasma/" target="_blank"><strong>Dennis Ippel &#8211; Incredibly fast Plasma</strong></a></p>
<p><a href="http://blog.joa-ebert.com/2009/04/03/massive-amounts-of-3d-particles-without-alchemy-and-pixelbender/" target="_blank"><strong>Joa Ebert &#8211; Massive amounts of 3D particles without Alchemy and Pixelbender</strong></a></p>
<p>All the work in that list is incredible, but for this post, I&#8217;m most interested in the last 2. Joa&#8217;s work on getting AS3 up to speed with my Alchemy demo (Joa&#8217;s demo is actually faster then the Alchemy version on my machine) is incredible. And it also proves the one thing I tried to convey in my blog post <a href="http://www.unitzeroone.com/blog/2008/11/28/adobe-alchemy-is-it-actionscript-heresy/"><strong>Adobe Alchemy, is it ActionScript Heresy ?</strong></a>.</p>
<p><span id="more-212"></span></p>
<p>Joa&#8217;s optimization relies mostly on a linked list implementation to iterate over the particles, and using the <strong><a href="http://www.mikechambers.com/blog/2008/08/19/using-vectors-in-actionscript-3-and-flash-player-10/" target="_blank">Flash 10 Vector type</a></strong> to allow for faster access to write to screen. Another speed improvement over the Alchemy version is not using Pixelbender, but having both rotation and projection done in the same loop as drawing to screen. All in all, his result on this is pretty awesome.</p>
<p>Again, writing highly optimized ActionScript should enable you to do the same speedwise as Alchemy compiled code. There&#8217;s at least one definitive advantage which Alchemy has in that case. The first advantage in Alchemy lies is the fast ByteArray access (which currently only Alchemy and <strong><a href="http://www.ncannasse.fr/blog/virtual_memory_api" target="_blank">Haxe</a></strong> can use).</p>
<p>The second advantage is why I think we should have a better AS3 compiler. It is the use of a more advanced compiler. This reduces the need to *highly* optimize your code, although I&#8217;d always recommend doing that in any case. My demo&#8217;s here are meant of examples on how to use Alchemy, rather then to get the last bit of performance out. That, we&#8217;ll leave to PapervisionX work.</p>
<p>Now, as I said, for this post we would be looking at two of the responses on my earlier Alchemy demo, the second one being Dennis Ippel&#8217;s Fast Plasma effects. Plasma effects and Lookup Table efffects aren&#8217;t too different. <strong><a href="http://mrdoob.com/81/Flash_10_Shaders_Plane_Deformations" target="_blank">Ricardo Cabello</a></strong> did some experiments with them earlier, using Pixelbender. I worked on taking this type of effect and implementing it using Alchemy. Since that I had already done some experiments with them earlier, I thought it would be nice to release the sources, and see what you guys do with them. Maybe Joa feels like another shot of doing the same with ActionScript ?</p>
<p><a href="http://unitzeroone.com/labs/alchemyLookupTable/" target="_blank"><strong>Example</strong></a></p>
<p><strong><a href="http://unitzeroone.com/labs/alchemyLookupTable/lookupEffect.zip" target="_blank">Source</a></strong></p>
<p>Play around, let me know what you do with it, and make sure you check out Mr. Quilez his webpage, specifically, the article on <a href="http://iquilezles.org/www/articles/deform/deform.htm"><strong>Plane Deformations</strong></a>, where part of this code is derived from. If you want to optimize more, you *could* read <strong><a href="http://www.kebby.org/articles/h14a2.html" target="_blank">Kebby&#8217;s article F***ing learn to code again</a></strong>.</p>
<p>One more observation  : the difference between running this on Firefox on a Mac and just running it in the FlashPlayer is huge, even bigger then normal. Could someone from Adobe finally explain this ?</p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2009/04/06/more-play-with-alchemy-lookup-table-effects/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Flash 10, Massive amounts of 3D particles with Alchemy (source included).</title>
		<link>http://unitzeroone.com/blog/2009/03/18/flash-10-massive-amounts-of-3d-particles-with-alchemy-source-included/</link>
		<comments>http://unitzeroone.com/blog/2009/03/18/flash-10-massive-amounts-of-3d-particles-with-alchemy-source-included/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 15:26:12 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Work]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/?p=201</guid>
		<description><![CDATA[Pushing around +300.000 3D particles, realtime, on screen, using Flash ? No problem, if you are using Adobe Alchemy &#38; PixelBender to compile and run your code! During my session &#8220;professionally pushing pixels&#8221; at FITC Amsterdam this year, amongst other &#8230; <a href="http://unitzeroone.com/blog/2009/03/18/flash-10-massive-amounts-of-3d-particles-with-alchemy-source-included/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a title="See the demo." href="http://www.unitzeroone.com/labs/alchemyPushingPixels/" target="_blank"><img class="alignnone size-full wp-image-202" title="pushingpixels" src="http://unitzeroone.com/wordpress/wp-content/uploads/pushingpixels.jpg" alt="pushingpixels" width="430" height="140" /></a></p>
<p>Pushing around +300.000 3D particles, realtime, on screen, using Flash ? No problem, if you are using Adobe Alchemy &amp; PixelBender to compile and run your code!</p>
<p>During my session &#8220;<em>professionally pushing pixels</em>&#8221; at FITC Amsterdam this year, amongst other things, I talked about how to best utilize parts of the Flash Player to get top performance. This is one of the examples I showed. What you are seeing in this example, is +300.000 particles being 3D transformed, projected and draw to 2D. And it does so at quite a good framerate (well, it&#8217;ll depend on your machine too).</p>
<p>So, how do we achieve this ? The answer is a combination of PixelBender and Alchemy.</p>
<p><span id="more-201"></span></p>
<p><strong>First, let&#8217;s look at the 3D transformation and projection.</strong></p>
<p>Flash 10 has a number of native features to allow for 3D transformation and projection. You&#8217;ll find that this is a combination of using the Vector, Vector3D, Matrix3D, PerspectiveProjection, etc. Although these features are great, we can&#8217;t use them in combination with Alchemy easily. I&#8217;ll explain why later, for now, let&#8217;s look at an alternative method to do the projection.</p>
<p>Where oh where in the Flash Player do we have a method of doing very fast math ? The answer is; pixelbender! Although Pixelbender is normally used for image based manipulation, you can make it do any type of number-crunching which is able to be executed in parallel and without loops.</p>
<p>To calculate rotations and projecting our 3D data, we use Pixelbender in &#8220;ShaderJob&#8221; mode. When using pixelbender in image based mode, it operates in 8 bits per channel. Thankfully, when using it with a ShaderJob, it allows 32 bits precision per channel for the data processing. Since 8 bit precision wouldn&#8217;t be enough for this example, we use a shaderjob.</p>
<p>The VertexProjector pixelbender kernel, included with the source is a simple way of transforming and projecting vertices (representing particles, in this case) in 3D space. We feed this kernel a bytearray of x,y,z paired data, and execute the shaderjob. It then returns the data as a bytearray, in px, py, pz format.</p>
<p><strong>Drawing things to screen.</strong></p>
<p>Now we have all the 2D projected 3D data, we need to draw things to screen, and we have to do so as quickly as possible. This step is traditionally called rasterization. In AS3, you&#8217;re most likely to use getPixel when drawing on a per pixel basis. Doing so in a loop for 300.000 pixels turns out to be very slow. The solution for this would be to optimize that loop as much as possible. Either by writing your own bytecode, or maybe writing your own post-processor for you code, before you compile. But we don&#8217;t have too, since Adobe Alchemy exists.</p>
<p>As you can read in <strong><a href="http://www.unitzeroone.com/blog/2008/11/28/adobe-alchemy-is-it-actionscript-heresy/" target="_blank">my earlier post</a></strong> about Adobe Alchemy, I openly questioned why it was so speedy, as compared to regularly compiled ActionScript 3 code. Although the answer is rather complex, the combination of C Based code, the LLVM compiler and &#8220;Alchemy Virtual Memory&#8221; are the base of this. The large difference between Alchemy compiled actionscript and regular compiled Actionscript can be further explained by the regular AS3 compiler not doing any optimisation. This example shows off those performance increases.</p>
<p>One thing to worry about when using Alchemy in your ActionScript projects is marshalling. You can read Branden Hall&#8217;s post on Alchemy <strong><a href="http://www.automatastudios.com/2008/11/21/understanding-adobe-alchemy/" target="_blank">for more info on that</a></strong>. Since we wouldn&#8217;t be able to marshal 300.000 vertices from a Vector.&lt;Number&gt; in AS3 to our alchemy code, we need to find a better solution. This is exactly why we are using Pixelbender and more-over, the bytearray data.</p>
<p>It is possible to manipulate the memory Alchemy uses in the runtime. This memory is represented as an AS3 ByteArray object. If we directly write and get our data from this memory block, no marshalling is needed. Although this means not all things can be done this way, for some things, this can be very useful. For instance, getting large blocks of data, like images and bytearrays of coordinates.</p>
<p>Getting all these 3D particles to screen is simply 1 inner loop. While we would normally call setPixel for that, in Alchemy code, we don&#8217;t have that luxury. Instead of that, we write directly to our screenbuffer memory, which is represented as a set of int&#8217;s. Here, one more problem comes into play. <a href="http://en.wikipedia.org/wiki/Endianness" target="_blank"><strong>Endianess</strong></a>, defines the byte ordering for a set of data. Alchemy uses little-endianess for it&#8217;s internal memory representation. Specificall, it uses a small class called LEByteArray. This class extends ByteArray and ensures no changes are made to the endianess of the memory. Makes sense, since otherwise your code would blow up.</p>
<p>Writing to the screen is then a piece of cake. We take the alchemy processed data from it&#8217;s memory, and write it to a bitmapdata using the formerly much less usable setPixels() command. It&#8217;s amazing to see how fast this is.</p>
<p>Look at the <strong><a href="http://www.unitzeroone.com/labs/alchemyPushingPixels/" target="_blank">example here</a></strong>, and download <strong><a href="http://www.unitzeroone.com/labs/alchemyPushingPixels/alchemyParticlePusher.zip" target="_blank">the full sourcecode</a></strong> here. As you can see from the example, the difference between doing this with regular ActionScript versus Alchemy nears a 5 fold speed increase.</p>
<p>Thanks to <strong><a href="http://bit-101.com" target="_blank">Keith Peters</a></strong>, for providing me with the 3D Strange Attractor code! And additional thanks to <strong><a href="http://mrdoob.com" target="_blank">Mr.Doob</a></strong> for the stats object.</p>
<p>In future I&#8217;ll be posting more demos of the technology. Amongst which there will be one appliance for the future version of Papervision3D, <a href="http://blog.papervision3d.org/2009/03/16/papervisionx-what-it-is-and-what-it-isnt/" target="_blank"><strong>PapervisionX</strong></a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2009/03/18/flash-10-massive-amounts-of-3d-particles-with-alchemy-source-included/feed/</wfw:commentRss>
		<slash:comments>84</slash:comments>
		</item>
		<item>
		<title>Playing with Alchemy : C64 Music Playback on Flash 10.</title>
		<link>http://unitzeroone.com/blog/2009/02/12/playing-with-alchemy-c64-music-playback-on-flash-10/</link>
		<comments>http://unitzeroone.com/blog/2009/02/12/playing-with-alchemy-c64-music-playback-on-flash-10/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 17:15:58 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Cool Sites]]></category>
		<category><![CDATA[Examples]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Random Thoughts]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[alchemy]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c64]]></category>
		<category><![CDATA[opcodes]]></category>
		<category><![CDATA[sid]]></category>
		<category><![CDATA[virtual machine]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/?p=176</guid>
		<description><![CDATA[It&#8217;s been silent here. Next to tripping to Tokyo to speak at Adobe MAX in Januari and doing some small jobs, I&#8217;m doing a very, very cool Flash 10 Project utilizing the upcoming Papervision for Flash 10. For some optimization &#8230; <a href="http://unitzeroone.com/blog/2009/02/12/playing-with-alchemy-c64-music-playback-on-flash-10/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.unitzeroone.com/labs/tinysidflash/" target="_blank"><img class="alignnone size-full wp-image-180" title="6581" src="http://unitzeroone.com/wordpress/wp-content/uploads/6581.jpg" alt="6581" width="430" height="195" /></a></p>
<p>It&#8217;s been silent here. Next to tripping to Tokyo to speak at Adobe MAX in Januari and doing some small jobs, I&#8217;m doing a very, very cool Flash 10 Project utilizing the upcoming Papervision for Flash 10. For some optimization parts I&#8217;ve been looking into using Alchemy as an easy way to write optimized bytecode. As opposed to what some people took from my previous post on Alchemy, I don&#8217;t hate Alchemy. My point there was that if Alchemy can perform that well, so should ActionScript be able to, with the standard compiler.</p>
<p><span id="more-176"></span></p>
<p>Now, that being said, all work and no play makes jack a dull boy. With no time to spare during the morning, daytime and evening, I took the laptop with me to bed last night, and decided to do something I didn&#8217;t do before, port something with <strong><a href="http://labs.adobe.com/technologies/alchemy/" target="_blank">Adobe Alchemy</a></strong>. I decided upon a long time thing on my wish list; SID Playback in Flash. <strong><a href="http://en.wikipedia.org/wiki/MOS6581" target="_blank">What is SID ?</a></strong> Well, SID stands for Sound Interface Device, referring to the MOS6581 and it&#8217;s a programmable audiochip as used in the Commodore 64 and Commodore 128. I grew up with the Commodore 64, and the audio it produces is still something I hold dearly. You are quite likely to have heard a SID chip before, if you listen to the radio, as it is quite a possible you&#8217;ve heard one of these baby&#8217;s scream. Good recent examples are :</p>
<p><strong><a href="http://www.youtube.com/watch?v=8cWL89fjfUU" target="_blank">Bastian &#8211; You&#8217;ve got my love.</a></strong> (the beat in this song comes from Jeroen Tel&#8217;s Rubicon).</p>
<p><strong><a href="http://www.youtube.com/watch?v=zusMLb44qXE" target="_blank">Nelly Furtado &#8211; Do It</a></strong> (controversy all around, <strong><a href="http://en.wikipedia.org/wiki/2007_Timbaland_plagiarism_controversy" target="_blank">Timbaland blatantly stole Glenn Rune Gallefoss&#8217;s version of Acid Jazzed Evening</a></strong>).</p>
<p><strong><a href="http://www.youtube.com/watch?v=1teWn-HDUv4" target="_blank">De Jeugd van Tegenwoordig &#8211; Hollereer</a></strong> (Produced by Bastian, C64 lover himself).</p>
<p>My interest was more playing back the old C64 tunes from games and demos. Keep in mind, an average SID file is about 2kilobyte to 10kilobyte; a perfect Small Web Format for all your music during preloading needs <img src='http://unitzeroone.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . Now, this is something I have been working on before in Flash 9, using the <strong><a href="http://osflash.org/fc64" target="_blank">FC64 project</a></strong>, the amazing Flash C64 emulation effort by Claus Wahlers and Darron Schall. Last year, I even made a start with porting FC64 to Flash 10, but that needed to be dropped in favor of actual client work. SID Playback is something different from playing back .mod .xm or .mid files, as the SID chip doesn&#8217;t do much on it&#8217;s own. Essentially, a .SID file is an executable meant to be ran on the 6510, the Commodore 64&#8242;s CPU. So to playback the file, you not only need to emulate the SID chip, but also the 6510 and the needed registers / memory.</p>
<p>Software emulation of the SID chip has been around for a while, and all modern platforms have a way of playback SID files. Winamp plugins, command line utilities for conversion, it&#8217;s all there. As is there opensource code to do this. There&#8217;s libraries for most major languages. So, after a bit of research, I decided upon the <strong><a href="http://www.rsinsch.de/?id=7298b" target="_blank">Linux version of TinySid</a></strong>. This library is small enough and well optimized. It looked simple to port, so I went at it. All in all, 4 hours later, I had this baby up and running! (And an unhappy girlfriend who isn&#8217;t into the nerd thing, nor is she into listening to chiptunes whilst trying to sleep). Considering my very rusty C and a little hack around I had to do for the audio output, Alchemy shows off it&#8217;s feathers here. Many kudo&#8217;s to the Alchemy and Flash Player team for this effort. Just now I spent half an hour building a tiny interface using <strong><a href="http://www.bit-101.com/blog/?p=1217" target="_blank">Keith Peter&#8217;s Minimal Components</a></strong>, and collected some songs; and here it is.</p>
<p><strong><a href="http://www.unitzeroone.com/labs/tinysidflash/" target="_blank">TinySidFlash (open link, requires Flash 10).</a></strong></p>
<p>My favorites : Politik and Science (A C64 version of Coldplay&#8217;s the Scientist), Morphing and Turbo. Yes, I love Dane&#8217;s tunes!</p>
<p>There&#8217;s no code yet, as this is still very rough and unfinished work. I&#8217;m pretty sure that when I get time again, I&#8217;ll have a go at LibSidPlay instead, since the overall emulation in that library is a lot better.</p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2009/02/12/playing-with-alchemy-c64-music-playback-on-flash-10/feed/</wfw:commentRss>
		<slash:comments>43</slash:comments>
		</item>
		<item>
		<title>Some experiments with the FP10 3D api. Shading &amp; Speed</title>
		<link>http://unitzeroone.com/blog/2008/11/24/some-experiments-with-the-fp10-3d-api-shading-speed/</link>
		<comments>http://unitzeroone.com/blog/2008/11/24/some-experiments-with-the-fp10-3d-api-shading-speed/#comments</comments>
		<pubDate>Mon, 24 Nov 2008 22:48:08 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[Papervision3D]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Work]]></category>
		<category><![CDATA[10]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[flash10]]></category>
		<category><![CDATA[flashplayer]]></category>
		<category><![CDATA[fp10]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/?p=163</guid>
		<description><![CDATA[Behind the scenes I&#8217;ve been insanely busy for the last months. But just to keep you posted on some progess on my side, here&#8217;s some demos of me playing around with Flash Player 10&#8242;s 3D API&#8217;s. I&#8217;ll keep this short, &#8230; <a href="http://unitzeroone.com/blog/2008/11/24/some-experiments-with-the-fp10-3d-api-shading-speed/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div id="attachment_165" class="wp-caption alignnone" style="width: 440px"><a href="http://unitzeroone.com/wordpress/wp-content/uploads/elephant1.jpg"><img class="size-full wp-image-165" title="elephant" src="http://unitzeroone.com/wordpress/wp-content/uploads/elephant1.jpg" alt="A smooth shaded elephant." width="430" height="220" /></a><p class="wp-caption-text">A smooth shaded elephant.</p></div>
<p>Behind the scenes I&#8217;ve been insanely busy for the last months. But just to keep you posted on some progess on my side, here&#8217;s some demos of me playing around with Flash Player 10&#8242;s 3D API&#8217;s.</p>
<p>I&#8217;ll keep this short, here&#8217;s some demos.</p>
<p>Some tests with shading : <a href="http://unitzeroone.com/labs/fp10_shadetests/Test_320_Faces.swf" target="_blank"><strong>1</strong></a>, <a href="http://unitzeroone.com/labs/fp10_shadetests/Test_1121_Faces.swf" target="_blank"><strong>2</strong></a>, <a href="http://unitzeroone.com/labs/fp10_shadetests/Test_1600_Faces.swf" target="_blank"><strong>3</strong></a>, <a href="http://unitzeroone.com/labs/fp10_shadetests/Test_1920_Faces.swf" target="_blank"><strong>4</strong></a>, <a href="http://unitzeroone.com/labs/fp10_shadetests/Test_3600_Faces.swf" target="_blank"><strong>5</strong></a>, <a href="http://www.unitzeroone.com/labs/fp10_shadetests/Test_10150_Faces.swf" target="_blank"><strong>6</strong></a></p>
<p>You&#8217;ll notice that the speed slows down when you go up in the number of examples. The amount of triangles increase per example. Since shading is still one of the most heavy appliances of any 3D engine, I thought it would be good to start out testing that, and see how it would work in a realistic 3D engine environment.</p>
<p>Next, this is not adviced to look at if you get car-sick easily&#8230;..<a href="http://unitzeroone.com/labs/fp10_speed/Main.swf" target="_blank"><strong>a pure speed test</strong></a>.</p>
<p>A bit slower then it could run using any of the new wmodes, but for speeds sake, we&#8217;re getting there.</p>
<p>Source code not available yet. First I&#8217;m looking at how to optimize. And yes, I&#8217;m working hard on a new version of Papervision3D, with the rest of the team. Soon I&#8217;ll post some better examples, including a <a href="http://en.wikipedia.org/w/index.php?title=Binary_Space_Partition" target="_blank"><strong>BSP</strong></a> example.</p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2008/11/24/some-experiments-with-the-fp10-3d-api-shading-speed/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>OpenSource Image Dithering for AS3. (demo+source).</title>
		<link>http://unitzeroone.com/blog/2008/05/06/opensource-image-dithering-for-as3-demosource/</link>
		<comments>http://unitzeroone.com/blog/2008/05/06/opensource-image-dithering-for-as3-demosource/#comments</comments>
		<pubDate>Tue, 06 May 2008 15:47:28 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Examples]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[dithering]]></category>
		<category><![CDATA[halftone]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[processing]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/?p=155</guid>
		<description><![CDATA[Intro As promised in my previous post, here&#8217;s a small opensource project from my side. It&#8217;s tiny, really, but I hadn&#8217;t seen an ActionScript implementation of any form of Image dithering before. Dithering&#8230;.what ? Just a brief explanation what dithering &#8230; <a href="http://unitzeroone.com/blog/2008/05/06/opensource-image-dithering-for-as3-demosource/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a title="Image Dithering" href="http://www.unitzeroone.com/examples/ImageDithering/index.html" target="_blank"><img class="alignnone size-full wp-image-156" title="Lena normal and Lena Dithered" src="http://unitzeroone.com/wordpress/wp-content/uploads/lenas.jpg" alt="" width="430" height="200" /></a></p>
<p><strong>Intro<br />
</strong></p>
<p>As promised in my previous post, here&#8217;s a small opensource project from my side. It&#8217;s tiny, really, but I hadn&#8217;t seen an ActionScript implementation of any form of Image dithering before.</p>
<p><strong>Dithering&#8230;.what ? </strong></p>
<p>Just a brief explanation what dithering in this context means. <a href="http://en.wikipedia.org/wiki/Dithering" target="_blank">From wikipedia</a> :</p>
<p><em>&#8220;<strong>Dither</strong> is an intentionally applied form of noise, used to randomize quantization error, thereby preventing large-scale patterns such as contouring that are more objectionable than uncorrelated noise.&#8221;</em></p>
<p>Words to take note of in that sentence are quantization, and &#8220;intentionally applied form of noise&#8221;. In our case quantization is the removal or swapping of colors. The form of noise applied differs over the several implementations and in so called &#8220;ordered dithering&#8221; it&#8217;s hardly noise, rather a carefully chosen threshold matrix.</p>
<p><strong>Dithering, why ? </strong></p>
<p>Dithering imagery has been around for some time. Put a close eye to any black and white printed newspaper&#8217;s pictures and you&#8217;ll see the effect.</p>
<p>It&#8217;s basically been around a lot longer then I have in my 28 years of life&#8230;that&#8217;s for sure. I first learned terms like &#8220;ordered dithering&#8221; and &#8220;Floyd-Steinberg Error Diffusion&#8221; in my young and early days on the Amiga hardware. See, in those days computer hardware wasn&#8217;t capable of displaying the huge arrays of colours like now-a-days. Since you then had few colours to spare (a typical amiga workbench ran at 16 to 128 colours or so), you needed to be creative to get yourself a nicely pimped desktop image, whilst still sparing colours for your icons.</p>
<p>A better example of a dithering implementation for our industry is probably that checkbox when you want to save for web in Photoshop, using GIF. Or when you print something on a pure black and white printer.</p>
<p>Conclusion; dithering is normally used to create the illusion of tones on a device which is otherwise not capable of displaying it. So why port this to our ARGB/32Bit enabled Flash Player ? Part of the reason why I worked on this is because I just like the aesthetic of the effect. It just brings back wonderful memories of pimping my Amiga desktop.</p>
<p><strong>Dithering in AS3</strong></p>
<p>So, the algorithms for dithering are really quite simple. I was playing around with <span style="text-decoration: line-through;">hydra</span> Pixel Bender and had some ideas on converting some old algorithms to have them run in realtime. Then I thought I could make this run in realtime on Flash 9. So, first I did a version of the Algo in pure AS3. I played around with converting it to something fast enough to run at at least 20 frames per second on an average machine&#8230;and painfully failed. The remains are the AS3 version (<span style="text-decoration: line-through;">hydra</span> Pixel Bender version still in progress)&#8230;.and I decided to clean that up a bit, and have it released as an OS project for anyone to use.</p>
<p>Currently it only contains so-called error-diffusion based ditherers. They make the most sense anyway, since the ordered ditherers really have nasty visual sideeffects, like <a title="Raster" href="http://www.pl32.com/tutorial/sraster/sraster.htm" target="_blank">Bayer&#8217;s crosshatches</a>. Check the variants out in this little demo application using the class.</p>
<p><a href="http://www.unitzeroone.com/examples/ImageDithering/index.html" target="_blank">The Demo</a> : try and use &#8220;No Dithering&#8221; first to see the effects of regular palette conversion.</p>
<p><a href="http://code.google.com/p/imageditheringas3/" target="_blank">The Source</a></p>
<p>Usage :</p>
<p>ImageDithering.dither(bitmapData, type, levels, grayscale);</p>
<p>Where :</p>
<p><strong>BitmapData</strong> is the image to be manipulated.</p>
<p><strong>Type</strong> is the form of dithering, currently supported :</p>
<ol>
<li>ImageDitheringType.FLOYD_STEINBERG</li>
<li>ImageDitheringType.FALSE_FLOYD_STEINBERG</li>
<li>ImageDitheringType.STUCK</li>
<li>ImageDitheringType.NO_DITHER</li>
</ol>
<p><strong>Levels</strong> is the amount of colour levels to quantize to per channel.</p>
<p><strong>Grayscale</strong> is a boolean indicating whether to convert the image to grayscale before the process is ran.</p>
<p>Right click and viewsource on the example to see how it&#8217;s implemented in Flex.</p>
<p>Quick update : <a title="Quasimondo" href="http://www.quasimondo.com/" target="_blank">Mario Klingemann</a>, working on <a href="http://a.viary.com/blog/posts/a-video-of-peacock-in-action" target="_blank">Aviary&#8217;s Peacock</a> did a <a href="http://flickr.com/photos/quasimondo/2471315060/" target="_blank">quick test with it</a>. My effort had some use anyway!</p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2008/05/06/opensource-image-dithering-for-as3-demosource/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Papervision3D + Water Simulation = Waterballs</title>
		<link>http://unitzeroone.com/blog/2008/03/19/papervision3d-water-simulation-waterballs/</link>
		<comments>http://unitzeroone.com/blog/2008/03/19/papervision3d-water-simulation-waterballs/#comments</comments>
		<pubDate>Tue, 18 Mar 2008 23:49:48 +0000</pubDate>
		<dc:creator>UnitZeroOne</dc:creator>
				<category><![CDATA[Cool Sites]]></category>
		<category><![CDATA[Examples]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Papervision3D]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Work]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Ball]]></category>
		<category><![CDATA[Water]]></category>

		<guid isPermaLink="false">http://www.unitzeroone.com/blog/2008/03/19/papervision3d-water-simulation-waterballs/</guid>
		<description><![CDATA[You always have projects lying around that are to be finished&#8230;but probably never have the time for&#8230; Today Exey Panteleev posted some creative use of Papervision3D and the Shaders in 2.0. Accompanying to his post he asked if it would &#8230; <a href="http://unitzeroone.com/blog/2008/03/19/papervision3d-water-simulation-waterballs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.unitzeroone.com/blog/2008/03/19/papervision3d-water-simulation-waterballs/waterball-2/" target="_blank" rel="attachment wp-att-150" title="Waterball 2"><img src="http://unitzeroone.com/wordpress/wp-content/uploads/waterball2.jpg" alt="Waterball 2" /></a></p>
<p>You always have projects lying around that are to be finished&#8230;but probably never have the time for&#8230;</p>
<p>Today <strong><a href="http://exey.ru/blog/home/fluid-simulation-pv3d-and-away3d" title="Exey's blog" target="_blank">Exey Panteleev</a></strong> posted <strong><a href="http://www.nabble.com/Fluid-Simulation-3D---Water-to16130437.html" target="_blank">some creative use of Papervision3D</a></strong> and the Shaders in 2.0. Accompanying to his post he asked if it would be possible to run water simulation with Papervision3D&#8230;.</p>
<p><em>Actually, yes&#8230;</em><br />
<strong><a href="http://www.unitzeroone.com/papervision/waterBump/bin-release/WaterBall.swf" title="Waterball_1" target="_blank">Water Ball Experiment 1</a> </strong><strong><a href="http://www.unitzeroone.com/papervision/waterBall2/bin-release/WaterBall.swf" title="Waterball_2" target="_blank">Water Ball 2(cpu burner alert!)</a></strong></p>
<p>As one of those things I never finished and probably don&#8217;t have time to finish within the next month or so, I have two examples of Papervision3D running interactive water on top of a sphere.</p>
<p>Disclaimer : these things are hacked together experiments from a couple of months ago&#8230;as a result performance isn&#8217;t to good. I&#8217;m sure that given some time they can run smooth, without burning your cpu to the ground. Hope you enjoy anyway <img src='http://unitzeroone.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://unitzeroone.com/blog/2008/03/19/papervision3d-water-simulation-waterballs/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

