<?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>dispatchEvent()™ &#187; Architecture</title>
	<atom:link href="http://dispatchevent.org/category/architecture/feed/" rel="self" type="application/rss+xml" />
	<link>http://dispatchevent.org</link>
	<description>Collective thoughts on the Flash Platform, iOS, Unity, and any other technology we use.</description>
	<lastBuildDate>Tue, 07 Feb 2012 19:22:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Simple Flow Chart for a &#8220;Simon-Says&#8221; Memory Game</title>
		<link>http://dispatchevent.org/mims/simple-flow-chart-for-a-simon-says-memory-game/</link>
		<comments>http://dispatchevent.org/mims/simple-flow-chart-for-a-simon-says-memory-game/#comments</comments>
		<pubDate>Fri, 14 Jan 2011 03:45:26 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Videogames]]></category>
		<category><![CDATA[diagram]]></category>
		<category><![CDATA[flowchart]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[simon]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=868</guid>
		<description><![CDATA[This is just a quick little flow-chart. A project I&#8217;m working on includes a &#8216;Simon-says&#8217; type game. I thought I&#8217;d share my notes on how the game logic will work. Update: Here&#8217;s my quick prototype (before skinning)]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2011/01/SimonFlowchart.png"><img src="http://dispatchevent.org/wp-content/uploads/2011/01/SimonFlowchart-300x250.png" alt="" title="SimonFlowchart" width="300" height="250" class="alignnone size-medium wp-image-872" /></a><br />
This is just a quick little flow-chart. A project I&#8217;m working on includes a &#8216;Simon-says&#8217; type game. I thought I&#8217;d share my notes on how the game logic will work. </p>
<p>Update: <a href="http://zomgamez.com/games/simon/">Here&#8217;s my quick prototype</a> (before skinning)</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/simple-flow-chart-for-a-simon-says-memory-game/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>IDisplayObject? &#8211; Getting around the lack of an interface for the DisplayObject in Flash</title>
		<link>http://dispatchevent.org/mims/idisplayobject/</link>
		<comments>http://dispatchevent.org/mims/idisplayobject/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 02:27:22 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[displayobject]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[idisplayobject]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[workaround]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=838</guid>
		<description><![CDATA[Interfaces are amazing things. When I was young and green, I didn&#8217;t understand their purpose, but after working with them for a while, I will defend their use to the end. I try to create lots of interfaces early on &#8230; <a href="http://dispatchevent.org/mims/idisplayobject/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2010/03/DisplayObject_subclasses.png"><img class="alignnone size-medium wp-image-840" title="DisplayObject_subclasses" src="http://dispatchevent.org/wp-content/uploads/2010/03/DisplayObject_subclasses-300x156.png" alt="" width="300" height="156" /></a></p>
<p>Interfaces are amazing things.  When I was young and green, I didn&#8217;t understand their purpose, but after working with them for a while, I will defend their use to the end. I try to create lots of interfaces early on in my projects and I find that by keeping things flexible, it saves more time despite the extra typing, pardon the double entendre.</p>
<p>But this is not an article about why interfaces are so great. No, this is an article about the mysterious gap in the Flash Player API with regards to an interface for DisplayObjects. If you have a class typed as something like <code>IView</code>, there&#8217;s no way to enure that <code>IView</code> can be a parameter of display list functions like <code> addChild()</code>.</p>
<p><span id="more-838"></span>Why can&#8217;t we guarantee that something is a DisplayObject through interfaces?Â There is a practical answer. The inner workings of the Flash Player are slowing unfolding to us with each version. We now have low level access to sound, byte streams, and text rendering. However, the display list still relies exclusively on one of the only truly abstract classes in ActionScript 3.0, the DisplayObject. Because a low-level drawing engine is not exposed to AS3 programmers, we don&#8217;t know how it works and we cannot guarantee through an interface that an arbitrary class can be drawn.</p>
<p>Fortunately, there are some workarounds that can help, each with their own strengths and weaknesses. Personally, I think #2 is the way to go. It&#8217;s practically dripping with polymorphic goodness.</p>
<ol>
<li>
<h3>Make your interface inherit from IBitmapDrawable and IEventDispatcher</h3>
<p>DisplayObject is the only class that uses both of these two interfaces so by combining them in your interface, you can sort of be sure you&#8217;re working with a DisplayObject. Still, this is my least favorite solution</p>
<h4>Pros:</h4>
<ul>
<li>Uses interfaces exclusively.</li>
<li>Only a DisplayObject would implement both of these.</li>
</ul>
<h4>Cons:</h4>
<ul>
<li>There&#8217;s nothing to stop you from using this to create a class that isn&#8217;t a DisplayObject and that could cause problems.</li>
<li>You would still have to type cast to DisplayObject to use this as an argument for <code>addChild()</code>.</li>
</ul>
</li>
<li>
<h3>Create an interface that exposes a method to return the object as a DisplayObject</h3>
<p>My personal favorite solution. It not only solves the problem of guaranteeing that a class can go in the display list, it doesn&#8217;t even require that the class be a DisplayObject.</p>
<p>Here&#8217;s an example of what this would look like. <a href="http://gist.github.com/332408">IDisplayObject.as</a></p>
<h4>Pros:</h4>
<ul>
<li>Flexible solution that conforms to good OOD principles.</li>
<li>Uses interfaces exclusively.</li>
<li>Easy to apply. You can usually implement it with a single line of code: <code>return this;</code></li>
</ul>
<h4>Cons:</h4>
<ul>
<li>Requires you to use <code>asDisplayObject()</code> every time you want to use the object as a DisplayObject.</li>
<li>Calling <code>foo.asDisplayObject()</code> would throw an exception if <code>foo</code> was null so additional checks may be necessary.</li>
</ul>
</li>
<li>
<h3>Use an <a href="http://en.wikipedia.org/wiki/Abstract_type">abstract class</a> that inherits from DisplayObject</h3>
<p>Not an ideal solution primarily because Flash doesn&#8217;t have true abstract classes (although <a href="http://dispatchevent.org/mims/abstract-classes-in-as3/">there are workarounds</a>) but still totally valid.</p>
<h4>Pros:</h4>
<ul>
<li>Guarantees that the object is a DisplayObject. No type casting required.</li>
<li>Abstract classes can be treated virtually the same as an interface for practical use.</li>
</ul>
<h4>Cons:</h4>
<ul>
<li>No true abstract classes in Flash.</li>
<li>Not as flexible as an interface-based solution since it forces you to inherit from DisplayObject.</li>
</ul>
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/idisplayobject/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>MVC cheat sheet</title>
		<link>http://dispatchevent.org/mims/mvc-cheat-sheet/</link>
		<comments>http://dispatchevent.org/mims/mvc-cheat-sheet/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 23:55:08 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[link]]></category>
		<category><![CDATA[moock]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=666</guid>
		<description><![CDATA[Sometimes I forget the details of whether my Model should know about my Controller and that sort of thing. I found this little MVC cheat sheet on the internet that got me straightened out in a jiffy with step-by-step instructions. &#8230; <a href="http://dispatchevent.org/mims/mvc-cheat-sheet/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Sometimes I forget the details of whether my <a href="http://www.swinburne.edu.au/design/tutorials/P-flash/T-The-Model-View-Controller-Design-Pattern-in-Actionscript-3/ID-144/">Model</a> should know about my <a href="http://www.swinburne.edu.au/design/tutorials/P-flash/T-The-Model-View-Controller-Design-Pattern-in-Actionscript-3/ID-144/">Controller</a> and that sort of thing. I found this <a href="http://www.moock.org/lectures/mvc/">little MVC cheat sheet</a> on the internet that got me straightened out in a jiffy with step-by-step instructions. The page is actually the lecture notes from one of <a href="http://www.moock.org/">Colin Moock</a>&#8216;s presentations circa the <a href="http://books.google.com/books?id=wQlYlMuTbwYC&amp;dq=essential+actionscript+2.0&amp;printsec=frontcover&amp;source=bn&amp;hl=en&amp;ei=y4jBSdHXIoHasAOs4cX3Bg&amp;sa=X&amp;oi=book_result&amp;resnum=7&amp;ct=result">Essential AS 2.0</a> days but it&#8217;s still very useful. Those of you struggling with the lingo, replace Observer with EventDispatcher and ignore the junk about attachMovie. God, how did we ever write <a href="http://dispatchevent.org/mims/converting-as3-to-as2/">AS2</a>!?</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/mvc-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Q&amp;A &#8211; is, as, and type conversion</title>
		<link>http://dispatchevent.org/mims/is-and-as/</link>
		<comments>http://dispatchevent.org/mims/is-and-as/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 07:41:08 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[as]]></category>
		<category><![CDATA[coercion]]></category>
		<category><![CDATA[cs]]></category>
		<category><![CDATA[downcasting]]></category>
		<category><![CDATA[is]]></category>
		<category><![CDATA[lesson]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[types]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=591</guid>
		<description><![CDATA[A question from a reader gave me an excuse to write a huge rant about type conversions: I&#8217;m doing a little exercise in a book that makes a textfield in which each letter can only be entered once. Not very &#8230; <a href="http://dispatchevent.org/mims/is-and-as/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A question from a reader gave me an excuse to write a huge rant about type conversions:</p>
<blockquote><p>I&#8217;m doing a little exercise in a book that makes a textfield in which each letter can only be entered once. Not very useful, more of a teaching thing really. However there&#8217;s a bit of code that says:</p>
<p><code>var tf:TextField = event.target as TextField;</code></p>
<p>I don&#8217;t understand this at all! What the hell is <code>event.target as TextField</code>? Anyway here&#8217;s the full code for context&#8217;s sake:</p>
<pre lang="actionscript3">
package com.FoundationAS3.ch6 {

	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.events.TextEvent;

	public class PreventDefaultTest extends Sprite {

		public function PreventDefaultTest() {
			var tf:TextField = new TextField();
			addChild(tf);

			tf.width = stage.stageWidth;
			tf.height = stage.stageHeight;
			tf.type = TextFieldType.INPUT;
			tf.wordWrap = true;

			tf.addEventListener(TextEvent.TEXT_INPUT, onTextFieldTextInput);
		}

		private function onTextFieldTextInput(event:TextEvent):void {
			var tf:TextField = event.target as TextField;
			if (tf.text.indexOf(event.text) &gt; -1) {
				event.preventDefault();
			}
		}
	}
}
</pre>
<p>Thanks,<br />
-Neal
</p></blockquote>
<p>My response after the jump.<br />
<span id="more-591"></span><br />
Neal,</p>
<p>First of all, let me say that preventing the default event handler, e.g. for a <code>TextField</code>, is rarely used and isn&#8217;t worth spending a lot of time discussing.</p>
<p>On the other hand, the <code>as</code> operator (along with the <code>is</code> operator and the type cast) are totally useful and you should learn all about them. First, let me cover <code>is</code>:</p>
<h3>is</h3>
<p><code><a href="http://livedocs.adobe.com/flex/2/langref/operators.html#is">is</a></code> is an operator that evaluates whether some object <em>is</em> of a certain type. The syntax is <code>[object] is [type]</code>. The term &#8216;type&#8217; is similar but not interchangeable with &#8216;class&#8217;. A type can refer to not only the class of an object, but also the super-classes it extends and interfaces it implements. An example:</p>
<pre lang="actionscript3">
var sprite:Sprite = new Sprite();
trace(sprite is Sprite); // true, because the sprite object is an instance of Sprite
trace(sprite is DisplayObject); // true, Sprite is a subclass of DisplayObject
trace(sprite is MovieClip); // false, MovieClip is a subclass of Sprite.
trace(sprite is IEventDispatcher); // true, DisplayObject extends EventDispatcher which implements IEventDispatcher.
</pre>
<p>Note that sprite is not a MovieClip but a MovieClip is a Sprite. Because MovieClip extends Sprite and contains all the same methods and properties as Sprite but not the other way around. </p>
<p>Note: the <code>instanceof</code> operator commonly used in AS1/2 still exists in AS3 but is for all practical purposes deprecated by <code>is</code> (although still useful if you&#8217;re manipulating prototypes). <code>typeof</code> is also related but shouldn&#8217;t be used in place of <code>is</code> because it only returns strings for primitive data types like Object and String. In order to get the actual name of the class that an object is an instance of, you can use the <code>flash.utils.getQualifiedClassName()</code> global function.</p>
<h3>as</h3>
<p><code><a href="http://livedocs.adobe.com/flex/2/langref/operators.html#as">as</a></code> functions similarly to is except that it actually will attempt to coerce the object into the data type that you ask for. <a href="http://en.wikipedia.org/wiki/Type_conversion">Coercion</a>, AKA type conversion or casting, is the act of changing the data type of an object. </p>
<p>With the case from your book, an <code>Event</code> object has a <code>target</code> property which refers back to the object that originally dispatched the event. Since the <code>Event</code> object is designed to be sent out from all different types of objects, the target&#8217;s data type is <code>Object</code> (the mother of all the other classes). So, if the variable you&#8217;re defining is a TextField, you&#8217;re expecting an object with a <code>text</code> property. <code>Object</code>, doesn&#8217;t have a <code>text</code> property so you have a dilemma. The solution is to cast the object into the type you want it to be, basically forcing it to be more specific.</p>
<pre lang="actionscript3">
var textField:TextField = event.target; // Throws compile error because target is an Object not a TextField

var textField:TextField = event.target as TextField; // OK! as long as the event target actually is a text field
</pre>
<p>Going from a more generic type to a more specific type is called a <em>downcast</em>. Going from a more specific type to a more generic type is called an <em>upcast</em>. Upcasting in ActionScript, as with most other languages, is done automatically and is always safe. e.g. a Sprite can be used as a parameter for a function that requires a DisplayObject. Downcasting on the other hand is unsafe meaning that you can&#8217;t always guarantee that it will work. A DisplayObject is not necessarily a Sprite. </p>
<p>When an attempt to downcast with <code>as</code> fails, the value returned will be <code>null</code>:</p>
<pre lang="actionscript3">
var string:String = new String();
var textField:TextField = string as TextField // string can't be converted. textField will be set to null
</pre>
<p>If you&#8217;re not sure whether your object is the right type (and you should never assume it is) check to see if the value is null before proceeding:</p>
<pre lang="actionscript3">
var typedObject:TypedObject = mysteryObject as TypedObject;
if (typedObject != null) {
	// conversion was successful! do something with typedObject
} else {
	// conversion failed
}
</pre>
<h3>Type casts</h3>
<p>Another way to do this with slightly different results is by type casting. Type casting works with the syntax <code>Type(object)</code> and is functionally similar to <code>object as Type</code>. The only difference is with a type cast, you get a runtime error if the coercion fails.</p>
<p><code>var textField:TextField = TextField(event.target); // if event.target is a TextField, you're good. If not, you get an error.<br />
</code></p>
<p>you can also shortcut like this:</p>
<p><code>TextField(event.target).text = "foo";</code></p>
<h3>Conclusion</h3>
<p>Why are objects like <code>event.target</code> given such generic data types? The idea is that you want to minimize the requirements of a property, parameter, or function to maximize the number of objects that will qualify thus making your program more flexible. In other words, strive to use the most broadly defined data types that you can get away with. </p>
<p>For example, say you&#8217;re creating a simulator program for getting a person from their home to their job. You may be tempted to define your <code>modeOfTransportation</code> variable with a type of <code>Car</code>. But down the road the company you&#8217;re working for wants to create a more green image for themselves and suggests using alternative modes of transportation. If you&#8217;re code is based on Car, it&#8217;s limited in what you can do with it. However, if you had used a <code>Vehicle</code> type (includes Car, Bike, Motorcycle, Donkey) instead, you may not have had a problem. Using interfaces like <code>IConveyance</code> makes your program even more flexible because you can include non-vehicluar objects like MolecularTransporter, Feet, and CrowdSurfing as long as they satisfy the interface. In fact, I would suggest as an experiment that the next time you start a project, try coding all the interfaces first before you move on to coding specific classes. You&#8217;ll be surprised at how flexible it is and how it forces you to consider the roles of your classes from a higher level. </p>
<p>Though you should strive for generic types, sometimes you will need to get specific. If your program has a gas station simulator in it, the <code>fillTankOfVehicle()</code> method might require a <code>MotorVehicle</code> class (includes Car, Motorcycle, Plane) instead of simply <code>Vehicle</code>. Still, you should only get very specific when your program requires it. If you are making a racing program, use <code>F1RaceCar</code> only when a simple <code>Car</code> won&#8217;t cut it.</p>
<p>I hope this helps! This is definitely a difficult topic even for experienced programmers to grasp!</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/is-and-as/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Tip: Adding version checking to your external code library</title>
		<link>http://dispatchevent.org/mims/version-checking/</link>
		<comments>http://dispatchevent.org/mims/version-checking/#comments</comments>
		<pubDate>Fri, 24 Oct 2008 18:14:33 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[KitchenSync]]></category>
		<category><![CDATA[library]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=446</guid>
		<description><![CDATA[Since version 1.0 of a code library that I&#8217;m sure you&#8217;re tired of me talking about came out, I have been making steady updates, some of which break legacy code. I was also having trouble keeping track of which version &#8230; <a href="http://dispatchevent.org/mims/version-checking/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Since version 1.0 of <a href="http://kitchensynclib.googlecode.com" target="_blank">a code library that I&#8217;m sure you&#8217;re tired of me talking about</a> came out, I have been making steady updates, some of which break legacy code. I was also having trouble keeping track of which version of the library a particular demo was written for. In order to make sure that the new code library doesn&#8217;t cause unpredictable results for the old implementations I added a version check to the main class.</p>
<p>This version check is very simple. It checks a version number in the client code against a version number of the library (or external classes) when the main class of the library is initialized. It is also completely optional (so average users don&#8217;t need to mark up their code with version numbers).</p>
<p>Here&#8217;s an example:</p>
<p>Say you normally initialize your library using:</p>
<pre lang="actionscript3">MyLibrary.initialize();</pre>
<p>Which calls the initialize method:</p>
<pre lang="actionscript3">public static function initialize():void {
   // initialize library here
}</pre>
<p>If the external code changes unexpectedly (say through an SVN update) this could cause problems that are difficult to trace. The solution is to modify the initializer to match the client code version with the initializer version.</p>
<pre lang="actionscript3">public static const VERSION:String = "1.6";
public static function initialize(versionCheck:String = VERSION):void {
   if (versionCheck != VERSION) {
       throw new Error ("The version check failed! This library is version " + VERSION + ". Update your code or GTFO!");
   }
   // initialize library here
}</pre>
<p>And when you run the initializer, use the version number you&#8217;re expecting.</p>
<pre lang="actionscript3">MyLibrary.initialize("1.6");</pre>
<p>Some things to notice with this approach:</p>
<ul>
<li>I used a string instead of a number for the version number so that it would allow for sub-sub version numbers and other markers, e.g. &#8220;1.6.24 beta r545&#8243;</li>
<li>Because there is a default value for <code>versionCheck</code> in the initializer, providing a version number is optional. Using <code>MyLibrary.initialize()</code> will still work and throw no errors.</li>
<li>Unfortunately, there is not much you can do if the version numbers don&#8217;t match except to warn the client that the external code has changed. Still, I&#8217;ve found this to be very useful.</li>
</ul>
<p>The code for my initializer in its entirety after the jump&#8230;<br />
<span id="more-446"></span><br />
From <a href="http://code.google.com/p/kitchensynclib/source/browse/trunk/src/org/as3lib/kitchensync/KitchenSync.as">KitchenSync.as</a></p>
<pre lang="actionscript3">/**
* The current version of the library. Use this to verify that the library is the
* version that your software expects.
*/
public static const VERSION:String = "1.6";

/**
* Flag noting whether the engine has been initialized.
*/
private static var _initialized:Boolean = false;

/**
* Initializes the timing core for KitchenSync. Must be called before using any actions.
*
* @param frameRateSeed must be a DisplayObject that is added to the display list.
* @param versionCheck a string for the version you think you're using. e.g. 1.2 This is recommended
*                                         but not required. It will throw an error if you're using the wrong version of KS.
*/
public static function initialize(frameRateSeed:DisplayObject, versionCheck:String = VERSION):void
{       

	if (_initialized) {
		throw new IllegalOperationError("KitchenSync has already been initialized.");
	}
	if (versionCheck != VERSION) {
		throw new Error ("Version check failed. Please update to the correct version or to continue using this version (at your own risk) put the initialize() method inside a try{} block.");
	}

	// Initialization code omitted

	_initialized = true;
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/version-checking/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>See Mims present KitchenSync at Singularity &lt;head&gt; web conference!</title>
		<link>http://dispatchevent.org/mims/see-mims-present-kitchensync-at-singularity-head-web-conference/</link>
		<comments>http://dispatchevent.org/mims/see-mims-present-kitchensync-at-singularity-head-web-conference/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 19:53:21 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[In Real Life]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[KitchenSync]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=353</guid>
		<description><![CDATA[I&#8217;m honored to announce that I will be presenting at the &#60;head&#62; web conference (formerly called Singularity) this October 24-26th!Â  I&#8217;ll be talking about the basics of KitchenSync and what makes it so special. I&#8217;m very excited, not only to &#8230; <a href="http://dispatchevent.org/mims/see-mims-present-kitchensync-at-singularity-head-web-conference/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m honored to announce that I will be presenting at the <a href="http://headconference.com" target="_blank">&lt;head&gt; web conference</a> (formerly called Singularity) this October 24-26th!Â  <a href="http://www.headconference.com/speakers/mims-h-wright/" target="_blank">I&#8217;ll be talking</a> about the basics of <a href="http://kitchensynclib.googlecode.com">KitchenSync</a> and what makes it so special. I&#8217;m very excited, not only to be a speaker (it will be my first time to speak at a conference), but also to be an attendee. This is the first(?) ever web conference to be presented exclusively online&#8230; so I expect you to be there!</p>
<div style="text-align: center;"><a href="http://www.headconference.com/"><img src="http://www.headconference.com/images/buttons/button_468x60.gif" alt="&lt;head&gt; web conference: October 24-26, 2008" width="468" height="60" /></a><br/><br />
<strong style="font-size:50px">+</strong><br />
<a href="http://kitchensynclib.googlecode.com"><img class="alignnone" title="KitchenSyncLogo" src="http://as3lib.org/kitchensync/docs/img/KSLogo.png" alt="KitchenSync" width="338" height="72" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/see-mims-present-kitchensync-at-singularity-head-web-conference/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Papervision3D Part 3: Features continued</title>
		<link>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p3/</link>
		<comments>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p3/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 21:56:37 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=290</guid>
		<description><![CDATA[This posting is part 3 of a series. If you find that you&#8217;d rather start from the beginning, check out Part 1 and Part 2 first. In this post, I&#8217;ll cover Papervision animation, the ASCollada project, render statistics, performance optimization. &#8230; <a href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p3/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png"><img class="alignleft size-medium wp-image-289" src="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png" alt="" width="226" height="111" /></a>This posting is part 3 of a series. If you find that you&#8217;d rather start from the beginning, check out <a href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/">Part 1</a> and <a href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/">Part 2</a> first. In this post, I&#8217;ll cover Papervision animation, the ASCollada project, render statistics, performance optimization.</p>
<p><em><strong>Animation</strong></em><br />
Animation in Papervision3D can be performed the exact same way animation would be performed in 2D. Simply apply any tween or algorithm to an object property (like x, y, rotationX, scaleY, etc) and re-render the scene. But, for imported animations its not quite that simple. Lately Moses&#8217;s GoASAP package is being adopted in testing for the Papervision engine. It could soon become adopted by the system.</p>
<p><em><strong>The Collada DAE Parser</strong></em><br />
Imported animations come in plenty of flavors but must conform to the same system. That&#8217;s the reason the animations package exists. Papervision has long supported externally created 3D assets. You&#8217;ll find those file parsers in <a title="pv3d.objects.parsers" href="http://code.google.com/p/papervision3d/source/browse/#svn/trunk/branches/GreatWhite/src/org/papervision3d/objects/parsers">pv3d.objects.parsers</a>. Although, these importers are nice to have, a big part of Great White was the introduction of the open source project ASCollada. ASCollada is an amazing parser for the standard 3D asset interchange format known as <a href="http://en.wikipedia.org/wiki/COLLADA">Collada</a>. Collada files are basically very dense XML files that use a .dae file extension. Collada files can be exported from Maya, 3D Studio Max, Blender, Google Sketchup, and XSI. However, level of support for those programs probably follows this order: 3D Studio Max, Maya, Blender, Google Sketchup, XSI. Also, if you&#8217;re importing MD2 models, the MD2 file parser will import most animations as well.</p>
<p><span id="more-290"></span></p>
<p>You can try it out using the DAE class like so:</p>
<p><span style="#0000ff;"><code>import org.papervision3d.events.FileLoadEvent;<br />
import org.papervision3d.objects.parsers.DAE;<br />
daeScene = new DAE();<br />
daeScene.addEventListener(FileLoadEvent.LOAD_COMPLETE, onSceneGeometryLoaded);<br />
daeScene.addEventListener(FileLoadEvent.ANIMATIONS_COMPLETE, onSceneAnimationsLoaded);<br />
daeScene.load("your_scene.dae");<br />
var animChannel:AbstractChannel3D = daeScene.getAnimationChannels()[0];<br />
var frame:uint = 20;<br />
var animObject:DisplayObject3D = animChannel.defaultTarget;<br />
animChannel.updateToFrame(frame, animObject);</code></span></p>
<p><em><strong>Render Statistics</strong></em><br />
Papervision records all the primary rendering tasks. If you want to monitor rendering statistics, you can have them captured when you execute the BasicRenderEngine instance method &#8220;renderScene().&#8221; When traced, a typical render report will appear like this:</p>
<p><span style="#0000ff;">ProjectionTime:0 RenderTime:1 Particles:0 CulledParticles:0 Triangles:38 ShadedTriangles:0 CulledTriangles:82 FilteredObjects:0 CulledObjects:0</span></p>
<p>You can use this information to determine how well your scene is rendering. And it could give you ideas on how you can improve rendering by adjusting camera settings, culling plans, and clipping.</p>
<p><em><strong>Optimization</strong></em><br />
Great White has gained many huge performance advantages over previous versions of Papervision. One important advantage is that nearly all materials will render a surface to BitmapData. This is great because, as of Flash Player Update 3 (9.0.115, mid-2007) <a title="flash.display.BitmapData multi-core support" href="http://www.kaourantin.net/2007/06/multi-core-support.html">Multicore CPU support has been added to much of the BitmapData operations</a>.</p>
<p>Clipping is a flag added to the Viewport3D constructor in Great White that will force the engine to perform clipping of all objects outside the the viewing rectangle (the viewport). This feature may seem obvious, but a lot of public engines neglect this.</p>
<p><em><strong>Culling Algorithms</strong></em><br />
Drawing is the most expensive process that Papervision performs. As such, there are a few <a title="Hidden surface removal" href="http://en.wikipedia.org/wiki/Hidden_surface_determination">different standard methods</a> for removing items from the render queue in any 3D drawing API. This helps speed up render times by removing renderable triangles that would otherwise be drawn. Papervision3D performs backface culling, view frustum culling, and contribution culling but NOT occlusion culling. Occlusion culling is a huge process that is more built into accelerated APIs like OpenGL. Though it can be very difficult to perform well, it can also add extrordinary benefits to rendering performance.</p>
<p><em><strong>MovieClip Materials</strong></em><br />
Papervision3D supports interactive, animated, and smoothed <a title="org.papervision3d.materials.MovieMaterial" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/MovieMaterial.as">MovieClip</a> materials. However, those features come at a cost. You may already be aware that BitmapData smoothing (anti-aliasing) is slower than normal BitmapData rendering. Anti-aliasing algorithms are simply expensive operations and thats the bottom line. The other two features are performance hogs because they require that the Flash player to update the surface BitmapData object on each frame update &#8211;instead of reusing the original object that was derived from the MovieClip.</p>
<p><em><strong>Relative Performance</strong></em><br />
I&#8217;m currently coding lots of Flash player performance tests as they relate to Papervision. Right now I&#8217;m only using the following methods for testing: Math.sqrt(), Math.sin(), Matrix3D.multiply3x3(), and BitmapData.draw(). The test is simply a for loop that iterates 9999 times. It looks interesting and helps me make another point about PV3D performance. I&#8217;ll have to publish this application elsewhere, but for now here&#8217;s a sample of what I&#8217;m finding:</p>
<table style="134px;" border="0" cellspacing="0" cellpadding="3" width="301">
<tbody>
<tr>
<td>method</td>
<td>milliseconds</td>
</tr>
<tr>
<td>Math.sqrt(x)</td>
<td>1</td>
</tr>
<tr>
<td>Math.sin(x)</td>
<td>2</td>
</tr>
<tr>
<td>Matrix3D.multiply3x3(a,b)</td>
<td>13</td>
</tr>
<tr>
<td>BitmapDataObject1.draw(c)</td>
<td>661</td>
</tr>
<tr>
<td>BitmapDataObject2.draw(d)</td>
<td>2037</td>
</tr>
</tbody>
</table>
<p>Figure A: Performance timetable for 4 operations in a for loop lasting 9999 iterations. BitmapDataObject1 is 40&#215;40, transparent and BitmapDataObject2 is 600&#215;600, transparent. They both draw a single purple circle.</p>
<p>As you can see bitmap drawing is the most expensive operation here. In almost every instance that I can think of, drawing will be the most performance intensive activity in any 3D rendering API. I could explain that here, but it would probably double the size of this post. ;)Â  In a nutshell, it always helps to render only when you actually need to feature interaction and/or animation. Additionally, actively perform any reasonable operation to limit the number of objects in the scene. Again, the library does a lot for you there, but gains can always be made. Also, a little experience will show you that keeping the renderable area small will help also.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p3/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Papervision3D Part 2: Features</title>
		<link>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/</link>
		<comments>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 04:50:12 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=287</guid>
		<description><![CDATA[This is part 2 of a 4 part series outlining 3D in Flash by dissecting the open source Papervision3D library. Before getting deep into features let me first make a few points about using Papervision3D. The Papervision3d source SVN location &#8230; <a href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png"><img class="alignleft size-medium wp-image-289" src="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png" alt="" width="226" height="111" /></a>This is part 2 of a 4 part series outlining 3D in Flash by dissecting the open source Papervision3D library. Before getting deep into features let me first make a few points about using Papervision3D.</p>
<p>The <a title="Google Code PV3D SVN source" href="http://code.google.com/p/papervision3d/">Papervision3d source SVN location</a> includes the standard AS3 version of Papervision3D (<a title="pv3d.Papervision3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/as3/trunk/src/org/papervision3d/Papervision3D.as">version 1.7</a> as of this writing). If you look at the branches folder inside trunk you will find <a title="pv3d.Papervision3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/Papervision3D.as">version 2.0</a> which is code-named &#8220;Great White&#8221;. This series is focused on that branch, and NOT version 1.7. Also, its important to know that Great White is probably the fastest and most frequently changing part of the Papervision source and thus details in this article will likely change over time.</p>
<p>Also, as a convention in these posts, I&#8217;ll be putting direct references to actual Google Code hosted repository files inside this page. If you don&#8217;t wish to open that repository each time you want to know the path of a class, then simply mouse over the link and look at the link address or the tool tip that shows up for the link. All references to Papervision3D classes assume that all uses of the term &#8220;pv3d&#8221; refer to the root Papervision3D package.</p>
<p><span id="more-287"></span></p>
<p>All Flash demonstrations are interactive. After focusing on the Flash applet, you can use the following key controls to control the camera.</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td>key</td>
<td>control</td>
</tr>
<tr>
<td>w</td>
<td>move forward</td>
</tr>
<tr>
<td>s</td>
<td>move backward</td>
</tr>
<tr>
<td>a</td>
<td>move left</td>
</tr>
<tr>
<td>d</td>
<td>move right</td>
</tr>
<tr>
<td>q</td>
<td>decrease rotation Z</td>
</tr>
<tr>
<td>e</td>
<td>increase rotation Z</td>
</tr>
<tr>
<td>r</td>
<td>increase field of view</td>
</tr>
<tr>
<td>f</td>
<td>decrease field of view</td>
</tr>
<tr>
<td>t</td>
<td>increase distance of the near clipping plane</td>
</tr>
<tr>
<td>g</td>
<td>decrease distance of the near clipping plane</td>
</tr>
<tr>
<td>y</td>
<td>increase distance of the far clipping plane</td>
</tr>
<tr>
<td>h</td>
<td>decrease distance of the far clipping plane</td>
</tr>
<tr>
<td>mouse Y</td>
<td>pitch</td>
</tr>
<tr>
<td>mouse X</td>
<td>yaw</td>
</tr>
</tbody>
</table>
<p>Please note that nothing will promote your understanding of the code better than just reading it yourself. Although that may seem daunting, you&#8217;ll end up doing it anyway if you really get into the project. A good place to start might be reading the comments for classes in the folder pv3d.core.proto. If you&#8217;ve happened upon this page but are unfamiliar with computer graphics from a technical standpoint, please <a title="introduction" href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/">read Part 1</a></p>
<p><em><strong>Geometry</strong></em><br />
In Papervision, all geometry is basically stored in the form of vertex data (<a title="pv3d.core.geom.renderables.Vertex3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/geom/renderables/Vertex3D.as">Vertex3D</a>). Collections of Vertices are stored in <a title="pv3d.core.proto.GeometryObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/proto/GeometryObject3D.as?r=595">GeometryObject3D</a> instances. Every <a title="pv3d.objects.DisplayObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/objects/DisplayObject3D.as">DisplayObject3D</a> class contains object information (such as location, transformation, orientation axis, etc) AND a reference to a <a title="pv3d.core.proto.GeometryObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/proto/GeometryObject3D.as?r=595">GeometryObject3D</a> instance. The <a title="pv3d.objects.DisplayObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/objects/DisplayObject3D.as">DisplayObject3D</a> class is the building block of all 3D data in Papervision &#8211;much like the flash.display.DisplayObject class is the building block of a 2D stage. However, one important difference is that a <a title="pv3d.objects.DisplayObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/objects/DisplayObject3D.as">DisplayObject3D</a> will not contain any rasterized visual data (as the DisplayObject does in its graphics object). It contains only data that is used by the rendering engine (<a title="pv3d.render.BasicRenderEngine" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/render/BasicRenderEngine.as">BasicRenderEngine</a>) and the object&#8217;s material (* <a title="pv3d.core.proto.MaterialObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/proto/MaterialObject3D.as">MaterialObject3D</a>) which is used to draw the object onto a <a title="pv3d.view.Viewport3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/view/Viewport3D.as">Viewport3D</a> object.</p>
<p>*Note: the actual method performing all drawing operations is NOT <a title="pv3d.core.proto.MaterialObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/proto/MaterialObject3D.as">MaterialObject3D</a>.drawTriangle but instead any of its subclassses that are overriding that method (for example <a title="pv3d.materials.ColorMaterial" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/ColorMaterial.as">ColorMaterial</a>.drawTriangle).</p>
<p><em><strong>Texture Mapping</strong></em><br />
Up until now, all discussion about 3D rendering has excluded the use of images used on geometric surfaces. This feature, called texture mapping, is very widely used. Unfortunately, it can also be quite an expensive process in terms of CPU cylces. Texture mapping has also evolved to allow for plenty of visual effects like <a title="bump mapping" href="http://en.wikipedia.org/wiki/Bump_mapping">bump mapping</a>, <a title="normal mapping" href="http://en.wikipedia.org/wiki/Normal_mapping">normal mapping</a>, <a title="displacement mapping" href="http://en.wikipedia.org/wiki/Displacement_map">displacement mapping</a>, light mapping and more.</p>
<p>As you may recall from <a title="Papervision3D Introduction part 1" href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/">Part 1</a>, all surface geometry in Papervision is divided into triangles. However, since images used in texture mapping are rectangular, something must be done to determine how the image can be mapped onto triangles in order to render the rectangular map as a single image. This is where the <a title="uv mapping" href="http://en.wikipedia.org/wiki/UV_mapping">UV coordinates</a> come in. A UV is simply a 2D coordinate that represents a location on the texture map that is associated with the 3D point on a triangle. Figure A1 shows this relationship.</p>
<p>Figure A1: Three example UVs for texture mapping a rectangular plane.</p>
<p><img src="http://www.calebjohnston.com/storage/posts/uvs.jpg" alt="UV mapping example" width="450" height="168" /></p>
<p>In Papervision, all the actual drawing commands exist in the material class being used for an object (as I mentioned above). Please note that two options for texture mapping exist. There&#8217;s &#8216;normal&#8217; texture mapping which is also known as &#8216;<a title="Affine transformation of a plane" href="http://en.wikipedia.org/wiki/Affine_transformation#Affine_transformation_of_the_plane">affine</a>&#8216; texture mapping. And then there&#8217;s &#8216;precise&#8217; texture mapping which would be perspective correct. Normal texture mapping is a bit less accurate but far faster in rendering then precise textures. Exhibit A2 shows an example.</p>
<p>Exhibit A2: Normal (left) vs precise (right) texture mapping in Papervision3D 2.0</p>
<p>[kml_flashembed movie="http://www.calebjohnston.com/storage/posts/textureExample.swf" height="250" width="450" /]</p>
<p><strong><em>Materials</em></strong><br />
A Material is a term borrowed from 3D development tools (like 3D Studio Max) that describes a collection of properties that will determine how a 3D surface will be rendered. Materials can become very complicated in production 3D rendering tools, but in Papervision a material has only a few properties. Those properties will determine whether lines, fills and/or a bitmap is drawn and how they&#8217;re drawn. The real key component of all materials is the drawTriangle method which is called by the engine during the render cycle.</p>
<p><strong><em>Lighting and Shading</em></strong><br />
Light simulation is probably one of the most intricate and complicated aspects of 3D rasterisation. Other forms of computer rendering (like <a title="ray tracing" href="http://en.wikipedia.org/wiki/Ray_tracing">ray tracing</a>) don&#8217;t treat lighting the way the rasterisation technique does. The reason is simple, performance. So in order to mimic light phenomena using rasterisation, shaders can be used. With the Great White branch of Papervision, lighting and shading have been added. Outside of Papervision, the term &#8220;<a title="shader explanation" href="http://en.wikipedia.org/wiki/Shader">shader</a>&#8221; sort of has multiple definitions. Shaders are used in 3D development tools to determine how light will appear on a surface. But in real-time rendering APIs (like <a title="OpenGL API" href="http://en.wikipedia.org/wiki/OpenGL">OpenGL</a> and <a title="Microsoft Direct3D" href="http://en.wikipedia.org/wiki/Direct3D">Direct3D</a>) a shader is used to modify the <a title="graphics pipeline" href="http://en.wikipedia.org/wiki/Graphics_pipeline">graphics pipeline</a>. There are actually several languages that govern shader authoring. Even Adobe has their own brand of shader language called <a title="Adobe Image Foundation toolkit" href="http://labs.adobe.com/wiki/index.php/AIF_Toolkit">Adobe Image Foundation</a>. Although shading and lighting are rather complicated features in GPU accelerated APIs, in Great White they&#8217;re actually much simpler.</p>
<p>With Papervision, shaders are probably most useful for applying native flash effects (filters and blend modes) to any desired surface. Although, filters are not fully supported yet. Aside from that, applying a shader to a material is basically the same as applying a gradient-like light map to the BitmapData surface. So if you understand gradients and BitmapData objects in Flash, you basically understand Papervision shading as well. There are really 4 types of light maps you can use and those are <a title="pv3d.materials.shaders.PhongShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/PhongShader.as">Phong</a>, <a title="pv3d.materials.shaders.FlatShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/FlatShader.as">Flat</a>, <a title="pv3d.materials.shaders.GouraudShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/GouraudShader.as">Gouraud</a>, and <a title="pv3d.materials.shaders.CellShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/CellShader.as">Cell</a>. For each of those light maps there is a shader. There is also one other shader that can create an environment map. Its the <a title="pv3d.materials.shaders.EnvMapShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/EnvMapShader.as">EnvMapShader</a>. It allows one to pass in bitmap objects that are used in combination with the surface texture map. Also you can use bump maps in Papervision3D shaders. See the <a title="pv3d.materials.utils.BumpmapGenerator" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/utils/BumpmapGenerator.as">BumpmapGenerator</a> class. Exhibit B illustrates a simple example of various shaders. While this is not really the same &#8216;shading&#8217; that happens in video games, with Flash 10, shading could definitely change radically in Papervision.</p>
<p>Exhibit B: Shading examples in Papervision3D 2.0</p>
<p>[kml_flashembed movie="http://www.calebjohnston.com/storage/posts/shadersExample.swf" height="250" width="450" /]</p>
<p>Its also important to note that shading requires a light source. Unlike other popular 3D APIs, there is no default ambient light. And any light sources that are used are not a part of the scene. Instead you must add a light source to the shader and its position is used in determining what the light map looks like. At the time of this writing there is only one light source supported per shader in Papervision3D. Also there is only one type of light to choose from -a <a title="pv3d.lights.PointLight3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/lights/PointLight3D.as">point light</a>.</p>
<p><em><strong>Cameras</strong></em><br />
Cameras aren&#8217;t that complicated in Papervision3D. There are three types of Cameras: free, target, and debug. A free camera is totally unattached to anything that exists in the environment and can be moved &#8216;freely&#8217;. But a target camera will have a focus object within the scene. That object can be moved freely, but the camera will always come along. It works just like a focus camera object would work in a 3D development tool like 3D Studio Max or Maya. And thus a key aspect of that behavior is that if you want to translate a <a title="pv3d.cameras.Camera3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/cameras/Camera3D.as">Camera3D</a> object, it will actually rotate about its focus object. The last type of camera (debug) allows for key control, so that you can move the camera around as desired. This is highly useful when you&#8217;re building a complex scene or importing geometry from an external editor.</p>
<p>The only three camera-specific properties you can manipulate to control the view are zoom, focus and field of view (fov). The fov is in degrees. Normally 60 is representative of a normal 35mm camera lens. But the debug camera defaults to 90 degrees. Zoom and focus can be determined based on the fov and the camera&#8217;s distance to the near clipping plane. Exhibit C demonstrates the interaction of the fov and focus value. Also, here are some rather crude numbers for comparison:</p>
<table border="0" cellspacing="3" cellpadding="0" width="460">
<tbody>
<tr>
<td>lens focal length</td>
<td>lens type</td>
<td>PV3D camera focus</td>
<td>PV3D field of view</td>
</tr>
<tr>
<td>21 mm</td>
<td>very wide angle</td>
<td>6-</td>
<td>120+</td>
</tr>
<tr>
<td>21-35 mm</td>
<td>wide angle</td>
<td>6-12</td>
<td>80-120</td>
</tr>
<tr>
<td>37-70 mm</td>
<td>normal</td>
<td>12-17</td>
<td>60-80</td>
</tr>
<tr>
<td>70-135 mm</td>
<td>medium telephoto</td>
<td>17-27</td>
<td>40-60</td>
</tr>
<tr>
<td>135-300 mm</td>
<td>telephoto</td>
<td>27+</td>
<td>40-</td>
</tr>
</tbody>
</table>
<p>Note: all camera focus values are used with a default debug zoom value of 24. Field of view values are in degrees.</p>
<p>Exhibit C: Demonstration of camera field of view and focus. Use keys r and f to increase and decrease the fov respectively.</p>
<p>[kml_flashembed movie="http://www.calebjohnston.com/storage/posts/cameraExample.swf" height="250" width="450" /]</p>
<p>Stay tuned for more feature dissection in Part 3. In the meantime, <a title="Papervision3d introduction part2 examples" href="http://www.calebjohnston.com/storage/posts/Papervision3D-introduction-part2.zip">download examples source files here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Papervision3D Part 1: Introduction</title>
		<link>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/</link>
		<comments>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/#comments</comments>
		<pubDate>Fri, 18 Jul 2008 15:51:40 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=286</guid>
		<description><![CDATA[I have many friends asking me for more information on Papervision 3D. Usually, they&#8217;re just genuinely interested in learning about it and also how they can use it. These friends are bright people, but generally unfamiliar with the topic of &#8230; <a href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png"><img class="alignleft size-medium wp-image-289" src="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png" alt="" width="226" height="111" /></a></p>
<p>I have many friends asking me for more information on Papervision 3D. Usually, they&#8217;re just genuinely interested in learning about it and also how they can use it. These friends are bright people, but generally unfamiliar with the topic of computer graphics. I&#8217;ve consistently directed them to Wikipedia articles that I think will make everything clear to them (in this order):</p>
<ol>
<li><a href="http://en.wikipedia.org/wiki/Rendering_(computer_graphics)#Scanline_rendering_and_rasterisation">Computer Rendering</a></li>
<li><a href="http://en.wikipedia.org/wiki/Rasterization">Rasterisation</a></li>
<li><a href="http://en.wikipedia.org/wiki/Perspective_projection#Perspective_projection">3D Projection</a></li>
<li><a href="http://en.wikipedia.org/wiki/Matrix_multiplication">Matrix Multiplication</a></li>
</ol>
<p>Unfortunately, I think people are reluctant to read those articles because they&#8217;re half written in math formulas. Those formulas are critical for getting a real understanding of what&#8217;s going on &#8220;under the hood&#8221; but I admit they&#8217;re annoying to read if you don&#8217;t really want to learn the math. And also, those articles won&#8217;t mention a single Papervision class file anywhere (naturally). I&#8217;m sure this is a little less exciting for someone who&#8217;s into 3D in Flash. Therefore, I&#8217;m reviewing and dissecting Papervision3D 2.0 (Great White) in a multi-part series for those who are curious about 3D in Flash.</p>
<p>Part 1 will review those Wikipedia articles and relate them to Papervision along the way. If you&#8217;re already familiar with computer graphics as a topic of CS, you may wish to skip this post. Parts 2 &amp; 3 will review the details of many features of Papervision3D. Part 4 will be a set of useful notes and tips for anyone who&#8217;s not already experienced with Papervision3D.</p>
<p><span id="more-286"></span></p>
<p><em><strong>An Ultra-Brief Background of Computer Graphics</strong></em><br />
Drawing an image from a 3D scene using a computer can be done many different ways. However, if its going to be done very quickly in order to allow for animation and/or interactivity then typically a process called rasterisation is best. This term is used to describe the transformation of (vector) data into raster (or pixel) data, such as an image.</p>
<p>A few things should also be understood about the vector data used in rasterisation. It really can be almost anything that defines a 3D entity. However Papervision follows the popular convention of using 3D points oriented into triangles. So if a surface looks like a rectangle, its actually (at least) two triangles &#8211;each triangle having at least one face. It should also be noted that in 3D space two more important values are often used: <a title="Normal vector" href="http://en.wikipedia.org/wiki/Surface_normal">normals</a> and <a title="UV Mapping" href="http://en.wikipedia.org/wiki/UV_mapping">UV</a>s. A normal is short for &#8220;surface normal vector&#8221; which is a vector value that is perpendicular to the triangle&#8217;s face. And a UV is a value that is used to determine how an image can be mapped to the triangle&#8217;s face. In Papervision, there can be one UV for every 3D point. And there can be one normal for every triangle.</p>
<p>Rasterisation is a term that is used for both 2D and 3D graphics. Without getting into the real nitty gritty behind what&#8217;s going on inside a computer to produce an image on a monitor, we can say that Flash has pretty much always performed 2D rasterisation. But with a 3D engine used, a lot of logic is plugged in to produce an illusion of 3D on a 2D screen.</p>
<p>So what is all that logic? In short, 3D projection, matrix math and display list management. Plus, a lot of performance enhancement, shading, parsers, presets, and the structure of a nice OOP API. Here are the basics.</p>
<p><em><strong>3D Projection</strong></em><br />
Ultimately, the task of projection is mapping points which are represented in 3D space in a 2D coordinate system. There are different ways of doing this. Figure A1 shows 2 common examples: orthographic and perspective projections.</p>
<p>Figure A1: two common 3D projections of a cube</p>
<p><img class="alignnone" src="http://www.calebjohnston.com/storage/posts/3d_projection.jpg" alt="3D Projections" /></p>
<p>When using either projection technique and mapping everything within view to a 2D rectangular plane, a renderable volume is determined. This volume will be the space bound by a cube if projection is orthographic. Or it will be a frustum if the projection is perspective. This space is highly useful for making some key optimizations. Figure A2 helps explain the view volume.</p>
<p>Figure A2: Perspective projection view frustum with view frustum culling.</p>
<p><img class="alignnone" src="http://www.calebjohnston.com/storage/posts/view_frustum.jpg" alt="3D perspective projection view frustum" /></p>
<p>The process of projection is achieved through transforming matrices. In Papervision (as in most 3D APIs) a 4&#215;4 matrix will represent translation, rotation, and scaling for all axes. If you want to understand the raw math behind the matrix convention in 3D graphics, you should actually be reading the links I posted above from Wikipedia. Otherwise the following section will very briefly review the topic.</p>
<p><em><strong>3D Matrices</strong></em><br />
A Papervision 3D matrix is represented in 16 Number values. Figure B helps to illustrate how those numbers are used in a right-handed coordinate system.Â  With Papervision, a left-hand coordinate system is used. This means that the z axis points into the screen and away from the viewer. This will have some important implications if you decide to import models into Papervision from files generated using common 3D software.</p>
<p>Figure B: Three example matrix transformations</p>
<p><img class="alignnone" src="http://www.calebjohnston.com/storage/posts/matrix_transformation.jpg" alt="3 example matrix transformation" /></p>
<p>There are also 3 matrices that are used to represent a 3D scene in Papervision: the world matrix, the view matrix (or camera matrix), and the object transform matrix. So when an object is projected, it will go through all 3 matrix multiplications AND any animation matrix operations that are performed. More explicitly, each 3D vertex that exists in each 3D object will have to be transformed by all these matrices to end up as a 2D point in Flash.</p>
<p><em><strong>Display List Management</strong></em><br />
When an object is added to a scene it is also added to a render list. That render list is sorted so that each object being rendered appears on the screen at the correct depth. Each renderable object is then drawn to the viewport using the viewport graphics object. NOTE: This means that the final render in Papervision is drawn in a single DisplayObject.</p>
<p>Display list management is also where a lot of performance gains can be made. Many times its not necessary to show all the triangle faces that are in a scene because they don&#8217;t exist inside the viewing volume (typically a frustum). Removing objects from the render list because they exist outside the viewing volume is called view frustum culling. There are plenty of other (more advanced) methods used in order to optimize the render cycle. Many of those will be explained in part 3.</p>
<p><em><strong>Valuable Presets</strong></em><br />
Simple objects like cubes and spheres that come prefabricated in Papervision are called Primitives. They may not seem so sophisticated but consider how you would describe a sphere in terms of triangles using only 3D coordinates. Not to mention how you would determine all the triangle&#8217;s UV coordinates and normals! And if you don&#8217;t desire creating your 3D scene from primitives, you can generate your own objects algorithmically or even import them from an external source such as a collada file. That&#8217;s very valuable indeed!</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Actionscript 3 performance tuning review</title>
		<link>http://dispatchevent.org/calebjohnston/as3-performance-tuning/</link>
		<comments>http://dispatchevent.org/calebjohnston/as3-performance-tuning/#comments</comments>
		<pubDate>Wed, 09 Jul 2008 16:34:47 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[AIR]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=285</guid>
		<description><![CDATA[After late-night conversations amongst coworkers and friends over beers, I&#8217;ve discovered that many flash developers remain unfamiliar with AVM2&#8242;s inter workings. A while ago, I found a couple documents which have benefited me greatly in understanding AVM2 and AS3: Actionscript &#8230; <a href="http://dispatchevent.org/calebjohnston/as3-performance-tuning/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>After late-night conversations amongst coworkers and friends over beers, I&#8217;ve discovered that many flash developers remain unfamiliar with AVM2&#8242;s inter workings. A while ago, I found a couple documents which have benefited me greatly in understanding AVM2 and AS3:</p>
<p><a href="http://www.onflex.org/ACDS/AS3TuningInsideAVM2JIT.pdf">Actionscript 3.0 and Performance Tuning</a></p>
<p><a href="http://www.adobe.com/devnet/actionscript/articles/avm2overview.pdf">AVM2 Overview</a></p>
<p>There are definitely some big take-aways in these two documents. I would list them here, but then you might not read them for yourself! ;)</p>
<p>The first document is 74 powerpoint slides (prepared by Gary Grossman of Adobe) which is very useful for getting a quick understanding of AVM2 topics such as garbage collection, the benefits of strong typing, the Actionscript byte code (abc) format, the code interpreter and JIT compilation. For an AS3 developer this is a must-read.</p>
<p>The second document is a bit more dense. It contains 108 pages of more formally described underpinnings of the virtual machine. It focuses a lot on how your AS3 code will ultimately be run as processor instructions. Its a great follow-up to the first document. If you&#8217;re a geek, I would highly recommend reading this overview.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/as3-performance-tuning/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Code Documentation</title>
		<link>http://dispatchevent.org/calebjohnston/code-documentation/</link>
		<comments>http://dispatchevent.org/calebjohnston/code-documentation/#comments</comments>
		<pubDate>Sat, 24 May 2008 16:29:46 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>

		<guid isPermaLink="false">http://blog.extends.eventdispatcher.org/?p=276</guid>
		<description><![CDATA[I recently finished a campaign site for Starbucks in order to promote the Starbucks brand of coffee available in grocery stores. The address is www.starbuckscoffeeathome.com. It was a very pleasant project to work on, but it was also quite fast &#8230; <a href="http://dispatchevent.org/calebjohnston/code-documentation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I recently finished a campaign site for Starbucks in order to promote the Starbucks brand of coffee available in grocery stores. The address is <a href="http://www.starbuckscoffeeathome.com">www.starbuckscoffeeathome.com</a>. It was a very pleasant project to work on, but it was also quite fast paced. The project also remained in a state of high flux until launch. These two aspects combined made it nearly impossible to keep accurate comments on my code. So, after this project was complete I decided to re-write my UML for it based on the way it ended up (rather than the way I originally designed it). After doing so I&#8217;ve come to believe this serves as better and more digestible documentation for a developer than most inline commenting. Thats not to say it would completely replace code commenting, but I feel as though its more useful for another developer to see in order to get a grasp on how a body of code works. For this diagram I didn&#8217;t have the right tools available to me immediately so I used what I had (which was Adobe Illustrator). This required a greater investment of time, but the time consumed was likely on par with the amount of time required to produce sufficient written documention. For most practical situations, a simple sketch would suffice. Have a look at the diagram (and submit your critiques if you like).</p>
<p><a href="http://www.calebjohnston.com/storage/Starbucks_basic_class_UML.pdf">Download the Starbucks basic class UML (PDF).</a></p>
<p>I&#8217;ve also conducted a certain amount of performance profiling that I will write up in the near future.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/code-documentation/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The State pattern in Flex &#8211; combining view states with logical states</title>
		<link>http://dispatchevent.org/mims/the-state-pattern-in-flex-combining-view-states-with-logical-states/</link>
		<comments>http://dispatchevent.org/mims/the-state-pattern-in-flex-combining-view-states-with-logical-states/#comments</comments>
		<pubDate>Wed, 23 Jan 2008 07:15:17 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[User Experience]]></category>

		<guid isPermaLink="false">http://mimswright.com/blog/?p=229</guid>
		<description><![CDATA[If you&#8217;ve used Flex, you&#8217;ve no doubt (er, hopefully) been using View States (AKA &#60;mx:State&#62;) to change the look of your RIA as it progresses through different situations of use. While this is immeasurably useful, it does not necessarily qualify &#8230; <a href="http://dispatchevent.org/mims/the-state-pattern-in-flex-combining-view-states-with-logical-states/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve used Flex, you&#8217;ve no doubt (er, hopefully) been using <a href="http://livedocs.adobe.com/flex/2/docs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&#038;file=00000923.html#321190">View States</a> (AKA &lt;mx:State&gt;) to change the look of your RIA as it progresses through different situations of use. While  this is immeasurably useful, it does not necessarily qualify as an implementation of the <a href="http://www.google.com/url?sa=t&#038;ct=res&#038;cd=5&#038;url=http%3A%2F%2Fwww.cs.umd.edu%2Fclass%2Ffall2002%2Fcmsc433-0101%2FLectures%2FdesignPatterns2.pdf&#038;ei=xtWWR6W9Ao-siAHp6_zbCQ&#038;usg=AFQjCNET3tf19Z44Ejoy9f-ilwgu_3ahrg&#038;sig2=XkAAY1IAvln2Hmpt-plpGQ">State Design Pattern</a> which allows you to change not only how a component looks but how it <em>functions</em> as well.<br />
(for more on design patterns, read my favorite book <a href="http://www.amazon.com/Head-First-Design-Patterns/dp/0596007124/tag=dis03-20">Head first design patterns</a>).<br />
<span id="more-229"></span><br />
Take the following example for a &#8220;Breakfast maker&#8221; application. </p>
<p><a href='http://mimswright.com/blog/wp-content/uploads/2008/01/logicalstatedemo.zip' title='LogicalStateDemo'>Download Source!</a></p>
<p><code><strong>StateDemo.mxml</strong></code></p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;absolute&quot; xmlns:local=&quot;*&quot; currentState=&quot;{ENGLISH}&quot;&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[
			// define the state names as constants
			static public const ENGLISH:String = &quot;English&quot;;
			static public const FRENCH:String = &quot;French&quot;;

			/**
			 * When the &quot;make breakfast&quot; button is clicked, display the steps
			 * you'll need to follow to make breakfast.
			 * Imagine that you'd need to implement all of these steps as functions
			 * and that there are several more languages to support.
			 */
			protected function onBreakfastButton(event:Event):void {
				if (currentState == ENGLISH) {
					output.text = &quot;Fry eggs&quot; +
								  &quot;\nFry tomatoes&quot; +
								  &quot;\nToast bread&quot; +
								  &quot;\nMake tea&quot;;
				}
				if (currentState == FRENCH) {
					output.text = &quot;Tartiner du beurre sur baguette&quot; +
								  &quot;\nMettre le yaourt dans un bol&quot; +
								  &quot;\nTranche les fruits&quot; +
								  &quot;\nFaire cafe&quot;;
				}

			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;!-- Define the changes to the view in the &lt;mx:states&gt; tags --&gt;
	&lt;mx:states&gt;
		&lt;mx:State name=&quot;{ENGLISH}&quot;&gt;
			&lt;mx:SetProperty target=&quot;{breakfastButton}&quot; name=&quot;label&quot; value=&quot;Make Breakfast&quot; /&gt;
		&lt;/mx:State&gt;
		&lt;mx:State name=&quot;{FRENCH}&quot;&gt;
			&lt;mx:SetProperty target=&quot;{breakfastButton}&quot; name=&quot;label&quot; value=&quot;	Pr&Atilde;&copy;parer des petits-d&Atilde;&copy;jeuners&quot; /&gt;
		&lt;/mx:State&gt;
	&lt;/mx:states&gt;

	&lt;mx:VBox&gt;
		&lt;mx:Button id=&quot;breakfastButton&quot; click=&quot;onBreakfastButton(event)&quot; /&gt;
		&lt;mx:TextArea id=&quot;output&quot;  height=&quot;100&quot; width=&quot;250&quot;/&gt;
		&lt;mx:HBox&gt;
			&lt;!-- Swap states using these buttons --&gt;
			&lt;mx:Button label=&quot;English&quot; click=&quot;{currentState = ENGLISH}&quot; /&gt;
			&lt;mx:Button label=&quot;French&quot; click=&quot;{currentState = FRENCH}&quot; /&gt;
		&lt;/mx:HBox&gt;
	&lt;/mx:VBox&gt;
&lt;/mx:Application&gt;
</pre>
<p>Compiling this code gives you the following&#8230;<br />
<a href="/wp-content/uploads/2008/01/statedemo.swf">View SWF</a></p>
<h2>The problem</h2>
<p>While there&#8217;s nothing inherently wrong with this application, there could be complications when trying to make changes to the logic. First of all, the <code>onButtonClick()</code> handler has to provide different functionality based on the <code>currentState</code>. The states themselves need to add labels to the <code>breakfastButton</code>. Imagine what would happen if you expanded this application to support 15 languages or to create lunch, dinner, and teatime. Things could get out of control fast!</p>
<h2>The Solution &#8211; applying the state design pattern</h2>
<p>The state design pattern allows you to separate out state specific functionality and defer the execution of methods to those state objects. </p>
<p><img src='http://mimswright.com/blog/wp-content/uploads/2008/01/picture-2.png' alt='BasicStatePatternDiagram' /></p>
<p>I&#8217;ll combine the state pattern with the view states by making a <code>currentLogicalState</code> property of the application. This setter will also automatically set the <code>currentState</code> based on a name stored in the <code>currentLogicalState</code>. This is easier done than said&#8230;</p>
<h3>1. Define a logical state interface</h3>
<p>My logical state interface only needs to have one getter for <code>name</code> so that we can associate it with a view state.<br />
<strong><br />
<code><strong>ILogicalState.as</strong></code></p>
<pre>
package
{
	public interface ILogicalState
	{
		function get name():String;
	}
}
</pre>
<h3>2. create a customized state interface for this application</h3>
<p>This interface should contain any methods that are state dependent. </p>
<p><code><strong>IBreakfastMakerState.as</strong></code></p>
<pre>
package
{
	public interface IBreakfastMakerState extends ILogicalState
	{
		function get breakfastInstructions():String;
		function get breakfastLabel():String;
	}
}
</pre>
<p>Note that this interface extends ILogicalState.</p>
<h3>3. create state classes</h3>
<p>I&#8217;ll create two different state classes, one for English breakfast and one for French Breakfast. Each will implement the <code>IBreakfastMakerState</code> interface and will provide the functionality needed to prepare the appropriate breakfast.</p>
<p><code><strong>EnglishBreakfastState.as</strong></code></p>
<pre>
package
{
	public class EnglishBreakfastState implements IBreakfastMakerState
	{
		public function get name():String
		{
			return "English";
		}

		public function get breakfastInstructions():String
		{
			return "Fry eggs" +
				   "\nToast bread" +
				   "\nFry tomatoes" +
				   "\nMake tea";
		}
		public function get breakfastLabel():String {
			return "Make Breakfast";
		}
	}
}
</pre>
<p><code><strong>FrenchBreakfastState.as</strong></code></p>
<pre>
package
{
	public class FrenchBreakfastState implements IBreakfastMakerState
	{
		public function get name():String
		{
			return "French";
		}

		public function get breakfastInstructions():String
		{
			return "Tartiner du beurre sur baguette" +
				   "\nMettre le yaourt dans un bol" +
				   "\nTranche les fruits" +
				   "\nFaire cafe";
		}

		public function get breakfastLabel():String {
			return "PrÃ©parer des petits-dÃ©jeuners";
		}
	}
}
</pre>
<h3>4. Refactor StateDemo.mxml</h3>
<p>Finally, rewrite the StateDemo.mxml to take advantage of the new state objects and call it LogicalStateDemo.mxml. (Note, this application should run exactly the same as StateDemo.mxml)</p>
<p><code><strong>LogicalStateDemo.mxml</strong></code></p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;absolute&quot; xmlns:local=&quot;*&quot;
	initialize=&quot;onInitialize(event)&quot;&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[

			// define the logical states as constants
			static public const ENGLISH:IBreakfastMakerState = new EnglishBreakfastState();
			static public const FRENCH:IBreakfastMakerState = new FrenchBreakfastState();

			/**
			 * keep track of the current logical state and when the currentLogicalState changes
			 * update the currentState using its name property.
			 */
			protected var _currentLogicalState:IBreakfastMakerState;
			public function set currentLogicalState(state:IBreakfastMakerState):void {
				_currentLogicalState = state;
				currentState = _currentLogicalState.name;
			}

			protected function onInitialize(event:Event):void {
				currentLogicalState = ENGLISH;
			}

			protected function onBreakfastButton(event:Event):void {
				// rely on the logical state to handle the logic of preparing the breakfast.
				output.text = _currentLogicalState.breakfastInstructions;
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;!-- Define the changes to the view in the &lt;mx:states&gt; tags --&gt;
	&lt;mx:states&gt;
		&lt;!-- Name each view state using the name of the logical state --&gt;
		&lt;mx:State name=&quot;{ENGLISH.name}&quot;&gt;
			&lt;!-- Change the label using a value from the logical state --&gt;
			&lt;mx:SetProperty target=&quot;{breakfastButton}&quot; name=&quot;label&quot; value=&quot;{ENGLISH.breakfastLabel}&quot; /&gt;
		&lt;/mx:State&gt;
		&lt;mx:State name=&quot;{FRENCH.name}&quot;&gt;
			&lt;mx:SetProperty target=&quot;{breakfastButton}&quot; name=&quot;label&quot; value=&quot;{FRENCH.breakfastLabel}&quot; /&gt;
		&lt;/mx:State&gt;
	&lt;/mx:states&gt;

	&lt;mx:VBox&gt;
		&lt;mx:Button id=&quot;breakfastButton&quot; click=&quot;onBreakfastButton(event)&quot; /&gt;
		&lt;mx:TextArea id=&quot;output&quot;  height=&quot;100&quot; width=&quot;250&quot;/&gt;
		&lt;mx:HBox&gt;
			&lt;!-- Swap logical states using these buttons --&gt;
			&lt;mx:Button label=&quot;English&quot; click=&quot;{currentLogicalState = ENGLISH}&quot; /&gt;
			&lt;mx:Button label=&quot;French&quot; click=&quot;{currentLogicalState = FRENCH}&quot; /&gt;
		&lt;/mx:HBox&gt;
	&lt;/mx:VBox&gt;
&lt;/mx:Application&gt;
</pre>
<p><em>Et voila!</em> A state pattern that works with the existing view states. This may seem like a lot of work for such a simple thing but it will really pay off in the long run on a complicated RIA.</p>
<p><a href='http://mimswright.com/blog/wp-content/uploads/2008/01/logicalstatedemo.zip' title='LogicalStateDemo'>Download Source!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/the-state-pattern-in-flex-combining-view-states-with-logical-states/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Introducing KitchenSync &#8211; an open-source animation library for AS3</title>
		<link>http://dispatchevent.org/mims/introducing-kitchensync-animation-library-for-as3/</link>
		<comments>http://dispatchevent.org/mims/introducing-kitchensync-animation-library-for-as3/#comments</comments>
		<pubDate>Tue, 22 Jan 2008 18:23:51 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://mimswright.com/blog/?p=223</guid>
		<description><![CDATA[After about 6 months in development, I&#8217;m very proud to announce the release of KitchenSync, a multi-purpose tool written in ActionScript 3.0 for doing tween based animations and timing of functions and much more. The project is open-source under the &#8230; <a href="http://dispatchevent.org/mims/introducing-kitchensync-animation-library-for-as3/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/kitchensynclib/"><img src="http://mimswright.com/kitchensync/docs/img/KSLogo.png" /></a><br />
After about 6 months in development, I&#8217;m very proud to announce the release of <a href="http://code.google.com/p/kitchensynclib/">KitchenSync</a>, a multi-purpose tool written in ActionScript 3.0 for doing tween based animations and timing of functions and much more. The project is open-source under the GNU LGPL and hosted at <a href="http://code.google.com/p/kitchensynclib/">Google Code</a>. Please take a moment to check it out and feel free to write to me with questions, comments or suggestions for improvement!</p>
<h2>KitchenSync is more than an animation library</h2>
<p>KitchenSync is more than an animation library. <a href="http://code.google.com//p/kitchensynclib/wiki/Tween">Tweens</a> are a major part of KitchenSync but that is not the end. It also allows you to sequence <a href="http://code.google.com//p/kitchensynclib/wiki/SynchronizedSound">sounds</a>, <a href="http://code.google.com//p/kitchensynclib/wiki/SynchronizedFunction">functions</a>, and <a href="http://code.google.com//p/kitchensynclib/wiki/SynchronizedDispatchEvent">event dispatches</a> among other <a href="http://code.google.com//p/kitchensynclib/wiki/AbstractSynchronizedAction">actions</a>. The framework is open-ended allowing you to come up with new ways to work with the <a href="/p/kitchensynclib/wiki/Synchronizer">virtual timeline</a>.</p>
<h2>KitchenSync was designed with developers in mind</h2>
<p>KitchenSync was designed for developers who want a smart way to handle animation or other time-based functionality with code. Written from the ground up in ActionScript 3.0, KitchenSync relies on smart object-oriented architecture rather than complicated shorthand. It includes a number of features and shortcuts, such as the <tt>clone()</tt> method, that save effort for developers. KitchenSync makes extensive use of events and informative runtime errors and is quite flexible when it comes to extending the functionality.</p>
<h2>KitchenSync aims to&#8230;</h2>
<ul>
<li>offer a well-architected, extensible framework for working with time-based animations and events. </li>
<li>take advantage of the power of ActionScript 3.0 while using OOP best practices and design patterns and without requiring the Flex framework. </li>
<li>respond to the needs of developers with a rich set of features. </li>
<li>be a full-featured library for animation and timeline based actions.</li>
</ul>
<h2>Links</h2>
<ul>
<li><a href="http://code.google.com/p/kitchensynclib/wiki/GettingStarted">Getting started</a> </li>
<li><a href="http://code.google.com/p/kitchensynclib/w/list?q=label:Actions" rel="nofollow">Types of synchronized actions</a> </li>
<li><a href="http://code.google.com/p/kitchensynclib/wiki/TimeUnit">Units of time, parsing time strings, and sync mode</a> </li>
<li><a href="http://mimswright.com/kitchensync/docs/api/" rel="nofollow">API Reference</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/introducing-kitchensync-animation-library-for-as3/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Flex 3 Tips, Tricks, and Gotchas (A Series)</title>
		<link>http://dispatchevent.org/roger/flex-3-tips-tricks-and-gotchas-a-series/</link>
		<comments>http://dispatchevent.org/roger/flex-3-tips-tricks-and-gotchas-a-series/#comments</comments>
		<pubDate>Thu, 13 Sep 2007 21:46:10 +0000</pubDate>
		<dc:creator>Roger Braunstein</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Flex]]></category>

		<guid isPermaLink="false">http://www.partlyhuman.com/blog/roger/flex-3-tips-tricks-and-gotchas-a-series</guid>
		<description><![CDATA[At Your Majesty, I just launched a small (2.5kloc outside libraries, 2 weeks dev/qa time) site using Flex 3: the Axe Vice Naughty to Nice sweepstakes site. I chose Flex for this project because of the exceedingly short dev cycle, &#8230; <a href="http://dispatchevent.org/roger/flex-3-tips-tricks-and-gotchas-a-series/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>At Your Majesty, I just launched a small (2.5kloc outside libraries, 2 weeks dev/qa time) site using Flex 3: the <a href="http://www.axevice.com/naughtytonice/">Axe Vice Naughty to Nice</a> sweepstakes site. I chose Flex for this project because of the exceedingly short dev cycle, and because it contained forms and validation I could take out-of-the-box. However, like any project, I ran into a fair share of problems from annoying to outrageously aggravating, and I feel like it always helps to document what I learned, not just for everyone else but for my future self. You&#8217;d be surprised how often I have to open up chapters I wrote myself for the AS3 Bible or Introduction to Flex 2 and refresh my &#8220;memory,&#8221; if you can even call my rattling collection of underused neurons such a thing. Read on for <em>tons</em> of tips, tricks, techniques, and tilapia.<br />
<span id="more-176"></span></p>
<h2>General Impressions and Tactics</h2>
<p>Flex is always a completely different mindset to think in, and even the amount of interactivity present in this limited site was too much to build 100% in Flex. I backed out and built the &#8220;game&#8221; (ha ha) portion of the site in Flash with AS3 and Tweener, even going so far as to use plenty of timeline animations. Let&#8217;s never forget that despite all our powerful coding techniques, hand animation has its place. This part is loaded in a SWFLoader and communicates using event bubbling (hooray!)</p>
<p>In this site I tried to synchronize the state of multiple different parts of the site using a centralized set of states. All of the elements on the site share a common set of states which are stored as static constants of a States class (call it something different yourself, since this interferes with autocompletion when you&#8217;re typing an <tt>&lt;mx:states&gt;</tt> property tag). I always use data binding to connect up to those states: <tt>&lt;mx:State name="{States.SEND_TO_FRIEND}"&gt;</tt>. Navigations are sent right to the top (I ended up factoring out the navigator class since the navigations are so straightforward here), and then passed top-down, recursively when necessary. This simple approach to navigation let me break up the site into tiny chunks but still maintain a unified state without using different mechanisms for each part. The technique worked out well &#8212; for a tiny site like this.</p>
<p>I rediscovered that relying on states is great because state changes automatically have plenty of events and effects to bind to, and they are a great way to control transitions. I rediscovered that you should always resist the urge to bend a component to your will. Just because you have something that looks like a horizontal slider, you can spend endless hours trying to break into and override the operation of a Flex component, then realize that writing <tt>startDrag()</tt> isn&#8217;t really that hard.</p>
<p>I used resource bundles to easily do the frequent copy changes you know you can expect when a site has to pass legal review. This was a really good choice, and I love resource bundles, though they can be tiring to type and confusing to set up. I&#8217;ll cover them in more detail below.</p>
<p>I also rediscovered that flex effects are incredibly hard to do cool things with. However, let&#8217;s not forget that they&#8217;re super easy to do simple things with. I was groaning at the prospect of adding animated fade rollovers to all this text, then I went out and did it and it took like 5 seconds (much easier than writing all that code for event handlers):</p>
<pre>&lt;mx:Text ... rollOverEffect=&quot;{linkRollOver}&quot; rollOutEffect=&quot;{linkRollOut}&quot;&gt;
&lt;mx:Fade id=&quot;linkRollOver&quot; alphaFrom=&quot;0.15&quot; alphaTo=&quot;0.3&quot; duration=&quot;200&quot;/&gt;
&lt;mx:Fade id=&quot;linkRollOut&quot; alphaFrom=&quot;0.3&quot; alphaTo=&quot;0.15&quot; duration=&quot;350&quot;/&gt;</pre>
<p>More general tips: Use <tt>Canvas</tt> for everything. Always set <tt>horizontalScrollPolicy</tt> and <tt>verticalScrollPolicy</tt> to <tt>"off"</tt>. Use <tt>clipContent="false"</tt> to your advantage as well. Don&#8217;t forget the really powerful <tt>horizontalCenter="0"</tt> and <tt>verticalCenter="0"</tt> for aligning things, even inside non-layout-managed containers.</p>
<p>You can use Flash-style display list access. If you start feeling constrained by Flex but you don&#8217;t need to build a whole darn SWF for one thing, you can build the clips you like in the places they need to be, and use it as an asset inside an <tt>Image</tt> tag. Then you can use the <tt>content</tt> property to &#8220;break through&#8221; the Flex framework into the Flashy goodness inside. For example, take the red marker that fills up the clue bar as you find clues. Man, such a simple thing, but it&#8217;d be pretty annoying to do it right in Flex when it has to look just so! So I have all these clips laid out on stage and put in the right place, and I assign the top level clip a linkage class, export to SWF, and pull it into an Image:</p>
<pre>&lt;mx:Image id=&quot;clueBarClip&quot; source=&quot;@Embed(source=&apos;/../assets/ui.swf&apos;,symbol=&apos;CluesIndicator&apos;)&quot;/&gt;</pre>
<p>Then I can just tinker with the red bar inside it:</p>
<pre>var fill:DisplayObject = DisplayObject(clueBarClip.content["fill"]);
fill.scaleX = progress.numCluesFound / 3;</pre>
<p>That was sooo easy. First I got my way into that library instance by accessing the <tt>content</tt> of the image, then see how I just grabbed the inner clip by its stage instance name &#8220;fill&#8221;? Use this creatively and don&#8217;t forget to mix in Flash when you don&#8217;t need Flexiness.</p>
<p>One last tip. Always check to see if someone else has built that thing you&#8217;re tearing your hair off to build. Flex components are so much easier to bundle up and reuse than flash components, I&#8217;ve found. Beside <a href="http://code.google.com/p/flexlib/">flexlib</a>, there are several lists of useful components out there, like <a href="http://flexbox.mrinalwadhwa.com/">flexbox</a>.</p>
<h2>What do you mean, Flex doesn&#8217;t do that?</h2>
<p>I kind of assumed that Flex did a few things for you that it does not. Let us not forget:</p>
<ul>
<li>Flex does <em>NOT</em> have a video player component! That&#8217;s right, all it has is a video display component. You&#8217;ll have to build your own scrubber, time display, controls, buffer screen, omg.</li>
<li>Flex will <em>NOT</em> validate a whole form at once. Each one of the validators only works on its own. If you want to ensure a whole form is valid or not, tough titties. I thought there&#8217;d be an easy way to hack a bunch of validators together, but hours of hacking later, I was only frustrated. Thank goodness Paul Rangel came along and <a href="http://blog.wheelerstreet.com/?p=123">solved this problem</a> rather handily. I used his form validator to control the enabled&#8230;.ness? of my buttons.</li>
<li>Flex does not seem to have a validator for combo boxes, radio groups, or check boxes. However, I built an exceedingly simple one which makes this a snap. See <a href="http://www.partlyhuman.com/articles/flex/ComboValidator.as"><tt>ComboValidator</tt></a>. This code uses it to validate a combo box (the first value is instructional and won&#8217;t be accepted) and a checkbox (which you need to check).
<pre>
&lt;validators:ComboValidator rejectedValues=&quot;{[0]}&quot; source=&quot;{someComboInput}&quot; property=&quot;selectedIndex&quot; errorMessage=&quot;Select one.&quot; /&gt;
&lt;validators:ComboValidator acceptedValues=&quot;{[true]}&quot; source=&quot;{someCheckBox}&quot; property=&quot;selected&quot; errorMessage=&quot;check this box!&quot;/&gt;
</pre>
</li>
</ul>
<h2>Freaking Gotchas</h2>
<p>Freaking Flex! Oh, how I cursed you.</p>
<ul>
<li><b>Preloaders.</b> Flex, you utterly fail! You know nobody paying money for a site is going to allow the default Flex loader. And yes, you can specify your own preloader class with the <tt>preloader</tt> attribute on the Application, but that has serious issues with using embedded assets. Yes, there are brave people who have <a href="http://www.onflex.org/ted/2006/07/flex-2-custom-preloaders.php">figured out how to do this</a>, but without copying their solutions almost verbatim, including some mysterious parts (with the mime-type and casting to a ByteArray, using a Loader? Two classes?) I wasn&#8217;t able to get things to work. And even so, I&#8217;ve heard reports that while loading my swf, the AVM hangs until the assets gets loaded &#8212; sometimes popping the script timeout error. All in all, doing a custom preloader in Flex that uses assets is really essential, and is not very well supported or communicated about. When I use this technique, does the Flex compiler know to put all the assets in my preloader in the first frame? Who knows! I&#8217;d like a flex compiler option to specify a SWF or class reference as a preloader, and guarantee that all of that is compiled in frame 1. Yugh. Please fix for Flex 4!</li>
<li><b>Scale 9.</b> As I wrote about in <a href="http://www.partlyhuman.com/books/flexshortcut/">Introduction to Flex 2</a>, the big difference between skins and background images is that you can use scale 9 on your skins to let one image work in many different sizes without looking awkward. But for whatever reason, and nobody ever tells you this, <em>you can&#8217;t use scale 9 with assets embedded from symbols in SWFs</em>. It just doesn&#8217;t work. Regardless of whether you build the guides in Flash yourself, or write them in the embed tag. If you want to use scale 9 in your skins, pull them in as PNGs, and use the all-but-hidden embed &#8220;grid&#8221; attributes:
<pre>Button
{
    up-skin: Embed(source="button/off.png", scaleGridLeft="10", scaleGridTop="7", scaleGridRight="51", scaleGridBottom="13");
    over-skin: Embed(source="button/over.png", scaleGridLeft="10", scaleGridTop="7", scaleGridRight="51", scaleGridBottom="13");
    down-skin: Embed(source="button/down.png", scaleGridLeft="10", scaleGridTop="7", scaleGridRight="51", scaleGridBottom="13");
    disabled-skin: Embed(source="button/disabled.png", scaleGridLeft="10", scaleGridTop="7", scaleGridRight="51", scaleGridBottom="13");
}</pre>
<p>Don&#8217;t forget that you have to duplicate your skin for all states that might be used, or the Halo skin will show up instead (that kind of sucks). I wasted so much time trying to work around my scale 9 skins not scaling by 9. Sooo much time. But I made &#8216;em PNGs and suddenly everything is hunky-dory. AUGH.</li>
<li><b>Disappearing fonts.</b> Some Flex components make the brilliant move of forcibly applying a font style. So if you keep seeing your fonts disappear, check the type of the component. Buttons and all their subclasses will default to a <tt>font-weight</tt> of bold, so if you don&#8217;t embed the bold version of a font or remember to set <tt>font-weight</tt> to normal, you might not ever see your buttons&#8217; labels, or they might only appear on your computer, or show up as Times New Roman or some default font on a user&#8217;s box. Always remember to test your sites while turning off the fonts that you used to build it!
<p>Speaking of which, I have to endorse font face embedding using SWF fonts. It&#8217;s the only way to embed PostScript fonts (at least in Flex 2), you can set the antialiasing settings and the character ranges visually in the IDE, and most importantly, you can share files so easily without trying to get the same font working with multiple developers who might have different versions of the font, be running on different platforms that assign different names to the font, and any amount of other ridiculous fonttomfoolery. Just check in your font swfs, and everyone will be happy.</li>
<li><b>Resource Bundles.</b> These are awesome, but took me forever to get working properly. I think the documentation misses some info about how to set up your project for resource bundles. Anyway, if you&#8217;re building a site that might require frequent copy changes, or might appear in multiple languages, then you should definitely try out Flex resource bundles. In Flex 3, you can even swap out resource bundles at runtime. Yay!
<p>So what&#8217;s a resource bundle? It&#8217;s just a collection of values that you stick in a file, and you can link into your program. Instead of writing the strings directly in your code, you can centralize them all for easy translation and changes. If you&#8217;ve built a lot of sites in Flash, I wager you&#8217;ve done this yourself with XML files at one point. Using the Flex version is great cause you can link directly to strings in MXML with some short syntax, rather than writing code. You can also use property files to store arrays, class references, and images that are localized. Awesome! F.ex.</p>
<pre>
string1=Hello
string2=World
</pre>
<pre>
&lt;mx:Label text=&quot;@Resource(key=&apos;string1&apos;,bundle=&apos;Strings&apos;)&quot;/&gt;
&lt;mx:Label text=&quot;@Resource(key=&apos;string2&apos;,bundle=&apos;Strings&apos;)&quot;/&gt;
</pre>
<p>But I ran into problems getting things working. First, the stuff that made sense:</p>
<ul>
<li>You can link to resources either by using the <tt>@Resource(key='KeyName', bundle='BundleName')</tt> directive in MXML, or using the <tt>[ResourceBundle("BundleName")]</tt> metadata tag to create a reference to a ResourceBundle in ActionScript.</li>
<li>You can either specify the bundle name in these methods to specify which property file to reference, or without it, the property file with the same location as the containing class will be used. For example, if you omit the bundle name in com.example.Rectangle, Flex will look for the key in the com/example/Rectangle.properties file. I used a single bundle and always included the bundle name.</li>
<li>When you use ActionScript to reference a ResourceBundle object, you can use methods on it to retrieve values as other things than strings. I use this to fill in combo boxes:
<pre>signupReferrerOptions=Select an option, MySpace Page, Web banners, TV, Friend</pre>
<pre>&lt;mx:ComboBox id=&quot;age&quot; selectedIndex=&quot;0&quot; dataProvider=&quot;{Main.stringBundle.getStringArray(&apos;signupAgeOptions&apos;)}&quot;/&gt;</pre>
</li>
</ul>
<p>But what wasn&#8217;t clear to me was how to set them up.</p>
<ul>
<li>Typically, you create a path for resources, such as /locale/, in your project root. Then each language gets its own subdirectory under here, with its own copy of all the property files, such as /locale/en_US/Strings.properties, or /locale/en_US/com/example/Rectangle.properties</li>
<li>Whatever directory is the root of the particular language&#8217;s property files (/locale/en_US/) needs to be in the source path when you build the project. Flex Builder doesn&#8217;t set this up automatically, even if you add the locale/ dir to the source path and set <tt>-locale en_US</tt> in the compiler arguments.</li>
<li>To set things up properly in Flex Builder, make sure the current locale is set in the Flex Compiler options with the <tt>-locale</tt> option. Then, add the folder <tt>locale/{locale}</tt> (literally) to the source path. Flex Builder or mxmlc should substitute the correct locale at build time. Only when the property files are in your build path will the bundles be reachable. The compiler doesn&#8217;t provide very helpful errors when you do this wrong.</li>
</ul>
</li>
<li><b>Multiline controls.</b> Why Flex doesn&#8217;t allow you to flow the labels for buttons, checkboxes, radio buttons, and the like to more than one line is just aggravating. I hacked these components to allow it, but I didn&#8217;t have time to get the sizing correct, instead hacking in the right amount of padding manually&#8230; oh well.</li>
<li><b>Where is the root for embeds anyway?</b> Looks like it&#8217;s in the root of the source path. So if you have a folder structure with /src/com/example/Application.mxml trying to reach /assets/whatever.gif, you can actually always get to the assets with this odd path: /../assets/whatever.gif.</li>
</ul>
<h2>Specific Techniques</h2>
<p>So, like most of my projects, I tried out some fun stuff in this project. This project required some PHP scripting as well. Sending variables in a POST/GET to PHP scripts is easy in AS3, but you know, just not quite easy enough to warrant typing it over and over, so I made a little helper class, <a href="http://partlyhuman.com/articles/flex/FormSubmitter.as"><tt>FormSubmitter</tt></a>, with the method</p>
<pre>public function send(url:String, hash:Object, method:String = URLRequestMethod.POST):IAsynchronousToken</pre>
<p>Then I extend it for some services just to make the URLs to the scripts constants:</p>
<pre>
package com.axevice
{
    import <a href="http://partlyhuman.com/articles/flex/XMLFormSubmitter.as">com.yourmajesty.services.XMLFormSubmitter</a>;

    public class Service extends XMLFormSubmitter
    {
        public static const SEND_TO_FRIEND:String = "somesendtofriendscript.php";
        public static const SIGNUP:String = "somesignupscript.php";
    }
}
</pre>
<p>And then calling them and reacting to them is so nice.</p>
<pre>
var hash:Object = {yourName: yourName.text, yourEmail: yourEmail.text, theirName: theirName.text, theirEmail: theirEmail.text};
(new Service()).send(Service.SEND_TO_FRIEND, hash).addEventListener(AsynchronousTokenEvent.COMPLETE, onSendComplete);
</pre>
<p>That&#8217;s all for now! In the next installment, I want to cover a class I wrote that uses introspection to automatically bind models to XML.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/roger/flex-3-tips-tricks-and-gotchas-a-series/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>(pseudo) Abstract Classes in AS3!</title>
		<link>http://dispatchevent.org/mims/abstract-classes-in-as3/</link>
		<comments>http://dispatchevent.org/mims/abstract-classes-in-as3/#comments</comments>
		<pubDate>Thu, 05 Apr 2007 17:09:53 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.losdesigns.com/?p=46</guid>
		<description><![CDATA[(Since we&#8217;re MXNA&#8217;d now, I wanted to bring this post and maybe a couple of others back up to the top by reposting them. This was written back in October) I was looking at this blog post by Tink about &#8230; <a href="http://dispatchevent.org/mims/abstract-classes-in-as3/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>(Since we&#8217;re MXNA&#8217;d now, I wanted to bring this post and maybe a couple of others back up to the top by reposting them. This was written back in October)</p>
<p>I was looking at <a href="http://www.tink.ws/blog/stricter-abstracts/">this blog post by Tink</a> about more strict Abstract constructors in Flash using Errors. I worked out a way that is a bit more formalized. It adds support for abstract methods and unlike Tink&#8217;s example, doesn&#8217;t require you to type out the string of the class name.</p>
<p><span id="more-46"></span></p>
<p><span style="text-decoration: line-through;"><strong>Download the <a href="http://www.losdesigns.com/blog/wp-content/uploads/2006/10/AbstractTest.zip">source</a>.</strong></span><strong> Sorry, this link is dead, but the source is now part of <a href="http://code.google.com/p/as3lib/source/browse/trunk/src/org/as3lib/utils/AbstractEnforcer.as">AS3Lib</a></strong><span style="text-decoration: line-through;"><strong><br />
</strong></span></p>
<p>Basically, it works by throwing an error whenever you want a class to be subclassed or a method to be overridden. It&#8217;s a runtime error and doesn&#8217;t get thrown until you actually try to instantiate or run a method which. While this isn&#8217;t perfect it&#8217;s better than nothing.</p>
<p>It also checks the type in the constructor which allows you to add code to the constructor that will be inherited by the subclass upon instantiation without causing the errors (in other words, you can safely call <code>super()</code> without getting an error). It wraps up everything into an <code>AbstractEnforcer</code> utility class that simplifies the syntax.</p>
<p>The <code>AbstractEnforcer.enforceConstructor()</code> method uses a second utility function that you may find useful: <code>strictIs(instance:Object, comparisonClass:Class)</code> located in <code>com.mimswright.utils</code>. This function works just like the <code>is</code> operator but performs a strict comparison on the fully qualified class name. The result is that you will only get true back if <code>instance</code>&#8216;s class is exactly the same as <code>comparisonClass</code> (with the is operator you would get true if <code>instance</code> was a subclass of <code>comparisonClass</code>). It&#8217;s a bit nicer than doing a string comparison of the class names.</p>
<p>I&#8217;m still looking for people to bang on it and see if it breaks or find more improvements so please check it out.</p>
<p>Note: This is AS3 only. You&#8217;ll need to have some way to compile AS3 to use this (like Flex Builder). You&#8217;ll also have to be a big geek and be into anime and Spawn action figures.<br />
The code is set up to break as it is, but I left some commented code in there so you can try different scenarios.</p>
<p>Thanks to Tink and everyone.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/abstract-classes-in-as3/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

