Archive for the ‘CODE’ Category

Friday, January 11th, 2008
Interesting library for html to flash front end. Basically this runs off the HTML in your page to draw the same in Flash. I am sure there are great pitfalls in this but when controlled this could be very key in a flash add-on to CMS or CMS content. Might be useful for many things.

Wrapper is a cross-browser compliant HTML/CSS rendering engine written in ActionScript that sits on top of your standards compliant HTML page. Wrapper eliminates cross-browser issues and makes integrating ActionScript and HTML/CSS projects possible without needing to compile.

Wrappers strives to answer the most common problems web designers face without forcing them to learn too many new things. Most web sites can be created in HTML or CSS, then when you need to extend Wrapper’s capabilities you can either use JSON to call functions within ActionScript or you can load compiled plug-ins. Wrapper also has built in methods within CSS to load custom fonts, display elements as any shape, and fill them with linear or radial gradient background colors. ActionScript’s event model is also implemented within Wrapper’s HTML. Wrapper’s best features are the ones that you get for free because of how it is set up. It’s like getting all the great features of the Flash Player without needing to deal with compiling and being able to create your content the same way any HTML page would be created. Wrapper is fully accessible to the search engines and integrates well with any back-end technology.

Wrapper is currently released as a fully functional open source beta for Flash Player 9. Wrapper is set up as a pre-compiled plug-in but can easily be integrated into any Flex or AIR applications or even as an ActionScript framework for creation of compiled projects.

Documentation can be found in the wiki and news about this project can be found at http://motionandcolor.com

Examples can be found in the downloads http://code.google.com/p/htmlwrapper/downloads/list

Source is for everything is in svn http://code.google.com/p/htmlwrapper/source

I checked it out and it looks pretty well done, most of the time HTML to Flash or vice versa has to be a semi-controlled environment in terms of the markup. This and FlashML which is only AS2 I am using a partially converted to AS3 are part of my rotation for HTML<–>Flash content challenges for research right now. Usually most CMS in Flash has content loaded into the flash and then an alternate (sometimes similar) representation, here this is trying to merge the two which has it’s challenges.

Try out a demo (view source)

EDIT: Title dyslexia


Thursday, January 10th, 2008

Using SharedObjects in Flash is very simple. Flash has SharedObjects that have been in the player since Flash6 when the introduction of Flash Communication Server which is now Flash Media Server which is releasing version 3 soon (also remote SharedObjects in Red5 is an open source RTMP media server that is based on Flash Media Server). So we can thank this release for SharedObjects, Camera objects, Audio, lots of the NetConnections, protocol enhancements and many other things. However to keep the tips simple we will just touch on the local usage and post a series of posts on these objects.

SharedObjects locally and remote have changed the way offline is thought about and are the backbone of many offline systems and prototypes. They have been influential in moving storage locally to remote in a lightweight AMF0 or AMF3 format.

SharedObject is in the flash.net namespace in AS3.

Here we show how to use the local version of a SharedObject to store data in the most simple form.

import flash.net.SharedObject;
var so:SharedObject = SharedObject.getLocal("userData");
so.data.username= "user1377";
so.data.pwdhash= "[hash] or pwd";
so.flush(); // writes changes to disk

You can see this is extremely simple to store data.Here we show how to use the local version of a SharedObject to retrieve data in the most simple form.

import flash.net.SharedObject;
var so:SharedObject = SharedObject.getLocal("userData");
var username:String = so.data.username;
var pwdhash:String = so.data.pwdhash;

That is it! In the most basic form SharedObjects are more simple than cookies and also are quite nice living outside the bounds of the cookies folder. If a user deletes all cookies it will not delete the SharedObjects. To delete SharedObjects you need to roght click on the Flash player, go to Settings and delete the objects there.You can store any type of data Flash supports from objects to numbers to strings in the SharedObject data.

import flash.net.SharedObject;
var so:SharedObject = SharedObject.getLocal("userData");
so.data.username= "user1377";
so.data.uid= new Number(1337);
var obj:Object = new Object();
obj.prop = "value";
so.data.userobj= obj;
so.flush(); // writes changes to disk

For large applications SharedObjects local are great because users can have their SharedObject space set to a high amount of space or unlmited for large offline type apps or more complex apps stored in a state object. It gets interesting when you pass this to the server in AMF or extremely compact AMF3 format to a remote stored object, via remoting, Shared Object events or any way you want to.We will be posting more on remote shared objects and some of the other tools such as Camera and Streams for AS3 over the coming weeks and deeper into the Sync Events for remote and local SOs.Sephiroth has a great Python tool to peer into the SOs on disk.

The first version of SharedObject Reader was written in python 2.2.
This new version is written in C# (C Sharp) as it’s now part of FlashDevelop editor.

Red5 also does this as well as many AMF kits.

Sync Events for SharedObject (as they change they launch a sync event)

Event object type: flash.events.SyncEvent
SyncEvent.type property = flash.events.SyncEvent.SYNC

Read more at adobe docs:

flash.net.SharedObject

Sample from AS3 docs showing usage

package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.events.NetStatusEvent;
    import flash.net.SharedObject;
    import flash.net.SharedObjectFlushStatus;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFieldType;

    public class SharedObjectExample extends Sprite {

        private var mySo:SharedObject;

        public function SharedObjectExample() {
            buildUI();
            saveBtn.addEventListener(MouseEvent.CLICK, saveValue);
            clearBtn.addEventListener(MouseEvent.CLICK, clearValue);

            mySo = SharedObject.getLocal("application-name");
            output.appendText("SharedObject loaded...\n");
            output.appendText("loaded value: " + mySo.data.savedValue + "\n\n");
        }

         private function saveValue(event:MouseEvent):void {
            output.appendText("saving value...\n");
            mySo.data.savedValue = input.text;

            var flushStatus:String = null;
            try {
                flushStatus = mySo.flush(10000);
            } catch (error:Error) {
                output.appendText("Error...Could not write SharedObject to disk\n");
            }
            if (flushStatus != null) {
                switch (flushStatus) {
                    case SharedObjectFlushStatus.PENDING:
                        output.appendText("Requesting permission to save object...\n");
                        mySo.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
                        break;
                    case SharedObjectFlushStatus.FLUSHED:
                        output.appendText("Value flushed to disk.\n");
                        break;
                }
            }
            output.appendText("\n");
        }

        private function clearValue(event:MouseEvent):void {
            output.appendText("Cleared saved value...Reload SWF and the value should be \"undefined\".\n\n");
            delete mySo.data.savedValue;
        }

        private function onFlushStatus(event:NetStatusEvent):void {
            output.appendText("User closed permission dialog...\n");
            switch (event.info.code) {
                case "SharedObject.Flush.Success":
                    output.appendText("User granted permission -- value saved.\n");
                    break;
                case "SharedObject.Flush.Failed":
                    output.appendText("User denied permission -- value not saved.\n");
                    break;
            }
            output.appendText("\n");

            mySo.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
        }

        // UI elements
        private var inputLbl:TextField;
        private var input:TextField;
        private var output:TextField;
        private var saveBtn:Sprite;
        private var clearBtn:Sprite;

        private function buildUI():void {
            // input label
            inputLbl = new TextField();
            addChild(inputLbl);
            inputLbl.x = 10;
            inputLbl.y = 10;
            inputLbl.text = "Value to save:";

            // input TextField
            input = new TextField();
            addChild(input);
            input.x = 80;
            input.y = 10;
            input.width = 100;
            input.height = 20;
            input.border = true;
            input.background = true;
            input.type = TextFieldType.INPUT;

            // output TextField
            output = new TextField();
            addChild(output);
            output.x = 10;
            output.y = 35;
            output.width = 250;
            output.height = 250;
            output.multiline = true;
            output.wordWrap = true;
            output.border = true;
            output.background = true;

            // Save button
            saveBtn = new Sprite();
            addChild(saveBtn);
            saveBtn.x = 190;
            saveBtn.y = 10;
            saveBtn.useHandCursor = true;
            saveBtn.graphics.lineStyle(1);
            saveBtn.graphics.beginFill(0xcccccc);
            saveBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5);
            var saveLbl:TextField = new TextField();
            saveBtn.addChild(saveLbl);
            saveLbl.text = "Save";
            saveLbl.selectable = false;

            // Clear button
            clearBtn = new Sprite();
            addChild(clearBtn);
            clearBtn.x = 230;
            clearBtn.y = 10;
            clearBtn.useHandCursor = true;
            clearBtn.graphics.lineStyle(1);
            clearBtn.graphics.beginFill(0xcccccc);
            clearBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5);
            var clearLbl:TextField = new TextField();
            clearBtn.addChild(clearLbl);
            clearLbl.text = "Clear";
            clearLbl.selectable = false;
        }
    }
}
Monday, December 31st, 2007

Great news! Polygonal Labs has released the long awaited Motor Physics engine. It is now called Motor2.

UPDATE: Now hosted at Google code

Project hosted at code.google.com/p/motor2
License: New BSD License

After the port of Box2DFlashAS3 appeared the fate of Motor Physics engine was unknown. But with time and just before the stroke of midnight on the final hour of 2007 Michael Baczynski released Motor2 2D physics engine on the world.

This now gives us, count them, FOUR AS3 Physics engines that were released in 2007 in order of release.

Be sure to check the demos of Motor Physics:

To get the source head on over to the blog and in the post it is in the first para.

Currently you can get the source for the preview here.

Polygonal always has such great information and demo write ups the source link gets lost in there. Hopefully this will be at Google code soon or a public SVN. The code looks great and there are optimizations in there but even those are elegant.

With 3 excellent flash as3 3d engines (papervision3d, away3d, sandy), 4 physics engines, lots of great utilities like FZip or ASZip, AlivePDF, Red5, haXe etc etc. 2008 is looking like it will be a great year for performance, optimization and gaming/app platforms on the web like never before seen. I am most looking forward to the coming gaming market for flash, lots of possibilities. With the added competition from Silverlight, much innovation will happen here.

It is great that Motor2, which has a great author and dedicated to performance has joined the physics engine scene, not only that posting on new years eve. Thanks to all that make the flash platform possible of creating excellent new fun and useful tools.

UPDATE: Now hosted at Google code

Project hosted at code.google.com/p/motor2
License: New BSD License

Saturday, December 15th, 2007


haXe, one of the coolest and most versatile languages and platforms of today just released something to add to the already amazing feature set of haXe.  Nicolas Cannasse has posted about releasing haXe Video 1.0. I have been engulfed by Red5 for a few weeks and this could not have come at a better time for fun.

haxeVideo is an opensource video streaming server entirely written in haXe.

Features of haXe Video 1.0:

  • FLV streaming using RTMP protocol
  • Webcam and Microphone recording to FLV file
  • Live streaming for web conferencing
  • light and fast scalable server
  • only 50 KB of server source code : modify whatever you need !

Links

Tuesday, December 4th, 2007

Only a year after release Papervision is getting a major update to 2.0.

Get it while it is hot from the SVN server on google code: http://papervision3d.googlecode.com/svn/trunk/branches/GreatWhite

Papervision3D, launched a year ago, really sparked the AS3 and flash/flex world and inspired every flash guru I know into working on this code. There have been some great tools made and some fwa’s won but it is only the beginning.

I am mostly looking forward to performance enhancements, ascollada integration, culling and Andy Zupko’s 2d bitmap effects on 3d.

New features:

  • Faster!
  • ShadeMaterials
  • Shaders
  • ASCollada (animation support)
  • Frustrum Culling
  • Multiple Viewports (3d editor anyone?)
  • Render to Scene
  • and more!

SVN server and branch:

We do indeed like to ride the racecars!

Tuesday, November 27th, 2007

Found via Zeh, this great bulk loading kit for AS3 from Arthur Debert.

AS3 Loaders are very useful, but when you have large projects there is always a pause and focus on loading scenarios and architecture needed for your loading scenarios, sometimes this can literally eat days and entirely change performance with wrong moves. BulkLoader is a well written kit from Authur Debert that makes loading scenarios or using BulkLoader as a base to your loading situations a great pluggable piece of code that has many excellent features.

Some of the calls like BulkLoader.getLoader(“main-site”).getContent(“bg”), are also very similar to Silverlight’s downloader object that can be queued like this. All in all a kit that is very useful that I have already put to work and will help teams standardize on bulk loading for those killer flash apps.

Creating a BulkLoader instance

// creates a BulkLoader instance with a name of "main-site", that can be used to retrieve items without having a reference to this instance

var loader : BulkLoader = new BulkLoader("main-site");

Add urls to load

// simplest case:
loader.add("logo.png");

// use an "id" so the item can be retrieved later without a reference to the url
loader.add("background.jpg", {id:"bg"});

// since the url by itself can't tell us what the filetype is, use the type property to let BulkLoader know what to do:
loader.add("/some-web-services?size=Large", {type:"image"});

// add an item that should be loaded first (higher priority):
loader.add("/data/config.xml", {priority:20});

// add a max try number (defaults to 3)
loader.add("/unreliable-web-services.xml", {maxTries:6});

// you can also use a URLRequest object , this will load from a POST request

var postRequest : URLRequest = new URLRequest("/save-prefs.php");
postRequest.method = "POST";

var postData : URLVariables = new URLVariables(myPostDataObject );
postRequest.data = postData;
loader.add(postRequest, {"id":"settings"});

// of course, all options can be combined:
loader.add("the-sound-webservices?name=maintrack", {"id":"soundtrack", type:"sound", maxTries:1, priority:100});

Listening for events

// simplest case:
loader.add("logo.png");

// use an "id" so the item can be retrieved later without a reference to the url
loader.add("background.jpg", {id:"bg"});

// since the url by itself can't tell us what the filetype is, use the type property to let BulkLoader know what to do:
loader.add("/some-web-services?size=Large", {type:"image"});

// add an item that should be loaded first (higher priority):
loader.add("/data/config.xml", {priority:20});

// add a max trie number (defaults to 3)
loader.add("/unreliable-web-services.xml", {maxTries:6});

// you can also use a URLRequest object , this will load from a POST request

var postRequest : URLRequest = new URLRequest("/save-prefs.php");
postRequest.method = "POST";

var postData : URLVariables = new URLVariables(myPostDataObject );
postRequest.data = postData;
loader.add(postRequest, {"id":"settings"});

// of course, all options can be combined:
loader.add("the-sound-webservices?name=maintrack", {"id":"soundtrack", type:"sound", maxTries:1, priority:100});

Listening for events:

// attaching events to all items:

// this will fire once all items have been loaded
loader.addEventListener(BulkLoader.COMPLETE, onAllLoaded);

// this will fire on progress for any item

// the event , BulkProgress is a subclass of ProgressEvent (with extra information)
loader.addEventListener(BulkLoader.PROGRESS, onAllProgress);

// this will fire if any item fails to load:

// the event is BulkErrorEvent and holds an array (errors) with all failed LoadingItem instances
loader.addEventListener(BulkLoader.ERROR, onAllError);

// you can also listen to events in individual items               

// this will fire as soon as the item registred with the id of "bg" is done loading (even if there are other items to load)
loader.get("bg").addEventListener(Event.COMPLETE,onBackgroundLoaded)

// this will only trigged if the config.xml loading fails:
loader.get("data/config.xml").addEventListener(BulkLoader.ERROR, onXMLFailed);

Starting the loading operation

BulkLoader will only begin loading once you call the start method:

loader.start();

Retrieving content


var theBgBitmap : Bitmap = loader.getContent("bg") as Bitmap;

// you don't need to keep a reference to the loader intance, you can get it by name:
var theBgBitmap : Bitmap = BulkLoader.getLoader("main-site").getContent("bg") as Bitmap;

// you can also use the conviniece methods to get a typed object:
var theBgBitmap : Bitmap = loader.getBitmap("bg");

// grab a BitmapData directly:
var theBgBitmap : Bitmap = loader.getBitmapData("bg");

Other convenience functions: getXML, getText, getNetStream, getSound, getMovieClip, getNetStreamMetaData.

You can retrieve an item using it’s id, it’s url as a String or as the URLRequest object (if the item was created with an URLRequest).

Arthur also has experience on Tweener so making simplified calls and minimalist code to make a library successful is very clear in the notes/goals on the project and the resulting code:

BulkLoader is a minimal library written in Actionscript 3 (AS3) that aims to make loading and managing complex loading requirements easier and faster. BulkLoader takes a more dynamic, less architecture heavy aproach. Few imports and making heavy use of AS3′s dynamic capabilities, BulkLoader has a one-liner feel that doesn’t get your way.

BulkLoader tries to hide the complexity of loading many data types in AS3, providing a unified interface for loading, accessing and events notification for different types of content.

This library is licensed under an open source MIT license.

Features:

  • Connection pooling.
  • Unified interface for different loading types.
  • Unified progress notification.
  • Events for individual items and as groups.
  • Priority
  • Stop and resuming individually as well as in bulk.
  • Cache managing.
  • Statistics about loading (latency, speed, average speed).
  • Multiple kinds on progress indication: ratio (items loaded / items to load), bytes , and weighted percentage.
  • Multiple number of retries.
  • Configurable logging.

Design goals:

  • Minimal imports.
  • Few method to learn.
  • Dynamic nature: items can be added by specifying a url as a String or a URLRequest .
  • Items can be assigned an identifier key to be used on retrieval.
  • Only one class to learn / use.

BulkLoader tries to gracefully handle progress notification in these use cases:

  • Few connections to open: bytes total can be used instantly.
  • Many connections opened: progress by ratio
  • Many connections opened for data of widely varying sizes: progress by weight.

Check out and download AS3 BulkLoader!

This is quite a contribution to the flash community and is a perfect candidate for the base of your loading assets projects and scenarios. Thanks Arthur!

Thursday, November 22nd, 2007

Andy Zupko is probably doing some of the coolest / useful work in performance and possible effects combining 2D and 3D. Using 2D BitmapData and papervision 3D it turns out you can create a parallel dimension of coolness that cannot fully exist by themselves.

Papervision 2.0 with these effects and if it is as pluggable as it seems is very good for games that lighting is a key component or effects. Imagine a game that can customize weapons with 2d effects in 3d, or rocket boosters, or fireworks or all kinds of inspiring things like changing the mood or environment such as fog, lighting etc… If you start taling about adding physics to all this it just gets too fun. Effects have always been there and around, but making this possible to have a semi-standard way to do this and if it is pluggable, this can lead to many engine advancements.

I think the PV3d team additions of Tim Knip and Andy Zupko have been very good and zupko era in PV3d has begun. Tim Knip is also very active and helping to really organize the ascollada formats and performance stuff like only drawing what is on screen.

Who needs Hydra now? j/k although having this now in papervision leads me to see a very fun 2008 ahead for Flash, it is also, if as pluggable as it seems, a bit like a shaders kit.

All those older great 2d effects merging into 3d from the good old days (some still going very strong) of praystation, yugop, levitated, neave (great 2d tv effects in neave.tv) , flight404 (moved to processing) and many others. And a new era of zupko [pv3d], mr. doob, unitzeroone [pv3d], fabrice [away3d] and many more a new 2d effects in 3d platform is emerging. This kit for papervision3d by zupko and Hydra is making the future glowing full of bright points, and lots of effect explosions.

Let’s hope papervision3d 2.0 it is released soon and it has zupko’s effects code in there.

 

Sunday, November 18th, 2007

Another great new 2D physics engine for AS3 has been released called Box2dFlashAS3 that is based on the excellent kit Box2D for C++. It has been a busy year for physics engines in AS3. FOAM was released this month, APE, the highly anticipated Motor Physics from polygonal labs and plenty more still I am sure.

The Box2dFlashAS3 version has some great demos available on the site that show, use the arrow keys to move to the different demos highlighted here.

  1. bridge
  2. ragdolls
  3. compound shapes
  4. rube goldberg / domino / tank tracks etc
  5. stacked boxes
  6. slider crank / piston
  7. pulleys
  8. gears

Box2DFlashAS3 is an open source port of Erin Catto’s powerful c++ physics library Box2D. Cycle through the demos to see some of the features.

Full source code for the engine and examples can be downloaded from the project’s sourceforge page found Here.

This kit is nice because it mimics Box2D for the crossover and ability of developers to use it in C++ and Flash AS3 moreso than other kits. It looks good and performs well except for a memory or FPS pause I get intermittently.  The demos are already inspiring many uses of the features highlighted for games and effects.

Monday, November 12th, 2007

Sandy 3.0 was released today. To go along with that a RedSandy (Red5 and sandy demo) has also been released. Sandy is the original 3d flash engine that was around before Papervision3D and Away3D and all the others. Sandy3d is an excellent library and it has many features that others do not have well particularly in the easier control of objects and importing all types of files such as ASE, WRL and 3ds in addition to COLLADA which other 3d engines like PV3d and Away3d support although it has been slower in the past 3.0 may change that.

Sandy 3D engine main features are :

  • Flash player 7 to 9 compatibility.

  • Both MTASC and Macromedia compilers compliant for AS2 and Flash CS3 and FlexBuilder for AS3 versions.

  • Several 3D primitives, allowing fast and parameterized object creation without any 3D modelisation knowledge.

  • Advanced and easy object management allowing some fantastic possibilities during your creations (scaling, rotation, translation, tween, etc.)

  • Advanced camera management ( rotation, motion on linear or bezier-curve path, movements, etc.)

  • Complex object loading thanks to the .ASE and .WRL files parser , but also Collada and 3DS files for AS3, (files generated by several 3D object modeling packages such as 3D Studio Max or Blender)

  • Material system to easily change your objects appearance. Several material are available allowing to create transparent faces, bitmap texture and video texture as webcam video stream.

  • Managment of Flash filters bringing some very nice visual effects

Red5 is the best multi-user media server out there right now and it is built with Java.

The cool and probably most interesting part is Sandy combined with Red5 to create multi-user environments in 3d for flash. There have been experiments with this and many attempts at this and is being done but an open source kit that does this is very helpful and these are two great flash toolkits in Sandy and Red5.

Get your game on!

Getting started video with Sandy 3.0 with a wise robot
[youtube=http://www.youtube.com/watch?v=vPz4VwIlrQg]

Sunday, November 11th, 2007

Drew Cummin’s FOAM is a great flash as3 2d physics package that can be integrated quickly and get started with realistic physics in 2d flash apps and games. I have been playing with this since FOAM’s release last week and putting together some tests to show, comparing with APE and really looking forward to polygonal labs Motor Physics to add there.

Three excellent physics engines (FOAM, APE and Motor Physics) for flash in AS3 already. Basically at flash9 player/avm2 market saturation (it is now available to develop on in over 94% of market) is showing the power of the ES4/Javascript2 based Actionscript3 language and how it is inspiring developers to new levels of interest/inspiration. Then again haXe can target them all but I digress.

FOAM was recently released but the author Drew Cummins is showing very good support for the toolkit and released a plethora of goodins to support this great kit, bug fixes, samples, docs and some realistic physics demos as well as in depth walkthrough of creating a force generator and comparison of the Euler and RK4 equations used in that process and their differences (Euler being less correct due to the factors of the platform and intervals and environment, RK4 more correct but more expensive to run)

If you are developing realistic physics in flash games or apps this toolkit is a great source of inspiration.