21 August 2012
To make the most of this tutorial, you need experience with ActionScript programming in Adobe Flash Builder or a similar integrated development envirionment (IDE). You also need previous experience developing Stage3D-based applications using Away3D. A good introduction to Stage3D and Away3D is Richard Olsson’s article Creating 3D games and apps with Away3D and Stage3D – Part 1: Setting up a 3D project in 30 minutes. Previous experience using Autodesk 3ds Max is also required.
Intermediate
Away3D 4 is the latest version of the popular open source 3D engine for Adobe Flash Player and Adobe AIR. Based on the new Stage3D API available with Flash Player 11 and AIR 3, the new engine can be used for highly detailed 3D games, entertainment, simulation, and much more. The open source nature of the engine means you get full access to the source code, so you can even modify it should the need arise.
This tutorial shows how to take a biped-animated model from Autodesk 3ds Max and turn it into an interactive SWF file that can be played in Adobe Flash Player. You can see it running below. Click the man in the window to control the man using the arrow keys, the E key, Shift, and the Space bar.
To complete this tutorial, make sure you have 3ds Max installed and working on your computer. Then download the latest official version of Away3D 4 from the Downloads section on Away3D.com or download the most current version via GitHub. You will also need a tool for creating your SWF file such as Adobe Flash Builder.
The AWD format was created by the Away3D team because existing 3D file formats were not suited for the web. The goal was to create an extensible, compact format that enabled the export of 3D data with or without all assets embedded (such as textures, animation, and more). Support for any number of models is provided, so even complete scenes can be exported. The format is free, defined in an open specification, and has an open-source SDK for C++ and Python to aid in encoding AWD files and to encourage others to adopt the format in their software as well.
The AWD team intends to build AWD exporters for the most popular 3D packages such as Blender, Maya, and 3ds Max. The 3ds Max plugin for 3ds Max 2012 is available now. At the time this tutorial was written, the plugins for Maya and Blender are only available as source code, but will be available in compiled versions soon.
To install the 3ds Max plugin, download the version for your system (32-bit or 64-bit) and follow the instructions in the AWD in 3ds Max wiki. Once you have copied the files to the correct folder, restart 3ds Max and you will see the AWD option when you select Export from the main menu (see Figure 1).

The model and code for this tutorial was created by French designer Thillet Laurent. It started as a custom model that was rigged in Character Studio and animated with Biped. The samples files for this tutorial contain the 3ds Max file, textures, Biped .bip files, a src folder containing the ActionScript code, and a file named sequence.txt that I'll discuss later.
Follow these steps to get started:

The skeleton will be exported in the AWD file, but you can control the visibility using ActionScript when playing the animation. An option to only include layers set as "renderable" is on the current wish list, and that will eliminate this step in the future.

While working with your own files for AWD export, keep in mind that AWD currently supports geometry and meshes (including instancing), scene graphs with containers and parenting, basic color and texture materials, skeletons, and skeletal animation. Any other elements, such as procedural textures and other Max specific features, will be ignored.
Once you have finished your model, you need to indicate which parts of the animation you want to export.
Breathe 0 60 Walk 70 130 Run 140 157
This file is only used when exporting from Max, as the exporter embeds this data into the AWD file. You can change the sequence around. The first one mentioned will be played back by the AWD preview application that is included with the exporter plugin.
After it exports the file, the exporter will, by default, create and open a Flash preview file. If you just want to view the file on your computer ensure Export For Local Preview is selected. If you want to export the file for others to view online, select Export For Deployment. If you choose the latter, you will not see anything when opening the exported file locally. This is expected behavior and part of the Flash Player security sandbox model.

Note: The plugin will export the whole scene. Exporting only selections is currently not supported.

Don't worry if the Skeleton shows in the exported file (see Figure5). When you use it in your project, it's up to you to make it visible.
Note: If the exported file just shows a blank window and nothing loads, recheck your sequences.txt file. Ensure the file is inside the folder you are exporting to, that the filename is correct, and that the names in the file match the names you used in the Motion Mixer.
This tutorial does not cover the basic setup of an Away3D 4 scene. See the Tutorials section on Away3d.com for tutorials on the basics of cameras, lights, materials, and adding objects to your scene. In this tutorial, I'll be concentrating on the steps that make it possible to load the exported AWD file and then access and control the animations within.
For this part of the tutorial, you'll use Adobe Flash Builder, but you can use other IDEs as well. You can find a detailed description on how to use Away3D with Adobe Flash Professional, Adobe Flash Builder, and the free open source tool FlashDevelop in my article on the topic in Flash Magazine. You may also be interested in Using ActionScript projects in Flex or Flash, which explains how to use ActionScript projects in these same tools.
To start using the model, follow these steps:


Your Package Explorer should now show all the files and folders required for the project, including MaxAWDWorkflow.as (see Figure 8).

If you can't see anything in the exported file or you get an Error #2044 message, you may need to add modify your HTML template. This process is explained in the next section. If you see the red sphere, skip ahead to the section Running the example file.
Unfortunately, you can't just export your file when working with Stage3D. The most common problem is that you get a dialog box that says "Error #2044: Unhandled ErrorEvent:. text=Error #3702: Context3D not available." Context3D is one of the core classes for Stage3D in the Flash Player. Using Stage3D requires that you set the wmode parameter in your HTML embed code.
To do this in Flash Builder, follow these steps:
params properties and add the following line (see Figure 9):params.wmode="direct";

<renderMode>direct</renderMode>
-swf-version=13
This command will force compilation for Flash Player 11.x.
Once you know your setup works, you are ready to test the exported AWD file. To do this, you must set the AWDViewerLoth.as file to be the default file to run.
Keep AWDViewerLoth.as open for the rest of this tutorial as you will be referencing bits of it later.
-use-network=false to your setup. See the Stack Overflow entry on Security Sandbox for more details.To understand what makes this model work, I encourage you to explore the code.
Looking at the AWDViewerLoth class in the sample files, you will see the constructor calls the methods initEngine() , initText() and initLights() . These methods set up the scene, the view, and the camera—all the basics that you need to view your 3D content. The last method called in the constructor is initLoading(), which loads your assets using the AssetLibrary class.
AssetLibrary is a new class in Away3D 4 that simplifies working with loaded assets. Assets are any item that can be used in the engine: a Mesh, a Geometry, a BitmapTexture, and so on. You tell AssetLibrary to load what you need (models, textures, animations) and then request the results when loaded.
To use it, you must first enable the file format parsers that you want to use in your project. Away3D4 can import files in OBJ, AC3D, DAE, 3DS, MD2, and MD5 formats as well as the native AWD1 and AWD2 formats. You can add all these parsers at once by calling the Parsers.enableAllBundled() method. However, the more parsers you enable, the larger your SWF file. In this project, you can save 82Kb by enabling the AWD2 parser only:
AssetLibrary.enableParser( AWD2Parser );
AssetLibrary will keep you updated on the loading progress using the event system built into Flash Player. The three important events you should listen for are AssetEvent.ASSET_COMPLETE , LoaderEvent.LOAD_ERROR , and LoaderEvent.RESOURCE_COMPLETE .
A 3D model may require more than just the mesh. For this example, the model contains animations that are controlled by a skeleton. The skeleton has different poses and it may also embed materials (basic color materials and textures are supported). The model itself is built from many different submeshes and these contain geometry. Using the onAssetComplete() method, which is the handler for the AssetEvent.ASSET_COMPLETE event, you can inspect each of these as they load and apply actions to them.
In this tutorial, this event is only used for debugging as the loading itself is handled by AssetLibrary. Using a trace command, you can see the name and type of each asset as it is loaded.
AssetLibrary.addEventListener(AssetEvent.ASSET_COMPLETE, onAssetComplete);
private function onAssetComplete(event:AssetEvent):void {
trace("Loaded " + event.asset.name + " Name: " + event.asset.name);
}
If you run this application in debug mode and look at the trace output, you'll see that the loaded assets all have the same names as used when authoring in 3ds Max and the animations map to the names you added to the sequences.txt file. Take care when naming your models to avoid problems caused by naming conflicts. If there is a naming conflict, AssetLibrary has ways of handling some. Those methods are beyond the scope of this article.
You can also listen for even more detailed events that tell when each of these assets has been loaded. You can learn which events exist by looking at the top of the away3d.library.AssetLibraryBundle class included in the Away3D source.
This event occurs when an asset does not load as it should. Make sure you handle this event by adding an event listener to your loader and at a minimum, displaying an error message the user can see. If you do not handle this event or display and error message for the user to see, your project will not display anything and the user will see a blank screen when such an error occurs.
In the sample code for this tutorial the onLoadError() method simply traces the error out to the console. When running your project in debug mode, you should see "Error #2032: Stream Error" in your IDE when this error occurs.
AssetLibrary.addEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
protected function onLoadError(event:LoaderEvent):void{
showError("Error loading: " + event.url);
}
This event will fire for every element you ask AssetLibrary to load. In this case, the texture is separate from the AWD model so you have two load calls:
AssetLibrary.load(new URLRequest(TEXTURE_URL));
AssetLibrary.load(new URLRequest(MESH_URL));
Note: AWD2 may also embed the textures into the model. This simplifies asset management at the price of larger files.
On the web, there is no guarantee that assets will complete loading in the same order as you request them. To manage this, the onResourceComplete() method maintains a counter to check that you have loaded all the resources you need before moving on.
AssetLibrary.addEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
private function onResourceComplete(ev:LoaderEvent):void {
assetsThatAreloaded++;
// check to see if we have all we need
if (assetsThatAreloaded == assetsToLoad) {
setupScene();
}
}
Once both the model and the texture have loaded, it is safe to display your 3D model. This is done in the setupScene() method.
Any material that is to be rendered in Away3D must be added to the scene. In the setupScene() method you prepare the material for your "hero" and then apply it to the model. Since most 3D programs work in arbitrary units, scaling your model will often be required. After the material is prepared and applied to the model, the model is scaled with the following code:
hero.scale( 8 );
You can avoid scaling the model if you know how the camera setup will work. Rather than scaling the model, you can tweak the camera setup to compensate for model size. It's all relative, so you decide. For larger 3D projects it is important to avoid any such issues by agreeing on a world scale and then making sure all models follow that.
When the model is set up as you want it, you add it to your scene:
scene.addChild( hero );
This makes the model renderable and thus visible. It will be standing in the default pose, so next you'll set up the animation set. This acts as a container for animation data and uses the values traced in the ASSET_COMPLETE handler earlier:
animationSet = new SkeletonAnimationSet(3);
animationSet.addState(breatheState.name, breatheState);
animationSet.addState(walkState.name, walkState);
animationSet.addState(runState.name, runState);
Now that you have your animation set, you can set up your animator. It will connect the animation data to the model and provide a control mechanism. You do this with an animator object that ties together the skeleton information you retrieved from ASSET_COMPLETE with the newly created animation set, and applies it to your hero model. To stop the character from walking away from the camera, you can disable the position update that usually applies to bones animation when any motion is expected:
animator = new SkeletonAnimator(animationSet, skeleton);
animator.updateRootPosition = false;
hero.animator = animator;
Finally, you define a state transition for your animation states. This is used when transitioning active states in the animator, and can be custom created for whatever behavior is required. For now, you can use the default crossfade transition object:
crossfadeTransition = new CrossfadeStateTransition(XFade_TIME);
The XFADE_TIME constant (defined at the top of the ActionScript file) tells how many seconds Away3D should blend between the current and the new animation state. Setting this to zero would cause the change to happen instantly. This looks bad, so you usually want to blend the vertex positions as shown here.
To be sure that all the animations were successfully loaded and created, you invoke the animationSet.hasState() method for each animation that should exist. This isn't required, but it's a good idea to do this to avoid strange errors. If all is good, you point the camera at your hero and start rendering and listening for user input.
if (animationSet.hasState("Breathe") && animationSet.hasState("Walk") && animationSet.hasState("Run")) {
hoverController.lookAtObject = hero; // point the camera at the hero
goToPauseState(); // starts the "breathe" animation
initListeners(); // get ready for user input
} else {
showError("Animation error");
}
Depending on which key the user presses, the movement of the character is performed in the updateMovement() method. If the user is not pressing any key, the goToPauseState() method is executed. In both of these methods, you set the name of the animation state and then activate it using:
animator.play(currentAnim, crossfadeTransition);
Thanks to the AWD format and the AWD plugins, it is easy to import animated and textured models straight from Autodesk 3ds Max into Away3D. The new AssetLibrary class in Away3D 4 simplifies the loading procedure for basic scenes like this as well as for large and complex games. The ActionScript language makes it easy to build large scale interactive applications for the web and mobile, and the compactness of the AWD files improves the end user experience by ensuring less loading time.
Check out the Tutorials section on Away3D.com to learn more about using Away3D. You can also find more Away3D 4 tutorials at Flashmagazine.com and GotoAndLearn.

This work is licensed under a Creative Commons Attribution-Noncommercial 3.0 Unported License.