-->

Having created a scene last time with texture mapped objects, I’d now like to add some interaction so that we can rotate the camera around the scene and make the 3D objects react to mouse events. As you’ll see this is very straightforward with Away3D as each triangle drawn on the screen individually detects mouse events. For an equivalent tutorial in Papervision3D, check out First steps in Papervision3D : Part 5.

Previous articles summary :

For the scene interaction we’ll be looking at two different types of events. Firstly, the standard flash MouseEvent that we’ll use to rotate the camera when the user clicks on the stage and moves the mouse. Secondly we’ll look at the Away3D-specific event: the MouseEvent3D. This event is created for similar mouse actions on 3D objects but more importantly it contains the associated 3D object. To add MouseEvent3D listeners, all Object3D objects have the following functions for different mouse interactions:

  • onMouseDown : called when the mouse button is pressed over the object
  • onMouseUp : called when the mouse button is released over the object
  • onMouseMove : called when the mouse moves over the object
  • onMouseOver : called when the mouse enters the object
  • onMouseOut : called when the mouse leaves the object

Another new feature for this tutorial is to add object animation using an external library: Tweener.

Without having to calculate and specify the change in positions (for example) of objects within the code, a tween does all the hard work for us. A tween works on a particular property of an object and at each frame of an animation modifies this property in a particular manner. You’ll find more information on tweens on the web, for example at wikipedia.

Tweener is an opensource library, compatible with Actionscript2 and Actionscript3 as well as JavaScript and HaXE. To install it in your Eclipse/Flex Builder 3 environment simply create a new Flex Library Project, download the sources from the Tweener homepage and extract them into the src directory. The source should be automatically compiled and you can either link your own ActionScript projects to this project or directly used the compiled library. If you need help on compiling new flex library projects in eclipse then you should find useful information on my post for installing and compiling Away3D in eclipse.

Lets take a look at the code. I’m following directly from the example in the last post but am simply adding the new mouse listeners.

package {   import away3d.cameras.Camera3D;   import away3d.containers.ObjectContainer3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.base.Object3D;   import away3d.core.math.Number3D;   import away3d.core.utils.Cast;   import away3d.events.MouseEvent3D;   import away3d.materials.BitmapMaterial;   import away3d.materials.TransformBitmapMaterial;   import away3d.primitives.Cube;   import away3d.primitives.Cylinder;   import away3d.primitives.Sphere;   import away3d.primitives.Torus;     import caurina.transitions.Tweener;     import flash.display.Bitmap;   import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;   import flash.events.MouseEvent;     [SWF(backgroundColor="#000000")]     public class Example004 extends Sprite {     [Embed(source="/../assets/earth.jpg")] private var EarthImage:Class;     private var earthBitmap:Bitmap = new EarthImage();     [Embed(source="/../assets/away3D.png")] private var Away3DImage:Class;     private var away3DBitmap:Bitmap = new Away3DImage();     [Embed(source="/../assets/checker.jpg")] private var CheckerImage:Class;     private var checkerBitmap:Bitmap = new CheckerImage();     private static const ORBITAL_RADIUS:Number = 150;     private static const CAMERA_ORBIT:Number = 600;     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;       private var group:ObjectContainer3D;     private var sphere:Sphere;     private var cube:Cube;     private var centerCube:Cube;     private var cylinder:Cylinder;     private var torus:Torus;       private var doRotation:Boolean = false;     private var lastMouseX:int;     private var lastMouseY:int;     private var cameraPitch:Number = 60;     private var cameraYaw:Number = -60;         public function Example004() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;       // Add resize event listener       stage.addEventListener(Event.RESIZE, onResize);             // Listen to mouse up and down events on the stage       stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);       stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);       // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise frame-enter loop       this.addEventListener(Event.ENTER_FRAME, loop);     }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:25, focus:30});       setCameraPosition();             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }     private function createScene():void {       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);           // Create a new sphere object using a bitmap material representing the earth       var earthMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(earthBitmap));       sphere = new Sphere({material:earthMaterial, radius:50, segmentsW:10, segmentsH:10});       sphere.x = ORBITAL_RADIUS;       group.addChild(sphere);       // Create a new cube object using a tiled bitmap material       var tiledAway3DMaterial:TransformBitmapMaterial = new TransformBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});       cube = new Cube({material:tiledAway3DMaterial, width:75, height:75, depth:75});       cube.z = -ORBITAL_RADIUS;       group.addChild(cube);         // Create a cylinder mapping the earth data again       cylinder = new Cylinder({material:earthMaterial, radius:25, height:100, segmentsW:16});       cylinder.x = -ORBITAL_RADIUS;       group.addChild(cylinder);         // Create a torus object and use a checkered bitmap material       var checkerBitmapMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(checkerBitmap));       torus = new Torus({material:checkerBitmapMaterial, radius:40, tube:10, segmentsT:8, segmentsR:16});       torus.z = ORBITAL_RADIUS;       group.addChild(torus);         // Create a new cube object using a smoothed, precise bitmap material       var away3DMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});       centerCube = new Cube({material:away3DMaterial, width:75, height:75, depth:75});       group.addChild(centerCube);       // add mouse listeners to all the 3D objects       sphere.addOnMouseDown(onMouseDownOnObject);       cube.addOnMouseDown(onMouseDownOnObject);       cylinder.addOnMouseDown(onMouseDownOnObject);       torus.addOnMouseDown(onMouseDownOnObject);       centerCube.addOnMouseDown(onMouseDownOnObject);     }         private function loop(event:Event):void {             // rotate the group of objects       group.yaw(2);           // rotate the objects       sphere.yaw(-4);       cube.yaw(-4);       cylinder.yaw(-4);       torus.yaw(-4);       // update the camera position       updateCamera();       // Render the 3D scene       view.render();     }     // updates the camera position     private function updateCamera():void {             // If the mouse button has been clicked then update the camera position            if (doRotation) {                 // convert the change in mouse position into a change in camera angle         var dPitch:Number = (mouseY - lastMouseY) / 2;         var dYaw:Number = (mouseX - lastMouseX) / 2;                 // update the camera angles         cameraPitch -= dPitch;         cameraYaw -= dYaw;         // limit the pitch of the camera         if (cameraPitch <= 0) {           cameraPitch = 0.1;         } else if (cameraPitch >= 180) {           cameraPitch = 179.9;         }               // reset the last mouse position         lastMouseX = mouseX;         lastMouseY = mouseY;                 // reposition the camera         setCameraPosition();       }           }     // sets the camera position given pitch and yaw angles     private function setCameraPosition():void {       camera.y = CAMERA_ORBIT * Math.cos(cameraPitch * Math.PI / 180);       camera.x = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.cos(cameraYaw * Math.PI / 180);       camera.z = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.sin(cameraYaw * Math.PI / 180);             // keep the camera looking at the origin       camera.lookAt(new Number3D(0, 0, 0));     }     // called when mouse down on stage     private function onMouseDown(event:MouseEvent):void {       doRotation = true;       lastMouseX = event.stageX;       lastMouseY = event.stageY;     }     // called when mouse up on stage     private function onMouseUp(event:MouseEvent):void {       doRotation = false;     }       // called when mouse down on a 3D object     private function onMouseDownOnObject(event:MouseEvent3D):void {       var object:Object3D = event.object;       Tweener.addTween(object, {y:200, time:1, transition:"easeOutSine", onComplete:function():void {goBack(object);} });     }         // called when a tween created in onMouseDownOnObject has terminated     private function goBack(object:Object3D):void {       Tweener.addTween(object, {y:0, time:2, transition:"easeOutBounce"});     }         // called when the window is resized     private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   }     }

The example embeds the same images as the last time so if you need them you can find them in my last post. Don’t forget that you’ll need to link to the Tweener library for this to compile correctly. The resulting Flash movie should be as below - click on the image below to load it. Now when you click on the background and move the mouse you should be able to rotate the scene (effectively moving the camera) and clicking on each object should make them bounce.

First of all, lets have a look how the we add the standard Flash MouseEvent to rotate the camera.

Starting with the constructor we add two listeners.

      // Listen to mouse up and down events on the stage       stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);       stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);

When a mouse click is detected on the stage the function onMouseDown is called. When the button is released onMouseUp is called. These functions indicate when the camera movement should start and stop.

    // called when mouse down on stage     private function onMouseDown(event:MouseEvent):void {       doRotation = true;       lastMouseX = event.stageX;       lastMouseY = event.stageY;     }     // called when mouse up on stage     private function onMouseUp(event:MouseEvent):void {       doRotation = false;     }

To start the camera movement we set the boolean doRotation to true and to stop it we set it to false. The amount of rotation depends on how far the mouse moves during a single frame so we store the position of the mouse at every frame as well. The camera is then updated during the loop function

    private function loop(event:Event):void {             // rotate the group of objects       group.yaw(2);           // rotate the objects       sphere.yaw(-4);       cube.yaw(-4);       cylinder.yaw(-4);       torus.yaw(-4);       // update the camera position       updateCamera();       // Render the 3D scene       view.render();     }

Other than the call to updateCamera the rendering remains identical to the last example. The camera position is then calculated as follows.

    // updates the camera position     private function updateCamera():void {             // If the mouse button has been clicked then update the camera position            if (doRotation) {                 // convert the change in mouse position into a change in camera angle         var dPitch:Number = (mouseY - lastMouseY) / 2;         var dYaw:Number = (mouseX - lastMouseX) / 2;                 // update the camera angles         cameraPitch -= dPitch;         cameraYaw -= dYaw;         // limit the pitch of the camera         if (cameraPitch <= 0) {           cameraPitch = 0.1;         } else if (cameraPitch >= 180) {           cameraPitch = 179.9;         }               // reset the last mouse position         lastMouseX = mouseX;         lastMouseY = mouseY;                 // reposition the camera         setCameraPosition();       }           }

From the change in mouse position we calculate (arbitrarily) a change in angle from the y axis (pitch) and similarly around the y axis (yaw). The pitch is kept within limits to avoid the camera from going over the poles and hence changing the up direction of the camera. Once we’ve calculated the new values of pitch and yaw for the camera position we can convert these angles into x, y and z positions. This is done in setCameraPosition.

    // sets the camera position given pitch and yaw angles     private function setCameraPosition():void {       camera.y = CAMERA_ORBIT * Math.cos(cameraPitch * Math.PI / 180);       camera.x = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.cos(cameraYaw * Math.PI / 180);       camera.z = CAMERA_ORBIT * Math.sin(cameraPitch * Math.PI / 180) * Math.sin(cameraYaw * Math.PI / 180);             // keep the camera looking at the origin       camera.lookAt(new Number3D(0, 0, 0));     }

Note that we keep the camera at all times looking at the origin.

Moving on to the interaction with the 3D objects using the MouseEvent3D event, for this example I’m just going to look at the events when the mouse is clicked over an object. You’ll see that adding the listeners is very simple: at the end of the createScene a listener is added to each object.

      // add mouse listeners to all the 3D objects       sphere.addOnMouseDown(onMouseDownOnObject);       cube.addOnMouseDown(onMouseDownOnObject);       cylinder.addOnMouseDown(onMouseDownOnObject);       torus.addOnMouseDown(onMouseDownOnObject);       centerCube.addOnMouseDown(onMouseDownOnObject);

The rest of createScene is identical to the previous example. Now, whenever a user clicks on these objects, the function onMouseDownOnObject is called.

    // called when mouse down on a 3D object     private function onMouseDownOnObject(event:MouseEvent3D):void {       var object:Object3D = event.object;       Tweener.addTween(object, {y:200, time:1, transition:"easeOutSine", onComplete:function():void {goBack(object);} });     }

The listener is called with the MouseEvent3D passed as an argument. From this we can easily obtain the Object3D for which the event occurred. We then invoke Tweener to perform an animation on the object.

Tweener contains static methods that allow us to modify object properties. In this case we simply modify the y position of the object so that it goes to a value of 200 in 1 second using the easeOutSine transition function. I’d recommend looking at the Tweener documentation on the different transition functions. The onComplete argument allows us to put the sphere back to its original position when the tween has completed.

    // called when a tween created in onMouseDownOnObject has terminated     private function goBack(object:Object3D):void {       Tweener.addTween(object, {y:0, time:2, transition:"easeOutBounce"});     }

This then uses another tween with an easeOutBounce transition to move the sphere back to the x-z plane.

And that’s all there is to it! With Tweener you can modify a number of different properties in parallel. For example you can change y and scale the object at the same time. The interface provided by Away3D is in any case very easy to use. Making a comparison to Papervision3D I find it a bit easier: with Papervision3D we need to say that the say that each individual material is interactive, as well as the View itself. This is surely to produce some performance optimisation. Other than this the interaction with objects is very similar for both engines and, I hope you’ll find, is straightforward to implement!

Next article:

In this post I’d like to show how to add textures to 3D objects rather than using plain colours which provides much more realistic (or at least interesting) rendering. You’ll find that with Away3D the concepts are very similar to those used in other 3D engines - for a comparison and some texture mapping references check out my equivalent tutorial for texture mapping in Papervision3D. I’m going to discuss texture mapping rather early on in this series of articles (earlier than for the Papervision3D series) simply because you’ll find that when come on to adding lighting and shading it opens up a much richer set of possibilities. But, I’m sure you’ll find that adding textures is a very simple process - at least, I hope so!

Previous articles summary :

Adding textures to objects in Away3D (as with most, if not all, 3D engines) is done by mapping coordinates on bitmap data to triangle vertices, known as texture mapping. More specifically, a technique known as uv mapping is used where u and v are the coordinates of the bitmap data which are then passed to the renderer for every triangle vertex. The following diagram tries to explain this for a pyramid. The uv coordinates are totally invented but you can see that for a single triangle the uv coordinates for every vertex are mapped onto the bitmap data (having a maximum u being equal to 1, and similarly for the maximum v) and the resulting triangle from the bitmap used to render the pyramid face.

In this example you’ll see that a number of different primitives are used (a cube, sphere, torus and cylinder). Each triangle used to produce these 3D objects has the uv coordinates for each vertex calculated. You can see in the link above for uv mapping the calculation necessary for a sphere. As you’ll see below, the image used to give texture to the sphere has been pre-calculated so that once mapped it produces a realistic image of the earth.

Ok, so on with the example code. As usual this is built on the previous example and there are not too many differences. We’ll go into more detail on what’s changed later. The code produces five primitives, all rotating about the origin and each one rotating about its individual y-axis.

package {   import away3d.cameras.Camera3D;   import away3d.containers.ObjectContainer3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.math.Number3D;   import away3d.core.utils.Cast;   import away3d.materials.BitmapMaterial;   import away3d.materials.TransformBitmapMaterial;   import away3d.primitives.Cube;   import away3d.primitives.Cylinder;   import away3d.primitives.Sphere;   import away3d.primitives.Torus;     import flash.display.Bitmap;   import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;     [SWF(backgroundColor="#000000")]     public class Example003 extends Sprite {     [Embed(source="/../assets/earth.jpg")] private var EarthImage:Class;     private var earthBitmap:Bitmap = new EarthImage();     [Embed(source="/../assets/away3D.png")] private var Away3DImage:Class;     private var away3DBitmap:Bitmap = new Away3DImage();     [Embed(source="/../assets/checker.jpg")] private var CheckerImage:Class;     private var checkerBitmap:Bitmap = new CheckerImage();     private static const ORBITAL_RADIUS:Number = 150;     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;       private var group:ObjectContainer3D;     private var sphere:Sphere;     private var cube:Cube;     private var centerCube:Cube;     private var cylinder:Cylinder;     private var torus:Torus;         public function Example003() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;       // Add resize event listener       stage.addEventListener(Event.RESIZE, onResize);             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise frame-enter loop       this.addEventListener(Event.ENTER_FRAME, loop);     }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:25, focus:30, x:-200, y:400, z:-400});       camera.lookAt(new Number3D(0, 0, 0));             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }     private function createScene():void {       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);           // Create a new sphere object using a bitmap material representing the earth       var earthMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(earthBitmap));       sphere = new Sphere({material:earthMaterial, radius:50, segmentsW:10, segmentsH:10});       sphere.x = ORBITAL_RADIUS;       group.addChild(sphere);       // Create a new cube object using a tiled bitmap material       var tiledAway3DMaterial:TransformBitmapMaterial = new TransformBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});       cube = new Cube({material:tiledAway3DMaterial, width:75, height:75, depth:75});       cube.z = -ORBITAL_RADIUS;       group.addChild(cube);         // Create a cylinder mapping the earth data again       cylinder = new Cylinder({material:earthMaterial, radius:25, height:100, segmentsW:16});       cylinder.x = -ORBITAL_RADIUS;       group.addChild(cylinder);         // Create a torus object and use a checkered bitmap material       var checkerBitmapMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(checkerBitmap));       torus = new Torus({material:checkerBitmapMaterial, radius:40, tube:10, segmentsT:8, segmentsR:16});       torus.z = ORBITAL_RADIUS;       group.addChild(torus);         // Create a new cube object using a smoothed, precise bitmap material       var away3DMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});       centerCube = new Cube({material:away3DMaterial, width:75, height:75, depth:75});       group.addChild(centerCube);     }         private function loop(event:Event):void {             // rotate the group of objects       group.yaw(2);           // rotate the objects       sphere.yaw(-4);       cube.yaw(-4);       cylinder.yaw(-4);       torus.yaw(-4);       // Render the 3D scene       view.render();     }     private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   } }

Copy the code above and compile it within Flex Builder 3 or Eclipse. The images I used are shown below - click on them and save them if you want to use the same ones.

Click on the image below to see the resulting flash movie. The images are embedded in the movie making it larger than the previous examples so it could take a couple of seconds to load.

The code follows the same style as the previous examples: initialisation of 3D elements, creation of scene and rendering loop. As usual I’ll just concentrate on what’s new.

Not really related to Away3D but important for projects (in Flex) using images is the ability to embed images in the compiled movie. As you can see the images are embedded in the class definition.

    [Embed(source="/../assets/earth.jpg")] private var EarthImage:Class;     private var earthBitmap:Bitmap = new EarthImage();     [Embed(source="/../assets/away3D.png")] private var Away3DImage:Class;     private var away3DBitmap:Bitmap = new Away3DImage();     [Embed(source="/../assets/checker.jpg")] private var CheckerImage:Class;     private var checkerBitmap:Bitmap = new CheckerImage();

Using the Embed meta-tag we can add binary object to the compiled movie. These can then be converted into usable graphic elements, as shown above for a Bitmap. As with the same example in Papervision3D, I’m not going to go into detail of embedding objects here, rather I’ll leave you with these couple of references that are very useful. The first one is at at assertTrue and the second is from the Flex livedocs.

You’ll note that the source is “../assets”. This is because I have my assets folder at the same level as the src folder - when the Actionscript is compiled, the root folder is the src folder. If you want to compile the above source then simply create an assets folder and put the image files in it.

Now that we have embedded the images and obtained bitmap data we can start to create texture mapped materials. This is done in createScene where some different methods of creating different textures is examined.

    private function createScene():void {       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);           // Create a new sphere object using a bitmap material representing the earth       var earthMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(earthBitmap));       sphere = new Sphere({material:earthMaterial, radius:50, segmentsW:10, segmentsH:10});       sphere.x = ORBITAL_RADIUS;       group.addChild(sphere);       // Create a new cube object using a tiled bitmap material       var tiledAway3DMaterial:TransformBitmapMaterial = new TransformBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});       cube = new Cube({material:tiledAway3DMaterial, width:75, height:75, depth:75});       cube.z = -ORBITAL_RADIUS;       group.addChild(cube);         // Create a cylinder mapping the earth data again       cylinder = new Cylinder({material:earthMaterial, radius:25, height:100, segmentsW:16});       cylinder.x = -ORBITAL_RADIUS;       group.addChild(cylinder);         // Create a torus object and use a checkered bitmap material       var checkerBitmapMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(checkerBitmap));       torus = new Torus({material:checkerBitmapMaterial, radius:40, tube:10, segmentsT:8, segmentsR:16});       torus.z = ORBITAL_RADIUS;       group.addChild(torus);         // Create a new cube object using a smoothed, precise bitmap material       var away3DMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});       centerCube = new Cube({material:away3DMaterial, width:75, height:75, depth:75});       group.addChild(centerCube);     }

As you can see, the creation of the 3D objects is very simple: just create a new primitive, pass it some initialisation arguments and create a new material for it. Of course, compared the previous example, the materials are now texture mapped. Two different materials are used in this example: the BitmapMaterial for simple texture mapping and TransformBitmapMaterial which gives us more options.

Starting with the Sphere, we use a simple BitmapMaterial and pass it bitmap data. The class Cast in Away3D provides useful transformation routines - in this case to return the BitmapData of the Bitmap object.

      var earthMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(earthBitmap));

The Sphere is then created using this material. All uv mapping is handled by the Sphere itself to render the image over the sphere triangles.

The next object is a Cube. Here I want to illustrate how to tile images over an object. Tiling allows us to repeat an image over a surface, for example imagine a scene with a grassy plain with the same grass image repeated a number of times. This allows us to keep the image size reasonable and have a texture mapped object that isn’t too pixelated.

      var tiledAway3DMaterial:TransformBitmapMaterial = new TransformBitmapMaterial(Cast.bitmap(away3DBitmap), {repeat:true, scaleX:.5, scaleY:.5});

To tile bitmap we need to use the TransformBitmapMaterial class. With this we can manipulate the image data, for example, here we scale it to half its size and indicate that it should be repeated. Scaling here implies that the maximum u and v coordinates of the texture become 0.5 rather than 1 hence we should see a two-by-two image drawn on each face of the cube. If the repeat:true initialisation parameter is skipped then the image is drawn only once… try recompiling without this to see the result.

The Cylinder and Torus objects use simple BitmapMaterials again just to show how the bitmaps are mapped to these primitives.

Finally the cube in the center shows an example of a texture map using a smoothed image and uses more precise perspective calculations when rendered. This link for texture mapping shows what happens for affine texture mapping: Away3D (as for Papervision3D) tries to optimise the calculation for rendering textures and this can result in a distorted image. You can see this in the above example for the tiled cube where the black lines appear to be wavy. The distortion can, however, be corrected but of course this produces a more cpu-intensive calculation.

      var away3DMaterial:BitmapMaterial = new BitmapMaterial(Cast.bitmap(away3DBitmap), {smooth:true, precision:2});

For the central cube we set smooth:true to have a less pixelated texture and we set precision:2 to indicate that the texture should be correctly rendered to within 2 pixels. A value of 0 turns off the precision calculation.

As an alternative to using more precise rendering of a texture we can also increase the number of triangles used so that the distortion becomes less evident. You can check out this example for Papervision3D that illustrates the result. Of course, increasing the number of triangles increases the render time but within limits it can produce a visually acceptable rendering quicker than a single precise texture mapping.

So that’s it for texture mapping at its simplest! As you can see there’s nothing too complicated in adding bitmaps to 3D objects but bear in mind that it is obviously more cpu-intensive that simple coloured objects. As with the previous articles I’d recommend having a look at the Away3D source - you’ll see that there are a lot of different types of materials in the away3D.materials package including the BitmapFileMaterial which loads an image from a URL, rather than embedding it in the movie. Anyway, hope this has been of use. As always, questions and comments are welcome!

Next article:

-->
Saturday, November 15th, 2008

First steps in Away3D : Part 2 - Animation

Following from my previous post, I’d like to make the scene a bit more interesting by adding some animation. As you’ll see, not many modifications to the code are necessary. As with Part 1, I’m basing this example on a previous Papervision3D example that you can find in First steps in Papervision3D : Part 3.

Previous articles summary :

Using the same objects as before (a Sphere and LineSegments displaying the x, y and z axes), my objective is to rotate all of them about the origin and individually rotate the sphere. Rotation in Away3D is very easy to achieve. These objects inherit from a base class called Object3D as do all 3D object displayed in a Scene in Away3D. This class provides a number of useful functions to rotate, translate and scale an object. The simplest way to rotate an object is to use the pitch, yaw and roll functions which rotate an object about its local x, y and z axes respectively.

So, lets dive right in and take a look at the code. As I mentioned before, this is based on the previous example and very little modifications have been made. As before I’m using eclipse with the Flex Builder 3 plugin to compile the examples: take a look at my previous post if you’re new to eclipse and want to see how to set up the projects. Otherwise, create a new ActionScript class, call it Example002 and cut and paste the following code.

package {   import away3d.cameras.Camera3D;   import away3d.containers.ObjectContainer3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.base.Vertex;   import away3d.core.math.Number3D;   import away3d.materials.WireColorMaterial;   import away3d.materials.WireframeMaterial;   import away3d.primitives.LineSegment;   import away3d.primitives.Sphere;     import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;     [SWF(backgroundColor="#000000")]     public class Example002 extends Sprite {     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;       private var group:ObjectContainer3D;     private var sphere:Sphere;         public function Example002() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;       // Add resize event listener       stage.addEventListener(Event.RESIZE, onResize);             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise frame-enter loop       this.addEventListener(Event.ENTER_FRAME, loop);     }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:15, focus:30, x:100, y:300, z:-200});       camera.lookAt(new Number3D(0, 0, 0));             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }     private function createScene():void {       // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);             // Create a new sphere object using a wirecolor material       var sphereMaterial:WireColorMaterial = new WireColorMaterial(0x5500FF, {wirecolor:0xFF9900});       sphere = new Sphere({material:sphereMaterial, radius:50, segmentsW:10, segmentsH:10});       // Position the sphere and add it to the group       sphere.x = -100;       group.addChild(sphere);         // Create a origin vertex       var origin:Vertex = new Vertex(0, 0, 0);       // Create the red-coloured x-axis with a width of 2 and add it to the group       var xAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0xFF0000, {width:2})});       xAxis.start = origin;       xAxis.end = new Vertex(100, 0, 0);       group.addChild(xAxis);           // Create the green-coloured y-axis with a width of 2 and add it to the group       var yAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x00FF00, {width:2})});       yAxis.start = origin;       yAxis.end = new Vertex(0, 100, 0);       group.addChild(yAxis);           // Create the blue-coloured z-axis with a width of 2 and add it to the group       var zAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x0000FF, {width:2})});       zAxis.start = origin;       zAxis.end = new Vertex(0, 0, 100);       group.addChild(zAxis);       }         private function loop(event:Event):void {             // rotate the group of objects       group.yaw(5);           // rotate the sphere       sphere.yaw(-10);           // Render the 3D scene       view.render();     }     private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   } }

This should produce a scene that is rotated about the y-axis with a sphere that rotates in the opposite direction, also about its y-axis. Click on the image below to see the final result.

As always, lets take a look at the code in more detail. Since there are so many similarities with the previous example I won’t go into detail for everything, just what is new.

Starting with the constructor, you’ll notice that I’ve added a resize listener that calls the method onResize.

    private function onResize(event:Event):void {       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;     }   } }

This is used to ensure that if a user resizes the browser or flash player that the View is automatically resized to take up the full stage area. Its not really much of a 3D element of the scene but its important not to forget it!

The rest of the code takes the same form as before: initialise the 3D elements, create the scene and re-render the scene at every new frame. As you’ll see in init3D I’ve modified the camera slightly.

      // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:15, focus:30, x:100, y:300, z:-200});       camera.lookAt(new Number3D(0, 0, 0));

The camera is now in a different position, but more importantly I’ve added a call to camera.lookAt. Previously the camera was looking directly along the z-axis: now I’ve told it to look at the origin. You can similarly call the functions tilt and pan which (as it says in the code comments for the Camera3D class) is like someone nodding and shaking their head.

Moving on to the scene creation in createScene, I’ve introduced a new element used to group the objects: an ObjectContainer3D.

      // Create an object container to group the objects on the scene       group = new ObjectContainer3D();       scene.addChild(group);

This object is not itself visible on the scene but allows us to add children to it and translate, rotate and scale these children all together. So, rather than adding each individual object to the scene, they are now added to the group as is, for example, the sphere.

      // Create a new sphere object using a wirecolor material       var sphereMaterial:WireColorMaterial = new WireColorMaterial(0x5500FF, {wirecolor:0xFF9900});       sphere = new Sphere({material:sphereMaterial, radius:50, segmentsW:10, segmentsH:10});       // Position the sphere and add it to the group       sphere.x = -100;       group.addChild(sphere);  

The lines are similarly added to the group. So that’s the only difference to the scene creation itself (other than the sphere now being a different colour). Now we come to adding the animation.

To add animation we simply need to modify object parameters at each frame and then re-render the scene. As I mentioned before I simple rotate the ObjectContainer3D and the Sphere itself and this is done in the loop function that is called at the start of every new frame.

    private function loop(event:Event):void {             // rotate the group of objects       group.yaw(5);           // rotate the sphere       sphere.yaw(-10);           // Render the 3D scene       view.render();     }

As you can see there’s really not much to it: simple rotate the group about its y axis, and the same for the sphere itself. The call the view.render then updates what we see on the screen.

And that’s it! To get a feel for the animation, try changing the yaw method to roll or pitch, or try adding some translation. I’d recommend having a look at the Away3D code to see what else is available - you’ll find that there are a lot of possibilities! Anyway, I hope this has been a useful step in making more interesting 3D scenes in Away3D!

Next article:

Wednesday, November 12th, 2008

First steps in Away3D : Part 1 - Getting started

In the same spirit as the First steps in Papervision3D series of articles, I’m documenting my own progress in learning about this 3D engine for Flash. I hope as well that this provides a useful tutorial for others getting started with Away3D. I guess what I’m trying to say is that this is by no means a definitive guide to Away3D! This is my first day as well so if you find mistakes or have suggestions then please let me know!

Before starting I’d like to post a couple of links to a series of articles that I found very interesting and useful for beginners learning the basics of 3D programming. The first one one, Flash 3D Basics, provides a very good overview of the important elements for any 3D development. The second one is aimed directly at Away3D, but is relevant also to Papervision3D, and discusses the two main classes for any Away3D flash movie: The View and The Scene. You’ll see both of these being used below. Anyway, I’d really recommend taking a look at them.

For this post I’m really starting at the very beginning. My aim is simply to draw 3D shapes on the screen, exactly as I did for First steps in Papervision3D : Part 1. For this I’m assuming that you are using Flex Builder 3, or the Flex Builder 3 plugin for eclipse, as I am. I’m also assuming that you have Away3D built and ready to link to. My previous article on downloading and installing Away3D in eclipse might help if this isn’t the case.

For those of you who are new to using Flex Builder 3, we need to first of all create a new project and then set it’s build path to that of the Away3D source.

In eclipse (or Flex Builder 3), from the File menu, select New and then ActionScript project. You’ll see a New ActionScript Project window appear.

Type in a project name (for example I named it Tartiflop) and click on Finish. We then need to configure the project to use either the Away3D.swf library that I showed how to create before, or we link directly to the Away3D source. I prefer the second method simply because it gives me a more convenient access to the library source by navigating within eclipse. To do this, select the new project and right-click. Select Properties from the drop-down menu. Select the ActionScript Build Path on the left.

Select the Library path tab and click on Add Project….

Select the Away3D Flex Library project and click on OK. You’ll see that the library has now been added into the list of build path libraries.

We’re now ready to start creating our first Away3D flash movie! You’ll notice that the new project wizard of eclipse has automatically created an ActionScript class called Tartiflop.as. We don’t need this so you can delete it. For this post the class is called Example001.as so you’ll need to create a new ActionScript. Right-click on src in the Tartiflop project in the Flex Navigator tree. Select New and then ActionScript Class. Name the new class Example001 and click Finish.

The following code draws a sphere and three lines showing the x, y and z axes. Cut and paste the code below (we’ll go into the details of how it works later), save and it should hopefully compile without any errors!

package {   import away3d.cameras.Camera3D;   import away3d.containers.Scene3D;   import away3d.containers.View3D;   import away3d.core.base.Vertex;   import away3d.materials.WireColorMaterial;   import away3d.materials.WireframeMaterial;   import away3d.primitives.LineSegment;   import away3d.primitives.Sphere;     import flash.display.Sprite;   import flash.display.StageAlign;   import flash.display.StageScaleMode;   import flash.events.Event;     [SWF(backgroundColor="#000000")]     public class Example001 extends Sprite {     private var scene:Scene3D;     private var camera:Camera3D;     private var view:View3D;         public function Example001() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise Event loop       this.addEventListener(Event.ENTER_FRAME, loop);        }     private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:20, focus:30, x:-100, y:-100, z:-500});             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }     private function createScene():void {       // First object : a sphere             // Create a new material for the sphere : simple white wireframe       var sphereMaterial:WireColorMaterial = new WireColorMaterial(0x000000, {wirecolor:0xFFFFFF});       // Create a new sphere object using wireframe material, radius 50 with       // 10 horizontal and vertical segments       var sphere:Sphere = new Sphere({material:sphereMaterial, radius:50, segmentsW:10, segmentsH:10});       // Position the sphere (default = [0, 0, 0])       sphere.x = -100;       scene.addChild(sphere);         // Second object : x-, y- and z-axis         // Create a origin vertex       var origin:Vertex = new Vertex(0, 0, 0);       // Create the red-coloured x-axis with a width of 2       var xAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0xFF0000, {width:2})});       xAxis.start = origin;       xAxis.end = new Vertex(100, 0, 0);       scene.addChild(xAxis);           // Create the green-coloured y-axis with a width of 2       var yAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x00FF00, {width:2})});       yAxis.start = origin;       yAxis.end = new Vertex(0, 100, 0);       scene.addChild(yAxis);           // Create the blue-coloured z-axis with a width of 2       var zAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x0000FF, {width:2})});       zAxis.start = origin;       zAxis.end = new Vertex(0, 0, 100);       scene.addChild(zAxis);       }         private function loop(event:Event):void {       // Render the 3D scene       view.render();     }   } }

To see the final result, right-click again on the Tartiflop project and select Run As and Flex Application. What you should see is the following: click on the image below to see the real flash movie (its not much more interesting than the image though!).

Let’s go into more detail with the code. I’m taking a look at this with the point of view of someone who has been using Papervision3D and its interesting to look at the similarities and differences between the two libraries. If you compare the code to the equivalent in Papervision3D, you can see that the codes resemble a lot.

The constructor of Example001 is identical to that of the equivalent example in Paperivision3D: the stage parameters are set so that the scene is scaled correctly, the 3D elements are initialised, the scene is created and then we add a frame-enter event listener.

Example001 inherits from the Sprite class as is indeed possible with Papervision3D. Papervision3D however provides a BasicView class where the scene, camera, view and renderer are all encapsulated (see part 2 of the Papervision3D series for example). Also the stage scaling is automatically encapsulated in the BasicView class.

    public function Example001() {             // set up the stage       stage.align = StageAlign.TOP_LEFT;       stage.scaleMode = StageScaleMode.NO_SCALE;             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();             // Initialise Event loop       this.addEventListener(Event.ENTER_FRAME, loop);        }

However, as we can see, its not very complicated to initialise all the 3D elements individually - as we do in the init3D() function.

    private function init3D():void {       // Create a new scene where all the 3D object will be rendered       scene = new Scene3D();             // Create a new camera, passing some initialisation parameters       camera = new Camera3D({zoom:20, focus:30, x:-100, y:-100, z:-500});             // Create a new view that encapsulates the scene and the camera       view = new View3D({scene:scene, camera:camera});       // center the viewport to the middle of the stage       view.x = stage.stageWidth / 2;       view.y = stage.stageHeight / 2;       addChild(view);     }

We first of all create a Scene3D object which is used later to contain all of our rendered 3D elements. Secondly we create a Camera3D which sets up all our viewing parameters and finally we create a View3D object which provides us with our window through which we observe the scene.

Interesting to note is the way we can create Away3D objects. Unlike Papervsion3D which has well defined constructors taking specific arguments, Away3D allows us to pass an array of initialisation parameters. One good point is that this makes the code more concise, however, personally, I feel that it is less intuitive: with Papervision3D I felt I could determine relatively quickly what was needed to construct an object but here you need to search more within a class to obtain useful information. Having said that I have to admit that I haven’t yet looked at the Away3D documentation! I’m someone who is too excited to get his hands dirty before reading the manual!

With respect to the camera, unlike Papervision3D it is not possible to modify the field of view (or fov) directly and instead we need to manipulate the zoom and focus of the camera (see my post on the relationship between all three and also this really good article explaining the Away3D camera). Having an OpenGL background I find the field of view more intuitive however this is just a personal opinion.

After the 3D base elements have been created we can move on to creating the scene. This, as is fairly obvious, is done in the createScene() function.

    private function createScene():void {       // First object : a sphere             // Create a new material for the sphere : simple white wireframe       var sphereMaterial:WireColorMaterial = new WireColorMaterial(0x000000, {wirecolor:0xFFFFFF});       // Create a new sphere object using wireframe material, radius 50 with       // 10 horizontal and vertical segments       var sphere:Sphere = new Sphere({material:sphereMaterial, radius:50, segmentsW:10, segmentsH:10});       // Position the sphere (default = [0, 0, 0])       sphere.x = -100;       scene.addChild(sphere);         // Second object : x-, y- and z-axis         // Create a origin vertex       var origin:Vertex = new Vertex(0, 0, 0);       // Create the red-coloured x-axis with a width of 2       var xAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0xFF0000, {width:2})});       xAxis.start = origin;       xAxis.end = new Vertex(100, 0, 0);       scene.addChild(xAxis);           // Create the green-coloured y-axis with a width of 2       var yAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x00FF00, {width:2})});       yAxis.start = origin;       yAxis.end = new Vertex(0, 100, 0);       scene.addChild(yAxis);           // Create the blue-coloured z-axis with a width of 2       var zAxis:LineSegment = new LineSegment({material:new WireframeMaterial(0x0000FF, {width:2})});       zAxis.start = origin;       zAxis.end = new Vertex(0, 0, 100);       scene.addChild(zAxis);       }

The scene is very simple: no lighting and just two stationary types of objects. As with Papervision3D, most objects provide only the vertices of a given shape: the rendering (what we see on the screen) is done through the material.

In this example we use two types of materials for two different types of shapes. This is different to Papervision3D where any material seems to be usable with any object. Here, the two shapes belong to two different families: an AbstractPrimitive and an AbstractWirePrimitive. Each one uses a material also belonging to a different family: an ITriangleMaterial and an ISegmentMaterial respectively. If we give the wrong type of material to a particular primitive then it is not rendered.

The two shapes used are a Sphere (an AbstractPrimitive) and a LineSegment (an AbstractWirePrimitive). We therefore give them two different types of materials. In this example I’ve used a WireColorMaterial and a WireframeMaterial respectively. The WireColorMaterial is created with a face color (black in this case) and a wire color is passed in the list of initialisation arguments (being white). The wireframe material is simply white but I’ve passed a width of 2 in the initialisation parameters.

The sphere is created first, taking a list of initialisation parameters including the sphere material. It should be noted that these parameters can be set afterwards, not necessarily in the constructor. I then create 3 lines for each axis, each one with a different color wireframe material. The lines are then given two vertices to define their start and end positions. Each 3D object is added to the scene so that they are rendered.

As a first impression of Away3D, I actually find that the construction of these primitive objects is more concise than for Papervision3D. Looking through the source directory of Away3D I also get the impression that there is more choice of primitives compared to Papervision3D.

Finally for this example, a small function is used to render the scene. We added in the constructor a frame-enter event listener called loop.

    private function loop(event:Event):void {       // Render the 3D scene       view.render();     }

Very simply, we call the function render of view to redraw the scene. This is another difference to Papervision3D: Papervision3D has a specific Renderer class used to draw the scene.

And that’s it! A very simple example of rendering a 3D scene in Away3D. Compared to Papervision3D, for something this simple, there really isn’t a huge difference. Overall I feel that Away3D is more concise but maybe loses degree of simplicity using the parameters array rather than having explicit constructor arguments… but that’s just a personal point of view though.

One surprise is the difference in file sizes between Papervision3D and Away3D. In Away3D the flash animation come to 136KB whereas in Papervision3D its at only 82KB. Okay, so neither are huge and maybe Away3D is a bigger library… but I’m interested to see how this compares for more complex examples.

Anyway, that’s it for this example. For me too its a first step - I just wanted to see what the Away3D library was like and how easy it was to convert from a Papervision3D source to an Away3D one. I hope to continue along the same theme to produce more complex examples over the coming weeks. As always, comments and suggestions as are always welcome so please don’t hesitate!

Next article:

-->
Monday, September 29th, 2008

First steps in Papervision3D : Part 9 - Importing and working with 3D objects

Previous articles summary :

Back again for another article in the First Steps series… its been a while since the last one mainly because I’ve moved from Blogger to Wordpress and that’s been quite a hassle. But, hopefully, now that its up and running it won’t be so long before the next one… fingers crossed!

In this article (which again is probably going to be quite a long one) I’m looking at how to import 3D objects that have been created using specialised applications such as 3DS Max, Maya, Blender and Google Sketchup to name a few.

To improve the exchange of digital assets between these different applications, various file formats exists that allow 3D objects from one application to be used in another. One particular format that is readable by Papervision3D, is the Collaborative Design Activity format or COLLADA which saves the information of a 3D scene as XML.

The Collada format specifications are maintained by the Khronos Group and embedded within the file are details on geometry, shaders and effects, physics, animation and kinematics. The specifications are supported by a number of companies including 3DS Max, Maya and Blender. The files themselves have the .dae extension, standing for Digital Asset Exchange.

Papervision3D contains a extensive package to parse and import Collada files yet has a simple interface making it easy to use complex 3D models created in specialised applications. Worth noting are a couple of sites that contain Collada files created by different communities that can be downloaded and used fairly freely. These are

As I’ve mentioned from the beginning of this series, these posts represent also what I’ve learned over the last few weeks and are by no means expert tutorials. I’ve therefore made use of a number of sites in understanding how to import objects into Papervision3D and I’m sure you’ll find useful information on them as well.

Since there are a number of points to look at I decided it was best to split this post into two parts. In the first part of this post I’ll illustrate a selection of different ways of importing objects into Papervision3D based on the above examples and also from exploring the source code of Paperivison3D itself. In the second part I’m going to look at how to add interactivity and shading with Collada objects. I’ll also present some problems that exist with shading in the current version of Papervision3D - well, it is beta after all!

Lets have a look at the source for the first example. Here, my objective is simply to import 3D objects into a scene using a number of different sources. These include

The last one is making use of a special class within Papervision3D dedicated to file with the .kmz file extension (Google Earth). These files are actually .zip files that contain texture maps and Collada data.

Papervision3D also has (as far as I can tell) two main ways of importing Collada data: one is using the Collada class, the other is using the DAE class, both of which are in the org.papervision3d.objects.parsers package. Again, as far as I can tell, the DAE class appears to be more mature making extensive use of the org.ascollada package and I’ve had more success over the last few days using this rather than the Collada class.

So here’s the source code, importing four objects using different sources and different importing methods.

package {     import flash.events.Event;   import flash.events.MouseEvent;     import org.papervision3d.events.FileLoadEvent;   import org.papervision3d.lights.PointLight3D;   import org.papervision3d.materials.BitmapMaterial;   import org.papervision3d.materials.MovieMaterial;   import org.papervision3d.materials.utils.MaterialsList;   import org.papervision3d.objects.DisplayObject3D;   import org.papervision3d.objects.parsers.Collada;   import org.papervision3d.objects.parsers.DAE;   import org.papervision3d.objects.parsers.KMZ;   import org.papervision3d.view.BasicView;   public class Example009a extends BasicView {       [Embed(source="/../assets/cow.dae", mimeType="application/octet-stream")] private var CowDAE:Class;     [Embed(source="/../assets/Cow.png")] private var CowBitmapImage:Class;     private var light:PointLight3D;     private var doRotation:Boolean = false;     private var lastMouseX:int;     private var lastMouseY:int;     private var cameraPitch:Number = 60;     private var cameraYaw:Number = -60;             public function Example009a() {       super(0, 0, true, true);             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();       // Listen to mouse up and down events on the stage       stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);       stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);       // Start rendering the scene       startRendering();     }         private function init3D():void {       // position the camera       camera.z = -700;       camera.fov = 60;       camera.orbit(cameraPitch, cameraYaw);     }         private function createScene():void {       // create new Collada from URL, using original materials and scaled to 50%       var cow:Collada = new Collada("http://www.tartiflop.com/pv3d/FirstSteps/collada/cow.dae", null, 0.5);       cow.moveDown(100);       cow.moveBackward(200);       cow.yaw(90);       scene.addChild(cow);       // create a texture mapped material from embedded png       var cowMaterial:BitmapMaterial = new MovieMaterial(new CowBitmapImage(), true);             // add the texture map to a material list corresponding to the material symbols in the dae       var cowMaterials:MaterialsList = new MaterialsList();       cowMaterials.addMaterial(cowMaterial, "mat0");       // create a new Collada, specifying the materials we want to use       var cow2:Collada = new Collada(new XML(new CowDAE()), cowMaterials);       cow2.moveRight(300);       cow2.moveDown(100);       scene.addChild(cow2);           // create a new DAE that is animated and perform actions once it is loaded       var seymour:DAE = new DAE(true);       seymour.addEventListener(FileLoadEvent.LOAD_COMPLETE, function onLoad(event:Event):void {         seymour.scale = 20;         seymour.moveForward(200);         seymour.moveDown(100);         scene.addChild(seymour);       });             // load the DAE from a specific URL       seymour.load("http://www.tartiflop.com/pv3d/FirstSteps/collada/Seymour.dae");             // create a new 3D object from a 3D google earth object file and perform actions when loaded       var kmz:KMZ = new KMZ();       kmz.addEventListener(FileLoadEvent.LOAD_COMPLETE, function onLoad(event:Event):void {         kmz.scale = 20;         kmz.moveLeft(300);         kmz.moveDown(100);         scene.addChild(kmz);       });             // load kmz from a specific URL       kmz.load("http://www.tartiflop.com/pv3d/FirstSteps/collada/thing.kmz");           }     override protected function onRenderTick(event:Event=null):void {       // update camera position       updateCamera();           // call the renderer       super.onRenderTick(event);     }         private function updateCamera():void {             // If the mouse button has been clicked then update the camera position            if (doRotation) {                 // convert the change in mouse position into a change in camera angle         var dPitch:Number = (mouseY - lastMouseY) / 2;         var dYaw:Number = (mouseX - lastMouseX) / 2;                 // update the camera angles         cameraPitch -= dPitch;         cameraYaw -= dYaw;         // limit the pitch of the camera         if (cameraPitch <= 0) {           cameraPitch = 0.1;         } else if (cameraPitch >= 180) {           cameraPitch = 179.9;         }               // reset the last mouse position         lastMouseX = mouseX;         lastMouseY = mouseY;                 // reposition the camera         camera.orbit(cameraPitch, cameraYaw);       }           }     // called when mouse down on stage     private function onMouseDown(event:MouseEvent):void {       doRotation = true;       lastMouseX = event.stageX;       lastMouseY = event.stageY;     }     // called when mouse up on stage     private function onMouseUp(event:MouseEvent):void {       doRotation = false;     }       } }

This produces the following flash animation (click on the image below). Note that it can take some time for the models to be loaded into flash, but in the end you should see four models including two cows, an animated Space Boy (coming from the public directory of the Collada test model bank at Khronos) and a rather crappy thing I made in Google Sketchup! You can rotate the scene by clicking and moving the mouse at the same time.

So, lets take a closer look at the code… As with other examples I’m using the same standard BasicView derived class - the main difference from previous ones coming in the createScene function.

The first cow object is created by obtaining all the data for the Collada object from an external URL. Contained in the .dae file is information on the texture maps so we don’t need to specify anything other than the location of the Collada file itself to create a fully rendered object.

      // create new Collada from URL, using original materials and scaled to 50%       var cow:Collada = new Collada("http://www.tartiflop.com/pv3d/FirstSteps/collada/cow.dae", null, 0.5);       cow.moveDown(100);       cow.moveBackward(200);       cow.yaw(90);       scene.addChild(cow);

Here I’m using the Collada class which provides a very simple interface to import Collada data. The first argument is of course the location of the .dae file (you can just as easily use a file on the local file system). The second argument is to specify a different material for the object: in this case I’ll use the file referenced by the Collada file itself. The third parameter relates to the scaling: in this case 50%. The resulting object is then translated, rotated and added to the scene.

We can similarly import Collada data by embedding the data in the Flash animation (as we’ve seen in previous examples in this series). We have to, however, embed both the Collada data and the texture map data for it to be correctly rendered. You’ll find the embedded files at the beginning of the class definition.

    [Embed(source="/../assets/cow.dae", mimeType="application/octet-stream")] private var CowDAE:Class;     [Embed(source="/../assets/Cow.png")] private var CowBitmapImage:Class;

The .dae file format is not recognised by Flash which is why we need to explicitly give the mimeType. As you’ll see below we can use the DAE data directly as an XML document. The Collada object is then created as follows.

      // create a texture mapped material from embedded png       var cowMaterial:BitmapMaterial = new MovieMaterial(new CowBitmapImage(), true);             // add the texture map to a material list corresponding to the material symbols in the dae       var cowMaterials:MaterialsList = new MaterialsList();       cowMaterials.addMaterial(cowMaterial, "mat0");       // create a new Collada, specifying the materials we want to use       var cow2:Collada = new Collada(new XML(new CowDAE()), cowMaterials);       cow2.moveRight(300);       cow2.moveDown(100);       scene.addChild(cow2);

We specifically create a material for the 3D object: I’m using a MovieMaterial which in this case is created with a simple bitmap image. Since a Collada object can have a number of different textured materials we need to provide it with a MaterialList. The names associated with the materials have to relate to details within the Collada file… after some investigation I found that the material was referenced by the name mat0. The Collada object is then created by passing data encapsulated in an XML format and this time specifying the material list used in association with the data. As with the first object, we then translate it and add it to the scene.

The third object is an animated Collada object. This time I’m using the DAE class which has more success in importing the data. The interface remains very similar to the Collada class however we need to specifically load the data.

      // create a new DAE that is animated and perform actions once it is loaded       var seymour:DAE = new DAE(true);       seymour.addEventListener(FileLoadEvent.LOAD_COMPLETE, function onLoad(event:Event):void {         seymour.scale = 20;         seymour.moveForward(200);         seymour.moveDown(100);         scene.addChild(seymour);       });             // load the DAE from a specific URL       seymour.load("http://www.tartiflop.com/pv3d/FirstSteps/collada/Seymour.dae");

The first argument to the DAE constructor specifies whether we want the DAE to be animated or not: in this case we do. We then add a listener which is triggered when the data is fully loaded. This allows us to add it to the scene and modify its size and position when we are sure that the data is coherent. The data is loaded by specifying a URL to the Collada file.

Finally to show how to import data from a different source, I’ve included an example that I made using Google Sketchup and exported as a Google Earth object (.kmz file extension). And yes, I know, its not very pretty…

      // create a new 3D object from a 3D google earth object file and perform actions when loaded       var kmz:KMZ = new KMZ();       kmz.addEventListener(FileLoadEvent.LOAD_COMPLETE, function onLoad(event:Event):void {         kmz.scale = 20;         kmz.moveLeft(300);         kmz.moveDown(100);         scene.addChild(kmz);       });             // load kmz from a specific URL       kmz.load("http://www.tartiflop.com/pv3d/FirstSteps/collada/thing.kmz");

Papervision3D provides us with a class KMZ specifically to import this type of data. In fact, embedded in this file is a .dae Collada file (and the class has a reference to a DAE object as well) so the import mechanism remains the same… it is however another handy tool. As you can see we use the same technique as with the DAE import.

So, there we are: four different methods of importing Collada data. Now for the more advanced part of this post: adding shading to the objects.

In principal this should follow from the previous post on texture mapping with lighting where a ShadedMaterial is used to skin an object (as we did above with cow2 when we specified a list of materials for the DAE). However, at the time of writing this article, this is not working correctly: the main problem being black lines appearing on face edges. As you can see from the list of bugs at the home of Papervision3D, an issue has been raised explaining the problem. You can also see on the Papervision3D mailing list that this is a recurring problem (here and here for example).

This said, all is not lost! Thanks to those talented people involved in the Papervision3D project, specifically in this case to Andy Zupko, a work-around does exist! Also, I’d like to give a thanks to the Papervision3D newsgroup because the list is very active and you can find a lot of very good information on it… like this fix.

So, here’s the second example source code for this post. Here I’m showing the two different methods for rendering a shaded Collada object: the first (not fully working in the current release of Papervision3D) using a ShadedMaterial and the second using Andy’s work-around which involves blending two identical models: one with a simple shaded material, the other with a texture-mapped material.

package {     import flash.display.BlendMode;   import flash.events.Event;   import flash.events.MouseEvent;   import flash.text.TextField;   import flash.text.TextFieldAutoSize;   import flash.text.TextFormat;   import flash.utils.getTimer;     import org.papervision3d.events.FileLoadEvent;   import org.papervision3d.events.InteractiveScene3DEvent;   import org.papervision3d.lights.PointLight3D;   import org.papervision3d.materials.BitmapMaterial;   import org.papervision3d.materials.MovieMaterial;   import org.papervision3d.materials.shadematerials.GouraudMaterial;   import org.papervision3d.materials.shaders.GouraudShader;   import org.papervision3d.materials.shaders.ShadedMaterial;   import org.papervision3d.materials.utils.MaterialsList;   import org.papervision3d.objects.DisplayObject3D;   import org.papervision3d.objects.parsers.DAE;   import org.papervision3d.view.BasicView;   public class Example009b extends BasicView {       [Embed(source="/../assets/cow.dae", mimeType="application/octet-stream")] private var CowDAE:Class;     [Embed(source="/../assets/Cow.png")] private var CowBitmapImage:Class;     private var light:PointLight3D;         private var shadedMaterialCow:DAE;     private var gouraudCow:DAE;     private var texturedCow:DAE;     private var allCows:DisplayObject3D;         private var doRotation:Boolean = false;     private var lastMouseX:int;     private var lastMouseY:int;     private var cameraPitch:Number = 60;     private var cameraYaw:Number = -60;           private var fpsText:TextField;     private var textFormat:TextFormat;       private var frames:Number = 0;     private var lastTimeMS:Number = 0;       private var doSimple:Boolean = false;       public function Example009b() {       super(0, 0, true, true);             // Initialise Papervision3D       init3D();             // Create the 3D objects       createScene();       // create the frame rate counter label       createFPSLabel();       // Listen to mouse up and down events on the stage       stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);       stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);       // Start rendering the scene       startRendering();     }         private function init3D():void {       // position the camera       camera.z = -500;       camera.fov = 60;       camera.orbit(cameraPitch, cameraYaw);     }         private function createFPSLabel():void {       // create text and format to display current fps       textFormat = new TextFormat();       textFormat.size = 20;       textFormat.font = "Arial";             fpsText = new TextField();       fpsText.x = 50;       fpsText.y = 50;       fpsText.textColor = 0xFFFFFF;       fpsText.text = "";       fpsText.setTextFormat(textFormat);       fpsText.autoSize = TextFieldAutoSize.LEFT;             stage.addChild(fpsText);     }     private function createScene():void {       // Specify a point light source and its location       light = new PointLight3D(true);       light.x = 500;       light.y = 300;       light.z = -500;       scene.addChild(light);       // create a display object to group all created cows       allCows = new DisplayObject3D();       scene.addChild(allCows);       // create a cow with a shaded material       createSimpleShadedDAE();             // create a shaded cow by blending two different rendered objects       createNiceShadedDAE();     }     private function createSimpleShadedDAE():void {       // create BitmapMaterial from texture map       var cowBitmapMaterial:BitmapMaterial = new MovieMaterial(new CowBitmapImage(), true);         // create a ShadedMaterial using a Gouraud shader       var shader:GouraudShader = new GouraudShader(light, 0xFFFFFF, 0x333333);       var shadedMaterial:ShadedMaterial = new ShadedMaterial(cowBitmapMaterial, shader);       shadedMaterial.interactive = true;             // Material list linked to material symbol name in dae       var mainMaterials:MaterialsList = new MaterialsList();       mainMaterials.addMaterial(shadedMaterial, "mat0");       // create a new dae and perform actions when loaded       shadedMaterialCow = new DAE(false);       shadedMaterialCow.addEventListener(FileLoadEvent.LOAD_COMPLETE, function onLoad(event:Event):void {         shadedMaterialCow.moveDown(100);         shadedMaterialCow.scale = 100;                 // add cow to scene when loaded         allCows.addChild(shadedMaterialCow);                 // recursively add event listeners to dae and all children         addEventListeners(shadedMaterialCow, InteractiveScene3DEvent.OBJECT_CLICK, toggleRendering);       });             // load the dae from the embedded structure and replace the materials       shadedMaterialCow.load(new XML(new CowDAE()), mainMaterials);     }         private function createNiceShadedDAE():void {       // create a simple texture mapped material for the embedded png       var cowBitmapMaterial:BitmapMaterial = new MovieMaterial(new CowBitmapImage(), true);       cowBitmapMaterial.interactive = true;             // add the material to a material list corresponding to the dae       var bitmapMaterials:MaterialsList = new MaterialsList();       bitmapMaterials.addMaterial(cowBitmapMaterial, "mat0");       // create a new dae and perform actions when loaded       texturedCow = new DAE(false);       texturedCow.addEventListener(FileLoadEvent.LOAD_COMPLETE, function onLoad(event:Event):void {         texturedCow.moveDown(100);         texturedCow.scale = 100;         // set the dae to initially not be visible         texturedCow.visible = false;                 // add to the scene         allCows.addChild(texturedCow);                 // listen to events (applies to all children of dae as well)         addEventListeners(texturedCow, InteractiveScene3DEvent.OBJECT_CLICK, toggleRendering);               });       // load the dae from the embedded structure and replace the materials       texturedCow.load(new XML(new CowDAE()), bitmapMaterials);       // create a simple Gouraud shaded material and add to list corresponding to dae       var gouraudMaterial:GouraudMaterial = new GouraudMaterial(light, 0xFFFFFF, 0x333333);       var shadedMaterials:MaterialsList = new MaterialsList();       shadedMaterials.addMaterial(gouraudMaterial, "mat0");       // create a new dae and perform actions when loaded       gouraudCow = new DAE(false);       gouraudCow.addEventListener(FileLoadEvent.LOAD_COMPLETE, function onLoad(event:Event):void {         gouraudCow.scale = 100;         gouraudCow.moveDown(100);         // set the dae to initially not be visible         gouraudCow.visible = false;           // add to the scene         allCows.addChild(gouraudCow);         // change the rendering so that it is blended with other rendered objects         viewport.getChildLayer(gouraudCow).blendMode = BlendMode.MULTIPLY;        });             // load the dae from the embedded structure and replace the materials       gouraudCow.load(new XML(new CowDAE()), shadedMaterials);     }     // used to ensure that all children in a dae listen to events     private function addEventListeners(displayObject:DisplayObject3D, eventType:String, listener:Function):void {       // add listener to DisplayObect       displayObject.addEventListener(eventType, listener);             // add listener to all contained childred       for each(var child:DisplayObject3D in displayObject.children) {         addEventListeners(child, eventType, listener);       }     }         // toggles between the two rendering techniques     private function toggleRendering(event:InteractiveScene3DEvent):void {       texturedCow.visible = !texturedCow.visible;       gouraudCow.visible = !gouraudCow.visible;       shadedMaterialCow.visible = !shadedMaterialCow.visible;     }     override protected function onRenderTick(event:Event=null):void {             // rotate the scene       allCows.yaw(-1);             // calculate the frame rate       calculateFrameRate();       // update the camera position       updateCamera();           // call the renderer       super.onRenderTick(event);     }         private function calculateFrameRate():void {       // calculate the time elapsed since the last calculation            var currentTimeMS:Number = getTimer();       var elapsedTimeMS:Number = currentTimeMS - lastTimeMS;       // if a second has elapsed then calculate the fps       if (elapsedTimeMS >= 1000) {         fpsText.text = frames.toString() + " fps";         fpsText.setTextFormat(textFormat);                 // reset the counter         lastTimeMS = currentTimeMS;         frames = 0;             } else {         // increment the counter         frames++;       }           }         private function updateCamera():void {             // If the mouse button has been clicked then update the camera position            if (doRotation) {                 // convert the change in mouse position into a change in camera angle         var dPitch:Number = (mouseY - lastMouseY) / 2;         var dYaw:Number = (mouseX - lastMouseX) / 2;                 // update the camera angles         cameraPitch -= dPitch;         cameraYaw -= dYaw;         // limit the pitch of the camera         if (cameraPitch <= 0) {           cameraPitch = 0.1;         } else if (cameraPitch >= 180) {           cameraPitch = 179.9;         }               // reset the last mouse position         lastMouseX = mouseX;         lastMouseY = mouseY;                 // reposition the camera         camera.orbit(cameraPitch, cameraYaw);       }           }     // called when mouse down on stage     private function onMouseDown(event:MouseEvent):void {       doRotation = true;       lastMouseX = event.stageX;       lastMouseY = event.stageY;     }     // called when mouse up on stage     private function onMouseUp(event:MouseEvent):void {       doRotation = false;     }       } }

The resulting Flash animation can be seen below by clicking on the image. You can rotate the scene by clicking and moving the mouse. You can also switch between the two rendering techniques by clicking on the cow. To show that there is not a huge difference in performance between the two techniques, a frame-rate meter is shown in the top-left hand corner.

So again, lets take a closer look at the code. Starting with the ShadedMaterial version that produces the problems. This is created in the createSimpleShadedDAE function.

    private function createSimpleShadedDAE():void {       // create BitmapMaterial from texture map       var cowBitmapMaterial:BitmapMaterial = new MovieMaterial(new CowBitmapImage(), true);         // create a ShadedMaterial using a Gouraud shader       var shader:GouraudShader = new GouraudShader(light, 0xFFFFFF, 0x333333);       var shadedMaterial:ShadedMaterial = new ShadedMaterial(cowBitmapMaterial, shader);       shadedMaterial.interactive = true;             // Material list linked to material symbol name in dae       var mainMaterials:MaterialsList = new MaterialsList();       mainMaterials.addMaterial(shadedMaterial, "mat0");       // create a new dae and perform actions when loaded       shadedMaterialCow = new DAE(false);       shadedMaterialCow.addEventListener(FileLoadEvent.LOAD_COMPLETE, function onLoad(event:Event):void {         shadedMaterialCow.moveDown(100);         shadedMaterialCow.scale = 100;                 // add cow to scene when loaded         allCows.addChild(shadedMaterialCow);                 // recursively add event listeners to dae and all children         addEventListeners(shadedMaterialCow, InteractiveScene3DEvent.OBJECT_CLICK, toggleRendering);       });             // load the dae from the embedded structure and replace the materials       shadedMaterialCow.load(new XML(new CowDAE()), mainMaterials);     }

As we’ve seen in previous posts, to create a shaded bitmap material we combine a BitmapMaterial with a Shader. Here we use the embedded bitmap data of the texture map combined with a simple Gouraud shader. These are combined in a ShadedMaterial which is then added to the material list as we did above for the first part of this post. I’m using a DAE object to load the Collada data which is then combined with material data.

What you’ll notice however is that the interactivity is added in a different manner from previous posts. For Collada objects we need to add the event listener to all of the children of the DAE as well as the DAE itself - see this post on the Papervision3D newsgroup for details. To perform this, I’ve added (as mentioned in the post) a small routine to recursively add the listener to all children.

    // used to ensure that all children in a dae listen to events     private function addEventListeners(displayObject:DisplayObject3D, eventType:String, listener:Function):void {       // add listener to DisplayObect       displayObject.addEventListener(eventType, listener);             // add listener to all contained childred       for each(var child:DisplayObject3D in displayObject.children) {         addEventListeners(child, eventType, listener);       }     }

So, as you can see from the Flash animation, this method doesn’t work - yet! So, now for the fix provided by Andy Zupko. You’ll find his original post on shadow casting very interesting. The idea is that we take advantage of the Flash architecture to blend 2D objects together. To do this we render the DAE twice: once with a texture map but no shading and another time with no texture map and simple shading. Each render produces a 2D image (what is seen on the screen). These images can be superimposed and blended so that the resulting image is a shaded texture map.

The overhead of drawing the same 3D object twice seems to be fairly smal