<?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>FlexWiz Blog &#187; ActionScript 3</title>
	<atom:link href="http://blog.flexwiz.net/category/as3/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.flexwiz.net</link>
	<description>On Game Development and the Flash platform</description>
	<lastBuildDate>Sat, 17 Dec 2011 22:46:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>SpriteSheet Animation in AS3</title>
		<link>http://blog.flexwiz.net/spritesheet-animation-in-as3/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=spritesheet-animation-in-as3</link>
		<comments>http://blog.flexwiz.net/spritesheet-animation-in-as3/#comments</comments>
		<pubDate>Sun, 04 Dec 2011 20:33:05 +0000</pubDate>
		<dc:creator>theWiz</dc:creator>
				<category><![CDATA[ActionScript 3]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Bitmap]]></category>
		<category><![CDATA[Blitting]]></category>
		<category><![CDATA[SpriteSheet]]></category>
		<category><![CDATA[TexturePacker]]></category>

		<guid isPermaLink="false">http://blog.flexwiz.net/?p=919</guid>
		<description><![CDATA[Over the last few years sprite-sheet animation gained popularity among game developers. It offers some real advantages over movie clips &#8211; lighter and potentially faster performance, with the added bonus of code portability. If you plan to deploy your game on Android and iOS  as well, this is definitely the way to go. I found that most [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-medium wp-image-934" title="sheetDemo3ab" src="http://blog.flexwiz.net/wp-content/uploads/2011/11/sheetDemo3ab-300x258.png" alt="" width="300" height="258" />Over the last few years sprite-sheet animation gained popularity among game developers. It offers some real advantages over movie clips &#8211; lighter and potentially faster performance, with the added bonus of code portability. If you plan to deploy your game on Android and iOS  as well, this is definitely the way to go.</p>
<p>I found that most of the tutorials on sprite sheets are for the Cocos2D engine (in Objective-C for iOS). Here I will show a practical and convenient way to animate sprite sheets in AS3, making the game perform well on both Flash in browser and AIR mobile.</p>
<p><span id="more-919"></span></p>
<p>There are a few off the shelf engines that use variations of spritesheets, among them Starling (Flash 11 only) and Flixel. These may be perfect for certain type of projects, but I decided to write my own classes to minimize the dependency on 3rd party code.</p>
<h3>Demo</h3>
<div class="wp-caption aligncenter" style="width: 540px"><a href="http://blog.flexwiz.net/sources/animSprite/AnimDemo.swf"><img title="demo" src="http://blog.flexwiz.net/wp-content/uploads/2011/12/demo1a.png" alt="" width="530" height="394" /></a><p class="wp-caption-text">Click image to see the demo</p></div>
<p>Download the full <a href="https://bitbucket.org/flexwiz/spritesheet" target="_blank">demo code</a> from BitBucket <a href="https://bitbucket.org/flexwiz/spritesheet" target="_blank">here</a>.</p>
<h3>The Tools</h3>
<p>You would need a code IDE (FlashDevelop, FDT or Flash Builder) and an image tool that can pack textures. I use the popular <a href="http://www.texturepacker.com/" target="_blank">TexturePacker</a>, in my opinion the best texture tool for developers. If anyone knows anything better, please comment.</p>
<h3>Preparing the assets</h3>
<p>The animated sprite is created by the artist  with their animation package of choice. This is a sequence of images that form the animation frames.  In this case (and most others) all frames are the same size.</p>
<p>Open TexturePacker and import the individual images into the projects. Select json as the data format, check &#8216;Allow free sizes&#8217; and make sure &#8216;Allow rotation&#8217; is not checked. Publish the texture to the output folder. <a href="http://blog.flexwiz.net/wp-content/uploads/2011/12/settings.png" target="_blank">The setting I use</a> can be seen <a href="http://blog.flexwiz.net/wp-content/uploads/2011/12/settings.png" target="_blank">here</a>.</p>
<p>There are many different options with TexturePacker, that are out of scope of this article. For more in depth look, check out Chris Fletcher&#8217;s tutorial <a href="http://chris-fletcher.com/tag/texturepacker-tutorial/" target="_blank">here</a>.</p>
<p>Once published, you end up with a large PNG file &#8211; the texture sheet, and a json file to go with it.</p>
<h3>Reading the texure with the AnimTextureSheet class</h3>
<p>I created the AnimTextureSheet class to encapsulate a texture sheet and its data. After loading your animation assets, you get a BitmapData from the sheet PNG and a string from the json file. After decoding the json string, the function populateFrameArray serialize the frame data into an array which is then passed into the  newly created AnimTextureSheet.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">	<span style="color: #6699cc; font-weight: bold;">var</span> seqRaw<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">Object</span> = JSON<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">decode</span><span style="color: #000000;">&#40;</span> sheetData <span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
	<span style="color: #6699cc; font-weight: bold;">var</span> animData<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">Array</span>= <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #000066; font-weight: bold;">;</span>
	populateFrameArray<span style="color: #000000;">&#40;</span>animData<span style="color: #000066; font-weight: bold;">,</span> seqRaw<span style="color: #000066; font-weight: bold;">.</span>frames<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
&nbsp;
	<span style="color: #009900; font-style: italic;">// Sort</span>
	animData<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">sortOn</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;id&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
&nbsp;
	<span style="color: #009900; font-style: italic;">// Create and initialize the tile sheet</span>
	<span style="color: #6699cc; font-weight: bold;">var</span> tileSheet<span style="color: #000066; font-weight: bold;">:</span>AnimTextureSheet= <span style="color: #0033ff; font-weight: bold;">new</span> AnimTextureSheet<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
	tileSheet<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span>texture<span style="color: #000066; font-weight: bold;">,</span> animData<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span></pre></div></div>

<p>Once initialized, the tille sheet is ready to go, and the  drawFrame() method can be called to blit a frame into a destination bitmap buffer.</p>
<p><strong>UPDATE</strong><br />
When compiling with Flash Player 11 (or Flex 4.6) there is a build error due to the new native JSON parser:<br />
<code>Can not resolve a multiname reference unambiguously. JSON [..]</code><br />
To resolve the problem, simply change the first line to read:<br />
<code>var seqRaw:Object =  com.adobe.serialization.json.JSON.decode( sheetData );</code></p>
<h3>Play it</h3>
<p>To actually display the animation,  we need a display object to hold the bitmap. For that purpose I created the AnimSprite class, that is based on flash.display.Bitmap. This class in only for convenience - you can create your own &#8211; it demonstrates the possible use cases for an animated sprite.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">	<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> createAnim<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">:</span>AnimSprite
	<span style="color: #000000;">&#123;</span>
		<span style="color: #6699cc; font-weight: bold;">var</span> anim<span style="color: #000066; font-weight: bold;">:</span>AnimSprite = <span style="color: #0033ff; font-weight: bold;">new</span> AnimSprite<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
&nbsp;
		anim<span style="color: #000066; font-weight: bold;">.</span>initialize<span style="color: #000000;">&#40;</span>_texSheet<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
		anim<span style="color: #000066; font-weight: bold;">.</span>addSequence<span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;all&quot;</span><span style="color: #000066; font-weight: bold;">,</span> arFrames<span style="color: #000066; font-weight: bold;">,</span> <span style="color: #000000; font-weight:bold;">16</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
&nbsp;
		anim<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">play</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;all&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
		<span style="color: #0033ff; font-weight: bold;">return</span> anim<span style="color: #000066; font-weight: bold;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #009900; font-style: italic;">// Call on enter frame event</span>
	<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> onFrameUpdate<span style="color: #000000;">&#40;</span>event<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">Event</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #004993;">pause</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
			<span style="color: #0033ff; font-weight: bold;">return</span><span style="color: #000066; font-weight: bold;">;</span>
		<span style="color: #000000;">&#125;</span>
		<span style="color: #0033ff; font-weight: bold;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #6699cc; font-weight: bold;">var</span> i<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">int</span> = <span style="color: #000000; font-weight:bold;">0</span><span style="color: #000066; font-weight: bold;">;</span> i <span style="color: #000066; font-weight: bold;">&lt;</span> arSprites<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">length</span><span style="color: #000066; font-weight: bold;">;</span> i<span style="color: #000066; font-weight: bold;">++</span><span style="color: #000000;">&#41;</span> 	<span style="color: #000000;">&#123;</span>
			AnimSprite<span style="color: #000000;">&#40;</span>arSprites<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">.</span>updateAnimation<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The above code shows how AnimSprite is actually used.</p>
<ol>
<li>instantiate the AnimSprite</li>
<li>initialize it with  a tile sheet</li>
<li>add one or more sequences (indexed frames) with an individual frame rate</li>
<li>add it to the stage.</li>
</ol>
<p>To play it:</p>
<ol>
<li>Call play() to start playing a sequence</li>
<li>call updateAnimation() on every frame</li>
</ol>
<h3>How it works</h3>
<p>AnimSprite uses partial blitting technique to animate. It uses the bitmapData as a frame buffer that holds the frame image that gets displayed. On every update, the updateAnimation()  function checks if the animation frame need to advance, and if so calls advanceFrame() &#8211; that sets the dirty flag when the current frame index is changed.  The the following method is then used to draw the frame:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">	<span style="color: #0033ff; font-weight: bold;">protected</span> <span style="color: #339966; font-weight: bold;">function</span> drawFrameInternal<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
	<span style="color: #000000;">&#123;</span>
		dirty = <span style="color: #0033ff; font-weight: bold;">false</span><span style="color: #000066; font-weight: bold;">;</span>
&nbsp;
		<span style="color: #004993;">bitmapData</span><span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">fillRect</span><span style="color: #000000;">&#40;</span><span style="color: #004993;">bitmapData</span><span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">rect</span><span style="color: #000066; font-weight: bold;">,</span> <span style="color: #000000; font-weight:bold;">0</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
		mAnimSheet<span style="color: #000066; font-weight: bold;">.</span>drawFrame<span style="color: #000000;">&#40;</span>curIndex<span style="color: #000066; font-weight: bold;">,</span> <span style="color: #004993;">bitmapData</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
	<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Check out the code for more details on the AnimSprite class.</p>
<p>That&#8217;s pretty much it. Let me know if you find any bugs or problems.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.flexwiz.net/spritesheet-animation-in-as3/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Molehill and the DisplayList &#8211; A Step Back?</title>
		<link>http://blog.flexwiz.net/molehill-and-the-displaylist-a-step-back/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=molehill-and-the-displaylist-a-step-back</link>
		<comments>http://blog.flexwiz.net/molehill-and-the-displaylist-a-step-back/#comments</comments>
		<pubDate>Sun, 31 Jul 2011 21:00:51 +0000</pubDate>
		<dc:creator>theWiz</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[ActionScript 3]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Blitting]]></category>
		<category><![CDATA[Molehill]]></category>

		<guid isPermaLink="false">http://blog.flexwiz.net/?p=629</guid>
		<description><![CDATA[There has been a lot of buzz about  Molehill (or Stage3D) and GPU hardware acceleration in the upcoming Flash player 11. However, very little was said on the practical aspects on normal flash applications and games.  Now that the public beta is out, we can get a feel of what it really is, and see [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-medium wp-image-868" title="" src="http://blog.flexwiz.net/wp-content/uploads/2011/07/molehill-300x164.png" alt="" width="300" height="164" />There has been a lot of buzz about  Molehill (or Stage3D) and GPU hardware acceleration in the upcoming Flash player 11. However, very little was said on the practical aspects on normal flash applications and games.  Now that the public beta is out, we can get a feel of what it really is, and see what you can and cannot do with it.</p>
<p>Here is my take on the issue of Stage3D/Molehill. While reading related tweets and posts, I notice a few misconceptions about Molehill &#8211; and this is something I’d like to address here.<br />
<span id="more-629"></span></p>
<h4>Dude, where is my Display List?</h4>
<p>Right from the start I felt something doesn&#8217;t feel right. If all the demos are using engines like Away3D, what&#8217;s in it for &#8216;plain&#8217; flash games? Apparently, Molehill (and Flash 11) does not include GPU hardware acceleration for the Display List.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-869" src="http://blog.flexwiz.net/wp-content/uploads/2011/07/zombie.jpg" alt="" width="468" height="265" /></p>
<p>First of all a note about architecture. Flash uses a retained mode rendering model, through its Display List. It means we don&#8217;t actually draw, we place display objects on the display list (and the stage) &#8211; the rest is done by the Flash player, where the drawing actually takes place on every frame.</p>
<p>In contrast, Moelhill API  is a thin wrapper for OpenGL  (or Direct3D in some cases) that provides low level drawing of 3D geometry and textures, including programmable shaders. It exists outside of the flash stage, almost as a standalone system. It is not designed to support, or implement drawing of display objects.</p>
<p>While not without its problems, the flash display list is the core feature of Flash: a simple and easy to use scene graph that gets processed and rendered on every frame. Its what makes Flash Flash: you would not want to imagine building any games or applications without it.</p>
<h4>Catching up to current technologies</h4>
<p>This year we started seeing GPU hardware acceleration in JavaScript/CSS, although not on all browsers. Browser have rendering engines that can accelerate primitive drawing for vectors and font when rasterizing them to canvas. I would expect no less from the flash player.<br />
The days when non-accelerated Display List was sufficient for developers are over. Here is what <a href="http://blog.bengarney.com/" target="_blank">Ben Garney</a>, a flash game heavyweight, says on <a href="http://blog.bengarney.com/2010/10/18/the-flash-display-list-and-games/" target="_blank">his blog</a>:</p>
<blockquote><p>[...] I use the display list for lots of things, just like any Flash developer. It’s a useful, flexible, and powerful tool.</p>
<p>But when I have specific, performance oriented needs, I ditch it in favor of something I can control completely. That’s why I always use a raster pipeline – drawing all my own pixels – for my game rendering. Using BitmapData.copyPixels has a consistent, reliable cost, whereas the cost of drawing a DisplayObject hierarchy, either on stage or via draw(), is highly variable and difficult to predict in terms of both memory and CPU consumption. [...]</p></blockquote>
<p>So developers like Ben Garney are opting to write their own renderers in order to gain better performance, but that is not an ideal long term solution. A much better one would be to utilize both multi-threading and GPU hardware acceleration for the standard flash Display List.</p>
<h4>Hello 1993</h4>
<p>For me, this is Deja vu all over again. It brings memories of the early 90s, were all we had was raw OpenGL or DirectX, and programming 3D was considered a black magic, some sort of witchcraft. We had to use special bitmap fonts and skimp on UI features for games, because everything was done in low-level, with no component libraries to speak of.<br />
A lot has changed since then, both in technologies and standards. Are we are expected to use the low level Molehill or use a Molehill based 3D engine for any plain old 2D project?</p>
<div id="attachment_865" class="wp-caption aligncenter" style="width: 410px"><a href="http://blog.flexwiz.net/wp-content/uploads/2011/05/1993-Ford-Mustang.jpg"><img class="size-full wp-image-865 " title="1993-Ford-Mustang" src="http://blog.flexwiz.net/wp-content/uploads/2011/05/1993-Ford-Mustang.jpg" alt="" width="400" height="300" /></a><p class="wp-caption-text">1993 Ford Mustang</p></div>
<p>Bringing GPU acceleration to a small subset of flash applications just won&#8217;t cut it. Casual games that make a large part of Flash projects, need fast performing 2D display as well as complex UI. Forcing developers to shoehorn Molehill into any 2D project is just wrong. It&#8217;s not a good solution and would push more Flash developers to jump ship and look for alternatives.</p>
<h4>GPU Acceleration for All</h4>
<p>Don’t get me wrong: I am a 3D enthusiast myself, and did a lot of 3D programming on different games way before I started using Flash &#8211; and 3D API in flash is better than none. I simply don’t like the idea of having to choose between hardware acceleration or the Display List and not both of them together.</p>
<p>The next logical step for Adobe would be to build GPU hardware acceleration into the Flash Display List, so that the bottleneck of scene rendering would be removed. Yes, it carries some risks since Flash would become dependent on display driver vendors to run consistently on different platforms, but surely this can be resolved by partnering with nVidia and AMD. If done correctly, any existing AS3 code would be accelerated without any changes.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.flexwiz.net/molehill-and-the-displaylist-a-step-back/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Facebook AS3 API Blues</title>
		<link>http://blog.flexwiz.net/facebook-as3-api-blues/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=facebook-as3-api-blues</link>
		<comments>http://blog.flexwiz.net/facebook-as3-api-blues/#comments</comments>
		<pubDate>Mon, 04 Jul 2011 02:34:27 +0000</pubDate>
		<dc:creator>theWiz</dc:creator>
				<category><![CDATA[ActionScript 3]]></category>
		<category><![CDATA[Adobe]]></category>
		<category><![CDATA[Facebook]]></category>

		<guid isPermaLink="false">http://blog.flexwiz.net/?p=824</guid>
		<description><![CDATA[While working on adding Facebook connectivity for a Flash based project, I found myself spending way too much time fighting with the Facebook-as3 API. For a Flash developer, there are two basic ways of using the Facebook API: directly with HTTP requests or with the help of Adobe&#8217;s facebook-as3 API. This library is maintained by [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-841" src="http://blog.flexwiz.net/wp-content/uploads/2011/07/fbLogo.png" alt="" width="140" height="140" />While working on adding Facebook connectivity for a Flash based project, I found myself spending way too much time fighting with the Facebook-as3 API. For a Flash developer, there are two basic ways of using the Facebook API: directly with HTTP requests or with the help of Adobe&#8217;s <a href="http://code.google.com/p/facebook-actionscript-api/" target="_blank">facebook-as3 API</a>. This library is maintained by Adobe, and you would expect it to be well documented and reliable, but it has some major issues, most of them are with the OAuth 2.0 authentication process.<span id="more-824"></span></p>
<h3>How to make Facebook-AS3 API to actually work without going insane</h3>
<p>Note that the last major change in the API was in April 2010 with the introduction of OAuth 2.0 in Facebook. At the time of this writing, version 1.6.1 is the current version of the API.</p>
<p>First, the setup for a web based project is a bit messy, since you need to register your Facebook app with a specific URL and put some code in the Html wrapper &#8211; for a full explanation read <a href="http://www.blog.elimak.com/2011/03/connect-flash-with-facebook-using-the-adobe-sdk-for-facebook/">this post</a>.</p>
<h4>OAuth in AS3</h4>
<p>Logging in a Facebook user with OAuth2 is simple enough if you use HTTP and JS. Issue a call with the AppID and permissions and it receive the access token in the JS callback function. Not so with the facebook-as3 API: you need to call Facebook.init() and then depending on the result call Facebook.login() to handle the login prompt.</p>
<p><img class="size-medium wp-image-842 alignnone aligncenter" src="http://blog.flexwiz.net/wp-content/uploads/2011/07/03_fblogin_popup-300x167.png" alt="" width="400" height="224" /></p>
<h4>Problem #1 - Facebook.init() returns (null, null)</h4>
<p>The official documentation says Facebook.init will return a session on success and null on fail &#8211; however it actually returns only the session in the result, or null if you are not logged in. The second argument (fail object) is always null. Just this simple discovery had cost me a few days of hair pulling, so don&#8217;t rely on the docs.  Yes, they are supposed to be updated frequently by Adobe but somehow this detail slipped out [facepalm].</p>
<h4>Problem #2 &#8211;  Facebook.login() returns null regardless of actual login</h4>
<p>Calling login right after Facebook.init() returns may not work as expected, and worse &#8211; results will vary depending on the browser and Flash player version (For me it works in Chrome and fails on IE8).</p>
<p>Don&#8217;t waste time on the official docs, since there is no mention of that there. It turns out that Flash player 10 imposes a security restriction (that may or may not be related to the browser) that will cause login to fail silently and return right away with null and lose connection with the login popup, which is very confusing since the API call to Facebook actually works in the browser, only not in your code [facepalm again].</p>
<h3>My Solution</h3>
<p>There is more than one solution to the authentication process, and it really depends on what you need. You could avoid the  facebook-as3 library all together, as some developers on the forums suggested. There are no restrictions in HTTP/JS login, and it is painless. But what about the AS3 code?</p>
<p>After looking at a few samples, it appears that the simple solution would be to have a login button in your app, and require the user to click it to invoke the login popup. Simply put the Facebook.login call in the button handler function and it works perfectly.<br />
However, you need to prevent subsequent calls to Facebook.login after a successful once, so make sure you hide or disable the button or face the consequences (I managed to crash IE8 with multiple login calls).  See sample code below:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript3" style="font-family:monospace;">	Facebook<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">init</span><span style="color: #000000;">&#40;</span>APPID<span style="color: #000066; font-weight: bold;">,</span> onInit<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
	<span style="color: #000066; font-weight: bold;">...</span>
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> onInit<span style="color: #000000;">&#40;</span>result<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">Object</span><span style="color: #000066; font-weight: bold;">,</span> fail<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">Object</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
	<span style="color: #000000;">&#123;</span>
		btnLogin<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">visible</span> = <span style="color: #000000;">&#40;</span>result==<span style="color: #0033ff; font-weight: bold;">null</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
		<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span>result <span style="color: #000066; font-weight: bold;">!</span>= <span style="color: #0033ff; font-weight: bold;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #009900; font-style: italic;">// We have a session</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;you are logged in&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
		<span style="color: #000000;">&#125;</span>
		<span style="color: #0033ff; font-weight: bold;">else</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;need to log in&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #009900; font-style: italic;">// Login Button handler</span>
	<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> btnLogin_clickHandler<span style="color: #000000;">&#40;</span>event<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">MouseEvent</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
	<span style="color: #000000;">&#123;</span>
		Facebook<span style="color: #000066; font-weight: bold;">.</span>login<span style="color: #000000;">&#40;</span>onLogin<span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0033ff; font-weight: bold;">private</span> <span style="color: #339966; font-weight: bold;">function</span> onLogin<span style="color: #000000;">&#40;</span>result<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">Object</span><span style="color: #000066; font-weight: bold;">,</span> f<span style="color: #000066; font-weight: bold;">:</span><span style="color: #004993;">Object</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">:</span><span style="color: #0033ff; font-weight: bold;">void</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0033ff; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span>result == <span style="color: #0033ff; font-weight: bold;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Access denied!!!&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
		<span style="color: #0033ff; font-weight: bold;">else</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #004993;">trace</span><span style="color: #000000;">&#40;</span><span style="color: #990000;">&quot;Login complete.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000066; font-weight: bold;">;</span>
			btnLogin<span style="color: #000066; font-weight: bold;">.</span><span style="color: #004993;">enabled</span>= <span style="color: #0033ff; font-weight: bold;">false</span><span style="color: #000066; font-weight: bold;">;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span></pre></div></div>

<p>If anybody has a better solution I would love to hear.  Hopefully someone at Adobe will notice and modify the documentation to better reflect the reality, or even better &#8211; fix those issues inside the AS3 API so that it would be consistent with the HTTP/JS API.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.flexwiz.net/facebook-as3-api-blues/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Top 10 Performance Killers in your AIR Application</title>
		<link>http://blog.flexwiz.net/top-10-performance-killers-in-your-air-application/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=top-10-performance-killers-in-your-air-application</link>
		<comments>http://blog.flexwiz.net/top-10-performance-killers-in-your-air-application/#comments</comments>
		<pubDate>Tue, 24 May 2011 15:48:05 +0000</pubDate>
		<dc:creator>theWiz</dc:creator>
				<category><![CDATA[ActionScript 3]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[AIR]]></category>
		<category><![CDATA[Blitting]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://blog.flexwiz.net/?p=624</guid>
		<description><![CDATA[With the recent release of AIR 2.7, I thought it would be a good idea to return to the basics of efficient code. While the performance is greatly improved on mobile and desktop, it&#8217;s still the coders responsibility to stick to best practices and avoid performance killers. The same is true for Flash inside a browser (Flash Player [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-714" src="http://blog.flexwiz.net/wp-content/uploads/2011/05/high-speed.jpg" alt="" width="320" height="240" />With the recent release of AIR 2.7, I thought it would be a good idea to return to the basics of efficient code. While the performance is greatly improved on mobile and desktop, it&#8217;s still the coders responsibility to stick to best practices and avoid performance killers. The same is true for Flash inside a browser (Flash Player 10.3).</p>
<p>Slow and heavy code is more apparent on a mobile platform &#8211; often the desktop hardware will compensate with a powerful CPU and plenty of memory so you might not even notice that your application or game is lagging. <span id="more-624"></span></p>
<h5>Intro: The Runtime</h5>
<p>Every game or application makes use of two major resources: CPU and memory. How you use them will determine how it will run: hogging the CPU or memory will result in a slow or choppy run, and in some cases may crash the app. The following are a couple of things every decent Flash developer should understand about the Flash player and AIR runtime. By the way, every time you read &#8216;Flash Player&#8217; here it refers to the AIR runtime as well.</p>
<p style="text-align: center;"><img class="size-full wp-image-694  aligncenter" src="http://blog.flexwiz.net/wp-content/uploads/2011/05/marshalledsliceexport.png" alt="" width="500" height="220" /></p>
<p>Flash is a JIT environment (JIT= Just In Time) and uses a VM (Virtual Machine) dubbed AVM2. The Flash player uses a familiar model of frame cycles – a loop were each frame is processed and then rendered to the screen in sequence. Running on a single thread, the frame execution model divides the frame time slice into two distinct sections, one for user code execution and one for rendering content to screen (we ignore the green part for simplicity). The player tries to balance the two, in a model that is often referred to as the <a href="http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/"  target="_blank">elastic racetrack</a>.</p>
<p>Objects in memory are garbage collected, and there is very little control on when and how fast an object would be collected and released. Memory allocation and release are costly operations and best be batched together in few blocks  rather than  small objects. Also keep in mind that large single object fragment less than multiple small objects.</p>
<p>Now without further ado, on to  list.</p>
<h5>10. Bad code, in general</h5>
<p>Bad code is typically the root cause of performance problems. Simply put, if its not architected and designed to be efficient it will not be efficient. A few scenarios come to mind:</p>
<ul>
<li>Coding a large system piece by piece without ever considering the big picture.</li>
<li>Leaving old legacy code intact long after the business requirements have changed. Again, lack of design before coding.</li>
<li>Coders are pressured to meet deadlines under a tight schedule and abandon any practices, in hope of getting the job done faster &#8211; this usually has the opposite effect.</li>
</ul>
<h5>9. Using Flex when its not needed</h5>
<p>If you choose to use Flex over pure AS3, there better be a very good reason for it. Simply because you need a few labels and a couple of buttons in your app is not reason enough. There is a huge overhead involved with the Flex component framework, both in memory and CPU usage. Treat Flex as a necessary evil and avoid it if possible &#8211; there are plenty of alternate UI component frameworks that are lighter, like MinimalComps or Reflex, to name a few. In many cases its easier to implement few UI control yourself, based on supplied graphic assets.</p>
<h5>8. Abusing MXML in Flex Apps</h5>
<p>If despite the above you are using Flex, try to minimize the use of MXML, and use it n high level components only. MXML markup generates code on build time, and often coders are not aware that they can actually write it themselves better.</p>
<p>A typical way coders abuse MXML is by nesting boxes and groups only to create a layout, each with conditional properties (left/right/top/bottom). This will code unnecessary bloated code and hog CPU cycles on every redraw, since the layout need to be recalculated across all those nested groups.</p>
<p>The same goes for data binding &#8211; using binding when you can simply assign a value is a sure way to overload the app, particularly when its used on dozens of fields.</p>
<h5>7. Misusing the MVC pattern</h5>
<p>While a good programmer knows how to use patterns, a great programmer knows when to avoid them. Bending a component so that is uses MVC is wrong if the pattern is not needed.</p>
<p>Take a simple widget as an example: one could separate the code into a view class with 4-10 lines of code, a mediator class with all the functionality and throw in a few command classes, each to activate a specific function on the mediator. Almost all classes will require injection and you&#8217;ll end up with 4-6 different classes.  Now, just to wire them up is more effort than the entire widget &#8211; this is over engineering:  producing pieces of code that are overly complicated where simplicity is needed.</p>
<p>So for small widgets and controls, opt for the simple one class combo with a few public functions, and write it with as few lines as humanly possible. Simplicity is the key, and MVC should be left for top-level components in more complex cases.</p>
<h5>6. Not using a Tweener</h5>
<p>Tweeners are the secret weapon of flash coders. When you need animation sequencing or delayed calls, its best to use  a tweener.  I use <a href="http://www.greensock.com/tweenmax/">TweenMax</a> and its delayedCall() method to make delayed calls with ease and zero overhead, but any other tweener will do just as good.</p>
<p>Speaking of performance, a tweener is almost guaranteed to work faster than any half-baked solution you cooked up when you didn&#8217;t have the time to design properly. It has its own internal timer so you never have to use one yourself.</p>
<h5>5. Using Timers</h5>
<p>When people ask me what is the best way to use timers, my answer is simple: don’t use them &#8211; ever.</p>
<p>Besides the fact that timers are inaccurate and not very easy to use, they have a certain overhead that can add up and cripple the performance of your game. Timers hook into the Flash Player environment and calculates time on each frame,  using CPU cycles on every frame per each timer that is created. These will quickly add up to slow down the app - the more timer instances linger in the system, the more you can expect slow and choppy gameplay or unresponsive UI.</p>
<p>As an aternative, use a tweener or simply use the ENTER_FRAME event on the stage so it would be triggered on every frame.</p>
<p>Just one word of warning: enter frame is a system event &#8211; to minimize impact, use it sparsely.  If you are writing a game, it’s best to use it just for one object (your main game class) and have a single centralized enter frame handler make all the subsequent calls to game objects.</p>
<h5>4. Memory Allocation and Release</h5>
<p>As already mentioned, allocating memory is a costly operation.Whenever you use &#8216;new&#8217; to create an object, it triggers a bunch of low-level functions inside the AIR runtime/Flash player, such as heap allocation, garbage collection and buffer locking.  Its important to avoid creating and destroying objects frequently or inside the game loop. Either create them ahead of time or use Object Pooling to avoid the performance hit.</p>
<p>Regarding garbage collection, stick to the basics: don’t leave any references behind (especially class members) and clean up your classes so they get picked up. Frequently calling System.gc() (in AIR only) is not a good idea since it will be invoked anyway by the player, and may cause an overhead.</p>
<p>Pay special attention to anyscronous objects like loaders: you need to call loader.unloadAndStop() to release the loaded content.</p>
<h5>3. Overloaded display list</h5>
<p>The Flash Player use a deferred rendering model based on a scene graph, or a display list. This means that instead of issuing draw calls, we place display objects on the stage and the rest is done internally in the player runtime environment.On every render cycle, it traverses through the display list hierarchy top to bottom and draws every object in its place. While the implementation is internal to the player, the time it takes to draw one frame depends on the size and complexity of the display list.</p>
<p>One way to reduce render time is to minimize the amount of display objects – by removing any hidden or unnecessary objects. In a game you might want to keep references to the game objects and remove them from the display list when they are off-screen. Also make sure that removed object are actually disposed, by removing any references and event listeners and stopping movie clips and sounds, otherwise they will keep using CPU cycles on every frame.</p>
<h5>2. Drawing API and Vector Rendering</h5>
<p>Rendering in the Flash player consists mainly of rasterization and compositing, and both could form a potential bottleneck.</p>
<p>In compositing, alpha blending and filters are applied. Keep these under tight lid, specially filters can be extremely CPU intensive. One way to optimize filters is to compose them off screen on by drawing the filtered object into a bitmap, and then use the bitmap in place of the original object.</p>
<p><img class="aligncenter" src="http://blog.flexwiz.net/wp-content/uploads/2011/05/img61.gif" alt="" width="336" height="250" /></p>
<p>Rasterization is the process of drawing all vector shapes and fonts into pixels (in a bitmap). This is where the old &#8216;Bitmap vs Vector&#8217; debate take place &#8211; a trade-off between memory and CPU usage exists. While vector shapes take little space they are slow to rasterize and put a toll on the CPU on every redraw. Bitmaps, on the other hand, take more space up-front but they skip the rasterization on redraw so drawing is much faster.</p>
<p>Bitmaps also allow for baking in post processing effects and skip the run-time filters. Since a large portion of the frame rendering is spent on rasterizing vector shapes, we can try to rasterize some elements ahead of time using off screen blitting.</p>
<p>Some game engines like Flixel and PushButton offer bitmap only rendering, where all display objects are rasterized in advance and then blitted to a central bitmap buffer which is the only object on the display list. With this technique rendering is faster in magnitudes, but it has its own limitations.</p>
<p>Also for some platforms (Mobile devices and TV), AIR has built in GPU acceleration for bitmap rendering &#8211; Many developers prefer bitmaps for this reason alone.</p>
<h5>1. Using Events</h5>
<p>There is no easy way to say this – the Flash event/listener model is one of the weak points in the runtime environment. It’s slow, messy, and requires extra boilerplate code to achieve the trivial. Most Flash coders tolerate it, but you don’t have to – I’ll show a few good alternatives.</p>
<p>So what exactly is wrong with native flash events?</p>
<p>Every time dispatchEvent() is called it makes a copy (or a clone) of the event object. When this happens inside the game loop you get lots of small memory allocations every frame – a sure way to cause a performance hit. From my days writing console games in C++ I was taught to avoid this scenario, and this applies in magnitudes in a JITed environment like AIR or Flash player.</p>
<p>Here’s a partial list of problems in flash event model:</p>
<ul>
<li>Custom events require new classes</li>
<li>You must allocate new objects for each dispatch – a costly operation</li>
<li>Registering for an event via addEventListener leaves a reference to the listener object that keeps it from being released automatically.</li>
<li>It does not compare well to modern event models, such as C# events.</li>
</ul>
<p>In short, this model is slow, heavy and inefficient. Since we are after high performance and efficient memory usage, I would strongly suggest considering an alternative. This is only true for custom events – on display objects you may still need to use Flash events for mouse, keyboard or enter frame – but you can keep these to a minimum.</p>
<p>A solid alternative to events are <a href="https://github.com/robertpenner/as3-signals/wiki/" target="_blank">AS3 Signals</a>,  an open source library by Robert Penner. I use them is all my projects and games. For more about signals check out <a href="http://www.peterelst.com/blog/2010/01/22/as3-signals-the-best-thing-since-sliced-bread/">this post</a> from Flash guru Peter Elst.</p>
<h5>Conclusion</h5>
<p>Writing fast and efficient code in Flash and AIR requires some attention and planning, to avoid common pitfalls. Keeping the display list light and avoid costly operations inside the update loop is key to a smooth and solid performance.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.flexwiz.net/top-10-performance-killers-in-your-air-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

