Windows, I’d like a divorce… the kids? You can have them on the weekends.

This morning I woke up at about 9AM with a massive hangover. Groan, complain, shut up Dylan you’re just a pussy. I stumble over to my PC per usual to my daily routine and notice my computer had rebooted in the middle of the night and there is these strange visual artifacts strung across my screen.

Damn it!

I go to do something and load my audio application, and I am greeted with a stutter of sound, the video driver resets itself, and then frozen. Yey! I get to spend my wonderful Thursday hungover and repairing my Windows Vista install… yep, I was just ASKING FOR IT.

No, screw this. I’m sick and tired of this. 95 was just ugly, 98 was just broken, 2000 was just handicapped compared to XP, XP hated me and gave me strange IRQ request errors, Vista has been fine for the most part… until now.

I’ve always dual booted some flavour of Linux for several years now. My favourite flavour the past 2 years has been Ubuntu Linux, big surprise, she seems to be the Unix slut of the century! And if you know me, I just love me some sluts. I’ve never made a 100% transition to Linux due to some user-unfriendliness and the lack of support for some of my software even through emulation.

But it has never failed me. It just always worked. Well… older versions didn’t “just work”, but these fresher and newer distros today have been fixing that. That and I have a few years of experience playing with it now that I think I can fully handle the transition.

So instead of wasting my day on repairing my Windows Vista install (i know, i know, I shouldn’t of even got Vista, but if you saw what XP did to me you’d get it. And to you Mac fags, SHUT UP), I’m going to just make the full transition to Ubuntu. I will be setting a VMware guest install of Vista as a test bed so I can debug stuff I write for Windows, it isn’t the best way to debug, but it should cover most bases. Anyways it isn’t like I’m writing stuff that is really all that intensive on Windows… coding video games and Flash isn’t that special that a VMware guest can’t work.

Downside is I probably have to now teach myself OpenGL, I mean if I’m going to stay here in Linux now (I’m writing this on my dual boot Ubuntu install, must not be hardware if she’s running great) I better consider it. DirectX doesn’t work over here. But I’ll probably stick to learning DirectX and run through VMware because well… DirectX is viable, OpenGL is just fun.

Wish me luck…

You know where the dictionary is!

Several times when I was a kid I would be reading a new book, possibly for school, or because my mother gave me another book from the shelf to entertain me on cold winter days. If I wasn’t outside I should be reading. I’m not saying I had one of those anti-television moms who was tyrannical about my TV viewing schedules. I watched a lot of TV as a kid, but my mother was very sensitive to the idea of convincing to something else. Instead of telling me I wasn’t allowed to watch TV she supplied me with tons of things to do that were really fun and didn’t take place in front of the TV set.

You know, erector sets, legos, chemistry set, puzzles, board games, and books for in doors. The only thing she was demanding about was being out doors. It was just a normal rule, boys are to be in the sun when the sun is shining. Boys can drink from the hose. Boys can pee in a bush standing. So stay the FUCK outdoors, this is me time!

I’m deviating, so back to the point.

When I was a kid I spent a lot of my time reading books. I like geography, rocks/geology, dinosaurs and math, and these books were full of big words that I had no idea what they meant.

“Maaa, what’s a fractal? What’s does poly mean? MAAAAA I can’t read this word… ig… ignep… igneee…”

“You know where the dictionary is!” would be her response. 7 times out of 10 it was probably because she didn’t know the meaning herself, and she has admitted this. I was reading math and geology books, my mother was into Hemingway and Shakespeare, not little boy stuff. Just as big and complex of words, but never any of the words I was reading. So I was forced to look the damn word up myself.

I wanted to know how to spell something it was a 10 minute discussion about sounding the word out, breaking the syllables apart, and comparing them to known syllables in my lexicon. Over time I was trained to recognize the meaning of a word due to its similarity to another word.

The definition of telepathy: the transfer of thoughts with out perceptual sensory

I learned to infer the meaning from tele in telephone which to me meant remote or transfer. And pathy from words like sympathy, and antipathy means feeling. From context then I could make the educated guess that the word meant transferring feelings remotely.

Reference Materials
Reference materials are things like textbooks and periodicals. We all know them, when you write a research paper you consult several reference material for facts on the matter you are researching. Back in the olden days before us lucky folk had this great reference material known as ‘teh interwebs’, we had to consult this hulking books of madness like encyclopedias.

Sometimes I wonder how many kids today witness an encyclopedia. I mean it has been only a decade since the internet has entered all our homes and already it seems like we’ve lost interest in a lot of these reference materials. Encyclopedias exist for free in digital form now and don’t take up the 3 shelves on the family book shelf they used to!

Why I bring this up is today we kind of take for granted the tools we’ve been given for finding our way around these massive databases of information. When you go to Wikipedia for information you don’t read the entire contents of Wikipedia, that would take you your entire life! You search it for the topic you require using its search engine.

Encyclopedias and textbooks had much more archaic forms of this as well. You had to consult the glossary, appendix, table of contents, etc if you wanted to locate something in the book. If it was a series of books, like an encyclopedia, it was broken into letters. Or in more robust scenarios we devised sorting tools like the dieing dewey decimal system.

We know these exist, I’m not saying you the reader are an ignorant fool betrothed to damnation due to a lack of ‘culture and tradition’ because you’ve embraced technology. BAH! I’m not saying this at all. Come on, I’ve engaged myself in bleeding edge technology since I was shittin’ yella!

No what I’m trying to make a point of is that these archaic search tools required a lot more work from you the searchee because they weren’t nearly as helpful as GOOGLE. Paper & ink costs money and there is only so much space to fill with words pointing to the pages of a text to go to for a certain topic before it becomes convoluted and just as difficult to search through as it would to just read the fuckin’ text itself.

Instead you had to generalize the topic you were searching for. If I wanted to read about black soldiers who fought in the civil war for the confederate army, I couldn’t just type that into a search box and find all relevant material pertaining to the subject. I first searched the libraries dewey decimal system for books on Civil War material, then I narrowed my search to stories from the confederate army, and further more to black soldiers. Of course a few books directly about this topic are going to pop up, but I’m missing out on a lot of books that have a couple chapters about it as well. So by broadening my search this way and consulting the different indexes of the books I could collect up a large reference pool for myself. It also took an hour to just find the books!

But along the whole path I honed a very important skill. The ability to break apart and compare systems to each other by generalized descriptions. There is a reason us humans like to sort things and cast labels to things, it makes it far easier to locate the stuff we need when we need it!

This skill has evolved though with the onset of ‘teh interwebs’. The process of sorting this material and information has a new middle man, no longer is it the appendix and dewey decimal system which is very tangible, it is now search engines and databases. A less tangible and very complex pool of algorithms and information that most of us don’t fully understand yet. But the principals are still there, these algorithms for sorting the data were devised by the same human intuition of categorizing and utilizes the same basic concepts of breaking apart systems into generalized groups. We just need to utilize these tools to hunt for our information.

I meet people a lot who wonder how it is I find the information I find via google. Or I meet others who say “I google’d it and came up with nothing on the subject”. Come on now, google isn’t a human, it can’t figure out what you are asking, you have to ask it the right question. Very similar to how you had to ask the index the right question. The great part is your choices of different things to ask it is far greater then that of archaic text books. There is limitless amounts of storage space for it and with the right principals it can be stored in a less convoluted manner masked from you the ‘searchee’.

There shouldn’t be this error of an inability to find an answer via google. You just are looking for something way to specific. Which brings me to a more annoying subject that I am upset about!

Do you really want information!?
If you’ve made it this far into this blog entry, you must not have a problem reading. We are already 1300 hundred words into this article and you’re still here! So why is it you are afraid to read through your search results? Google and Yahoo aren’t going to just hand you the specific website and direct you to the correct paragraph with the answer you want. It might if you are searching for a specific item, but that’s not research, that’s just bullshit consumer shopping (2007 hottest google search word was ‘iphone’). Yeah that might spit the answers you are looking for fairly quickly because it’s the freakin’ iphone! There is a reason why trademarks exist, the name is recognizable and unique, thus finding information about ‘iphone’ will always result in iPhones!

But searching for something more arbitrary like ‘vector’ isn’t going to be so helpful. Just because you google’d something more vague and it didn’t give you the exact answer you needed, don’t give up there. Don’t go running to mommy (or forums and newsgroups) to ask a human the answer, you’ve completely given up on the entire purpose of the internet!

Never mind the fact you’ve given up on the entire practice of learning. Consuming processed information is not learning, it’s memorizing processed information. It’s like this, knowing 12 * 12 = 144 because your teacher pounded your times tables into your head in 3rd grade doesn’t mean you learned to multiply. You merely memorized that 12 * 12 is 144. Where is the concept of multiplication in that?

So when you are searching a topic that you don’t know a lot about and you don’t know enough information about the topic to infer relative search words, then read what results you get. Do you know what a geometric cartesian ‘vector’ is? No you probably don’t, and you probably didn’t know that the geometric cartesian part was part of what it is called. But I guarantee anyone who has spent any time in an art program or tinkered around with programming has at least heard someone say what it is. Hasn’t that alone tickled your brain into wondering what on God’s green Earth the freakin’ thing is!?

hypothetical
You are building a small flash animation in which you move vector art around the screen from position to position. You want them to follow some path, but the path is dynamic and changing depending on the user input. You do a search about animations and you see people talking about animations, but nothing specific to the exact animation you want to create. But you notice a repeating themes, people are talking about vectors and cartesian coordinates. Vector, you remember that word when you were in flash, it was used to describe the kind of graphics it displays. A recurring theme!?

Well I bet though if you searched the word ‘vector’ you’d get billions of results and only 1% of them would actually talk about the mathematical ‘vector’. Your results will probably turn up things like:

  • Vector art/graphics
  • Vector type Array
  • Biological creatures that transmit diseases
  • topic about aeronautics and aerospace
  • amongst much more…

By reading this you will probably quickly learn there are tons of different applications of what a vector is, and that this application is very broad spanning across multiple topics. Along the whole line though you will probably notice a repeating theme… it has to do with direction, magnitude, values… sooner or later you probably should get that this stuff is applied to math.

Now you continue your search for mathematical vectors and you probably find the geometric cartesian vector. An ordered set of values that represent magnitude and direction. You’ve now found the guts of the topic. Extending further you probably will then search for arithmetic process of vectors and learn about dot product and the sort.

But you remember back to the initial search you made of ‘vector’ and maybe remember that result where there is a category of creatures called vectors when they are a host to some parasite that is used for transmitting the disease. Such as a mosquito that carries the ‘West Nile Virus’. And how in aeronautics it was used to describe controlling the direction of airplanes. You then can infer that this name was used because the action resembles that of a vector. The virus travels in a direction through the insect to its victim.

The amount of reading you partook maybe took an hour or two. Comparable to the time it would have taken to just search your local library for books, let alone read them. And you’ve left with a very robust understanding of what a ‘vector’ is. Now you return back to these discussions you found about animations that weren’t quite like yours, but now that you understand the technique that is being used you get the principal of the process.

Now you can create your animation with out copying someone else, but by utilizing there techniques. Was it really that hard? I hope not. Did you learn something new? Oh I bet you learned more in that 2 hours of research then in an entire month of Algebra class in high school. Furthermore I guarantee you’re going to remember this information far more easily then any of that pounded memorized shit you learned like your times tables.

In Conclusion
In school they made you do research papers for a reason. It wasn’t to learn about the topic you did the paper on, that’s why they let you pick whatever topic you damn well pleased. It was to teach you how to search for the information. You were given a choice of topic to make sure you were interested enough to actually do the work… kids just aren’t interested enough most of the time.

I personally think schools should endorse the use of the internet as sources for a research paper, because the internet is becoming the largest reference material known to man right now. But the search tools given to us are vastly more complex then what we are used to. I understand an educators discomfort in this because there is so much misinformation on the web, but students need practice so that way they can learn to sort out the garbage from the good.

For instance I had college professors that didn’t allow wikipedia.org as a reference, so people just avoided it. But I still used it, and pointed out to everyone in class that why not just go there for information and locate THEIR references. They are located at the bottom of the page for you, as proof that this information was legite. You want to avoid misinformation, look for the source. Don’t take the writers word because he says so, get his source and make sure it’s reputable and that he actually matched the sources argument. There’s a reason we trust Webster for definitions of words, the publisher is held responsible to produce accurate information. So go through the not so reputable sources to locate the reputable sources held accountable!

We need to practice using it so we can adequately get information out of it.

Instead of using it to search for porn and iphones.

Random site updates

So I updated some things around the site.

ArtWork
There is a new artwork tab showing off some of my really bleh artwork. It’s just some random stuff from over the years, and is mostly a visual tale of why I don’t use a lot of graphics in my projects. I’m not a graphics major, I design games, program, and do math… not draw. Not to say I’m bad, I’m just not good. I do find pleasure in doing it sometimes, and that’s what this tab is all about. The ones I’ve done and enjoyed doing! Keep in mind for you photo fans out there… I was never a digital photographer. Most of those photos are from the late 90’s to 2001. My black & white or sepia work was always developed in my dark room with my own lab. I never had the pleasure of these new-fangle digital cameras with their autocorrections. So yeah, the focus is a little whacky at times.

Donations
I added a donations link to the website. It’s kind of conceded, but hey, it can’t hurt… or can it? Anyways, if you like any of my source code, or any of the code that WILL come in the future. Let me know. Donate a couple bucks if you want. It’ll probably kick me in the butt and give me more initiative to share the code to some of my more complex applications. A lot of the tech blogs I write aren’t easy slap dash jobs done in 10 minutes… they can take several hours, and in some cases a couple days.

I hope everyone benefits from my work!

Portfolio
There has also been some additions to my rather lacking portfolio. I’m skimming through my actual portfolio looking through projects to see what I can publicly show off. There are a lot of things I can’t show you guys due to verbal contracts with customers. I never signed anything with these people saying I wouldn’t lay claim to it, but it is an assumed point, and I don’t want to offend anyone in that matter. They DO pay my bills and all!

Anyways, there were some additions.

There is a small Tetris style game I wrote in a days time, it’s a Beta build, but I think it’s kind of fun for what it is.

There is also a demo of the AiEngine I’m building right now, once I get far enough along with that Engine and get a good portion of the game I’m developing it for I plan to write up a series of articles about it. And of course I’ll be releasing it to you guys the public!

Also I added a basic flash website design I put together for a friend. It’s nothing really special, but it isn’t the graphical part of it that really matters. The website is dynamic in that it can have all its content updated on the fly via xml files… no need for these fla templates that you have to open up, and hack around in code for. Just change the image on the server, or add a song to your playlist, and the swf is updated on the fly.

Event Dispatcher Woes, who is listening?

So I’ve noticed there is a lot of confusion around EventDispatchers in the Actionscript 3.0 library. I myself have been rather confused about this very annoying little method of capturing events in an application for quite some time. With practice and diligence though you sooner or later just figure it out. I fault this partly on the very poor documentation on the Adobe LiveDocs, but it also has to do with our innability to just sit down and think about how garbage collection and EventDispatchers would actually work.

When does an EventDispatcher become elligable for Garbage Collection?

This is our big question really, isn’t it? When you go an add an event listener method to an EventDispatcher, there are these 3 extra params other then the type and listener function: capture phase, priority and weak reference. The latter of which a lot of people, including myself for some time, looked at backwards. The ‘weak reference’ param has nothing to do with EventDispatcher, then what it actually has to do with the ‘listener function’.

When does an object get collected?

the word pointer used in the subsequent article does not refer to the Pointer type prevelent in major OO languages like C++, unless otherwise stated.

So let’s start at the root. When does an object get collected by Garbage Collection? Well that’s an easy answer, when no other persistent object contains any reference to said object. Easier said then interpretted though. What does this mean? Well let’s first approach this from a memory stand point.

In Actionscript 3 you don’t have direct access to memory, it’s a big security risk that would allow the programmer to exploit some of the freedom the stack and registers give you. I’m not going to get into that, just understand you are removed completely from the local user’s memory management. Now all object’s are constructs of simpler data, which are constructs of even simpler data until you finally get to the basic construct of prims and operative code. The actual compiled object is no longer an object, but instead a large outline of operative code and primitive types. All of this takes up space in memory, so when you instantiate an instance of any class, it takes up a certain block of memory allocated to the Flash Player.

The Flash Player watches all your objects in memory and keeps an eye on if you are actually utilizing it or not. If you aren’t it throws it away to free up memory for new objects to be instantiated. But it also only does this when memory is needed! It doesn’t just do it because you’ve stopped using an object. The process of ‘sweeping’ the memory takes up processing power, so it isn’t done consistently. The sweep get’s triggered when it notices there is a necessity for memory and the memory is reaching brimming point. Basically meaning, it checks System.totalMemory, and if it exceeds a certain point it sweeps through the memory and clears out unneccesary objects.

We finally come to what regulates IF it is elligable or not. This is the simplest of things. The actual decission is unidirectional, this means that it is if IT is being referenced, not if it references something! Unidirectional is like saying, “all oranges are fruit, but not all fruit are vegetables.” The opposite is called cyclical logic, and usually allows faults, cyclical logic fails when you say, “All apples and oranges are fruit, so all fruit must be apples and oranges.” Faulty logic!

When you are in a language with memory management, like C, or C++, you have what are called ‘pointers’. A ‘pointer’ is a direct reference to another object. It links two objects in memory so the one being pointed at is dependent on the one pointing. This is a direct persistent reference. In Actionscript you perform this task implicitly by creating a property of an object with a reference to another through a variable:

public class ClassA { protected var _obj:Object = new Object(); public function ClassA():void { // } }

Now remember, “_obj” is not the object it is referencing, it is just a reference. If you say _obj = *anotherObject*, the original object still exists in memory. It just isn’t referenced anymore. This is what we mean by referencing, what ever _obj ==, there is an implicit pointer drawn from the instance of ClassA to the instance of Object it is referencing. When the Garbage Collection sweeps the memory it notices that this one object pointing at another and skips over the object being pointed at, not the one performing the pointing, remember it is unidirectional.

Now most of you Actionscript coders know this and no to completely remove something from memory, you stop referencing it. BUT we forget about a few things. The AS3 library is full of different classes that we don’t have direct access to, and some of their methods create these references with out us knowing it. One of these Classes that does this is the EventDispatcher and the addEventListener() method. This method creates two references:

  • The Event Capture Phase references the EventDispatcher
  • The EventDispatcher references the function to call

The first of these two references ALWAYS occurs. By adding an event listener to an EventDispatcher, it will alway remain in memory until you remove it, this is because it has become a member of the Event Flow and thusly is referenced and can’t be removed. The second reference, the event listener referenced by the EventDispatcher, can be weak or strong. This is set by the ‘useWeakReference’ Boolean param when adding the event listener. By setting this to true this means that the the FUNCTION, not the EventDispatcher, is being losely referenced. This allows the object containing said function to be available for Garbage Collection no matter if some EventDispatcher is dispatching to it.

For instance, let’s say you create a Button and add it to the DisplayList. You then create a Sprite with the image of a box in it and add that to the DisplayList. Finally you add an event listener to the Button that says to fire a function that is a member of the Sprite. The function in the Sprite tells the Sprite to change its colour. Now later on down the line you remove that Sprite from the DisplayList and want it to get collected by Garbage Collection, by setting the “useWeakRefernce” param to true when setting the event listener, you no longer have to remove the event listener from the Button for this Sprite to be collected by Garbage Collection. It just get’s removed.

Let’s look at some code and you will see what I mean:

package { import flash.display.Sprite; import flash.events.Event; import flash.system.System; import flash.text.TextField; [SWF(width="500", height="300")] public class Main extends Sprite { public function Main() { initAsynch(); } protected function initAsynch():void { var obj:Object = new Object(); obj.updateToss = function (e:Event):void { e.currentTarget.x += 1; var val:Number = (e.currentTarget) ? e.currentTarget.x : NaN; trace("obj.updateSprite", val, System.totalMemory); }; this.addEventListener(Event.ENTER_FRAME, obj.updateToss, false, 0, true); this.addEventListener(Event.ENTER_FRAME, updateToss, false,0,true); this.addEventListener(Event.ENTER_FRAME, update, false, 0, true); } protected function updateToss(e:Event):void { e.currentTarget.x += 1; var val:Number = (e.currentTarget) ? e.currentTarget.x : NaN; trace("Main.updateSprite", val, System.totalMemory); } protected function update(e:Event):void { for (var i:int = 0; i < 100; i++) { var tf:TextField = new TextField(); } } } }

Make this your document class and run it. First notice that ‘this’ is persitent, it won’t be removed from memory because it is the base Object of the movie. Now notice I attach to methods to ‘this’, the local member function “Main.updateToss”, and a non-member function “Object.updateToss”. I then force Garbage Colletion in real time by filling the memory up with hundreds of TextFields in “Main.update”, I use TextFields because they are meaty memory hogs. After a few updates Garbage Collection has to run to make room for new TextFields, all the old TextFields are cleaned out, as well as the Object that contains “Object.updateToss”. You should notice that in the console output “Object.updateSprite, ###, #######” only traces a handful of times, but “Main.updateSprite, ###, ######” continues to run! This is because obj got collected up by Garbage Collection because no other object referenced it, and I don’t allow the EventDispatcher reference it by setting “useWeakReference” to true.

Now let’s change out these lines:

this.addEventListener(Event.ENTER_FRAME, obj.updateToss, false, 0, true); this.addEventListener(Event.ENTER_FRAME, updateToss, false,0,true);

so that it says:

var spr:Sprite = new Sprite(); spr.addEventListener(Event.ENTER_FRAME, obj.updateToss, false, 0, true); spr.addEventListener(Event.ENTER_FRAME, updateToss, false,0,true);

Note again there is no persistent reference to the Sprite, but yet it still remains in memory. Object.updateToss get’s thrown out though because we’ve used a weak reference. By adding an event listener that is persistent to the Sprite, “Main.updateToss”, the Sprite remains. We have to remove this event listener, and the crappy part is there is no way to create a weak reference in the Event Flow.

So in conclussion, remember in the future that by adding an event listener to an EventDispatcher creates a persistent reference to the EventDispatcher no matter what. The ‘useWeakReference’ has nothing to do with the EventDispatcher, and only deals with the event listener function attatched to the EventDispatcher. Always clear up events no matter what!

I’m INVISIBLE!!!!

Abstraction is an art all its own. Especially when dealing with preformed libraries. In Actionscript 3 / Flash you are handed a very visually determined class hierarchy. Nearly all the objects you create with the flash library are already members of the Flash Display Engine and hide all the nitty gritty stuff from you the programmer. A lot of novices don’t know how to break away from this construct, so here I’m going to show how to abstract the visual side of a project from the actual guts of the project. I will admit, the handful of code I’m going to show you isn’t the cleanest method for doing this, but it’s a very simple way of seperating the two.

The Ball Game

In this project what I’ve done is set up a very basic program with balls bouncing around inside of a rectangular space. When describing this application in code though I reference NOTHING of a visual aspect. My container is just a Rectangle Object referenced in the BallGame Class. The actual visual side of it is all described in the GameView Class.

As for the “game” it is made of 3 basic classes:

As you can tell by looking through the code none of the classes extend a DisplayObject and have no visual information about them. I’ve done it this way to completely seperate the animation itself from the visual side, only for the purpose of example. This isn’t the best way to perform the job. You can still abstract the view completely but make a better visual container for all objects by creating your own custom DisplayObject class which all objects either instantiate or extend. More on this method in later blog entries.

Now these three classes on their own will perform the animation completely and accurately, there just wouldn’t be any visual side to show the user the outcome. But rest assured it all runs properly in the background. In turn though you lose the functionality of so many methods and options that the Flash DisplayList gives you, like placing children into some parent’s coordinate space, or checking overlapping boundaries of DisplayObjects. All this has to be done by hand… but think about it, this is how it is done but nearly all programmers in other languages that aren’t as visually dependent as Flash.
The Ball View

The GameView Class handles drawing the animation for the user to see. In here we merely cycle through the objects in the BallGame Class and update a Sprite’s graphics with this new stuff. By doing this we can quickly change out the visual glyph of the Ball with out having to change the class. Notice that when you click on the stage in the application above, the colour of the ball changes. Nothing occurs to the animation itself, only that the view has it’s ballColour property altered.

For a more complex scenario I could change out from drawing a circle on the graphics and instead draw a Bitmap, like say a JPEG I have stored on the server. Go and check out the beta version of my Tetris/Breakout Remix Game. In this I describe the entire game completely abstracted from the view, I can then quickly swap out the different shapes with PNG files for the visuals. Note that these following files are the actual BitmapData objects used in game:



To Be Continued…

link to source code

Swarm of the elements!!! AGH!

So over at the Actionscript.org forums another question was brought up about a specific effect in this thread. It interested me and I hopped right on making it for the blog here.

The effect is basically a cluster effect where when you click on an object any similar objects cluster around it, and other objects get out of the way. I approached this problem by utilizing a node system. All nodes have sibling nodes that are “similar” to it and should cluster around. With a little math we get this result:

To attack this problem I started with a construct of two basic classes:

The first, Node.as, is very simple. It extends the Sprite class so that it can contain DisplayObjects and Graphics, and have a position. On top of that it contains an array called “_siblings”. This is a list of all other nodes that are considered similar to it. I protected this array so that way you can only add or remove objects of type “Node” to/from it. We don’t want any other kind of object appearing as a sibling or the engine would break! There is also a method for retrieving a clone of the array of all siblings. We don’t want to hand out a direct reference to this array or it would allow other objects to put stuff in the array that are not of type Node. This is one of the downsides to working with untyped arrays in AS3. In the latest version of Actionscript Adobe has added typed arrays, which will allow much more freedom with storing objects in these kinds of lists.

Next we have the Engine, ClusterEvent.as, in which we perform all the actual work to move nodes around. The engine is far more of a complex class then Node.as. So let’s dig into this class to get a look at what it does exactly.

Properties

Note I protect ALL properties of my Classes. This is a good practice for any developer to work on doing. This gives you the coder the freedom to control any and all accessibility to your properties, and seperate the internal variable name from the external property name. Note how I use the underscore for all internal properties, but the getter/setter names for said properties are more descriptive and lack the underscore.

Static constant properties on the other hand I keep public, they can’t be changed anyways because they are constants!

In the engine I store several properties:

  • _stage – a reference to the stage that should be passed in the constructor method. Because the engine isn’t a DisplayObject but needs access to the stage we need this
  • _nodes – an array of all the nodes in the node tree for this engine
  • _activeNode – an internal property that refers to the node being dragged at the moment, if any
  • _siblingPositions – a Dictionary of points that describe where all the siblings of the activeNode should be with respect to the activeNode

The first few methods in my Class are just getter and setter methods to access any protected variables I would like to be made public. Note that some of these properties perform extra tasks in setting the related protected value. For instance if I change the reference to the stage to something new I should remove all event listeners from the old stage reference first. Or when I hand out a copy of the node tree, I don’t want to give direct access to it, but instead a clone of the node tree.

I follow this up with two methods to start and stop the engine.

The Algorithm

The algorithm is fairly basic, but is made up of several methods to facilitate all the things that occur. First their are the event Listeners. At the end of the Class I have 4 methods for adding and removing events. There is a MOUSE_DOWN event set to each node in the node tree, and two events added to the stage: ENTER_FRAME for updating and lerping positions, and MOUSE_UP to stop dragging any active nodes.

There is also a small group of repetetive functions I abstracted from the main algorithm just to clean the code up. This includes: generating the Dictionary of points around the activeNode for the sibling cluster; lerping the position of a node to a specific point; and filtering the node tree of any siblings and returning a cloned array.

Finally there is the Algorithm for the effect. This is made of three parts:

  • grabNewNode – this adds a reference to the recently clicked active node, and generates a cluster of points around itself for all sibings.
  • dropCurrentNode – this removes any reference to an active node when the mouse is released. It also clears the dictionary of points.
  • updateNodePositions – Here we update the positions of all nodes in the node tree with respect to the activeNode

When updating the positions we do 3 basic steps:

  • Update the activeNode – find the mouse position and lerp the currently active node toward it
  • Update sibling nodes – grab a copy of the array of siblings for the currently active node, compar it to the dictionary, and update their positions
  • Update non-sibling nodes – filter the node tree of all siblings and then update their positions if and only if they are to close to the active node.

And that is it! In the package I’ve included 2 more classes though. The Main.as file contains an instance of all the nodes and the engine, and the BoxBug.as Class extends the Node.as Class so as to add some visual information to the Nodes.

link to ElementCluster source code