Category: ActionScript

  • Converting AS3 to AS2 and Surviving AS2 in General

    If you are in a hurry, skip to Gotchas.

    Introduction

    There are a variety of reasons to still use AS2. Some of the more realistic are:

    1. Supporting legacy content
    2. Awaiting a larger corporation to sign off on AS3 development
    3. Having to work with a client-side API written in AS2 by a third party

    In my case, I found out #3 after I was well over 3 weeks into development of an AS3 solution. As more and more traditional programmers learn ActionScript 3, whether from Flex development, or from curiosity about how one would code JavaScript in newer browsers from Mozilla via the Tamarin engine, you may also be put in a position to maintain or modify some AS2 content, typically written in Flash.

    Even with “as3” and “es” set to false when using the mxmlc compiler, you still aren’t capable of using Flex Builder 2 or 3 as a serious solution to doing ActionScript 2 development. Furthermore, Flash the IDE (CS3 in this case) isn’t a serious development environment either. While Flash CS3 did add some minor code editing features, it’s pretty clear form that release that Adobe has no intention of improving AS2 development in Flash.

    If you are maintaining a sizable code base, or simply converting it, whether to support a 3rd party API or merely to keep your sanity, having a good tool and some advice on how to quickly get past the gotchas can really make a difference.

    Tools

    AS2 really jump started the open source industry for Flash. There are a plethora of options out there. Unfortunately, when this industry was ramping up, I jumped ship to Flex. You can investigate yourself over at OSFlash.org. I have no clue what is good for Mac, however…

    …for PC, I recommend FlashDevelop. No, not FDT (Flash Develop Tool), just FD. If you see a forum, you know you’ve reached the right place. That’s correct, it doesn’t even have a proper web page. I use Google to actually find the download page on their site for the software ( flashdevelop download site:flashdevelop.org ) It’s just that good. Steven Sacks took me through a Breezo of this program almost a year and a half ago. It’s written in .NET (but suggests Java 1.6???), hence, I lug both my Mac AND my 14.5 lb PC laptop to work JUST so I can use that one piece of software. That’s right, a $2,600 former gaming laptop just to use an a piece of open source software. I say again, it’s just that good. Speaking of Alienware, they like DoubleClick, can go diaf together. Anyway, imagine Flex Builder, only for AS2. Code hinting, code completion, etc. Yes, for your own classes, not just Adobe’s.

    I’ve converted to mostly Mac for full time Flex & Flash Development. However, I own a copy of CrossOver to use just one piece of software: BeyondCompare. This works just as well for AS2 as it does for AS3. It’s code diffing software, and I use it to sync my local copy with Subversion’s.

    While you technically only need Flash MX 2004, Flash 8 runs more predictably, and Flash CS3 has both 8’s stability, with some minor compiler & code editing changes that make it bearable to be in the 5 minutes of your day you just have to use it instead of FlashDevelop. If you can get a copy, do so. Keep in mind, if you wish to use Flash Player 8’s new Garbage Collector and filters, you’ll need Flash 8, and if you wish to compile to Flash Player 9 for use of full screen functionality, you’ll need Flash CS3.

    If you are maintaining a Flex 1.5 code base, my heart goes out to you. In a box. Stabbed with a rusty knife. Send the box to your boss, maybe he’ll fire you, and you won’t have to maintain a Flex 1.5 code base.

    Gotchas

    This assumes pure AS, and doesn’t take into account components.

    If you are converting from AS3 to AS2, do a find and replace on the following:

    • void to Void
    • int and uint to Number
    • const to var
    • :* to :Object
    • protected to private
    • remove all “override”
    • public class to class
    • :Shape to :MovieClip
    • someMovieClip.graphics to someMovieClip
    • remove :void from constructors since in AS2 they cannot return a value

    I haven’t found an easy way to manage converting your package path back to prefixing on the class name, so have been doing this as well as deleting unsupported imports by hand.

    If you use the Graphics.drawRect, you’ll have to write a wrapper function that emulates what it does. There is some good AS1 code on Adobe’s site to write a quick Utility class for drawing.

    Your creation methods and addChild/removeChild is really where a lot of your work is. Converting them to attachMovie factory method is correct, however, making a method that checks for types is a little better to at least ensure your variable casting is good to go. Know, however, that MTASC in FlashDevelop, and the Flash IDE expect different things in different places. Casting in AS2 doesn’t always work, nor is it always consistent like AS3. You don’t have the as keyword, and as such, you can only cast to things that don’t have constructors that do magical things, like Array that actually makes an array vs. casting to an Array.

    If you want addChild/removeChild features, use _visible = false, _visible = true instead.

    Watch your default values with magic numbers. Changing your scaleX to _xscale is not enough; remember, it’s:

    AS3: scaleX = 1
    AS2: _xscale = 100

    Big difference. Same goes for alpha values.

    While try / catch blocks are supported, they do something uncool in my opinion. In Flash Player 9 using AS3, you get an exception window in the debug player. In AS2, you do not. You’re code magically stops and you have no idea where. All exceptions are usually automatically caught and handled internally in AS2 and below, so if you check a null value, the next line of code is still run, and your app goes on it’s merry, albeit wrong state of mind, way. This made bug hunting in AS3 a lot easier than in AS2. It also made try catches actually useful vs. something to make the Java devs feel comfortable in ActionScript. However, try catch blocks in Flash Player 8 and below actually abort ALL code in the stack; this can be viewed as a good or bad thing. Good because if nothing happens, you can blame it on a try catch block. Bad in that it can be really hard to see the ramifications of the bad code. This makes it really hard to debug other parts of your application using breakpoints in the Flash IDE because if the try catch aborts a stack that would of caused your other code to run, you’ll never get there.

    Interfaces do not work very well in ActionScript 2. Furthermore, you cannot have getter / setters in an AS2 interface. While extending works, the implementations can be really tricky. If you spend more than hour fighting your code to accept the interface, go with convention, and just trash the interface… or use a psuedo base class. If you can’t use a base class, use a mixin (a class/function that adds methods to a Class’s prototype at runtime or simply just decorates an instance).

    A note about using mixin methods; those too also don’t always work with interfaces. For example, this:

    function removeEventListener(target:String, listener:Object):Void;

    In your interface doesn’t think this is a valid implementation:

    public var removeEventListener:Function;

    While it’s technically correct, what it doesn’t know is that at runtime, with the mixin, it WILL be. There is where tools & languages haven’t matured enough to support prototype classes. Therefore, just re-define the method the correct way to match the signature, but don’t have it do anything. Yes, it uses slightly more RAM and resources, but oh well.

    Don’t expect your initialization order to be correct in static methods. Meaning, if ClassB uses ClassA, one would expect the compiler to see that, and initialize ClassA first, and then ClassB. This was a problem that surfaced in Flash 5, was fixed via hardcoding the initialization order in Flash 6, and eventually done by the compiler in Flash 7. It doesn’t, however, work that great at least in some static methods that do class constructing things while the application is initialized. You may be able to hack it by writing your own class initialization stuff inside a MovieClip with an #initclip 0, but in my quick test, like zee goggles, it do nothing.

    If you don’t know what a Delegate is, don’t worry about it. Just change this:

    something.addEventListener("eventName", functionHandler);

    to this:

    something.addEventListener("eventName", mx.utils.Delegate.create(this, functionHandler));

    Keep in mind the MTASC compiler uses a stricter set of rules (yes, even with strict mode turned off) and doesn’t work natively with the mx components unless you explicitly tell it to ignore them. FlashDevelop has GUI options for this vs. writing command line compiler options. The one thing that can cause issues is intrinsic files; files used to represent classes native to the Flash Player, but still needed for compile time checking. This are AS2 classes that have method & property signatures, but they don’t actually do anything. This can cause problems when they differ.

    For example, NetConnection has a method called connect. Depending on what documentation you read, it can return different values. Flash Communication Server (now known as Flash Media Server) says it returns nothing; newer docs say Void, whereas MX 2004 says Boolean. The Flash AS2 compiler assumes Boolean as well, but MTASC’s intrinsic says Void. You’ll get this neat error message in FlashDevelop saying “Void should be Boolean”, yet it points the error being in the intrinsic. So, you can either edit the intrinsic, or just add that one particular file to an exclude list, and move on knowing it’ll compile just fine in Flash.

    That’s all the major stuff. Good luck!

  • DoubleClick and ActionScript 3?

    Has any used DoubleClick’s Dart/In-Stream, etc. solutions with ActionScript 3?

    They currently only support ActionScript 2, 1, and 0 (code on frames). They do not support going directly to their web services. We entertained reverse engineering their API, but the problem with that is being held accountable for the video metrics they handle via FLVPlayback/NetStream and having to emulate those perfectly. This is also why an AS2 / AS3 LocalConnection option won’t work out well because you have basically write a Facade NetStream, and pray you not only match every method, but also dispatch every event.

    Naturally I’m not looking forward to using AS2 for a number of reasons. AS3 would of allowed us to use runtime skinning, thus reducing the amount of code we need maintain for a variety of clients; skin.swf’s vs. unique video players that increase weekly resulting in a large maintenance cost.

    I’m still investigating 3rd parties that usually act as the middle men to DoubleClick, lowering the amount of bling you have to front to even get a return phone call. Apparently some of these firms have API’s of their own that abstract DoubleClick since they wrap their own reporting and billing data around it.

    Anyone???

  • I have a hard time writing slow ActionScript 3

    I have a problem going backwards. When I learned attachMovie in Flash 5, that function was the death knell for my Director career. “Create something from nothing!?!?” :: queue Quake sound :: “GODLIKE!!! (nsfw)“.

    In Director, everything you wanted to be on a depth had to have had something there originally, put there on the “score” (Director’s timeline). If you didn’t do this at author-time, you couldn’t swap things out on that depth. The attachMovie function in Flash was great because this didn’t matter; I had thousands of depths to play with; the sky was the limit!

    I later learned the sky on _root had a limit; it was called the Settings Panel. Lakitu wouldn’t even go near that elevation. It didn’t matter though; creating new MovieClip’s allowed millions of depths that designers & coders never used; it was wonderful.

    To be fair, you could abstract this stuff in Director. The crew over at Director-Online had at least 2 sprite engines that emulated what Flash did, with extra features. Furthermore, I couldn’t really appreciate this stuff back then anyway; I couldn’t even return values from functions. I just had functions set global variables. Class? Que? n00b.

    I tried going back after I learned some things, but I just couldn’t do it. Flash offered too much. It was soo fast. So much more effective. ActionScript just seemed more organized than Lingo.

    After getting over my frustration at AS1, I learned that I could create re-usable stuff. While I loved to re-invent the wheel ALL THE FRIKIN’ TIME, it did get tiring after awhile, especially when my 4th generation Scrollbar still lacked track clicking and scroll buttons. Creating re-usable tools was hot.

    After getting over my furious frustration with AS2, and learning enough design patterns to pretend like I knew what I was doing, I slowly developed a loathing for AS1. I then had a hatred for anything not AS1; aka, code puked on frames.

    I remember seeing a lot of creative things done with prototype in ActionScript 1, however, and even some still in AS2. So, I tried to go back, and experiment. I always ended up getting bit in the arse in the end.

    When AS3 came out, the early version, it actually wasn’t that different (for me) from AS2. AddChild vs. createNewMovieClip, aka the new DisplayList was pretty easy. Protected vs. private, and other namespace features made sense pretty quickly too. The only hard thing was learning the immensely large new API. It’s one thing to remember that a CheckBox emits both a click AND a change event in the Flex SDK, and you need to care about the latter… it’s another to remember that navigateToURL is in the flash.utils.* package. Even the built-in stuff is immensely large.

    What is interesting, though, is that I never developed a hatred for AS2. Because of the complete and utter lack of communication between the 2 AVM’s, combined with Flex’ slow rise to power meant a lot of parallel AS2 and AS3 work. If you asked me if I wanted to do an AS2 or AS3 project, I’d probably respond AS3, unless your deadline was a week or less.

    …and that’s my point. Writing AS3 is slow. It’s finally reached a maturity as a programming language; a real language, not a “scripting language” because it now officially compiles to machine code on 3 differentchip sets. As a real language, it has all the features (most, hehe… private constructor what, abstract classes who?) a traditional programmer would expect from a programming language.

    My boss, a professional Java Developer who now does a lot of PHP (and I’m sure has a larger illustrious career I don’t know about yet), said that a strongly-typed language should be making me faster, not slower.

    In shock and anger, I pulled my phone from my pocket, called up “Bullshit”, and requested he leap upon my bosses’ head.

    There is a reason I click the “Flash” icon on my task bar, do File > New, hit F9, and test a new String parsing algorithm there in AS3 instead of going the ActionScript project route in Flex Builder… or even “new ActionScript File” and making it launching it as an Application. Flash is faster. Sure, once you get rolling, you can have some good test bed code combined with test cases even run by ANT in Flex. I’d still argue the instant gratification in Flash beats Flex.

    …but it doesn’t stop there. I mean, after hearing about things such as “int promotion” and “compiler optimizations based on clear, strongly-typed variables”, AS3 can get out of control. Parsing a pipe (|) delimited string, properties separated by commas (,), with name value pairs separated by equal signs (=) has gone from 15 lines in pre AS1 to 40 in AS3 if you ensure every parsed variable is strongly typed. For an algorithm that’s only run one time very rarely, AS3 doesn’t really benefit here.

    Fine? Then why not NOT strongly type so much? Only strongly-type to ensure you don’t get any type casting exceptions, and move on with life?

    …because… I … can’t. It’s hard to stop. I’ve been trained by the fear of the software engineer army to strongly-type everything. To ensure the compiler has a crystal clear understanding of everything, and that my code will run at moch-10. I can have faith that the old AVM will never even need gas, because the key in the ignition for it will never be turned. All the code I write now ensures everything is typed, and all namespaces are correct.

    I’ve tried abandoning namespaces and using *, Object, and even just abandoning type-casting in general for quick tests or prototypes. It’s just as time goes on, I find the code I add to those things starts getting more AS3 like.

    Bottom line, it’s really really hard to break the habit. Every time I go back to AS2 for some random project, I’m reminded how damn fast it is to create things in it. Half the exceptions I get in AS3 I really don’t care about, and don’t need to know about; they don’t impact the project from working if they are small in scope. A lot of my data is either primitives or simply arrays.

    For smaller projects, AS2 is still the bomb. For smaller algorithms, less strong-typing just results in less, more readable code.

    I can see why professional Ruby, JavaScript, and Python developers still exist. I don’t care what anyone says, loosely typed scripting languages still kick ass. While I wish their engines weren’t so damn slow for larger projects, lately, I’ve just been finding that for a lot of smaller scoped projects or areas, I’m glad I have the loosely typed option.

    While I fully believe the majority of the industry will use C# for Silverlight 1.1 going forward, MAN was it refreshing to write it in JavaScript for 1.0. Taking a break from AS3’s strict ways was great. SmartFoxServer has an option similar to later builds of Red5. You can write in the standard Java for performance reasons OR in your scripting language of choice (JavaScript, Python, etc). For a lot of work, scripting languages are good enough, and since they are good enough, you can write less code, faster to get the same result. That last part is debatable, but not by me. After having a career in both, to me they both clearly have their place.

    …what I can’t figure out is how to drop the “good habits” that AS3 teaches you to go back to fast and furious ways of scripting languages.

  • Weak Activation Object

    It appears either A) The Activation Object in ActionScript 3 is dumber than it’s predecessor, or B) the new Garbage Collector implemented in Flash Player 8 is more aggressive, or C) I’ve never had this use case. Naturally, I’d like to believe that it’s A, but I have a sinking suspicion it’s a combination of B & C.

    I read this post by Matthew Tretter describing how reference-less objects such as Tweens and URLLoader’s won’t work consistently when there are no references to them.  This is because they have no references, and when the Garbage Collector comes around, he sees this, and destroys the mofo’s. This is in direct violation of how a lot of us have coded in the past since Flash Player 6 implemented dynamic MovieClip methods like onPress, and onRelease. Using anonymous functions with anonymous variables was just the lay of the land:

    my_mc.onPress = function()
    {
        var my_xml = new XML();
        my_xml.ignoreWhite = true;
        my_xml.onLoad = function(success)
        {
           trace("success!, parse this.");
        };
    }

    In the above example, my_xml is a local variable. In ActionScript 1 and 2, no one has a reference to it. Thus, at the end of onPress, it’ll die… or, so it would appear. However, Garbage Collection first has to activate to kill it; theoretically GC only runs every 60 seconds, or when memory increases 20% in 1 frame. The GC will kill it if no one has a reference to it. However, the Activation Object does. For both XML and LoadVars, I and thousands of other Flash Developers have used this technique with a variety of ways to handle scope as well.

    You’ll notice, however, that this code isn’t very memory intensive, thus I guess staying under the radar of GC. It merely makes an XML object, gets the XML, parses it, and that’s it, done. When AS2 came out, I started keeping class references to these variables for ease of writing code, and confirmation I was in fact deleting them later when I was done. Therefore, my guess as to why I’ve never seen the problem Matthew talks about is that I’ve never created extremely memory intensive applications pre-AS2 that used of asynchronous operations created via local variables. Seems plausible.

    So, I told him he was wrong and moved on. He tracked my ass down to Flashmedia to politely plead his case. Turns out I was wrong… and extremely lazy. I didn’t do diligence and actually test his code. Upon testing his code (1000 creations vs. my 1), and his problem was easily reproducible. He’s created some classes that help encapsulate this so you don’t have to worry about it.

    For example, Robert Penner’s original Tween classes actually kept a global reference of all crated Tween instances in a static array, so there was always at least 1 reference. I had just always assumed that the Activation Object knew of asynchronous objects, and thus released the lock (killed the reference) on it after their asynchronous operation had completed such as onData, or onLoad for LoadVars/XML.

    I often create local variables for loading such as Loader or URLoader for generic loading code, so I was horrified that this scenario was this predictable. I’m not sure how to best resolve this yet since I’ve been doing this for years and it’ll really be a pain in the ass to start either keeping class references for these things or using a wrapper class. I only load 1 or 3 of these at any one time, not 1000 so maybe I’ve just gotten lucky all of these years. Maybe a beer will help… yeah… a beer…

    Anyway, I apologize Matthew for saying you were wrong without due diligence on my part; I was wrong and could of at least had the common courtesy to actually test your provided code before making judgments based on long held assumptions.