Archive for the ‘Code’ Category

25
Feb 10

Save MovieClip as PNG Example

A couple of guys on Twitter asked me if I would write-up how I generate PNG files from MovieClips in my SWF, at run-time. So I put this example together and am sharing it here.

We use this technique in our virtual world WebbliWorld to save a PNG version of the users avatars after they have customised them. But there are all kinds of other reasons you may need this. My example includes two methods: Saving the PNG locally using the local file system, and Saving the PNG to a web server using AMFPHP.

This technique requires Flash Player 10 and the Adobe AS3 Core Lib.

Here's a very simple example (included in the zip download below):

Essentially it all boils down to this:

1) When you are ready to save your image, create a Bitmap version of your MovieClip.

Actionscript:
  1. private function getMovieClipAsBitmap():Bitmap
  2. {
  3. var bounds:Rectangle = theMovieClip.getBounds(theMovieClip);
  4.  
  5. //    The * 2 is because we're scaling the clip up by a factor of two, to result in a larger PNG
  6. //    If you don't need this, remove it and comment out the m.scale call below
  7. var theBitmap:Bitmap = new Bitmap(new BitmapData(bounds.width * 2, bounds.height * 2, true, 0x0));
  8.  
  9. var m:Matrix = new Matrix(1, 0, 0, 1, -bounds.x, -bounds.y);
  10.  
  11. //    Simply scale the matrix to make a bigger PNG. Here we are doubling it. Comment this out if you don't need it.
  12. m.scale(2, 2);
  13.  
  14. //    Need to crop the PNG to a given size? Pass it a Rectangle as the 5th parameter to draw()
  15. //var r:Rectangle = new Rectangle(0, 0, 50, 40);
  16.  
  17. theBitmap.bitmapData.draw(theMovieClip, m, null, null, null, true);
  18.  
  19. return theBitmap;
  20. }

2) Convert this Bitmap to a ByteArray.

Actionscript:
  1. private function getMovieClipAsByteArrayPNG():ByteArray
  2. {
  3. var data:Bitmap = getMovieClipAsBitmap();
  4.  
  5. var ba:ByteArray = PNGEncoder.encode(data.bitmapData);
  6.  
  7. return ba;
  8. }

3) Send this ByteArray to either the local filesystem, or AMFPHP.

Actionscript:
  1. //    Uses FileReference to save the PNG locally to the hard drive (see "saveToServer" for an alternative)
  2. private function saveLocalPNG(event:MouseEvent):void
  3. {
  4. var ba:ByteArray = getMovieClipAsByteArrayPNG();
  5.  
  6. file.save(ba, "BirdyNamNam.png");
  7. }

Complete source code is included in the zip file including an AMFPHP PHP script for saving on a web server.

Hope someone finds this useful.

Download the Soure Code zip.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

23
Feb 10

Blockparty 2010 Invtro and the Opensource demo engine evoTinyEngine

Blockparty is an annual demo party held in the US, and 2010's is about to hit in a few months time. As with all good demo parties there is usually an invitation demo to announce it, and to whet the appetite somewhat. This year EvoFlash created this little beauty, and of course it's AS3 to the core:

I've not been to a demo party since 1999, but boy does this make me wish I could be there. Nice one guys, nice one.

There are some lovely effects as you'd expect. Evoflash have been at this for years now, and obviously have a highly streamlined demo pipeline going on. With impressive pre and post render effects; gorgeous blooms, radial blurs, reflections and shadowing. And what's more - they have released it as open source, free for demo coding plebs like me to use!

Called evoTinyEngine it's a small framework that offers you three core elements: Assets, the main Engine and Modifiers. The Modifiers can be stacked up on-top of each other. The Engine handles the construction and destruction of all the Modifiers for you, and there are some really nice things ready to use. Everything is based on 16th note beats, which allows for tight syncing with the audio in your demo.

I haven't dug through the code much yet but I'd be willing to bet there are some insane routines in there, that would be well worth studying for game development as well as demos.

(Now let's see if this blog post kicks off a 20+ comment flame war about "is it really a demo?" yadda yadda ... ;)

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

06
Jan 10

Access LiveDocs locally with Doc v3.0.1

Although the code-insight features of FlashDevelop help a lot, you can't beat a good AS3 reference - and I use Adobe LiveDocs almost exclusively for this. Although I have a Firefox search plugin that gives me quick access to it, I have still always wanted a decent local copy that offered the same benefits my browser does, but faster.

Thanks to the magic of Twitter (cheers @kode80) today I found such a beast in the shape of an AIR app called Doc?

Doc? allows you to view, search and bookmark all your favourite ASDocs. But the biggest feature for me is that on-line docs can be downloaded and stored locally too. This means that the docs for things like Away3D, Flint, Papervision, Adobe CoreLib, TweenMax or anything else that has ASDoc documentation can be added to your local books collection.

Adding a remote ASDoc

Adding new books couldn't be more simple. Just start-up Doc?, click the settings icon in the top-right and select ""Add Remote ASDoc". You'll be asked for some details. Here they are for the Stardust Particles system:

Note: when adding URLs be sure to specify a directory, and don't have the index.html on the end.

Doc? will then download and index the files, storing them locally.

Be advised that on large sets of documentation this can take a while. Indexing the AS3 Language Reference took nearly 10 minutes, and that's on an Intel Quad Core Q9950 @ 2.83GHz with 8GB RAM. Doc? stores the indexes in a local SQLite database.

Once downloaded and indexed the docs are available from the Books menu, ready for easy and fast local searching!

Here you can see I searched for "Radius" specifically in the Stardust book, and am viewing the CollisionRadius page. You can search across all books, highlight results in the text, include title and/or content in the search and even bookmark sections you know you return to often.

The tree view display has icons depending on the style of result - the green "C" circle icon means it's a Class, but it also shows packages, methods, constants, interface and others.

AS3 Language Reference

One of the first things I recommend you do is download the ActionScript3 Language Reference zip from the Adobe web site (5.8MB). Unzip it somewhere and use the "Add Local Book" Settings option to add it. It will still need to be indexed (and this takes a long time), but it's better to grab the zip as it can often have more up to date docs vs. those installed with CS4.

I'm quite sure that this app will save me a lot of time vs. digging through browser bookmarks.

Visit the Doc? web site

All I'd like to see now is this built into FlashDevelop, so F1 searched within Doc? :)

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

16
Dec 09

FlodEx 1.01 – SidMon, Future Composer and BP SoundMod supported

Christian has been busy! FlodPro was already the best Amiga module replay library available for AS3. But not content with that he went and added support for 3 new chip-tune formats: SidMon, Future Composer and BP SoundMod.

As a special Christmas present for those who visit this blog I whipped up this little demo, showcasing 6 tunes, 2 of each newly supported format.

Hit the jump to see the demo in action :)

(more...)

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

01
Oct 09

DarkCubes released – Retro 16-bit demoscene gameyness

Away3D is an awesome 3D library for Flash. Flod is an awesome library for replaying tracker music in Flash. Throw those two things together with my inner-geek upbringing of the 80s and you get DarkCubes. I grew up drip-fed on ST/Amiga demo effects, and this random little 3D game is what I banged out during a couple of lunch breaks and some hours last night.

DarkCubes Credits

I actually wrote DarkCubes back in 2000 on the PC/Windows using DarkBASIC (hence the title of the game). So I had the code and figured it would make a good first experiment for Away3D. A bit of messing around, a bit of swearing, and lots of fiddling later and this tiny puzzler was born.

The logo is from the original PC game and was made by Yann 'Kohai' Parmentier. The music is by Adam Sikorski (DSX of TRSI), 505 of Checkpoint and Toodeloo of the Dead Hackers Society. The rest by yours truly.

Lots of keys do stuff in-game, so have a fiddle! (1-5 changes the music for example, D turns on Debug info, 7-9 change texture, etc. Read the scroller for the full list).

I make no apologies for this beating shitty spec  Netbooks / PCs over the head with a giant CPU grinding axe. Deal with it. It's hardly the end of the world.

DarkCubes In-game

Click here to play (sorry no pre-loader, but it's only 1MB in size)

Enjoy ;)

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

17
Sep 09

Flickr Water Painting Demo

Flickr Water Painting I had an idea for a game where you had to restore colour to the world, by speeding around in a boat and dropping colour bombs onto the greyscale picture below. I thought it'd be fun if the images were pulled in from Flickr dynamically, creating a constant ever-changing sea of levels.

A few hours and a prototype later, and I realise it's not actually going to work after all. There's just no easy way to control what comes back from Flickr - you can't search for images which just have "Big" sizes available, and you can't easily exclude black and white images, which totally ruin the painting part of the game! There are also commercial issues with the Flickr API Keys needed to search and request images. So in the end what was a nice idea in theory, turned out to be a bit crappy in reality.

However I was left a random but pretty prototype. I've removed the boat/gameplay element, so it's just the water painting demo hooked into Flickr.

Lots of pictures come back with "Image not available", so just search again. If it seems to hang for a while after clicking Search, then just search again! Paint with the left mouse button. Sometimes it works right away, and sometimes only on the third or so attempt.

[kml_flashembed publishmethod="dynamic" fversion="10.0.0" movie="http://sandbox.photonstorm.com/painterFlickr.swf" width="640" height="480" targetclass="flashmovie"]

One of my artist friends commented that this made him look at the use of colour in a whole different light. He said that as you start filling the image in, the colours that come through are often totally different to what you'd expect - and when the colour is presented in low volumes it can often look very wrong. As if your brain has substituted the colours for you, and when they don't match it gets confused.

I think there's something quite calming / feng shui about it all personally.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

15
Sep 09

Creating MovieClips dynamically at run-time using the Linkage Class

linkageI found myself needing to create a MovieClip dynamically at run-time. But all I had was a string representation of its Class, as set in the Linkage properties for the Symbol. In my situation the string had been stored in an xml file. Now you could use a standard switch/case block to do this, checking the string and creating a new MovieClip as required. But in this case there were hundreds of possible things it could have been, and it seemed a very "hacky" way to do it.

So how do you go about creating an actual display object from just the Linkage Class value? Thankfully it's pretty easy, and this new bit of code now sits happily in my "everyday functions" collection!

Edit: Updated to be a little more robust, and removed an un-needed cast:

Actionscript:
  1. public function createMovieClipFromLinkageValue(linkageValue:String):MovieClip
  2. {
  3.     try
  4.     {
  5.         var libraryReference:Class = getDefinitionByName(linkageValue) as Class;
  6.     }
  7.     catch (error:ReferenceError)
  8.     {
  9.         trace(error);
  10.     }
  11.  
  12.     if (libraryReference)
  13.     {
  14.         return new libraryReference();
  15.     }
  16.  
  17.     return new MovieClip;
  18. }
  19.  
  20. var newClip:MovieClip = createMovieClipFromLinkageValue("playerFishMC");

Make sure you have imported flash.utils.getDefinitionByName.

Simply pass this function the Linkage value as entered in the IDE, and it'll spit a MovieClip back at you (providing it was a MovieClip in the first place). I'm sure you can see how to extend it to return a Sprite instead, should you require that.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

23
Apr 09

SourceBinder – pure AS3 awesomeness!

SourceBinder

Quite out of the blue I received an invite to the SourceBinder project tonight. I honestly couldn't even remember what it was, but after a couple of minutes playing I was hooked!

If you are experienced with node based creation tools, like FilterForge for example, then you'll have a good idea what this is about. Basically it's an FP10 visual creation tool - you can create your own nodes (or use many of the public ones up there) and chain them together to create stunning visual effects. Loads of libraries are built in already like JigFlashLib, Tweener, Flint and PV3d, so nodes can be created using these.

SourceBinder Example

Nodes can perform tasks such as colour changing, mouse input, sound handling, PV3D creation and loads more. They are simple AS3 classes (which you can edit live online). You chain them together using a neat drag and drop interface, the final "display renderer" node being responsible for the output.

It's just great - I urge you to try it!

http://sourcebinder.org

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

07
Apr 09

Particle Worm Explosion

I was messing around tonight with the explosion code I wrote for Infinite Ammo, with a squiggly "worm like" behaviour and created the following weirdness. Click anywhere to set off an explosion. Click as much as you like to create total mayhem!

[kml_flashembed fversion="9.0.0" movie="/swfs/eskaflow.swf" targetclass="flashmovie" publishmethod="static" width="600" height="400"]Get Adobe Flash player

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

11
Mar 09

Infinite Ammo 4k Source Code Released

Infinite Ammo 4k

Well everyone else seems to be blogging about the release of their 4k games, so I'm doing so too :) I managed to get mine finished and submitted on-time. I don't expect it to win a thing (results are in 3 days time), but I had great fun participating all the same.

I have created a games page entry for it, and in a slightly unusual move for me I have released the full source code for the game too. You can get it from it's games page. What you learn from it I have no idea. At the very least there's a pretty explosion / particle system, and a massively optimised and compressed Tween engine! Or you could just skim down through the code, shaking your head thinking "and he ENJOYED coding this?!" :)

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

28
Feb 09

How do you extract a Sprite back out of a ByteArray?

I should probably post this into some AS forums (and will do so later), but I had to get this out there quickly and it's bugging the hell out of me:

In short, how do you extract a Sprite from a ByteArray? (or any kind of display object for that matter).

I can write the object just fine, and read it back into a variable, but I'll be blown if I can then convert that back into what it was originally.

Here are my attempts so far:

Actionscript:
  1. var test:Sprite = new Sprite();
  2. test.graphics.beginFill(0xff0000);
  3. test.graphics.drawRect(0,0,64,64);
  4. test.graphics.endFill();
  5.  
  6. //addChild(test); // to test, works fine
  7.  
  8. var b:ByteArray = new ByteArray();
  9.  
  10. trace(b.length);    //    0 bytes
  11.  
  12. b.writeObject(test);
  13.  
  14. trace(b.length);    //    754 bytes, so our Sprite is definitely in there
  15.  
  16. //    Reset the pointer
  17. b.position = 0;
  18.  
  19. trace(b.position);    //    0 as I'd expect
  20.  
  21. var newTest:Sprite;
  22. //newTest = b.readObject() as Sprite;    //    Ends up being null
  23. //newTest = Sprite(b.readObject());    // Type Coercion failed error
  24. //trace(newTest);
  25. //addChild(newTest);    //    and kaboom, constant "Parameter child must be non-null." errors :(
  26.  
  27. var take2:Object = b.readObject();
  28. trace(take2);    // ok take2 contains an object, but how can I get the Sprite out of it?
  29.  
  30. trace(b.position);    //    754, so it has definitely read it all

Ummm someone, please help? :)

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

26
Feb 09

(Spoiler!) Play test my 4kb Game Competition entry

My 4kb Game Competition entry is very nearly finished. I'm in the final "tweaking" stages, trying to get the last few small bugs out, and iron the gameplay a little so it's less "random" and even more progressive.

The game is a twitch shooter based (loosley!) on Geometry Wars and requires some pretty mad flying skillz to last more than 30 seconds. The idea is literally to see what kind of score you can get. Here's a screenie:

Infinite Ammo

There are 10 different baddies, "boss waves", bullet power-ups and particle explosion effects galore! (I went a bit over the top in all honesty). I'd love to have added sound, but I'm pushed to the limit of my 4096 bytes shackles already.

I know the game isn't quite as "playable" as it should be, and I'll work on that in the final few days left before I need to submit to the contest. I also know I don't have a chance of winning (having seen some of the other entries lined-up!), but it was bloody great fun to code anyway.

And so as a sneak peak to you here's the latest beta to play. Comments welcome (but please do bear in mind this whole game had to fit into 4096 bytes, so don't go requesting anything insane ok?!)

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon