papervision3D - PQ torus

demo, code, actionscript, flex, flash, papervision3D, mxml


here we go again, another papervision3D demo featuring math permeated lines. this time im working with a classic piece of code known as the PQ torus. the vague idea is that you have 2 numbers (P + Q) that are used in the algorithm to define the knot. in general, given P + Q mutually prime, the line wraps meridionally around the torus P times and wraps the longitudinally around it Q times. i was having some trouble grasping exactly how this was going to be achieved, until i read this article on blackpawn’s website. he really breaks down the algo to a very simplistic level...

    calculus
  1. r = .5 * (2 + sin(Q * Φ))
  2. x = r * cos(P * Φ)
  3. y = r * cos(Q * Φ)
  4. z = r * sin(P * Φ)

simple right? lol.
so Φ (or phi in my code) is basically a variable that is definded by change. in this case, im simply incrementing phi + .02 every frame. this seeds the math and gives you the cool visual effect.

anyway, after getting a handle on the math, writing the demo code was a snap. i took the existing code i wrote from the 3D object tracer and the lorenz attractor and combined them. (i also found + fixed an error for computing the line gradient color) i started out by allowing the users to only select values for PQ and that actually made sense.


but after some experimentation i found that using some unorthodox values for P+Q could net some very interesting results. take a look at some of these...




click here to view the demo
click here for the source code

custom flex skins

code, actionscript, flex, flash, mxml, css, tutorial


creating web-applications with flex 3 is great. there are a ton of pre-made components, and an open-ended architecture to allow you to create your own. built into flex is also a variety of options to change the visual styles of the components. today i will talk about two different types of customization. first, the simplest method, is using css to style your components. next, the more advanced technique, is creating component skins. for this example i will be using flash cs3.

with in a flex mxml application, css is natively understood. so by utilizing the tag, we can create a variety of styles for out application. personally, i don't really care for the eclipse/flex built in css editor, but since flex uses valid css, any editor can work! macromedia has also created a very useful tool for helping designers/developers write flex 3 specific css. click here to view the flex 3 style explorer

now for some code...
like in all css there are two ways to define a style.
first as an overall style for one type of object, for instance...

    css code
  1. Button {
  2. cornerRadius: 0;
  3. fillColors: #333333, #cccccc, #cccccc, #666666;
  4. color: #ffffff;
  5. borderColor: #ffffff;
  6. }

this style will be applied to all buttons that appear in your application. notice the style name is simply "Button", the name of the component type. this is how flex understands which objects to apply the style to.

    css code
  1. .anotherButton {
  2. cornerRadius: 0;
  3. fillColors: #ffffff, #333333, #333333, #666666;
  4. color: #ffffff;
  5. borderColor: #000000;
  6. }

now, this code by default will not be applied to any components in your application. notice the style name is time is ".anotherButton", the period that prefaces the style name indicates that this is a custom style, not a component style definition. to apply this style to a button in your application use the following code...

<mx:Button styleName="anotherButton"/>

here's a very simple flex 3 application using css styles
    mxml code
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  3. <mx:Style>
  4. Application {
  5. backgroundColor: #000000;
  6. backgroundGradientColors: #666666, #cccccc;
  7. themeColor: #00ff00;
  8. color: #ffffff;
  9. }
  10. Panel {
  11. borderStyle: solid;
  12. borderColor: #cccccc;
  13. roundedBottomCorners: true;
  14. cornerRadius: 0;
  15. headerHeight: 18;
  16. backgroundColor: #666666;
  17. titleStyleName: "panelTitle";
  18. }
  19. .panelTitle {
  20. letterSpacing: 3;
  21. color: #ffffff;
  22. textAlign: center;
  23. fontFamily: Verdana;
  24. fontSize: 12;
  25. }
  26. TextInput {
  27. borderStyle: solid;
  28. borderColor: #ffffff;
  29. borderThickness: 1;
  30. cornerRadius: 0;
  31. backgroundColor: #333333;
  32. color: #ffffff;
  33. textAlign: center;
  34. fontFamily: Verdana;
  35. fontSize: 12;
  36. }
  37. Button {
  38. cornerRadius: 0;
  39. fillColors: #333333, #999999, #ffffff, #333333;
  40. color: #ffffff;
  41. textRollOverColor: #ffffff;
  42. textSelectedColor: #ffffff;
  43. borderColor: #333333;
  44. }
  45. .anotherButton {
  46. cornerRadius: 0;
  47. fillColors: #ffffff, #666666, #333333, #999999;
  48. color: #ffffff;
  49. textRollOverColor: #ffffff;
  50. textSelectedColor: #ffffff;
  51. borderColor: #333333;
  52. }
  53. </mx:Style>
  54. <mx:Panel styleName="" width="244" height="134" layout="absolute" horizontalCenter="-1" verticalCenter="9" title="here's a panel">
  55. <mx:Label x="0" y="10" text="Label"/>
  56. <mx:TextInput x="0" y="27" width="220" text="text input"/>
  57. <mx:Button x="0" y="57" label="Button"/>
  58. <mx:Button styleName="anotherButton" x="78" y="57" label="Button"/>
  59. <mx:Button x="155" y="57" label="Button"/>
  60. </mx:Panel>
  61. </mx:Application>
  62.  

skinning is the technique of images and/or movieclips to create a visual style for a flex component. being that adobe makes a dozen different applications, there are in fact a dozen different ways to create flex skins. here's a really nice article over viewing the different ways to skin flex
and here's another great article

today in going to discuss creating skins in flash. adobe makes it really easy for us by providing a set of pre-made flex skin templates. go a head and download them from here:

Your looking for the "Flex Skin Design Extension for Flash"
the files
the documentation
(*note* you will need an adobe ID -- they are free btw...)

there are also a set of component classes for creating completely custom, skinnable flex compatable components called "the flex component kit for flash cs3". but im not gonna dive into all that just yet... ;D

now that you have download the "flex3skins-flash.mxp" file, you need to register it with the adobe extension manager. (this should be installed already if you have any cs3 product, but if not grab a copy here) just double click on the file, or open the extension manager and click "File... Install Extension"



after agreeing to the disclaimer, you should see an alert box telling you that your templates have been successfully installed. now we're ready to make some flex skins!

open flash cs3.
select "File... New", then click the "templates" tab on the top left. change the category to "Flex Skins", and now you can see a list of all the available flex component templates. now just to let you know, there is not a template for EVERY available flex component, but the vast majority.



so go ahead and select the "button" template. when the flash file loads take a look at the library, you'll notice there's a movieclip called "button_skin". open it up and take a look at what's there.



in the timeline, in the "states" layer, we have four separate keyframes, up, over, down, and disabled. these keyframes are the four main visual styles for the flex button component. now, take a look at the gridline down in the main design area. these lines are called a scale9grid (more info about that here) they show flex the areas that are allowed to scale, the default size, and the main area where the label is going to be placed. make a new layer in the timeline above "art" and add blank key frames that match the layer below. now add some images for each of the button states. then use the cursor tool to move the scale9grid lines to match up for your skin.



once you have all the images ready to go right click on the "button_skin" object in the library and click "linkage". this brings up the actionscript3 properties for that particular movieclip. give your visual style a name I used "blaqueButtonSkin". now take a look at the base class for this object. it need to be set to "mx.flash.UIMovieClip". the user interface movieclip class is setup to look for the names of the keyframes to decide which images to use for the different states of your skinned components. so make sure you keep the frame names set to "up, over, down, and disabled" or flex will not be able to parse your skin!



the last step in flash is to generate our skin library for flex. click "File... Publish Setting" (or ctrl+shift+f12) make sure your swf setting are set to actionscipt3, and the "Export .SWC" checkbox is checked. then publish your skin. take a look in the directory that flash published to. there should be a few files in there, but were only going to be concerned with the SWC file. copy that file to the clip board and open flex 3.

in flex start by creating a new MXML application. then right click on the /libs folder and paste in our skin.swc file. everything in the lib (or library) folder is automatically added into flex's available namespaces to be used in your application. switch into the source code tab and add a style tag to your application. then add the following css...

    css code
  1. Button {
  2. skin: Embed(skinClass="blaqueButtonSkin");
  3. color: #ffffff;
  4. textRollOverColor: #ffffff;
  5. textSelectedColor: #ffffff;
  6. textAlign: left;
  7. }

notice how the skin is applied to the button with the "skin" tag and we're using the linkage name we set in flash, blaqueButtonSkin. also by using the embed keyword in conjunction with the skinClass tag will attach your visual style completely, even during design time.

one thing to note is that some of the components are based on other ones. the for instance, its template file only contains the up and down arrows. the textbox that the actual selected number appears in is based on the regular flex component. so to skin both parts you will need to make a skin for the numericstepper as well as the textarea. but you can save both of those files into one swc by just copying and pasting the library object from one template into the library of another one.

another as3 range seeded randomizer

code, actionscript, flash, random, flex

just another take on a classic piece of code. the pseudo-random number generator. this one is almost the same, just a slightly diffrent algorithm.

    actionscript 3 code
  1. private function randomizer(low:Number, high:Number):Number {
  2. var num:Number = high-low;
  3. return (Math.random()*num)+low;
  4. }
then use it...
    actionscript 3 code
  1. var x:Number = randomizer(5, 50);
i <3 randomization

tracing 3D objects with papervision3D

demo, code, actionscript, flex, flash, papervision3D, fontz, mxml, tutorial


a question popped up on the papervision3D mailing list the other day about using the lines3D class to trace a 3D object. i found the idea fascinating, so i whipped up this little demo to demonstrate how simple it actually was. i started out by creating a simple cylinder with a wide base and small top, and setting its visibility to false. then creating my lines3D object. finally in the render loop i create a new line3D that connects each vertice. by checking to see in a counter variable is less than the total object vertice count ((box.geometry.vertices.length)), and adding a new line3D if the counter is less than that, or deleting all the lines and starting over.

check out that demo here
view the demo source

so that wasnt enough.
i decide that i wanted to trace the actual papervision3D logo. and since i have already made it in a font, it wasnt hard at all. working with the optimized version of the font on my site worked fine, but since there were so few verticies, the script would draw the logo in a matter of seconds. so instead of trying to devise a method of tweening from vertice to vertice i just went into font lab and added more points!
((the font used in this demo is available here))

now, i went into 3D studio max, clicked the "Splines" button, and created a new text object. i used the new PV3D.Flex.Font i just made, set the size to 100 (larger/smaller is fine) and typed in the letter "A" (the only character in the font).

after that i used the rotation tools to stand the letter upright, and moved it forward some. the next step is to do a mesh select, by clicking the modifiers tab and selecting "Mesh Select" from the dropdown menu. then in the mesh select parameters panel select vertices. now click back into your main perspective and select all the vertices (ctrl+a).


the next step is an important one ((and the one i always forget)) we need to give our 3D object a uvw mapping. still under the modifiers tab, select "UVW Mapping" from the dropdown list. and under the parameters panel make sure its mapping mode is set to "Planar". i was having all kinds of trouble exporting 3D objects that were based on points only. seraf explained to me that w/o a uvw mapping on your object the as3geomClassExporter cant map the u and v points onto the triangle mesh, which are needed for texturing purposes.


now its time to export our 3D logo, click on the tools tab and select max script, then run the as3geomClassExporter. set your package folder and the actual class name, then select papervision3D 2.0 from the dropdown list. for this particular object i left the scale set to 1. then click export class and save it in the same folder as you set in your package.



then its onto flex.
i decided i wanted to use the math-based color fade from my last demo again, so i couldnt use the standard color picker. this demo uses 2 states, normal and the color picker. which is just a 2nd state with a panel object w/ blank flex buttons on them. using the flex buttons worked out well because i was able to just set the color gradient to the same colors in the fade, or just solid ones for the normal sets. i tried to make is one a simple as possible so you can understand the core concepts of whats going on more than the over-all "flashy-ness" of the thing. so enjoy!

click here to view the demo
and its source of course!

the lorenz attractor

demo, code, actionscript, flex, flash, papervision3D, random, work, mxml


we were discussing recursive algorithms and chaos theory at work yesterday. when the chemistry professor brought up the lorenz attractor. he was trying to draw one on the white board for about 10 minutes until i decided it would be easier to draw in flash, lol!

after a quick conversation w/ andy zupko about the new Line3D object, and my new CanvasView3D component for papervision, i made a sweet Lorenz attractor!

the algor is super simple

    pseudo code
  1. x1 = x0 + h * a * (y0 - x0);
  2. y1 = y0 + h * (x0 * (b - z0) - y0);
  3. z1 = z0 + h * (x0 * y0 - c * z0);

A, B, and C are variables that get their values from form components in the application, while H is a constant that represent the angles of the curves dictated by segment size. x0, y0, and z0 are the origin vertex’s while x1, y1, and z1 are the destination points.

besides the form objects for the A, B, and C values, the application features an event driven camera, that follows the drawing as it happens. as well as a hover camera, which lets your rotate the object in 3D. the actual lines that are being drawn are given a new material each render. that's how the color tweening effect is achieved. use the color picker box to select a valid color to start with. also, the algor run 3000 times, (getting slower and slower as it loops) press the generate button to erase the lorenz you already have a begin drawing a new one w/ the form values you have selected.

a little background on the lorenz...
the lorenz attractor is a 3D structure corresponding to the long-term behavior of chaotic flow. the visual “map” represents the evolution of a dynamic system, that complexifys and into a unique non-repetitious pattern. originally discovered by edward lorenz in 1963, the current algorithm is based on simplified version of his equations of convection rolls arising in the atmosphere. for detailed technical info check out math world and this article by dominic van berkel.

click here to check out the demo
then browse the source code

CanvasView3D – new flex component

code, actionscript, flex, papervision3D, downloadz, mxml

after my last post about creating an actionscript project that extends the basic view, i got to thinking... my flex canvas3D is getting a bit outdated. these days i just make canvas then add my viewport3D or a basicView to it. so why not create a new UIcomponent that extends basicView? why not indeed...

introducing my new class, called CanvasView3D! this little flex gem makes setting up papervision3D in an MXML setting simple. by creating the CanvasView3D component, and initializing it to a local variable, you will automatically create a scene3D, camera3D, viewport3D, and a basicRenderEngine, all the core components of any PV3D application!

first things first, add a new xml namespace to your flex application
in this case, its going to be com.fontvirus.*

    mxml code
  1. <mx:Application
  2. xmlns:mx="http://www.adobe.com/2006/mxml"
  3. xmlns:xx="com.fontvirus.*"
  4. layout="absolute"
  5. applicationComplete="init3D()">
  6. </mx:Application>
now that we have a new custom namespace called "xx", we need to make a new CanvasView3D object.
    mxml code
  1. <xx:CanvasView3D id="paperCanvas" top="0" bottom="0" left="0" right="0"/>
the top, bottom, left, and right properties dictate the placement and size of the CanvasView3D object. in this case it will be stretched to fit the full screen size. but there are other properties you can set here as well (or in your as3 code), such as:
    mxml code
  1. <xx:CanvasView3D autoScaleMode="true" interactivity="false" autoClipMode="true" autoCullMode="true"/>
now that our CanvasView3D is setup and ready in our MXML, we need to instantiate it actionscript code. this step is just as easy as the rest, just declare a new basicView object and set it to your CanvasView3D’s view property.
    actionscript 3 code
  1. var view:BasicView = paperCanvas.view;
now we have access to all of the bacicView objects just like if we would have created one then added it to a UIcomponent, etc, etc... now you have a choice to setup new variables for each of your objects or just use them through the basicView.
    actionscript 3 code
  1. var cam:Camera3D = paperCanvas.view.camera;
  2. cam.zoom = 10;
  3. cam.focus = 2;
  4. var scene:Scene3D = paperCanvas.view.scene;
  5. scene.addChild(new DisplyObject3D());
  6. var viewport:ViewPort3D = paperCanvas.view.viewport.
  7. var num = viewport.lastRenderList.length;
  8. var renderer:BasicRenderEngine = paperCanvas.view.renderer;
  9. render.renderScene(cam, scene, view);

or

    actionscript 3 code
  1. view.camera.zoom = 10;
  2. view.camera.focus = 2;
  3. view.scene.addChild(new DisplyObject3D());
  4. var num = view.viewport.lastRenderList.length;
  5. view.renderer.renderScene(view.camera, view.scene, view.viewport);
personally i think the second coding style is much more concise and simplistic. but that's just one thing that is so great about object oriented languages, there's 10000 ways to do the same thing. its all about circumstance, and necessity.

i hope this is useful to some one.

download the CanvasView3D class
here's a simple little demo
and some code to get you started

extending the basic view

code, actionscript, flash, papervision3D

the core PV3D team has released a new class called the basicView. the idea here is to create one object that already contains the camera, scene, viewport, and render engine needed to made a 3D scene in flash.

after reading the post about it on andy’s blog, you can see that this is a very simple technique. but lets take it one step further. why not create a new actionscipt project that extends basic view?! its very simple, and makes setting up your scene a snap!

    actionscript3 code
  1. package {
  2. import com.fontvirus.*;
  3. import flash.display.*;
  4. import flash.events.Event;
  5. import org.papervision3d.cameras.*;
  6. import org.papervision3d.core.render.data.RenderStatistics;
  7. import org.papervision3d.lights.*;
  8. import org.papervision3d.materials.shadematerials.*;
  9. import org.papervision3d.objects.primitives.*;
  10. import org.papervision3d.scenes.*;
  11. import org.papervision3d.view.*;
  12. [SWF(backgroundColor="#000000")]
  13. public class basicPV3D extends BasicView
  14. {
  15. private var thelight :PointLight3D;
  16. private var thing :Sphere;
  17. private var fps :FlashFPS;
  18. private var stats :RenderStatistics;
  19. public function basicPV3D():void
  20. {
  21. super(0,0,true,true,Camera3D.TYPE);
  22. stats = this.renderer.renderScene(this.scene, this.camera, this.viewport);
  23. this.viewport.autoClipping = false;
  24. init3D();
  25. }
  26. private function init3D():void
  27. {
  28. stage.align = StageAlign.TOP_LEFT;
  29. stage.scaleMode = StageScaleMode.NO_SCALE;
  30. fps = new FlashFPS(0x006600, 0x000000, 0xffffff, 0, "kb");
  31. addChild(fps);
  32. thelight = new PointLight3D();
  33. scene = new Scene3D();
  34. thing = new Sphere(new PhongMaterial(thelight, 0x00FF00, 0x000000, 4), 500, 10, 14);
  35. scene.addChild(thing);
  36. startRendering();
  37. }
  38. override protected function onRenderTick(event:Event=null):void
  39. {
  40. fps.update("rendered: " + stats.shadedTriangles + " polys");
  41. thing.rotationY++;
  42. super.onRenderTick(event);
  43. }
  44. }
  45. }


this demo is so basic i decided not to post a swf...
but this can be run using flex builder 3 or flash cs3 and the papervision3D - 2.0 great white sources.

papervision3D - face level interaction

demo, code, actionscript, flex, papervision3D, mxml


the new pv3d 2.0 release features an entirely new way of dispatching and handling events. earlier versions of the engine utilized two different flavors of materials, regular and interactive. with this new release, you just have materials with a boolean interactive property.

with this simple demo, im trying to learn more about the new interactive scene events. first, you create a 3D scene, and set it's interactive flag to true:

    actionscript3 code
  1. view = new Viewport3D(width, height, scaleToStage, interactive);

then create a material and set it's interactive property to true:
    actionscript3 code
  1. skin = new CompositeMaterial();
  2. skin.interactive = true;

this can also be done through the object as opposed to the material
    actionscript3 code
  1. terrain = new Plane(...);
  2. terrain.material.interactive = true;

after that you attach listeners to your object. in this case, we're going to use the interactiveScene3DEvent.
    actionscript3 code
  1. terrian.addEventListener(InteractiveScene3DEvent.OBJECT_CLICK, extrude);


here's a list of the available interactive scene3d events
    actionscript3 events
  1. OBJECT_CLICK
  2. OBJECT_OVER
  3. OBJECT_OUT
  4. OBJECT_MOVE
  5. OBJECT_PRESS
  6. OBJECT_RELEASE
  7. OBJECT_RELEASE_OUTSIDE
  8. OBJECT_ADDED

from these events its possible to receive a multitude of information. the 4 main ones are the instance properties available to you, which are: displyObject3D, face3D, renderHitData, and sprite. in this demo i use face3D to return the current triangle3D that the user is interacting with.

when the user moves the mouse over the plane, a highlight function is fired. i look at the current face3D and the last face3D and change their materials. this gives the effect that the triangle you are hovering over is illuminated.

but the code gets a bit hacky in the extrude function. this gets fired when the user actually clicks the plane. i receive an event from the interactive scene manager and once again get the current face3D instance. beyond that, i look that the v0 property and increment (or decrement, depending on the user's on click settings) the current face's z amount. notice that the current face is not the only one affected. it's surrounding triangles also rise up and form pyramids on their own. this is a sign is a well programmed engine!

as usual, sources are available...
view the interactive terrain generator
view its source code here

papervision3D 2.0 - dynamic lighting demo

demo, code, actionscript, flex, papervision3D, mxml


working with the new pv3d 2.0 release, there are a lot of new features to learn. one of the most powerful being the new pointlight3D class. using this will allow you to create all kinds of cool shading effects. at first i was having some trouble deciding where the light is positioned by default. i tried setting the light’s visibility flag to true, but it still wasn’t rendering. after a bit of digging i discovered that the position of the light by default it set to (x:0, y:0, z:-1000), no wonder it wasn’t rendering, it was in the same postion as the camera!

so i decided to make a little flex demo for the new pointlight3D class. the flex form allows you to use sliders to move the x, y, and z position of the light, as well a an orbiting function. you can set the orbit to horizontal or vertical spin, as well as setting the radius and speed the light will orbit.

just a little note on the light’s visibility:
by default, your light object will not be visible (though the light casted from the object will be). to make your light visible you need to do two things:

first, when creating your light you need to set the showLight flag to true. second, you add your light to your scene3D (normally you don’t add the light to the scene, you just create it and use it later)

    actionscript3 code
  1. thelight = new PointLight3D(true);
  2. scene.addChild(thelight);

check out the demo here
then view the source code

papervision3D 2.0 – great white

demo, code, actionscript, flex, papervision3D, downloadz, preview, mxml


well the time is finally upon us, for all of you who aren’t avid mailing list readers, papervsion3D 2.0 alpha ((code name: great white)) has been released for testing. and the team bringing real-time 3D in flash has gone all out this release! this versions new features boast shaded materials, custom shaders, the new ascollada (now with animation support), frustrum culling, multiple viewports, rendering to scene, and more.. not to mention the average 26% gain in overall fps!

this weekend my wife nina was out of town, which means that i had some time to sit down and check out some of pv3D 2.0’s new features. i made a simple demo of creating a 3D scene in flex using MXML. The demo basically lets you switch between a few different 3D models, ((the first two are by mr.doob and the rest are by me)) and the material drawn on it. this demo features the new flat shaded, cell shaded, gouraud shaded, and phong shaded materials at your disposal in the new version. as usual models exported from 3D studio max to actionscript 3 with the help of the awesome as3 geom class exporter.

click here to check out the demo
and click here to view the source

get bitmapData of any flex component

code, actionscript, flex, papervision3D, css, mxml


i guess this is more of a test then a real demo. in flex its extremely simple to access the bitmap data from any component on the screen as it is styled at that time. this includes things like text with in a text box.
In this example I create a flex panel
<mx:Panel id="myPanel" />

then create a bitmapdata object
var formTexture = new BitmapData;

then I draw the panel right into it
formTexture.draw(myPanel);

then I use that texture on a 3D plane with the help of papervsion3D. and a little glow filter just because...

heres the full source:

    mxml and actionscript 3 code
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application
  3. xmlns:mx="http://www.adobe.com/2006/mxml"
  4. xmlns:xx="com.fontvirus.*"
  5. layout="absolute"
  6. backgroundGradientAlphas="[1.0, 1.0]"
  7. backgroundGradientColors="[#000000, #555555]"
  8. creationComplete="init3D()"
  9. enterFrame="loop3D(event)">
  10. <mx:Script>
  11. <![CDATA[
  12. import mx.controls.Alert;
  13. import org.papervision3d.cameras.Camera3D;
  14. import org.papervision3d.scenes.Scene3D;
  15. import org.papervision3d.objects.Plane;
  16. import org.papervision3d.objects.DisplayObject3D;
  17. import org.papervision3d.materials.BitmapMaterial;
  18. import com.fontvirus.FlexFPS;
  19. private var theFPS:FlexFPS;
  20. private var basePoint:Point;
  21. private var rect:Rectangle;
  22. private var formTexture:BitmapData;
  23. private var scene3D:Scene3D;
  24. private var camera:Camera3D;
  25. private var rootNode:DisplayObject3D;
  26. private var plane:DisplayObject3D;
  27. private function init3D():void {
  28. theFPS = new FlexFPS(0x006600, 0x000000, 0xFFFFFF);
  29. this.addChild(theFPS);
  30. var formwidth:Number = myPanel.width;
  31. var formheight:Number = myPanel.height;
  32. formTexture = new BitmapData (formwidth, formheight);
  33. scene3D = new Scene3D(paperCanvas.canvas);
  34. camera = new Camera3D();
  35. camera.zoom = 10;
  36. camera.focus = 200;
  37. rootNode = scene3D.addChild(new DisplayObject3D("rootNode"));
  38. rootNode.container = paperCanvas.canvas;
  39. var material1:BitmapMaterial = new BitmapMaterial(formTexture);
  40. material1.oneSide = false;
  41. plane = rootNode.addChild(new Plane(material1,formwidth,formheight,4,4), "plane");
  42. }
  43. private function loop3D(event:Event):void {
  44. theFPS.update("rendered: " + scene3D.stats.rendered.toString());
  45. if(camera != null) {
  46. camera.x += ((mouseX * 5) - camera.x) * 0.10;
  47. camera.y += ((mouseY * 5) - camera.y) * 0.10;
  48. formTexture.draw(myPanel);
  49. rootNode = scene3D.getChildByName("rootNode");
  50. rootNode.container.filters = [new GlowFilter(0x00FF00, 1, 90, 90, 1, 1, false, false)];
  51. scene3D.renderCamera(camera);
  52. }
  53. }
  54. private function reset():void {
  55. txtname.text = "";
  56. txtpass.text = "";
  57. }
  58. private function hit():void {
  59. Alert.show("login success!", "fontvir.us", 1, this);
  60. }
  61. ]]>
  62. </mx:Script>
  63. <mx:Panel id="myPanel" title="flexComponet3D" shadowDistance="6" shadowDirection="left" backgroundColor="#000000" color="#fFFFFF" cornerRadius="0" headerHeight="22" headerColors="[#000000, #666666]" width="209" backgroundAlpha="1.0" height="162" borderStyle="solid" x="10" y="62">
  64. <mx:Form width="204" height="135" backgroundColor="#000000">
  65. <mx:FormItem label=" "/>
  66. <mx:FormItem label="name">
  67. <mx:TextInput width="83" backgroundColor="#666666" themeColor="#00FF00" color="#FFFFFF" id="txtname"/>
  68. </mx:FormItem>
  69. <mx:FormItem label="password">
  70. <mx:TextInput width="82" backgroundColor="#666666" themeColor="#00FF00" color="#FFFFFF" id="txtpass"/>
  71. </mx:FormItem>
  72. <mx:HBox width="100%">
  73. <mx:Button label="enter" textRollOverColor="#cccccc" textSelectedColor="#FFFFFF" color="#FFFFFF" fillColors="[#333333, #999999]" borderColor="#000000" themeColor="#00FF00" click="hit()"/>
  74. <mx:Button label="reset" textRollOverColor="#cccccc" textSelectedColor="#FFFFFF" color="#FFFFFF" fillColors="[#333333, #999999]" borderColor="#000000" themeColor="#00FF00" click="reset()"/>
  75. </mx:HBox>
  76. </mx:Form>
  77. </mx:Panel>
  78. <xx:Canvas3D id="paperCanvas" backgroundAlpha="0" width="100%" height="100%" x="235" y="0"/>
  79. <mx:Style>
  80. Alert {
  81. corner-radius: 14;
  82. header-height: 27;
  83. header-colors: #999999, #000000;
  84. background-color: #000000;
  85. color: #ffffff;
  86. border-thickness: 4;
  87. border-color: #000000;
  88. panel-border-style: roundCorners;
  89. shadow-distance: 9;
  90. shadow-direction: right;
  91. }
  92. Button {
  93. width: 85;
  94. height: 24;
  95. border-thickness: 1;
  96. corner-radius: 4;
  97. fill-colors: #666666, #999999;
  98. border-color: #666666;
  99. theme-color: #000000;
  100. text-roll-over-color: #ffffff;
  101. text-selected-color: #cccccc;
  102. color: #cccccc;
  103. }
  104. </mx:Style>
  105. </mx:Application>

view demo here

actionscript 3 runtime variables

code, actionscript, flash, flex, php

the key to creating dynamic systems on the web is the ability to send and receive data from one component to the next. flash and flex are no different. there are a lot of cases where you need to send these variables while the application is running, but there are an equal amount of times where the application needs data at run time. passing variables to flash historically has been rather easy, you just query-string data right into the src tag of your flash movie:

    Actionscript 2 code
  1. src="test.swf?passed=hello"

by doing this flash would create a new variable (in this case named passed) when the flash movie is loaded. but with the advent of OOP coding in AS3, this technique has become depreciated.

in actionscript 3 you need to use the flashvars parameter to send data to your flash movie. the technique is the same for both flash and flex, but once the variable is passed flash and flex has a different syntax to access these vars. here is a simple php script that displays a text box, for data input then creates a swf wrapper that embeds your variable into the swf
( look for <?php echo($getit); ?> )

    php code
  1. <html><head><title>flex runtime vars</title>
  2. <?php
  3. $getit = $_REQUEST["what"];
  4. if(!$getit){
  5. ?>
  6. </head><body bgcolor="#000000">
  7. <form method="GET" action="index.php">
  8. <input type="text" id="what" name="what" style="COLOR: #cccccc;BACKGROUND-COLOR:#000000" /><br />
  9. <input type="submit" value="submit" style='COLOR: #cccccc; BACKGROUND-COLOR: #282828' />
  10. </form>
  11. <?php
  12. } else {
  13. ?>
  14. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  15. <link rel="stylesheet" type="text/css" href="deeplinking/deeplinking.css" />
  16. <script src="AC_OETags.js" language="javascript"></script>
  17. <script src="deeplinking/deeplinking.js" language="javascript"></script>
  18. <style>
  19. body { margin: 0px; overflow:hidden }
  20. </style>
  21. <script language="JavaScript" type="text/javascript">
  22. var requiredMajorVersion = 9;
  23. var requiredMinorVersion = 0;
  24. var requiredRevision = 28;
  25. </script>
  26. <body scroll="no" bgcolor="#000000">
  27. <script language="JavaScript" type="text/javascript">
  28. <!--
  29. var hasProductInstall = DetectFlashVer(6, 0, 65);
  30. var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
  31. if ( hasProductInstall && !hasRequestedVersion ) {
  32. var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
  33. var MMredirectURL = window.location;
  34. document.title = document.title.slice(0, 47) + " - Flash Player Installation";
  35. var MMdoctitle = document.title;
  36. AC_FL_RunContent(
  37. "src", "playerProductInstall",
  38. "FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
  39. "width", "100%",
  40. "height", "100%",
  41. "align", "middle",
  42. "id", "test",
  43. "quality", "high",
  44. "bgcolor", "#869ca7",
  45. "name", "test",
  46. "allowScriptAccess","sameDomain",
  47. "type", "application/x-shockwave-flash",
  48. "pluginspage", "http://www.adobe.com/go/getflashplayer"
  49. );
  50. } else if (hasRequestedVersion) {
  51. AC_FL_RunContent(
  52. "src", "test",
  53. "width", "100%",
  54. "height", "100%",
  55. "align", "middle",
  56. "id", "test",
  57. "quality", "high",
  58. "bgcolor", "#869ca7",
  59. "name", "test",
  60. "allowScriptAccess","sameDomain",
  61. "type", "application/x-shockwave-flash",
  62. "flashvars",'passed=<?php echo($getit); ?>',
  63. "pluginspage", "http://www.adobe.com/go/getflashplayer"
  64. );
  65. } else {
  66. var alternateContent = 'Alternate HTML content should be placed here. '
  67. + 'This content requires the Adobe Flash Player. '
  68. + '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
  69. document.write(alternateContent);
  70. }
  71. // -->
  72. </script>
  73. <noscript>
  74. <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  75. id="test" width="100%" height="100%"
  76. codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
  77. <param name="movie" value="test.swf" />
  78. <param name="quality" value="high" />
  79. <param name="bgcolor" value="#869ca7" />
  80. <param name="flashvars" value="passed=<?php echo($getit); ?>" />
  81. <param name="allowScriptAccess" value="sameDomain" />
  82. <embed src="test.swf" quality="high" bgcolor="#869ca7"
  83. width="100%" height="100%" name="test" align="middle"
  84. flashvars="passed=<?php echo($getit); ?>"
  85. play="true"
  86. loop="false"
  87. quality="high"
  88. allowScriptAccess="sameDomain"
  89. type="application/x-shockwave-flash"
  90. pluginspage="http://www.adobe.com/go/getflashplayer">
  91. </embed>
  92. </object>
  93. </noscript>
  94. <?php
  95. }
  96. ?>
  97. </body></html>

to access the "passed" var is flex use:
Application.application.parameters.passed;
    mxml and actionscript 3 code
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application
  3. xmlns:mx="http://www.adobe.com/2006/mxml"
  4. layout="absolute"
  5. backgroundGradientAlphas="[1.0, 1.0]"
  6. backgroundGradientColors="[#000000, #252525]"
  7. creationComplete="init()">
  8. <mx:Script>
  9. <![CDATA[
  10. public var passedvar:String;
  11. private function init():void {
  12. //passed is the name of the flash var
  13. passedvar = Application.application.parameters.passed;
  14. thething.htmlText = passedvar.toString();
  15. }
  16. ]]>
  17. </mx:Script>
  18. <mx:Label id="thething" text="Label" color="#FFFFFF" fontSize="23" horizontalCenter="0" verticalCenter="0" />
  19. </mx:Application>

to access the "passed" var is flash use:
LoaderInfo(this.root.loaderInfo).parameters;
    flash actionscript 3 code
  1. var tf:TextField = new TextField();
  2. tf.textColor = 0xFFFFFF;
  3. addChild(tf);
  4. try {
  5. var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
  6. //passed is the name of the flash var
  7. tf.appendText("passed var: " + paramObj['passed'].toString());
  8. } catch (error:Error) {
  9. tf.appendText("error: " + error.toString());
  10. }
view the flex demo here
view the flash demo here

tieTheKnot

code, actionscript, flash, flex, papervision3D, demo, mxml


so i had the chance this weekend to create a few 3D models and export their geometry into papervision3D primitives. so i decided to create a demo, using both my as3 torusKnot primitives and the new flex accordion component. about the time i finished my demo i decided to re-sync my pv3d folder with the svn. at that exact same moment their was a slip-up. somehow one of the new dev materials got leaked into the public svn. the new material features dynamic lighting! so i decided to hack it into my new demo. so enjoy my custom primitive shadedColorMaterial demo created in flex3.
updated with fullscreen support!

view the demo or the source (right click enabled)
stay in the loop, join the papervison3D mailing list.

as3 geometry class exporter

flash, downloadz, linx, actionscript, code, papervision3D, tutorial

a new component for 3D studio max has arrived that allows you to export the geometry of you model directly into a format that actionscript 3 can understand. the plugin has options for exporting to papervision3d, away3d, and sandy. it was developed my dreammania.net and can be downloaded here. and exporting a model couldnt be easier.

step 1. create you model, and select it
(you can tell its selected because of the white bounding box)

step 2. open the utilities panel and select MaxScript

step 3. in the MaxScript window, select Run Script

step 4. select the as3GeomClassExporter.ms file,
then select it from the drop down

step 5. a new as3GeomClassExporter panel will appear. select you 3D engine, give your object a class name, and a package location (if necessary) then press the export class button to save it.


now using this object in papervision3D is a snap! just...

    actionscript 3
  1. import com.fontvirus.KnotAgain;
  2. var theKnot:KnotAgain = new KnotAgain( skin );

papervision3D video cube

code, actionscript, flash, flex, papervision3D, demo


my latest papervision3d project was a revamp of the video cube. this time around the rotation of the cube is static, not mouse driven, also i added some new filtering, and a diffrent method of using a video texture that dousnt throw an error message. the flv is from the best cartoon ever lupin the 3rd. this episode is called "buns, guns, and fun in the sun"

check it out here.

    actionscipt 3 code
  1. package
  2. {
  3. import flash.display.*;
  4. import flash.events.*;
  5. import flash.media.*;
  6. import flash.net.*;
  7. import flash.text.*;
  8. import flash.filters.*;
  9. //filmed in papervision3d
  10. import org.papervision3d.scenes.*;
  11. import org.papervision3d.objects.*;
  12. import org.papervision3d.cameras.*;
  13. import org.papervision3d.materials.*;
  14. [SWF(backgroundColor=0x333333)]
  15. public class main extends Sprite
  16. {
  17. // _______________________________________________________________________
  18. // vars3D
  19. private var container : Sprite;
  20. private var scene : MovieScene3D;
  21. private var camera : Camera3D;
  22. private var planeObj : DisplayObject3D;
  23. private var planeSize : int = 500;
  24. private var segment : int = 2;
  25. private var material : BitmapMaterial;
  26. private var bmpData : BitmapData;
  27. private var connection: NetConnection;
  28. private var stream : NetStream;
  29. private var video : Video;
  30. private var label : TextField;
  31. private var valx : Number = 0;
  32. private var valy : Number = 0;
  33. private var count : uint = 0;
  34. static public const
  35. TEXTURE_W:int = 320,
  36. TEXTURE_H:int = 240;
  37. // _______________________________________________________________________
  38. // constructor
  39. public function main():void
  40. {
  41. stage.frameRate = 60;
  42. stage.quality = "MEDIUM";
  43. stage.scaleMode = "noScale";
  44. stage.align = StageAlign.TOP_LEFT;
  45. this.addEventListener(Event.ENTER_FRAME, loop3D);
  46. this.stage.addEventListener(Event.RESIZE, onStageResize);
  47. label=new TextField();
  48. label.autoSize=TextFieldAutoSize.LEFT;
  49. label.x = 10;
  50. label.textColor=0xFFFFFF;
  51. label.selectable=false;
  52. addChild(label);
  53. init3D();
  54. connection=new NetConnection();
  55. connection.addEventListener(NetStatusEvent.NET_STATUS,netStatusHandler);
  56. connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);
  57. connection.connect(null);
  58. }
  59. private function netStatusHandler(evt:NetStatusEvent):void {
  60. switch (evt.info.code) {
  61. case "NetConnection.Connect.Success":
  62. stream = new NetStream(connection);
  63. stream.addEventListener(NetStatusEvent.NET_STATUS,netStatusHandler);
  64. stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR,asyncErrorHandler);
  65. video = new Video();
  66. video.attachNetStream(stream);
  67. stream.play("lupinIII-s2e002-buns.guns.and.fun.in.the.sun.flv");
  68. label.htmlText ="the.fontvir.us presents... \n lupin the 3d\n buns guns and fun in the sun";
  69. break;
  70. case "NetStream.Play.StreamNotFound":
  71. label.text="flv not found...";
  72. break;
  73. case "NetStream.Play.Stop":
  74. //loop video
  75. stream.seek(0);
  76. break;
  77. }
  78. }
  79. // _______________________________________________________________________
  80. // event handlers
  81. private function asyncErrorHandler(evt:AsyncErrorEvent):void {
  82. }
  83. private function securityErrorHandler(evt:SecurityErrorEvent):void {
  84. label.text="security error...";
  85. }
  86. // _______________________________________________________________________
  87. // init3D
  88. private function init3D():void
  89. {
  90. this.container = new Sprite();
  91. addChild(this.container);
  92. this.container.x = this.stage.stageWidth / 2;
  93. this.container.y = this.stage.stageHeight / 2;
  94. scene = new MovieScene3D( container );
  95. camera = new Camera3D();
  96. camera.z = -planeSize;
  97. camera.focus = 1000;
  98. camera.zoom = 1;
  99. bmpData = new BitmapData(TEXTURE_W,TEXTURE_H,false,0xff0000);
  100. material = new BitmapMaterial(bmpData);
  101. material.oneSide = true;
  102. planeObj = scene.addChild( new Cube( material, planeSize, planeSize, planeSize, segment, segment, segment) );
  103. }
  104. // _______________________________________________________________________
  105. // loop3d
  106. private function loop3D( event:Event ):void
  107. {
  108. valx -= 0.2;
  109. valy -= 0.5;
  110. planeObj.rotationY = valx;
  111. planeObj.rotationX = 35;
  112. video.attachNetStream(null);
  113. bmpData.draw(video);
  114. video.attachNetStream(stream);
  115. var filters:Array = new Array;
  116. filters.push(new GlowFilter(0xFFFFFF, 1, 10, 10, 10, 1));
  117. filters.push(new DropShadowFilter(70, 55, 0x000000, 0.5, 9, 9, 1, BitmapFilterQuality.HIGH));
  118. /*
  119. var blur:Number = 10*Math.sin( (++count/25) );
  120. if(blur > 0){
  121. filters.push(new BlurFilter(blur,blur,BitmapFilterQuality.HIGH));
  122. }
  123. */
  124. planeObj.container.filters = filters;
  125. this.scene.renderCamera( camera );
  126. }
  127. // _______________________________________________________________________
  128. // onStageResize
  129. private function onStageResize(event:Event):void
  130. {
  131. this.container.x = this.stage.stageWidth / 2;
  132. this.container.y = this.stage.stageHeight / 2;
  133. }
  134. }
ps... happy birthday to me!!!

actionscript3 randomizer

code, actionscript, flash, random, flex

here a nice little one liner. this function returns a random number between a user supplied range.

    actionscript 3 code
  1. function randomizer (low:Number, high:Number):Number {
  2. return Math.floor(low + (Math.random() * (high-low)));
  3. }
example useage, will return a number between 5 - 50.
  1. var x:Number = randomizer(5, 50);

3D sound visualizer

code, flash, tech, downloadz, actionscript, flex, papervision3D, demo, rawk, mxml


a fellow papervsion3d enthusiast zeh (creator of the popular mctween) has created a new way of animating full 3d objects in the flash/flex environment with 100% code! Introducing the caurina tweener, witch is now hosted on googlecode, this re-envisioning of tweening is no longer a collection of h4x and prototypes extending existing ones. zeh has written full static classes following the idea of simple, one line commands. tweener is still in development, but is completely stable and functional.

check out the sound visualization demo i created using pv3d and tweener
http://the.fontvir.us/pv3d/spikey/
and its source code
http://the.fontvir.us/pv3d/spikey/spikey.as

UPDATE!

i have created a new version of the demo in flex using mxml. this demo also has the ability to dynamically change the colors of the filters applied to the spikey ball. i also compiled this demo with the current trunk version of papervision3D as well as the new 1.5 refractored branch to test the speed increase with the new version.

check out the 0.91 version here (source)
and the new 1.5 version here (source)

papervision3d component for cs3!

downloadz, tech, flash, actionscript, papervision3D


today john grden of rockonflash.com has release his new papervision3D component. this plugin for the flash cs3 ide allows you to...

- render and edit your 3d objects in Flash IDE at design time!
- it supports 3 material types
- you can creates movieScene3D and free or target cameras
- management of resizing / centering of a papervision3D scene
- dynamic masking to constrain the viewable area to set bounds
- full api and access to scene, camera, and collada objects to code around
- automatically loads materials via collada file
- new custom panel for modifying rotation, camera zoom, camera focus, camera Z

john has really outdone himself this time. this takes alot of the tedium of testing and retesting your 3D scenes to make sure the objects are positioned correctly.

- download the component here

watch the rmi training videos
- for developers
- for designers
- source files for training videos

papervision3D

flash, downloadz, tech, linx, code, actionscript, flex, papervision3D

so i finally got a copy of adobe cs3 and flex builder2. flex is amazing, combining mxml and actionscript 3 together into a seamless package. now that im on the as3 tip, i decided to dive into papervision3D. pv3d is a set of actionscript classes that are used to create 3D objects within the flash environment. Currently in beta, the source code is only available to osflash emailing list members. so if yew want it... signup here. i have also posted my first flex as3 pv3d project, the metroid speedrun 3D cube. and here's the source. Thanx to carlos for creating pv3d and thanx to luis for the video texture tutorial.

MMVII .( xero harrison ) . http://the.fontvir.us/b10g
RSS syndication