Archive for the ‘Programming’ Category

Weak vs Strong References in AS3

Sunday, December 9th, 2007

For those of you not familiar with the concept, a weak-reference is a reference to an object that will not hold the linked object in memory when that object is garbage collected.

There are only two ways to create a weak reference in AS3. The first is with the IEventDispatcher.dispatchEvent() method which allows you to create a weak link between the dispatcher and the listener. To quote the AS3 Bible:

ActionScript 3.0 introduces the concept of weak and strong memory references. Normally, an object will be garbage collected if there are no references to the object. That is, when no objects are using a variable, it gets thrown out. Weak references allow you to reference an object but the object will still be eligible for garbage collection unless another object holds a strong reference to the object. By setting the [eventDispatch() method's] useWeakReference flag to true, you will create a weak link between the event broadcaster and the event listener. That way, if an event listener is deleted while still listening to the event broadcaster, the weak reference will allow it to be garbage collected. This helps to prevent memory leaks.

The other way is with the objects used as keys in a Dictionary object.

ActionScript, unlike many other languages, does not have a way to explicitly remove an object from memory. Instead it waits until all references to an object are removed and then auto-deletes it. Therefore, an object will continue to stay in memory if all strong references aren’t removed.

Below is an example of how strong-references hold an object in memory. If you’d like to try this out, copy the below text into a file called StrongReferencesExample.as

[ftf]
package {
import flash.display.Sprite;

public class StrongReferencesExample extends Sprite
{
public function StrongReferencesExample()
{
// create a new object called dog. Add it to the first leash object
// and make leash2 a copy of leash 1.
var leash1:Object = new Dog();
var leash2:Object = leash1;

// tracing both leashes will show that they hold a reference to the Dog
trace(leash1); // [object Dog]
trace(leash2); // [object Dog]

// deleting the dog from the first leash will not remove it from the second leash
// even though we originally set leash2 equal to leash1
leash1 = null;
trace(leash1); // null
trace(leash2); // [object Dog]

// The object (dog) will not be free until all of the references to it (leashes) are broken.
leash2 = null;
trace(leash1); // null
trace(leash2); // null
}
}
}
// Define a simple Dog class within the same file.
class Dog {}

[/ftf]

Richard Lord over at Big Room Games has an interesting article on hacking AS3 to allow you to create weak-references to objects. The hack is pretty decent but lacks a few things I’d like to see like strong typing at compile-time or a more refined ‘memory manager’ type functionality. However, I tried implementing both of these and came up empty handed. If you can think of a way to make this strong-typed, I’ll give you a candy bar.

Using the WeakReference hack could be useful if you want to make sure that an object will not stay in memory if you forget to delete all references to it. However, keeping track of your objects and practicing good memory management is a much better solution and hacks like this one should be saved for special cases where tracking use of an object becomes difficult or impractical.

Thanks to Alex for the link!

Preventing Out-of-memory errors in Eclipse / FlexBuilder

Wednesday, December 5th, 2007

You may occasionally get an error that Eclipse has run out of memory. Part of the problem here is that Eclipse is only allocated 256MB of RAM by default. I’ve found this can be helped (but I sometimes still have problems) when I set my maximum memory allocation to a larger value such as 1024MB. Detailed instructions for how to do this can be found on the Eclipse help site.

If you like playing with runtime arguments like memory allocation, don’t stop there. Check the list of command line arguments on the help page listed above. I use -nosplash which prevents the eclipse logo from coming up during startup. Cleaning the Eclipse application with -clean can be useful too especially after installing plugins or when things are breaking for no reason. (Mac users can skip the tedious .ini editing process and do this by typing /Applications/eclipse/eclipse -clean in the terminal.

Skrypt Kidz 3000 - Episode 2 - Flash Developers VS. Flash Designers

Sunday, December 2nd, 2007

Skrypt Kidz 3000

A new episode of Brooklyn Skrypt Kidz has been posted where we talk about the ever-widening gap between Flash designers and Developers.

Go there / Do that / Be There

Discussion - Is OOP for OCD?

Monday, November 26th, 2007

[Repost from Jan 31 2007]

Recently, I’ve been playing around with compiling ActionScript 3.0 with strict mode turned off. This makes everything much more loose. Type checking is thrown out, classes can be dynamically altered - essentially, you sacrifice speed and rigourousness for flexibility and forgiveness. In other words, it’s compiled more like AS1 was compiled.
I’ve also been spending some spare time looking at Objective-C (the language used for Mac programming). Obj-C adds functionality to C which makes it sort of object oriented but in reality, it’s very loose. The book I’m reading seems to glorify the dynamic nature pointing out how nice and flexible it is to try to access something that might not exist within an object. Obj-C programmers tend to break the “is a” rule using inheritance to gain functionality rather than identity. Even though it all curdles my blood, it’s hard to deny that this is a system which allows you to very quickly (and fairly elegantly) create working applications.

So my question to you is this.
Is all of the effort that we as developers put into creating object oriented, well defined, interface driven, decoupled code worth the effort?
Is there a value in keeping things loose and dynamic?
Should we shun languages that make this impossible or difficult?

Skrypt Kidz 3000 Podcast

Monday, November 19th, 2007

Update: We’re up on iTunes!
Mims H. Wright - Skrypt Kidz 3000 - Skrypt Kidz 3000

A few weeks ago we asked you what you would want to hear from a new Flash podcast. The votes came in with a tutorial based podcast in the lead with 44%, followed by a discussion by experts with 18% and a healthy chunk of you (16%) thought it was irresponsible for us to bring another new podcast soul into this cruel world.

You told us what you wanted to hear and we listened to you.

But then we decided to ignore your suggestions and do something completely different.

It’s my pleasure to present Skrypt Kidz 3000 — a new semi-regular podcast where a barbarous crew of Flash and Flex developers get together to spend our precious weekend hours yakking about Flash issues. In our inaugural episode we discuss the pros and cons of using Flex over Flash. We also talk about Flex and FDT pricing and Adobe’s new wireframing tool Thermo.

Runtime Stack Information for Logging and Debugging

Sunday, November 18th, 2007

Or, “Hack Your Stack for Fun and Profit!” Yes, this is really and truly a hack, my friends, but, like many hacks, you might find it very useful. Using the Stack class I provide, you can get all sorts of information about the code being run right now: the package, class name, method, filename, and even the line number. You can also grab an Array version of a stack trace and follow it up. Sweet!

So check out this egregious hack. First, you grab the stack trace by throwing and catching a dummy Error and copping its stack trace as a string. Note, that this technique only works (and is only useful) in the Debug Player.

public static function getRawStackTrace():String
{
	var stackTrace:String;
	try
	{
		throw new Error();
	} catch (error:Error) {
		stackTrace = error.getStackTrace();
	}
	return stackTrace;
}

Then you slice it up into lines, and hack those lines into their constituent parts by some crazy regular expressions. That’s pretty much it.

public static function getPartsFromStackTraceEntry(stackEntry:String):Object
{
	return stackEntry.match(/(?P<package>[\w\d\.]+)::(?P<classname>[\w\d\.\:]*?)(?P<isStatic>\$?)\/((?P<scope>[\w\d\.\:]+)::)?(?P<method>[\w\d]+\(\))(\[(?P<filename>[\w\d\\\/\.]+):(?P<line>\d+)\])?/);
}

Fun, right? The properties in the returned Object are:

  • package
  • classname
  • isStatic
  • scope
  • method
  • filename
  • line

You can clean this up into package.classname::method with getSimplifiedStackTraceEntry().

So that’s it, it’s just some regular expressions, but with this hack you can pull out all kinds of juicy information about the context your code is running in. It can be useful for your own debugging, logging, and error reporting.

filecom.yourmajesty.debug.Stack View Source | Download (.as, 2k)

Code Samples for ActionScript Bible are online

Tuesday, November 13th, 2007

Hey people,

I and my publishers have gotten many comments about the lack of code samples on the AS3 Bible website. I just wanted to let you know that they’re up (mostly). The remaining chapters should be up this week.

Get it here under the download tab.

Cylinder Mapping

Monday, November 12th, 2007

At Your Majesty, we worked on a site where some images appear on different products. I had my hands full with the image generation backend and the hosting issues to work too much on the Flash, but I was able to contribute one effect. I wrote a cylindrical mapping class which let us put any image on a mug as it rotated in three-space.

The process for building this was actually kind of interesting. I ended up actually using that graphing calculator that comes with OS X to preview different equations. I figured, if I could visualize the cross-section of the cylinder across the axis of distortion, then I would have an appropriate function to generate the distortion for each pixel, so I plotted a bunch of different equations interactively without coding them up. For the vertical displacement, the curve of the top lip (and the entire front) of a mug looks like a semicircle, perhaps squashed, so I quickly ended up the equation for a circle, y² + x² = r or y = ±√(r - x²). However, the sides are a bit more exaggerated.

Word to first-time displacement map users like myself, using the drawing API’s gradient tool as a source for displacement map data is not going to yield very good effects, since it seems that it only interpolates between colors linearly, which won’t do much more than shear your image.

So here’s the effect applied to my banner. Scrub the mouse left to right below to “rotate” the “cylinder.” You can see that while the speed of the effect of course scales with the size of the distortion map, it is very fast.

If you see this message, you need to install Flash Player 9.


The code isn’t all cleaned up but at least the interface is clean. We simply create a new distortion map with a size and a display object to attach, set some parameters, and attach its ‘wet’ output to our display list.

map = new CylinderMap(200, 200, new IMAGE());
map.sideCompression = 100;
map.arc = -0.3;
map.rotation = 100;
addChild(map.wet);

And here’s the code for the displacement map class.

filecom.yourmajesty.effects.distortion.CylinderMap View Source | Download (.as, 5k)
filecom.yourmajesty.effects.distortion.IDistortionMap View Source | Download (.as, 1k)

ActionScript 3.0 Bible Available Now

Tuesday, November 6th, 2007

View this article in other languages:

After nearly a year in development I’m very proud to announce that the ActionScript 3.0 bible has hit the shelves. This is our first book and its very exciting for us. The AS3 Bible is not just an update to the previous edition, the Flash 8 ActionScript Bible, but was written from the ground up with ActionScript 3.0 development in mind. We tried to focus on topics that matter to real world developers and to make it just as useful for experienced AS2 developers as it is for beginning programmers.

We’ve put a lot into this book and sincerely hope you enjoy it.

Get it at Amazon

NOTE: many people have been complaining about the lack of code on the companion site. We’re currently working with our publisher to get that sorted out as soon as possible and hopefully it should be up by the end of the week.

Mims with Bible

I asked a passing hobo to pose for a picture with the new Bible

Flash / Flex podcast

Wednesday, October 17th, 2007

I’ve been kicking around the idea of starting a Flash / Flex podcast. The plan is to get drunk and talk about Flash but maybe you have a better idea.
Do you care? Would you listen? What should we call it? What should we talk about? What topics would you like to hear discussed?
Please leave us any feedback you like.

{democracy:4}